asn.c 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835
  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 = (word32)b & 0x7FU;
  1987. int minLen;
  1988. /* Calculate minimum length to be encoded with bytes. */
  1989. if (b == ASN_INDEF_LENGTH) {
  1990. /* Indefinite length encoding - no length bytes. */
  1991. minLen = 0;
  1992. }
  1993. else if (bytes == 1) {
  1994. minLen = 0x80;
  1995. }
  1996. /* Only support up to the number of bytes that fit into return var. */
  1997. else if (bytes > sizeof(length)) {
  1998. WOLFSSL_MSG("GetLength - overlong data length spec");
  1999. return ASN_PARSE_E;
  2000. } else {
  2001. minLen = 1 << ((bytes - 1) * 8);
  2002. }
  2003. /* Check the number of bytes required are available. */
  2004. if ((idx + bytes) > maxIdx) {
  2005. WOLFSSL_MSG("GetLength - bad long length");
  2006. return BUFFER_E;
  2007. }
  2008. /* Big-endian encoding of number. */
  2009. while (bytes--) {
  2010. b = input[idx++];
  2011. length = (length << 8) | b;
  2012. }
  2013. /* Negative value indicates we overflowed the signed int. */
  2014. if (length < 0) {
  2015. return ASN_PARSE_E;
  2016. }
  2017. /* Don't allow lengths that are longer than strictly required. */
  2018. if (length < minLen) {
  2019. return ASN_PARSE_E;
  2020. }
  2021. }
  2022. else {
  2023. /* Length in first byte. */
  2024. length = b;
  2025. }
  2026. /* When requested, check the buffer has at least length bytes left. */
  2027. if (check && ((idx + (word32)length) > maxIdx)) {
  2028. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  2029. return BUFFER_E;
  2030. }
  2031. /* Return index after length encoding. */
  2032. *inOutIdx = idx;
  2033. /* Return length if valid. */
  2034. if (length > 0) {
  2035. *len = length;
  2036. }
  2037. /* Return length calculated or error code. */
  2038. return length;
  2039. }
  2040. /* Gets the tag of next BER/DER encoded item.
  2041. *
  2042. * Checks there is enough data in the buffer for the tag byte.
  2043. *
  2044. * @param [in] input BER encoded data.
  2045. * @param [in, out] inOutIdx On in, starting index of tag.
  2046. * On out, end of parsed tag.
  2047. * @param [out] tag Tag value found.
  2048. * @param [in] maxIdx Maximum index of input data.
  2049. *
  2050. * return 0 on success
  2051. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2052. * return BUFFER_E when not enough space in buffer for tag.
  2053. */
  2054. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2055. {
  2056. int ret = 0;
  2057. word32 idx = 0;
  2058. /* Check validity of parameters. */
  2059. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2060. ret = BAD_FUNC_ARG;
  2061. }
  2062. if (ret == 0) {
  2063. /* Get index and ensure space for tag. */
  2064. idx = *inOutIdx;
  2065. if (idx + ASN_TAG_SZ > maxIdx) {
  2066. WOLFSSL_MSG("Buffer too small for ASN tag");
  2067. ret = BUFFER_E;
  2068. }
  2069. }
  2070. if (ret == 0) {
  2071. /* Return the tag and the index after tag. */
  2072. *tag = input[idx];
  2073. *inOutIdx = idx + ASN_TAG_SZ;
  2074. }
  2075. /* Return error code. */
  2076. return ret;
  2077. }
  2078. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2079. *
  2080. * BER/DER has Type-Length-Value triplets.
  2081. * Check that the tag/type is the required value.
  2082. * When requested will check that the Length decoded, indicating the number
  2083. * of bytes in the Value, is available in the buffer after the Length bytes.
  2084. *
  2085. * Only supporting a length upto INT_MAX.
  2086. *
  2087. * @param [in] input Buffer holding DER/BER encoded data.
  2088. * @param [in] tag ASN.1 tag value expected in header.
  2089. * @param [in, out] inOutIdx On in, starting index of header.
  2090. * On out, end of parsed header.
  2091. * @param [out] len Number of bytes in the ASN.1 data.
  2092. * @param [in] maxIdx Length of data in buffer.
  2093. * @param [in] check Whether to check the buffer has at least the
  2094. * decoded length of bytes remaining.
  2095. * @return Number of bytes in the ASN.1 data on success.
  2096. * @return BUFFER_E when there is not enough data to parse.
  2097. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2098. */
  2099. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2100. int* len, word32 maxIdx, int check)
  2101. {
  2102. int ret = 0;
  2103. word32 idx = *inOutIdx;
  2104. byte tagFound;
  2105. int length = 0;
  2106. /* Get tag/type. */
  2107. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2108. ret = ASN_PARSE_E;
  2109. }
  2110. /* Ensure tag is the expected value. */
  2111. if ((ret == 0) && (tagFound != tag)) {
  2112. ret = ASN_PARSE_E;
  2113. }
  2114. /* Get the encoded length. */
  2115. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2116. ret = ASN_PARSE_E;
  2117. }
  2118. if (ret == 0) {
  2119. /* Return the length of data and index after header. */
  2120. *len = length;
  2121. *inOutIdx = idx;
  2122. ret = length;
  2123. }
  2124. /* Return number of data bytes or error code. */
  2125. return ret;
  2126. }
  2127. /* Decode the DER/BER header (Type-Length) and check the length.
  2128. *
  2129. * BER/DER has Type-Length-Value triplets.
  2130. * Check that the tag/type is the required value.
  2131. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2132. * is available in the buffer after the Length bytes.
  2133. *
  2134. * @param [in] input Buffer holding DER/BER encoded data.
  2135. * @param [in] tag ASN.1 tag value expected in header.
  2136. * @param [in, out] inOutIdx On in, starting index of header.
  2137. * On out, end of parsed header.
  2138. * @param [out] len Number of bytes in the ASN.1 data.
  2139. * @param [in] maxIdx Length of data in buffer.
  2140. * @return Number of bytes in the ASN.1 data on success.
  2141. * @return BUFFER_E when there is not enough data to parse.
  2142. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2143. */
  2144. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2145. word32 maxIdx)
  2146. {
  2147. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2148. }
  2149. #ifndef WOLFSSL_ASN_TEMPLATE
  2150. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2151. word32 maxIdx, int check)
  2152. {
  2153. word32 idx = *inOutIdx;
  2154. int length;
  2155. if ((idx + 1) > maxIdx)
  2156. return BUFFER_E;
  2157. *tag = input[idx++];
  2158. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2159. return ASN_PARSE_E;
  2160. *len = length;
  2161. *inOutIdx = idx;
  2162. return length;
  2163. }
  2164. #endif
  2165. /* Decode the header of a BER/DER encoded SEQUENCE.
  2166. *
  2167. * @param [in] input Buffer holding DER/BER encoded data.
  2168. * @param [in, out] inOutIdx On in, starting index of header.
  2169. * On out, end of parsed header.
  2170. * @param [out] len Number of bytes in the ASN.1 data.
  2171. * @param [in] maxIdx Length of data in buffer.
  2172. * @return Number of bytes in the ASN.1 data on success.
  2173. * @return BUFFER_E when there is not enough data to parse.
  2174. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2175. */
  2176. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2177. word32 maxIdx)
  2178. {
  2179. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2180. maxIdx);
  2181. }
  2182. /* Decode the header of a BER/DER encoded SEQUENCE.
  2183. *
  2184. * @param [in] input Buffer holding DER/BER encoded data.
  2185. * @param [in, out] inOutIdx On in, starting index of header.
  2186. * On out, end of parsed header.
  2187. * @param [out] len Number of bytes in the ASN.1 data.
  2188. * @param [in] maxIdx Length of data in buffer.
  2189. * @param [in] check Whether to check the buffer has at least the
  2190. * decoded length of bytes remaining.
  2191. * @return Number of bytes in the ASN.1 data on success.
  2192. * @return BUFFER_E when there is not enough data to parse.
  2193. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2194. */
  2195. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2196. word32 maxIdx, int check)
  2197. {
  2198. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2199. maxIdx, check);
  2200. }
  2201. /* Decode the header of a BER/DER encoded SET.
  2202. *
  2203. * @param [in] input Buffer holding DER/BER encoded data.
  2204. * @param [in, out] inOutIdx On in, starting index of header.
  2205. * On out, end of parsed header.
  2206. * @param [out] len Number of bytes in the ASN.1 data.
  2207. * @param [in] maxIdx Length of data in buffer.
  2208. * @return Number of bytes in the ASN.1 data on success.
  2209. * @return BUFFER_E when there is not enough data to parse.
  2210. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2211. */
  2212. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2213. word32 maxIdx)
  2214. {
  2215. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2216. maxIdx);
  2217. }
  2218. /* Decode the header of a BER/DER encoded SET.
  2219. *
  2220. * @param [in] input Buffer holding DER/BER encoded data.
  2221. * @param [in, out] inOutIdx On in, starting index of header.
  2222. * On out, end of parsed header.
  2223. * @param [out] len Number of bytes in the ASN.1 data.
  2224. * @param [in] maxIdx Length of data in buffer.
  2225. * @param [in] check Whether to check the buffer has at least the
  2226. * decoded length of bytes remaining.
  2227. * @return Number of bytes in the ASN.1 data on success.
  2228. * @return BUFFER_E when there is not enough data to parse.
  2229. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2230. */
  2231. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2232. word32 maxIdx, int check)
  2233. {
  2234. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2235. maxIdx, check);
  2236. }
  2237. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2238. /* Decode the BER/DER encoded NULL.
  2239. *
  2240. * No data in a NULL ASN.1 item.
  2241. * Ensure that the all fields are as expected and move index past the element.
  2242. *
  2243. * @param [in] input Buffer holding DER/BER encoded data.
  2244. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2245. * On out, end of parsed NULL item.
  2246. * @param [in] maxIdx Length of data in buffer.
  2247. * @return 0 on success.
  2248. * @return BUFFER_E when there is not enough data to parse.
  2249. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2250. * @return ASN_EXPECT_0_E when the length is not zero.
  2251. */
  2252. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2253. {
  2254. int ret = 0;
  2255. word32 idx = *inOutIdx;
  2256. /* Check buffer has enough data for a NULL item. */
  2257. if ((idx + 2) > maxIdx) {
  2258. ret = BUFFER_E;
  2259. }
  2260. /* Check the tag is NULL. */
  2261. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2262. ret = ASN_TAG_NULL_E;
  2263. }
  2264. /* Check the length is zero. */
  2265. if ((ret == 0) && (input[idx++] != 0)) {
  2266. ret = ASN_EXPECT_0_E;
  2267. }
  2268. if (ret == 0) {
  2269. /* Return the index after NULL tag. */
  2270. *inOutIdx = idx;
  2271. }
  2272. /* Return error code. */
  2273. return ret;
  2274. }
  2275. #endif
  2276. #ifndef WOLFSSL_ASN_TEMPLATE
  2277. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2278. *
  2279. * output Buffer to write into.
  2280. * returns the number of bytes added to the buffer.
  2281. */
  2282. static int SetASNNull(byte* output)
  2283. {
  2284. output[0] = ASN_TAG_NULL;
  2285. output[1] = 0;
  2286. return 2;
  2287. }
  2288. #endif
  2289. #ifndef NO_CERTS
  2290. #ifndef WOLFSSL_ASN_TEMPLATE
  2291. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2292. *
  2293. * input Buffer holding DER/BER encoded data.
  2294. * inOutIdx Current index into buffer to parse.
  2295. * maxIdx Length of data in buffer.
  2296. * returns BUFFER_E when there is not enough data to parse.
  2297. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2298. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2299. */
  2300. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2301. {
  2302. word32 idx = *inOutIdx;
  2303. byte b;
  2304. if ((idx + 3) > maxIdx)
  2305. return BUFFER_E;
  2306. b = input[idx++];
  2307. if (b != ASN_BOOLEAN)
  2308. return ASN_PARSE_E;
  2309. if (input[idx++] != 1)
  2310. return ASN_PARSE_E;
  2311. b = input[idx++] != 0;
  2312. *inOutIdx = idx;
  2313. return b;
  2314. }
  2315. #endif
  2316. #endif /* !NO_CERTS*/
  2317. /* Decode the header of a BER/DER encoded OCTET STRING.
  2318. *
  2319. * @param [in] input Buffer holding DER/BER encoded data.
  2320. * @param [in, out] inOutIdx On in, starting index of header.
  2321. * On out, end of parsed header.
  2322. * @param [out] len Number of bytes in the ASN.1 data.
  2323. * @param [in] maxIdx Length of data in buffer.
  2324. * @return Number of bytes in the ASN.1 data on success.
  2325. * @return BUFFER_E when there is not enough data to parse.
  2326. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2327. */
  2328. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2329. {
  2330. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2331. }
  2332. #ifndef WOLFSSL_ASN_TEMPLATE
  2333. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2334. *
  2335. * Removes the leading zero byte when found.
  2336. *
  2337. * input Buffer holding DER/BER encoded data.
  2338. * inOutIdx Current index into buffer to parse.
  2339. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2340. * maxIdx Length of data in buffer.
  2341. * returns BUFFER_E when there is not enough data to parse.
  2342. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2343. * or invalid use of or missing leading zero.
  2344. * Otherwise, 0 to indicate success.
  2345. */
  2346. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2347. word32 maxIdx)
  2348. {
  2349. int ret;
  2350. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2351. if (ret < 0)
  2352. return ret;
  2353. if (*len > 0) {
  2354. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2355. /* check for invalid padding on negative integer.
  2356. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2357. */
  2358. if (*len > 1) {
  2359. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2360. return ASN_PARSE_E;
  2361. }
  2362. #endif
  2363. /* remove leading zero, unless there is only one 0x00 byte */
  2364. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2365. (*inOutIdx)++;
  2366. (*len)--;
  2367. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2368. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2369. return ASN_PARSE_E;
  2370. #endif
  2371. }
  2372. }
  2373. return 0;
  2374. }
  2375. #ifndef NO_CERTS
  2376. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2377. * 7 bits.
  2378. *
  2379. * input Buffer holding DER/BER encoded data.
  2380. * inOutIdx Current index into buffer to parse.
  2381. * maxIdx Length of data in buffer.
  2382. * returns BUFFER_E when there is not enough data to parse.
  2383. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2384. * Otherwise, the 7-bit value.
  2385. */
  2386. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2387. {
  2388. word32 idx = *inOutIdx;
  2389. byte b;
  2390. if ((idx + 3) > maxIdx)
  2391. return BUFFER_E;
  2392. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2393. return ASN_PARSE_E;
  2394. if (b != ASN_INTEGER)
  2395. return ASN_PARSE_E;
  2396. if (input[idx++] != 1)
  2397. return ASN_PARSE_E;
  2398. b = input[idx++];
  2399. *inOutIdx = idx;
  2400. return b;
  2401. }
  2402. #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, (byte)(leadingBit ? 0x80U : 0x00U), output);
  2704. if (maxSz >= 0 && (idx + length) > maxSz)
  2705. return BUFFER_E;
  2706. if (output) {
  2707. int err = mp_to_unsigned_bin(n, output + idx);
  2708. if (err != MP_OKAY)
  2709. return MP_TO_E;
  2710. }
  2711. idx += length;
  2712. return idx;
  2713. }
  2714. #endif
  2715. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2716. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2717. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2718. * an RSA key.
  2719. * The number is assumed to be positive.
  2720. *
  2721. * n Multi-precision integer to encode.
  2722. * output Buffer to write into.
  2723. * returns BUFFER_E when the data is too long for the buffer.
  2724. * MP_TO_E when encoding the integer fails.
  2725. * Otherwise, the number of bytes added to the buffer.
  2726. */
  2727. static int SetASNIntRSA(void* n, byte* output)
  2728. {
  2729. int idx = 0;
  2730. int leadingBit;
  2731. int length;
  2732. leadingBit = wc_Rsa_leading_bit(n);
  2733. length = wc_Rsa_unsigned_bin_size(n);
  2734. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2735. if ((idx + length) > MAX_RSA_INT_SZ)
  2736. return BUFFER_E;
  2737. if (output) {
  2738. int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2739. if (err != MP_OKAY)
  2740. return MP_TO_E;
  2741. }
  2742. idx += length;
  2743. return idx;
  2744. }
  2745. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2746. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2747. #ifdef WOLFSSL_ASN_TEMPLATE
  2748. /* ASN.1 template for an INTEGER. */
  2749. static const ASNItem intASN[] = {
  2750. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2751. };
  2752. enum {
  2753. INTASN_IDX_INT = 0
  2754. };
  2755. /* Number of items in ASN.1 template for an INTEGER. */
  2756. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2757. #endif /* WOLFSSL_ASN_TEMPLATE */
  2758. /* Windows header clash for WinCE using GetVersion */
  2759. /* Decode Version - one byte INTEGER.
  2760. *
  2761. * @param [in] input Buffer of BER data.
  2762. * @param [in, out] inOutIdx On in, start of encoded Version.
  2763. * On out, start of next encode ASN.1 item.
  2764. * @param [out] version Number encoded in INTEGER.
  2765. * @param [in] maxIdx Maximum index of data in buffer.
  2766. * @return 0 on success.
  2767. * @return ASN_PARSE_E when encoding is invalid.
  2768. * @return BUFFER_E when data in buffer is too small.
  2769. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2770. */
  2771. int GetMyVersion(const byte* input, word32* inOutIdx,
  2772. int* version, word32 maxIdx)
  2773. {
  2774. #ifndef WOLFSSL_ASN_TEMPLATE
  2775. word32 idx = *inOutIdx;
  2776. byte tag;
  2777. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2778. return ASN_PARSE_E;
  2779. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2780. return ASN_PARSE_E;
  2781. if (tag != ASN_INTEGER)
  2782. return ASN_PARSE_E;
  2783. if (input[idx++] != 0x01)
  2784. return ASN_VERSION_E;
  2785. *version = input[idx++];
  2786. *inOutIdx = idx;
  2787. return *version;
  2788. #else
  2789. ASNGetData dataASN[intASN_Length];
  2790. int ret;
  2791. byte num;
  2792. /* Clear dynamic data and set the version number variable. */
  2793. XMEMSET(dataASN, 0, sizeof(dataASN));
  2794. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2795. /* Decode the version (INTEGER). */
  2796. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2797. maxIdx);
  2798. if (ret == 0) {
  2799. /* Return version through variable and return value. */
  2800. *version = num;
  2801. ret = num;
  2802. }
  2803. return ret;
  2804. #endif /* WOLFSSL_ASN_TEMPLATE */
  2805. }
  2806. #ifndef NO_PWDBASED
  2807. /* Decode small integer, 32 bits or less.
  2808. *
  2809. * @param [in] input Buffer of BER data.
  2810. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2811. * On out, start of next encode ASN.1 item.
  2812. * @param [out] number Number encoded in INTEGER.
  2813. * @param [in] maxIdx Maximum index of data in buffer.
  2814. * @return 0 on success.
  2815. * @return ASN_PARSE_E when encoding is invalid.
  2816. * @return BUFFER_E when data in buffer is too small.
  2817. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2818. */
  2819. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2820. {
  2821. #ifndef WOLFSSL_ASN_TEMPLATE
  2822. word32 idx = *inOutIdx;
  2823. word32 len;
  2824. byte tag;
  2825. *number = 0;
  2826. /* check for type and length bytes */
  2827. if ((idx + 2) > maxIdx)
  2828. return BUFFER_E;
  2829. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2830. return ASN_PARSE_E;
  2831. if (tag != ASN_INTEGER)
  2832. return ASN_PARSE_E;
  2833. len = input[idx++];
  2834. if (len > 4)
  2835. return ASN_PARSE_E;
  2836. if (len + idx > maxIdx)
  2837. return ASN_PARSE_E;
  2838. while (len--) {
  2839. *number = *number << 8 | input[idx++];
  2840. }
  2841. *inOutIdx = idx;
  2842. return *number;
  2843. #else
  2844. ASNGetData dataASN[intASN_Length];
  2845. int ret;
  2846. word32 num;
  2847. /* Clear dynamic data and set the 32-bit number variable. */
  2848. XMEMSET(dataASN, 0, sizeof(dataASN));
  2849. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2850. /* Decode the short int (INTEGER). */
  2851. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2852. maxIdx);
  2853. if (ret == 0) {
  2854. /* Return number through variable and return value. */
  2855. *number = (int)num;
  2856. ret = (int)num;
  2857. }
  2858. return ret;
  2859. #endif
  2860. }
  2861. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
  2862. defined(HAVE_PKCS12)
  2863. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2864. * returns total amount written including ASN tag and length byte on success */
  2865. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2866. {
  2867. word32 idx = *inOutIdx;
  2868. int len = 0;
  2869. int i;
  2870. byte ar[MAX_LENGTH_SZ];
  2871. /* check for room for type and length bytes */
  2872. if ((idx + 2) > maxIdx)
  2873. return BUFFER_E;
  2874. input[idx++] = ASN_INTEGER;
  2875. idx++; /* place holder for length byte */
  2876. if (MAX_LENGTH_SZ + idx > maxIdx)
  2877. return ASN_PARSE_E;
  2878. /* find first non zero byte */
  2879. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2880. c32toa(number, ar);
  2881. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2882. if (ar[i] != 0) {
  2883. break;
  2884. }
  2885. }
  2886. /* handle case of 0 */
  2887. if (i == MAX_LENGTH_SZ) {
  2888. input[idx++] = 0; len++;
  2889. }
  2890. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2891. input[idx++] = ar[i]; len++;
  2892. }
  2893. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2894. * and set number of bytes for integer, then update the index value */
  2895. input[*inOutIdx + 1] = (byte)len;
  2896. *inOutIdx = idx;
  2897. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2898. }
  2899. #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
  2900. #endif /* !NO_PWDBASED */
  2901. #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 BAD_FUNC_ARG when the params is NULL.
  5637. * @return ASN_PARSE_E when the decoding fails.
  5638. * @return 0 on success.
  5639. */
  5640. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5641. enum wc_HashType* hash, int* mgf, int* saltLen)
  5642. {
  5643. #ifndef WOLFSSL_ASN_TEMPLATE
  5644. int ret = 0;
  5645. word32 idx = 0;
  5646. int len = 0;
  5647. word32 oid = 0;
  5648. byte tag;
  5649. int length;
  5650. if (params == NULL) {
  5651. ret = BAD_FUNC_ARG;
  5652. }
  5653. if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
  5654. ret = ASN_PARSE_E;
  5655. }
  5656. if (ret == 0) {
  5657. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5658. /* Hash algorithm to use on message. */
  5659. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5660. ret = ASN_PARSE_E;
  5661. }
  5662. if (ret == 0) {
  5663. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5664. ret = ASN_PARSE_E;
  5665. }
  5666. }
  5667. if (ret == 0) {
  5668. ret = RsaPssHashOidToType(oid, hash);
  5669. }
  5670. }
  5671. else {
  5672. /* Default hash algorithm. */
  5673. *hash = WC_HASH_TYPE_SHA;
  5674. }
  5675. }
  5676. if (ret == 0) {
  5677. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5678. /* MGF and hash algorithm to use with padding. */
  5679. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5680. ret = ASN_PARSE_E;
  5681. }
  5682. if (ret == 0) {
  5683. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5684. ret = ASN_PARSE_E;
  5685. }
  5686. }
  5687. if ((ret == 0) && (oid != MGF1_OID)) {
  5688. ret = ASN_PARSE_E;
  5689. }
  5690. if (ret == 0) {
  5691. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5692. if (ret == 0) {
  5693. ret = RsaPssHashOidToMgf1(oid, mgf);
  5694. }
  5695. }
  5696. }
  5697. else {
  5698. /* Default MGF/Hash algorithm. */
  5699. *mgf = WC_MGF1SHA1;
  5700. }
  5701. }
  5702. if (ret == 0) {
  5703. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5704. /* Salt length to use with padding. */
  5705. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5706. ret = ASN_PARSE_E;
  5707. }
  5708. if (ret == 0) {
  5709. ret = GetInteger16Bit(params, &idx, sz);
  5710. if (ret >= 0) {
  5711. *saltLen = ret;
  5712. ret = 0;
  5713. }
  5714. }
  5715. }
  5716. else {
  5717. /* Default salt length. */
  5718. *saltLen = 20;
  5719. }
  5720. }
  5721. if (ret == 0) {
  5722. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5723. /* Unused - trialerField. */
  5724. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5725. ret = ASN_PARSE_E;
  5726. }
  5727. if (ret == 0) {
  5728. ret = GetInteger16Bit(params, &idx, sz);
  5729. if (ret > 0) {
  5730. ret = 0;
  5731. }
  5732. }
  5733. }
  5734. }
  5735. if ((ret == 0) && (idx != sz)) {
  5736. ret = ASN_PARSE_E;
  5737. }
  5738. return ret;
  5739. #else
  5740. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5741. int ret = 0;
  5742. word16 sLen = 20;
  5743. if (params == NULL) {
  5744. ret = BAD_FUNC_ARG;
  5745. }
  5746. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5747. if (ret == 0) {
  5748. word32 inOutIdx = 0;
  5749. /* Default values. */
  5750. *hash = WC_HASH_TYPE_SHA;
  5751. *mgf = WC_MGF1SHA1;
  5752. /* Set OID type expected. */
  5753. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5754. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5755. /* Place the salt length into 16-bit var sLen. */
  5756. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5757. /* Decode the algorithm identifier. */
  5758. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5759. params, &inOutIdx, sz);
  5760. }
  5761. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5762. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5763. ret = RsaPssHashOidToType(oid, hash);
  5764. }
  5765. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5766. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5767. ret = RsaPssHashOidToMgf1(oid, mgf);
  5768. }
  5769. if (ret == 0) {
  5770. *saltLen = sLen;
  5771. }
  5772. FREE_ASNGETDATA(dataASN, NULL);
  5773. return ret;
  5774. #endif /* WOLFSSL_ASN_TEMPLATE */
  5775. }
  5776. #endif /* WC_RSA_PSS */
  5777. #ifndef HAVE_USER_RSA
  5778. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5779. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5780. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5781. /* Byte offset of numbers in RSA key. */
  5782. size_t rsaIntOffset[] = {
  5783. OFFSETOF(RsaKey, n),
  5784. OFFSETOF(RsaKey, e),
  5785. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5786. OFFSETOF(RsaKey, d),
  5787. OFFSETOF(RsaKey, p),
  5788. OFFSETOF(RsaKey, q),
  5789. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5790. OFFSETOF(RsaKey, dP),
  5791. OFFSETOF(RsaKey, dQ),
  5792. OFFSETOF(RsaKey, u)
  5793. #endif
  5794. #endif
  5795. };
  5796. /* Get a number from the RSA key based on an index.
  5797. *
  5798. * Order: { n, e, d, p, q, dP, dQ, u }
  5799. *
  5800. * Caller must ensure index is not invalid!
  5801. *
  5802. * @param [in] key RSA key object.
  5803. * @param [in] idx Index of number.
  5804. * @return A pointer to an mp_int when valid index.
  5805. * @return NULL when invalid index.
  5806. */
  5807. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5808. {
  5809. /* Cast key to byte array to and use offset to get to mp_int field. */
  5810. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5811. }
  5812. #endif
  5813. #ifdef WOLFSSL_ASN_TEMPLATE
  5814. /* ASN.1 template for an RSA private key.
  5815. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5816. */
  5817. static const ASNItem rsaKeyASN[] = {
  5818. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5819. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5820. /* Integers need to be in this specific order
  5821. * as asn code depends on this. */
  5822. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5823. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5824. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5825. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5826. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5827. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5828. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5829. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5830. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5831. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5832. * v2 - multiprime */
  5833. #endif
  5834. };
  5835. enum {
  5836. RSAKEYASN_IDX_SEQ = 0,
  5837. RSAKEYASN_IDX_VER,
  5838. /* Integers need to be in this specific order
  5839. * as asn code depends on this. */
  5840. RSAKEYASN_IDX_N,
  5841. RSAKEYASN_IDX_E,
  5842. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5843. RSAKEYASN_IDX_D,
  5844. RSAKEYASN_IDX_P,
  5845. RSAKEYASN_IDX_Q,
  5846. RSAKEYASN_IDX_DP,
  5847. RSAKEYASN_IDX_DQ,
  5848. RSAKEYASN_IDX_U,
  5849. #endif
  5850. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  5851. };
  5852. /* Number of items in ASN.1 template for an RSA private key. */
  5853. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5854. #endif
  5855. /* Decode RSA private key.
  5856. *
  5857. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5858. *
  5859. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5860. * being extracted.
  5861. *
  5862. * @param [in] input Buffer holding BER encoded data.
  5863. * @param [in, out] inOutIdx On in, start of RSA private key.
  5864. * On out, start of ASN.1 item after RSA private key.
  5865. * @param [in, out] key RSA key object. May be NULL.
  5866. * @param [out] keySz Size of key in bytes. May be NULL.
  5867. * @param [in] inSz Number of bytes in buffer.
  5868. * @return 0 on success.
  5869. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  5870. * @return BAD_FUNC_ARG when key and keySz are NULL.
  5871. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5872. * is invalid.
  5873. * @return BUFFER_E when data in buffer is too small.
  5874. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5875. * non-zero length.
  5876. * @return MP_INIT_E when the unable to initialize an mp_int.
  5877. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5878. */
  5879. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  5880. RsaKey* key, int* keySz, word32 inSz)
  5881. {
  5882. #ifndef WOLFSSL_ASN_TEMPLATE
  5883. int version, length;
  5884. word32 algId = 0;
  5885. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  5886. return BAD_FUNC_ARG;
  5887. }
  5888. /* if has pkcs8 header skip it */
  5889. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5890. /* ignore error, did not have pkcs8 header */
  5891. }
  5892. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5893. return ASN_PARSE_E;
  5894. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5895. return ASN_PARSE_E;
  5896. if (key == NULL) {
  5897. int i;
  5898. /* Modulus */
  5899. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  5900. return ASN_PARSE_E;
  5901. }
  5902. *inOutIdx += (word32)*keySz;
  5903. for (i = 1; i < RSA_INTS; i++) {
  5904. if (SkipInt(input, inOutIdx, inSz) < 0) {
  5905. return ASN_RSA_KEY_E;
  5906. }
  5907. }
  5908. }
  5909. else {
  5910. key->type = RSA_PRIVATE;
  5911. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5912. mp_memzero_add("Decode RSA key d", &key->d);
  5913. mp_memzero_add("Decode RSA key p", &key->p);
  5914. mp_memzero_add("Decode RSA key q", &key->q);
  5915. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5916. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5917. mp_memzero_add("Decode RSA key dP", &key->dP);
  5918. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  5919. mp_memzero_add("Decode RSA key u", &key->u);
  5920. #endif
  5921. #endif
  5922. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  5923. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  5924. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5925. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  5926. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  5927. GetInt(&key->q, input, inOutIdx, inSz) < 0
  5928. #else
  5929. SkipInt(input, inOutIdx, inSz) < 0 ||
  5930. SkipInt(input, inOutIdx, inSz) < 0 ||
  5931. SkipInt(input, inOutIdx, inSz) < 0
  5932. #endif
  5933. ) {
  5934. return ASN_RSA_KEY_E;
  5935. }
  5936. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  5937. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5938. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  5939. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  5940. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5941. #else
  5942. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  5943. SkipInt(input, inOutIdx, inSz) < 0 ||
  5944. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5945. #endif
  5946. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  5947. if (wc_InitRsaHw(key) != 0) {
  5948. return BAD_STATE_E;
  5949. }
  5950. #endif
  5951. }
  5952. return 0;
  5953. #else
  5954. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5955. int ret = 0;
  5956. byte version = (byte)-1;
  5957. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5958. word32 algId = 0;
  5959. #endif
  5960. void* heap = NULL;
  5961. /* Check validity of parameters. */
  5962. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  5963. (keySz == NULL))) {
  5964. ret = BAD_FUNC_ARG;
  5965. }
  5966. if ((ret == 0) && (key != NULL)) {
  5967. heap = key->heap;
  5968. }
  5969. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5970. if (ret == 0) {
  5971. /* if has pkcs8 header skip it */
  5972. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5973. /* ignore error, did not have pkcs8 header */
  5974. }
  5975. }
  5976. #endif
  5977. (void)heap;
  5978. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  5979. if (ret == 0) {
  5980. /* Register variable to hold version field. */
  5981. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  5982. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  5983. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5984. #define RSA_ASN_INTS RSA_PUB_INTS
  5985. /* Not extracting all data from BER encoding. */
  5986. #define RSA_ASN_COMPLETE 0
  5987. #else
  5988. #define RSA_ASN_INTS RSA_INTS
  5989. /* Extracting all data from BER encoding. */
  5990. #define RSA_ASN_COMPLETE 1
  5991. #endif
  5992. if (key != NULL) {
  5993. int i;
  5994. /* Extract all public fields. */
  5995. for (i = 0; i < RSA_ASN_INTS; i++) {
  5996. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  5997. GetRsaInt(key, i));
  5998. }
  5999. }
  6000. /* Parse BER encoding for RSA private key. */
  6001. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  6002. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  6003. }
  6004. /* Check version: 0 - two prime, 1 - multi-prime
  6005. * Multi-prime has optional sequence after coefficient for extra primes.
  6006. * If extra primes, parsing will fail as not all the buffer was used.
  6007. */
  6008. if ((ret == 0) && (version > PKCS1v1)) {
  6009. ret = ASN_PARSE_E;
  6010. }
  6011. if ((ret == 0) && (key != NULL)) {
  6012. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6013. /* RSA key object has all private key values. */
  6014. key->type = RSA_PRIVATE;
  6015. #else
  6016. /* RSA key object has all public key values. */
  6017. key->type = RSA_PUBLIC;
  6018. #endif
  6019. #ifdef WOLFSSL_XILINX_CRYPT
  6020. if (wc_InitRsaHw(key) != 0)
  6021. ret = BAD_STATE_E;
  6022. #endif
  6023. }
  6024. else if (ret == 0) {
  6025. /* Not filling in key but do want key size. */
  6026. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6027. /* Check whether first byte of data is 0x00 and drop it. */
  6028. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6029. (*keySz)--;
  6030. }
  6031. }
  6032. FREE_ASNGETDATA(dataASN, heap);
  6033. return ret;
  6034. #endif /* WOLFSSL_ASN_TEMPLATE */
  6035. }
  6036. /* Decode RSA private key.
  6037. *
  6038. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6039. *
  6040. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6041. * being extracted.
  6042. *
  6043. * @param [in] input Buffer holding BER encoded data.
  6044. * @param [in, out] inOutIdx On in, start of RSA private key.
  6045. * On out, start of ASN.1 item after RSA private key.
  6046. * @param [in, out] key RSA key object.
  6047. * @param [in] inSz Number of bytes in buffer.
  6048. * @return 0 on success.
  6049. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6050. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6051. * is invalid.
  6052. * @return BUFFER_E when data in buffer is too small.
  6053. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6054. * non-zero length.
  6055. * @return MP_INIT_E when the unable to initialize an mp_int.
  6056. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6057. */
  6058. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6059. word32 inSz)
  6060. {
  6061. if (key == NULL) {
  6062. return BAD_FUNC_ARG;
  6063. }
  6064. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6065. }
  6066. /* Valdidate RSA private key ASN.1 encoding.
  6067. *
  6068. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6069. *
  6070. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6071. * being extracted.
  6072. *
  6073. * @param [in] input Buffer holding BER encoded data.
  6074. * @param [in, out] inOutIdx On in, start of RSA private key.
  6075. * On out, start of ASN.1 item after RSA private key.
  6076. * @param [in] inSz Number of bytes in buffer.
  6077. * @return 0 on success.
  6078. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6079. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6080. * is invalid.
  6081. * @return BUFFER_E when data in buffer is too small.
  6082. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6083. * non-zero length.
  6084. * @return MP_INIT_E when the unable to initialize an mp_int.
  6085. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6086. */
  6087. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6088. word32 inSz)
  6089. {
  6090. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6091. }
  6092. #endif /* HAVE_USER_RSA */
  6093. #endif /* NO_RSA */
  6094. #ifdef WOLFSSL_ASN_TEMPLATE
  6095. /* ASN.1 template for a PKCS #8 key.
  6096. * Ignoring optional attributes and public key.
  6097. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6098. */
  6099. static const ASNItem pkcs8KeyASN[] = {
  6100. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6101. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6102. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6103. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6104. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6105. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6106. #ifdef WC_RSA_PSS
  6107. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6108. #endif
  6109. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6110. /* attributes [0] Attributes OPTIONAL */
  6111. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6112. };
  6113. enum {
  6114. PKCS8KEYASN_IDX_SEQ = 0,
  6115. PKCS8KEYASN_IDX_VER,
  6116. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6117. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6118. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6119. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6120. #ifdef WC_RSA_PSS
  6121. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6122. #endif
  6123. PKCS8KEYASN_IDX_PKEY_DATA,
  6124. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6125. };
  6126. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6127. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6128. #endif
  6129. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6130. *
  6131. * @param [in] input Buffer holding BER data.
  6132. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6133. * On out, start of encoded key.
  6134. * @param [in] sz Size of data in buffer.
  6135. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6136. * @return Length of key data on success.
  6137. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6138. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6139. * is invalid.
  6140. * @return BUFFER_E when data in buffer is too small.
  6141. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6142. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6143. * non-zero length.
  6144. */
  6145. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6146. word32* algId)
  6147. {
  6148. #ifndef WOLFSSL_ASN_TEMPLATE
  6149. word32 idx;
  6150. int version, length;
  6151. int ret;
  6152. byte tag;
  6153. if (input == NULL || inOutIdx == NULL)
  6154. return BAD_FUNC_ARG;
  6155. idx = *inOutIdx;
  6156. if (GetSequence(input, &idx, &length, sz) < 0)
  6157. return ASN_PARSE_E;
  6158. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6159. return ASN_PARSE_E;
  6160. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6161. return ASN_PARSE_E;
  6162. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6163. return ASN_PARSE_E;
  6164. idx = idx - 1; /* reset idx after finding tag */
  6165. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6166. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6167. word32 seqIdx = idx;
  6168. int seqLen;
  6169. /* Not set when -1. */
  6170. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6171. int mgf = -1;
  6172. int saltLen = 0;
  6173. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6174. return ASN_PARSE_E;
  6175. }
  6176. /* Get the private key parameters. */
  6177. ret = DecodeRsaPssParams(input + seqIdx,
  6178. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6179. if (ret != 0) {
  6180. return ASN_PARSE_E;
  6181. }
  6182. /* TODO: store parameters so that usage can be checked. */
  6183. idx += seqLen;
  6184. }
  6185. #endif /* WC_RSA_PSS && !NO_RSA */
  6186. if (tag == ASN_OBJECT_ID) {
  6187. if (SkipObjectId(input, &idx, sz) < 0)
  6188. return ASN_PARSE_E;
  6189. }
  6190. ret = GetOctetString(input, &idx, &length, sz);
  6191. if (ret < 0) {
  6192. if (ret == BUFFER_E)
  6193. return ASN_PARSE_E;
  6194. /* Some private keys don't expect an octet string */
  6195. WOLFSSL_MSG("Couldn't find Octet string");
  6196. }
  6197. *inOutIdx = idx;
  6198. return length;
  6199. #else
  6200. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6201. int ret = 0;
  6202. word32 oid = 9;
  6203. byte version;
  6204. word32 idx;
  6205. /* Check validity of parameters. */
  6206. if (input == NULL || inOutIdx == NULL) {
  6207. return BAD_FUNC_ARG;
  6208. }
  6209. idx = *inOutIdx;
  6210. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6211. if (ret == 0) {
  6212. /* Get version, check key type and curve type. */
  6213. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6214. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6215. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6216. /* Parse data. */
  6217. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6218. &idx, sz);
  6219. }
  6220. if (ret == 0) {
  6221. /* Key type OID. */
  6222. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6223. /* Version 1 includes an optional public key.
  6224. * If public key is included then the parsing will fail as it did not
  6225. * use all the data.
  6226. */
  6227. if (version > PKCS8v1) {
  6228. ret = ASN_PARSE_E;
  6229. }
  6230. }
  6231. if (ret == 0) {
  6232. switch (oid) {
  6233. #ifndef NO_RSA
  6234. case RSAk:
  6235. /* Must have NULL item but not OBJECT_ID item. */
  6236. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6237. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6238. ret = ASN_PARSE_E;
  6239. }
  6240. break;
  6241. #ifdef WC_RSA_PSS
  6242. case RSAPSSk:
  6243. /* Must not have NULL item. */
  6244. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6245. ret = ASN_PARSE_E;
  6246. }
  6247. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6248. enum wc_HashType hash;
  6249. int mgf;
  6250. int saltLen;
  6251. const byte* params = GetASNItem_Addr(
  6252. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6253. word32 paramsSz = GetASNItem_Length(
  6254. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6255. /* Validate the private key parameters. */
  6256. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6257. &saltLen);
  6258. if (ret != 0) {
  6259. return ASN_PARSE_E;
  6260. }
  6261. /* TODO: store parameters so that usage can be checked. */
  6262. }
  6263. break;
  6264. #endif
  6265. #endif
  6266. #ifdef HAVE_ECC
  6267. case ECDSAk:
  6268. /* Must not have NULL item. */
  6269. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6270. ret = ASN_PARSE_E;
  6271. }
  6272. break;
  6273. #endif
  6274. #ifdef HAVE_ED25519
  6275. case ED25519k:
  6276. /* Neither NULL item nor OBJECT_ID item allowed. */
  6277. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6278. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6279. ret = ASN_PARSE_E;
  6280. }
  6281. break;
  6282. #endif
  6283. #ifdef HAVE_CURVE25519
  6284. case X25519k:
  6285. /* Neither NULL item nor OBJECT_ID item allowed. */
  6286. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6287. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6288. ret = ASN_PARSE_E;
  6289. }
  6290. break;
  6291. #endif
  6292. #ifdef HAVE_ED448
  6293. case ED448k:
  6294. /* Neither NULL item nor OBJECT_ID item allowed. */
  6295. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6296. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6297. ret = ASN_PARSE_E;
  6298. }
  6299. break;
  6300. #endif
  6301. #ifdef HAVE_CURVE448
  6302. case X448k:
  6303. /* Neither NULL item nor OBJECT_ID item allowed. */
  6304. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6305. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6306. ret = ASN_PARSE_E;
  6307. }
  6308. break;
  6309. #endif
  6310. /* DSAk not supported. */
  6311. /* Falcon, Dilithium and Sphincs not supported. */
  6312. /* Ignore OID lookup failures. */
  6313. default:
  6314. break;
  6315. }
  6316. }
  6317. if (ret == 0) {
  6318. /* Return algorithm id of internal key. */
  6319. *algId = oid;
  6320. /* Return index to start of internal key. */
  6321. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6322. /* Return value is length of internal key. */
  6323. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6324. }
  6325. FREE_ASNGETDATA(dataASN, NULL);
  6326. return ret;
  6327. #endif
  6328. }
  6329. /* TODO: test case */
  6330. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6331. {
  6332. word32 oid;
  6333. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6334. }
  6335. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6336. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6337. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6338. {
  6339. word32 inOutIdx = 0;
  6340. int length;
  6341. if (input == NULL)
  6342. return BAD_FUNC_ARG;
  6343. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6344. if (length < 0)
  6345. return length;
  6346. if ((word32)length + inOutIdx > sz)
  6347. return BUFFER_E;
  6348. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6349. return length;
  6350. }
  6351. int ToTraditional(byte* input, word32 sz)
  6352. {
  6353. word32 oid;
  6354. return ToTraditional_ex(input, sz, &oid);
  6355. }
  6356. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6357. #if defined(HAVE_PKCS8) && !defined(NO_CERTS)
  6358. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6359. {
  6360. int length;
  6361. word32 algId;
  6362. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6363. return BAD_FUNC_ARG;
  6364. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6365. return length;
  6366. }
  6367. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6368. int algoID, const byte* curveOID, word32 oidSz)
  6369. {
  6370. #ifndef WOLFSSL_ASN_TEMPLATE
  6371. word32 keyIdx = 0;
  6372. word32 tmpSz = 0;
  6373. word32 sz;
  6374. word32 tmpAlgId = 0;
  6375. /* If out is NULL then return the max size needed
  6376. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6377. if (out == NULL && outSz != NULL) {
  6378. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6379. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6380. if (curveOID != NULL)
  6381. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6382. WOLFSSL_MSG("Checking size of PKCS8");
  6383. return LENGTH_ONLY_E;
  6384. }
  6385. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6386. if (key == NULL || out == NULL || outSz == NULL) {
  6387. return BAD_FUNC_ARG;
  6388. }
  6389. /* check the buffer has enough room for largest possible size */
  6390. if (curveOID != NULL) {
  6391. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6392. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6393. return BUFFER_E;
  6394. }
  6395. else {
  6396. oidSz = 0; /* with no curveOID oid size must be 0 */
  6397. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6398. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6399. return BUFFER_E;
  6400. }
  6401. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6402. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6403. (void)tmpAlgId;
  6404. return ASN_PARSE_E;
  6405. }
  6406. /* PrivateKeyInfo ::= SEQUENCE */
  6407. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6408. /* version Version
  6409. * no header information just INTEGER */
  6410. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6411. tmpSz += sz; keyIdx += sz;
  6412. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6413. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6414. if (curveOID != NULL && oidSz > 0) {
  6415. byte buf[MAX_LENGTH_SZ];
  6416. sz = SetLength(oidSz, buf);
  6417. sz += 1; /* plus one for ASN object id */
  6418. }
  6419. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6420. tmpSz += sz; keyIdx += sz;
  6421. /* privateKey PrivateKey *
  6422. * pkcs8 ecc uses slightly different format. Places curve oid in
  6423. * buffer */
  6424. if (curveOID != NULL && oidSz > 0) {
  6425. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6426. keyIdx += sz; tmpSz += sz;
  6427. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6428. keyIdx += oidSz; tmpSz += oidSz;
  6429. }
  6430. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6431. keyIdx += sz; tmpSz += sz;
  6432. XMEMCPY(out + keyIdx, key, keySz);
  6433. tmpSz += keySz;
  6434. /* attributes optional
  6435. * No attributes currently added */
  6436. /* rewind and add sequence */
  6437. sz = SetSequence(tmpSz, out);
  6438. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6439. *outSz = tmpSz + sz;
  6440. return (int)(tmpSz + sz);
  6441. #else
  6442. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6443. int sz;
  6444. int ret = 0;
  6445. word32 keyIdx = 0;
  6446. word32 tmpAlgId = 0;
  6447. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6448. /* Check validity of parameters. */
  6449. if (out == NULL && outSz != NULL) {
  6450. }
  6451. else if (key == NULL || out == NULL || outSz == NULL) {
  6452. ret = BAD_FUNC_ARG;
  6453. }
  6454. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6455. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6456. (void)tmpAlgId;
  6457. ret = ASN_PARSE_E;
  6458. }
  6459. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6460. if (ret == 0) {
  6461. /* Only support default PKCS #8 format - v0. */
  6462. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6463. /* Set key OID that corresponds to key data. */
  6464. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6465. oidKeyType);
  6466. if (curveOID != NULL && oidSz > 0) {
  6467. /* ECC key and curveOID set to write. */
  6468. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], curveOID, oidSz);
  6469. }
  6470. else {
  6471. /* EC curve OID to encode. */
  6472. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6473. }
  6474. /* Only RSA keys have NULL tagged item after OID. */
  6475. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6476. #ifdef WC_RSA_PSS
  6477. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6478. #endif
  6479. /* Set key data to encode. */
  6480. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6481. /* Get the size of the DER encoding. */
  6482. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6483. }
  6484. if (ret == 0) {
  6485. /* Always return the calculated size. */
  6486. *outSz = (word32)sz;
  6487. }
  6488. /* Check for buffer to encoded into. */
  6489. if ((ret == 0) && (out == NULL)) {
  6490. WOLFSSL_MSG("Checking size of PKCS8");
  6491. ret = LENGTH_ONLY_E;
  6492. }
  6493. if (ret == 0) {
  6494. /* Encode PKCS #8 key into buffer. */
  6495. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6496. ret = sz;
  6497. }
  6498. FREE_ASNSETDATA(dataASN, NULL);
  6499. return ret;
  6500. #endif /* WOLFSSL_ASN_TEMPLATE */
  6501. }
  6502. #endif /* HAVE_PKCS8 && !NO_CERTS */
  6503. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6504. /* check that the private key is a pair for the public key
  6505. * return 1 (true) on match
  6506. * return 0 or negative value on failure/error
  6507. *
  6508. * privKey : buffer holding DER format private key
  6509. * privKeySz : size of private key buffer
  6510. * pubKey : buffer holding DER format public key
  6511. * pubKeySz : size of public key buffer
  6512. * ks : type of key */
  6513. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6514. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6515. {
  6516. int ret;
  6517. (void)privKeySz;
  6518. (void)pubKeySz;
  6519. (void)ks;
  6520. if (privKey == NULL || pubKey == NULL) {
  6521. return BAD_FUNC_ARG;
  6522. }
  6523. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6524. /* test if RSA key */
  6525. if (ks == RSAk
  6526. #ifdef WC_RSA_PSS
  6527. || ks == RSAPSSk
  6528. #endif
  6529. ) {
  6530. #ifdef WOLFSSL_SMALL_STACK
  6531. RsaKey* a;
  6532. RsaKey* b = NULL;
  6533. #else
  6534. RsaKey a[1], b[1];
  6535. #endif
  6536. word32 keyIdx = 0;
  6537. #ifdef WOLFSSL_SMALL_STACK
  6538. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6539. if (a == NULL)
  6540. return MEMORY_E;
  6541. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6542. if (b == NULL) {
  6543. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6544. return MEMORY_E;
  6545. }
  6546. #endif
  6547. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6548. #ifdef WOLFSSL_SMALL_STACK
  6549. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6550. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6551. #endif
  6552. return ret;
  6553. }
  6554. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6555. wc_FreeRsaKey(a);
  6556. #ifdef WOLFSSL_SMALL_STACK
  6557. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6558. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6559. #endif
  6560. return ret;
  6561. }
  6562. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6563. WOLFSSL_MSG("Checking RSA key pair");
  6564. keyIdx = 0; /* reset to 0 for parsing public key */
  6565. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6566. pubKeySz)) == 0) {
  6567. /* limit for user RSA crypto because of RsaKey
  6568. * dereference. */
  6569. #if defined(HAVE_USER_RSA)
  6570. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6571. ret = 1; /* return first RSA cert as match */
  6572. #else
  6573. /* both keys extracted successfully now check n and e
  6574. * values are the same. This is dereferencing RsaKey */
  6575. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6576. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6577. ret = MP_CMP_E;
  6578. WOLFSSL_ERROR_VERBOSE(ret);
  6579. }
  6580. else
  6581. ret = 1;
  6582. #endif
  6583. }
  6584. else {
  6585. WOLFSSL_ERROR_VERBOSE(ret);
  6586. }
  6587. }
  6588. wc_FreeRsaKey(b);
  6589. wc_FreeRsaKey(a);
  6590. #ifdef WOLFSSL_SMALL_STACK
  6591. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6592. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6593. #endif
  6594. }
  6595. else
  6596. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6597. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6598. if (ks == ECDSAk) {
  6599. #ifdef WOLFSSL_SMALL_STACK
  6600. ecc_key* key_pair;
  6601. byte* privDer;
  6602. #else
  6603. ecc_key key_pair[1];
  6604. byte privDer[MAX_ECC_BYTES];
  6605. #endif
  6606. word32 privSz = MAX_ECC_BYTES;
  6607. word32 keyIdx = 0;
  6608. #ifdef WOLFSSL_SMALL_STACK
  6609. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6610. if (key_pair == NULL)
  6611. return MEMORY_E;
  6612. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6613. if (privDer == NULL) {
  6614. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6615. return MEMORY_E;
  6616. }
  6617. #endif
  6618. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6619. #ifdef WOLFSSL_SMALL_STACK
  6620. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6621. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6622. #endif
  6623. return ret;
  6624. }
  6625. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6626. privKeySz)) == 0) {
  6627. WOLFSSL_MSG("Checking ECC key pair");
  6628. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6629. == 0) {
  6630. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6631. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6632. #endif
  6633. wc_ecc_free(key_pair);
  6634. ret = wc_ecc_init(key_pair);
  6635. if (ret == 0) {
  6636. ret = wc_ecc_import_private_key(privDer,
  6637. privSz, pubKey,
  6638. pubKeySz, key_pair);
  6639. }
  6640. /* public and private extracted successfully now check if is
  6641. * a pair and also do sanity checks on key. wc_ecc_check_key
  6642. * checks that private * base generator equals pubkey */
  6643. if (ret == 0) {
  6644. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6645. ret = 1;
  6646. }
  6647. else {
  6648. WOLFSSL_ERROR_VERBOSE(ret);
  6649. }
  6650. }
  6651. ForceZero(privDer, privSz);
  6652. }
  6653. }
  6654. else {
  6655. WOLFSSL_ERROR_VERBOSE(ret);
  6656. }
  6657. wc_ecc_free(key_pair);
  6658. #ifdef WOLFSSL_SMALL_STACK
  6659. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6660. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6661. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6662. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6663. #endif
  6664. }
  6665. else
  6666. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6667. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6668. if (ks == ED25519k) {
  6669. #ifdef WOLFSSL_SMALL_STACK
  6670. ed25519_key* key_pair;
  6671. #else
  6672. ed25519_key key_pair[1];
  6673. #endif
  6674. word32 keyIdx = 0;
  6675. #ifdef WOLFSSL_SMALL_STACK
  6676. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6677. DYNAMIC_TYPE_ED25519);
  6678. if (key_pair == NULL)
  6679. return MEMORY_E;
  6680. #endif
  6681. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6682. #ifdef WOLFSSL_SMALL_STACK
  6683. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6684. #endif
  6685. return ret;
  6686. }
  6687. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6688. privKeySz)) == 0) {
  6689. WOLFSSL_MSG("Checking ED25519 key pair");
  6690. keyIdx = 0;
  6691. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6692. key_pair)) == 0) {
  6693. /* public and private extracted successfully no check if is
  6694. * a pair and also do sanity checks on key. wc_ecc_check_key
  6695. * checks that private * base generator equals pubkey */
  6696. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6697. ret = 1;
  6698. }
  6699. else {
  6700. WOLFSSL_ERROR_VERBOSE(ret);
  6701. }
  6702. }
  6703. }
  6704. else {
  6705. WOLFSSL_ERROR_VERBOSE(ret);
  6706. }
  6707. wc_ed25519_free(key_pair);
  6708. #ifdef WOLFSSL_SMALL_STACK
  6709. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6710. #endif
  6711. }
  6712. else
  6713. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6714. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6715. if (ks == ED448k) {
  6716. #ifdef WOLFSSL_SMALL_STACK
  6717. ed448_key* key_pair = NULL;
  6718. #else
  6719. ed448_key key_pair[1];
  6720. #endif
  6721. word32 keyIdx = 0;
  6722. #ifdef WOLFSSL_SMALL_STACK
  6723. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6724. DYNAMIC_TYPE_ED448);
  6725. if (key_pair == NULL)
  6726. return MEMORY_E;
  6727. #endif
  6728. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6729. #ifdef WOLFSSL_SMALL_STACK
  6730. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6731. #endif
  6732. return ret;
  6733. }
  6734. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6735. privKeySz)) == 0) {
  6736. WOLFSSL_MSG("Checking ED448 key pair");
  6737. keyIdx = 0;
  6738. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6739. key_pair)) == 0) {
  6740. /* public and private extracted successfully no check if is
  6741. * a pair and also do sanity checks on key. wc_ecc_check_key
  6742. * checks that private * base generator equals pubkey */
  6743. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6744. ret = 1;
  6745. }
  6746. else {
  6747. WOLFSSL_ERROR_VERBOSE(ret);
  6748. }
  6749. }
  6750. }
  6751. else {
  6752. WOLFSSL_ERROR_VERBOSE(ret);
  6753. }
  6754. wc_ed448_free(key_pair);
  6755. #ifdef WOLFSSL_SMALL_STACK
  6756. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6757. #endif
  6758. }
  6759. else
  6760. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6761. #if defined(HAVE_PQC)
  6762. #if defined(HAVE_FALCON)
  6763. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6764. #ifdef WOLFSSL_SMALL_STACK
  6765. falcon_key* key_pair = NULL;
  6766. #else
  6767. falcon_key key_pair[1];
  6768. #endif
  6769. word32 keyIdx = 0;
  6770. #ifdef WOLFSSL_SMALL_STACK
  6771. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6772. DYNAMIC_TYPE_FALCON);
  6773. if (key_pair == NULL)
  6774. return MEMORY_E;
  6775. #endif
  6776. ret = wc_falcon_init(key_pair);
  6777. if (ret < 0) {
  6778. #ifdef WOLFSSL_SMALL_STACK
  6779. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6780. #endif
  6781. return ret;
  6782. }
  6783. if (ks == FALCON_LEVEL1k) {
  6784. ret = wc_falcon_set_level(key_pair, 1);
  6785. }
  6786. else if (ks == FALCON_LEVEL5k) {
  6787. ret = wc_falcon_set_level(key_pair, 5);
  6788. }
  6789. if (ret < 0) {
  6790. #ifdef WOLFSSL_SMALL_STACK
  6791. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6792. #endif
  6793. return ret;
  6794. }
  6795. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6796. privKeySz)) == 0) {
  6797. WOLFSSL_MSG("Checking Falcon key pair");
  6798. keyIdx = 0;
  6799. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6800. key_pair)) == 0) {
  6801. /* Public and private extracted successfully. Sanity check. */
  6802. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6803. ret = 1;
  6804. }
  6805. else {
  6806. WOLFSSL_ERROR_VERBOSE(ret);
  6807. }
  6808. }
  6809. }
  6810. else {
  6811. WOLFSSL_ERROR_VERBOSE(ret);
  6812. }
  6813. wc_falcon_free(key_pair);
  6814. #ifdef WOLFSSL_SMALL_STACK
  6815. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6816. #endif
  6817. }
  6818. else
  6819. #endif /* HAVE_FALCON */
  6820. #if defined(HAVE_DILITHIUM)
  6821. if ((ks == DILITHIUM_LEVEL2k) ||
  6822. (ks == DILITHIUM_LEVEL3k) ||
  6823. (ks == DILITHIUM_LEVEL5k)) {
  6824. #ifdef WOLFSSL_SMALL_STACK
  6825. dilithium_key* key_pair = NULL;
  6826. #else
  6827. dilithium_key key_pair[1];
  6828. #endif
  6829. word32 keyIdx = 0;
  6830. #ifdef WOLFSSL_SMALL_STACK
  6831. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6832. DYNAMIC_TYPE_DILITHIUM);
  6833. if (key_pair == NULL)
  6834. return MEMORY_E;
  6835. #endif
  6836. ret = wc_dilithium_init(key_pair);
  6837. if (ret < 0) {
  6838. #ifdef WOLFSSL_SMALL_STACK
  6839. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6840. #endif
  6841. return ret;
  6842. }
  6843. if (ks == DILITHIUM_LEVEL2k) {
  6844. ret = wc_dilithium_set_level(key_pair, 2);
  6845. }
  6846. else if (ks == DILITHIUM_LEVEL3k) {
  6847. ret = wc_dilithium_set_level(key_pair, 3);
  6848. }
  6849. else if (ks == DILITHIUM_LEVEL5k) {
  6850. ret = wc_dilithium_set_level(key_pair, 5);
  6851. }
  6852. if (ret < 0) {
  6853. #ifdef WOLFSSL_SMALL_STACK
  6854. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6855. #endif
  6856. return ret;
  6857. }
  6858. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6859. privKeySz)) == 0) {
  6860. WOLFSSL_MSG("Checking Dilithium key pair");
  6861. keyIdx = 0;
  6862. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6863. key_pair)) == 0) {
  6864. /* Public and private extracted successfully. Sanity check. */
  6865. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6866. ret = 1;
  6867. }
  6868. }
  6869. wc_dilithium_free(key_pair);
  6870. #ifdef WOLFSSL_SMALL_STACK
  6871. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6872. #endif
  6873. }
  6874. else
  6875. #endif /* HAVE_DILITHIUM */
  6876. #if defined(HAVE_SPHINCS)
  6877. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6878. (ks == SPHINCS_FAST_LEVEL3k) ||
  6879. (ks == SPHINCS_FAST_LEVEL5k) ||
  6880. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6881. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6882. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6883. #ifdef WOLFSSL_SMALL_STACK
  6884. sphincs_key* key_pair = NULL;
  6885. #else
  6886. sphincs_key key_pair[1];
  6887. #endif
  6888. word32 keyIdx = 0;
  6889. #ifdef WOLFSSL_SMALL_STACK
  6890. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6891. DYNAMIC_TYPE_SPHINCS);
  6892. if (key_pair == NULL)
  6893. return MEMORY_E;
  6894. #endif
  6895. ret = wc_sphincs_init(key_pair);
  6896. if (ret < 0) {
  6897. #ifdef WOLFSSL_SMALL_STACK
  6898. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6899. #endif
  6900. return ret;
  6901. }
  6902. if (ks == SPHINCS_FAST_LEVEL1k) {
  6903. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6904. }
  6905. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6906. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6907. }
  6908. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6909. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6910. }
  6911. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6912. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6913. }
  6914. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6915. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6916. }
  6917. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6918. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6919. }
  6920. if (ret < 0) {
  6921. #ifdef WOLFSSL_SMALL_STACK
  6922. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6923. #endif
  6924. return ret;
  6925. }
  6926. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6927. privKeySz)) == 0) {
  6928. WOLFSSL_MSG("Checking Sphincs key pair");
  6929. keyIdx = 0;
  6930. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6931. key_pair)) == 0) {
  6932. /* Public and private extracted successfully. Sanity check. */
  6933. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6934. ret = 1;
  6935. }
  6936. }
  6937. wc_sphincs_free(key_pair);
  6938. #ifdef WOLFSSL_SMALL_STACK
  6939. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6940. #endif
  6941. }
  6942. else
  6943. #endif /* HAVE_SPHINCS */
  6944. #endif /* HAVE_PQC */
  6945. {
  6946. ret = 0;
  6947. }
  6948. (void)ks;
  6949. return ret;
  6950. }
  6951. /* check that the private key is a pair for the public key in certificate
  6952. * return 1 (true) on match
  6953. * return 0 or negative value on failure/error
  6954. *
  6955. * key : buffer holding DER format key
  6956. * keySz : size of key buffer
  6957. * der : a initialized and parsed DecodedCert holding a certificate */
  6958. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  6959. {
  6960. if (key == NULL || der == NULL) {
  6961. return BAD_FUNC_ARG;
  6962. }
  6963. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  6964. der->pubKeySize, (enum Key_Sum) der->keyOID);
  6965. }
  6966. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  6967. #ifndef NO_PWDBASED
  6968. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6969. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  6970. * size of encryption algorithm.
  6971. *
  6972. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  6973. * blockSz based on encryption algorithm.
  6974. *
  6975. * @param [in] first First byte of OID to use in check.
  6976. * @param [in] second Second byte of OID to use in check.
  6977. * @param [out] id wolfSSL id for PBE algorithm.
  6978. * @param [out] version Version of PBE OID:
  6979. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  6980. * @param [out] blockSz Block size of encryption algorithm.
  6981. * @return 0 on success.
  6982. * @return ALGO_ID_E when OID not supported.
  6983. * @return ASN_INPUT_E when first byte is invalid.
  6984. */
  6985. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  6986. {
  6987. int ret = 0;
  6988. (void)id;
  6989. (void)blockSz;
  6990. *version = -1;
  6991. /* pkcs-12 1 = pkcs-12PbeIds */
  6992. if (first == 1) {
  6993. /* PKCS #12: Appendix C */
  6994. switch (second) {
  6995. #if !defined(NO_SHA)
  6996. #ifndef NO_RC4
  6997. case PBE_SHA1_RC4_128:
  6998. *id = PBE_SHA1_RC4_128;
  6999. *version = PKCS12v1;
  7000. if (blockSz != NULL) {
  7001. *blockSz = 1;
  7002. }
  7003. break;
  7004. #endif
  7005. #ifndef NO_DES3
  7006. case PBE_SHA1_DES3:
  7007. *id = PBE_SHA1_DES3;
  7008. *version = PKCS12v1;
  7009. if (blockSz != NULL) {
  7010. *blockSz = DES_BLOCK_SIZE;
  7011. }
  7012. break;
  7013. #endif
  7014. #ifdef WC_RC2
  7015. case PBE_SHA1_40RC2_CBC:
  7016. *id = PBE_SHA1_40RC2_CBC;
  7017. *version = PKCS12v1;
  7018. if (blockSz != NULL) {
  7019. *blockSz = RC2_BLOCK_SIZE;
  7020. }
  7021. break;
  7022. #endif
  7023. #endif /* !NO_SHA */
  7024. default:
  7025. ret = ALGO_ID_E;
  7026. break;
  7027. }
  7028. }
  7029. else if (first != PKCS5) {
  7030. /* Bad OID. */
  7031. ret = ASN_INPUT_E;
  7032. }
  7033. /* PKCS #5 PBES2: Appendix A.4
  7034. * pkcs-5 13 = id-PBES2 */
  7035. else if (second == PBES2) {
  7036. *version = PKCS5v2;
  7037. /* Id and block size come from CheckAlgoV2() */
  7038. }
  7039. else {
  7040. /* PKCS #5 PBES1: Appendix A.3 */
  7041. /* see RFC 2898 for ids */
  7042. switch (second) {
  7043. #ifndef NO_DES3
  7044. #ifndef NO_MD5
  7045. case PBES1_MD5_DES:
  7046. *id = PBE_MD5_DES;
  7047. *version = PKCS5;
  7048. if (blockSz != NULL) {
  7049. *blockSz = DES_BLOCK_SIZE;
  7050. }
  7051. break;
  7052. #endif
  7053. #ifndef NO_SHA
  7054. case PBES1_SHA1_DES:
  7055. *id = PBE_SHA1_DES;
  7056. *version = PKCS5;
  7057. if (blockSz != NULL) {
  7058. *blockSz = DES_BLOCK_SIZE;
  7059. }
  7060. break;
  7061. #endif
  7062. #endif /* !NO_DES3 */
  7063. default:
  7064. ret = ALGO_ID_E;
  7065. break;
  7066. }
  7067. }
  7068. /* Return error code. */
  7069. return ret;
  7070. }
  7071. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7072. #ifdef HAVE_PKCS8
  7073. /* Check the encryption algorithm with PBES2 is supported and return block size
  7074. * and wolfSSL id for the PBE.
  7075. *
  7076. * @param [in] oid Encryption algorithm OID id.
  7077. * @param [out] id wolfSSL id for PBE algorithm.
  7078. * @param [out] version Version of PBE OID:
  7079. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7080. * @return 0 on success.
  7081. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7082. */
  7083. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7084. {
  7085. int ret = 0;
  7086. (void)id;
  7087. (void)blockSz;
  7088. switch (oid) {
  7089. #if !defined(NO_DES3) && !defined(NO_SHA)
  7090. case DESb:
  7091. *id = PBE_SHA1_DES;
  7092. if (blockSz != NULL) {
  7093. *blockSz = DES_BLOCK_SIZE;
  7094. }
  7095. break;
  7096. case DES3b:
  7097. *id = PBE_SHA1_DES3;
  7098. if (blockSz != NULL) {
  7099. *blockSz = DES_BLOCK_SIZE;
  7100. }
  7101. break;
  7102. #endif
  7103. #ifdef WOLFSSL_AES_256
  7104. case AES256CBCb:
  7105. *id = PBE_AES256_CBC;
  7106. if (blockSz != NULL) {
  7107. *blockSz = AES_BLOCK_SIZE;
  7108. }
  7109. break;
  7110. #endif
  7111. #ifdef WOLFSSL_AES_128
  7112. case AES128CBCb:
  7113. *id = PBE_AES128_CBC;
  7114. if (blockSz != NULL) {
  7115. *blockSz = AES_BLOCK_SIZE;
  7116. }
  7117. break;
  7118. #endif
  7119. default:
  7120. WOLFSSL_MSG("No PKCS v2 algo found");
  7121. ret = ALGO_ID_E;
  7122. break;
  7123. }
  7124. /* Return error code. */
  7125. return ret;
  7126. }
  7127. #endif /* HAVE_PKCS8 */
  7128. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7129. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7130. int* algoID, void* heap)
  7131. {
  7132. word32 tmpIdx = 0;
  7133. if (key == NULL || algoID == NULL)
  7134. return BAD_FUNC_ARG;
  7135. *algoID = 0;
  7136. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7137. {
  7138. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7139. if (rsa == NULL)
  7140. return MEMORY_E;
  7141. wc_InitRsaKey(rsa, heap);
  7142. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7143. *algoID = RSAk;
  7144. }
  7145. else {
  7146. WOLFSSL_MSG("Not RSA DER key");
  7147. }
  7148. wc_FreeRsaKey(rsa);
  7149. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7150. }
  7151. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7152. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7153. if (*algoID == 0) {
  7154. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7155. if (ecc == NULL)
  7156. return MEMORY_E;
  7157. tmpIdx = 0;
  7158. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7159. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7160. *algoID = ECDSAk;
  7161. /* now find oid */
  7162. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7163. WOLFSSL_MSG("Error getting ECC curve OID");
  7164. wc_ecc_free(ecc);
  7165. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7166. return BAD_FUNC_ARG;
  7167. }
  7168. }
  7169. else {
  7170. WOLFSSL_MSG("Not ECC DER key either");
  7171. }
  7172. wc_ecc_free(ecc);
  7173. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7174. }
  7175. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7176. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7177. if (*algoID == 0) {
  7178. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7179. DYNAMIC_TYPE_TMP_BUFFER);
  7180. if (ed25519 == NULL)
  7181. return MEMORY_E;
  7182. tmpIdx = 0;
  7183. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7184. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7185. *algoID = ED25519k;
  7186. }
  7187. else {
  7188. WOLFSSL_MSG("Not ED25519 DER key");
  7189. }
  7190. wc_ed25519_free(ed25519);
  7191. }
  7192. else {
  7193. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7194. }
  7195. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7196. }
  7197. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7198. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7199. if (*algoID == 0) {
  7200. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7201. DYNAMIC_TYPE_TMP_BUFFER);
  7202. if (ed448 == NULL)
  7203. return MEMORY_E;
  7204. tmpIdx = 0;
  7205. if (wc_ed448_init(ed448) == 0) {
  7206. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7207. *algoID = ED448k;
  7208. }
  7209. else {
  7210. WOLFSSL_MSG("Not ED448 DER key");
  7211. }
  7212. wc_ed448_free(ed448);
  7213. }
  7214. else {
  7215. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7216. }
  7217. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7218. }
  7219. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7220. #if defined(HAVE_PQC)
  7221. #if defined(HAVE_FALCON)
  7222. if (*algoID == 0) {
  7223. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7224. DYNAMIC_TYPE_TMP_BUFFER);
  7225. if (falcon == NULL)
  7226. return MEMORY_E;
  7227. if (wc_falcon_init(falcon) != 0) {
  7228. tmpIdx = 0;
  7229. if (wc_falcon_set_level(falcon, 1) == 0) {
  7230. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7231. == 0) {
  7232. *algoID = FALCON_LEVEL1k;
  7233. }
  7234. else {
  7235. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7236. }
  7237. }
  7238. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7239. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7240. == 0) {
  7241. *algoID = FALCON_LEVEL5k;
  7242. }
  7243. else {
  7244. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7245. }
  7246. }
  7247. else {
  7248. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7249. }
  7250. wc_falcon_free(falcon);
  7251. }
  7252. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7253. }
  7254. #endif /* HAVE_FALCON */
  7255. #if defined(HAVE_DILITHIUM)
  7256. if (*algoID == 0) {
  7257. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7258. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7259. if (dilithium == NULL)
  7260. return MEMORY_E;
  7261. if (wc_dilithium_init(dilithium) != 0) {
  7262. tmpIdx = 0;
  7263. if (wc_dilithium_set_level(dilithium, 2)
  7264. == 0) {
  7265. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7266. keySz) == 0) {
  7267. *algoID = DILITHIUM_LEVEL2k;
  7268. }
  7269. else {
  7270. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7271. }
  7272. }
  7273. else if (wc_dilithium_set_level(dilithium, 3)
  7274. == 0) {
  7275. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7276. keySz) == 0) {
  7277. *algoID = DILITHIUM_LEVEL3k;
  7278. }
  7279. else {
  7280. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7281. }
  7282. }
  7283. else if (wc_dilithium_set_level(dilithium, 5)
  7284. == 0) {
  7285. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7286. keySz) == 0) {
  7287. *algoID = DILITHIUM_LEVEL5k;
  7288. }
  7289. else {
  7290. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7291. }
  7292. }
  7293. else {
  7294. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7295. }
  7296. wc_dilithium_free(dilithium);
  7297. }
  7298. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7299. }
  7300. #endif /* HAVE_DILITHIUM */
  7301. #if defined(HAVE_SPHINCS)
  7302. if (*algoID == 0) {
  7303. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7304. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7305. if (sphincs == NULL)
  7306. return MEMORY_E;
  7307. if (wc_sphincs_init(sphincs) != 0) {
  7308. tmpIdx = 0;
  7309. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7310. == 0) {
  7311. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7312. keySz) == 0) {
  7313. *algoID = SPHINCS_FAST_LEVEL1k;
  7314. }
  7315. else {
  7316. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7317. }
  7318. }
  7319. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7320. == 0) {
  7321. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7322. keySz) == 0) {
  7323. *algoID = SPHINCS_FAST_LEVEL3k;
  7324. }
  7325. else {
  7326. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7327. }
  7328. }
  7329. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7330. == 0) {
  7331. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7332. keySz) == 0) {
  7333. *algoID = SPHINCS_FAST_LEVEL5k;
  7334. }
  7335. else {
  7336. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7337. }
  7338. }
  7339. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7340. == 0) {
  7341. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7342. keySz) == 0) {
  7343. *algoID = SPHINCS_SMALL_LEVEL1k;
  7344. }
  7345. else {
  7346. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7347. }
  7348. }
  7349. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7350. == 0) {
  7351. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7352. keySz) == 0) {
  7353. *algoID = SPHINCS_SMALL_LEVEL3k;
  7354. }
  7355. else {
  7356. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7357. }
  7358. }
  7359. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7360. == 0) {
  7361. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7362. keySz) == 0) {
  7363. *algoID = SPHINCS_SMALL_LEVEL5k;
  7364. }
  7365. else {
  7366. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7367. }
  7368. }
  7369. else {
  7370. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7371. }
  7372. wc_sphincs_free(sphincs);
  7373. }
  7374. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7375. }
  7376. #endif /* HAVE_SPHINCS */
  7377. #endif /* HAVE_PQC */
  7378. /* if flag is not set then this is not a key that we understand. */
  7379. if (*algoID == 0) {
  7380. WOLFSSL_MSG("Bad key DER or compile options");
  7381. return BAD_FUNC_ARG;
  7382. }
  7383. (void)tmpIdx;
  7384. (void)curveOID;
  7385. (void)oidSz;
  7386. (void)keySz;
  7387. (void)heap;
  7388. return 1;
  7389. }
  7390. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7391. #ifdef WOLFSSL_ASN_TEMPLATE
  7392. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7393. /* ASN.1 template for PBES2 parameters.
  7394. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7395. * A.2 - PBKDF2-params
  7396. * B.2 - Encryption schemes
  7397. * C - AlgorithmIdentifier
  7398. */
  7399. static const ASNItem pbes2ParamsASN[] = {
  7400. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7401. /* PBKDF2 */
  7402. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7403. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7404. /* Salt */
  7405. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7406. /* Iteration count */
  7407. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7408. /* Key length */
  7409. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7410. /* PRF - default is HMAC-SHA1 */
  7411. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7412. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7413. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7414. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7415. /* Encryption algorithm */
  7416. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7417. /* IV for CBC */
  7418. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7419. };
  7420. enum {
  7421. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7422. PBES2PARAMSASN_IDX_KDF_OID,
  7423. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7424. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7425. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7426. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7427. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7428. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7429. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7430. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7431. PBES2PARAMSASN_IDX_ENCS_OID,
  7432. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7433. };
  7434. /* Number of items in ASN.1 template for PBES2 parameters. */
  7435. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7436. /* ASN.1 template for PBES1 parameters.
  7437. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7438. */
  7439. static const ASNItem pbes1ParamsASN[] = {
  7440. /* Salt */
  7441. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7442. /* Iteration count */
  7443. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7444. };
  7445. enum {
  7446. PBES1PARAMSASN_IDX_SALT = 0,
  7447. PBES1PARAMSASN_IDX_ITER
  7448. };
  7449. /* Number of items in ASN.1 template for PBES1 parameters. */
  7450. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7451. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7452. #endif /* WOLFSSL_ASN_TEMPLATE */
  7453. #ifdef HAVE_PKCS8
  7454. /*
  7455. * Equivalent to calling TraditionalEnc with the same parameters but with
  7456. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7457. * part of the API (WOLFSSL_ASN_API).
  7458. */
  7459. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7460. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7461. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7462. {
  7463. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7464. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7465. }
  7466. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7467. int *blkSz)
  7468. {
  7469. int ret = 0;
  7470. switch (encAlgId) {
  7471. #if !defined(NO_DES3) && !defined(NO_SHA)
  7472. case DESb:
  7473. *len = sizeof(blkDesCbcOid);
  7474. *oid = blkDesCbcOid;
  7475. *id = PBE_SHA1_DES;
  7476. *blkSz = 8;
  7477. break;
  7478. case DES3b:
  7479. *len = sizeof(blkDes3CbcOid);
  7480. *oid = blkDes3CbcOid;
  7481. *id = PBE_SHA1_DES3;
  7482. *blkSz = 8;
  7483. break;
  7484. #endif
  7485. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7486. case AES256CBCb:
  7487. *len = sizeof(blkAes256CbcOid);
  7488. *oid = blkAes256CbcOid;
  7489. *id = PBE_AES256_CBC;
  7490. *blkSz = 16;
  7491. break;
  7492. #endif
  7493. default:
  7494. (void)len;
  7495. (void)oid;
  7496. (void)id;
  7497. (void)blkSz;
  7498. ret = ALGO_ID_E;
  7499. }
  7500. return ret;
  7501. }
  7502. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7503. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7504. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7505. void* heap)
  7506. {
  7507. #ifdef WOLFSSL_SMALL_STACK
  7508. byte* saltTmp = NULL;
  7509. #else
  7510. byte saltTmp[MAX_SALT_SIZE];
  7511. #endif
  7512. int genSalt = 0;
  7513. int ret = 0;
  7514. int version = 0;
  7515. int pbeId = 0;
  7516. int blockSz = 0;
  7517. const byte* encOid = NULL;
  7518. int encOidSz = 0;
  7519. word32 padSz = 0;
  7520. word32 innerLen = 0;
  7521. const byte* pbeOidBuf = NULL;
  7522. word32 pbeOidBufSz = 0;
  7523. word32 pbeLen = 0;
  7524. word32 kdfLen = 0;
  7525. word32 encLen = 0;
  7526. byte cbcIv[MAX_IV_SIZE];
  7527. word32 idx = 0;
  7528. word32 encIdx = 0;
  7529. (void)heap;
  7530. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7531. if (key == NULL || outSz == NULL || password == NULL) {
  7532. ret = BAD_FUNC_ARG;
  7533. }
  7534. if (ret == 0) {
  7535. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7536. }
  7537. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7538. genSalt = 1;
  7539. saltSz = 8;
  7540. }
  7541. if (ret == 0 && version == PKCS5v2) {
  7542. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7543. }
  7544. if (ret == 0) {
  7545. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7546. (blockSz - 1));
  7547. /* inner = OCT salt INT itt */
  7548. innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2);
  7549. if (version != PKCS5v2) {
  7550. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7551. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7552. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7553. }
  7554. else {
  7555. pbeOidBuf = pbes2;
  7556. pbeOidBufSz = sizeof(pbes2);
  7557. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7558. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7559. /* enc = OBJ enc_alg OCT iv */
  7560. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7561. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7562. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7563. (size_t)encLen);
  7564. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7565. }
  7566. }
  7567. if (ret == 0) {
  7568. /* outerLen = length of PBE encoding + octet string data */
  7569. /* Plus 2 for tag and length for pbe */
  7570. word32 outerLen = 2 + pbeLen;
  7571. /* Octet string tag, length */
  7572. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7573. /* Octet string bytes */
  7574. outerLen += keySz + padSz;
  7575. if (out == NULL) {
  7576. /* Sequence tag, length */
  7577. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7578. return LENGTH_ONLY_E;
  7579. }
  7580. SetOctetString(keySz + padSz, out);
  7581. idx += SetSequence(outerLen, out + idx);
  7582. encIdx = idx + outerLen - keySz - padSz;
  7583. /* Put Encrypted content in place. */
  7584. XMEMCPY(out + encIdx, key, keySz);
  7585. if (padSz > 0) {
  7586. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7587. keySz += padSz;
  7588. }
  7589. if (genSalt == 1) {
  7590. #ifdef WOLFSSL_SMALL_STACK
  7591. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7592. if (saltTmp == NULL) {
  7593. ret = MEMORY_E;
  7594. }
  7595. else
  7596. #endif
  7597. {
  7598. salt = saltTmp;
  7599. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7600. WOLFSSL_MSG("Error generating random salt");
  7601. }
  7602. }
  7603. }
  7604. }
  7605. if (ret == 0) {
  7606. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7607. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7608. }
  7609. if (ret == 0) {
  7610. if (version != PKCS5v2) {
  7611. /* PBE algorithm */
  7612. idx += SetSequence(pbeLen, out + idx);
  7613. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7614. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7615. idx += pbeOidBufSz;
  7616. }
  7617. else {
  7618. /* PBES2 algorithm identifier */
  7619. idx += SetSequence(pbeLen, out + idx);
  7620. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7621. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7622. idx += pbeOidBufSz;
  7623. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7624. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7625. /* KDF Algorithm Identifier */
  7626. idx += SetSequence(kdfLen, out + idx);
  7627. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7628. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7629. idx += sizeof(pbkdf2Oid);
  7630. }
  7631. idx += SetSequence(innerLen, out + idx);
  7632. idx += SetOctetString(saltSz, out + idx);
  7633. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7634. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7635. if (ret > 0)
  7636. ret = 0;
  7637. }
  7638. if (ret == 0) {
  7639. if (version == PKCS5v2) {
  7640. /* Encryption Algorithm Identifier */
  7641. idx += SetSequence(encLen, out + idx);
  7642. idx += (word32)SetObjectId(encOidSz, out + idx);
  7643. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7644. idx += (word32)encOidSz;
  7645. /* Encryption Algorithm Parameter: CBC IV */
  7646. idx += SetOctetString((word32)blockSz, out + idx);
  7647. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7648. idx += (word32)blockSz;
  7649. }
  7650. idx += SetOctetString(keySz, out + idx);
  7651. /* Default PRF - no need to write out OID */
  7652. idx += keySz;
  7653. ret = (int)idx;
  7654. }
  7655. #ifdef WOLFSSL_SMALL_STACK
  7656. if (saltTmp != NULL) {
  7657. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7658. }
  7659. #endif
  7660. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7661. return ret;
  7662. }
  7663. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7664. int passwordSz)
  7665. {
  7666. int ret;
  7667. int length;
  7668. word32 inOutIdx = 0;
  7669. if (input == NULL || password == NULL) {
  7670. return BAD_FUNC_ARG;
  7671. }
  7672. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7673. ret = ASN_PARSE_E;
  7674. }
  7675. else {
  7676. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7677. passwordSz);
  7678. if (ret > 0) {
  7679. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7680. }
  7681. }
  7682. if (ret > 0) {
  7683. /* DecryptContent will decrypt the data, but it will leave any padding
  7684. * bytes intact. This code calculates the length without the padding
  7685. * and we return that to the user. */
  7686. inOutIdx = 0;
  7687. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7688. ret = ASN_PARSE_E;
  7689. }
  7690. else {
  7691. ret = (int)inOutIdx + length;
  7692. }
  7693. }
  7694. return ret;
  7695. }
  7696. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7697. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7698. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7699. * buffer size. */
  7700. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7701. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7702. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7703. void* heap)
  7704. {
  7705. int ret = 0;
  7706. byte *pkcs8Key = NULL;
  7707. word32 pkcs8KeySz = 0;
  7708. int algId = 0;
  7709. const byte* curveOid = NULL;
  7710. word32 curveOidSz = 0;
  7711. if (ret == 0) {
  7712. /* check key type and get OID if ECC */
  7713. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7714. if (ret == 1)
  7715. ret = 0;
  7716. }
  7717. if (ret == 0) {
  7718. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7719. curveOidSz);
  7720. if (ret == LENGTH_ONLY_E)
  7721. ret = 0;
  7722. }
  7723. if (ret == 0) {
  7724. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7725. if (pkcs8Key == NULL)
  7726. ret = MEMORY_E;
  7727. }
  7728. if (ret == 0) {
  7729. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7730. curveOid, curveOidSz);
  7731. if (ret >= 0) {
  7732. pkcs8KeySz = (word32)ret;
  7733. ret = 0;
  7734. }
  7735. }
  7736. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7737. if (ret == 0) {
  7738. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7739. }
  7740. #endif
  7741. if (ret == 0) {
  7742. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7743. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7744. }
  7745. if (pkcs8Key != NULL) {
  7746. ForceZero(pkcs8Key, pkcs8KeySz);
  7747. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7748. }
  7749. (void)rng;
  7750. return ret;
  7751. }
  7752. /* Same as TraditionalEnc, but in the public API. */
  7753. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7754. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7755. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7756. WC_RNG* rng, void* heap)
  7757. {
  7758. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7759. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7760. }
  7761. #ifdef WOLFSSL_ASN_TEMPLATE
  7762. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7763. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7764. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7765. */
  7766. static const ASNItem pkcs8DecASN[] = {
  7767. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7768. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7769. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7770. /* PKCS #7 */
  7771. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7772. 0, 0, 2 },
  7773. /* PKCS #8 */
  7774. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7775. };
  7776. enum {
  7777. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7778. PKCS8DECASN_IDX_ENCALGO_OID,
  7779. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7780. PKCS8DECASN_IDX_ENCCONTENT,
  7781. PKCS8DECASN_IDX_ENCDATA
  7782. };
  7783. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7784. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7785. #endif
  7786. /* Decrypt data using PBE algorithm.
  7787. *
  7788. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7789. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7790. *
  7791. * Note: input buffer is overwritten with decrypted data!
  7792. *
  7793. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7794. *
  7795. * @param [in] input Data to decrypt and unwrap.
  7796. * @param [in] sz Size of encrypted data.
  7797. * @param [in] password Password to derive encryption key with.
  7798. * @param [in] passwordSz Size of password in bytes.
  7799. * @return Length of decrypted data on success.
  7800. * @return MEMORY_E when dynamic memory allocation fails.
  7801. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7802. * is invalid.
  7803. * @return BUFFER_E when data in buffer is too small.
  7804. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7805. * @return Other when decryption fails.
  7806. */
  7807. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7808. {
  7809. #ifndef WOLFSSL_ASN_TEMPLATE
  7810. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7811. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7812. int iterations = 0, keySz = 0;
  7813. #ifdef WOLFSSL_SMALL_STACK
  7814. byte* salt = NULL;
  7815. byte* cbcIv = NULL;
  7816. #else
  7817. byte salt[MAX_SALT_SIZE];
  7818. byte cbcIv[MAX_IV_SIZE];
  7819. #endif
  7820. byte tag;
  7821. if (passwordSz < 0) {
  7822. WOLFSSL_MSG("Bad password size");
  7823. return BAD_FUNC_ARG;
  7824. }
  7825. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7826. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7827. }
  7828. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7829. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7830. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7831. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7832. }
  7833. if (version == PKCS5v2) {
  7834. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7835. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7836. }
  7837. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7838. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7839. }
  7840. if (oid != PBKDF2_OID) {
  7841. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7842. }
  7843. }
  7844. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7845. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7846. }
  7847. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7848. * DEFAULT items. */
  7849. seqEnd = inOutIdx + (word32)length;
  7850. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7851. if (ret < 0)
  7852. goto exit_dc;
  7853. if (saltSz > MAX_SALT_SIZE) {
  7854. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7855. }
  7856. #ifdef WOLFSSL_SMALL_STACK
  7857. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7858. if (salt == NULL) {
  7859. ERROR_OUT(MEMORY_E, exit_dc);
  7860. }
  7861. #endif
  7862. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  7863. inOutIdx += (word32)saltSz;
  7864. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7865. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7866. }
  7867. /* OPTIONAL key length */
  7868. if (seqEnd > inOutIdx) {
  7869. word32 localIdx = inOutIdx;
  7870. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7871. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7872. }
  7873. if (tag == ASN_INTEGER &&
  7874. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7875. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7876. }
  7877. }
  7878. /* DEFAULT HMAC is SHA-1 */
  7879. if (seqEnd > inOutIdx) {
  7880. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7881. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7882. }
  7883. shaOid = oid;
  7884. }
  7885. #ifdef WOLFSSL_SMALL_STACK
  7886. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7887. if (cbcIv == NULL) {
  7888. ERROR_OUT(MEMORY_E, exit_dc);
  7889. }
  7890. #endif
  7891. if (version == PKCS5v2) {
  7892. /* get encryption algo */
  7893. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7894. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7895. }
  7896. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  7897. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7898. }
  7899. if (shaOid == 0)
  7900. shaOid = oid;
  7901. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7902. if (ret < 0)
  7903. goto exit_dc;
  7904. if (length > MAX_IV_SIZE) {
  7905. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7906. }
  7907. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  7908. inOutIdx += (word32)length;
  7909. }
  7910. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7911. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7912. }
  7913. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7914. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7915. }
  7916. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7917. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7918. }
  7919. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7920. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  7921. exit_dc:
  7922. #ifdef WOLFSSL_SMALL_STACK
  7923. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7924. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7925. #endif
  7926. if (ret == 0) {
  7927. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  7928. ret = length;
  7929. }
  7930. return ret;
  7931. #else
  7932. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7933. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7934. int ret = 0;
  7935. int id = 0;
  7936. int version;
  7937. word32 idx = 0;
  7938. word32 pIdx = 0;
  7939. word32 iterations;
  7940. word32 keySz = 0;
  7941. word32 saltSz = 0;
  7942. word32 shaOid = 0;
  7943. byte* salt = NULL;
  7944. byte* key = NULL;
  7945. byte cbcIv[MAX_IV_SIZE];
  7946. byte* params = NULL;
  7947. WOLFSSL_ENTER("DecryptContent");
  7948. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  7949. if (ret == 0) {
  7950. /* Check OID is a PBE Type */
  7951. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  7952. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  7953. &idx, sz);
  7954. }
  7955. if (ret == 0) {
  7956. /* Check the PBE algorithm and get the version and id. */
  7957. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  7958. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  7959. * Last byte: Alg or PBES2 */
  7960. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  7961. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  7962. &id, &version, NULL);
  7963. }
  7964. if (ret == 0) {
  7965. /* Get the parameters data. */
  7966. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  7967. /* Having a numbered choice means none or both will have errored out. */
  7968. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  7969. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  7970. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  7971. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  7972. else
  7973. ret = ASN_RSA_KEY_E;
  7974. }
  7975. if (ret == 0) {
  7976. if (version != PKCS5v2) {
  7977. /* Initialize for PBES1 parameters and put iterations in var. */
  7978. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  7979. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  7980. /* Parse the PBES1 parameters. */
  7981. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  7982. 0, params, &pIdx, sz);
  7983. if (ret == 0) {
  7984. /* Get the salt data. */
  7985. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  7986. }
  7987. }
  7988. else {
  7989. word32 ivSz = MAX_IV_SIZE;
  7990. /* Initialize for PBES2 parameters. Put iterations in var; match
  7991. * KDF, HMAC and cipher, and copy CBC into buffer. */
  7992. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  7993. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  7994. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  7995. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  7996. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  7997. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  7998. /* Parse the PBES2 parameters */
  7999. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  8000. 0, params, &pIdx, sz);
  8001. if (ret == 0) {
  8002. /* Get the salt data. */
  8003. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  8004. /* Get the digest and encryption algorithm id. */
  8005. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  8006. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8007. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8008. CheckAlgoV2(id, &id, NULL);
  8009. }
  8010. }
  8011. }
  8012. if (ret == 0) {
  8013. /* Decrypt the key. */
  8014. ret = wc_CryptKey(
  8015. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8016. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8017. }
  8018. if (ret == 0) {
  8019. /* Copy the decrypted key into the input (inline). */
  8020. XMEMMOVE(input, key, keySz);
  8021. ret = (int)keySz;
  8022. }
  8023. FREE_ASNGETDATA(dataASN, NULL);
  8024. return ret;
  8025. #endif
  8026. }
  8027. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8028. *
  8029. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8030. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8031. *
  8032. * Note: input buffer is overwritten with decrypted key!
  8033. *
  8034. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8035. *
  8036. * @param [in] input Data to decrypt and unwrap.
  8037. * @param [in] sz Size of encrypted data.
  8038. * @param [in] password Password to derive encryption key with.
  8039. * @param [in] passwordSz Size of password in bytes.
  8040. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8041. * @return Length of decrypted data on success.
  8042. * @return MEMORY_E when dynamic memory allocation fails.
  8043. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8044. * is invalid.
  8045. * @return BUFFER_E when data in buffer is too small.
  8046. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8047. * @return Other when decryption fails.
  8048. */
  8049. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8050. int passwordSz, word32* algId)
  8051. {
  8052. int ret;
  8053. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8054. if (ret > 0) {
  8055. ret = ToTraditional_ex(input, (word32)ret, algId);
  8056. }
  8057. return ret;
  8058. }
  8059. #endif /* HAVE_PKCS8 */
  8060. #ifdef HAVE_PKCS12
  8061. #define PKCS8_MIN_BLOCK_SIZE 8
  8062. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8063. {
  8064. int padSz;
  8065. /* calculate pad size */
  8066. padSz = blockSz - (sz & (blockSz - 1));
  8067. /* pad with padSz value */
  8068. if (buf) {
  8069. int i;
  8070. for (i = 0; i < padSz; i++) {
  8071. buf[sz+i] = (byte)(padSz & 0xFF);
  8072. }
  8073. }
  8074. /* return adjusted length */
  8075. return sz + padSz;
  8076. }
  8077. #ifdef WOLFSSL_ASN_TEMPLATE
  8078. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8079. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8080. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8081. */
  8082. static const ASNItem p8EncPbes1ASN[] = {
  8083. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8084. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8085. /* PBE algorithm */
  8086. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8087. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8088. /* Salt */
  8089. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8090. /* Iteration Count */
  8091. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8092. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8093. };
  8094. enum {
  8095. P8ENCPBES1ASN_IDX_SEQ = 0,
  8096. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8097. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8098. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8099. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8100. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8101. P8ENCPBES1ASN_IDX_ENCDATA
  8102. };
  8103. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8104. #endif
  8105. /* Wrap a private key in PKCS#8 and encrypt.
  8106. *
  8107. * Used for PKCS#12 and PKCS#7.
  8108. * vPKCS is the version of PKCS to use.
  8109. * vAlgo is the algorithm version to use.
  8110. *
  8111. * When salt is NULL, a random number is generated.
  8112. *
  8113. * data returned is :
  8114. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8115. *
  8116. * @param [in] input Data to encrypt.
  8117. * @param [in] inputSz Length of data in bytes.
  8118. * @param [out] out Buffer to write wrapped encrypted data into.
  8119. * @param [out] outSz Length of encrypted data in bytes.
  8120. * @param [in] password Password used to create encryption key.
  8121. * @param [in] passwordSz Length of password in bytes.
  8122. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8123. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8124. * @param [in] salt Salt to use with KDF.
  8125. * @param [in] saltSz Length of salt in bytes.
  8126. * @param [in] itt Number of iterations to use in KDF.
  8127. * @param [in] rng Random number generator to use to generate salt.
  8128. * @param [in] heap Dynamic memory allocator hint.
  8129. * @return The size of encrypted data on success
  8130. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8131. * @return ASN_PARSE_E when the salt size is too large.
  8132. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8133. * TraditionalEnc).
  8134. * @return MEMORY_E when dynamic memory allocation fails.
  8135. * @return Other when encryption or random number generation fails.
  8136. */
  8137. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8138. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8139. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8140. {
  8141. #ifndef WOLFSSL_ASN_TEMPLATE
  8142. word32 sz;
  8143. word32 inOutIdx = 0;
  8144. word32 tmpIdx = 0;
  8145. word32 totalSz = 0;
  8146. word32 seqSz;
  8147. word32 innerSz;
  8148. int ret;
  8149. int version, id, blockSz = 0;
  8150. #ifdef WOLFSSL_SMALL_STACK
  8151. byte* saltTmp = NULL;
  8152. byte* cbcIv = NULL;
  8153. #else
  8154. byte saltTmp[MAX_SALT_SIZE];
  8155. byte cbcIv[MAX_IV_SIZE];
  8156. #endif
  8157. byte seq[MAX_SEQ_SZ];
  8158. byte shr[MAX_SHORT_SZ];
  8159. word32 maxShr = MAX_SHORT_SZ;
  8160. word32 algoSz;
  8161. const byte* algoName;
  8162. (void)heap;
  8163. WOLFSSL_ENTER("EncryptContent");
  8164. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8165. return ASN_INPUT_E; /* Algo ID error */
  8166. if (version == PKCS5v2) {
  8167. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8168. return BAD_FUNC_ARG;
  8169. }
  8170. if (saltSz > MAX_SALT_SIZE)
  8171. return ASN_PARSE_E;
  8172. if (outSz == NULL) {
  8173. return BAD_FUNC_ARG;
  8174. }
  8175. /* calculate size */
  8176. /* size of constructed string at end */
  8177. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8178. totalSz = ASN_TAG_SZ;
  8179. totalSz += SetLength(sz, seq);
  8180. totalSz += sz;
  8181. /* size of sequence holding object id and sub sequence of salt and itt */
  8182. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8183. if (algoName == NULL) {
  8184. WOLFSSL_MSG("Unknown Algorithm");
  8185. return 0;
  8186. }
  8187. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8188. innerSz += algoSz;
  8189. /* get subsequence of salt and itt */
  8190. if (salt == NULL || saltSz == 0) {
  8191. sz = 8;
  8192. }
  8193. else {
  8194. sz = saltSz;
  8195. }
  8196. seqSz = SetOctetString(sz, seq);
  8197. seqSz += sz;
  8198. tmpIdx = 0;
  8199. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8200. if (ret >= 0) {
  8201. seqSz += (word32)ret;
  8202. }
  8203. else {
  8204. return ret;
  8205. }
  8206. innerSz += seqSz + SetSequence(seqSz, seq);
  8207. totalSz += innerSz + SetSequence(innerSz, seq);
  8208. if (out == NULL) {
  8209. *outSz = totalSz;
  8210. return LENGTH_ONLY_E;
  8211. }
  8212. inOutIdx = 0;
  8213. if (totalSz > *outSz)
  8214. return BUFFER_E;
  8215. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8216. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8217. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8218. inOutIdx += algoSz;
  8219. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8220. /* create random salt if one not provided */
  8221. if (salt == NULL || saltSz == 0) {
  8222. saltSz = 8;
  8223. #ifdef WOLFSSL_SMALL_STACK
  8224. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8225. if (saltTmp == NULL)
  8226. return MEMORY_E;
  8227. #endif
  8228. salt = saltTmp;
  8229. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8230. WOLFSSL_MSG("Error generating random salt");
  8231. #ifdef WOLFSSL_SMALL_STACK
  8232. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8233. #endif
  8234. return ret;
  8235. }
  8236. }
  8237. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8238. if (saltSz + inOutIdx > *outSz) {
  8239. #ifdef WOLFSSL_SMALL_STACK
  8240. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8241. #endif
  8242. return BUFFER_E;
  8243. }
  8244. XMEMCPY(out + inOutIdx, salt, saltSz);
  8245. inOutIdx += saltSz;
  8246. /* place iteration setting in buffer */
  8247. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8248. if (ret < 0) {
  8249. #ifdef WOLFSSL_SMALL_STACK
  8250. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8251. #endif
  8252. return ret;
  8253. }
  8254. if (inOutIdx + 1 > *outSz) {
  8255. #ifdef WOLFSSL_SMALL_STACK
  8256. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8257. #endif
  8258. return BUFFER_E;
  8259. }
  8260. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8261. /* get pad size and verify buffer room */
  8262. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8263. if (sz + inOutIdx > *outSz) {
  8264. #ifdef WOLFSSL_SMALL_STACK
  8265. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8266. #endif
  8267. return BUFFER_E;
  8268. }
  8269. inOutIdx += SetLength(sz, out + inOutIdx);
  8270. /* copy input to output buffer and pad end */
  8271. XMEMCPY(out + inOutIdx, input, inputSz);
  8272. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8273. #ifdef WOLFSSL_SMALL_STACK
  8274. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8275. if (cbcIv == NULL) {
  8276. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8277. return MEMORY_E;
  8278. }
  8279. #endif
  8280. /* encrypt */
  8281. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8282. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8283. #ifdef WOLFSSL_SMALL_STACK
  8284. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8285. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8286. #endif
  8287. return ret; /* encrypt failure */
  8288. }
  8289. #ifdef WOLFSSL_SMALL_STACK
  8290. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8291. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8292. #endif
  8293. (void)rng;
  8294. return (int)(inOutIdx + sz);
  8295. #else
  8296. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8297. int ret = 0;
  8298. int sz = 0;
  8299. int version;
  8300. int id = -1;
  8301. int blockSz = 0;
  8302. word32 pkcs8Sz = 0;
  8303. (void)heap;
  8304. WOLFSSL_ENTER("EncryptContent");
  8305. /* Must have a output size to return or check. */
  8306. if (outSz == NULL) {
  8307. ret = BAD_FUNC_ARG;
  8308. }
  8309. /* Check salt size is valid. */
  8310. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8311. ret = ASN_PARSE_E;
  8312. }
  8313. /* Get algorithm parameters for algorithm identifier. */
  8314. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8315. ret = ASN_INPUT_E;
  8316. }
  8317. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8318. if ((ret == 0) && (version == PKCS5v2)) {
  8319. ret = BAD_FUNC_ARG;
  8320. }
  8321. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8322. if (ret == 0) {
  8323. /* Setup data to go into encoding including PBE algorithm, salt,
  8324. * iteration count, and padded key length. */
  8325. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8326. oidPBEType);
  8327. if (salt == NULL || saltSz == 0) {
  8328. salt = NULL;
  8329. saltSz = PKCS5_SALT_SZ;
  8330. /* Salt generated into encoding below. */
  8331. }
  8332. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8333. salt, saltSz);
  8334. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8335. (word16)itt);
  8336. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8337. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8338. /* Calculate size of encoding. */
  8339. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8340. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8341. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8342. &sz);
  8343. }
  8344. /* Return size when no output buffer. */
  8345. if ((ret == 0) && (out == NULL)) {
  8346. *outSz = (word32)sz;
  8347. ret = LENGTH_ONLY_E;
  8348. }
  8349. /* Check output buffer is big enough for encoded data. */
  8350. if ((ret == 0) && (sz > (int)*outSz)) {
  8351. ret = BAD_FUNC_ARG;
  8352. }
  8353. if (ret == 0) {
  8354. /* Encode PKCS#8 key. */
  8355. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8356. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8357. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8358. out);
  8359. if (salt == NULL) {
  8360. /* Generate salt into encoding. */
  8361. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8362. data.buffer.data;
  8363. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8364. }
  8365. }
  8366. if (ret == 0) {
  8367. byte cbcIv[MAX_IV_SIZE];
  8368. /* Store PKCS#8 key in output buffer. */
  8369. byte* pkcs8 =
  8370. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8371. XMEMCPY(pkcs8, input, inputSz);
  8372. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8373. /* Encrypt PKCS#8 key inline. */
  8374. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8375. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8376. }
  8377. if (ret == 0) {
  8378. /* Returning size on success. */
  8379. ret = sz;
  8380. }
  8381. FREE_ASNSETDATA(dataASN, heap);
  8382. return ret;
  8383. #endif /* WOLFSSL_ASN_TEMPLATE */
  8384. }
  8385. #endif /* HAVE_PKCS12 */
  8386. #endif /* NO_PWDBASED */
  8387. #ifndef NO_RSA
  8388. #ifndef HAVE_USER_RSA
  8389. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  8390. /* This function is to retrieve key position information in a cert.*
  8391. * The information will be used to call TSIP TLS-linked API for *
  8392. * certificate verification. */
  8393. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8394. word32 inSz, word32* key_n,
  8395. word32* key_n_len, word32* key_e,
  8396. word32* key_e_len)
  8397. {
  8398. int ret = 0;
  8399. int length = 0;
  8400. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8401. byte b;
  8402. #endif
  8403. if (input == NULL || inOutIdx == NULL)
  8404. return BAD_FUNC_ARG;
  8405. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8406. return ASN_PARSE_E;
  8407. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8408. if ((*inOutIdx + 1) > inSz)
  8409. return BUFFER_E;
  8410. b = input[*inOutIdx];
  8411. if (b != ASN_INTEGER) {
  8412. /* not from decoded cert, will have algo id, skip past */
  8413. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8414. return ASN_PARSE_E;
  8415. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8416. return ASN_PARSE_E;
  8417. /* Option NULL ASN.1 tag */
  8418. if (*inOutIdx >= inSz) {
  8419. return BUFFER_E;
  8420. }
  8421. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8422. ret = GetASNNull(input, inOutIdx, inSz);
  8423. if (ret != 0)
  8424. return ret;
  8425. }
  8426. /* TODO: support RSA PSS */
  8427. /* should have bit tag length and seq next */
  8428. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8429. if (ret != 0)
  8430. return ret;
  8431. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8432. return ASN_PARSE_E;
  8433. }
  8434. #endif /* OPENSSL_EXTRA */
  8435. /* Get modulus */
  8436. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8437. *key_n += *inOutIdx;
  8438. if (ret < 0) {
  8439. return ASN_RSA_KEY_E;
  8440. }
  8441. if (key_n_len)
  8442. *key_n_len = length;
  8443. *inOutIdx += length;
  8444. /* Get exponent */
  8445. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8446. *key_e += *inOutIdx;
  8447. if (ret < 0) {
  8448. return ASN_RSA_KEY_E;
  8449. }
  8450. if (key_e_len)
  8451. *key_e_len = length;
  8452. return ret;
  8453. }
  8454. #endif /* WOLFSSL_RENESAS_TSIP */
  8455. #ifdef WOLFSSL_ASN_TEMPLATE
  8456. /* ASN.1 template for an RSA public key.
  8457. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8458. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8459. */
  8460. static const ASNItem rsaPublicKeyASN[] = {
  8461. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8462. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8463. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8464. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8465. #ifdef WC_RSA_PSS
  8466. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8467. #endif
  8468. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8469. /* RSAPublicKey */
  8470. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8471. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8472. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8473. };
  8474. enum {
  8475. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8476. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8477. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8478. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8479. #ifdef WC_RSA_PSS
  8480. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8481. #endif
  8482. RSAPUBLICKEYASN_IDX_PUBKEY,
  8483. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8484. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8485. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8486. };
  8487. /* Number of items in ASN.1 template for an RSA public key. */
  8488. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8489. #endif
  8490. /* Decode RSA public key.
  8491. *
  8492. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8493. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8494. *
  8495. * @param [in] input Buffer holding BER encoded data.
  8496. * @param [in, out] inOutIdx On in, start of RSA public key.
  8497. * On out, start of ASN.1 item after RSA public key.
  8498. * @param [in] inSz Number of bytes in buffer.
  8499. * @param [out] n Pointer to modulus in buffer.
  8500. * @param [out] nSz Size of modulus in bytes.
  8501. * @param [out] e Pointer to exponent in buffer.
  8502. * @param [out] eSz Size of exponent in bytes.
  8503. * @return 0 on success.
  8504. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8505. * is invalid.
  8506. * @return BUFFER_E when data in buffer is too small.
  8507. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8508. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8509. * non-zero length.
  8510. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8511. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8512. */
  8513. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8514. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8515. {
  8516. #ifndef WOLFSSL_ASN_TEMPLATE
  8517. int ret = 0;
  8518. int length = 0;
  8519. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8520. word32 localIdx;
  8521. byte tag;
  8522. #endif
  8523. if (input == NULL || inOutIdx == NULL)
  8524. return BAD_FUNC_ARG;
  8525. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8526. return ASN_PARSE_E;
  8527. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8528. localIdx = *inOutIdx;
  8529. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8530. return BUFFER_E;
  8531. if (tag != ASN_INTEGER) {
  8532. /* not from decoded cert, will have algo id, skip past */
  8533. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8534. return ASN_PARSE_E;
  8535. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8536. return ASN_PARSE_E;
  8537. /* Option NULL ASN.1 tag */
  8538. if (*inOutIdx >= inSz) {
  8539. return BUFFER_E;
  8540. }
  8541. localIdx = *inOutIdx;
  8542. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8543. return ASN_PARSE_E;
  8544. if (tag == ASN_TAG_NULL) {
  8545. ret = GetASNNull(input, inOutIdx, inSz);
  8546. if (ret != 0)
  8547. return ret;
  8548. }
  8549. #ifdef WC_RSA_PSS
  8550. /* Skip RSA PSS parameters. */
  8551. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8552. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8553. return ASN_PARSE_E;
  8554. *inOutIdx += length;
  8555. }
  8556. #endif
  8557. /* should have bit tag length and seq next */
  8558. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8559. if (ret != 0)
  8560. return ret;
  8561. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8562. return ASN_PARSE_E;
  8563. }
  8564. #endif /* OPENSSL_EXTRA */
  8565. /* Get modulus */
  8566. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8567. if (ret < 0) {
  8568. return ASN_RSA_KEY_E;
  8569. }
  8570. if (nSz)
  8571. *nSz = (word32)length;
  8572. if (n)
  8573. *n = &input[*inOutIdx];
  8574. *inOutIdx += (word32)length;
  8575. /* Get exponent */
  8576. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8577. if (ret < 0) {
  8578. return ASN_RSA_KEY_E;
  8579. }
  8580. if (eSz)
  8581. *eSz = (word32)length;
  8582. if (e)
  8583. *e = &input[*inOutIdx];
  8584. *inOutIdx += (word32)length;
  8585. return ret;
  8586. #else
  8587. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8588. int ret = 0;
  8589. #ifdef WC_RSA_PSS
  8590. word32 oid = RSAk;
  8591. #endif
  8592. /* Check validity of parameters. */
  8593. if (input == NULL || inOutIdx == NULL) {
  8594. ret = BAD_FUNC_ARG;
  8595. }
  8596. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8597. if (ret == 0) {
  8598. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8599. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8600. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8601. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8602. 0, input, inOutIdx, inSz);
  8603. if (ret != 0) {
  8604. /* Didn't work - try whole SubjectKeyInfo instead. */
  8605. #ifdef WC_RSA_PSS
  8606. /* Could be RSA or RSA PSS key. */
  8607. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8608. #else
  8609. /* Set the OID to expect. */
  8610. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8611. keyRsaOid, sizeof(keyRsaOid));
  8612. #endif
  8613. /* Decode SubjectKeyInfo. */
  8614. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8615. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8616. inSz);
  8617. }
  8618. }
  8619. #ifdef WC_RSA_PSS
  8620. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8621. /* Two possible OIDs supported - RSA and RSA PSS. */
  8622. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8623. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8624. ret = ASN_PARSE_E;
  8625. }
  8626. }
  8627. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8628. /* Can't have NULL and SEQ. */
  8629. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8630. ret = ASN_PARSE_E;
  8631. }
  8632. /* SEQ present only with RSA PSS. */
  8633. if ((ret == 0) && (oid != RSAPSSk)) {
  8634. ret = ASN_PARSE_E;
  8635. }
  8636. if (ret == 0) {
  8637. enum wc_HashType hash;
  8638. int mgf;
  8639. int saltLen;
  8640. const byte* params = GetASNItem_Addr(
  8641. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8642. word32 paramsSz = GetASNItem_Length(
  8643. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8644. /* Validate the private key parameters. */
  8645. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8646. /* TODO: store parameters so that usage can be checked. */
  8647. }
  8648. }
  8649. #endif
  8650. if (ret == 0) {
  8651. /* Return the buffers and lengths asked for. */
  8652. if (n != NULL) {
  8653. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8654. }
  8655. if (nSz != NULL) {
  8656. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8657. }
  8658. if (e != NULL) {
  8659. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8660. }
  8661. if (eSz != NULL) {
  8662. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8663. }
  8664. }
  8665. FREE_ASNGETDATA(dataASN, NULL);
  8666. return ret;
  8667. #endif /* WOLFSSL_ASN_TEMPLATE */
  8668. }
  8669. /* Decode RSA public key.
  8670. *
  8671. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8672. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8673. *
  8674. * @param [in] input Buffer holding BER encoded data.
  8675. * @param [in, out] inOutIdx On in, start of RSA public key.
  8676. * On out, start of ASN.1 item after RSA public key.
  8677. * @param [in, out] key RSA key object.
  8678. * @param [in] inSz Number of bytes in buffer.
  8679. * @return 0 on success.
  8680. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8681. * is invalid.
  8682. * @return BUFFER_E when data in buffer is too small.
  8683. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8684. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8685. * non-zero length.
  8686. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8687. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8688. */
  8689. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8690. word32 inSz)
  8691. {
  8692. int ret;
  8693. const byte *n = NULL, *e = NULL;
  8694. word32 nSz = 0, eSz = 0;
  8695. if (key == NULL)
  8696. return BAD_FUNC_ARG;
  8697. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8698. if (ret == 0) {
  8699. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8700. }
  8701. return ret;
  8702. }
  8703. #endif /* HAVE_USER_RSA */
  8704. #endif /* !NO_RSA */
  8705. #ifndef NO_DH
  8706. #if defined(WOLFSSL_DH_EXTRA)
  8707. /*
  8708. * Decodes DH public key to fill specified DhKey.
  8709. *
  8710. * return 0 on success, negative on failure
  8711. */
  8712. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8713. DhKey* key, word32 inSz)
  8714. {
  8715. int ret = 0;
  8716. int length;
  8717. word32 oid = 0;
  8718. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8719. return BAD_FUNC_ARG;
  8720. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8721. return ASN_PARSE_E;
  8722. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8723. return ASN_PARSE_E;
  8724. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8725. if (oid != DHk || ret < 0)
  8726. return ASN_DH_KEY_E;
  8727. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8728. return ASN_PARSE_E;
  8729. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8730. return ASN_DH_KEY_E;
  8731. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8732. mp_clear(&key->p);
  8733. return ASN_DH_KEY_E;
  8734. }
  8735. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8736. if (ret > 0) {
  8737. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8738. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8739. mp_clear(&key->p);
  8740. mp_clear(&key->g);
  8741. return ASN_DH_KEY_E;
  8742. }
  8743. }
  8744. else {
  8745. mp_clear(&key->p);
  8746. mp_clear(&key->g);
  8747. return ASN_DH_KEY_E;
  8748. }
  8749. return 0;
  8750. }
  8751. #endif /* WOLFSSL_DH_EXTRA */
  8752. #ifdef WOLFSSL_ASN_TEMPLATE
  8753. /* ASN.1 template for DH key.
  8754. * PKCS #3, 9 - DHParameter.
  8755. * (Also in: RFC 2786, 3)
  8756. */
  8757. static const ASNItem dhParamASN[] = {
  8758. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8759. /* prime */
  8760. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8761. /* base */
  8762. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8763. /* privateValueLength */
  8764. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8765. };
  8766. enum {
  8767. DHPARAMASN_IDX_SEQ = 0,
  8768. DHPARAMASN_IDX_PRIME,
  8769. DHPARAMASN_IDX_BASE,
  8770. DHPARAMASN_IDX_PRIVLEN
  8771. };
  8772. /* Number of items in ASN.1 template for DH key. */
  8773. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8774. #ifdef WOLFSSL_DH_EXTRA
  8775. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8776. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8777. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8778. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8779. */
  8780. static const ASNItem dhKeyPkcs8ASN[] = {
  8781. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8782. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8783. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8784. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8785. /* DHParameter */
  8786. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8787. /* p */
  8788. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8789. /* g */
  8790. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8791. /* q - factor of p-1 */
  8792. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8793. /* j - subgroup factor */
  8794. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8795. /* ValidationParms */
  8796. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8797. /* PrivateKey - PKCS #8 */
  8798. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8799. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8800. /* PublicKey - SubjectPublicKeyInfo. */
  8801. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8802. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8803. };
  8804. enum {
  8805. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8806. DHKEYPKCS8ASN_IDX_VER,
  8807. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8808. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8809. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8810. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8811. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8812. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8813. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8814. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8815. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8816. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8817. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8818. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8819. };
  8820. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8821. #endif
  8822. #endif
  8823. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8824. *
  8825. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8826. * object.
  8827. *
  8828. * @param [in] input BER/DER encoded data.
  8829. * @param [in, out] inOutIdx On in, start of DH key data.
  8830. * On out, end of DH key data.
  8831. * @param [in, out] key DH key object.
  8832. * @param [in] inSz Size of data in bytes.
  8833. * @return 0 on success.
  8834. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8835. * @return MEMORY_E when dynamic memory allocation fails.
  8836. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8837. * is invalid.
  8838. * @return BUFFER_E when data in buffer is too small.
  8839. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8840. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8841. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8842. * non-zero length.
  8843. * @return MP_INIT_E when the unable to initialize an mp_int.
  8844. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8845. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8846. */
  8847. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8848. {
  8849. #ifndef WOLFSSL_ASN_TEMPLATE
  8850. int ret = 0;
  8851. int length;
  8852. #ifdef WOLFSSL_DH_EXTRA
  8853. #if !defined(HAVE_FIPS) || \
  8854. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8855. word32 oid = 0, temp = 0;
  8856. #endif
  8857. #endif
  8858. WOLFSSL_ENTER("wc_DhKeyDecode");
  8859. if (inOutIdx == NULL)
  8860. return BAD_FUNC_ARG;
  8861. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8862. return ASN_PARSE_E;
  8863. #ifdef WOLFSSL_DH_EXTRA
  8864. #if !defined(HAVE_FIPS) || \
  8865. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8866. temp = *inOutIdx;
  8867. #endif
  8868. #endif
  8869. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8870. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8871. ret = ASN_DH_KEY_E;
  8872. }
  8873. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8874. mp_clear(&key->p);
  8875. ret = ASN_DH_KEY_E;
  8876. }
  8877. #ifdef WOLFSSL_DH_EXTRA
  8878. #if !defined(HAVE_FIPS) || \
  8879. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8880. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8881. if (ret == ASN_DH_KEY_E) {
  8882. *inOutIdx = temp;
  8883. /* the version (0) - private only (for public skip) */
  8884. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8885. *inOutIdx += (word32)length;
  8886. }
  8887. /* Size of dhKeyAgreement section */
  8888. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8889. return ASN_PARSE_E;
  8890. /* Check for dhKeyAgreement */
  8891. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8892. if (oid != DHk || ret < 0)
  8893. return ASN_DH_KEY_E;
  8894. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8895. return ASN_PARSE_E;
  8896. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8897. return ASN_DH_KEY_E;
  8898. }
  8899. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8900. mp_clear(&key->p);
  8901. return ASN_DH_KEY_E;
  8902. }
  8903. }
  8904. temp = *inOutIdx;
  8905. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8906. if (ret > 0) {
  8907. /* Found Bit String */
  8908. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8909. WOLFSSL_MSG("Found Public Key");
  8910. ret = 0;
  8911. }
  8912. } else {
  8913. *inOutIdx = temp;
  8914. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8915. if (ret > 0) {
  8916. /* Found Octet String */
  8917. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8918. WOLFSSL_MSG("Found Private Key");
  8919. /* Compute public */
  8920. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8921. }
  8922. } else {
  8923. /* Don't use length from failed CheckBitString/GetOctetString */
  8924. *inOutIdx = temp;
  8925. ret = 0;
  8926. }
  8927. }
  8928. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8929. #endif /* WOLFSSL_DH_EXTRA */
  8930. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8931. return ret;
  8932. #else
  8933. #ifdef WOLFSSL_DH_EXTRA
  8934. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8935. #else
  8936. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8937. #endif
  8938. int ret = 0;
  8939. /* Check input parameters are valid. */
  8940. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8941. ret = BAD_FUNC_ARG;
  8942. }
  8943. #ifdef WOLFSSL_DH_EXTRA
  8944. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8945. #else
  8946. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8947. #endif
  8948. if (ret == 0) {
  8949. /* Initialize data and set mp_ints to hold p and g. */
  8950. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  8951. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  8952. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  8953. /* Try simple PKCS #3 template. */
  8954. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  8955. inOutIdx, inSz);
  8956. #ifdef WOLFSSL_DH_EXTRA
  8957. if (ret != 0) {
  8958. mp_free(&key->p);
  8959. mp_free(&key->g);
  8960. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  8961. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  8962. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  8963. keyDhOid, sizeof(keyDhOid));
  8964. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  8965. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  8966. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  8967. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  8968. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  8969. /* Try PKCS #8 wrapped template. */
  8970. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  8971. input, inOutIdx, inSz);
  8972. if (ret == 0) {
  8973. /* VERSION only present in PKCS #8 private key structure */
  8974. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  8975. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  8976. ret = ASN_PARSE_E;
  8977. }
  8978. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  8979. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  8980. ret = ASN_PARSE_E;
  8981. }
  8982. }
  8983. if ((ret == 0) && mp_iszero(&key->pub)) {
  8984. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8985. }
  8986. }
  8987. #endif
  8988. }
  8989. FREE_ASNGETDATA(dataASN, key->heap);
  8990. return ret;
  8991. #endif /* WOLFSSL_ASN_TEMPLATE */
  8992. }
  8993. #ifdef WOLFSSL_DH_EXTRA
  8994. /* Export DH Key (private or public) */
  8995. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  8996. {
  8997. #ifndef WOLFSSL_ASN_TEMPLATE
  8998. int ret, privSz = 0, pubSz = 0;
  8999. word32 keySz, idx, len, total;
  9000. if (key == NULL || outSz == NULL) {
  9001. return BAD_FUNC_ARG;
  9002. }
  9003. /* determine size */
  9004. if (exportPriv) {
  9005. /* octect string: priv */
  9006. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9007. if (privSz < 0)
  9008. return privSz;
  9009. idx = 1 + SetLength((word32)privSz, NULL) +
  9010. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9011. }
  9012. else {
  9013. /* bit string: public */
  9014. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9015. if (pubSz < 0)
  9016. return pubSz;
  9017. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9018. }
  9019. keySz = idx;
  9020. /* DH Parameters sequence with P and G */
  9021. total = 0;
  9022. ret = wc_DhParamsToDer(key, NULL, &total);
  9023. if (ret != LENGTH_ONLY_E)
  9024. return ret;
  9025. idx += total;
  9026. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9027. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9028. idx += (word32)sizeof(keyDhOid);
  9029. len = idx - keySz;
  9030. /* sequence - all but pub/priv */
  9031. idx += SetSequence(len, NULL);
  9032. if (exportPriv) {
  9033. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9034. idx += 3;
  9035. }
  9036. /* sequence */
  9037. total = idx + SetSequence(idx, NULL);
  9038. /* if no output, then just getting size */
  9039. if (output == NULL) {
  9040. *outSz = total;
  9041. return LENGTH_ONLY_E;
  9042. }
  9043. /* make sure output fits in buffer */
  9044. if (total > *outSz) {
  9045. return BUFFER_E;
  9046. }
  9047. total = idx;
  9048. /* sequence */
  9049. idx = SetSequence(total, output);
  9050. if (exportPriv) {
  9051. /* version: 0 */
  9052. idx += (word32)SetMyVersion(0, output + idx, 0);
  9053. }
  9054. /* sequence - all but pub/priv */
  9055. idx += SetSequence(len, output + idx);
  9056. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9057. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9058. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9059. idx += sizeof(keyDhOid);
  9060. /* DH Parameters sequence with P and G */
  9061. total = *outSz - idx;
  9062. ret = wc_DhParamsToDer(key, output + idx, &total);
  9063. if (ret < 0)
  9064. return ret;
  9065. idx += total;
  9066. /* octect string: priv */
  9067. if (exportPriv) {
  9068. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9069. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9070. }
  9071. else {
  9072. /* bit string: public */
  9073. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9074. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9075. }
  9076. *outSz = idx;
  9077. return (int)idx;
  9078. #else
  9079. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9080. int ret = 0;
  9081. int sz;
  9082. WOLFSSL_ENTER("wc_DhKeyToDer");
  9083. XMEMSET(dataASN, 0, sizeof(dataASN));
  9084. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9085. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9086. /* Set mp_int containing p and g. */
  9087. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9088. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9089. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9090. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9091. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9092. if (exportPriv) {
  9093. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9094. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9095. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9096. }
  9097. else {
  9098. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9099. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9100. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9101. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9102. }
  9103. /* Calculate the size of the DH parameters. */
  9104. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9105. if (output == NULL) {
  9106. *outSz = (word32)sz;
  9107. ret = LENGTH_ONLY_E;
  9108. }
  9109. /* Check buffer is big enough for encoding. */
  9110. if ((ret == 0) && ((int)*outSz < sz)) {
  9111. ret = BUFFER_E;
  9112. }
  9113. if (ret == 0) {
  9114. /* Encode the DH parameters into buffer. */
  9115. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9116. /* Set the actual encoding size. */
  9117. *outSz = (word32)sz;
  9118. /* Return the actual encoding size. */
  9119. ret = sz;
  9120. }
  9121. return ret;
  9122. #endif
  9123. }
  9124. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9125. {
  9126. return wc_DhKeyToDer(key, out, outSz, 0);
  9127. }
  9128. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9129. {
  9130. return wc_DhKeyToDer(key, out, outSz, 1);
  9131. }
  9132. /* Convert DH key parameters to DER format, write to output (outSz)
  9133. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9134. * returned.
  9135. *
  9136. * Note : static function due to redefinition complications with DhKey and FIPS
  9137. * version 2 build.
  9138. *
  9139. * return bytes written on success */
  9140. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9141. {
  9142. #ifndef WOLFSSL_ASN_TEMPLATE
  9143. int ret;
  9144. word32 idx, total;
  9145. if (key == NULL || outSz == NULL) {
  9146. return BAD_FUNC_ARG;
  9147. }
  9148. /* determine size */
  9149. /* integer - g */
  9150. ret = SetASNIntMP(&key->g, -1, NULL);
  9151. if (ret < 0)
  9152. return ret;
  9153. idx = (word32)ret;
  9154. /* integer - p */
  9155. ret = SetASNIntMP(&key->p, -1, NULL);
  9156. if (ret < 0)
  9157. return ret;
  9158. idx += (word32)ret;
  9159. total = idx;
  9160. /* sequence */
  9161. idx += SetSequence(idx, NULL);
  9162. if (output == NULL) {
  9163. *outSz = idx;
  9164. return LENGTH_ONLY_E;
  9165. }
  9166. /* make sure output fits in buffer */
  9167. if (idx > *outSz) {
  9168. return BUFFER_E;
  9169. }
  9170. /* write DH parameters */
  9171. /* sequence - for P and G only */
  9172. idx = SetSequence(total, output);
  9173. /* integer - p */
  9174. ret = SetASNIntMP(&key->p, -1, output + idx);
  9175. if (ret < 0)
  9176. return ret;
  9177. idx += (word32)ret;
  9178. /* integer - g */
  9179. ret = SetASNIntMP(&key->g, -1, output + idx);
  9180. if (ret < 0)
  9181. return ret;
  9182. idx += (word32)ret;
  9183. *outSz = idx;
  9184. return (int)idx;
  9185. #else
  9186. ASNSetData dataASN[dhParamASN_Length];
  9187. int ret = 0;
  9188. int sz = 0;
  9189. WOLFSSL_ENTER("wc_DhParamsToDer");
  9190. if (key == NULL || outSz == NULL) {
  9191. ret = BAD_FUNC_ARG;
  9192. }
  9193. if (ret == 0) {
  9194. XMEMSET(dataASN, 0, sizeof(dataASN));
  9195. /* Set mp_int containing p and g. */
  9196. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9197. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9198. /* privateValueLength not encoded. */
  9199. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9200. /* Calculate the size of the DH parameters. */
  9201. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9202. }
  9203. if ((ret == 0) && (output == NULL)) {
  9204. *outSz = (word32)sz;
  9205. ret = LENGTH_ONLY_E;
  9206. }
  9207. /* Check buffer is big enough for encoding. */
  9208. if ((ret == 0) && (*outSz < (word32)sz)) {
  9209. ret = BUFFER_E;
  9210. }
  9211. if (ret == 0) {
  9212. /* Encode the DH parameters into buffer. */
  9213. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9214. /* Set the actual encoding size. */
  9215. *outSz = (word32)sz;
  9216. /* Return count of bytes written. */
  9217. ret = sz;
  9218. }
  9219. return ret;
  9220. #endif
  9221. }
  9222. #endif /* WOLFSSL_DH_EXTRA */
  9223. /* Decode DH parameters.
  9224. *
  9225. * PKCS #3, 9 - DHParameter.
  9226. * (Also in: RFC 2786, 3)
  9227. *
  9228. * @param [in] input Buffer holding BER encoded data.
  9229. * @param [in, out] inOutIdx On in, start of RSA public key.
  9230. * On out, start of ASN.1 item after RSA public key.
  9231. * @param [in] inSz Number of bytes in buffer.
  9232. * @param [in, out] p Buffer to hold prime.
  9233. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9234. * On out, size of prime in bytes.
  9235. * @param [in, out] g Buffer to hold base.
  9236. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9237. * On out, size of base in bytes.
  9238. * @return 0 on success.
  9239. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9240. * is invalid.
  9241. * @return BUFFER_E when data in buffer is too small.
  9242. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9243. */
  9244. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9245. byte* g, word32* gInOutSz)
  9246. {
  9247. #ifndef WOLFSSL_ASN_TEMPLATE
  9248. word32 idx = 0;
  9249. int ret;
  9250. int length;
  9251. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9252. return ASN_PARSE_E;
  9253. ret = GetASNInt(input, &idx, &length, inSz);
  9254. if (ret != 0)
  9255. return ret;
  9256. if (length <= (int)*pInOutSz) {
  9257. XMEMCPY(p, &input[idx], (size_t)length);
  9258. *pInOutSz = (word32)length;
  9259. }
  9260. else {
  9261. return BUFFER_E;
  9262. }
  9263. idx += (word32)length;
  9264. ret = GetASNInt(input, &idx, &length, inSz);
  9265. if (ret != 0)
  9266. return ret;
  9267. if (length <= (int)*gInOutSz) {
  9268. XMEMCPY(g, &input[idx], (size_t)length);
  9269. *gInOutSz = (word32)length;
  9270. }
  9271. else {
  9272. return BUFFER_E;
  9273. }
  9274. return 0;
  9275. #else
  9276. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9277. word32 idx = 0;
  9278. int ret = 0;
  9279. /* Make sure pointers are valid before use. */
  9280. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9281. (gInOutSz == NULL)) {
  9282. ret = BAD_FUNC_ARG;
  9283. }
  9284. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9285. if (ret == 0) {
  9286. /* Set the buffers to copy p and g into. */
  9287. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9288. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9289. /* Decode the DH Parameters. */
  9290. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9291. &idx, inSz);
  9292. }
  9293. FREE_ASNGETDATA(dataASN, NULL);
  9294. return ret;
  9295. #endif /* WOLFSSL_ASN_TEMPLATE */
  9296. }
  9297. #endif /* !NO_DH */
  9298. #ifndef NO_DSA
  9299. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9300. {
  9301. if (idx == 0)
  9302. return &key->p;
  9303. if (idx == 1)
  9304. return &key->q;
  9305. if (idx == 2)
  9306. return &key->g;
  9307. if (idx == 3)
  9308. return &key->y;
  9309. if (idx == 4)
  9310. return &key->x;
  9311. return NULL;
  9312. }
  9313. #ifdef WOLFSSL_ASN_TEMPLATE
  9314. /* ASN.1 template for DSA public and private keys.
  9315. * Public key: seq, p, q, g, y
  9316. * Private key: seq, version, p, q, g, y, x
  9317. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9318. */
  9319. static const ASNItem dsaKeyASN[] = {
  9320. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9321. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9322. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9323. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9324. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9325. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9326. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9327. };
  9328. enum {
  9329. DSAKEYASN_IDX_SEQ = 0,
  9330. DSAKEYASN_IDX_VER,
  9331. DSAKEYASN_IDX_P,
  9332. DSAKEYASN_IDX_Q,
  9333. DSAKEYASN_IDX_G,
  9334. DSAKEYASN_IDX_Y,
  9335. DSAKEYASN_IDX_X
  9336. };
  9337. /* Number of items in ASN.1 template for DSA private key. */
  9338. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9339. /* Number of items in ASN.1 template for DSA public key. */
  9340. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9341. /* ASN.1 template for PublicKeyInfo with DSA.
  9342. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9343. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9344. */
  9345. static const ASNItem dsaPubKeyASN[] = {
  9346. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9347. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9348. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9349. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9350. /* p */
  9351. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9352. /* q */
  9353. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9354. /* g */
  9355. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9356. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9357. /* y */
  9358. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9359. };
  9360. enum {
  9361. DSAPUBKEYASN_IDX_SEQ = 0,
  9362. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9363. DSAPUBKEYASN_IDX_ALGOID_OID,
  9364. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9365. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9366. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9367. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9368. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9369. DSAPUBKEYASN_IDX_PUBKEY_Y
  9370. };
  9371. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9372. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9373. #endif /* WOLFSSL_ASN_TEMPLATE */
  9374. /* Decode DSA public key.
  9375. *
  9376. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9377. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9378. *
  9379. * @param [in] input Buffer holding BER encoded data.
  9380. * @param [in, out] inOutIdx On in, start of DSA public key.
  9381. * On out, start of ASN.1 item after DSA public key.
  9382. * @param [in, out] key DSA key object.
  9383. * @param [in] inSz Number of bytes in buffer.
  9384. * @return 0 on success.
  9385. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9386. * is invalid.
  9387. * @return BUFFER_E when data in buffer is too small.
  9388. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9389. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9390. * non-zero length.
  9391. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9392. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9393. */
  9394. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9395. word32 inSz)
  9396. {
  9397. #ifndef WOLFSSL_ASN_TEMPLATE
  9398. int length;
  9399. int ret = 0;
  9400. word32 oid;
  9401. word32 maxIdx;
  9402. if (input == NULL || inOutIdx == NULL || key == NULL)
  9403. return BAD_FUNC_ARG;
  9404. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9405. return ASN_PARSE_E;
  9406. maxIdx = (word32)(*inOutIdx + (word32)length);
  9407. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9408. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9409. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9410. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9411. ret = ASN_DH_KEY_E;
  9412. if (ret != 0) {
  9413. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9414. return ASN_PARSE_E;
  9415. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9416. if (ret != 0)
  9417. return ret;
  9418. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9419. return ASN_PARSE_E;
  9420. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9421. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9422. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9423. return ASN_DH_KEY_E;
  9424. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9425. return ASN_PARSE_E;
  9426. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9427. return ASN_DH_KEY_E;
  9428. ret = 0;
  9429. }
  9430. key->type = DSA_PUBLIC;
  9431. return ret;
  9432. #else
  9433. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9434. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9435. int ret = 0;
  9436. /* Validated parameters. */
  9437. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9438. ret = BAD_FUNC_ARG;
  9439. }
  9440. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9441. if (ret == 0) {
  9442. int i;
  9443. /* Clear dynamic data items. */
  9444. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9445. /* seq
  9446. * p, q, g, y
  9447. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9448. for (i = 0; i < DSA_INTS - 1; i++)
  9449. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9450. /* Parse as simple form. */
  9451. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9452. inOutIdx, inSz);
  9453. if (ret != 0) {
  9454. /* Clear dynamic data items. */
  9455. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9456. /* Set DSA OID to expect. */
  9457. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9458. keyDsaOid, sizeof(keyDsaOid));
  9459. /* p, q, g */
  9460. for (i = 0; i < DSA_INTS - 2; i++)
  9461. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9462. GetDsaInt(key, i));
  9463. /* y */
  9464. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9465. /* Parse as SubjectPublicKeyInfo. */
  9466. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9467. input, inOutIdx, inSz);
  9468. }
  9469. }
  9470. if (ret == 0) {
  9471. /* Data parsed - set type of key parsed. */
  9472. key->type = DSA_PUBLIC;
  9473. }
  9474. FREE_ASNGETDATA(dataASN, key->heap);
  9475. return ret;
  9476. #endif
  9477. }
  9478. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9479. word32 inSz)
  9480. {
  9481. int length;
  9482. word32 maxIdx;
  9483. if (input == NULL || inOutIdx == NULL || key == NULL)
  9484. return BAD_FUNC_ARG;
  9485. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9486. return ASN_PARSE_E;
  9487. maxIdx = (word32)(*inOutIdx + (word32)length);
  9488. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9489. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9490. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9491. return ASN_DH_KEY_E;
  9492. return 0;
  9493. }
  9494. #ifdef WOLFSSL_ASN_TEMPLATE
  9495. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9496. static const ASNItem dsaKeyOctASN[] = {
  9497. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9498. /* p */
  9499. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9500. /* q */
  9501. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9502. /* g */
  9503. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9504. /* Private key */
  9505. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9506. /* x */
  9507. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9508. };
  9509. enum {
  9510. DSAKEYOCTASN_IDX_SEQ = 0,
  9511. DSAKEYOCTASN_IDX_P,
  9512. DSAKEYOCTASN_IDX_Q,
  9513. DSAKEYOCTASN_IDX_G,
  9514. DSAKEYOCTASN_IDX_PKEY_STR,
  9515. DSAKEYOCTASN_IDX_X
  9516. };
  9517. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9518. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9519. #endif
  9520. /* Decode DSA private key.
  9521. *
  9522. * @param [in] input Buffer holding BER encoded data.
  9523. * @param [in, out] inOutIdx On in, start of DSA public key.
  9524. * On out, start of ASN.1 item after DSA public key.
  9525. * @param [in, out] key DSA key object.
  9526. * @param [in] inSz Number of bytes in buffer.
  9527. * @return 0 on success.
  9528. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9529. * is invalid.
  9530. * @return BUFFER_E when data in buffer is too small.
  9531. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9532. * non-zero length.
  9533. */
  9534. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9535. word32 inSz)
  9536. {
  9537. #ifndef WOLFSSL_ASN_TEMPLATE
  9538. int length, version, ret = 0, temp = 0;
  9539. word32 algId = 0;
  9540. /* Sanity checks on input */
  9541. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9542. return BAD_FUNC_ARG;
  9543. }
  9544. /* if has pkcs8 header skip it */
  9545. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9546. /* ignore error, did not have pkcs8 header */
  9547. }
  9548. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9549. return ASN_PARSE_E;
  9550. temp = (int)*inOutIdx;
  9551. /* Default case expects a certificate with OctetString but no version ID */
  9552. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9553. if (ret < 0) {
  9554. mp_clear(&key->p);
  9555. ret = ASN_PARSE_E;
  9556. }
  9557. else {
  9558. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9559. if (ret < 0) {
  9560. mp_clear(&key->p);
  9561. mp_clear(&key->q);
  9562. ret = ASN_PARSE_E;
  9563. }
  9564. else {
  9565. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9566. if (ret < 0) {
  9567. mp_clear(&key->p);
  9568. mp_clear(&key->q);
  9569. mp_clear(&key->g);
  9570. ret = ASN_PARSE_E;
  9571. }
  9572. else {
  9573. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9574. if (ret < 0) {
  9575. mp_clear(&key->p);
  9576. mp_clear(&key->q);
  9577. mp_clear(&key->g);
  9578. ret = ASN_PARSE_E;
  9579. }
  9580. else {
  9581. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9582. if (ret < 0) {
  9583. mp_clear(&key->p);
  9584. mp_clear(&key->q);
  9585. mp_clear(&key->g);
  9586. mp_clear(&key->y);
  9587. ret = ASN_PARSE_E;
  9588. }
  9589. }
  9590. }
  9591. }
  9592. }
  9593. /* An alternate pass if default certificate fails parsing */
  9594. if (ret == ASN_PARSE_E) {
  9595. *inOutIdx = (word32)temp;
  9596. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9597. return ASN_PARSE_E;
  9598. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9599. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9600. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9601. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9602. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9603. return ASN_DH_KEY_E;
  9604. }
  9605. key->type = DSA_PRIVATE;
  9606. return 0;
  9607. #else
  9608. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9609. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9610. int ret = 0;
  9611. byte version = 0;
  9612. /* Sanity checks on input */
  9613. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9614. ret = BAD_FUNC_ARG;
  9615. }
  9616. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9617. if (ret == 0) {
  9618. int i;
  9619. /* Try dsaKeyOctASN */
  9620. /* Initialize key data and set mp_ints for params */
  9621. for (i = 0; i < DSA_INTS - 2; i++) {
  9622. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9623. }
  9624. /* and priv */
  9625. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9626. /* Try simple form. */
  9627. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9628. inOutIdx, inSz);
  9629. if (ret != 0) {
  9630. /* Try dsaKeyASN */
  9631. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9632. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9633. for (i = 0; i < DSA_INTS; i++) {
  9634. mp_int* n = GetDsaInt(key, i);
  9635. mp_clear(n);
  9636. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9637. }
  9638. /* Try simple OCTET_STRING form. */
  9639. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9640. inOutIdx, inSz);
  9641. }
  9642. }
  9643. if (ret == 0) {
  9644. /* Set the contents to be a private key. */
  9645. key->type = DSA_PRIVATE;
  9646. }
  9647. FREE_ASNGETDATA(dataASN, key->heap);
  9648. return ret;
  9649. #endif
  9650. }
  9651. #ifndef WOLFSSL_ASN_TEMPLATE
  9652. /* Release Tmp DSA resources */
  9653. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9654. {
  9655. int i;
  9656. for (i = 0; i < ints; i++)
  9657. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9658. (void)heap;
  9659. }
  9660. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9661. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9662. defined(WOLFSSL_CERT_GEN))
  9663. /* Encode a DSA public key into buffer.
  9664. *
  9665. * @param [out] output Buffer to hold encoded data.
  9666. * @param [in] key DSA key object.
  9667. * @param [out] outLen Length of buffer.
  9668. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9669. * @return Size of encoded data in bytes on success.
  9670. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9671. * than a minimal size (5 bytes), or buffer size is smaller than
  9672. * encoding size.
  9673. * @return MEMORY_E when dynamic memory allocation fails.
  9674. */
  9675. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9676. {
  9677. #ifndef WOLFSSL_ASN_TEMPLATE
  9678. /* p, g, q = DSA params, y = public exponent */
  9679. #ifdef WOLFSSL_SMALL_STACK
  9680. byte* p = NULL;
  9681. byte* g = NULL;
  9682. byte* q = NULL;
  9683. byte* y = NULL;
  9684. #else
  9685. byte p[MAX_DSA_INT_SZ];
  9686. byte g[MAX_DSA_INT_SZ];
  9687. byte q[MAX_DSA_INT_SZ];
  9688. byte y[MAX_DSA_INT_SZ];
  9689. #endif
  9690. byte innerSeq[MAX_SEQ_SZ];
  9691. byte outerSeq[MAX_SEQ_SZ];
  9692. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9693. int pSz, gSz, qSz, ySz;
  9694. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9695. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9696. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9697. return BAD_FUNC_ARG;
  9698. }
  9699. /* p */
  9700. #ifdef WOLFSSL_SMALL_STACK
  9701. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9702. if (p == NULL)
  9703. return MEMORY_E;
  9704. #endif
  9705. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9706. WOLFSSL_MSG("SetASNIntMP Error with p");
  9707. #ifdef WOLFSSL_SMALL_STACK
  9708. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9709. #endif
  9710. return pSz;
  9711. }
  9712. /* q */
  9713. #ifdef WOLFSSL_SMALL_STACK
  9714. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9715. if (q == NULL)
  9716. return MEMORY_E;
  9717. #endif
  9718. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9719. WOLFSSL_MSG("SetASNIntMP Error with q");
  9720. #ifdef WOLFSSL_SMALL_STACK
  9721. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9722. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9723. #endif
  9724. return qSz;
  9725. }
  9726. /* g */
  9727. #ifdef WOLFSSL_SMALL_STACK
  9728. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9729. if (g == NULL)
  9730. return MEMORY_E;
  9731. #endif
  9732. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9733. WOLFSSL_MSG("SetASNIntMP Error with g");
  9734. #ifdef WOLFSSL_SMALL_STACK
  9735. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9736. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9737. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9738. #endif
  9739. return gSz;
  9740. }
  9741. /* y */
  9742. #ifdef WOLFSSL_SMALL_STACK
  9743. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9744. if (y == NULL)
  9745. return MEMORY_E;
  9746. #endif
  9747. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9748. WOLFSSL_MSG("SetASNIntMP Error with y");
  9749. #ifdef WOLFSSL_SMALL_STACK
  9750. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9751. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9752. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9753. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9754. #endif
  9755. return ySz;
  9756. }
  9757. if (with_header) {
  9758. word32 algoSz;
  9759. #ifdef WOLFSSL_SMALL_STACK
  9760. byte* algo = NULL;
  9761. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9762. if (algo == NULL) {
  9763. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9764. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9765. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9766. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9767. return MEMORY_E;
  9768. }
  9769. #else
  9770. byte algo[MAX_ALGO_SZ];
  9771. #endif
  9772. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9773. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9774. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9775. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9776. (word32)(pSz + qSz + gSz), outerSeq);
  9777. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9778. bitStringSz + (word32)ySz + outerSeqSz, output);
  9779. /* check output size */
  9780. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9781. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9782. {
  9783. #ifdef WOLFSSL_SMALL_STACK
  9784. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9785. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9786. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9787. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9788. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9789. #endif
  9790. WOLFSSL_MSG("Error, output size smaller than outlen");
  9791. return BUFFER_E;
  9792. }
  9793. /* outerSeq */
  9794. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9795. idx += outerSeqSz;
  9796. /* algo */
  9797. XMEMCPY(output + idx, algo, algoSz);
  9798. idx += algoSz;
  9799. #ifdef WOLFSSL_SMALL_STACK
  9800. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9801. #endif
  9802. } else {
  9803. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9804. /* check output size */
  9805. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9806. #ifdef WOLFSSL_SMALL_STACK
  9807. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9808. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9809. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9810. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9811. #endif
  9812. WOLFSSL_MSG("Error, output size smaller than outlen");
  9813. return BUFFER_E;
  9814. }
  9815. idx = 0;
  9816. }
  9817. /* innerSeq */
  9818. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9819. idx += innerSeqSz;
  9820. /* p */
  9821. XMEMCPY(output + idx, p, (size_t)pSz);
  9822. idx += (word32)pSz;
  9823. /* q */
  9824. XMEMCPY(output + idx, q, (size_t)qSz);
  9825. idx += (word32)qSz;
  9826. /* g */
  9827. XMEMCPY(output + idx, g, (size_t)gSz);
  9828. idx += (word32)gSz;
  9829. /* bit string */
  9830. if (bitStringSz > 0) {
  9831. XMEMCPY(output + idx, bitString, bitStringSz);
  9832. idx += bitStringSz;
  9833. }
  9834. /* y */
  9835. XMEMCPY(output + idx, y, (size_t)ySz);
  9836. idx += (word32)ySz;
  9837. #ifdef WOLFSSL_SMALL_STACK
  9838. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9839. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9840. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9841. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9842. #endif
  9843. return (int)idx;
  9844. #else
  9845. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9846. int ret = 0;
  9847. int i;
  9848. int sz = 0;
  9849. const ASNItem *data = NULL;
  9850. int count = 0;
  9851. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9852. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9853. ret = BAD_FUNC_ARG;
  9854. }
  9855. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9856. if (ret == 0) {
  9857. if (with_header) {
  9858. /* Using dsaPubKeyASN */
  9859. data = dsaPubKeyASN;
  9860. count = dsaPubKeyASN_Length;
  9861. /* Set the algorithm OID to write out. */
  9862. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9863. /* Set the mp_ints to encode - parameters and public value. */
  9864. for (i = 0; i < DSA_INTS - 2; i++) {
  9865. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9866. GetDsaInt(key, i));
  9867. }
  9868. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9869. }
  9870. else {
  9871. /* Using dsaKeyASN */
  9872. data = dsaKeyASN;
  9873. count = dsaPublicKeyASN_Length;
  9874. /* Set the mp_ints to encode - parameters and public value. */
  9875. for (i = 0; i < DSA_INTS - 1; i++) {
  9876. /* Move all DSA ints up one slot (ignore VERSION so now
  9877. * it means P) */
  9878. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9879. GetDsaInt(key, i));
  9880. }
  9881. }
  9882. ret = SizeASN_Items(data, dataASN, count, &sz);
  9883. }
  9884. /* Check buffer is big enough for encoding. */
  9885. if ((ret == 0) && (sz > (int)outLen)) {
  9886. ret = BAD_FUNC_ARG;
  9887. }
  9888. /* Encode the DSA public key into output buffer. */
  9889. if (ret == 0) {
  9890. ret = SetASN_Items(data, dataASN, count, output);
  9891. }
  9892. FREE_ASNSETDATA(dataASN, key->heap);
  9893. return ret;
  9894. #endif /* WOLFSSL_ASN_TEMPLATE */
  9895. }
  9896. /* Encode a DSA public key into buffer.
  9897. *
  9898. * @param [out] output Buffer to hold encoded data.
  9899. * @param [in] key DSA key object.
  9900. * @param [out] outLen Length of buffer.
  9901. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9902. * @return Size of encoded data in bytes on success.
  9903. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9904. * than a minimal size (5 bytes), or buffer size is smaller than
  9905. * encoding size.
  9906. * @return MEMORY_E when dynamic memory allocation fails.
  9907. */
  9908. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9909. {
  9910. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  9911. }
  9912. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9913. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9914. int ints, int includeVersion)
  9915. {
  9916. #ifndef WOLFSSL_ASN_TEMPLATE
  9917. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  9918. word32 sizes[DSA_INTS];
  9919. int i, ret = 0;
  9920. byte seq[MAX_SEQ_SZ];
  9921. byte ver[MAX_VERSION_SZ];
  9922. byte* tmps[DSA_INTS];
  9923. if (ints > DSA_INTS || inLen == NULL)
  9924. return BAD_FUNC_ARG;
  9925. XMEMSET(sizes, 0, sizeof(sizes));
  9926. for (i = 0; i < ints; i++)
  9927. tmps[i] = NULL;
  9928. /* write all big ints from key to DER tmps */
  9929. for (i = 0; i < ints; i++) {
  9930. int mpSz;
  9931. mp_int* keyInt = GetDsaInt(key, i);
  9932. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  9933. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9934. DYNAMIC_TYPE_DSA);
  9935. if (tmps[i] == NULL) {
  9936. ret = MEMORY_E;
  9937. break;
  9938. }
  9939. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9940. if (mpSz < 0) {
  9941. ret = mpSz;
  9942. break;
  9943. }
  9944. sizes[i] = (word32)mpSz;
  9945. intTotalLen += (word32)mpSz;
  9946. }
  9947. if (ret != 0) {
  9948. FreeTmpDsas(tmps, key->heap, ints);
  9949. return ret;
  9950. }
  9951. /* make headers */
  9952. if (includeVersion)
  9953. verSz = (word32)SetMyVersion(0, ver, FALSE);
  9954. seqSz = SetSequence(verSz + intTotalLen, seq);
  9955. outLen = seqSz + verSz + intTotalLen;
  9956. *inLen = outLen;
  9957. if (output == NULL) {
  9958. FreeTmpDsas(tmps, key->heap, ints);
  9959. return LENGTH_ONLY_E;
  9960. }
  9961. if (outLen > *inLen) {
  9962. FreeTmpDsas(tmps, key->heap, ints);
  9963. return BAD_FUNC_ARG;
  9964. }
  9965. /* write to output */
  9966. XMEMCPY(output, seq, seqSz);
  9967. j = seqSz;
  9968. if (includeVersion) {
  9969. XMEMCPY(output + j, ver, verSz);
  9970. j += verSz;
  9971. }
  9972. for (i = 0; i < ints; i++) {
  9973. XMEMCPY(output + j, tmps[i], sizes[i]);
  9974. j += sizes[i];
  9975. }
  9976. FreeTmpDsas(tmps, key->heap, ints);
  9977. return (int)outLen;
  9978. #else
  9979. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  9980. int ret = 0;
  9981. int sz = 0;
  9982. (void)ints;
  9983. if ((key == NULL) || (inLen == NULL)) {
  9984. ret = BAD_FUNC_ARG;
  9985. }
  9986. if ((ret == 0) && (ints > DSA_INTS)) {
  9987. ret = BAD_FUNC_ARG;
  9988. }
  9989. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9990. if (ret == 0) {
  9991. int i;
  9992. if (includeVersion) {
  9993. /* Set the version. */
  9994. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  9995. }
  9996. else {
  9997. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  9998. }
  9999. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10000. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10001. /* Set the mp_ints to encode - params, public and private value. */
  10002. for (i = 0; i < DSA_INTS; i++) {
  10003. if (i < ints)
  10004. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10005. else
  10006. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10007. }
  10008. /* Calculate size of the encoding. */
  10009. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10010. }
  10011. if ((ret == 0) && (output == NULL)) {
  10012. *inLen = (word32)sz;
  10013. ret = LENGTH_ONLY_E;
  10014. }
  10015. /* Check buffer is big enough for encoding. */
  10016. if ((ret == 0) && (sz > (int)*inLen)) {
  10017. ret = BAD_FUNC_ARG;
  10018. }
  10019. if (ret == 0) {
  10020. /* Encode the DSA private key into output buffer. */
  10021. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10022. /* Return the size of the encoding. */
  10023. ret = sz;
  10024. }
  10025. FREE_ASNSETDATA(dataASN, key->heap);
  10026. return ret;
  10027. #endif /* WOLFSSL_ASN_TEMPLATE */
  10028. }
  10029. /* Encode a DSA private key into buffer.
  10030. *
  10031. * @param [in] key DSA key object.
  10032. * @param [out] output Buffer to hold encoded data.
  10033. * @param [out] inLen Length of buffer.
  10034. * @return Size of encoded data in bytes on success.
  10035. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10036. * or, buffer size is smaller than encoding size.
  10037. * @return MEMORY_E when dynamic memory allocation fails.
  10038. */
  10039. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10040. {
  10041. if (!key || !output)
  10042. return BAD_FUNC_ARG;
  10043. if (key->type != DSA_PRIVATE)
  10044. return BAD_FUNC_ARG;
  10045. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10046. }
  10047. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10048. return bytes written. Version is excluded to be compatible with
  10049. OpenSSL d2i_DSAparams */
  10050. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10051. {
  10052. if (!key || !output)
  10053. return BAD_FUNC_ARG;
  10054. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10055. }
  10056. /* This version of the function allows output to be NULL. In that case, the
  10057. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10058. size will be pointed to by inLen. */
  10059. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10060. {
  10061. if (!key || !inLen)
  10062. return BAD_FUNC_ARG;
  10063. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10064. }
  10065. #endif /* NO_DSA */
  10066. /* Initialize decoded certificate object with buffer of DER encoding.
  10067. *
  10068. * @param [in, out] cert Decoded certificate object.
  10069. * @param [in] source Buffer containing DER encoded certificate.
  10070. * @param [in] inSz Size of DER data in buffer in bytes.
  10071. * @param [in] heap Dynamic memory hint.
  10072. */
  10073. void InitDecodedCert(DecodedCert* cert,
  10074. const byte* source, word32 inSz, void* heap)
  10075. {
  10076. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10077. }
  10078. /* Initialize decoded certificate object with buffer of DER encoding.
  10079. *
  10080. * @param [in, out] cert Decoded certificate object.
  10081. * @param [in] source Buffer containing DER encoded certificate.
  10082. * @param [in] inSz Size of DER data in buffer in bytes.
  10083. * @param [in] heap Dynamic memory hint.
  10084. * @param [in] devId Crypto callback ID to use.
  10085. */
  10086. void InitDecodedCert_ex(DecodedCert* cert,
  10087. const byte* source, word32 inSz, void* heap, int devId)
  10088. {
  10089. if (cert != NULL) {
  10090. XMEMSET(cert, 0, sizeof(DecodedCert));
  10091. cert->subjectCNEnc = CTC_UTF8;
  10092. cert->issuer[0] = '\0';
  10093. cert->subject[0] = '\0';
  10094. cert->source = source; /* don't own */
  10095. cert->maxIdx = inSz; /* can't go over this index */
  10096. cert->heap = heap;
  10097. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10098. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10099. #ifdef WOLFSSL_CERT_NAME_ALL
  10100. cert->subjectNEnc = CTC_UTF8;
  10101. cert->subjectIEnc = CTC_UTF8;
  10102. cert->subjectDNQEnc = CTC_UTF8;
  10103. cert->subjectGNEnc = CTC_UTF8;
  10104. #endif
  10105. cert->subjectSNEnc = CTC_UTF8;
  10106. cert->subjectCEnc = CTC_PRINTABLE;
  10107. cert->subjectLEnc = CTC_UTF8;
  10108. cert->subjectSTEnc = CTC_UTF8;
  10109. cert->subjectOEnc = CTC_UTF8;
  10110. cert->subjectOUEnc = CTC_UTF8;
  10111. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10112. cert->issuerSNEnc = CTC_UTF8;
  10113. cert->issuerCEnc = CTC_PRINTABLE;
  10114. cert->issuerLEnc = CTC_UTF8;
  10115. cert->issuerSTEnc = CTC_UTF8;
  10116. cert->issuerOEnc = CTC_UTF8;
  10117. cert->issuerOUEnc = CTC_UTF8;
  10118. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10119. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10120. #ifndef NO_CERTS
  10121. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10122. #endif
  10123. }
  10124. }
  10125. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10126. void* heap)
  10127. {
  10128. InitDecodedCert(cert, source, inSz, heap);
  10129. }
  10130. /* Free the alternative names object.
  10131. *
  10132. * Frees each linked list items and its name.
  10133. *
  10134. * @param [in, out] altNames Alternative names.
  10135. * @param [in] heap Dynamic memory hint.
  10136. */
  10137. void FreeAltNames(DNS_entry* altNames, void* heap)
  10138. {
  10139. (void)heap;
  10140. while (altNames) {
  10141. DNS_entry* tmp = altNames->next;
  10142. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10143. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10144. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10145. #endif
  10146. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10147. altNames = tmp;
  10148. }
  10149. }
  10150. /* malloc and initialize a new alt name structure */
  10151. DNS_entry* AltNameNew(void* heap)
  10152. {
  10153. DNS_entry* ret;
  10154. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10155. if (ret != NULL) {
  10156. XMEMSET(ret, 0, sizeof(DNS_entry));
  10157. }
  10158. (void)heap;
  10159. return ret;
  10160. }
  10161. #ifndef IGNORE_NAME_CONSTRAINTS
  10162. /* Free the subtree names object.
  10163. *
  10164. * Frees each linked list items and its name.
  10165. *
  10166. * @param [in, out] names Subtree names.
  10167. * @param [in] heap Dynamic memory hint.
  10168. */
  10169. void FreeNameSubtrees(Base_entry* names, void* heap)
  10170. {
  10171. (void)heap;
  10172. while (names) {
  10173. Base_entry* tmp = names->next;
  10174. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10175. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10176. names = tmp;
  10177. }
  10178. }
  10179. #endif /* IGNORE_NAME_CONSTRAINTS */
  10180. /* Free the decoded cert object's dynamic data.
  10181. *
  10182. * @param [in, out] cert Decoded certificate object.
  10183. */
  10184. void FreeDecodedCert(DecodedCert* cert)
  10185. {
  10186. if (cert == NULL)
  10187. return;
  10188. if (cert->subjectCNStored == 1) {
  10189. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10190. }
  10191. if (cert->pubKeyStored == 1) {
  10192. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10193. }
  10194. if (cert->weOwnAltNames && cert->altNames)
  10195. FreeAltNames(cert->altNames, cert->heap);
  10196. #ifndef IGNORE_NAME_CONSTRAINTS
  10197. if (cert->altEmailNames)
  10198. FreeAltNames(cert->altEmailNames, cert->heap);
  10199. if (cert->altDirNames)
  10200. FreeAltNames(cert->altDirNames, cert->heap);
  10201. if (cert->permittedNames)
  10202. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10203. if (cert->excludedNames)
  10204. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10205. #endif /* IGNORE_NAME_CONSTRAINTS */
  10206. #ifdef WOLFSSL_SEP
  10207. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10208. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10209. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10210. #endif /* WOLFSSL_SEP */
  10211. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10212. if (cert->issuerName != NULL)
  10213. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10214. if (cert->subjectName != NULL)
  10215. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10216. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10217. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10218. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10219. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10220. #endif
  10221. #ifndef NO_CERTS
  10222. FreeSignatureCtx(&cert->sigCtx);
  10223. #endif
  10224. }
  10225. void wc_FreeDecodedCert(DecodedCert* cert)
  10226. {
  10227. FreeDecodedCert(cert);
  10228. }
  10229. #ifndef WOLFSSL_ASN_TEMPLATE
  10230. static int GetCertHeader(DecodedCert* cert)
  10231. {
  10232. int ret = 0, len;
  10233. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10234. return ASN_PARSE_E;
  10235. /* Reset the max index for the size indicated in the outer wrapper. */
  10236. cert->maxIdx = (word32)len + cert->srcIdx;
  10237. cert->certBegin = cert->srcIdx;
  10238. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10239. return ASN_PARSE_E;
  10240. cert->sigIndex = (word32)len + cert->srcIdx;
  10241. if (cert->sigIndex > cert->maxIdx)
  10242. return ASN_PARSE_E;
  10243. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10244. cert->sigIndex) < 0)
  10245. return ASN_PARSE_E;
  10246. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10247. &cert->serialSz, cert->sigIndex) < 0)
  10248. return ASN_PARSE_E;
  10249. return ret;
  10250. }
  10251. #endif
  10252. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10253. defined(HAVE_LIBOQS))
  10254. /* Store the key data under the BIT_STRING in dynamicly allocated data.
  10255. *
  10256. * @param [in, out] cert Certificate object.
  10257. * @param [in] source Buffer containing encoded key.
  10258. * @param [in, out] srcIdx On in, start of key data.
  10259. * On out, start of element after key data.
  10260. * @param [in] maxIdx Maximum index of certificate data.
  10261. */
  10262. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10263. word32 maxIdx)
  10264. {
  10265. int ret;
  10266. int length;
  10267. byte* publicKey;
  10268. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10269. if (ret == 0) {
  10270. #ifdef HAVE_OCSP
  10271. ret = CalcHashId(source + *srcIdx, (word32)length,
  10272. cert->subjectKeyHash);
  10273. }
  10274. if (ret == 0) {
  10275. #endif
  10276. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10277. DYNAMIC_TYPE_PUBLIC_KEY);
  10278. if (publicKey == NULL) {
  10279. ret = MEMORY_E;
  10280. }
  10281. else {
  10282. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10283. cert->publicKey = publicKey;
  10284. cert->pubKeyStored = 1;
  10285. cert->pubKeySize = (word32)length;
  10286. *srcIdx += (word32)length;
  10287. }
  10288. }
  10289. return ret;
  10290. }
  10291. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10292. #if !defined(NO_RSA)
  10293. #ifdef WOLFSSL_ASN_TEMPLATE
  10294. /* ASN.1 template for header before RSA key in certificate. */
  10295. static const ASNItem rsaCertKeyASN[] = {
  10296. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10297. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10298. };
  10299. enum {
  10300. RSACERTKEYASN_IDX_STR = 0,
  10301. RSACERTKEYASN_IDX_SEQ
  10302. };
  10303. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10304. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10305. #endif
  10306. /* Store RSA key pointer and length in certificate object.
  10307. *
  10308. * @param [in, out] cert Certificate object.
  10309. * @param [in] source Buffer containing encoded key.
  10310. * @param [in, out] srcIdx On in, start of RSA key data.
  10311. * On out, start of element after RSA key data.
  10312. * @param [in] maxIdx Maximum index of key data.
  10313. * @return 0 on success.
  10314. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10315. * is invalid.
  10316. * @return BUFFER_E when data in buffer is too small.
  10317. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10318. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10319. * non-zero length.
  10320. */
  10321. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10322. word32 maxIdx)
  10323. {
  10324. #ifndef WOLFSSL_ASN_TEMPLATE
  10325. int length;
  10326. int pubLen;
  10327. word32 pubIdx;
  10328. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10329. return ASN_PARSE_E;
  10330. pubIdx = *srcIdx;
  10331. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10332. return ASN_PARSE_E;
  10333. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10334. cert->sigCtx.CertAtt.pubkey_n_start =
  10335. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10336. #endif
  10337. cert->pubKeySize = (word32)pubLen;
  10338. cert->publicKey = source + pubIdx;
  10339. #ifdef WOLFSSL_MAXQ10XX_TLS
  10340. cert->publicKeyIndex = pubIdx;
  10341. #endif
  10342. *srcIdx += (word32)length;
  10343. #ifdef HAVE_OCSP
  10344. return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash);
  10345. #else
  10346. return 0;
  10347. #endif
  10348. #else
  10349. ASNGetData dataASN[rsaCertKeyASN_Length];
  10350. int ret;
  10351. /* No dynamic data. */
  10352. XMEMSET(dataASN, 0, sizeof(dataASN));
  10353. /* Decode the header before the key data. */
  10354. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10355. srcIdx, maxIdx);
  10356. if (ret == 0) {
  10357. /* Store the pointer and length in certificate object starting at
  10358. * SEQUENCE. */
  10359. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10360. &cert->publicKey, &cert->pubKeySize);
  10361. #ifdef WOLFSSL_MAXQ10XX_TLS
  10362. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10363. #endif
  10364. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10365. /* Start of SEQUENCE. */
  10366. cert->sigCtx.CertAtt.pubkey_n_start =
  10367. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10368. #endif
  10369. #ifdef HAVE_OCSP
  10370. /* Calculate the hash of the public key for OCSP. */
  10371. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  10372. cert->subjectKeyHash);
  10373. #endif
  10374. }
  10375. return ret;
  10376. #endif /* WOLFSSL_ASN_TEMPLATE */
  10377. }
  10378. #endif /* !NO_RSA */
  10379. #ifdef HAVE_ECC
  10380. #ifdef WOLFSSL_ASN_TEMPLATE
  10381. /* ASN.1 template for header before ECC key in certificate. */
  10382. static const ASNItem eccCertKeyASN[] = {
  10383. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10384. /* Algo parameters */
  10385. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10386. /* Subject public key */
  10387. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10388. };
  10389. enum {
  10390. ECCCERTKEYASN_IDX_OID = 0,
  10391. ECCCERTKEYASN_IDX_PARAMS,
  10392. ECCCERTKEYASN_IDX_SUBJPUBKEY
  10393. };
  10394. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10395. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10396. #endif /* WOLFSSL_ASN_TEMPLATE */
  10397. /* Store public ECC key in certificate object.
  10398. *
  10399. * Parse parameters and store public key data.
  10400. *
  10401. * @param [in, out] cert Certificate object.
  10402. * @param [in] source Buffer containing encoded key.
  10403. * @param [in, out] srcIdx On in, start of ECC key data.
  10404. * On out, start of element after ECC key data.
  10405. * @param [in] maxIdx Maximum index of key data.
  10406. * @param [in] pubKey Buffer holding encoded public key.
  10407. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10408. * @return 0 on success.
  10409. * @return BAD_FUNC_ARG when pubKey is NULL.
  10410. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10411. * is invalid.
  10412. * @return BUFFER_E when data in buffer is too small.
  10413. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10414. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10415. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10416. * non-zero length.
  10417. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10418. */
  10419. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10420. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10421. {
  10422. #ifndef WOLFSSL_ASN_TEMPLATE
  10423. int ret;
  10424. word32 localIdx;
  10425. byte* publicKey;
  10426. byte tag;
  10427. int length;
  10428. if (pubKey == NULL) {
  10429. return BAD_FUNC_ARG;
  10430. }
  10431. localIdx = *srcIdx;
  10432. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10433. return ASN_PARSE_E;
  10434. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10435. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10436. maxIdx) < 0)
  10437. return ASN_PARSE_E;
  10438. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10439. return ECC_CURVE_OID_E;
  10440. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10441. cert->sigCtx.CertAtt.curve_id = ret;
  10442. #else
  10443. (void)ret;
  10444. #endif
  10445. /* key header */
  10446. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10447. if (ret != 0)
  10448. return ret;
  10449. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10450. cert->sigCtx.CertAtt.pubkey_n_start =
  10451. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10452. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10453. cert->sigCtx.CertAtt.pubkey_e_start +=
  10454. cert->sigCtx.CertAtt.pubkey_n_len;
  10455. cert->sigCtx.CertAtt.pubkey_e_len =
  10456. cert->sigCtx.CertAtt.pubkey_n_len;
  10457. #endif
  10458. #ifdef WOLFSSL_MAXQ10XX_TLS
  10459. cert->publicKeyIndex = *srcIdx + 1;
  10460. #endif
  10461. #ifdef HAVE_OCSP
  10462. ret = CalcHashId(source + *srcIdx, (word32)length,
  10463. cert->subjectKeyHash);
  10464. if (ret != 0)
  10465. return ret;
  10466. #endif
  10467. *srcIdx += (word32)length;
  10468. }
  10469. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10470. if (publicKey == NULL)
  10471. return MEMORY_E;
  10472. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10473. cert->publicKey = publicKey;
  10474. cert->pubKeyStored = 1;
  10475. cert->pubKeySize = pubKeyLen;
  10476. return 0;
  10477. #else
  10478. int ret = 0;
  10479. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10480. byte* publicKey;
  10481. /* Validate parameters. */
  10482. if (pubKey == NULL) {
  10483. ret = BAD_FUNC_ARG;
  10484. }
  10485. /* Clear dynamic data and check OID is a curve. */
  10486. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  10487. if (ret == 0) {
  10488. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  10489. /* Parse ECC public key header. */
  10490. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  10491. source, srcIdx, maxIdx);
  10492. }
  10493. if (ret == 0) {
  10494. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  10495. /* Store curve OID. */
  10496. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  10497. }
  10498. /* Ignore explicit parameters. */
  10499. #ifdef WOLFSSL_MAXQ10XX_TLS
  10500. cert->publicKeyIndex =
  10501. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  10502. + 1;
  10503. #endif
  10504. #ifdef HAVE_OCSP
  10505. /* Calculate the hash of the subject public key for OCSP. */
  10506. ret = CalcHashId(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  10507. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  10508. cert->subjectKeyHash);
  10509. }
  10510. if (ret == 0) {
  10511. #endif
  10512. /* Store public key data length. */
  10513. cert->pubKeySize = pubKeyLen;
  10514. /* Must allocated space for key.
  10515. * Don't memcpy into constant pointer so use temp. */
  10516. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  10517. DYNAMIC_TYPE_PUBLIC_KEY);
  10518. if (publicKey == NULL) {
  10519. ret = MEMORY_E;
  10520. }
  10521. else {
  10522. /* Copy in whole public key and store pointer. */
  10523. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  10524. cert->publicKey = publicKey;
  10525. /* Indicate publicKey needs to be freed. */
  10526. cert->pubKeyStored = 1;
  10527. }
  10528. }
  10529. FREE_ASNGETDATA(dataASN, cert->heap);
  10530. return ret;
  10531. #endif /* WOLFSSL_ASN_TEMPLATE */
  10532. }
  10533. #endif /* HAVE_ECC */
  10534. #if !defined(NO_DSA)
  10535. #ifdef WOLFSSL_ASN_TEMPLATE
  10536. /* ASN.1 template for DSA key in certificate.
  10537. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  10538. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  10539. */
  10540. static const ASNItem dsaCertKeyASN[] = {
  10541. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10542. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10543. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10544. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  10545. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10546. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  10547. };
  10548. /* Number of items in ASN.1 template for DSA key in certificate. */
  10549. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  10550. #endif /* WOLFSSL_ASN_TEMPLATE */
  10551. /* Parse DSA parameters to ensure valid.
  10552. *
  10553. * @param [in] source Buffer containing encoded key.
  10554. * @param [in, out] srcIdx On in, start of DSA key data.
  10555. * On out, start of element after DSA key data.
  10556. * @param [in] maxIdx Maximum index of key data.
  10557. * @param [in] heap Dynamic memory hint.
  10558. * @return 0 on success.
  10559. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10560. * is invalid.
  10561. * @return BUFFER_E when data in buffer is too small.
  10562. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10563. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10564. * non-zero length.
  10565. */
  10566. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  10567. void* heap)
  10568. {
  10569. #ifndef WOLFSSL_ASN_TEMPLATE
  10570. int ret;
  10571. int length;
  10572. (void)heap;
  10573. ret = GetSequence(source, srcIdx, &length, maxIdx);
  10574. if (ret < 0)
  10575. return ret;
  10576. ret = SkipInt(source, srcIdx, maxIdx);
  10577. if (ret != 0)
  10578. return ret;
  10579. ret = SkipInt(source, srcIdx, maxIdx);
  10580. if (ret != 0)
  10581. return ret;
  10582. ret = SkipInt(source, srcIdx, maxIdx);
  10583. if (ret != 0)
  10584. return ret;
  10585. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10586. if (ret != 0)
  10587. return ret;
  10588. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  10589. if (ret != 0)
  10590. return ASN_PARSE_E;
  10591. *srcIdx += (word32)length;
  10592. return 0;
  10593. #else
  10594. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  10595. int ret = 0;
  10596. (void)heap;
  10597. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  10598. if (ret == 0) {
  10599. /* Parse the DSA key data to ensure valid. */
  10600. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  10601. source, srcIdx, maxIdx);
  10602. }
  10603. FREE_ASNGETDATA(dataASN, heap);
  10604. return ret;
  10605. #endif /* WOLFSSL_ASN_TEMPLATE */
  10606. }
  10607. #endif /* !NO_DSA */
  10608. /* Decode the SubjectPublicKeyInfo block in a certificate.
  10609. *
  10610. * Stores the public key in fields of the certificate object.
  10611. * Validates the BER/DER items and does not store in a key object.
  10612. *
  10613. * @param [in, out] cert Decoded certificate oject.
  10614. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  10615. * @param [in, out] inOutIdx On in, start of public key.
  10616. * On out, start of ASN.1 item after public key.
  10617. * @param [in] maxIdx Maximum index of key data.
  10618. * @return 0 on success.
  10619. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10620. * is invalid.
  10621. * @return BUFFER_E when data in buffer is too small.
  10622. */
  10623. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  10624. word32 maxIdx)
  10625. {
  10626. word32 srcIdx = *inOutIdx;
  10627. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10628. int pubLen;
  10629. #endif
  10630. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10631. int pubIdx = (int)srcIdx;
  10632. #endif
  10633. int ret = 0;
  10634. int length;
  10635. /* Validate paramaters. */
  10636. if (source == NULL) {
  10637. return ASN_PARSE_E;
  10638. }
  10639. #ifndef WOLFSSL_ASN_TEMPLATE
  10640. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  10641. #else
  10642. /* Get SEQUENCE and expect all data to be accounted for. */
  10643. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  10644. #endif
  10645. {
  10646. return ASN_PARSE_E;
  10647. }
  10648. #if defined(HAVE_ECC) || !defined(NO_DSA)
  10649. pubLen = (int)srcIdx - pubIdx + length;
  10650. #endif
  10651. maxIdx = srcIdx + (word32)length;
  10652. /* Decode the algorithm identifier for the key. */
  10653. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  10654. return ASN_PARSE_E;
  10655. }
  10656. (void)length;
  10657. /* Parse each type of public key. */
  10658. switch (cert->keyOID) {
  10659. #ifndef NO_RSA
  10660. #ifdef WC_RSA_PSS
  10661. case RSAPSSk:
  10662. if (srcIdx != maxIdx &&
  10663. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10664. word32 seqIdx = srcIdx;
  10665. int seqLen;
  10666. /* Not set when -1. */
  10667. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  10668. int mgf = -1;
  10669. int saltLen = 0;
  10670. /* Defaults for sig algorithm parameters. */
  10671. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  10672. int sigMgf = WC_MGF1SHA1;
  10673. int sigSaltLen = 20;
  10674. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  10675. return ASN_PARSE_E;
  10676. }
  10677. /* Get the pubic key parameters. */
  10678. ret = DecodeRsaPssParams(source + seqIdx,
  10679. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  10680. if (ret != 0) {
  10681. return ASN_PARSE_E;
  10682. }
  10683. /* Get the signature parameters. */
  10684. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  10685. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  10686. if (ret != 0) {
  10687. return ASN_PARSE_E;
  10688. }
  10689. /* Validated signature params match public key params. */
  10690. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  10691. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  10692. return ASN_PARSE_E;
  10693. }
  10694. if (mgf != -1 && mgf != sigMgf) {
  10695. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  10696. return ASN_PARSE_E;
  10697. }
  10698. if (saltLen > sigSaltLen) {
  10699. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  10700. return ASN_PARSE_E;
  10701. }
  10702. srcIdx += (word32)seqLen;
  10703. }
  10704. FALL_THROUGH;
  10705. #endif /* WC_RSA_PSS */
  10706. case RSAk:
  10707. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  10708. break;
  10709. #endif /* NO_RSA */
  10710. #ifdef HAVE_ECC
  10711. case ECDSAk:
  10712. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  10713. (word32)pubLen);
  10714. break;
  10715. #endif /* HAVE_ECC */
  10716. #ifdef HAVE_ED25519
  10717. case ED25519k:
  10718. cert->pkCurveOID = ED25519k;
  10719. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10720. break;
  10721. #endif /* HAVE_ED25519 */
  10722. #ifdef HAVE_ED448
  10723. case ED448k:
  10724. cert->pkCurveOID = ED448k;
  10725. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10726. break;
  10727. #endif /* HAVE_ED448 */
  10728. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  10729. #ifdef HAVE_FALCON
  10730. case FALCON_LEVEL1k:
  10731. cert->pkCurveOID = FALCON_LEVEL1k;
  10732. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10733. break;
  10734. case FALCON_LEVEL5k:
  10735. cert->pkCurveOID = FALCON_LEVEL5k;
  10736. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10737. break;
  10738. #endif /* HAVE_FALCON */
  10739. #ifdef HAVE_DILITHIUM
  10740. case DILITHIUM_LEVEL2k:
  10741. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  10742. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10743. break;
  10744. case DILITHIUM_LEVEL3k:
  10745. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  10746. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10747. break;
  10748. case DILITHIUM_LEVEL5k:
  10749. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  10750. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10751. break;
  10752. #endif /* HAVE_DILITHIUM */
  10753. #ifdef HAVE_SPHINCS
  10754. case SPHINCS_FAST_LEVEL1k:
  10755. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  10756. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10757. break;
  10758. case SPHINCS_FAST_LEVEL3k:
  10759. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  10760. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10761. break;
  10762. case SPHINCS_FAST_LEVEL5k:
  10763. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  10764. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10765. break;
  10766. case SPHINCS_SMALL_LEVEL1k:
  10767. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  10768. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10769. break;
  10770. case SPHINCS_SMALL_LEVEL3k:
  10771. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  10772. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10773. break;
  10774. case SPHINCS_SMALL_LEVEL5k:
  10775. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  10776. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  10777. break;
  10778. #endif /* HAVE_SPHINCS */
  10779. #endif /* HAVE_PQC */
  10780. #ifndef NO_DSA
  10781. case DSAk:
  10782. cert->publicKey = source + pubIdx;
  10783. cert->pubKeySize = (word32)pubLen;
  10784. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  10785. break;
  10786. #endif /* NO_DSA */
  10787. default:
  10788. WOLFSSL_MSG("Unknown or not compiled in key OID");
  10789. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  10790. ret = ASN_UNKNOWN_OID_E;
  10791. }
  10792. /* Return index after public key. */
  10793. *inOutIdx = srcIdx;
  10794. /* Return error code. */
  10795. return ret;
  10796. }
  10797. /* Calculate hash of the id using the SHA-1 or SHA-256.
  10798. *
  10799. * @param [in] data Data to hash.
  10800. * @param [in] len Length of data to hash.
  10801. * @param [out] hash Buffer to hold hash.
  10802. * @return 0 on success.
  10803. * @return MEMORY_E when dynamic memory allocation fails.
  10804. */
  10805. int CalcHashId(const byte* data, word32 len, byte* hash)
  10806. {
  10807. int ret;
  10808. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  10809. ret = wc_Sha256Hash(data, len, hash);
  10810. #elif !defined(NO_SHA)
  10811. ret = wc_ShaHash(data, len, hash);
  10812. #else
  10813. ret = NOT_COMPILED_IN;
  10814. (void)data;
  10815. (void)len;
  10816. (void)hash;
  10817. #endif
  10818. return ret;
  10819. }
  10820. #ifndef NO_CERTS
  10821. /* Get the hash of the id using the SHA-1 or SHA-256.
  10822. *
  10823. * If the id is not the length of the hash, then hash it.
  10824. *
  10825. * @param [in] id Id to get hash for.
  10826. * @param [in] len Length of id in bytes.
  10827. * @param [out] hash Buffer to hold hash.
  10828. * @return 0 on success.
  10829. * @return MEMORY_E when dynamic memory allocation fails.
  10830. */
  10831. static int GetHashId(const byte* id, int length, byte* hash)
  10832. {
  10833. int ret;
  10834. if (length == KEYID_SIZE) {
  10835. XMEMCPY(hash, id, (size_t)length);
  10836. ret = 0;
  10837. }
  10838. else {
  10839. ret = CalcHashId(id, (word32)length, hash);
  10840. }
  10841. return ret;
  10842. }
  10843. #endif /* !NO_CERTS */
  10844. #ifdef WOLFSSL_ASN_TEMPLATE
  10845. /* Id for email address. */
  10846. #define ASN_EMAIL 0x100
  10847. /* Id for domain component. */
  10848. #define ASN_DC 0x102
  10849. /* Id for jurisdiction country. */
  10850. #define ASN_JURIS_C 0x203
  10851. /* Id for jurisdiction state. */
  10852. #define ASN_JURIS_ST 0x202
  10853. /* Set the string for a name component into the subject name. */
  10854. #define SetCertNameSubject(cert, id, val) \
  10855. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  10856. /* Set the string length for a name component into the subject name. */
  10857. #define SetCertNameSubjectLen(cert, id, val) \
  10858. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  10859. /* Set the encoding for a name component into the subject name. */
  10860. #define SetCertNameSubjectEnc(cert, id, val) \
  10861. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  10862. /* Get the string of a name component from the subject name. */
  10863. #define GetCertNameSubjectStr(id) \
  10864. (certNameSubject[(id) - 3].str)
  10865. /* Get the string length of a name component from the subject name. */
  10866. #define GetCertNameSubjectStrLen(id) \
  10867. (certNameSubject[(id) - 3].strLen)
  10868. /* Get the NID of a name component from the subject name. */
  10869. #define GetCertNameSubjectNID(id) \
  10870. (certNameSubject[(id) - 3].nid)
  10871. #define ValidCertNameSubject(id) \
  10872. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  10873. (certNameSubject[(id) - 3].strLen > 0))
  10874. /* Mapping of certificate name component to useful information. */
  10875. typedef struct CertNameData {
  10876. /* Type string of name component. */
  10877. const char* str;
  10878. /* Length of type string of name component. */
  10879. byte strLen;
  10880. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10881. /* Offset of data in subject name component. */
  10882. size_t data;
  10883. /* Offset of length in subject name component. */
  10884. size_t len;
  10885. /* Offset of encoding in subject name component. */
  10886. size_t enc;
  10887. #endif
  10888. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10889. /* NID of type for subject name component. */
  10890. int nid;
  10891. #endif
  10892. } CertNameData;
  10893. /* List of data for common name components. */
  10894. static const CertNameData certNameSubject[] = {
  10895. /* Common Name */
  10896. {
  10897. "/CN=", 4,
  10898. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10899. OFFSETOF(DecodedCert, subjectCN),
  10900. OFFSETOF(DecodedCert, subjectCNLen),
  10901. OFFSETOF(DecodedCert, subjectCNEnc),
  10902. #endif
  10903. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10904. NID_commonName
  10905. #endif
  10906. },
  10907. /* Surname */
  10908. {
  10909. "/SN=", 4,
  10910. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10911. OFFSETOF(DecodedCert, subjectSN),
  10912. OFFSETOF(DecodedCert, subjectSNLen),
  10913. OFFSETOF(DecodedCert, subjectSNEnc),
  10914. #endif
  10915. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10916. NID_surname
  10917. #endif
  10918. },
  10919. /* Serial Number */
  10920. {
  10921. "/serialNumber=", 14,
  10922. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10923. OFFSETOF(DecodedCert, subjectSND),
  10924. OFFSETOF(DecodedCert, subjectSNDLen),
  10925. OFFSETOF(DecodedCert, subjectSNDEnc),
  10926. #endif
  10927. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10928. NID_serialNumber
  10929. #endif
  10930. },
  10931. /* Country Name */
  10932. {
  10933. "/C=", 3,
  10934. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10935. OFFSETOF(DecodedCert, subjectC),
  10936. OFFSETOF(DecodedCert, subjectCLen),
  10937. OFFSETOF(DecodedCert, subjectCEnc),
  10938. #endif
  10939. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10940. NID_countryName
  10941. #endif
  10942. },
  10943. /* Locality Name */
  10944. {
  10945. "/L=", 3,
  10946. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10947. OFFSETOF(DecodedCert, subjectL),
  10948. OFFSETOF(DecodedCert, subjectLLen),
  10949. OFFSETOF(DecodedCert, subjectLEnc),
  10950. #endif
  10951. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10952. NID_localityName
  10953. #endif
  10954. },
  10955. /* State Name */
  10956. {
  10957. "/ST=", 4,
  10958. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10959. OFFSETOF(DecodedCert, subjectST),
  10960. OFFSETOF(DecodedCert, subjectSTLen),
  10961. OFFSETOF(DecodedCert, subjectSTEnc),
  10962. #endif
  10963. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10964. NID_stateOrProvinceName
  10965. #endif
  10966. },
  10967. /* Street Address */
  10968. {
  10969. "/street=", 8,
  10970. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10971. OFFSETOF(DecodedCert, subjectStreet),
  10972. OFFSETOF(DecodedCert, subjectStreetLen),
  10973. OFFSETOF(DecodedCert, subjectStreetEnc),
  10974. #endif
  10975. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10976. NID_streetAddress
  10977. #endif
  10978. },
  10979. /* Organization Name */
  10980. {
  10981. "/O=", 3,
  10982. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10983. OFFSETOF(DecodedCert, subjectO),
  10984. OFFSETOF(DecodedCert, subjectOLen),
  10985. OFFSETOF(DecodedCert, subjectOEnc),
  10986. #endif
  10987. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10988. NID_organizationName
  10989. #endif
  10990. },
  10991. /* Organization Unit Name */
  10992. {
  10993. "/OU=", 4,
  10994. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10995. OFFSETOF(DecodedCert, subjectOU),
  10996. OFFSETOF(DecodedCert, subjectOULen),
  10997. OFFSETOF(DecodedCert, subjectOUEnc),
  10998. #endif
  10999. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11000. NID_organizationalUnitName
  11001. #endif
  11002. },
  11003. /* Title */
  11004. {
  11005. NULL, 0,
  11006. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11007. 0,
  11008. 0,
  11009. 0,
  11010. #endif
  11011. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11012. 0,
  11013. #endif
  11014. },
  11015. /* Undefined */
  11016. {
  11017. NULL, 0,
  11018. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11019. 0,
  11020. 0,
  11021. 0,
  11022. #endif
  11023. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11024. 0,
  11025. #endif
  11026. },
  11027. /* Undefined */
  11028. {
  11029. NULL, 0,
  11030. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11031. 0,
  11032. 0,
  11033. 0,
  11034. #endif
  11035. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11036. 0,
  11037. #endif
  11038. },
  11039. /* Business Category */
  11040. {
  11041. "/businessCategory=", 18,
  11042. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11043. OFFSETOF(DecodedCert, subjectBC),
  11044. OFFSETOF(DecodedCert, subjectBCLen),
  11045. OFFSETOF(DecodedCert, subjectBCEnc),
  11046. #endif
  11047. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11048. NID_businessCategory
  11049. #endif
  11050. },
  11051. /* Undefined */
  11052. {
  11053. NULL, 0,
  11054. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11055. 0,
  11056. 0,
  11057. 0,
  11058. #endif
  11059. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11060. 0,
  11061. #endif
  11062. },
  11063. /* Postal Code */
  11064. {
  11065. "/postalCode=", 12,
  11066. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11067. OFFSETOF(DecodedCert, subjectPC),
  11068. OFFSETOF(DecodedCert, subjectPCLen),
  11069. OFFSETOF(DecodedCert, subjectPCEnc),
  11070. #endif
  11071. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11072. NID_postalCode
  11073. #endif
  11074. },
  11075. /* User Id */
  11076. {
  11077. "/userid=", 8,
  11078. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11079. OFFSETOF(DecodedCert, subjectUID),
  11080. OFFSETOF(DecodedCert, subjectUIDLen),
  11081. OFFSETOF(DecodedCert, subjectUIDEnc),
  11082. #endif
  11083. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11084. NID_userId
  11085. #endif
  11086. },
  11087. #ifdef WOLFSSL_CERT_NAME_ALL
  11088. /* Name, id 41 */
  11089. {
  11090. "/N=", 3,
  11091. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11092. OFFSETOF(DecodedCert, subjectN),
  11093. OFFSETOF(DecodedCert, subjectNLen),
  11094. OFFSETOF(DecodedCert, subjectNEnc),
  11095. #endif
  11096. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11097. NID_name
  11098. #endif
  11099. },
  11100. /* Given Name, id 42 */
  11101. {
  11102. "/GN=", 4,
  11103. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11104. OFFSETOF(DecodedCert, subjectGN),
  11105. OFFSETOF(DecodedCert, subjectGNLen),
  11106. OFFSETOF(DecodedCert, subjectGNEnc),
  11107. #endif
  11108. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11109. NID_givenName
  11110. #endif
  11111. },
  11112. /* initials, id 43 */
  11113. {
  11114. "/initials=", 10,
  11115. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11116. OFFSETOF(DecodedCert, subjectI),
  11117. OFFSETOF(DecodedCert, subjectILen),
  11118. OFFSETOF(DecodedCert, subjectIEnc),
  11119. #endif
  11120. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11121. NID_initials
  11122. #endif
  11123. },
  11124. /* DN Qualifier Name, id 46 */
  11125. {
  11126. "/dnQualifier=", 13,
  11127. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11128. OFFSETOF(DecodedCert, subjectDNQ),
  11129. OFFSETOF(DecodedCert, subjectDNQLen),
  11130. OFFSETOF(DecodedCert, subjectDNQEnc),
  11131. #endif
  11132. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11133. NID_dnQualifier
  11134. #endif
  11135. },
  11136. #endif /* WOLFSSL_CERT_NAME_ALL */
  11137. };
  11138. static const int certNameSubjectSz =
  11139. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11140. /* ASN.1 template for an RDN.
  11141. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11142. */
  11143. static const ASNItem rdnASN[] = {
  11144. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11145. /* AttributeTypeAndValue */
  11146. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11147. /* AttributeType */
  11148. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11149. /* AttributeValue: Choice of tags - rdnChoice. */
  11150. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11151. };
  11152. enum {
  11153. RDNASN_IDX_SET = 0,
  11154. RDNASN_IDX_ATTR_SEQ,
  11155. RDNASN_IDX_ATTR_TYPE,
  11156. RDNASN_IDX_ATTR_VAL
  11157. };
  11158. /* Number of items in ASN.1 template for an RDN. */
  11159. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11160. /* Supported types of encodings (tags) for RDN strings.
  11161. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11162. * (IA5 String not listed in RFC but required for alternative types)
  11163. */
  11164. static const byte rdnChoice[] = {
  11165. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11166. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11167. };
  11168. #endif
  11169. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11170. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11171. * DNS entry
  11172. * return 0 on success
  11173. */
  11174. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11175. {
  11176. int ret = 0;
  11177. int nameSz;
  11178. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11179. char* ip;
  11180. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11181. return BAD_FUNC_ARG;
  11182. }
  11183. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11184. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11185. WOLFSSL_MSG("Unexpected IP size");
  11186. return BAD_FUNC_ARG;
  11187. }
  11188. ip = entry->name;
  11189. /* store IP addresses as a string */
  11190. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11191. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11192. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11193. >= (int)sizeof(tmpName))
  11194. {
  11195. WOLFSSL_MSG("IP buffer overrun");
  11196. return BUFFER_E;
  11197. }
  11198. }
  11199. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11200. int i;
  11201. for (i = 0; i < 8; i++) {
  11202. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11203. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11204. (i < 7) ? ":" : "")
  11205. >= (int)sizeof(tmpName))
  11206. {
  11207. WOLFSSL_MSG("IPv6 buffer overrun");
  11208. return BUFFER_E;
  11209. }
  11210. }
  11211. }
  11212. nameSz = (int)XSTRLEN(tmpName);
  11213. entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
  11214. if (entry->ipString == NULL) {
  11215. ret = MEMORY_E;
  11216. }
  11217. if (ret == 0) {
  11218. XMEMCPY(entry->ipString, tmpName, nameSz);
  11219. entry->ipString[nameSz] = '\0';
  11220. }
  11221. (void)heap;
  11222. return ret;
  11223. }
  11224. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11225. #ifdef WOLFSSL_ASN_TEMPLATE
  11226. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11227. /* Adds a DNS entry to a list of DNS entries
  11228. *
  11229. * @param [in, out] lst Linked list of DNS name entries.
  11230. * @param [in] entry Entry to add to the list
  11231. * @return 0 on success.
  11232. */
  11233. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11234. {
  11235. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11236. entry->next = NULL;
  11237. if (*lst == NULL) {
  11238. /* First on list */
  11239. *lst = entry;
  11240. }
  11241. else {
  11242. DNS_entry* temp = *lst;
  11243. /* Find end */
  11244. for (; (temp->next != NULL); temp = temp->next);
  11245. /* Add to end */
  11246. temp->next = entry;
  11247. }
  11248. #else
  11249. /* Prepend entry to linked list. */
  11250. entry->next = *lst;
  11251. *lst = entry;
  11252. #endif
  11253. return 0;
  11254. }
  11255. /* Allocate a DNS entry and set the fields.
  11256. *
  11257. * @param [in] cert Certificate object.
  11258. * @param [in] str DNS name string.
  11259. * @param [in] strLen Length of DNS name string.
  11260. * @param [in] type Type of DNS name string.
  11261. * @param [in, out] entries Linked list of DNS name entries.
  11262. * @return 0 on success.
  11263. * @return MEMORY_E when dynamic memory allocation fails.
  11264. */
  11265. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11266. int type, DNS_entry** entries)
  11267. {
  11268. DNS_entry* dnsEntry;
  11269. int ret = 0;
  11270. /* Only used for heap. */
  11271. (void)cert;
  11272. /* TODO: consider one malloc. */
  11273. /* Allocate DNS Entry object. */
  11274. dnsEntry = AltNameNew(cert->heap);
  11275. if (dnsEntry == NULL) {
  11276. ret = MEMORY_E;
  11277. }
  11278. if (ret == 0) {
  11279. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11280. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  11281. DYNAMIC_TYPE_ALTNAME);
  11282. if (dnsEntry->name == NULL) {
  11283. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11284. ret = MEMORY_E;
  11285. }
  11286. }
  11287. if (ret == 0) {
  11288. /* Set tag type, name length, name and NUL terminate name. */
  11289. dnsEntry->type = type;
  11290. dnsEntry->len = strLen;
  11291. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  11292. dnsEntry->name[strLen] = '\0';
  11293. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11294. /* store IP addresses as a string */
  11295. if (type == ASN_IP_TYPE) {
  11296. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11297. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11298. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11299. }
  11300. }
  11301. }
  11302. if (ret == 0) {
  11303. #endif
  11304. ret = AddDNSEntryToList(entries, dnsEntry);
  11305. }
  11306. return ret;
  11307. }
  11308. #endif
  11309. /* Set the details of a subject name component into a certificate.
  11310. *
  11311. * @param [in, out] cert Certificate object.
  11312. * @param [in] id Id of component.
  11313. * @param [in] str String for component.
  11314. * @param [in] strLen Length of string.
  11315. * @param [in] tag BER tag representing encoding of string.
  11316. * @return 0 on success, negative values on failure.
  11317. */
  11318. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  11319. byte tag)
  11320. {
  11321. int ret = 0;
  11322. /* Put string and encoding into certificate. */
  11323. if (id == ASN_COMMON_NAME) {
  11324. cert->subjectCN = (char *)str;
  11325. cert->subjectCNLen = (int)strLen;
  11326. cert->subjectCNEnc = (char)tag;
  11327. }
  11328. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11329. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  11330. /* Use table and offsets to put data into appropriate fields. */
  11331. SetCertNameSubject(cert, id, (char*)str);
  11332. SetCertNameSubjectLen(cert, id, strLen);
  11333. SetCertNameSubjectEnc(cert, id, tag);
  11334. }
  11335. #endif
  11336. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11337. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11338. else if (id == ASN_EMAIL) {
  11339. cert->subjectEmail = (char*)str;
  11340. cert->subjectEmailLen = strLen;
  11341. }
  11342. #endif
  11343. #ifdef WOLFSSL_CERT_EXT
  11344. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  11345. else if (id == ASN_JURIS_C) {
  11346. cert->subjectJC = (char*)str;
  11347. cert->subjectJCLen = strLen;
  11348. cert->subjectJCEnc = (char)tag;
  11349. }
  11350. else if (id == ASN_JURIS_ST) {
  11351. cert->subjectJS = (char*)str;
  11352. cert->subjectJSLen = strLen;
  11353. cert->subjectJSEnc = (char)tag;
  11354. }
  11355. #endif
  11356. return ret;
  11357. }
  11358. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  11359. *
  11360. * @param [in, out] cert Certificate object.
  11361. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  11362. * @param [in, out] idx Index int full name to place next component.
  11363. * @param [in, out] nid NID of component type.
  11364. * @param [in] isSubject Whether this data is for a subject name.
  11365. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  11366. * @return 0 on success.
  11367. * @return MEMORY_E when dynamic memory allocation fails.
  11368. * @return ASN_PARSE_E when type not supported.
  11369. */
  11370. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  11371. int isSubject, ASNGetData* dataASN)
  11372. {
  11373. int ret = 0;
  11374. const char* typeStr = NULL;
  11375. byte typeStrLen = 0;
  11376. byte* oid;
  11377. word32 oidSz;
  11378. int id = 0;
  11379. (void)nid;
  11380. /* Get name type OID from data items. */
  11381. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  11382. /* v1 name types */
  11383. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  11384. id = oid[2];
  11385. /* Check range of supported ids in table. */
  11386. if (ValidCertNameSubject(id)) {
  11387. /* Get the type string, length and NID from table. */
  11388. typeStr = GetCertNameSubjectStr(id);
  11389. typeStrLen = GetCertNameSubjectStrLen(id);
  11390. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11391. *nid = GetCertNameSubjectNID(id);
  11392. #endif
  11393. }
  11394. }
  11395. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  11396. /* Set the email id, type string, length and NID. */
  11397. id = ASN_EMAIL;
  11398. typeStr = WOLFSSL_EMAIL_ADDR;
  11399. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11400. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11401. *nid = NID_emailAddress;
  11402. #endif
  11403. }
  11404. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  11405. /* Set the user id, type string, length and NID. */
  11406. id = ASN_USER_ID;
  11407. typeStr = WOLFSSL_USER_ID;
  11408. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  11409. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11410. *nid = NID_userId;
  11411. #endif
  11412. }
  11413. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  11414. /* Set the domain component, type string, length and NID. */
  11415. id = ASN_DC;
  11416. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  11417. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  11418. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11419. *nid = NID_domainComponent;
  11420. #endif
  11421. }
  11422. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  11423. /* Set the favourite drink, type string, length and NID. */
  11424. id = ASN_FAVOURITE_DRINK;
  11425. typeStr = WOLFSSL_FAVOURITE_DRINK;
  11426. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  11427. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11428. *nid = NID_favouriteDrink;
  11429. #endif
  11430. }
  11431. /* Other OIDs that start with the same values. */
  11432. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  11433. WOLFSSL_MSG("Unknown pilot attribute type");
  11434. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  11435. ret = ASN_PARSE_E;
  11436. }
  11437. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  11438. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  11439. /* Set the jurisdiction id. */
  11440. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  11441. /* Set the jurisdiction type string, length and NID if known. */
  11442. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  11443. typeStr = WOLFSSL_JOI_C;
  11444. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  11445. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11446. *nid = NID_jurisdictionCountryName;
  11447. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11448. }
  11449. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  11450. typeStr = WOLFSSL_JOI_ST;
  11451. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  11452. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11453. *nid = NID_jurisdictionStateOrProvinceName;
  11454. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  11455. }
  11456. else {
  11457. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  11458. }
  11459. }
  11460. if ((ret == 0) && (typeStr != NULL)) {
  11461. /* OID type to store for subject name and add to full string. */
  11462. byte* str;
  11463. word32 strLen;
  11464. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  11465. /* Get the string reference and length. */
  11466. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  11467. if (isSubject) {
  11468. /* Store subject field components. */
  11469. ret = SetSubject(cert, id, str, (int)strLen, tag);
  11470. }
  11471. if (ret == 0) {
  11472. /* Check there is space for this in the full name string and
  11473. * terminating NUL character. */
  11474. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  11475. {
  11476. /* Add RDN to full string. */
  11477. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  11478. *idx += typeStrLen;
  11479. XMEMCPY(&full[*idx], str, strLen);
  11480. *idx += strLen;
  11481. }
  11482. else {
  11483. WOLFSSL_MSG("ASN Name too big, skipping");
  11484. }
  11485. }
  11486. }
  11487. return ret;
  11488. }
  11489. #endif /* WOLFSSL_ASN_TEMPLATE */
  11490. /* Get a certificate name into the certificate object.
  11491. *
  11492. * @param [in, out] cert Decoded certificate object.
  11493. * @param [out] full Buffer to hold full name as a string.
  11494. * @param [out] hash Buffer to hold hash of name.
  11495. * @param [in] nameType ISSUER or SUBJECT.
  11496. * @param [in] input Buffer holding certificate name.
  11497. * @param [in, out] inOutIdx On in, start of certificate name.
  11498. * On out, start of ASN.1 item after cert name.
  11499. * @param [in] maxIdx Index of next item after certificate name.
  11500. * @return 0 on success.
  11501. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11502. * is invalid.
  11503. * @return BUFFER_E when data in buffer is too small.
  11504. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11505. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  11506. * @return MEMORY_E when dynamic memory allocation fails.
  11507. */
  11508. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  11509. const byte* input, word32* inOutIdx, word32 maxIdx)
  11510. {
  11511. #ifndef WOLFSSL_ASN_TEMPLATE
  11512. int length; /* length of all distinguished names */
  11513. int dummy;
  11514. int ret;
  11515. word32 idx;
  11516. word32 srcIdx = *inOutIdx;
  11517. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11518. !defined(WOLFCRYPT_ONLY)
  11519. WOLFSSL_X509_NAME* dName = NULL;
  11520. #endif
  11521. WOLFSSL_MSG("Getting Cert Name");
  11522. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  11523. * calculated over the entire DER encoding of the Name field, including
  11524. * the tag and length. */
  11525. if (CalcHashId(input + *inOutIdx, maxIdx - *inOutIdx, hash) != 0)
  11526. return ASN_PARSE_E;
  11527. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11528. !defined(WOLFCRYPT_ONLY)
  11529. dName = wolfSSL_X509_NAME_new();
  11530. if (dName == NULL) {
  11531. return MEMORY_E;
  11532. }
  11533. #endif /* OPENSSL_EXTRA */
  11534. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  11535. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11536. !defined(WOLFCRYPT_ONLY)
  11537. wolfSSL_X509_NAME_free(dName);
  11538. #endif /* OPENSSL_EXTRA */
  11539. return ASN_PARSE_E;
  11540. }
  11541. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  11542. /* store pointer to raw issuer */
  11543. if (nameType == ISSUER) {
  11544. cert->issuerRaw = &input[srcIdx];
  11545. cert->issuerRawLen = length;
  11546. }
  11547. #endif
  11548. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  11549. if (nameType == SUBJECT) {
  11550. cert->subjectRaw = &input[srcIdx];
  11551. cert->subjectRawLen = length;
  11552. }
  11553. #endif
  11554. length += (int)srcIdx;
  11555. idx = 0;
  11556. while (srcIdx < (word32)length) {
  11557. byte b = 0;
  11558. byte joint[3];
  11559. byte tooBig = FALSE;
  11560. int oidSz;
  11561. const char* copy = NULL;
  11562. int copyLen = 0;
  11563. int strLen = 0;
  11564. byte id = 0;
  11565. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11566. && !defined(WOLFCRYPT_ONLY)
  11567. int nid = NID_undef;
  11568. int enc;
  11569. #endif /* OPENSSL_EXTRA */
  11570. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  11571. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  11572. }
  11573. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  11574. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11575. !defined(WOLFCRYPT_ONLY)
  11576. wolfSSL_X509_NAME_free(dName);
  11577. #endif /* OPENSSL_EXTRA */
  11578. return ASN_PARSE_E;
  11579. }
  11580. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  11581. if (ret != 0) {
  11582. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11583. !defined(WOLFCRYPT_ONLY)
  11584. wolfSSL_X509_NAME_free(dName);
  11585. #endif /* OPENSSL_EXTRA */
  11586. return ret;
  11587. }
  11588. /* make sure there is room for joint */
  11589. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  11590. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11591. !defined(WOLFCRYPT_ONLY)
  11592. wolfSSL_X509_NAME_free(dName);
  11593. #endif /* OPENSSL_EXTRA */
  11594. return ASN_PARSE_E;
  11595. }
  11596. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  11597. /* v1 name types */
  11598. if (joint[0] == 0x55 && joint[1] == 0x04) {
  11599. srcIdx += 3;
  11600. id = joint[2];
  11601. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  11602. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11603. !defined(WOLFCRYPT_ONLY)
  11604. wolfSSL_X509_NAME_free(dName);
  11605. #endif /* OPENSSL_EXTRA */
  11606. return ASN_PARSE_E;
  11607. }
  11608. if (id == ASN_COMMON_NAME) {
  11609. if (nameType == SUBJECT) {
  11610. cert->subjectCN = (char *)&input[srcIdx];
  11611. cert->subjectCNLen = strLen;
  11612. cert->subjectCNEnc = (char)b;
  11613. }
  11614. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  11615. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11616. else if (nameType == ISSUER) {
  11617. cert->issuerCN = (char*)&input[srcIdx];
  11618. cert->issuerCNLen = strLen;
  11619. cert->issuerCNEnc = (char)b;
  11620. }
  11621. #endif
  11622. copy = WOLFSSL_COMMON_NAME;
  11623. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  11624. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11625. && !defined(WOLFCRYPT_ONLY)
  11626. nid = NID_commonName;
  11627. #endif /* OPENSSL_EXTRA */
  11628. }
  11629. #ifdef WOLFSSL_CERT_NAME_ALL
  11630. else if (id == ASN_NAME) {
  11631. copy = WOLFSSL_NAME;
  11632. copyLen = sizeof(WOLFSSL_NAME) - 1;
  11633. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11634. if (nameType == SUBJECT) {
  11635. cert->subjectN = (char*)&input[srcIdx];
  11636. cert->subjectNLen = strLen;
  11637. cert->subjectNEnc = b;
  11638. }
  11639. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11640. #if (defined(OPENSSL_EXTRA) || \
  11641. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11642. && !defined(WOLFCRYPT_ONLY)
  11643. nid = NID_name;
  11644. #endif /* OPENSSL_EXTRA */
  11645. }
  11646. else if (id == ASN_INITIALS) {
  11647. copy = WOLFSSL_INITIALS;
  11648. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  11649. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11650. if (nameType == SUBJECT) {
  11651. cert->subjectI = (char*)&input[srcIdx];
  11652. cert->subjectILen = strLen;
  11653. cert->subjectIEnc = b;
  11654. }
  11655. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11656. #if (defined(OPENSSL_EXTRA) || \
  11657. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11658. && !defined(WOLFCRYPT_ONLY)
  11659. nid = NID_initials;
  11660. #endif /* OPENSSL_EXTRA */
  11661. }
  11662. else if (id == ASN_GIVEN_NAME) {
  11663. copy = WOLFSSL_GIVEN_NAME;
  11664. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  11665. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11666. if (nameType == SUBJECT) {
  11667. cert->subjectGN = (char*)&input[srcIdx];
  11668. cert->subjectGNLen = strLen;
  11669. cert->subjectGNEnc = b;
  11670. }
  11671. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11672. #if (defined(OPENSSL_EXTRA) || \
  11673. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11674. && !defined(WOLFCRYPT_ONLY)
  11675. nid = NID_givenName;
  11676. #endif /* OPENSSL_EXTRA */
  11677. }
  11678. else if (id == ASN_DNQUALIFIER) {
  11679. copy = WOLFSSL_DNQUALIFIER;
  11680. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  11681. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11682. if (nameType == SUBJECT) {
  11683. cert->subjectDNQ = (char*)&input[srcIdx];
  11684. cert->subjectDNQLen = strLen;
  11685. cert->subjectDNQEnc = b;
  11686. }
  11687. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11688. #if (defined(OPENSSL_EXTRA) || \
  11689. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11690. && !defined(WOLFCRYPT_ONLY)
  11691. nid = NID_dnQualifier;
  11692. #endif /* OPENSSL_EXTRA */
  11693. }
  11694. #endif /* WOLFSSL_CERT_NAME_ALL */
  11695. else if (id == ASN_SUR_NAME) {
  11696. copy = WOLFSSL_SUR_NAME;
  11697. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  11698. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11699. if (nameType == SUBJECT) {
  11700. cert->subjectSN = (char*)&input[srcIdx];
  11701. cert->subjectSNLen = strLen;
  11702. cert->subjectSNEnc = (char)b;
  11703. }
  11704. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11705. else if (nameType == ISSUER) {
  11706. cert->issuerSN = (char*)&input[srcIdx];
  11707. cert->issuerSNLen = strLen;
  11708. cert->issuerSNEnc = (char)b;
  11709. }
  11710. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11711. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11712. #if (defined(OPENSSL_EXTRA) || \
  11713. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11714. && !defined(WOLFCRYPT_ONLY)
  11715. nid = NID_surname;
  11716. #endif /* OPENSSL_EXTRA */
  11717. }
  11718. else if (id == ASN_COUNTRY_NAME) {
  11719. copy = WOLFSSL_COUNTRY_NAME;
  11720. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  11721. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11722. if (nameType == SUBJECT) {
  11723. cert->subjectC = (char*)&input[srcIdx];
  11724. cert->subjectCLen = strLen;
  11725. cert->subjectCEnc = (char)b;
  11726. }
  11727. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11728. else if (nameType == ISSUER) {
  11729. cert->issuerC = (char*)&input[srcIdx];
  11730. cert->issuerCLen = strLen;
  11731. cert->issuerCEnc = (char)b;
  11732. }
  11733. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11734. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11735. #if (defined(OPENSSL_EXTRA) || \
  11736. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11737. && !defined(WOLFCRYPT_ONLY)
  11738. nid = NID_countryName;
  11739. #endif /* OPENSSL_EXTRA */
  11740. }
  11741. else if (id == ASN_LOCALITY_NAME) {
  11742. copy = WOLFSSL_LOCALITY_NAME;
  11743. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  11744. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11745. if (nameType == SUBJECT) {
  11746. cert->subjectL = (char*)&input[srcIdx];
  11747. cert->subjectLLen = strLen;
  11748. cert->subjectLEnc = (char)b;
  11749. }
  11750. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11751. else if (nameType == ISSUER) {
  11752. cert->issuerL = (char*)&input[srcIdx];
  11753. cert->issuerLLen = strLen;
  11754. cert->issuerLEnc = (char)b;
  11755. }
  11756. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11757. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11758. #if (defined(OPENSSL_EXTRA) || \
  11759. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11760. && !defined(WOLFCRYPT_ONLY)
  11761. nid = NID_localityName;
  11762. #endif /* OPENSSL_EXTRA */
  11763. }
  11764. else if (id == ASN_STATE_NAME) {
  11765. copy = WOLFSSL_STATE_NAME;
  11766. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  11767. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11768. if (nameType == SUBJECT) {
  11769. cert->subjectST = (char*)&input[srcIdx];
  11770. cert->subjectSTLen = strLen;
  11771. cert->subjectSTEnc = (char)b;
  11772. }
  11773. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11774. else if (nameType == ISSUER) {
  11775. cert->issuerST = (char*)&input[srcIdx];
  11776. cert->issuerSTLen = strLen;
  11777. cert->issuerSTEnc = (char)b;
  11778. }
  11779. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11780. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  11781. #if (defined(OPENSSL_EXTRA) || \
  11782. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11783. && !defined(WOLFCRYPT_ONLY)
  11784. nid = NID_stateOrProvinceName;
  11785. #endif /* OPENSSL_EXTRA */
  11786. }
  11787. else if (id == ASN_ORG_NAME) {
  11788. copy = WOLFSSL_ORG_NAME;
  11789. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  11790. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11791. if (nameType == SUBJECT) {
  11792. cert->subjectO = (char*)&input[srcIdx];
  11793. cert->subjectOLen = strLen;
  11794. cert->subjectOEnc = (char)b;
  11795. }
  11796. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11797. else if (nameType == ISSUER) {
  11798. cert->issuerO = (char*)&input[srcIdx];
  11799. cert->issuerOLen = strLen;
  11800. cert->issuerOEnc = (char)b;
  11801. }
  11802. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11803. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11804. #if (defined(OPENSSL_EXTRA) || \
  11805. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11806. && !defined(WOLFCRYPT_ONLY)
  11807. nid = NID_organizationName;
  11808. #endif /* OPENSSL_EXTRA */
  11809. }
  11810. else if (id == ASN_ORGUNIT_NAME) {
  11811. copy = WOLFSSL_ORGUNIT_NAME;
  11812. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  11813. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11814. if (nameType == SUBJECT) {
  11815. cert->subjectOU = (char*)&input[srcIdx];
  11816. cert->subjectOULen = strLen;
  11817. cert->subjectOUEnc = (char)b;
  11818. }
  11819. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11820. else if (nameType == ISSUER) {
  11821. cert->issuerOU = (char*)&input[srcIdx];
  11822. cert->issuerOULen = strLen;
  11823. cert->issuerOUEnc = (char)b;
  11824. }
  11825. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11826. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11827. #if (defined(OPENSSL_EXTRA) || \
  11828. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11829. && !defined(WOLFCRYPT_ONLY)
  11830. nid = NID_organizationalUnitName;
  11831. #endif /* OPENSSL_EXTRA */
  11832. }
  11833. else if (id == ASN_SERIAL_NUMBER) {
  11834. copy = WOLFSSL_SERIAL_NUMBER;
  11835. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  11836. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11837. if (nameType == SUBJECT) {
  11838. cert->subjectSND = (char*)&input[srcIdx];
  11839. cert->subjectSNDLen = strLen;
  11840. cert->subjectSNDEnc = (char)b;
  11841. }
  11842. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  11843. else if (nameType == ISSUER) {
  11844. cert->issuerSND = (char*)&input[srcIdx];
  11845. cert->issuerSNDLen = strLen;
  11846. cert->issuerSNDEnc = (char)b;
  11847. }
  11848. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  11849. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11850. #if (defined(OPENSSL_EXTRA) || \
  11851. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11852. && !defined(WOLFCRYPT_ONLY)
  11853. nid = NID_serialNumber;
  11854. #endif /* OPENSSL_EXTRA */
  11855. }
  11856. else if (id == ASN_USER_ID) {
  11857. copy = WOLFSSL_USER_ID;
  11858. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  11859. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11860. if (nameType == SUBJECT) {
  11861. cert->subjectUID = (char*)&input[srcIdx];
  11862. cert->subjectUIDLen = strLen;
  11863. cert->subjectUIDEnc = (char)b;
  11864. }
  11865. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11866. #if (defined(OPENSSL_EXTRA) || \
  11867. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11868. && !defined(WOLFCRYPT_ONLY)
  11869. nid = NID_userId;
  11870. #endif /* OPENSSL_EXTRA */
  11871. }
  11872. #ifdef WOLFSSL_CERT_EXT
  11873. else if (id == ASN_STREET_ADDR) {
  11874. copy = WOLFSSL_STREET_ADDR_NAME;
  11875. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  11876. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11877. if (nameType == SUBJECT) {
  11878. cert->subjectStreet = (char*)&input[srcIdx];
  11879. cert->subjectStreetLen = strLen;
  11880. cert->subjectStreetEnc = (char)b;
  11881. }
  11882. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11883. #if (defined(OPENSSL_EXTRA) || \
  11884. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11885. && !defined(WOLFCRYPT_ONLY)
  11886. nid = NID_streetAddress;
  11887. #endif /* OPENSSL_EXTRA */
  11888. }
  11889. else if (id == ASN_BUS_CAT) {
  11890. copy = WOLFSSL_BUS_CAT;
  11891. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  11892. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11893. if (nameType == SUBJECT) {
  11894. cert->subjectBC = (char*)&input[srcIdx];
  11895. cert->subjectBCLen = strLen;
  11896. cert->subjectBCEnc = (char)b;
  11897. }
  11898. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11899. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  11900. && !defined(WOLFCRYPT_ONLY)
  11901. nid = NID_businessCategory;
  11902. #endif /* OPENSSL_EXTRA */
  11903. }
  11904. else if (id == ASN_POSTAL_CODE) {
  11905. copy = WOLFSSL_POSTAL_NAME;
  11906. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  11907. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11908. if (nameType == SUBJECT) {
  11909. cert->subjectPC = (char*)&input[srcIdx];
  11910. cert->subjectPCLen = strLen;
  11911. cert->subjectPCEnc = (char)b;
  11912. }
  11913. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  11914. #if (defined(OPENSSL_EXTRA) || \
  11915. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11916. && !defined(WOLFCRYPT_ONLY)
  11917. nid = NID_postalCode;
  11918. #endif /* OPENSSL_EXTRA */
  11919. }
  11920. #endif /* WOLFSSL_CERT_EXT */
  11921. }
  11922. #ifdef WOLFSSL_CERT_EXT
  11923. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  11924. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  11925. ASN_JOI_PREFIX_SZ)) &&
  11926. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  11927. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  11928. {
  11929. srcIdx += ASN_JOI_PREFIX_SZ;
  11930. id = input[srcIdx++];
  11931. b = input[srcIdx++]; /* encoding */
  11932. if (GetLength(input, &srcIdx, &strLen,
  11933. maxIdx) < 0) {
  11934. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11935. !defined(WOLFCRYPT_ONLY)
  11936. wolfSSL_X509_NAME_free(dName);
  11937. #endif /* OPENSSL_EXTRA */
  11938. return ASN_PARSE_E;
  11939. }
  11940. /* Check for jurisdiction of incorporation country name */
  11941. if (id == ASN_JOI_C) {
  11942. copy = WOLFSSL_JOI_C;
  11943. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  11944. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11945. if (nameType == SUBJECT) {
  11946. cert->subjectJC = (char*)&input[srcIdx];
  11947. cert->subjectJCLen = strLen;
  11948. cert->subjectJCEnc = (char)b;
  11949. }
  11950. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11951. #if (defined(OPENSSL_EXTRA) || \
  11952. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11953. && !defined(WOLFCRYPT_ONLY)
  11954. nid = NID_jurisdictionCountryName;
  11955. #endif /* OPENSSL_EXTRA */
  11956. }
  11957. /* Check for jurisdiction of incorporation state name */
  11958. else if (id == ASN_JOI_ST) {
  11959. copy = WOLFSSL_JOI_ST;
  11960. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  11961. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11962. if (nameType == SUBJECT) {
  11963. cert->subjectJS = (char*)&input[srcIdx];
  11964. cert->subjectJSLen = strLen;
  11965. cert->subjectJSEnc = (char)b;
  11966. }
  11967. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  11968. #if (defined(OPENSSL_EXTRA) || \
  11969. defined(OPENSSL_EXTRA_X509_SMALL)) \
  11970. && !defined(WOLFCRYPT_ONLY)
  11971. nid = NID_jurisdictionStateOrProvinceName;
  11972. #endif /* OPENSSL_EXTRA */
  11973. }
  11974. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  11975. WOLFSSL_MSG("ASN Name too big, skipping");
  11976. tooBig = TRUE;
  11977. }
  11978. }
  11979. #endif /* WOLFSSL_CERT_EXT */
  11980. else {
  11981. /* skip */
  11982. byte email = FALSE;
  11983. byte pilot = FALSE;
  11984. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  11985. id = ASN_EMAIL_NAME;
  11986. email = TRUE;
  11987. }
  11988. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  11989. /* last value of OID is the type of pilot attribute */
  11990. id = input[srcIdx + (word32)oidSz - 1];
  11991. if (id == 0x01)
  11992. id = ASN_USER_ID;
  11993. pilot = TRUE;
  11994. }
  11995. srcIdx += (word32)oidSz + 1;
  11996. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  11997. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  11998. !defined(WOLFCRYPT_ONLY)
  11999. wolfSSL_X509_NAME_free(dName);
  12000. #endif /* OPENSSL_EXTRA */
  12001. return ASN_PARSE_E;
  12002. }
  12003. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12004. WOLFSSL_MSG("ASN name too big, skipping");
  12005. tooBig = TRUE;
  12006. }
  12007. if (email) {
  12008. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12009. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12010. WOLFSSL_MSG("ASN name too big, skipping");
  12011. tooBig = TRUE;
  12012. }
  12013. else {
  12014. copy = WOLFSSL_EMAIL_ADDR;
  12015. }
  12016. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12017. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12018. if (nameType == SUBJECT) {
  12019. cert->subjectEmail = (char*)&input[srcIdx];
  12020. cert->subjectEmailLen = strLen;
  12021. }
  12022. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12023. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12024. else if (nameType == ISSUER) {
  12025. cert->issuerEmail = (char*)&input[srcIdx];
  12026. cert->issuerEmailLen = strLen;
  12027. }
  12028. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12029. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12030. #if (defined(OPENSSL_EXTRA) || \
  12031. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12032. && !defined(WOLFCRYPT_ONLY)
  12033. nid = NID_emailAddress;
  12034. #endif /* OPENSSL_EXTRA */
  12035. }
  12036. if (pilot) {
  12037. switch (id) {
  12038. case ASN_USER_ID:
  12039. copy = WOLFSSL_USER_ID;
  12040. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12041. #if (defined(OPENSSL_EXTRA) || \
  12042. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12043. && !defined(WOLFCRYPT_ONLY)
  12044. nid = NID_userId;
  12045. #endif /* OPENSSL_EXTRA */
  12046. break;
  12047. case ASN_DOMAIN_COMPONENT:
  12048. copy = WOLFSSL_DOMAIN_COMPONENT;
  12049. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12050. #if (defined(OPENSSL_EXTRA) || \
  12051. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12052. && !defined(WOLFCRYPT_ONLY)
  12053. nid = NID_domainComponent;
  12054. #endif /* OPENSSL_EXTRA */
  12055. break;
  12056. case ASN_FAVOURITE_DRINK:
  12057. copy = WOLFSSL_FAVOURITE_DRINK;
  12058. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12059. #if (defined(OPENSSL_EXTRA) || \
  12060. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12061. && !defined(WOLFCRYPT_ONLY)
  12062. nid = NID_favouriteDrink;
  12063. #endif /* OPENSSL_EXTRA */
  12064. break;
  12065. default:
  12066. WOLFSSL_MSG("Unknown pilot attribute type");
  12067. #if (defined(OPENSSL_EXTRA) || \
  12068. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12069. !defined(WOLFCRYPT_ONLY)
  12070. wolfSSL_X509_NAME_free(dName);
  12071. #endif /* OPENSSL_EXTRA */
  12072. return ASN_PARSE_E;
  12073. }
  12074. }
  12075. }
  12076. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12077. {
  12078. WOLFSSL_MSG("ASN Name too big, skipping");
  12079. tooBig = TRUE;
  12080. }
  12081. if ((copy != NULL) && !tooBig) {
  12082. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  12083. idx += (word32)copyLen;
  12084. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  12085. idx += (word32)strLen;
  12086. }
  12087. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12088. !defined(WOLFCRYPT_ONLY)
  12089. switch (b) {
  12090. case CTC_UTF8:
  12091. enc = MBSTRING_UTF8;
  12092. break;
  12093. case CTC_PRINTABLE:
  12094. enc = V_ASN1_PRINTABLESTRING;
  12095. break;
  12096. default:
  12097. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12098. enc = MBSTRING_UTF8;
  12099. }
  12100. if (nid != NID_undef) {
  12101. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12102. &input[srcIdx], strLen, -1, -1) !=
  12103. WOLFSSL_SUCCESS) {
  12104. wolfSSL_X509_NAME_free(dName);
  12105. return ASN_PARSE_E;
  12106. }
  12107. }
  12108. #endif /* OPENSSL_EXTRA */
  12109. srcIdx += (word32)strLen;
  12110. }
  12111. full[idx++] = 0;
  12112. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12113. !defined(WOLFCRYPT_ONLY)
  12114. if (nameType == ISSUER) {
  12115. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12116. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12117. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12118. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12119. #endif
  12120. cert->issuerName = dName;
  12121. }
  12122. else {
  12123. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12124. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12125. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12126. #endif
  12127. cert->subjectName = dName;
  12128. }
  12129. #endif
  12130. *inOutIdx = srcIdx;
  12131. return 0;
  12132. #else
  12133. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12134. int ret = 0;
  12135. word32 idx = 0;
  12136. int len;
  12137. word32 srcIdx = *inOutIdx;
  12138. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12139. WOLFSSL_X509_NAME* dName = NULL;
  12140. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12141. WOLFSSL_MSG("Getting Cert Name");
  12142. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12143. * calculated over the entire DER encoding of the Name field, including
  12144. * the tag and length. */
  12145. if (CalcHashId(input + srcIdx, maxIdx - srcIdx, hash) != 0) {
  12146. ret = ASN_PARSE_E;
  12147. }
  12148. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12149. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12150. if (ret == 0) {
  12151. /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
  12152. dName = wolfSSL_X509_NAME_new();
  12153. if (dName == NULL) {
  12154. ret = MEMORY_E;
  12155. }
  12156. }
  12157. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12158. if (ret == 0) {
  12159. /* Expecting a SEQUENCE using up all data. */
  12160. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12161. }
  12162. if (ret == 0) {
  12163. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12164. /* Store pointer and length to raw issuer. */
  12165. if (nameType == ISSUER) {
  12166. cert->issuerRaw = &input[srcIdx];
  12167. cert->issuerRawLen = len;
  12168. }
  12169. #endif
  12170. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12171. /* Store pointer and length to raw subject. */
  12172. if (nameType == SUBJECT) {
  12173. cert->subjectRaw = &input[srcIdx];
  12174. cert->subjectRawLen = len;
  12175. }
  12176. #endif
  12177. /* Process all RDNs in name. */
  12178. while ((ret == 0) && (srcIdx < maxIdx)) {
  12179. int nid = 0;
  12180. /* Initialize for data and setup RDN choice. */
  12181. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12182. /* Ignore type OID as too many to store in table. */
  12183. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12184. /* Parse RDN. */
  12185. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12186. &srcIdx, maxIdx);
  12187. if (ret == 0) {
  12188. /* Put RDN data into certificate. */
  12189. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12190. dataASN);
  12191. }
  12192. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12193. /* TODO: push this back up to ssl.c
  12194. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12195. if (ret == 0) {
  12196. int enc;
  12197. byte* str;
  12198. word32 strLen;
  12199. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12200. /* Get string reference. */
  12201. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12202. /* Convert BER tag to a OpenSSL type. */
  12203. switch (tag) {
  12204. case CTC_UTF8:
  12205. enc = MBSTRING_UTF8;
  12206. break;
  12207. case CTC_PRINTABLE:
  12208. enc = V_ASN1_PRINTABLESTRING;
  12209. break;
  12210. default:
  12211. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12212. enc = MBSTRING_UTF8;
  12213. }
  12214. if (nid != 0) {
  12215. /* Add an entry to the X509_NAME. */
  12216. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12217. strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12218. ret = ASN_PARSE_E;
  12219. }
  12220. }
  12221. }
  12222. #endif
  12223. }
  12224. }
  12225. if (ret == 0) {
  12226. /* Terminate string. */
  12227. full[idx] = 0;
  12228. /* Return index into encoding after name. */
  12229. *inOutIdx = srcIdx;
  12230. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12231. /* Store X509_NAME in certificate. */
  12232. if (nameType == ISSUER) {
  12233. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12234. defined(HAVE_LIGHTY)) && \
  12235. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12236. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12237. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12238. #endif
  12239. cert->issuerName = dName;
  12240. }
  12241. else {
  12242. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12243. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12244. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12245. #endif
  12246. cert->subjectName = dName;
  12247. }
  12248. }
  12249. else {
  12250. /* Dispose of unused X509_NAME. */
  12251. wolfSSL_X509_NAME_free(dName);
  12252. #endif
  12253. }
  12254. FREE_ASNGETDATA(dataASN, cert->heap);
  12255. return ret;
  12256. #endif /* WOLFSSL_ASN_TEMPLATE */
  12257. }
  12258. #ifdef WOLFSSL_ASN_TEMPLATE
  12259. /* ASN.1 template for certificate name. */
  12260. static const ASNItem certNameASN[] = {
  12261. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12262. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12263. };
  12264. enum {
  12265. CERTNAMEASN_IDX_OID = 0,
  12266. CERTNAMEASN_IDX_NAME
  12267. };
  12268. /* Number of items in ASN.1 template for certificate name. */
  12269. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12270. #endif
  12271. /* Get a certificate name into the certificate object.
  12272. *
  12273. * Either the issuer or subject name.
  12274. *
  12275. * @param [in, out] cert Decoded certificate object.
  12276. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12277. * @param [in] maxIdx Index of next item after certificate name.
  12278. * @return 0 on success.
  12279. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12280. * is invalid.
  12281. * @return BUFFER_E when data in buffer is too small.
  12282. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12283. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12284. * @return MEMORY_E when dynamic memory allocation fails.
  12285. */
  12286. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12287. {
  12288. #ifndef WOLFSSL_ASN_TEMPLATE
  12289. char* full;
  12290. byte* hash;
  12291. int length;
  12292. word32 localIdx;
  12293. byte tag;
  12294. WOLFSSL_MSG("Getting Name");
  12295. if (nameType == ISSUER) {
  12296. full = cert->issuer;
  12297. hash = cert->issuerHash;
  12298. }
  12299. else {
  12300. full = cert->subject;
  12301. hash = cert->subjectHash;
  12302. }
  12303. if (cert->srcIdx >= (word32)maxIdx) {
  12304. return BUFFER_E;
  12305. }
  12306. localIdx = cert->srcIdx;
  12307. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12308. return ASN_PARSE_E;
  12309. }
  12310. if (tag == ASN_OBJECT_ID) {
  12311. WOLFSSL_MSG("Trying optional prefix...");
  12312. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  12313. return ASN_PARSE_E;
  12314. WOLFSSL_MSG("Got optional prefix");
  12315. }
  12316. localIdx = cert->srcIdx;
  12317. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12318. return ASN_PARSE_E;
  12319. }
  12320. localIdx = cert->srcIdx + 1;
  12321. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  12322. return ASN_PARSE_E;
  12323. }
  12324. length += (int)(localIdx - cert->srcIdx);
  12325. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  12326. cert->srcIdx + (word32)length);
  12327. #else
  12328. ASNGetData dataASN[certNameASN_Length];
  12329. word32 idx = cert->srcIdx;
  12330. int ret = 0;
  12331. WOLFSSL_MSG("Getting Name");
  12332. XMEMSET(dataASN, 0, sizeof(dataASN));
  12333. /* Initialize for data and don't check optional prefix OID. */
  12334. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  12335. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  12336. cert->source, &idx, (word32)maxIdx);
  12337. if (ret == 0) {
  12338. char* full;
  12339. byte* hash;
  12340. /* Store offset of SEQUENCE that is start of name. */
  12341. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  12342. /* Get fields to fill in based on name type. */
  12343. if (nameType == ISSUER) {
  12344. full = cert->issuer;
  12345. hash = cert->issuerHash;
  12346. }
  12347. else {
  12348. full = cert->subject;
  12349. hash = cert->subjectHash;
  12350. }
  12351. /* Parse certificate name. */
  12352. ret = GetCertName(cert, full, hash, nameType, cert->source,
  12353. &cert->srcIdx, idx);
  12354. }
  12355. return ret;
  12356. #endif
  12357. }
  12358. #ifndef NO_ASN_TIME
  12359. /* two byte date/time, add to value */
  12360. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  12361. {
  12362. int i = *idx;
  12363. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12364. date[i+1] > 0x39) {
  12365. return ASN_PARSE_E;
  12366. }
  12367. *value += (int)btoi(date[i++]) * 10;
  12368. *value += (int)btoi(date[i++]);
  12369. *idx = i;
  12370. return 0;
  12371. }
  12372. #ifdef WOLFSSL_LINUXKM
  12373. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  12374. {
  12375. int i = *idx;
  12376. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12377. date[i+1] > 0x39) {
  12378. return ASN_PARSE_E;
  12379. }
  12380. *value += (long)btoi(date[i++]) * 10;
  12381. *value += (long)btoi(date[i++]);
  12382. *idx = i;
  12383. return 0;
  12384. }
  12385. #endif
  12386. int ExtractDate(const unsigned char* date, unsigned char format,
  12387. struct tm* certTime, int* idx)
  12388. {
  12389. XMEMSET(certTime, 0, sizeof(struct tm));
  12390. if (format == ASN_UTC_TIME) {
  12391. if (btoi(date[*idx]) >= 5)
  12392. certTime->tm_year = 1900;
  12393. else
  12394. certTime->tm_year = 2000;
  12395. }
  12396. else { /* format == GENERALIZED_TIME */
  12397. #ifdef WOLFSSL_LINUXKM
  12398. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12399. #else
  12400. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12401. #endif
  12402. certTime->tm_year *= 100;
  12403. }
  12404. #ifdef AVR
  12405. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  12406. /* AVR libc stores these as uint8_t instead of int */
  12407. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  12408. int tm_year = certTime->tm_year - 2000;
  12409. int tm_mon = certTime->tm_mon - 1;
  12410. int tm_mday = certTime->tm_mday;
  12411. int tm_hour = certTime->tm_hour;
  12412. int tm_min = certTime->tm_min;
  12413. int tm_sec = certTime->tm_sec;
  12414. #ifdef WOLFSSL_LINUXKM
  12415. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  12416. #else
  12417. if (GetTime(&tm_year, date, idx) != 0) return 0;
  12418. #endif
  12419. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  12420. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  12421. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  12422. if (GetTime(&tm_min , date, idx) != 0) return 0;
  12423. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  12424. /* Re-populate certTime with computed values */
  12425. certTime->tm_year = tm_year;
  12426. certTime->tm_mon = tm_mon;
  12427. certTime->tm_mday = tm_mday;
  12428. certTime->tm_hour = tm_hour;
  12429. certTime->tm_min = tm_min;
  12430. certTime->tm_sec = tm_sec;
  12431. #else
  12432. /* adjust tm_year, tm_mon */
  12433. #ifdef WOLFSSL_LINUXKM
  12434. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12435. #else
  12436. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12437. #endif
  12438. certTime->tm_year -= 1900;
  12439. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  12440. certTime->tm_mon -= 1;
  12441. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  12442. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  12443. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  12444. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  12445. #endif
  12446. return 1;
  12447. }
  12448. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  12449. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  12450. int GetTimeString(byte* date, int format, char* buf, int len)
  12451. {
  12452. struct tm t;
  12453. int idx = 0;
  12454. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  12455. return 0;
  12456. }
  12457. if (date[idx] != 'Z') {
  12458. WOLFSSL_MSG("UTCtime, not Zulu") ;
  12459. return 0;
  12460. }
  12461. /* place month in buffer */
  12462. buf[0] = '\0';
  12463. switch(t.tm_mon) {
  12464. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  12465. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  12466. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  12467. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  12468. case 4: XSTRNCAT(buf, "May ", 5); break;
  12469. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  12470. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  12471. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  12472. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  12473. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  12474. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  12475. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  12476. default:
  12477. return 0;
  12478. }
  12479. idx = 4; /* use idx now for char buffer */
  12480. if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  12481. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  12482. >= len - idx)
  12483. {
  12484. WOLFSSL_MSG("buffer overrun in GetTimeString");
  12485. return 0;
  12486. }
  12487. return 1;
  12488. }
  12489. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  12490. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  12491. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  12492. /* Set current time string, either UTC or GeneralizedTime.
  12493. * (void*) tm should be a pointer to time_t, output is placed in buf.
  12494. *
  12495. * Return time string length placed in buf on success, negative on error */
  12496. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  12497. {
  12498. byte* data_ptr = buf;
  12499. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  12500. int data_len = 0;
  12501. WOLFSSL_ENTER("GetAsnTimeString");
  12502. if (buf == NULL || len == 0)
  12503. return BAD_FUNC_ARG;
  12504. XMEMSET(uf_time, 0, sizeof(uf_time));
  12505. /* GetFormattedTime returns length with null terminator */
  12506. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  12507. if (data_len <= 0) {
  12508. return ASN_TIME_E;
  12509. }
  12510. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  12511. else if (len < (word32)data_len + 2) {
  12512. return BUFFER_E;
  12513. }
  12514. if (data_len == ASN_UTC_TIME_SIZE-1) {
  12515. /* increment data_len for ASN length byte after adding the data_ptr */
  12516. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  12517. /* -1 below excludes null terminator */
  12518. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  12519. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  12520. data_ptr += ASN_UTC_TIME_SIZE - 1;
  12521. }
  12522. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  12523. /* increment data_len for ASN length byte after adding the data_ptr */
  12524. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  12525. /* -1 below excludes null terminator */
  12526. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  12527. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  12528. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  12529. }
  12530. else {
  12531. WOLFSSL_MSG("Invalid time size returned");
  12532. return ASN_TIME_E;
  12533. }
  12534. /* append null terminator */
  12535. *data_ptr = 0;
  12536. /* return length without null terminator */
  12537. return data_len;
  12538. }
  12539. /* return just the time string as either UTC or Generalized Time*/
  12540. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  12541. {
  12542. struct tm* ts = NULL;
  12543. struct tm* tmpTime = NULL;
  12544. int year, mon, day, hour, mini, sec;
  12545. int ret;
  12546. #if defined(NEED_TMP_TIME)
  12547. struct tm tmpTimeStorage;
  12548. tmpTime = &tmpTimeStorage;
  12549. #endif
  12550. /* Needed in case XGMTIME does not use the tmpTime argument. */
  12551. (void)tmpTime;
  12552. WOLFSSL_ENTER("GetFormattedTime");
  12553. if (buf == NULL || len == 0)
  12554. return BAD_FUNC_ARG;
  12555. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  12556. if (ts == NULL) {
  12557. WOLFSSL_MSG("failed to get time data.");
  12558. return ASN_TIME_E;
  12559. }
  12560. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  12561. * the null terminator. ASN encoded values leave off the terminator. */
  12562. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  12563. /* UTC Time */
  12564. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  12565. year = ts->tm_year;
  12566. }
  12567. else {
  12568. year = ts->tm_year - 100;
  12569. }
  12570. mon = ts->tm_mon + 1;
  12571. day = ts->tm_mday;
  12572. hour = ts->tm_hour;
  12573. mini = ts->tm_min;
  12574. sec = ts->tm_sec;
  12575. #if defined(WOLF_C89)
  12576. if (len < ASN_UTC_TIME_SIZE) {
  12577. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  12578. return BUFFER_E;
  12579. }
  12580. ret = XSPRINTF((char*)buf,
  12581. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  12582. hour, mini, sec);
  12583. #else
  12584. ret = XSNPRINTF((char*)buf, len,
  12585. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  12586. hour, mini, sec);
  12587. #endif
  12588. }
  12589. else {
  12590. /* GeneralizedTime */
  12591. year = ts->tm_year + 1900;
  12592. mon = ts->tm_mon + 1;
  12593. day = ts->tm_mday;
  12594. hour = ts->tm_hour;
  12595. mini = ts->tm_min;
  12596. sec = ts->tm_sec;
  12597. #if defined(WOLF_C89)
  12598. if (len < ASN_GENERALIZED_TIME_SIZE) {
  12599. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  12600. return BUFFER_E;
  12601. }
  12602. ret = XSPRINTF((char*)buf,
  12603. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  12604. hour, mini, sec);
  12605. #else
  12606. ret = XSNPRINTF((char*)buf, len,
  12607. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  12608. hour, mini, sec);
  12609. #endif
  12610. }
  12611. return ret;
  12612. }
  12613. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  12614. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  12615. #if defined(USE_WOLF_VALIDDATE)
  12616. /* to the second */
  12617. int DateGreaterThan(const struct tm* a, const struct tm* b)
  12618. {
  12619. if (a->tm_year > b->tm_year)
  12620. return 1;
  12621. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  12622. return 1;
  12623. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12624. a->tm_mday > b->tm_mday)
  12625. return 1;
  12626. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12627. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  12628. return 1;
  12629. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12630. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  12631. a->tm_min > b->tm_min)
  12632. return 1;
  12633. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  12634. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  12635. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  12636. return 1;
  12637. return 0; /* false */
  12638. }
  12639. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  12640. {
  12641. return DateGreaterThan(b,a);
  12642. }
  12643. /* like atoi but only use first byte */
  12644. /* Make sure before and after dates are valid */
  12645. int wc_ValidateDate(const byte* date, byte format, int dateType)
  12646. {
  12647. time_t ltime;
  12648. struct tm certTime;
  12649. struct tm* localTime;
  12650. struct tm* tmpTime;
  12651. int i = 0;
  12652. int timeDiff = 0;
  12653. int diffHH = 0, diffMM = 0;
  12654. #if defined(NEED_TMP_TIME)
  12655. struct tm tmpTimeStorage;
  12656. tmpTime = &tmpTimeStorage;
  12657. #else
  12658. tmpTime = NULL;
  12659. #endif
  12660. (void)tmpTime;
  12661. ltime = wc_Time(0);
  12662. if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
  12663. /* A negative response here could be due to a 32-bit time_t
  12664. * where the year is 2038 or later. */
  12665. WOLFSSL_MSG("wc_Time failed to return a valid value");
  12666. return 0;
  12667. }
  12668. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  12669. if (dateType == BEFORE) {
  12670. WOLFSSL_MSG("Skewing local time for before date check");
  12671. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  12672. }
  12673. #endif
  12674. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  12675. if (dateType == AFTER) {
  12676. WOLFSSL_MSG("Skewing local time for after date check");
  12677. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  12678. }
  12679. #endif
  12680. if (!ExtractDate(date, format, &certTime, &i)) {
  12681. WOLFSSL_MSG("Error extracting the date");
  12682. return 0;
  12683. }
  12684. if ((date[i] == '+') || (date[i] == '-')) {
  12685. int diffSign;
  12686. WOLFSSL_MSG("Using time differential, not Zulu") ;
  12687. diffSign = date[i++] == '+' ? 1 : -1 ;
  12688. if (GetTime(&diffHH, date, &i) != 0)
  12689. return 0;
  12690. if (GetTime(&diffMM, date, &i) != 0)
  12691. return 0;
  12692. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  12693. } else if (date[i] != 'Z') {
  12694. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  12695. return 0;
  12696. }
  12697. ltime -= (time_t)timeDiff ;
  12698. localTime = XGMTIME(&ltime, tmpTime);
  12699. if (localTime == NULL) {
  12700. WOLFSSL_MSG("XGMTIME failed");
  12701. return 0;
  12702. }
  12703. if (dateType == BEFORE) {
  12704. if (DateLessThan(localTime, &certTime)) {
  12705. WOLFSSL_MSG("Date BEFORE check failed");
  12706. return 0;
  12707. }
  12708. }
  12709. else { /* dateType == AFTER */
  12710. if (DateGreaterThan(localTime, &certTime)) {
  12711. WOLFSSL_MSG("Date AFTER check failed");
  12712. return 0;
  12713. }
  12714. }
  12715. return 1;
  12716. }
  12717. #endif /* USE_WOLF_VALIDDATE */
  12718. int wc_GetTime(void* timePtr, word32 timeSize)
  12719. {
  12720. time_t* ltime = (time_t*)timePtr;
  12721. if (timePtr == NULL) {
  12722. return BAD_FUNC_ARG;
  12723. }
  12724. if ((word32)sizeof(time_t) > timeSize) {
  12725. return BUFFER_E;
  12726. }
  12727. *ltime = wc_Time(0);
  12728. return 0;
  12729. }
  12730. #ifdef TIME_OVERRIDES
  12731. #ifndef HAVE_TIME_T_TYPE
  12732. typedef long time_t;
  12733. #endif
  12734. extern time_t XTIME(time_t* t);
  12735. #endif
  12736. static wc_time_cb timeFunc = NULL;
  12737. int wc_SetTimeCb(wc_time_cb f)
  12738. {
  12739. timeFunc = f;
  12740. return 0;
  12741. }
  12742. time_t wc_Time(time_t* t)
  12743. {
  12744. if (timeFunc != NULL) {
  12745. return timeFunc(t);
  12746. }
  12747. return XTIME(t);
  12748. }
  12749. #endif /* !NO_ASN_TIME */
  12750. #ifdef WOLFSSL_ASN_TEMPLATE
  12751. /* TODO: use a CHOICE instead of two items? */
  12752. /* ASN.1 template for a date - either UTC or Generalized Time. */
  12753. static const ASNItem dateASN[] = {
  12754. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  12755. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  12756. };
  12757. enum {
  12758. DATEASN_IDX_UTC = 0,
  12759. DATEASN_IDX_GT
  12760. };
  12761. /* Number of items in ASN.1 template for a date. */
  12762. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  12763. #endif /* WOLFSSL_ASN_TEMPLATE */
  12764. /* Get date buffer, format and length. Returns 0=success or error */
  12765. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  12766. *
  12767. * @param [in] source Buffer containing encoded date.
  12768. * @param [in, out] idx On in, the index of the date.
  12769. * On out, index after date.
  12770. * @param [out] pDate Pointer into buffer of data bytes.
  12771. * @param [out] pFormat Format of date - BER/DER tag.
  12772. * @param [out] pLength Length of date bytes.
  12773. * @param [in] maxIdx Index of next item after date.
  12774. * @return 0 on success.
  12775. * @return BAD_FUNC_ARG when source or idx is NULL.
  12776. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12777. * is invalid.
  12778. * @return BUFFER_E when data in buffer is too small.
  12779. */
  12780. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  12781. byte* pFormat, int* pLength, word32 maxIdx)
  12782. {
  12783. #ifndef WOLFSSL_ASN_TEMPLATE
  12784. int length;
  12785. byte format;
  12786. if (source == NULL || idx == NULL)
  12787. return BAD_FUNC_ARG;
  12788. /* get ASN format header */
  12789. if (*idx+1 > maxIdx)
  12790. return BUFFER_E;
  12791. format = source[*idx];
  12792. *idx += 1;
  12793. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  12794. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  12795. return ASN_TIME_E;
  12796. }
  12797. /* get length */
  12798. if (GetLength(source, idx, &length, maxIdx) < 0)
  12799. return ASN_PARSE_E;
  12800. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  12801. return ASN_DATE_SZ_E;
  12802. /* return format, date and length */
  12803. if (pFormat)
  12804. *pFormat = format;
  12805. if (pDate)
  12806. *pDate = &source[*idx];
  12807. if (pLength)
  12808. *pLength = length;
  12809. *idx += (word32)length;
  12810. return 0;
  12811. #else
  12812. ASNGetData dataASN[dateASN_Length];
  12813. int ret = 0;
  12814. if ((source == NULL) || (idx == NULL)) {
  12815. ret = BAD_FUNC_ARG;
  12816. }
  12817. if (ret == 0) {
  12818. /* Initialize data. */
  12819. XMEMSET(dataASN, 0, sizeof(dataASN));
  12820. /* Parse date. */
  12821. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  12822. maxIdx);
  12823. }
  12824. if (ret == 0) {
  12825. /* Determine which tag was seen. */
  12826. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  12827. : DATEASN_IDX_GT;
  12828. /* Return data from seen item. */
  12829. if (pFormat != NULL) {
  12830. *pFormat = dataASN[i].tag;
  12831. }
  12832. if (pDate != NULL) {
  12833. *pDate = dataASN[i].data.ref.data;
  12834. }
  12835. if (pLength != NULL) {
  12836. *pLength = (int)dataASN[i].data.ref.length;
  12837. }
  12838. }
  12839. return ret;
  12840. #endif
  12841. }
  12842. #ifndef WOLFSSL_ASN_TEMPLATE
  12843. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  12844. {
  12845. int ret, length;
  12846. const byte *datePtr = NULL;
  12847. byte date[MAX_DATE_SIZE];
  12848. byte format;
  12849. word32 startIdx = 0;
  12850. if (dateType == BEFORE)
  12851. cert->beforeDate = &cert->source[cert->srcIdx];
  12852. else
  12853. cert->afterDate = &cert->source[cert->srcIdx];
  12854. startIdx = cert->srcIdx;
  12855. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  12856. &length, (word32)maxIdx);
  12857. if (ret < 0)
  12858. return ret;
  12859. XMEMSET(date, 0, MAX_DATE_SIZE);
  12860. XMEMCPY(date, datePtr, (size_t)length);
  12861. if (dateType == BEFORE)
  12862. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  12863. else
  12864. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  12865. #ifndef NO_ASN_TIME_CHECK
  12866. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  12867. !XVALIDATE_DATE(date, format, dateType)) {
  12868. if (dateType == BEFORE) {
  12869. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  12870. return ASN_BEFORE_DATE_E;
  12871. }
  12872. else {
  12873. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  12874. return ASN_AFTER_DATE_E;
  12875. }
  12876. }
  12877. #else
  12878. (void)verify;
  12879. #endif
  12880. return 0;
  12881. }
  12882. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  12883. {
  12884. int length;
  12885. int badDate = 0;
  12886. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  12887. return ASN_PARSE_E;
  12888. maxIdx = (int)cert->srcIdx + length;
  12889. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  12890. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  12891. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  12892. return ASN_AFTER_DATE_E;
  12893. if (badDate != 0)
  12894. return badDate;
  12895. return 0;
  12896. }
  12897. #endif /* !WOLFSSL_ASN_TEMPLATE */
  12898. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  12899. byte* format, int* length)
  12900. {
  12901. int ret;
  12902. word32 idx = 0;
  12903. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  12904. return ret;
  12905. }
  12906. #ifndef NO_ASN_TIME
  12907. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  12908. struct tm* timearg)
  12909. {
  12910. int idx = 0;
  12911. (void)length;
  12912. if (!ExtractDate(date, format, timearg, &idx))
  12913. return ASN_TIME_E;
  12914. return 0;
  12915. }
  12916. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  12917. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  12918. {
  12919. int ret = 0;
  12920. const byte* date;
  12921. byte format;
  12922. int length;
  12923. if (cert == NULL)
  12924. return BAD_FUNC_ARG;
  12925. if (before && cert->beforeDateSz > 0) {
  12926. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  12927. &format, &length);
  12928. if (ret == 0)
  12929. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  12930. }
  12931. if (after && cert->afterDateSz > 0) {
  12932. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  12933. &format, &length);
  12934. if (ret == 0)
  12935. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  12936. }
  12937. return ret;
  12938. }
  12939. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  12940. #endif /* !NO_ASN_TIME */
  12941. #ifndef WOLFSSL_ASN_TEMPLATE
  12942. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  12943. {
  12944. int length;
  12945. word32 endSeqIdx;
  12946. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  12947. return ASN_PARSE_E;
  12948. endSeqIdx = cert->srcIdx + (word32)length;
  12949. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  12950. maxIdx) < 0) {
  12951. return ASN_OBJECT_ID_E;
  12952. }
  12953. if (cert->srcIdx != endSeqIdx) {
  12954. #ifdef WC_RSA_PSS
  12955. if (*sigOid == CTC_RSASSAPSS) {
  12956. cert->sigParamsIndex = cert->srcIdx;
  12957. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  12958. }
  12959. else
  12960. #endif
  12961. /* Only allowed a ASN NULL header with zero length. */
  12962. if (endSeqIdx - cert->srcIdx != 2)
  12963. return ASN_PARSE_E;
  12964. else {
  12965. byte tag;
  12966. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  12967. return ASN_PARSE_E;
  12968. if (tag != ASN_TAG_NULL)
  12969. return ASN_PARSE_E;
  12970. }
  12971. }
  12972. cert->srcIdx = endSeqIdx;
  12973. return 0;
  12974. }
  12975. #endif
  12976. #ifdef WOLFSSL_ASN_TEMPLATE
  12977. /* TODO: move code around to not require this. */
  12978. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  12979. int* badDateRet, int stopAtPubKey,
  12980. int stopAfterPubKey);
  12981. #endif
  12982. /* Parse the certificate up to the X.509 public key.
  12983. *
  12984. * If cert data is invalid then badDate get set to error value.
  12985. *
  12986. * @param [in, out] cert Decoded certificate object.
  12987. * @param [in] verify Whether to verify dates.
  12988. * @param [out] badDate Error code when verify dates.
  12989. * @return 0 on success.
  12990. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  12991. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  12992. * @return ASN_DATE_SZ_E when time data is not supported.
  12993. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12994. * is invalid.
  12995. * @return BUFFER_E when data in buffer is too small.
  12996. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12997. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  12998. */
  12999. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  13000. {
  13001. #ifndef WOLFSSL_ASN_TEMPLATE
  13002. int ret;
  13003. if (cert == NULL || badDate == NULL)
  13004. return BAD_FUNC_ARG;
  13005. *badDate = 0;
  13006. if ( (ret = GetCertHeader(cert)) < 0)
  13007. return ret;
  13008. WOLFSSL_MSG("Got Cert Header");
  13009. #ifdef WOLFSSL_CERT_REQ
  13010. if (!cert->isCSR) {
  13011. #endif
  13012. /* Using the sigIndex as the upper bound because that's where the
  13013. * actual certificate data ends. */
  13014. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  13015. return ret;
  13016. WOLFSSL_MSG("Got Algo ID");
  13017. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  13018. return ret;
  13019. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  13020. *badDate = ret;
  13021. #ifdef WOLFSSL_CERT_REQ
  13022. }
  13023. #endif
  13024. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  13025. return ret;
  13026. WOLFSSL_MSG("Got Subject Name");
  13027. return ret;
  13028. #else
  13029. /* Use common decode routine and stop at public key. */
  13030. int ret;
  13031. *badDate = 0;
  13032. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13033. if (ret >= 0) {
  13034. /* Store current index: public key. */
  13035. cert->srcIdx = (word32)ret;
  13036. }
  13037. return ret;
  13038. #endif /* WOLFSSL_ASN_TEMPLATE */
  13039. }
  13040. /* Parse the certificate up to and including X.509 public key.
  13041. *
  13042. * @param [in, out] cert Decoded certificate object.
  13043. * @param [in] verify Whether to verify dates.
  13044. * @return 0 on success.
  13045. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13046. * @return ASN_DATE_SZ_E when time data is not supported.
  13047. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13048. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13049. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13050. * is invalid.
  13051. * @return BUFFER_E when data in buffer is too small.
  13052. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13053. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13054. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13055. */
  13056. int DecodeToKey(DecodedCert* cert, int verify)
  13057. {
  13058. #ifndef WOLFSSL_ASN_TEMPLATE
  13059. int badDate = 0;
  13060. int ret;
  13061. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13062. return ret;
  13063. /* Determine if self signed */
  13064. #ifdef WOLFSSL_CERT_REQ
  13065. if (cert->isCSR)
  13066. cert->selfSigned = 1;
  13067. else
  13068. #endif
  13069. {
  13070. cert->selfSigned = XMEMCMP(cert->issuerHash,
  13071. cert->subjectHash,
  13072. KEYID_SIZE) == 0 ? 1 : 0;
  13073. }
  13074. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13075. if (ret != 0)
  13076. return ret;
  13077. WOLFSSL_MSG("Got Key");
  13078. if (badDate != 0)
  13079. return badDate;
  13080. return ret;
  13081. #else
  13082. int ret;
  13083. int badDate = 0;
  13084. /* Call internal version and stop after public key. */
  13085. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13086. /* Always return date errors. */
  13087. if (ret == 0) {
  13088. ret = badDate;
  13089. }
  13090. return ret;
  13091. #endif /* WOLFSSL_ASN_TEMPLATE */
  13092. }
  13093. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13094. static int GetSignature(DecodedCert* cert)
  13095. {
  13096. int length;
  13097. int ret;
  13098. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13099. NULL);
  13100. if (ret != 0)
  13101. return ret;
  13102. cert->sigLength = (word32)length;
  13103. cert->signature = &cert->source[cert->srcIdx];
  13104. cert->srcIdx += cert->sigLength;
  13105. if (cert->srcIdx != cert->maxIdx)
  13106. return ASN_PARSE_E;
  13107. return 0;
  13108. }
  13109. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13110. #ifndef WOLFSSL_ASN_TEMPLATE
  13111. static word32 SetOctetString8Bit(word32 len, byte* output)
  13112. {
  13113. output[0] = ASN_OCTET_STRING;
  13114. output[1] = (byte)len;
  13115. return 2;
  13116. }
  13117. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13118. {
  13119. word32 idx = SetOctetString8Bit(digSz, output);
  13120. XMEMCPY(&output[idx], digest, digSz);
  13121. return idx + digSz;
  13122. }
  13123. #endif
  13124. /* Encode a length for DER.
  13125. *
  13126. * @param [in] length Value to encode.
  13127. * @param [out] output Buffer to encode into.
  13128. * @return Number of bytes encoded.
  13129. */
  13130. word32 SetLength(word32 length, byte* output)
  13131. {
  13132. /* Start encoding at start of buffer. */
  13133. word32 i = 0;
  13134. if (length < ASN_LONG_LENGTH) {
  13135. /* Only one byte needed to encode. */
  13136. if (output) {
  13137. /* Write out length value. */
  13138. output[i] = (byte)length;
  13139. }
  13140. /* Skip over length. */
  13141. i++;
  13142. }
  13143. else {
  13144. /* Calculate the number of bytes required to encode value. */
  13145. byte j = (byte)BytePrecision(length);
  13146. if (output) {
  13147. /* Encode count byte. */
  13148. output[i] = (byte)(j | ASN_LONG_LENGTH);
  13149. }
  13150. /* Skip over count byte. */
  13151. i++;
  13152. /* Encode value as a big-endian byte array. */
  13153. for (; j > 0; --j) {
  13154. if (output) {
  13155. /* Encode next most-significant byte. */
  13156. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13157. }
  13158. /* Skip over byte. */
  13159. i++;
  13160. }
  13161. }
  13162. /* Return number of bytes in encoded length. */
  13163. return i;
  13164. }
  13165. /* Encode a DER header - type/tag and length.
  13166. *
  13167. * @param [in] tag DER tag of ASN.1 item.
  13168. * @param [in] len Length of data in ASN.1 item.
  13169. * @param [out] output Buffer to encode into.
  13170. * @return Number of bytes encoded.
  13171. */
  13172. static word32 SetHeader(byte tag, word32 len, byte* output)
  13173. {
  13174. if (output) {
  13175. /* Encode tag first. */
  13176. output[0] = tag;
  13177. }
  13178. /* Encode the length. */
  13179. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13180. }
  13181. /* Encode a SEQUENCE header in DER.
  13182. *
  13183. * @param [in] len Length of data in SEQUENCE.
  13184. * @param [out] output Buffer to encode into.
  13185. * @return Number of bytes encoded.
  13186. */
  13187. word32 SetSequence(word32 len, byte* output)
  13188. {
  13189. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13190. }
  13191. /* Encode an OCTET STRING header in DER.
  13192. *
  13193. * @param [in] len Length of data in OCTET STRING.
  13194. * @param [out] output Buffer to encode into.
  13195. * @return Number of bytes encoded.
  13196. */
  13197. word32 SetOctetString(word32 len, byte* output)
  13198. {
  13199. return SetHeader(ASN_OCTET_STRING, len, output);
  13200. }
  13201. /* Encode a SET header in DER.
  13202. *
  13203. * @param [in] len Length of data in SET.
  13204. * @param [out] output Buffer to encode into.
  13205. * @return Number of bytes encoded.
  13206. */
  13207. word32 SetSet(word32 len, byte* output)
  13208. {
  13209. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13210. }
  13211. /* Encode an implicit context specific header in DER.
  13212. *
  13213. * Implicit means that it is constructed only if the included ASN.1 item is.
  13214. *
  13215. * @param [in] tag Tag for the implicit ASN.1 item.
  13216. * @param [in] number Context specific number.
  13217. * @param [in] len Length of data in SET.
  13218. * @param [out] output Buffer to encode into.
  13219. * @return Number of bytes encoded.
  13220. */
  13221. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13222. {
  13223. tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13224. | ASN_CONTEXT_SPECIFIC | number);
  13225. return SetHeader(tag, len, output);
  13226. }
  13227. /* Encode an explicit context specific header in DER.
  13228. *
  13229. * Explicit means that there will be an ASN.1 item underneath.
  13230. *
  13231. * @param [in] number Context specific number.
  13232. * @param [in] len Length of data in SET.
  13233. * @param [out] output Buffer to encode into.
  13234. * @return Number of bytes encoded.
  13235. */
  13236. word32 SetExplicit(byte number, word32 len, byte* output)
  13237. {
  13238. return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
  13239. len, output);
  13240. }
  13241. #if defined(OPENSSL_EXTRA)
  13242. /* Encode an Othername into DER.
  13243. *
  13244. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  13245. * @param [out] output Buffer to encode into. If NULL, don't encode.
  13246. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  13247. */
  13248. word32 SetOthername(void *name, byte *output)
  13249. {
  13250. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  13251. char *nameStr = NULL;
  13252. int nameSz = 0;
  13253. word32 len = 0;
  13254. if ((nm == NULL) || (nm->value == NULL)) {
  13255. WOLFSSL_MSG("otherName value is NULL");
  13256. return WOLFSSL_FAILURE;
  13257. }
  13258. nameStr = nm->value->value.utf8string->data;
  13259. nameSz = nm->value->value.utf8string->length;
  13260. len = nm->type_id->objSz +
  13261. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
  13262. SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
  13263. if (output != NULL) {
  13264. /* otherName OID */
  13265. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  13266. output += nm->type_id->objSz;
  13267. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  13268. output);
  13269. output += SetHeader(CTC_UTF8, nameSz, output);
  13270. XMEMCPY(output, nameStr, nameSz);
  13271. }
  13272. return len;
  13273. }
  13274. #endif /* OPENSSL_EXTRA */
  13275. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  13276. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  13277. {
  13278. #ifdef HAVE_OID_ENCODING
  13279. int ret;
  13280. #endif
  13281. int idx;
  13282. word32 oidSz = 0;
  13283. /* validate key */
  13284. if (key == NULL || key->dp == NULL) {
  13285. return BAD_FUNC_ARG;
  13286. }
  13287. #ifdef HAVE_OID_ENCODING
  13288. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  13289. if (ret != 0) {
  13290. return ret;
  13291. }
  13292. #else
  13293. oidSz = key->dp->oidSz;
  13294. #endif
  13295. idx = SetObjectId((int)oidSz, output);
  13296. /* length only */
  13297. if (output == NULL) {
  13298. return idx + (int)oidSz;
  13299. }
  13300. /* verify output buffer has room */
  13301. if (oidSz > outSz)
  13302. return BUFFER_E;
  13303. #ifdef HAVE_OID_ENCODING
  13304. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  13305. if (ret != 0) {
  13306. return ret;
  13307. }
  13308. #else
  13309. XMEMCPY(output+idx, key->dp->oid, oidSz);
  13310. #endif
  13311. idx += (int)oidSz;
  13312. return idx;
  13313. }
  13314. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  13315. #ifdef HAVE_ECC
  13316. /* Determines whether the signature algorithm is using ECDSA.
  13317. *
  13318. * @param [in] algoOID Signature algorithm identifier.
  13319. * @return 1 when algorithm is using ECDSA.
  13320. * @return 0 otherwise.
  13321. */
  13322. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  13323. {
  13324. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  13325. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  13326. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  13327. return 1;
  13328. }
  13329. return 0;
  13330. }
  13331. #endif
  13332. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  13333. * and post-quantum algorithms.
  13334. *
  13335. * @param [in] algoOID Algorithm OID.
  13336. * @return 1 when is EC signing algorithm.
  13337. * @return 0 otherwise.
  13338. */
  13339. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  13340. {
  13341. (void)algoOID;
  13342. return (0
  13343. #ifdef HAVE_ECC
  13344. || IsSigAlgoECDSA(algoOID)
  13345. #endif
  13346. #ifdef HAVE_ED25519
  13347. || (algoOID == ED25519k)
  13348. #endif
  13349. #ifdef HAVE_CURVE25519
  13350. || (algoOID == X25519k)
  13351. #endif
  13352. #ifdef HAVE_ED448
  13353. || (algoOID == ED448k)
  13354. #endif
  13355. #ifdef HAVE_CURVE448
  13356. || (algoOID == X448k)
  13357. #endif
  13358. #ifdef HAVE_PQC
  13359. #ifdef HAVE_FACON
  13360. || (algoOID == FALCON_LEVEL1k)
  13361. || (algoOID == FALCON_LEVEL5k)
  13362. #endif
  13363. #ifdef HAVE_DILITHIUM
  13364. || (algoOID == DILITHIUM_LEVEL2k)
  13365. || (algoOID == DILITHIUM_LEVEL3k)
  13366. || (algoOID == DILITHIUM_LEVEL5k)
  13367. #endif
  13368. #ifdef HAVE_SPHINCS
  13369. || (algoOID == SPHINCS_FAST_LEVEL1k)
  13370. || (algoOID == SPHINCS_FAST_LEVEL3k)
  13371. || (algoOID == SPHINCS_FAST_LEVEL5k)
  13372. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  13373. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  13374. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  13375. #endif
  13376. #endif /* HAVE_PQC */
  13377. );
  13378. }
  13379. /* Encode an algorithm identifier.
  13380. *
  13381. * [algoOID, type] is unique.
  13382. *
  13383. * @param [in] algoOID Algorithm identifier.
  13384. * @param [out] output Buffer to hold encoding.
  13385. * @param [in] type Type of OID being encoded.
  13386. * @param [in] curveSz Add extra space for curve data.
  13387. * @return Encoded data size on success.
  13388. * @return 0 when dynamic memory allocation fails.
  13389. */
  13390. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  13391. {
  13392. #ifndef WOLFSSL_ASN_TEMPLATE
  13393. word32 tagSz, idSz, seqSz, algoSz = 0;
  13394. const byte* algoName = 0;
  13395. byte ID_Length[1 + MAX_LENGTH_SZ];
  13396. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  13397. word32 length = 0;
  13398. tagSz = (type == oidHashType ||
  13399. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13400. (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
  13401. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13402. if (algoName == NULL) {
  13403. WOLFSSL_MSG("Unknown Algorithm");
  13404. return 0;
  13405. }
  13406. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  13407. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  13408. /* Copy only algo to output for DSA keys */
  13409. if (algoOID == DSAk && output) {
  13410. XMEMCPY(output, ID_Length, idSz);
  13411. XMEMCPY(output + idSz, algoName, algoSz);
  13412. if (tagSz == 2)
  13413. SetASNNull(&output[seqSz + idSz + algoSz]);
  13414. }
  13415. else if (output) {
  13416. XMEMCPY(output, seqArray, seqSz);
  13417. XMEMCPY(output + seqSz, ID_Length, idSz);
  13418. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  13419. if (tagSz == 2)
  13420. SetASNNull(&output[seqSz + idSz + algoSz]);
  13421. }
  13422. if (algoOID == DSAk)
  13423. length = idSz + algoSz + tagSz;
  13424. else
  13425. length = seqSz + idSz + algoSz + tagSz;
  13426. return length;
  13427. #else
  13428. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  13429. int ret = 0;
  13430. const byte* algoName = 0;
  13431. word32 algoSz = 0;
  13432. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  13433. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13434. if (algoName == NULL) {
  13435. WOLFSSL_MSG("Unknown Algorithm");
  13436. }
  13437. else {
  13438. int sz;
  13439. int o = 0;
  13440. /* Set the OID and OID type to encode. */
  13441. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  13442. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  13443. if (!(type == oidHashType ||
  13444. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13445. (type == oidKeyType && algoOID == RSAk))) {
  13446. /* Don't put out NULL DER item. */
  13447. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  13448. }
  13449. if (algoOID == DSAk) {
  13450. /* Don't include SEQUENCE for DSA keys. */
  13451. o = 1;
  13452. }
  13453. else if (curveSz > 0) {
  13454. /* Don't put out NULL DER item. */
  13455. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  13456. /* Include space for extra data of length curveSz.
  13457. * Subtract 1 for sequence and 1 for length encoding. */
  13458. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  13459. (word32)curveSz - 2);
  13460. }
  13461. /* Calculate size of encoding. */
  13462. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  13463. (int)algoIdASN_Length - (int)o, &sz);
  13464. if (ret == 0 && output != NULL) {
  13465. /* Encode into buffer. */
  13466. SetASN_Items(algoIdASN + o, dataASN + o,
  13467. (int)algoIdASN_Length - (int)o, output);
  13468. if (curveSz > 0) {
  13469. /* Return size excluding curve data. */
  13470. sz = (int)(dataASN[o].offset -
  13471. dataASN[ALGOIDASN_IDX_NULL].offset);
  13472. }
  13473. }
  13474. if (ret == 0) {
  13475. /* Return encoded size. */
  13476. ret = sz;
  13477. }
  13478. else {
  13479. /* Unsigned return type so 0 indicates error. */
  13480. ret = 0;
  13481. }
  13482. }
  13483. FREE_ASNSETDATA(dataASN, NULL);
  13484. return (word32)ret;
  13485. #endif /* WOLFSSL_ASN_TEMPLATE */
  13486. }
  13487. #ifdef WOLFSSL_ASN_TEMPLATE
  13488. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  13489. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  13490. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  13491. */
  13492. static const ASNItem digestInfoASN[] = {
  13493. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13494. /* digestAlgorithm */
  13495. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  13496. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  13497. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  13498. /* digest */
  13499. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  13500. };
  13501. enum {
  13502. DIGESTINFOASN_IDX_SEQ = 0,
  13503. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  13504. DIGESTINFOASN_IDX_DIGALGO_OID,
  13505. DIGESTINFOASN_IDX_DIGALGO_NULL,
  13506. DIGESTINFOASN_IDX_DIGEST
  13507. };
  13508. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  13509. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  13510. #endif
  13511. /* Encode signature.
  13512. *
  13513. * @param [out] out Buffer to hold encoding.
  13514. * @param [in] digest Buffer holding digest.
  13515. * @param [in] digSz Length of digest in bytes.
  13516. * @return Encoded data size on success.
  13517. * @return 0 when dynamic memory allocation fails.
  13518. */
  13519. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  13520. int hashOID)
  13521. {
  13522. #ifndef WOLFSSL_ASN_TEMPLATE
  13523. byte digArray[MAX_ENCODED_DIG_SZ];
  13524. byte algoArray[MAX_ALGO_SZ];
  13525. byte seqArray[MAX_SEQ_SZ];
  13526. word32 encDigSz, algoSz, seqSz;
  13527. encDigSz = SetDigest(digest, digSz, digArray);
  13528. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  13529. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  13530. XMEMCPY(out, seqArray, seqSz);
  13531. XMEMCPY(out + seqSz, algoArray, algoSz);
  13532. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  13533. return encDigSz + algoSz + seqSz;
  13534. #else
  13535. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  13536. int ret = 0;
  13537. int sz;
  13538. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  13539. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  13540. if (ret == 0) {
  13541. /* Set hash OID and type. */
  13542. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  13543. oidHashType);
  13544. /* Set digest. */
  13545. if (digest == out) {
  13546. XMEMCPY(dgst, digest, digSz);
  13547. digest = dgst;
  13548. }
  13549. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  13550. /* Calculate size of encoding. */
  13551. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  13552. }
  13553. if (ret == 0) {
  13554. /* Encode PKCS#1 v1.5 RSA signature. */
  13555. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  13556. ret = sz;
  13557. }
  13558. else {
  13559. /* Unsigned return type so 0 indicates error. */
  13560. ret = 0;
  13561. }
  13562. FREE_ASNSETDATA(dataASN, NULL);
  13563. return (word32)ret;
  13564. #endif
  13565. }
  13566. #ifndef NO_CERTS
  13567. int wc_GetCTC_HashOID(int type)
  13568. {
  13569. int ret;
  13570. enum wc_HashType hType;
  13571. hType = wc_HashTypeConvert(type);
  13572. ret = wc_HashGetOID(hType);
  13573. if (ret < 0) {
  13574. ret = 0; /* backwards compatibility */
  13575. }
  13576. return ret;
  13577. }
  13578. /* Initialize a signature context object.
  13579. *
  13580. * Object used for signing and verifying a certificate signature.
  13581. *
  13582. * @param [in, out] sigCtx Signature context object.
  13583. * @param [in] heap Dynamic memory hint.
  13584. * @param [in] devId Hardware device identifier.
  13585. */
  13586. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  13587. {
  13588. if (sigCtx) {
  13589. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  13590. sigCtx->devId = devId;
  13591. sigCtx->heap = heap;
  13592. }
  13593. }
  13594. /* Free dynamic data in a signature context object.
  13595. *
  13596. * @param [in, out] sigCtx Signature context object.
  13597. */
  13598. void FreeSignatureCtx(SignatureCtx* sigCtx)
  13599. {
  13600. if (sigCtx == NULL)
  13601. return;
  13602. if (sigCtx->digest) {
  13603. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  13604. sigCtx->digest = NULL;
  13605. }
  13606. #if !(defined(NO_RSA) && defined(NO_DSA))
  13607. if (sigCtx->sigCpy) {
  13608. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  13609. sigCtx->sigCpy = NULL;
  13610. }
  13611. #endif
  13612. #ifndef NO_ASN_CRYPT
  13613. if (sigCtx->key.ptr) {
  13614. switch (sigCtx->keyOID) {
  13615. #ifndef NO_RSA
  13616. #ifdef WC_RSA_PSS
  13617. case RSAPSSk:
  13618. #endif
  13619. case RSAk:
  13620. wc_FreeRsaKey(sigCtx->key.rsa);
  13621. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  13622. sigCtx->key.rsa = NULL;
  13623. break;
  13624. #endif /* !NO_RSA */
  13625. #ifndef NO_DSA
  13626. case DSAk:
  13627. wc_FreeDsaKey(sigCtx->key.dsa);
  13628. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  13629. sigCtx->key.dsa = NULL;
  13630. break;
  13631. #endif
  13632. #ifdef HAVE_ECC
  13633. case ECDSAk:
  13634. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  13635. defined(WC_ASYNC_ENABLE_ECC)
  13636. if (sigCtx->key.ecc->nb_ctx != NULL) {
  13637. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  13638. DYNAMIC_TYPE_TMP_BUFFER);
  13639. }
  13640. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  13641. WC_ASYNC_ENABLE_ECC */
  13642. wc_ecc_free(sigCtx->key.ecc);
  13643. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  13644. sigCtx->key.ecc = NULL;
  13645. break;
  13646. #endif /* HAVE_ECC */
  13647. #ifdef HAVE_ED25519
  13648. case ED25519k:
  13649. wc_ed25519_free(sigCtx->key.ed25519);
  13650. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  13651. sigCtx->key.ed25519 = NULL;
  13652. break;
  13653. #endif /* HAVE_ED25519 */
  13654. #ifdef HAVE_ED448
  13655. case ED448k:
  13656. wc_ed448_free(sigCtx->key.ed448);
  13657. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  13658. sigCtx->key.ed448 = NULL;
  13659. break;
  13660. #endif /* HAVE_ED448 */
  13661. #if defined(HAVE_PQC)
  13662. #if defined(HAVE_FALCON)
  13663. case FALCON_LEVEL1k:
  13664. case FALCON_LEVEL5k:
  13665. wc_falcon_free(sigCtx->key.falcon);
  13666. XFREE(sigCtx->key.falcon, sigCtx->heap,
  13667. DYNAMIC_TYPE_FALCON);
  13668. sigCtx->key.falcon = NULL;
  13669. break;
  13670. #endif /* HAVE_FALCON */
  13671. #if defined(HAVE_DILITHIUM)
  13672. case DILITHIUM_LEVEL2k:
  13673. case DILITHIUM_LEVEL3k:
  13674. case DILITHIUM_LEVEL5k:
  13675. wc_dilithium_free(sigCtx->key.dilithium);
  13676. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  13677. DYNAMIC_TYPE_DILITHIUM);
  13678. sigCtx->key.dilithium = NULL;
  13679. break;
  13680. #endif /* HAVE_DILITHIUM */
  13681. #if defined(HAVE_SPHINCS)
  13682. case SPHINCS_FAST_LEVEL1k:
  13683. case SPHINCS_FAST_LEVEL3k:
  13684. case SPHINCS_FAST_LEVEL5k:
  13685. case SPHINCS_SMALL_LEVEL1k:
  13686. case SPHINCS_SMALL_LEVEL3k:
  13687. case SPHINCS_SMALL_LEVEL5k:
  13688. wc_sphincs_free(sigCtx->key.sphincs);
  13689. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  13690. DYNAMIC_TYPE_SPHINCS);
  13691. sigCtx->key.sphincs = NULL;
  13692. break;
  13693. #endif /* HAVE_SPHINCS */
  13694. #endif /* HAVE_PQC */
  13695. default:
  13696. break;
  13697. } /* switch (keyOID) */
  13698. sigCtx->key.ptr = NULL;
  13699. }
  13700. #endif
  13701. /* reset state, we are done */
  13702. sigCtx->state = SIG_STATE_BEGIN;
  13703. }
  13704. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  13705. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  13706. byte* digest, int* typeH, int* digestSz, int verify)
  13707. {
  13708. int ret = 0;
  13709. switch (sigOID) {
  13710. #if defined(WOLFSSL_MD2)
  13711. case CTC_MD2wRSA:
  13712. if (!verify) {
  13713. ret = HASH_TYPE_E;
  13714. WOLFSSL_MSG("MD2 not supported for signing");
  13715. }
  13716. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  13717. *typeH = MD2h;
  13718. *digestSz = MD2_DIGEST_SIZE;
  13719. }
  13720. break;
  13721. #endif
  13722. #ifndef NO_MD5
  13723. case CTC_MD5wRSA:
  13724. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  13725. *typeH = MD5h;
  13726. *digestSz = WC_MD5_DIGEST_SIZE;
  13727. }
  13728. break;
  13729. #endif
  13730. #ifndef NO_SHA
  13731. case CTC_SHAwRSA:
  13732. case CTC_SHAwDSA:
  13733. case CTC_SHAwECDSA:
  13734. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  13735. *typeH = SHAh;
  13736. *digestSz = WC_SHA_DIGEST_SIZE;
  13737. }
  13738. break;
  13739. #endif
  13740. #ifdef WOLFSSL_SHA224
  13741. case CTC_SHA224wRSA:
  13742. case CTC_SHA224wECDSA:
  13743. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  13744. *typeH = SHA224h;
  13745. *digestSz = WC_SHA224_DIGEST_SIZE;
  13746. }
  13747. break;
  13748. #endif
  13749. #ifndef NO_SHA256
  13750. case CTC_SHA256wRSA:
  13751. case CTC_SHA256wECDSA:
  13752. case CTC_SHA256wDSA:
  13753. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  13754. *typeH = SHA256h;
  13755. *digestSz = WC_SHA256_DIGEST_SIZE;
  13756. }
  13757. break;
  13758. #endif
  13759. #ifdef WOLFSSL_SHA384
  13760. case CTC_SHA384wRSA:
  13761. case CTC_SHA384wECDSA:
  13762. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  13763. *typeH = SHA384h;
  13764. *digestSz = WC_SHA384_DIGEST_SIZE;
  13765. }
  13766. break;
  13767. #endif
  13768. #ifdef WOLFSSL_SHA512
  13769. case CTC_SHA512wRSA:
  13770. case CTC_SHA512wECDSA:
  13771. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  13772. *typeH = SHA512h;
  13773. *digestSz = WC_SHA512_DIGEST_SIZE;
  13774. }
  13775. break;
  13776. #endif
  13777. #ifdef WOLFSSL_SHA3
  13778. #ifndef WOLFSSL_NOSHA3_224
  13779. case CTC_SHA3_224wRSA:
  13780. case CTC_SHA3_224wECDSA:
  13781. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  13782. *typeH = SHA3_224h;
  13783. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  13784. }
  13785. break;
  13786. #endif
  13787. #ifndef WOLFSSL_NOSHA3_256
  13788. case CTC_SHA3_256wRSA:
  13789. case CTC_SHA3_256wECDSA:
  13790. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  13791. *typeH = SHA3_256h;
  13792. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  13793. }
  13794. break;
  13795. #endif
  13796. #ifndef WOLFSSL_NOSHA3_384
  13797. case CTC_SHA3_384wRSA:
  13798. case CTC_SHA3_384wECDSA:
  13799. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  13800. *typeH = SHA3_384h;
  13801. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  13802. }
  13803. break;
  13804. #endif
  13805. #ifndef WOLFSSL_NOSHA3_512
  13806. case CTC_SHA3_512wRSA:
  13807. case CTC_SHA3_512wECDSA:
  13808. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  13809. *typeH = SHA3_512h;
  13810. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  13811. }
  13812. break;
  13813. #endif
  13814. #endif
  13815. #ifdef HAVE_ED25519
  13816. case CTC_ED25519:
  13817. /* Hashes done in signing operation.
  13818. * Two dependent hashes with prefixes performed.
  13819. */
  13820. break;
  13821. #endif
  13822. #ifdef HAVE_ED448
  13823. case CTC_ED448:
  13824. /* Hashes done in signing operation.
  13825. * Two dependent hashes with prefixes performed.
  13826. */
  13827. break;
  13828. #endif
  13829. #ifdef HAVE_PQC
  13830. #ifdef HAVE_FALCON
  13831. case CTC_FALCON_LEVEL1:
  13832. case CTC_FALCON_LEVEL5:
  13833. /* Hashes done in signing operation. */
  13834. break;
  13835. #endif
  13836. #ifdef HAVE_DILITHIUM
  13837. case CTC_DILITHIUM_LEVEL2:
  13838. case CTC_DILITHIUM_LEVEL3:
  13839. case CTC_DILITHIUM_LEVEL5:
  13840. /* Hashes done in signing operation. */
  13841. break;
  13842. #endif
  13843. #ifdef HAVE_SPHINCS
  13844. case CTC_SPHINCS_FAST_LEVEL1:
  13845. case CTC_SPHINCS_FAST_LEVEL3:
  13846. case CTC_SPHINCS_FAST_LEVEL5:
  13847. case CTC_SPHINCS_SMALL_LEVEL1:
  13848. case CTC_SPHINCS_SMALL_LEVEL3:
  13849. case CTC_SPHINCS_SMALL_LEVEL5:
  13850. /* Hashes done in signing operation. */
  13851. break;
  13852. #endif
  13853. #endif /* HAVE_PQC */
  13854. default:
  13855. ret = HASH_TYPE_E;
  13856. WOLFSSL_MSG("Hash for Signature has unsupported type");
  13857. }
  13858. (void)buf;
  13859. (void)bufSz;
  13860. (void)sigOID;
  13861. (void)digest;
  13862. (void)digestSz;
  13863. (void)typeH;
  13864. (void)verify;
  13865. return ret;
  13866. }
  13867. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  13868. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  13869. static int ConfirmSignature(SignatureCtx* sigCtx,
  13870. const byte* buf, word32 bufSz,
  13871. const byte* key, word32 keySz, word32 keyOID,
  13872. const byte* sig, word32 sigSz, word32 sigOID,
  13873. const byte* sigParams, word32 sigParamsSz,
  13874. byte* rsaKeyIdx)
  13875. {
  13876. int ret = 0;
  13877. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  13878. CertAttribute* certatt = NULL;
  13879. #endif
  13880. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  13881. keySz == 0 || sig == NULL || sigSz == 0) {
  13882. return BAD_FUNC_ARG;
  13883. }
  13884. (void)key;
  13885. (void)keySz;
  13886. (void)sig;
  13887. (void)sigSz;
  13888. (void)sigParams;
  13889. (void)sigParamsSz;
  13890. WOLFSSL_ENTER("ConfirmSignature");
  13891. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
  13892. (void)rsaKeyIdx;
  13893. #else
  13894. #if !defined(NO_RSA) || defined(HAVE_ECC)
  13895. certatt = (CertAttribute*)&sigCtx->CertAtt;
  13896. #endif
  13897. if (certatt) {
  13898. certatt->keyIndex = rsaKeyIdx;
  13899. certatt->cert = buf;
  13900. certatt->certSz = bufSz;
  13901. }
  13902. #endif
  13903. #ifndef NO_ASN_CRYPT
  13904. switch (sigCtx->state) {
  13905. case SIG_STATE_BEGIN:
  13906. {
  13907. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  13908. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  13909. DYNAMIC_TYPE_DIGEST);
  13910. if (sigCtx->digest == NULL) {
  13911. ERROR_OUT(MEMORY_E, exit_cs);
  13912. }
  13913. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  13914. /* RSA PSS Defaults */
  13915. sigCtx->hash = WC_HASH_TYPE_SHA;
  13916. sigCtx->mgf = WC_MGF1SHA1;
  13917. sigCtx->saltLen = 20;
  13918. #endif
  13919. sigCtx->state = SIG_STATE_HASH;
  13920. } /* SIG_STATE_BEGIN */
  13921. FALL_THROUGH;
  13922. case SIG_STATE_HASH:
  13923. {
  13924. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  13925. if (sigOID == RSAPSSk) {
  13926. word32 fakeSigOID = 0;
  13927. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  13928. &sigCtx->mgf, &sigCtx->saltLen);
  13929. if (ret != 0) {
  13930. goto exit_cs;
  13931. }
  13932. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  13933. if (ret != 0) {
  13934. goto exit_cs;
  13935. }
  13936. /* Decode parameters. */
  13937. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  13938. &sigCtx->typeH, &sigCtx->digestSz, 1);
  13939. if (ret != 0) {
  13940. goto exit_cs;
  13941. }
  13942. }
  13943. else
  13944. #endif
  13945. {
  13946. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  13947. &sigCtx->typeH, &sigCtx->digestSz, 1);
  13948. if (ret != 0) {
  13949. goto exit_cs;
  13950. }
  13951. }
  13952. sigCtx->state = SIG_STATE_KEY;
  13953. } /* SIG_STATE_HASH */
  13954. FALL_THROUGH;
  13955. case SIG_STATE_KEY:
  13956. {
  13957. switch (keyOID) {
  13958. #ifndef NO_RSA
  13959. #ifdef WC_RSA_PSS
  13960. case RSAPSSk:
  13961. #endif
  13962. case RSAk:
  13963. {
  13964. word32 idx = 0;
  13965. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  13966. sigCtx->heap, DYNAMIC_TYPE_RSA);
  13967. if (sigCtx->key.rsa == NULL) {
  13968. ERROR_OUT(MEMORY_E, exit_cs);
  13969. }
  13970. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  13971. sigCtx->devId)) != 0) {
  13972. goto exit_cs;
  13973. }
  13974. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  13975. DYNAMIC_TYPE_SIGNATURE);
  13976. if (sigCtx->sigCpy == NULL) {
  13977. ERROR_OUT(MEMORY_E, exit_cs);
  13978. }
  13979. if (sigSz > MAX_ENCODED_SIG_SZ) {
  13980. WOLFSSL_MSG("Verify Signature is too big");
  13981. ERROR_OUT(BUFFER_E, exit_cs);
  13982. }
  13983. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  13984. keySz)) != 0) {
  13985. WOLFSSL_MSG("ASN Key decode error RSA");
  13986. WOLFSSL_ERROR_VERBOSE(ret);
  13987. goto exit_cs;
  13988. }
  13989. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  13990. sigCtx->out = NULL;
  13991. #ifdef WOLFSSL_ASYNC_CRYPT
  13992. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  13993. #endif
  13994. break;
  13995. }
  13996. #endif /* !NO_RSA */
  13997. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  13998. case DSAk:
  13999. {
  14000. word32 idx = 0;
  14001. if (sigSz < DSA_MIN_SIG_SIZE) {
  14002. WOLFSSL_MSG("Verify Signature is too small");
  14003. ERROR_OUT(BUFFER_E, exit_cs);
  14004. }
  14005. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  14006. sigCtx->heap, DYNAMIC_TYPE_DSA);
  14007. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  14008. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14009. if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
  14010. ERROR_OUT(MEMORY_E, exit_cs);
  14011. }
  14012. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  14013. WOLFSSL_MSG("wc_InitDsaKey_h error");
  14014. goto exit_cs;
  14015. }
  14016. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  14017. keySz)) != 0) {
  14018. WOLFSSL_MSG("ASN Key decode error DSA");
  14019. WOLFSSL_ERROR_VERBOSE(ret);
  14020. goto exit_cs;
  14021. }
  14022. if (sigSz != DSA_160_SIG_SIZE &&
  14023. sigSz != DSA_256_SIG_SIZE) {
  14024. /* Try to parse it as the contents of a bitstring */
  14025. #ifdef WOLFSSL_SMALL_STACK
  14026. mp_int* r;
  14027. mp_int* s;
  14028. #else
  14029. mp_int r[1];
  14030. mp_int s[1];
  14031. #endif
  14032. int rSz;
  14033. int sSz;
  14034. #ifdef WOLFSSL_SMALL_STACK
  14035. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14036. DYNAMIC_TYPE_TMP_BUFFER);
  14037. if (r == NULL) {
  14038. ERROR_OUT(MEMORY_E, exit_cs);
  14039. }
  14040. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14041. DYNAMIC_TYPE_TMP_BUFFER);
  14042. if (s == NULL) {
  14043. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14044. ERROR_OUT(MEMORY_E, exit_cs);
  14045. }
  14046. #endif
  14047. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  14048. goto exit_cs;
  14049. }
  14050. idx = 0;
  14051. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14052. != 0) {
  14053. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14054. "incorrect format");
  14055. mp_free(r);
  14056. mp_free(s);
  14057. #ifdef WOLFSSL_SMALL_STACK
  14058. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14059. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14060. #endif
  14061. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14062. }
  14063. rSz = mp_unsigned_bin_size(r);
  14064. sSz = mp_unsigned_bin_size(s);
  14065. if (rSz + sSz > (int)sigSz) {
  14066. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14067. "incorrect format");
  14068. mp_free(r);
  14069. mp_free(s);
  14070. #ifdef WOLFSSL_SMALL_STACK
  14071. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14072. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14073. #endif
  14074. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14075. }
  14076. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14077. mp_to_unsigned_bin(s,
  14078. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14079. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14080. "incorrect format");
  14081. mp_free(r);
  14082. mp_free(s);
  14083. #ifdef WOLFSSL_SMALL_STACK
  14084. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14085. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14086. #endif
  14087. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14088. }
  14089. mp_free(r);
  14090. mp_free(s);
  14091. #ifdef WOLFSSL_SMALL_STACK
  14092. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14093. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14094. #endif
  14095. }
  14096. else {
  14097. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14098. }
  14099. break;
  14100. }
  14101. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14102. #ifdef HAVE_ECC
  14103. case ECDSAk:
  14104. {
  14105. word32 idx = 0;
  14106. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14107. defined(WC_ASYNC_ENABLE_ECC)
  14108. ecc_nb_ctx_t* nbCtx;
  14109. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14110. WC_ASYNC_ENABLE_ECC */
  14111. sigCtx->verify = 0;
  14112. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14113. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14114. if (sigCtx->key.ecc == NULL) {
  14115. ERROR_OUT(MEMORY_E, exit_cs);
  14116. }
  14117. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14118. sigCtx->devId)) < 0) {
  14119. goto exit_cs;
  14120. }
  14121. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14122. defined(WC_ASYNC_ENABLE_ECC)
  14123. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14124. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14125. if (nbCtx == NULL) {
  14126. ERROR_OUT(MEMORY_E, exit_cs);
  14127. }
  14128. else {
  14129. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14130. if (ret != 0) {
  14131. goto exit_cs;
  14132. }
  14133. }
  14134. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14135. WC_ASYNC_ENABLE_ECC */
  14136. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14137. keySz);
  14138. if (ret < 0) {
  14139. WOLFSSL_MSG("ASN Key import error ECC");
  14140. WOLFSSL_ERROR_VERBOSE(ret);
  14141. goto exit_cs;
  14142. }
  14143. #ifdef WOLFSSL_ASYNC_CRYPT
  14144. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14145. #endif
  14146. break;
  14147. }
  14148. #endif /* HAVE_ECC */
  14149. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14150. case ED25519k:
  14151. {
  14152. sigCtx->verify = 0;
  14153. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14154. sizeof(ed25519_key), sigCtx->heap,
  14155. DYNAMIC_TYPE_ED25519);
  14156. if (sigCtx->key.ed25519 == NULL) {
  14157. ERROR_OUT(MEMORY_E, exit_cs);
  14158. }
  14159. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14160. sigCtx->heap, sigCtx->devId)) < 0) {
  14161. goto exit_cs;
  14162. }
  14163. if ((ret = wc_ed25519_import_public(key, keySz,
  14164. sigCtx->key.ed25519)) < 0) {
  14165. WOLFSSL_MSG("ASN Key import error ED25519");
  14166. WOLFSSL_ERROR_VERBOSE(ret);
  14167. goto exit_cs;
  14168. }
  14169. #ifdef WOLFSSL_ASYNC_CRYPT
  14170. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14171. #endif
  14172. break;
  14173. }
  14174. #endif
  14175. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14176. case ED448k:
  14177. {
  14178. sigCtx->verify = 0;
  14179. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14180. sizeof(ed448_key), sigCtx->heap,
  14181. DYNAMIC_TYPE_ED448);
  14182. if (sigCtx->key.ed448 == NULL) {
  14183. ERROR_OUT(MEMORY_E, exit_cs);
  14184. }
  14185. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14186. goto exit_cs;
  14187. }
  14188. if ((ret = wc_ed448_import_public(key, keySz,
  14189. sigCtx->key.ed448)) < 0) {
  14190. WOLFSSL_MSG("ASN Key import error ED448");
  14191. WOLFSSL_ERROR_VERBOSE(ret);
  14192. goto exit_cs;
  14193. }
  14194. #ifdef WOLFSSL_ASYNC_CRYPT
  14195. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14196. #endif
  14197. break;
  14198. }
  14199. #endif
  14200. #if defined(HAVE_PQC)
  14201. #if defined(HAVE_FALCON)
  14202. case FALCON_LEVEL1k:
  14203. {
  14204. sigCtx->verify = 0;
  14205. sigCtx->key.falcon =
  14206. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14207. sigCtx->heap,
  14208. DYNAMIC_TYPE_FALCON);
  14209. if (sigCtx->key.falcon == NULL) {
  14210. ERROR_OUT(MEMORY_E, exit_cs);
  14211. }
  14212. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14213. goto exit_cs;
  14214. }
  14215. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14216. < 0) {
  14217. goto exit_cs;
  14218. }
  14219. if ((ret = wc_falcon_import_public(key, keySz,
  14220. sigCtx->key.falcon)) < 0) {
  14221. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14222. WOLFSSL_ERROR_VERBOSE(ret);
  14223. goto exit_cs;
  14224. }
  14225. break;
  14226. }
  14227. case FALCON_LEVEL5k:
  14228. {
  14229. sigCtx->verify = 0;
  14230. sigCtx->key.falcon =
  14231. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14232. sigCtx->heap,
  14233. DYNAMIC_TYPE_FALCON);
  14234. if (sigCtx->key.falcon == NULL) {
  14235. ERROR_OUT(MEMORY_E, exit_cs);
  14236. }
  14237. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14238. goto exit_cs;
  14239. }
  14240. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14241. < 0) {
  14242. goto exit_cs;
  14243. }
  14244. if ((ret = wc_falcon_import_public(key, keySz,
  14245. sigCtx->key.falcon)) < 0) {
  14246. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14247. WOLFSSL_ERROR_VERBOSE(ret);
  14248. goto exit_cs;
  14249. }
  14250. break;
  14251. }
  14252. #endif /* HAVE_FALCON */
  14253. #if defined(HAVE_DILITHIUM)
  14254. case DILITHIUM_LEVEL2k:
  14255. {
  14256. sigCtx->verify = 0;
  14257. sigCtx->key.dilithium =
  14258. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14259. sigCtx->heap,
  14260. DYNAMIC_TYPE_DILITHIUM);
  14261. if (sigCtx->key.dilithium == NULL) {
  14262. ERROR_OUT(MEMORY_E, exit_cs);
  14263. }
  14264. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14265. goto exit_cs;
  14266. }
  14267. if ((ret = wc_dilithium_set_level(
  14268. sigCtx->key.dilithium, 2))
  14269. < 0) {
  14270. goto exit_cs;
  14271. }
  14272. if ((ret = wc_dilithium_import_public(key, keySz,
  14273. sigCtx->key.dilithium)) < 0) {
  14274. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14275. goto exit_cs;
  14276. }
  14277. break;
  14278. }
  14279. case DILITHIUM_LEVEL3k:
  14280. {
  14281. sigCtx->verify = 0;
  14282. sigCtx->key.dilithium =
  14283. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14284. sigCtx->heap,
  14285. DYNAMIC_TYPE_DILITHIUM);
  14286. if (sigCtx->key.dilithium == NULL) {
  14287. ERROR_OUT(MEMORY_E, exit_cs);
  14288. }
  14289. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14290. goto exit_cs;
  14291. }
  14292. if ((ret = wc_dilithium_set_level(
  14293. sigCtx->key.dilithium, 3))
  14294. < 0) {
  14295. goto exit_cs;
  14296. }
  14297. if ((ret = wc_dilithium_import_public(key, keySz,
  14298. sigCtx->key.dilithium)) < 0) {
  14299. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14300. goto exit_cs;
  14301. }
  14302. break;
  14303. }
  14304. case DILITHIUM_LEVEL5k:
  14305. {
  14306. sigCtx->verify = 0;
  14307. sigCtx->key.dilithium =
  14308. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14309. sigCtx->heap,
  14310. DYNAMIC_TYPE_DILITHIUM);
  14311. if (sigCtx->key.dilithium == NULL) {
  14312. ERROR_OUT(MEMORY_E, exit_cs);
  14313. }
  14314. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14315. goto exit_cs;
  14316. }
  14317. if ((ret = wc_dilithium_set_level(
  14318. sigCtx->key.dilithium, 5))
  14319. < 0) {
  14320. goto exit_cs;
  14321. }
  14322. if ((ret = wc_dilithium_import_public(key, keySz,
  14323. sigCtx->key.dilithium)) < 0) {
  14324. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14325. goto exit_cs;
  14326. }
  14327. break;
  14328. }
  14329. #endif /* HAVE_DILITHIUM */
  14330. #if defined(HAVE_SPHINCS)
  14331. case SPHINCS_FAST_LEVEL1k:
  14332. {
  14333. sigCtx->verify = 0;
  14334. sigCtx->key.sphincs =
  14335. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14336. sigCtx->heap,
  14337. DYNAMIC_TYPE_SPHINCS);
  14338. if (sigCtx->key.sphincs == NULL) {
  14339. ERROR_OUT(MEMORY_E, exit_cs);
  14340. }
  14341. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14342. goto exit_cs;
  14343. }
  14344. if ((ret = wc_sphincs_set_level_and_optim(
  14345. sigCtx->key.sphincs, 1, FAST_VARIANT))
  14346. < 0) {
  14347. goto exit_cs;
  14348. }
  14349. if ((ret = wc_sphincs_import_public(key, keySz,
  14350. sigCtx->key.sphincs)) < 0) {
  14351. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14352. goto exit_cs;
  14353. }
  14354. break;
  14355. }
  14356. case SPHINCS_FAST_LEVEL3k:
  14357. {
  14358. sigCtx->verify = 0;
  14359. sigCtx->key.sphincs =
  14360. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14361. sigCtx->heap,
  14362. DYNAMIC_TYPE_SPHINCS);
  14363. if (sigCtx->key.sphincs == NULL) {
  14364. ERROR_OUT(MEMORY_E, exit_cs);
  14365. }
  14366. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14367. goto exit_cs;
  14368. }
  14369. if ((ret = wc_sphincs_set_level_and_optim(
  14370. sigCtx->key.sphincs, 3, FAST_VARIANT))
  14371. < 0) {
  14372. goto exit_cs;
  14373. }
  14374. if ((ret = wc_sphincs_import_public(key, keySz,
  14375. sigCtx->key.sphincs)) < 0) {
  14376. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14377. goto exit_cs;
  14378. }
  14379. break;
  14380. }
  14381. case SPHINCS_FAST_LEVEL5k:
  14382. {
  14383. sigCtx->verify = 0;
  14384. sigCtx->key.sphincs =
  14385. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14386. sigCtx->heap,
  14387. DYNAMIC_TYPE_SPHINCS);
  14388. if (sigCtx->key.sphincs == NULL) {
  14389. ERROR_OUT(MEMORY_E, exit_cs);
  14390. }
  14391. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14392. goto exit_cs;
  14393. }
  14394. if ((ret = wc_sphincs_set_level_and_optim(
  14395. sigCtx->key.sphincs, 5, FAST_VARIANT))
  14396. < 0) {
  14397. goto exit_cs;
  14398. }
  14399. if ((ret = wc_sphincs_import_public(key, keySz,
  14400. sigCtx->key.sphincs)) < 0) {
  14401. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14402. goto exit_cs;
  14403. }
  14404. break;
  14405. }
  14406. case SPHINCS_SMALL_LEVEL1k:
  14407. {
  14408. sigCtx->verify = 0;
  14409. sigCtx->key.sphincs =
  14410. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14411. sigCtx->heap,
  14412. DYNAMIC_TYPE_SPHINCS);
  14413. if (sigCtx->key.sphincs == NULL) {
  14414. ERROR_OUT(MEMORY_E, exit_cs);
  14415. }
  14416. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14417. goto exit_cs;
  14418. }
  14419. if ((ret = wc_sphincs_set_level_and_optim(
  14420. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  14421. < 0) {
  14422. goto exit_cs;
  14423. }
  14424. if ((ret = wc_sphincs_import_public(key, keySz,
  14425. sigCtx->key.sphincs)) < 0) {
  14426. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14427. goto exit_cs;
  14428. }
  14429. break;
  14430. }
  14431. case SPHINCS_SMALL_LEVEL3k:
  14432. {
  14433. sigCtx->verify = 0;
  14434. sigCtx->key.sphincs =
  14435. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14436. sigCtx->heap,
  14437. DYNAMIC_TYPE_SPHINCS);
  14438. if (sigCtx->key.sphincs == NULL) {
  14439. ERROR_OUT(MEMORY_E, exit_cs);
  14440. }
  14441. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14442. goto exit_cs;
  14443. }
  14444. if ((ret = wc_sphincs_set_level_and_optim(
  14445. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  14446. < 0) {
  14447. goto exit_cs;
  14448. }
  14449. if ((ret = wc_sphincs_import_public(key, keySz,
  14450. sigCtx->key.sphincs)) < 0) {
  14451. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14452. goto exit_cs;
  14453. }
  14454. break;
  14455. }
  14456. case SPHINCS_SMALL_LEVEL5k:
  14457. {
  14458. sigCtx->verify = 0;
  14459. sigCtx->key.sphincs =
  14460. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14461. sigCtx->heap,
  14462. DYNAMIC_TYPE_SPHINCS);
  14463. if (sigCtx->key.sphincs == NULL) {
  14464. ERROR_OUT(MEMORY_E, exit_cs);
  14465. }
  14466. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14467. goto exit_cs;
  14468. }
  14469. if ((ret = wc_sphincs_set_level_and_optim(
  14470. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  14471. < 0) {
  14472. goto exit_cs;
  14473. }
  14474. if ((ret = wc_sphincs_import_public(key, keySz,
  14475. sigCtx->key.sphincs)) < 0) {
  14476. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14477. goto exit_cs;
  14478. }
  14479. break;
  14480. }
  14481. #endif /* HAVE_SPHINCS */
  14482. #endif /* HAVE_PQC */
  14483. default:
  14484. WOLFSSL_MSG("Verify Key type unknown");
  14485. ret = ASN_UNKNOWN_OID_E;
  14486. WOLFSSL_ERROR_VERBOSE(ret);
  14487. break;
  14488. } /* switch (keyOID) */
  14489. if (ret != 0) {
  14490. goto exit_cs;
  14491. }
  14492. sigCtx->state = SIG_STATE_DO;
  14493. #ifdef WOLFSSL_ASYNC_CRYPT
  14494. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  14495. /* make sure event is initialized */
  14496. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  14497. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  14498. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  14499. }
  14500. #endif
  14501. } /* SIG_STATE_KEY */
  14502. FALL_THROUGH;
  14503. case SIG_STATE_DO:
  14504. {
  14505. switch (keyOID) {
  14506. #ifndef NO_RSA
  14507. case RSAk:
  14508. #ifdef WC_RSA_PSS
  14509. case RSAPSSk:
  14510. if (sigOID == RSAPSSk) {
  14511. /* TODO: pkCbRsaPss - RSA PSS callback. */
  14512. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  14513. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  14514. sigCtx->saltLen, sigCtx->key.rsa);
  14515. }
  14516. else
  14517. #endif
  14518. {
  14519. #if defined(HAVE_PK_CALLBACKS)
  14520. if (sigCtx->pkCbRsa) {
  14521. ret = sigCtx->pkCbRsa(
  14522. sigCtx->sigCpy, sigSz, &sigCtx->out,
  14523. key, keySz,
  14524. sigCtx->pkCtxRsa);
  14525. }
  14526. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14527. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14528. else
  14529. #else
  14530. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  14531. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14532. #endif /* HAVE_PK_CALLBACKS */
  14533. {
  14534. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  14535. &sigCtx->out, sigCtx->key.rsa);
  14536. }
  14537. }
  14538. break;
  14539. #endif /* !NO_RSA */
  14540. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14541. case DSAk:
  14542. {
  14543. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  14544. sigCtx->key.dsa, &sigCtx->verify);
  14545. break;
  14546. }
  14547. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14548. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  14549. case ECDSAk:
  14550. {
  14551. #if defined(HAVE_PK_CALLBACKS)
  14552. if (sigCtx->pkCbEcc) {
  14553. ret = sigCtx->pkCbEcc(
  14554. sig, sigSz,
  14555. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  14556. key, keySz, &sigCtx->verify,
  14557. sigCtx->pkCtxEcc);
  14558. }
  14559. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  14560. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  14561. else
  14562. #else
  14563. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  14564. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  14565. #endif /* HAVE_PK_CALLBACKS */
  14566. {
  14567. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  14568. (word32)sigCtx->digestSz, &sigCtx->verify,
  14569. sigCtx->key.ecc);
  14570. }
  14571. break;
  14572. }
  14573. #endif /* HAVE_ECC */
  14574. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  14575. case ED25519k:
  14576. {
  14577. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  14578. &sigCtx->verify, sigCtx->key.ed25519);
  14579. break;
  14580. }
  14581. #endif
  14582. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  14583. case ED448k:
  14584. {
  14585. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  14586. &sigCtx->verify, sigCtx->key.ed448,
  14587. NULL, 0);
  14588. break;
  14589. }
  14590. #endif
  14591. #if defined(HAVE_PQC)
  14592. #if defined(HAVE_FALCON)
  14593. case FALCON_LEVEL1k:
  14594. case FALCON_LEVEL5k:
  14595. {
  14596. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  14597. &sigCtx->verify,
  14598. sigCtx->key.falcon);
  14599. break;
  14600. }
  14601. #endif /* HAVE_FALCON */
  14602. #if defined(HAVE_DILITHIUM)
  14603. case DILITHIUM_LEVEL2k:
  14604. case DILITHIUM_LEVEL3k:
  14605. case DILITHIUM_LEVEL5k:
  14606. {
  14607. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  14608. &sigCtx->verify,
  14609. sigCtx->key.dilithium);
  14610. break;
  14611. }
  14612. #endif /* HAVE_DILITHIUM */
  14613. #if defined(HAVE_SPHINCS)
  14614. case SPHINCS_FAST_LEVEL1k:
  14615. case SPHINCS_FAST_LEVEL3k:
  14616. case SPHINCS_FAST_LEVEL5k:
  14617. case SPHINCS_SMALL_LEVEL1k:
  14618. case SPHINCS_SMALL_LEVEL3k:
  14619. case SPHINCS_SMALL_LEVEL5k:
  14620. {
  14621. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  14622. &sigCtx->verify,
  14623. sigCtx->key.sphincs);
  14624. break;
  14625. }
  14626. #endif /* HAVE_SPHINCS */
  14627. #endif /* HAVE_PQC */
  14628. default:
  14629. break;
  14630. } /* switch (keyOID) */
  14631. #ifdef WOLFSSL_ASYNC_CRYPT
  14632. if (ret == WC_PENDING_E) {
  14633. goto exit_cs;
  14634. }
  14635. #endif
  14636. if (ret < 0) {
  14637. /* treat all errors as ASN_SIG_CONFIRM_E */
  14638. ret = ASN_SIG_CONFIRM_E;
  14639. WOLFSSL_ERROR_VERBOSE(ret);
  14640. goto exit_cs;
  14641. }
  14642. sigCtx->state = SIG_STATE_CHECK;
  14643. } /* SIG_STATE_DO */
  14644. FALL_THROUGH;
  14645. case SIG_STATE_CHECK:
  14646. {
  14647. switch (keyOID) {
  14648. #ifndef NO_RSA
  14649. case RSAk:
  14650. #ifdef WC_RSA_PSS
  14651. case RSAPSSk:
  14652. if (sigOID == RSAPSSk) {
  14653. #if (defined(HAVE_SELFTEST) && \
  14654. (!defined(HAVE_SELFTEST_VERSION) || \
  14655. (HAVE_SELFTEST_VERSION < 2))) || \
  14656. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  14657. (HAVE_FIPS_VERSION < 2))
  14658. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  14659. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14660. sigCtx->saltLen);
  14661. #elif (defined(HAVE_SELFTEST) && \
  14662. (HAVE_SELFTEST_VERSION == 2)) || \
  14663. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  14664. (HAVE_FIPS_VERSION == 2))
  14665. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  14666. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  14667. sigCtx->saltLen, 0);
  14668. #else
  14669. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  14670. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  14671. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  14672. sigCtx->heap);
  14673. #endif
  14674. break;
  14675. }
  14676. else
  14677. #endif
  14678. {
  14679. int encodedSigSz, verifySz;
  14680. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  14681. defined(WOLFSSL_RENESAS_SCEPROTECT)
  14682. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  14683. #endif
  14684. #ifdef WOLFSSL_SMALL_STACK
  14685. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  14686. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14687. if (encodedSig == NULL) {
  14688. ERROR_OUT(MEMORY_E, exit_cs);
  14689. }
  14690. #else
  14691. byte encodedSig[MAX_ENCODED_SIG_SZ];
  14692. #endif
  14693. verifySz = ret;
  14694. /* make sure we're right justified */
  14695. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  14696. sigCtx->digest, (word32)sigCtx->digestSz,
  14697. sigCtx->typeH);
  14698. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  14699. XMEMCMP(sigCtx->out, encodedSig,
  14700. (size_t)encodedSigSz) == 0) {
  14701. ret = 0;
  14702. }
  14703. else {
  14704. WOLFSSL_MSG("RSA SSL verify match encode error");
  14705. ret = ASN_SIG_CONFIRM_E;
  14706. WOLFSSL_ERROR_VERBOSE(ret);
  14707. }
  14708. #ifdef WOLFSSL_SMALL_STACK
  14709. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14710. #endif
  14711. break;
  14712. }
  14713. #endif /* NO_RSA */
  14714. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14715. case DSAk:
  14716. {
  14717. if (sigCtx->verify == 1) {
  14718. ret = 0;
  14719. }
  14720. else {
  14721. WOLFSSL_MSG("DSA Verify didn't match");
  14722. ret = ASN_SIG_CONFIRM_E;
  14723. WOLFSSL_ERROR_VERBOSE(ret);
  14724. }
  14725. break;
  14726. }
  14727. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14728. #ifdef HAVE_ECC
  14729. case ECDSAk:
  14730. {
  14731. if (sigCtx->verify == 1) {
  14732. ret = 0;
  14733. }
  14734. else {
  14735. WOLFSSL_MSG("ECC Verify didn't match");
  14736. ret = ASN_SIG_CONFIRM_E;
  14737. WOLFSSL_ERROR_VERBOSE(ret);
  14738. }
  14739. break;
  14740. }
  14741. #endif /* HAVE_ECC */
  14742. #ifdef HAVE_ED25519
  14743. case ED25519k:
  14744. {
  14745. if (sigCtx->verify == 1) {
  14746. ret = 0;
  14747. }
  14748. else {
  14749. WOLFSSL_MSG("ED25519 Verify didn't match");
  14750. ret = ASN_SIG_CONFIRM_E;
  14751. WOLFSSL_ERROR_VERBOSE(ret);
  14752. }
  14753. break;
  14754. }
  14755. #endif /* HAVE_ED25519 */
  14756. #ifdef HAVE_ED448
  14757. case ED448k:
  14758. {
  14759. if (sigCtx->verify == 1) {
  14760. ret = 0;
  14761. }
  14762. else {
  14763. WOLFSSL_MSG("ED448 Verify didn't match");
  14764. ret = ASN_SIG_CONFIRM_E;
  14765. WOLFSSL_ERROR_VERBOSE(ret);
  14766. }
  14767. break;
  14768. }
  14769. #endif /* HAVE_ED448 */
  14770. #ifdef HAVE_PQC
  14771. #ifdef HAVE_FALCON
  14772. case FALCON_LEVEL1k:
  14773. {
  14774. if (sigCtx->verify == 1) {
  14775. ret = 0;
  14776. }
  14777. else {
  14778. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  14779. ret = ASN_SIG_CONFIRM_E;
  14780. WOLFSSL_ERROR_VERBOSE(ret);
  14781. }
  14782. break;
  14783. }
  14784. case FALCON_LEVEL5k:
  14785. {
  14786. if (sigCtx->verify == 1) {
  14787. ret = 0;
  14788. }
  14789. else {
  14790. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  14791. ret = ASN_SIG_CONFIRM_E;
  14792. WOLFSSL_ERROR_VERBOSE(ret);
  14793. }
  14794. break;
  14795. }
  14796. #endif /* HAVE_FALCON */
  14797. #ifdef HAVE_DILITHIUM
  14798. case DILITHIUM_LEVEL2k:
  14799. {
  14800. if (sigCtx->verify == 1) {
  14801. ret = 0;
  14802. }
  14803. else {
  14804. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  14805. ret = ASN_SIG_CONFIRM_E;
  14806. }
  14807. break;
  14808. }
  14809. case DILITHIUM_LEVEL3k:
  14810. {
  14811. if (sigCtx->verify == 1) {
  14812. ret = 0;
  14813. }
  14814. else {
  14815. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  14816. ret = ASN_SIG_CONFIRM_E;
  14817. }
  14818. break;
  14819. }
  14820. case DILITHIUM_LEVEL5k:
  14821. {
  14822. if (sigCtx->verify == 1) {
  14823. ret = 0;
  14824. }
  14825. else {
  14826. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  14827. ret = ASN_SIG_CONFIRM_E;
  14828. }
  14829. break;
  14830. }
  14831. #endif /* HAVE_DILITHIUM */
  14832. #ifdef HAVE_SPHINCS
  14833. case SPHINCS_FAST_LEVEL1k:
  14834. {
  14835. if (sigCtx->verify == 1) {
  14836. ret = 0;
  14837. }
  14838. else {
  14839. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  14840. ret = ASN_SIG_CONFIRM_E;
  14841. }
  14842. break;
  14843. }
  14844. case SPHINCS_FAST_LEVEL3k:
  14845. {
  14846. if (sigCtx->verify == 1) {
  14847. ret = 0;
  14848. }
  14849. else {
  14850. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  14851. ret = ASN_SIG_CONFIRM_E;
  14852. }
  14853. break;
  14854. }
  14855. case SPHINCS_FAST_LEVEL5k:
  14856. {
  14857. if (sigCtx->verify == 1) {
  14858. ret = 0;
  14859. }
  14860. else {
  14861. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  14862. ret = ASN_SIG_CONFIRM_E;
  14863. }
  14864. break;
  14865. }
  14866. case SPHINCS_SMALL_LEVEL1k:
  14867. {
  14868. if (sigCtx->verify == 1) {
  14869. ret = 0;
  14870. }
  14871. else {
  14872. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  14873. ret = ASN_SIG_CONFIRM_E;
  14874. }
  14875. break;
  14876. }
  14877. case SPHINCS_SMALL_LEVEL3k:
  14878. {
  14879. if (sigCtx->verify == 1) {
  14880. ret = 0;
  14881. }
  14882. else {
  14883. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  14884. ret = ASN_SIG_CONFIRM_E;
  14885. }
  14886. break;
  14887. }
  14888. case SPHINCS_SMALL_LEVEL5k:
  14889. {
  14890. if (sigCtx->verify == 1) {
  14891. ret = 0;
  14892. }
  14893. else {
  14894. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  14895. ret = ASN_SIG_CONFIRM_E;
  14896. }
  14897. break;
  14898. }
  14899. #endif /* HAVE_SPHINCS */
  14900. #endif /* HAVE_PQC */
  14901. default:
  14902. break;
  14903. } /* switch (keyOID) */
  14904. break;
  14905. } /* SIG_STATE_CHECK */
  14906. default:
  14907. break;
  14908. } /* switch (sigCtx->state) */
  14909. exit_cs:
  14910. #endif /* !NO_ASN_CRYPT */
  14911. (void)keyOID;
  14912. (void)sigOID;
  14913. WOLFSSL_LEAVE("ConfirmSignature", ret);
  14914. #ifdef WOLFSSL_ASYNC_CRYPT
  14915. if (ret == WC_PENDING_E)
  14916. return ret;
  14917. #endif
  14918. FreeSignatureCtx(sigCtx);
  14919. return ret;
  14920. }
  14921. #ifndef IGNORE_NAME_CONSTRAINTS
  14922. static int MatchBaseName(int type, const char* name, int nameSz,
  14923. const char* base, int baseSz)
  14924. {
  14925. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  14926. name[0] == '.' || nameSz < baseSz ||
  14927. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  14928. type != ASN_DIR_TYPE)) {
  14929. return 0;
  14930. }
  14931. if (type == ASN_DIR_TYPE)
  14932. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  14933. /* If an email type, handle special cases where the base is only
  14934. * a domain, or is an email address itself. */
  14935. if (type == ASN_RFC822_TYPE) {
  14936. const char* p = NULL;
  14937. int count = 0;
  14938. if (base[0] != '.') {
  14939. p = base;
  14940. count = 0;
  14941. /* find the '@' in the base */
  14942. while (*p != '@' && count < baseSz) {
  14943. count++;
  14944. p++;
  14945. }
  14946. /* No '@' in base, reset p to NULL */
  14947. if (count >= baseSz)
  14948. p = NULL;
  14949. }
  14950. if (p == NULL) {
  14951. /* Base isn't an email address, it is a domain name,
  14952. * wind the name forward one character past its '@'. */
  14953. p = name;
  14954. count = 0;
  14955. while (*p != '@' && count < baseSz) {
  14956. count++;
  14957. p++;
  14958. }
  14959. if (count < baseSz && *p == '@') {
  14960. name = p + 1;
  14961. nameSz -= count + 1;
  14962. }
  14963. }
  14964. }
  14965. /* RFC 5280 section 4.2.1.10
  14966. * "...Any DNS name that can be constructed by simply adding zero or more
  14967. * labels to the left-hand side of the name satisfies the name constraint."
  14968. * i.e www.host.example.com works for host.example.com name constraint and
  14969. * host1.example.com does not. */
  14970. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  14971. int szAdjust = nameSz - baseSz;
  14972. name += szAdjust;
  14973. nameSz -= szAdjust;
  14974. }
  14975. while (nameSz > 0) {
  14976. if (XTOLOWER((unsigned char)*name++) !=
  14977. XTOLOWER((unsigned char)*base++))
  14978. return 0;
  14979. nameSz--;
  14980. }
  14981. return 1;
  14982. }
  14983. /* Search through the list to find if the name is permitted.
  14984. * name The DNS name to search for
  14985. * dnsList The list to search through
  14986. * nameType Type of DNS name to currently searching
  14987. * return 1 if found in list or if not needed
  14988. * return 0 if not found in the list but is needed
  14989. */
  14990. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  14991. {
  14992. Base_entry* current = dnsList;
  14993. int match = 0;
  14994. int need = 0;
  14995. int ret = 1; /* is ok unless needed and no match found */
  14996. while (current != NULL) {
  14997. if (current->type == nameType) {
  14998. need = 1; /* restriction on permitted names is set for this type */
  14999. if (name->len >= current->nameSz &&
  15000. MatchBaseName(nameType, name->name, name->len,
  15001. current->name, current->nameSz)) {
  15002. match = 1; /* found the current name in the permitted list*/
  15003. break;
  15004. }
  15005. }
  15006. current = current->next;
  15007. }
  15008. /* check if permitted name restriction was set and no matching name found */
  15009. if (need && !match)
  15010. ret = 0;
  15011. return ret;
  15012. }
  15013. /* Search through the list to find if the name is excluded.
  15014. * name The DNS name to search for
  15015. * dnsList The list to search through
  15016. * nameType Type of DNS name to currently searching
  15017. * return 1 if found in list and 0 if not found in the list
  15018. */
  15019. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15020. {
  15021. int ret = 0; /* default of not found in the list */
  15022. Base_entry* current = dnsList;
  15023. while (current != NULL) {
  15024. if (current->type == nameType) {
  15025. if (name->len >= current->nameSz &&
  15026. MatchBaseName(nameType, name->name, name->len,
  15027. current->name, current->nameSz)) {
  15028. ret = 1;
  15029. break;
  15030. }
  15031. }
  15032. current = current->next;
  15033. }
  15034. return ret;
  15035. }
  15036. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15037. {
  15038. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15039. int i;
  15040. if (signer == NULL || cert == NULL)
  15041. return 0;
  15042. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15043. return 1;
  15044. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15045. byte nameType = nameTypes[i];
  15046. DNS_entry* name = NULL;
  15047. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15048. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15049. switch (nameType) {
  15050. case ASN_DNS_TYPE:
  15051. /* Should it also consider CN in subject? It could use
  15052. * subjectDnsName too */
  15053. name = cert->altNames;
  15054. break;
  15055. case ASN_RFC822_TYPE:
  15056. /* Shouldn't it validade E= in subject as well? */
  15057. name = cert->altEmailNames;
  15058. /* Add subject email for checking. */
  15059. if (cert->subjectEmail != NULL) {
  15060. /* RFC 5280 section 4.2.1.10
  15061. * "When constraints are imposed on the rfc822Name name
  15062. * form, but the certificate does not include a subject
  15063. * alternative name, the rfc822Name constraint MUST be
  15064. * applied to the attribute of type emailAddress in the
  15065. * subject distinguished name" */
  15066. subjectDnsName.next = NULL;
  15067. subjectDnsName.type = ASN_RFC822_TYPE;
  15068. subjectDnsName.len = cert->subjectEmailLen;
  15069. subjectDnsName.name = (char *)cert->subjectEmail;
  15070. }
  15071. break;
  15072. case ASN_DIR_TYPE:
  15073. #ifndef WOLFSSL_NO_ASN_STRICT
  15074. name = cert->altDirNames;
  15075. #endif
  15076. /* RFC 5280 section 4.2.1.10
  15077. "Restrictions of the form directoryName MUST be
  15078. applied to the subject field .... and to any names
  15079. of type directoryName in the subjectAltName
  15080. extension"
  15081. */
  15082. if (cert->subjectRaw != NULL) {
  15083. subjectDnsName.next = NULL;
  15084. subjectDnsName.type = ASN_DIR_TYPE;
  15085. subjectDnsName.len = cert->subjectRawLen;
  15086. subjectDnsName.name = (char *)cert->subjectRaw;
  15087. }
  15088. break;
  15089. default:
  15090. /* Other types of names are ignored for now.
  15091. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15092. * and signer->extNameConstraintCrit is set? */
  15093. return 0;
  15094. }
  15095. while (name != NULL) {
  15096. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15097. WOLFSSL_MSG("Excluded name was found!");
  15098. return 0;
  15099. }
  15100. /* Check against the permitted list */
  15101. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15102. WOLFSSL_MSG("Permitted name was not found!");
  15103. return 0;
  15104. }
  15105. name = name->next;
  15106. }
  15107. /* handle comparing against subject name too */
  15108. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15109. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15110. nameType) == 1) {
  15111. WOLFSSL_MSG("Excluded name was found!");
  15112. return 0;
  15113. }
  15114. /* Check against the permitted list */
  15115. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15116. nameType) != 1) {
  15117. WOLFSSL_MSG("Permitted name was not found!");
  15118. return 0;
  15119. }
  15120. }
  15121. }
  15122. return 1;
  15123. }
  15124. #endif /* IGNORE_NAME_CONSTRAINTS */
  15125. #ifndef WOLFSSL_ASN_TEMPLATE
  15126. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15127. {
  15128. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15129. dnsEntry->next = NULL;
  15130. if (cert->altNames == NULL) {
  15131. /* First on list */
  15132. cert->altNames = dnsEntry;
  15133. }
  15134. else {
  15135. DNS_entry* temp = cert->altNames;
  15136. /* Find end */
  15137. for (; (temp->next != NULL); temp = temp->next);
  15138. /* Add to end */
  15139. temp->next = dnsEntry;
  15140. }
  15141. #else
  15142. dnsEntry->next = cert->altNames;
  15143. cert->altNames = dnsEntry;
  15144. #endif
  15145. }
  15146. #endif
  15147. #ifdef WOLFSSL_ASN_TEMPLATE
  15148. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15149. /* ASN.1 template for OtherName of an X.509 certificate.
  15150. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15151. * HW Name: RFC 4108, 5 - Hardware Module Name
  15152. * Only support HW Name where the type is a HW serial number.
  15153. *
  15154. * Other Names handled for FPKI (Federal PKI) use:
  15155. * UPN (Universal Principal Name), a non-standard Other Name
  15156. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15157. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15158. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15159. */
  15160. static const ASNItem otherNameASN[] = {
  15161. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15162. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15163. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15164. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15165. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15166. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15167. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15168. };
  15169. enum {
  15170. OTHERNAMEASN_IDX_TYPEID = 0,
  15171. OTHERNAMEASN_IDX_VALUE,
  15172. OTHERNAMEASN_IDX_UPN,
  15173. OTHERNAMEASN_IDX_FASCN,
  15174. OTHERNAMEASN_IDX_HWN_SEQ,
  15175. OTHERNAMEASN_IDX_HWN_TYPE,
  15176. OTHERNAMEASN_IDX_HWN_NUM
  15177. };
  15178. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15179. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15180. #ifdef WOLFSSL_SEP
  15181. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15182. {
  15183. int ret = 0;
  15184. word32 oidLen, serialLen;
  15185. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15186. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15187. /* Allocate space for HW type OID. */
  15188. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15189. DYNAMIC_TYPE_X509_EXT);
  15190. if (cert->hwType == NULL)
  15191. ret = MEMORY_E;
  15192. if (ret == 0) {
  15193. /* Copy, into cert HW type OID */
  15194. XMEMCPY(cert->hwType,
  15195. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15196. cert->hwTypeSz = (int)oidLen;
  15197. /* TODO: check this is the HW serial number OID - no test data. */
  15198. /* Allocate space for HW serial number, +1 for null terminator. */
  15199. cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
  15200. DYNAMIC_TYPE_X509_EXT);
  15201. if (cert->hwSerialNum == NULL) {
  15202. WOLFSSL_MSG("\tOut of Memory");
  15203. ret = MEMORY_E;
  15204. }
  15205. }
  15206. if (ret == 0) {
  15207. /* Copy into cert HW serial number. */
  15208. XMEMCPY(cert->hwSerialNum,
  15209. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15210. cert->hwSerialNum[serialLen] = '\0';
  15211. cert->hwSerialNumSz = (int)serialLen;
  15212. }
  15213. return ret;
  15214. }
  15215. #endif /* WOLFSSL_SEP */
  15216. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  15217. {
  15218. DNS_entry* entry = NULL;
  15219. int ret = 0;
  15220. word32 bufLen = 0;
  15221. const char* buf = NULL;
  15222. switch (oid) {
  15223. #ifdef WOLFSSL_FPKI
  15224. case FASCN_OID:
  15225. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  15226. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  15227. break;
  15228. #endif /* WOLFSSL_FPKI */
  15229. case UPN_OID:
  15230. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  15231. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  15232. break;
  15233. default:
  15234. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  15235. ret = ASN_UNKNOWN_OID_E;
  15236. break;
  15237. }
  15238. if (ret == 0) {
  15239. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  15240. if (ret == 0) {
  15241. #ifdef WOLFSSL_FPKI
  15242. entry->oidSum = oid;
  15243. #endif
  15244. AddDNSEntryToList(&cert->altNames, entry);
  15245. }
  15246. }
  15247. return ret;
  15248. }
  15249. /* Decode data with OtherName format from after implicit SEQUENCE.
  15250. *
  15251. * @param [in, out] cert Certificate object.
  15252. * @param [in] input Buffer containing encoded OtherName.
  15253. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15254. * On out, index after OtherName.
  15255. * @param [in] maxIdx Maximum index of data in buffer.
  15256. * @return 0 on success.
  15257. * @return MEMORY_E on dynamic memory allocation failure.
  15258. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15259. * is invalid.
  15260. * @return ASN_PARSE_E when OID does is not HW Name.
  15261. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15262. * @return BUFFER_E when data in buffer is too small.
  15263. */
  15264. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  15265. word32* inOutIdx, word32 maxIdx)
  15266. {
  15267. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  15268. int ret = 0;
  15269. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  15270. if (ret == 0) {
  15271. /* Check the first OID is a recognized Alt Cert Name type. */
  15272. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  15273. /* Parse OtherName. */
  15274. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  15275. inOutIdx, maxIdx);
  15276. }
  15277. if (ret == 0) {
  15278. /* Ensure expected OID. */
  15279. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  15280. #ifdef WOLFSSL_SEP
  15281. case HW_NAME_OID:
  15282. /* Only support HW serial number. */
  15283. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  15284. ret = DecodeSEP(dataASN, cert);
  15285. break;
  15286. #endif /* WOLFSSL_SEP */
  15287. #ifdef WOLFSSL_FPKI
  15288. case FASCN_OID:
  15289. #endif /* WOLFSSL_FPKI */
  15290. case UPN_OID:
  15291. ret = DecodeOtherHelper(dataASN, cert,
  15292. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  15293. break;
  15294. default:
  15295. WOLFSSL_MSG("\tunsupported OID skipping");
  15296. break;
  15297. }
  15298. }
  15299. FREE_ASNGETDATA(dataASN, cert->heap);
  15300. return ret;
  15301. }
  15302. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  15303. /* Decode a GeneralName.
  15304. *
  15305. * @param [in] input Buffer containing encoded OtherName.
  15306. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15307. * On out, index after OtherName.
  15308. * @param [in] len Length of data in buffer.
  15309. * @param [in] cert Decoded certificate object.
  15310. * @return 0 on success.
  15311. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15312. * is invalid.
  15313. * @return BUFFER_E when data in buffer is too small.
  15314. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15315. * @return MEMORY_E when dynamic memory allocation fails.
  15316. */
  15317. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  15318. int len, DecodedCert* cert)
  15319. {
  15320. int ret = 0;
  15321. word32 idx = *inOutIdx;
  15322. /* GeneralName choice: dnsName */
  15323. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15324. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  15325. &cert->altNames);
  15326. if (ret == 0) {
  15327. idx += (word32)len;
  15328. }
  15329. }
  15330. #ifndef IGNORE_NAME_CONSTRAINTS
  15331. /* GeneralName choice: directoryName */
  15332. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15333. int strLen;
  15334. word32 idxDir = idx;
  15335. /* Expecting a SEQUENCE using up all data. */
  15336. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  15337. {
  15338. WOLFSSL_MSG("\tfail: seq length");
  15339. return ASN_PARSE_E;
  15340. }
  15341. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  15342. ASN_DIR_TYPE, &cert->altDirNames);
  15343. if (ret == 0) {
  15344. idx += (word32)len;
  15345. }
  15346. }
  15347. /* GeneralName choice: rfc822Name */
  15348. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15349. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  15350. ASN_RFC822_TYPE, &cert->altEmailNames);
  15351. if (ret == 0) {
  15352. idx += (word32)len;
  15353. }
  15354. }
  15355. /* GeneralName choice: uniformResourceIdentifier */
  15356. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15357. WOLFSSL_MSG("\tPutting URI into list but not using");
  15358. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15359. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15360. "The name MUST NOT be a relative URI"
  15361. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15362. a scheme and hier-part. So the only strict requirement is a ':'
  15363. being present after the scheme. If a '/' is present as part of the
  15364. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15365. {
  15366. int i;
  15367. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15368. for (i = 0; i < len; i++) {
  15369. if (input[idx + (word32)i] == ':') {
  15370. break;
  15371. }
  15372. if (input[idx + (word32)i] == '/') {
  15373. i = len; /* error, found relative path since '/' was
  15374. * encountered before ':'. Returning error
  15375. * value in next if statement. */
  15376. }
  15377. }
  15378. /* test hier-part is empty */
  15379. if (i == 0 || i == len) {
  15380. WOLFSSL_MSG("\tEmpty or malformed URI");
  15381. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15382. return ASN_ALT_NAME_E;
  15383. }
  15384. /* test if scheme is missing */
  15385. if (input[idx + (word32)i] != ':') {
  15386. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15387. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15388. return ASN_ALT_NAME_E;
  15389. }
  15390. }
  15391. #endif
  15392. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  15393. &cert->altNames);
  15394. if (ret == 0) {
  15395. idx += (word32)len;
  15396. }
  15397. }
  15398. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  15399. defined(WOLFSSL_IP_ALT_NAME)
  15400. /* GeneralName choice: iPAddress */
  15401. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15402. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  15403. &cert->altNames);
  15404. if (ret == 0) {
  15405. idx += len;
  15406. }
  15407. }
  15408. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  15409. #endif /* IGNORE_NAME_CONSTRAINTS */
  15410. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15411. /* GeneralName choice: otherName */
  15412. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  15413. /* TODO: test data for code path */
  15414. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  15415. }
  15416. #endif
  15417. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  15418. * registeredID */
  15419. else {
  15420. WOLFSSL_MSG("\tUnsupported name type, skipping");
  15421. idx += (word32)len;
  15422. }
  15423. if (ret == 0) {
  15424. /* Return index of next encoded byte. */
  15425. *inOutIdx = idx;
  15426. }
  15427. return ret;
  15428. }
  15429. /* ASN.1 choices for GeneralName.
  15430. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15431. */
  15432. static const byte generalNameChoice[] = {
  15433. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  15434. ASN_CONTEXT_SPECIFIC | 1,
  15435. ASN_CONTEXT_SPECIFIC | 2,
  15436. ASN_CONTEXT_SPECIFIC | 3,
  15437. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  15438. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  15439. ASN_CONTEXT_SPECIFIC | 6,
  15440. ASN_CONTEXT_SPECIFIC | 7,
  15441. ASN_CONTEXT_SPECIFIC | 8,
  15442. 0
  15443. };
  15444. /* ASN.1 template for GeneralName.
  15445. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  15446. */
  15447. static const ASNItem altNameASN[] = {
  15448. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  15449. };
  15450. enum {
  15451. ALTNAMEASN_IDX_GN = 0
  15452. };
  15453. /* Number of items in ASN.1 template for GeneralName. */
  15454. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  15455. #endif /* WOLFSSL_ASN_TEMPLATE */
  15456. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  15457. /* return 0 on success */
  15458. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  15459. word32* idxIn, word32 sz)
  15460. {
  15461. word32 idx = *idxIn;
  15462. int strLen;
  15463. int ret;
  15464. byte tag;
  15465. /* Certificates issued with this OID in the subject alt name are for
  15466. * verifying signatures created on a module.
  15467. * RFC 4108 Section 5. */
  15468. if (cert->hwType != NULL) {
  15469. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  15470. return ASN_PARSE_E;
  15471. }
  15472. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  15473. return ASN_PARSE_E;
  15474. }
  15475. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  15476. WOLFSSL_MSG("\twrong type");
  15477. return ASN_PARSE_E;
  15478. }
  15479. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15480. WOLFSSL_MSG("\tfail: str len");
  15481. return ASN_PARSE_E;
  15482. }
  15483. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15484. WOLFSSL_MSG("\tBad Sequence");
  15485. return ASN_PARSE_E;
  15486. }
  15487. ret = GetASNObjectId(input, &idx, &strLen, sz);
  15488. if (ret != 0) {
  15489. WOLFSSL_MSG("\tbad OID");
  15490. return ret;
  15491. }
  15492. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  15493. DYNAMIC_TYPE_X509_EXT);
  15494. if (cert->hwType == NULL) {
  15495. WOLFSSL_MSG("\tOut of Memory");
  15496. return MEMORY_E;
  15497. }
  15498. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  15499. cert->hwTypeSz = strLen;
  15500. idx += (word32)strLen;
  15501. ret = GetOctetString(input, &idx, &strLen, sz);
  15502. if (ret < 0) {
  15503. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15504. cert->hwType = NULL;
  15505. return ret;
  15506. }
  15507. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  15508. DYNAMIC_TYPE_X509_EXT);
  15509. if (cert->hwSerialNum == NULL) {
  15510. WOLFSSL_MSG("\tOut of Memory");
  15511. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  15512. cert->hwType = NULL;
  15513. return MEMORY_E;
  15514. }
  15515. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  15516. cert->hwSerialNum[strLen] = '\0';
  15517. cert->hwSerialNumSz = strLen;
  15518. idx += (word32)strLen;
  15519. *idxIn = idx;
  15520. return 0;
  15521. }
  15522. #endif /* WOLFSSL_SEP */
  15523. #if !defined(WOLFSSL_ASN_TEMPLATE)
  15524. /* return 0 on success */
  15525. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  15526. word32* idx, word32 sz, int oid)
  15527. {
  15528. int ret = 0;
  15529. int strLen = 0;
  15530. byte tag;
  15531. DNS_entry* dnsEntry = NULL;
  15532. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15533. ret = ASN_PARSE_E;
  15534. }
  15535. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  15536. ret = ASN_PARSE_E;
  15537. }
  15538. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15539. ret = ASN_PARSE_E;
  15540. }
  15541. if (ret == 0) {
  15542. dnsEntry = AltNameNew(cert->heap);
  15543. if (dnsEntry == NULL) {
  15544. WOLFSSL_MSG("\tOut of Memory");
  15545. return MEMORY_E;
  15546. }
  15547. switch (oid) {
  15548. #ifdef WOLFSSL_FPKI
  15549. case FASCN_OID:
  15550. ret = GetOctetString(input, idx, &strLen, sz);
  15551. if (ret > 0) {
  15552. ret = 0;
  15553. }
  15554. break;
  15555. #endif /* WOLFSSL_FPKI */
  15556. case UPN_OID:
  15557. if (GetASNTag(input, idx, &tag, sz) < 0) {
  15558. ret = ASN_PARSE_E;
  15559. }
  15560. if (ret == 0 &&
  15561. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  15562. tag != ASN_IA5_STRING) {
  15563. WOLFSSL_MSG("Was expecting a string for UPN");
  15564. ret = ASN_PARSE_E;
  15565. }
  15566. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  15567. WOLFSSL_MSG("Was expecting a string for UPN");
  15568. ret = ASN_PARSE_E;
  15569. }
  15570. break;
  15571. default:
  15572. WOLFSSL_MSG("Unknown constructed other name, skipping");
  15573. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15574. dnsEntry = NULL;
  15575. }
  15576. }
  15577. if (ret == 0 && dnsEntry != NULL) {
  15578. dnsEntry->type = ASN_OTHER_TYPE;
  15579. dnsEntry->len = strLen;
  15580. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15581. DYNAMIC_TYPE_ALTNAME);
  15582. #ifdef WOLFSSL_FPKI
  15583. dnsEntry->oidSum = oid;
  15584. #endif /* WOLFSSL_FPKI */
  15585. if (dnsEntry->name == NULL) {
  15586. WOLFSSL_MSG("\tOut of Memory");
  15587. ret = MEMORY_E;
  15588. }
  15589. else {
  15590. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  15591. dnsEntry->name[strLen] = '\0';
  15592. AddAltName(cert, dnsEntry);
  15593. }
  15594. }
  15595. if (ret == 0) {
  15596. *idx += (word32)strLen;
  15597. }
  15598. else {
  15599. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15600. }
  15601. return ret;
  15602. }
  15603. #endif
  15604. /* Decode subject alternative names extension.
  15605. *
  15606. * RFC 5280 4.2.1.6. Subject Alternative Name
  15607. *
  15608. * @param [in] input Buffer holding encoded data.
  15609. * @param [in] sz Size of encoded data in bytes.
  15610. * @param [in, out] cert Decoded certificate object.
  15611. * @return 0 on success.
  15612. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15613. * is invalid.
  15614. * @return BUFFER_E when data in buffer is too small.
  15615. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15616. * @return MEMORY_E when dynamic memory allocation fails.
  15617. */
  15618. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  15619. {
  15620. #ifndef WOLFSSL_ASN_TEMPLATE
  15621. word32 idx = 0;
  15622. int length = 0;
  15623. WOLFSSL_ENTER("DecodeAltNames");
  15624. if (GetSequence(input, &idx, &length, sz) < 0) {
  15625. WOLFSSL_MSG("\tBad Sequence");
  15626. return ASN_PARSE_E;
  15627. }
  15628. if (length == 0) {
  15629. /* RFC 5280 4.2.1.6. Subject Alternative Name
  15630. If the subjectAltName extension is present, the sequence MUST
  15631. contain at least one entry. */
  15632. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  15633. return ASN_PARSE_E;
  15634. }
  15635. #ifdef OPENSSL_ALL
  15636. cert->extSubjAltNameSrc = input;
  15637. cert->extSubjAltNameSz = sz;
  15638. #endif
  15639. cert->weOwnAltNames = 1;
  15640. while (length > 0) {
  15641. byte current_byte;
  15642. /* Verify idx can't overflow input buffer */
  15643. if (idx >= (word32)sz) {
  15644. WOLFSSL_MSG("\tBad Index");
  15645. return BUFFER_E;
  15646. }
  15647. current_byte = input[idx++];
  15648. length--;
  15649. /* Save DNS Type names in the altNames list. */
  15650. /* Save Other Type names in the cert's OidMap */
  15651. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15652. DNS_entry* dnsEntry;
  15653. int strLen;
  15654. word32 lenStartIdx = idx;
  15655. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15656. WOLFSSL_MSG("\tfail: str length");
  15657. return ASN_PARSE_E;
  15658. }
  15659. length -= (int)(idx - lenStartIdx);
  15660. dnsEntry = AltNameNew(cert->heap);
  15661. if (dnsEntry == NULL) {
  15662. WOLFSSL_MSG("\tOut of Memory");
  15663. return MEMORY_E;
  15664. }
  15665. dnsEntry->type = ASN_DNS_TYPE;
  15666. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15667. DYNAMIC_TYPE_ALTNAME);
  15668. if (dnsEntry->name == NULL) {
  15669. WOLFSSL_MSG("\tOut of Memory");
  15670. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15671. return MEMORY_E;
  15672. }
  15673. dnsEntry->len = strLen;
  15674. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  15675. dnsEntry->name[strLen] = '\0';
  15676. AddAltName(cert, dnsEntry);
  15677. length -= strLen;
  15678. idx += (word32)strLen;
  15679. }
  15680. #ifndef IGNORE_NAME_CONSTRAINTS
  15681. else if (current_byte ==
  15682. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15683. DNS_entry* dirEntry;
  15684. int strLen;
  15685. word32 lenStartIdx = idx;
  15686. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15687. WOLFSSL_MSG("\tfail: str length");
  15688. return ASN_PARSE_E;
  15689. }
  15690. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  15691. WOLFSSL_MSG("\tfail: seq length");
  15692. return ASN_PARSE_E;
  15693. }
  15694. length -= (int)(idx - lenStartIdx);
  15695. dirEntry = AltNameNew(cert->heap);
  15696. if (dirEntry == NULL) {
  15697. WOLFSSL_MSG("\tOut of Memory");
  15698. return MEMORY_E;
  15699. }
  15700. dirEntry->type = ASN_DIR_TYPE;
  15701. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15702. DYNAMIC_TYPE_ALTNAME);
  15703. if (dirEntry->name == NULL) {
  15704. WOLFSSL_MSG("\tOut of Memory");
  15705. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15706. return MEMORY_E;
  15707. }
  15708. dirEntry->len = strLen;
  15709. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  15710. dirEntry->name[strLen] = '\0';
  15711. dirEntry->next = cert->altDirNames;
  15712. cert->altDirNames = dirEntry;
  15713. length -= strLen;
  15714. idx += (word32)strLen;
  15715. }
  15716. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15717. DNS_entry* emailEntry;
  15718. int strLen;
  15719. word32 lenStartIdx = idx;
  15720. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15721. WOLFSSL_MSG("\tfail: str length");
  15722. return ASN_PARSE_E;
  15723. }
  15724. length -= (int)(idx - lenStartIdx);
  15725. emailEntry = AltNameNew(cert->heap);
  15726. if (emailEntry == NULL) {
  15727. WOLFSSL_MSG("\tOut of Memory");
  15728. return MEMORY_E;
  15729. }
  15730. emailEntry->type = ASN_RFC822_TYPE;
  15731. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15732. DYNAMIC_TYPE_ALTNAME);
  15733. if (emailEntry->name == NULL) {
  15734. WOLFSSL_MSG("\tOut of Memory");
  15735. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15736. return MEMORY_E;
  15737. }
  15738. emailEntry->len = strLen;
  15739. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  15740. emailEntry->name[strLen] = '\0';
  15741. emailEntry->next = cert->altEmailNames;
  15742. cert->altEmailNames = emailEntry;
  15743. length -= strLen;
  15744. idx += (word32)strLen;
  15745. }
  15746. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15747. DNS_entry* uriEntry;
  15748. int strLen;
  15749. word32 lenStartIdx = idx;
  15750. WOLFSSL_MSG("\tPutting URI into list but not using");
  15751. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15752. WOLFSSL_MSG("\tfail: str length");
  15753. return ASN_PARSE_E;
  15754. }
  15755. length -= (int)(idx - lenStartIdx);
  15756. /* check that strLen at index is not past input buffer */
  15757. if ((word32)strLen + idx > sz) {
  15758. return BUFFER_E;
  15759. }
  15760. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15761. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15762. "The name MUST NOT be a relative URI"
  15763. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15764. a scheme and hier-part. So the only strict requirement is a ':'
  15765. being present after the scheme. If a '/' is present as part of the
  15766. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15767. {
  15768. word32 i;
  15769. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15770. for (i = 0; i < (word32)strLen; i++) {
  15771. if (input[idx + i] == ':') {
  15772. break;
  15773. }
  15774. if (input[idx + i] == '/') {
  15775. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15776. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15777. return ASN_ALT_NAME_E;
  15778. }
  15779. }
  15780. /* test hier-part is empty */
  15781. if (i == 0 || i == (word32)strLen) {
  15782. WOLFSSL_MSG("\tEmpty or malformed URI");
  15783. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15784. return ASN_ALT_NAME_E;
  15785. }
  15786. /* test if scheme is missing */
  15787. if (input[idx + i] != ':') {
  15788. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15789. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15790. return ASN_ALT_NAME_E;
  15791. }
  15792. }
  15793. #endif
  15794. uriEntry = AltNameNew(cert->heap);
  15795. if (uriEntry == NULL) {
  15796. WOLFSSL_MSG("\tOut of Memory");
  15797. return MEMORY_E;
  15798. }
  15799. uriEntry->type = ASN_URI_TYPE;
  15800. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15801. DYNAMIC_TYPE_ALTNAME);
  15802. if (uriEntry->name == NULL) {
  15803. WOLFSSL_MSG("\tOut of Memory");
  15804. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15805. return MEMORY_E;
  15806. }
  15807. uriEntry->len = strLen;
  15808. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  15809. uriEntry->name[strLen] = '\0';
  15810. AddAltName(cert, uriEntry);
  15811. length -= strLen;
  15812. idx += (word32)strLen;
  15813. }
  15814. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  15815. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  15816. DNS_entry* ipAddr;
  15817. int strLen;
  15818. word32 lenStartIdx = idx;
  15819. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  15820. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15821. WOLFSSL_MSG("\tfail: str length");
  15822. return ASN_PARSE_E;
  15823. }
  15824. length -= (idx - lenStartIdx);
  15825. /* check that strLen at index is not past input buffer */
  15826. if (strLen + idx > sz) {
  15827. return BUFFER_E;
  15828. }
  15829. ipAddr = AltNameNew(cert->heap);
  15830. if (ipAddr == NULL) {
  15831. WOLFSSL_MSG("\tOut of Memory");
  15832. return MEMORY_E;
  15833. }
  15834. ipAddr->type = ASN_IP_TYPE;
  15835. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  15836. DYNAMIC_TYPE_ALTNAME);
  15837. if (ipAddr->name == NULL) {
  15838. WOLFSSL_MSG("\tOut of Memory");
  15839. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15840. return MEMORY_E;
  15841. }
  15842. ipAddr->len = strLen;
  15843. XMEMCPY(ipAddr->name, &input[idx], strLen);
  15844. ipAddr->name[strLen] = '\0';
  15845. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  15846. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  15847. WOLFSSL_MSG("\tOut of Memory for IP string");
  15848. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15849. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  15850. return MEMORY_E;
  15851. }
  15852. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  15853. AddAltName(cert, ipAddr);
  15854. length -= strLen;
  15855. idx += (word32)strLen;
  15856. }
  15857. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  15858. #endif /* IGNORE_NAME_CONSTRAINTS */
  15859. else if (current_byte ==
  15860. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  15861. int strLen;
  15862. word32 lenStartIdx = idx;
  15863. word32 oid = 0;
  15864. int ret = 0;
  15865. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15866. WOLFSSL_MSG("\tfail: other name length");
  15867. return ASN_PARSE_E;
  15868. }
  15869. /* Consume the rest of this sequence. */
  15870. length -= (int)(((word32)strLen + idx - lenStartIdx));
  15871. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  15872. WOLFSSL_MSG("\tbad OID");
  15873. return ASN_PARSE_E;
  15874. }
  15875. /* handle parsing other type alt names */
  15876. switch (oid) {
  15877. #ifdef WOLFSSL_SEP
  15878. case HW_NAME_OID:
  15879. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  15880. if (ret != 0)
  15881. return ret;
  15882. break;
  15883. #endif /* WOLFSSL_SEP */
  15884. #ifdef WOLFSSL_FPKI
  15885. case FASCN_OID:
  15886. case UPN_OID:
  15887. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  15888. oid);
  15889. if (ret != 0)
  15890. return ret;
  15891. break;
  15892. #endif /* WOLFSSL_FPKI */
  15893. default:
  15894. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  15895. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15896. /* check to skip constructed other names too */
  15897. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  15898. (int)oid) != 0) {
  15899. WOLFSSL_MSG("\tfail: unsupported other name length");
  15900. return ASN_PARSE_E;
  15901. }
  15902. }
  15903. else {
  15904. idx += (word32)strLen;
  15905. }
  15906. }
  15907. (void)ret;
  15908. }
  15909. else {
  15910. int strLen;
  15911. word32 lenStartIdx = idx;
  15912. WOLFSSL_MSG("\tUnsupported name type, skipping");
  15913. if (GetLength(input, &idx, &strLen, sz) < 0) {
  15914. WOLFSSL_MSG("\tfail: unsupported name length");
  15915. return ASN_PARSE_E;
  15916. }
  15917. length -= (int)((word32)strLen + idx - lenStartIdx);
  15918. idx += (word32)strLen;
  15919. }
  15920. }
  15921. return 0;
  15922. #else
  15923. word32 idx = 0;
  15924. int length = 0;
  15925. int ret = 0;
  15926. WOLFSSL_ENTER("DecodeAltNames");
  15927. /* Get SEQUENCE and expect all data to be accounted for. */
  15928. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  15929. WOLFSSL_MSG("\tBad Sequence");
  15930. ret = ASN_PARSE_E;
  15931. }
  15932. if ((ret == 0) && (length == 0)) {
  15933. /* RFC 5280 4.2.1.6. Subject Alternative Name
  15934. If the subjectAltName extension is present, the sequence MUST
  15935. contain at least one entry. */
  15936. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  15937. ret = ASN_PARSE_E;
  15938. }
  15939. if (ret == 0) {
  15940. #ifdef OPENSSL_ALL
  15941. cert->extSubjAltNameSrc = input;
  15942. cert->extSubjAltNameSz = sz;
  15943. #endif
  15944. cert->weOwnAltNames = 1;
  15945. if ((word32)length + idx != sz) {
  15946. ret = ASN_PARSE_E;
  15947. }
  15948. }
  15949. while ((ret == 0) && (idx < sz)) {
  15950. ASNGetData dataASN[altNameASN_Length];
  15951. /* Clear dynamic data items. */
  15952. XMEMSET(dataASN, 0, sizeof(dataASN));
  15953. /* Parse GeneralName with the choices supported. */
  15954. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  15955. /* Decode a GeneralName choice. */
  15956. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  15957. &idx, sz);
  15958. if (ret == 0) {
  15959. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  15960. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  15961. }
  15962. }
  15963. return ret;
  15964. #endif
  15965. }
  15966. #ifdef WOLFSSL_ASN_TEMPLATE
  15967. /* ASN.1 template for BasicContraints.
  15968. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  15969. */
  15970. static const ASNItem basicConsASN[] = {
  15971. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  15972. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  15973. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  15974. };
  15975. enum {
  15976. BASICCONSASN_IDX_SEQ = 0,
  15977. BASICCONSASN_IDX_CA,
  15978. BASICCONSASN_IDX_PLEN
  15979. };
  15980. /* Number of items in ASN.1 template for BasicContraints. */
  15981. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  15982. #endif
  15983. /* Decode basic constraints extension in a certificate.
  15984. *
  15985. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  15986. *
  15987. * @param [in] input Buffer holding data.
  15988. * @param [in] sz Size of data in buffer.
  15989. * @param [in, out] cert Certificate object.
  15990. * @return 0 on success.
  15991. * @return MEMORY_E on dynamic memory allocation failure.
  15992. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  15993. * @return ASN_PARSE_E when CA boolean is not present unless
  15994. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  15995. * @return ASN_PARSE_E when path length more than 7 bits.
  15996. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15997. * is invalid.
  15998. * @return BUFFER_E when data in buffer is too small.
  15999. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  16000. * non-zero length.
  16001. */
  16002. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  16003. {
  16004. #ifndef WOLFSSL_ASN_TEMPLATE
  16005. word32 idx = 0;
  16006. int length = 0;
  16007. int ret;
  16008. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  16009. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16010. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16011. return ASN_PARSE_E;
  16012. }
  16013. if (length == 0)
  16014. return 0;
  16015. /* If the basic ca constraint is false, this extension may be named, but
  16016. * left empty. So, if the length is 0, just return. */
  16017. ret = GetBoolean(input, &idx, (word32)sz);
  16018. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  16019. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16020. * When CA Boolean not asserted use the default value "False" */
  16021. if (ret < 0) {
  16022. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16023. ret = 0;
  16024. }
  16025. cert->isCA = ret ? 1 : 0;
  16026. /* If there isn't any more data, return. */
  16027. if (idx >= (word32)sz) {
  16028. return 0;
  16029. }
  16030. ret = GetInteger7Bit(input, &idx, (word32)sz);
  16031. if (ret < 0)
  16032. return ret;
  16033. cert->pathLength = (byte)ret;
  16034. cert->pathLengthSet = 1;
  16035. return 0;
  16036. #else
  16037. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16038. int ret = 0;
  16039. word32 idx = 0;
  16040. byte isCA = 0;
  16041. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16042. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16043. if (ret == 0) {
  16044. /* Get the CA boolean and path length when present. */
  16045. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16046. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16047. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16048. &idx, (word32)sz);
  16049. }
  16050. /* Empty SEQUENCE is OK - nothing to store. */
  16051. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16052. /* Bad encoding when CA Boolean is false
  16053. * (default when not present). */
  16054. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16055. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16056. ret = ASN_PARSE_E;
  16057. }
  16058. /* Path length must be a 7-bit value. */
  16059. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16060. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16061. ret = ASN_PARSE_E;
  16062. }
  16063. /* Store CA boolean and whether a path length was seen. */
  16064. if (ret == 0) {
  16065. /* isCA in certificate is a 1 bit of a byte. */
  16066. cert->isCA = isCA ? 1 : 0;
  16067. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16068. }
  16069. }
  16070. FREE_ASNGETDATA(dataASN, cert->heap);
  16071. return ret;
  16072. #endif
  16073. }
  16074. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16075. {
  16076. word32 idx = 0;
  16077. int length = 0;
  16078. int skipLength = 0;
  16079. int ret;
  16080. byte tag;
  16081. WOLFSSL_ENTER("DecodePolicyConstraints");
  16082. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16083. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16084. return ASN_PARSE_E;
  16085. }
  16086. if (length == 0)
  16087. return ASN_PARSE_E;
  16088. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  16089. WOLFSSL_MSG("\tfail: bad TAG");
  16090. return ASN_PARSE_E;
  16091. }
  16092. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16093. /* requireExplicitPolicy */
  16094. cert->extPolicyConstRxpSet = 1;
  16095. }
  16096. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16097. /* inhibitPolicyMapping */
  16098. cert->extPolicyConstIpmSet = 1;
  16099. }
  16100. else {
  16101. WOLFSSL_MSG("\tfail: invalid TAG");
  16102. return ASN_PARSE_E;
  16103. }
  16104. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  16105. if (ret < 0) {
  16106. WOLFSSL_MSG("\tfail: invalid length");
  16107. return ret;
  16108. }
  16109. if (skipLength > 1) {
  16110. WOLFSSL_MSG("\tfail: skip value too big");
  16111. return BUFFER_E;
  16112. }
  16113. if (idx >= (word32)sz) {
  16114. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16115. return BUFFER_E;
  16116. }
  16117. cert->policyConstSkip = input[idx];
  16118. return 0;
  16119. }
  16120. /* Context-Specific value for: DistributionPoint.distributionPoint
  16121. * From RFC5280 SS4.2.1.13, Distribution Point */
  16122. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16123. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16124. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16125. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16126. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16127. * From RFC3280 SS4.2.1.7, GeneralName */
  16128. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16129. #ifdef WOLFSSL_ASN_TEMPLATE
  16130. /* ASN.1 template for CRL distribution points.
  16131. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16132. */
  16133. static const ASNItem crlDistASN[] = {
  16134. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16135. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16136. /* Distribution point name */
  16137. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16138. /* fullName */
  16139. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16140. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16141. /* nameRelativeToCRLIssuer */
  16142. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16143. /* reasons: IMPLICIT BIT STRING */
  16144. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16145. /* cRLIssuer */
  16146. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16147. };
  16148. enum {
  16149. CRLDISTASN_IDX_SEQ = 0,
  16150. CRLDISTASN_IDX_DP_SEQ,
  16151. CRLDISTASN_IDX_DP_DISTPOINT,
  16152. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16153. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16154. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16155. CRLDISTASN_IDX_DP_REASONS,
  16156. CRLDISTASN_IDX_DP_CRLISSUER
  16157. };
  16158. /* Number of items in ASN.1 template for CRL distribution points. */
  16159. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  16160. #endif
  16161. /* Decode CRL distribution point extension in a certificate.
  16162. *
  16163. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16164. *
  16165. * @param [in] input Buffer holding data.
  16166. * @param [in] sz Size of data in buffer.
  16167. * @param [in, out] cert Certificate object.
  16168. * @return 0 on success.
  16169. * @return MEMORY_E on dynamic memory allocation failure.
  16170. * @return ASN_PARSE_E when invalid bits of reason are set.
  16171. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  16172. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  16173. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16174. * is invalid.
  16175. * @return BUFFER_E when data in buffer is too small.
  16176. */
  16177. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  16178. {
  16179. #ifndef WOLFSSL_ASN_TEMPLATE
  16180. word32 idx = 0, localIdx;
  16181. int length = 0;
  16182. byte tag = 0;
  16183. WOLFSSL_ENTER("DecodeCrlDist");
  16184. cert->extCrlInfoRaw = input;
  16185. cert->extCrlInfoRawSz = (int)sz;
  16186. /* Unwrap the list of Distribution Points*/
  16187. if (GetSequence(input, &idx, &length, sz) < 0)
  16188. return ASN_PARSE_E;
  16189. /* Unwrap a single Distribution Point */
  16190. if (GetSequence(input, &idx, &length, sz) < 0)
  16191. return ASN_PARSE_E;
  16192. /* The Distribution Point has three explicit optional members
  16193. * First check for a DistributionPointName
  16194. */
  16195. localIdx = idx;
  16196. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16197. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  16198. {
  16199. idx++;
  16200. if (GetLength(input, &idx, &length, sz) < 0)
  16201. return ASN_PARSE_E;
  16202. localIdx = idx;
  16203. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16204. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  16205. {
  16206. idx++;
  16207. if (GetLength(input, &idx, &length, sz) < 0)
  16208. return ASN_PARSE_E;
  16209. localIdx = idx;
  16210. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16211. tag == GENERALNAME_URI)
  16212. {
  16213. idx++;
  16214. if (GetLength(input, &idx, &length, sz) < 0)
  16215. return ASN_PARSE_E;
  16216. cert->extCrlInfoSz = length;
  16217. cert->extCrlInfo = input + idx;
  16218. idx += (word32)length;
  16219. }
  16220. else
  16221. /* This isn't a URI, skip it. */
  16222. idx += (word32)length;
  16223. }
  16224. else {
  16225. /* This isn't a FULLNAME, skip it. */
  16226. idx += (word32)length;
  16227. }
  16228. }
  16229. /* Check for reasonFlags */
  16230. localIdx = idx;
  16231. if (idx < (word32)sz &&
  16232. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16233. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  16234. {
  16235. idx++;
  16236. if (GetLength(input, &idx, &length, sz) < 0)
  16237. return ASN_PARSE_E;
  16238. idx += (word32)length;
  16239. }
  16240. /* Check for cRLIssuer */
  16241. localIdx = idx;
  16242. if (idx < (word32)sz &&
  16243. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16244. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  16245. {
  16246. idx++;
  16247. if (GetLength(input, &idx, &length, sz) < 0)
  16248. return ASN_PARSE_E;
  16249. idx += (word32)length;
  16250. }
  16251. if (idx < (word32)sz)
  16252. {
  16253. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16254. "but we only use the first one.");
  16255. }
  16256. return 0;
  16257. #else
  16258. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  16259. word32 idx = 0;
  16260. int ret = 0;
  16261. #ifdef CRLDP_VALIDATE_DATA
  16262. word16 reason;
  16263. #endif
  16264. WOLFSSL_ENTER("DecodeCrlDist");
  16265. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  16266. cert->extCrlInfoRaw = input;
  16267. cert->extCrlInfoRawSz = (int)sz;
  16268. if (ret == 0) {
  16269. /* Get the GeneralName choice */
  16270. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  16271. /* Parse CRL distribtion point. */
  16272. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  16273. &idx, sz);
  16274. }
  16275. if (ret == 0) {
  16276. /* If the choice was a URI, store it in certificate. */
  16277. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  16278. word32 sz32;
  16279. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  16280. &cert->extCrlInfo, &sz32);
  16281. cert->extCrlInfoSz = (int)sz32;
  16282. }
  16283. #ifdef CRLDP_VALIDATE_DATA
  16284. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  16285. /* TODO: test case */
  16286. /* Validate ReasonFlags. */
  16287. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  16288. &reason);
  16289. /* First bit (LSB) unused and eight other bits defined. */
  16290. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  16291. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16292. ret = ASN_PARSE_E;
  16293. }
  16294. }
  16295. #endif
  16296. }
  16297. /* Only parsing the first one. */
  16298. if (ret == 0 && idx < (word32)sz) {
  16299. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16300. "but we only use the first one.");
  16301. }
  16302. /* TODO: validate other points. */
  16303. FREE_ASNGETDATA(dataASN, cert->heap);
  16304. return ret;
  16305. #endif /* WOLFSSL_ASN_TEMPLATE */
  16306. }
  16307. #ifdef WOLFSSL_ASN_TEMPLATE
  16308. /* ASN.1 template for the access description.
  16309. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16310. */
  16311. static const ASNItem accessDescASN[] = {
  16312. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16313. /* accessMethod */
  16314. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  16315. /* accessLocation: GeneralName */
  16316. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16317. };
  16318. enum {
  16319. ACCESSDESCASN_IDX_SEQ = 0,
  16320. ACCESSDESCASN_IDX_METH,
  16321. ACCESSDESCASN_IDX_LOC
  16322. };
  16323. /* Number of items in ASN.1 template for the access description. */
  16324. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  16325. #endif
  16326. /* Decode authority information access extension in a certificate.
  16327. *
  16328. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16329. *
  16330. * @param [in] input Buffer holding data.
  16331. * @param [in] sz Size of data in buffer.
  16332. * @param [in, out] cert Certificate object.
  16333. * @return 0 on success.
  16334. * @return MEMORY_E on dynamic memory allocation failure.
  16335. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16336. * is invalid.
  16337. * @return BUFFER_E when data in buffer is too small.
  16338. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  16339. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16340. */
  16341. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  16342. {
  16343. #ifndef WOLFSSL_ASN_TEMPLATE
  16344. word32 idx = 0;
  16345. int length = 0;
  16346. int count = 0;
  16347. byte b = 0;
  16348. word32 oid;
  16349. WOLFSSL_ENTER("DecodeAuthInfo");
  16350. /* Unwrap the list of AIAs */
  16351. if (GetSequence(input, &idx, &length, sz) < 0)
  16352. return ASN_PARSE_E;
  16353. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16354. /* Unwrap a single AIA */
  16355. if (GetSequence(input, &idx, &length, sz) < 0)
  16356. return ASN_PARSE_E;
  16357. oid = 0;
  16358. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  16359. return ASN_PARSE_E;
  16360. }
  16361. /* Only supporting URIs right now. */
  16362. if (GetASNTag(input, &idx, &b, sz) < 0)
  16363. return ASN_PARSE_E;
  16364. if (GetLength(input, &idx, &length, sz) < 0)
  16365. return ASN_PARSE_E;
  16366. /* Set ocsp entry */
  16367. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  16368. {
  16369. cert->extAuthInfoSz = length;
  16370. cert->extAuthInfo = input + idx;
  16371. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16372. count++;
  16373. #else
  16374. break;
  16375. #endif
  16376. }
  16377. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16378. /* Set CaIssuers entry */
  16379. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  16380. {
  16381. cert->extAuthInfoCaIssuerSz = length;
  16382. cert->extAuthInfoCaIssuer = input + idx;
  16383. count++;
  16384. }
  16385. #endif
  16386. idx += (word32)length;
  16387. }
  16388. return 0;
  16389. #else
  16390. word32 idx = 0;
  16391. int length = 0;
  16392. int count = 0;
  16393. int ret = 0;
  16394. WOLFSSL_ENTER("DecodeAuthInfo");
  16395. /* Unwrap the list of AIAs */
  16396. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16397. ret = ASN_PARSE_E;
  16398. }
  16399. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16400. ASNGetData dataASN[accessDescASN_Length];
  16401. /* Clear dynamic data and retrieve OID and name. */
  16402. XMEMSET(dataASN, 0, sizeof(dataASN));
  16403. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  16404. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  16405. /* Parse AccessDescription. */
  16406. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  16407. input, &idx, sz);
  16408. if (ret == 0) {
  16409. word32 sz32;
  16410. /* Check we have OCSP and URI. */
  16411. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  16412. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16413. /* Store URI for OCSP lookup. */
  16414. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16415. &cert->extAuthInfo, &sz32);
  16416. cert->extAuthInfoSz = (int)sz32;
  16417. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16418. count++;
  16419. #else
  16420. break;
  16421. #endif
  16422. }
  16423. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16424. /* Check we have CA Issuer and URI. */
  16425. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  16426. AIA_CA_ISSUER_OID) &&
  16427. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  16428. /* Set CaIssuers entry */
  16429. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  16430. &cert->extAuthInfoCaIssuer, &sz32);
  16431. cert->extAuthInfoCaIssuerSz = sz32;
  16432. count++;
  16433. }
  16434. #endif
  16435. /* Otherwise skip. */
  16436. }
  16437. }
  16438. return ret;
  16439. #endif
  16440. }
  16441. #ifdef WOLFSSL_ASN_TEMPLATE
  16442. /* ASN.1 template for AuthorityKeyIdentifier.
  16443. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  16444. */
  16445. static const ASNItem authKeyIdASN[] = {
  16446. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16447. /* keyIdentifier */
  16448. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  16449. /* authorityCertIssuer */
  16450. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  16451. /* authorityCertSerialNumber */
  16452. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  16453. };
  16454. enum {
  16455. AUTHKEYIDASN_IDX_SEQ = 0,
  16456. AUTHKEYIDASN_IDX_KEYID,
  16457. AUTHKEYIDASN_IDX_ISSUER,
  16458. AUTHKEYIDASN_IDX_SERIAL
  16459. };
  16460. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  16461. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  16462. #endif
  16463. /* Decode authority information access extension in a certificate.
  16464. *
  16465. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16466. *
  16467. * @param [in] input Buffer holding data.
  16468. * @param [in] sz Size of data in buffer.
  16469. * @param [in, out] cert Certificate object.
  16470. * @return 0 on success.
  16471. * @return MEMORY_E on dynamic memory allocation failure.
  16472. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16473. * is invalid.
  16474. * @return BUFFER_E when data in buffer is too small.
  16475. */
  16476. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  16477. {
  16478. #ifndef WOLFSSL_ASN_TEMPLATE
  16479. word32 idx = 0;
  16480. int length = 0;
  16481. byte tag;
  16482. WOLFSSL_ENTER("DecodeAuthKeyId");
  16483. if (GetSequence(input, &idx, &length, sz) < 0) {
  16484. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16485. return ASN_PARSE_E;
  16486. }
  16487. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16488. return ASN_PARSE_E;
  16489. }
  16490. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  16491. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16492. cert->extAuthKeyIdSet = 0;
  16493. return 0;
  16494. }
  16495. if (GetLength(input, &idx, &length, sz) <= 0) {
  16496. WOLFSSL_MSG("\tfail: extension data length");
  16497. return ASN_PARSE_E;
  16498. }
  16499. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16500. #ifdef WOLFSSL_AKID_NAME
  16501. cert->extRawAuthKeyIdSrc = input;
  16502. cert->extRawAuthKeyIdSz = sz;
  16503. #endif
  16504. cert->extAuthKeyIdSrc = &input[idx];
  16505. cert->extAuthKeyIdSz = length;
  16506. #endif /* OPENSSL_EXTRA */
  16507. return GetHashId(input + idx, length, cert->extAuthKeyId);
  16508. #else
  16509. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  16510. int ret = 0;
  16511. word32 idx = 0;
  16512. WOLFSSL_ENTER("DecodeAuthKeyId");
  16513. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  16514. if (ret == 0) {
  16515. /* Parse an authority key identifier. */
  16516. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  16517. &idx, sz);
  16518. }
  16519. if (ret == 0) {
  16520. /* Key id is optional. */
  16521. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  16522. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  16523. }
  16524. else {
  16525. #ifdef OPENSSL_EXTRA
  16526. /* Store the authority key id. */
  16527. #ifdef WOLFSSL_AKID_NAME
  16528. cert->extRawAuthKeyIdSrc = input;
  16529. cert->extRawAuthKeyIdSz = sz;
  16530. #endif
  16531. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
  16532. &cert->extAuthKeyIdSz);
  16533. #endif /* OPENSSL_EXTRA */
  16534. /* Get the hash or hash of the hash if wrong size. */
  16535. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  16536. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  16537. cert->extAuthKeyId);
  16538. }
  16539. }
  16540. FREE_ASNGETDATA(dataASN, cert->heap);
  16541. return ret;
  16542. #endif /* WOLFSSL_ASN_TEMPLATE */
  16543. }
  16544. /* Decode subject key id extension in a certificate.
  16545. *
  16546. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16547. *
  16548. * @param [in] input Buffer holding data.
  16549. * @param [in] sz Size of data in buffer.
  16550. * @param [in, out] cert Certificate object.
  16551. * @return 0 on success.
  16552. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  16553. * invalid.
  16554. * @return MEMORY_E on dynamic memory allocation failure.
  16555. */
  16556. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  16557. {
  16558. word32 idx = 0;
  16559. int length = 0;
  16560. int ret = 0;
  16561. WOLFSSL_ENTER("DecodeSubjKeyId");
  16562. ret = GetOctetString(input, &idx, &length, sz);
  16563. if (ret > 0) {
  16564. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16565. cert->extSubjKeyIdSrc = &input[idx];
  16566. cert->extSubjKeyIdSz = length;
  16567. #endif /* OPENSSL_EXTRA */
  16568. /* Get the hash or hash of the hash if wrong size. */
  16569. ret = GetHashId(input + idx, length, cert->extSubjKeyId);
  16570. }
  16571. return ret;
  16572. }
  16573. #ifdef WOLFSSL_ASN_TEMPLATE
  16574. /* ASN.1 template for KeyUsage.
  16575. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  16576. */
  16577. static const ASNItem keyUsageASN[] = {
  16578. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  16579. };
  16580. enum {
  16581. KEYUSAGEASN_IDX_STR = 0
  16582. };
  16583. /* Number of items in ASN.1 template for KeyUsage. */
  16584. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  16585. #endif
  16586. /* Decode key usage extension in a certificate.
  16587. *
  16588. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16589. *
  16590. * @param [in] input Buffer holding data.
  16591. * @param [in] sz Size of data in buffer.
  16592. * @param [in, out] cert Certificate object.
  16593. * @return 0 on success.
  16594. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  16595. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16596. * is invalid.
  16597. * @return MEMORY_E on dynamic memory allocation failure.
  16598. */
  16599. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  16600. {
  16601. #ifndef WOLFSSL_ASN_TEMPLATE
  16602. word32 idx = 0;
  16603. int length;
  16604. int ret;
  16605. WOLFSSL_ENTER("DecodeKeyUsage");
  16606. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  16607. if (ret != 0)
  16608. return ret;
  16609. if (length == 0 || length > 2)
  16610. return ASN_PARSE_E;
  16611. cert->extKeyUsage = (word16)(input[idx]);
  16612. if (length == 2)
  16613. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  16614. return 0;
  16615. #else
  16616. ASNGetData dataASN[keyUsageASN_Length];
  16617. word32 idx = 0;
  16618. WOLFSSL_ENTER("DecodeKeyUsage");
  16619. /* Clear dynamic data and set where to store extended key usage. */
  16620. XMEMSET(dataASN, 0, sizeof(dataASN));
  16621. GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
  16622. /* Parse key usage. */
  16623. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  16624. &idx, sz);
  16625. #endif /* WOLFSSL_ASN_TEMPLATE */
  16626. }
  16627. #ifdef WOLFSSL_ASN_TEMPLATE
  16628. /* ASN.1 template for KeyPurposeId.
  16629. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  16630. */
  16631. static const ASNItem keyPurposeIdASN[] = {
  16632. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  16633. };
  16634. enum {
  16635. KEYPURPOSEIDASN_IDX_OID = 0
  16636. };
  16637. /* Number of items in ASN.1 template for KeyPurposeId. */
  16638. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  16639. #endif
  16640. /* Decode extended key usage extension in a certificate.
  16641. *
  16642. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  16643. *
  16644. * @param [in] input Buffer holding data.
  16645. * @param [in] sz Size of data in buffer.
  16646. * @param [in, out] cert Certificate object.
  16647. * @return 0 on success.
  16648. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  16649. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16650. * is invalid.
  16651. * @return MEMORY_E on dynamic memory allocation failure.
  16652. */
  16653. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  16654. {
  16655. #ifndef WOLFSSL_ASN_TEMPLATE
  16656. word32 idx = 0, oid;
  16657. int length, ret;
  16658. WOLFSSL_ENTER("DecodeExtKeyUsage");
  16659. if (GetSequence(input, &idx, &length, sz) < 0) {
  16660. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16661. return ASN_PARSE_E;
  16662. }
  16663. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16664. cert->extExtKeyUsageSrc = input + idx;
  16665. cert->extExtKeyUsageSz = length;
  16666. #endif
  16667. while (idx < (word32)sz) {
  16668. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  16669. if (ret == ASN_UNKNOWN_OID_E)
  16670. continue;
  16671. else if (ret < 0)
  16672. return ret;
  16673. switch (oid) {
  16674. case EKU_ANY_OID:
  16675. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  16676. break;
  16677. case EKU_SERVER_AUTH_OID:
  16678. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  16679. break;
  16680. case EKU_CLIENT_AUTH_OID:
  16681. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  16682. break;
  16683. case EKU_CODESIGNING_OID:
  16684. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  16685. break;
  16686. case EKU_EMAILPROTECT_OID:
  16687. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  16688. break;
  16689. case EKU_TIMESTAMP_OID:
  16690. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  16691. break;
  16692. case EKU_OCSP_SIGN_OID:
  16693. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  16694. break;
  16695. #ifdef WOLFSSL_WOLFSSH
  16696. case EKU_SSH_CLIENT_AUTH_OID:
  16697. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  16698. break;
  16699. case EKU_SSH_MSCL_OID:
  16700. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  16701. break;
  16702. case EKU_SSH_KP_CLIENT_AUTH_OID:
  16703. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  16704. break;
  16705. #endif /* WOLFSSL_WOLFSSH */
  16706. default:
  16707. break;
  16708. }
  16709. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16710. cert->extExtKeyUsageCount++;
  16711. #endif
  16712. }
  16713. return 0;
  16714. #else
  16715. word32 idx = 0;
  16716. int length;
  16717. int ret = 0;
  16718. WOLFSSL_ENTER("DecodeExtKeyUsage");
  16719. /* Strip SEQUENCE OF and expect to account for all the data. */
  16720. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  16721. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16722. ret = ASN_PARSE_E;
  16723. }
  16724. if (ret == 0) {
  16725. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16726. /* Keep reference for WOLFSSL_X509. */
  16727. cert->extExtKeyUsageSrc = input + idx;
  16728. cert->extExtKeyUsageSz = length;
  16729. #endif
  16730. }
  16731. /* Check all OIDs. */
  16732. while ((ret == 0) && (idx < (word32)sz)) {
  16733. ASNGetData dataASN[keyPurposeIdASN_Length];
  16734. /* Clear dynamic data items and set OID type expected. */
  16735. XMEMSET(dataASN, 0, sizeof(dataASN));
  16736. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  16737. /* Decode KeyPurposeId. */
  16738. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  16739. input, &idx, sz);
  16740. /* Skip unknown OIDs. */
  16741. if (ret == ASN_UNKNOWN_OID_E) {
  16742. ret = 0;
  16743. }
  16744. else if (ret == 0) {
  16745. /* Store the bit for the OID. */
  16746. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  16747. case EKU_ANY_OID:
  16748. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  16749. break;
  16750. case EKU_SERVER_AUTH_OID:
  16751. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  16752. break;
  16753. case EKU_CLIENT_AUTH_OID:
  16754. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  16755. break;
  16756. case EKU_CODESIGNING_OID:
  16757. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  16758. break;
  16759. case EKU_EMAILPROTECT_OID:
  16760. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  16761. break;
  16762. case EKU_TIMESTAMP_OID:
  16763. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  16764. break;
  16765. case EKU_OCSP_SIGN_OID:
  16766. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  16767. break;
  16768. }
  16769. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  16770. /* Keep count for WOLFSSL_X509. */
  16771. cert->extExtKeyUsageCount++;
  16772. #endif
  16773. }
  16774. }
  16775. return ret;
  16776. #endif /* WOLFSSL_ASN_TEMPLATE */
  16777. }
  16778. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  16779. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  16780. {
  16781. word32 idx = 0;
  16782. int len = 0;
  16783. WOLFSSL_ENTER("DecodeNsCertType");
  16784. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  16785. return ASN_PARSE_E;
  16786. /* Don't need to worry about unused bits as CheckBitString makes sure
  16787. * they're zero. */
  16788. if (idx < (word32)sz)
  16789. cert->nsCertType = input[idx];
  16790. else
  16791. return ASN_PARSE_E;
  16792. return 0;
  16793. }
  16794. #endif
  16795. #ifndef IGNORE_NAME_CONSTRAINTS
  16796. #ifdef WOLFSSL_ASN_TEMPLATE
  16797. /* ASN.1 template for GeneralSubtree.
  16798. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  16799. */
  16800. static const ASNItem subTreeASN[] = {
  16801. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16802. /* base GeneralName */
  16803. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16804. /* minimum BaseDistance DEFAULT 0*/
  16805. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  16806. /* maximum BaseDistance OPTIONAL */
  16807. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  16808. };
  16809. enum {
  16810. SUBTREEASN_IDX_SEQ = 0,
  16811. SUBTREEASN_IDX_BASE,
  16812. SUBTREEASN_IDX_MIN,
  16813. SUBTREEASN_IDX_MAX
  16814. };
  16815. /* Number of items in ASN.1 template for GeneralSubtree. */
  16816. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  16817. #endif
  16818. #ifdef WOLFSSL_ASN_TEMPLATE
  16819. /* Decode the Subtree's GeneralName.
  16820. *
  16821. * @param [in] input Buffer holding data.
  16822. * @param [in] sz Size of data in buffer.
  16823. * @param [in] tag BER tag on GeneralName.
  16824. * @param [in, out] head Linked list of subtree names.
  16825. * @param [in] heap Dynamic memory hint.
  16826. * @return 0 on success.
  16827. * @return MEMORY_E when dynamic memory allocation fails.
  16828. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  16829. */
  16830. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  16831. Base_entry** head, void* heap)
  16832. {
  16833. Base_entry* entry;
  16834. word32 nameIdx = 0;
  16835. word32 len = sz;
  16836. int strLen;
  16837. int ret = 0;
  16838. (void)heap;
  16839. /* if constructed has leading sequence */
  16840. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  16841. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  16842. if (ret < 0) {
  16843. ret = ASN_PARSE_E;
  16844. }
  16845. else {
  16846. len = (word32)strLen;
  16847. ret = 0;
  16848. }
  16849. }
  16850. if (ret == 0) {
  16851. /* TODO: consider one malloc. */
  16852. /* Allocate Base Entry object. */
  16853. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  16854. DYNAMIC_TYPE_ALTNAME);
  16855. if (entry == NULL) {
  16856. ret = MEMORY_E;
  16857. }
  16858. }
  16859. if (ret == 0) {
  16860. /* Allocate name. */
  16861. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  16862. if (entry->name == NULL) {
  16863. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  16864. ret = MEMORY_E;
  16865. }
  16866. }
  16867. if (ret == 0) {
  16868. /* Store name, size and tag in object. */
  16869. XMEMCPY(entry->name, &input[nameIdx], len);
  16870. entry->name[len] = '\0';
  16871. entry->nameSz = (int)len;
  16872. entry->type = tag & ASN_TYPE_MASK;
  16873. /* Put entry at front of linked list. */
  16874. entry->next = *head;
  16875. *head = entry;
  16876. }
  16877. return ret;
  16878. }
  16879. #endif
  16880. /* Decode a subtree of a name constraints in a certificate.
  16881. *
  16882. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  16883. *
  16884. * @param [in] input Buffer holding data.
  16885. * @param [in] sz Size of data in buffer.
  16886. * @param [in, out] head Linked list of subtree names.
  16887. * @param [in] heap Dynamic memory hint.
  16888. * @return 0 on success.
  16889. * @return MEMORY_E when dynamic memory allocation fails.
  16890. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  16891. */
  16892. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  16893. void* heap)
  16894. {
  16895. #ifndef WOLFSSL_ASN_TEMPLATE
  16896. word32 idx = 0;
  16897. int ret = 0;
  16898. (void)heap;
  16899. while (idx < (word32)sz) {
  16900. int seqLength, strLength;
  16901. word32 nameIdx;
  16902. byte b, bType;
  16903. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  16904. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  16905. return ASN_PARSE_E;
  16906. }
  16907. if (idx >= (word32)sz) {
  16908. WOLFSSL_MSG("\tfail: expecting tag");
  16909. return ASN_PARSE_E;
  16910. }
  16911. nameIdx = idx;
  16912. b = input[nameIdx++];
  16913. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  16914. WOLFSSL_MSG("\tinvalid length");
  16915. return ASN_PARSE_E;
  16916. }
  16917. /* Get type, LSB 4-bits */
  16918. bType = (byte)(b & ASN_TYPE_MASK);
  16919. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  16920. bType == ASN_DIR_TYPE) {
  16921. Base_entry* entry;
  16922. /* if constructed has leading sequence */
  16923. if (b & ASN_CONSTRUCTED) {
  16924. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  16925. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  16926. return ASN_PARSE_E;
  16927. }
  16928. }
  16929. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  16930. DYNAMIC_TYPE_ALTNAME);
  16931. if (entry == NULL) {
  16932. WOLFSSL_MSG("allocate error");
  16933. return MEMORY_E;
  16934. }
  16935. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  16936. DYNAMIC_TYPE_ALTNAME);
  16937. if (entry->name == NULL) {
  16938. WOLFSSL_MSG("allocate error");
  16939. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  16940. return MEMORY_E;
  16941. }
  16942. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  16943. entry->name[strLength] = '\0';
  16944. entry->nameSz = strLength;
  16945. entry->type = bType;
  16946. entry->next = *head;
  16947. *head = entry;
  16948. }
  16949. idx += (word32)seqLength;
  16950. }
  16951. return ret;
  16952. #else
  16953. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  16954. word32 idx = 0;
  16955. int ret = 0;
  16956. (void)heap;
  16957. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  16958. /* Process all subtrees. */
  16959. while ((ret == 0) && (idx < (word32)sz)) {
  16960. byte minVal = 0;
  16961. byte maxVal = 0;
  16962. /* Clear dynamic data and set choice for GeneralName and location to
  16963. * store minimum and maximum.
  16964. */
  16965. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  16966. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  16967. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  16968. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  16969. /* Parse GeneralSubtree. */
  16970. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  16971. &idx, sz);
  16972. if (ret == 0) {
  16973. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  16974. /* Check GeneralName tag is one of the types we can handle. */
  16975. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  16976. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  16977. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16978. /* Parse the general name and store a new entry. */
  16979. ret = DecodeSubtreeGeneralName(input +
  16980. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  16981. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  16982. }
  16983. /* Skip entry. */
  16984. }
  16985. }
  16986. FREE_ASNGETDATA(dataASN, heap);
  16987. return ret;
  16988. #endif
  16989. }
  16990. #ifdef WOLFSSL_ASN_TEMPLATE
  16991. /* ASN.1 template for NameConstraints.
  16992. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  16993. */
  16994. static const ASNItem nameConstraintsASN[] = {
  16995. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16996. /* permittedSubtrees */
  16997. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  16998. /* excludededSubtrees */
  16999. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17000. };
  17001. enum {
  17002. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  17003. NAMECONSTRAINTSASN_IDX_PERMIT,
  17004. NAMECONSTRAINTSASN_IDX_EXCLUDE
  17005. };
  17006. /* Number of items in ASN.1 template for NameConstraints. */
  17007. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  17008. #endif
  17009. /* Decode name constraints extension in a certificate.
  17010. *
  17011. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17012. *
  17013. * @param [in] input Buffer holding data.
  17014. * @param [in] sz Size of data in buffer.
  17015. * @param [in, out] cert Certificate object.
  17016. * @return 0 on success.
  17017. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17018. * is invalid.
  17019. * @return MEMORY_E on dynamic memory allocation failure.
  17020. */
  17021. static int DecodeNameConstraints(const byte* input, word32 sz,
  17022. DecodedCert* cert)
  17023. {
  17024. #ifndef WOLFSSL_ASN_TEMPLATE
  17025. word32 idx = 0;
  17026. int length = 0;
  17027. WOLFSSL_ENTER("DecodeNameConstraints");
  17028. if (GetSequence(input, &idx, &length, sz) < 0) {
  17029. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17030. return ASN_PARSE_E;
  17031. }
  17032. while (idx < (word32)sz) {
  17033. byte b = input[idx++];
  17034. Base_entry** subtree = NULL;
  17035. if (GetLength(input, &idx, &length, sz) <= 0) {
  17036. WOLFSSL_MSG("\tinvalid length");
  17037. return ASN_PARSE_E;
  17038. }
  17039. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17040. subtree = &cert->permittedNames;
  17041. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17042. subtree = &cert->excludedNames;
  17043. else {
  17044. WOLFSSL_MSG("\tinvalid subtree");
  17045. return ASN_PARSE_E;
  17046. }
  17047. if (DecodeSubtree(input + idx, (word32)length, subtree,
  17048. cert->heap) < 0) {
  17049. WOLFSSL_MSG("\terror parsing subtree");
  17050. return ASN_PARSE_E;
  17051. }
  17052. idx += (word32)length;
  17053. }
  17054. return 0;
  17055. #else
  17056. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17057. word32 idx = 0;
  17058. int ret = 0;
  17059. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17060. if (ret == 0) {
  17061. /* Parse NameConstraints. */
  17062. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17063. nameConstraintsASN_Length, 1, input, &idx, sz);
  17064. }
  17065. if (ret == 0) {
  17066. /* If there was a permittedSubtrees then parse it. */
  17067. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17068. ret = DecodeSubtree(
  17069. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17070. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17071. &cert->permittedNames, cert->heap);
  17072. }
  17073. }
  17074. if (ret == 0) {
  17075. /* If there was a excludedSubtrees then parse it. */
  17076. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17077. ret = DecodeSubtree(
  17078. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17079. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17080. &cert->excludedNames, cert->heap);
  17081. }
  17082. }
  17083. FREE_ASNGETDATA(dataASN, cert->heap);
  17084. return ret;
  17085. #endif /* WOLFSSL_ASN_TEMPLATE */
  17086. }
  17087. #endif /* IGNORE_NAME_CONSTRAINTS */
  17088. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17089. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17090. /* Decode ITU-T X.690 OID format to a string representation
  17091. * return string length */
  17092. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17093. {
  17094. word32 val, inIdx = 0, outIdx = 0;
  17095. int w = 0;
  17096. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17097. return BAD_FUNC_ARG;
  17098. /* The first byte expands into b/40 dot b%40. */
  17099. val = in[inIdx++];
  17100. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17101. if (w < 0) {
  17102. w = BUFFER_E;
  17103. goto exit;
  17104. }
  17105. outIdx += w;
  17106. val = 0;
  17107. while (inIdx < inSz && outIdx < outSz) {
  17108. /* extract the next OID digit from in to val */
  17109. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17110. if (in[inIdx] & 0x80) {
  17111. val += in[inIdx] & 0x7F;
  17112. val *= 128;
  17113. }
  17114. else {
  17115. /* write val as text into out */
  17116. val += in[inIdx];
  17117. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17118. if (w < 0 || (word32)w > outSz - outIdx) {
  17119. w = BUFFER_E;
  17120. goto exit;
  17121. }
  17122. outIdx += w;
  17123. val = 0;
  17124. }
  17125. inIdx++;
  17126. }
  17127. if (outIdx == outSz)
  17128. outIdx--;
  17129. out[outIdx] = 0;
  17130. w = (int)outIdx;
  17131. exit:
  17132. return w;
  17133. }
  17134. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  17135. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  17136. #ifdef WOLFSSL_ASN_TEMPLATE
  17137. /* ASN.1 template for PolicyInformation.
  17138. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  17139. */
  17140. static const ASNItem policyInfoASN[] = {
  17141. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17142. /* policyIdentifier */
  17143. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17144. /* policyQualifiers */
  17145. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  17146. };
  17147. enum {
  17148. POLICYINFOASN_IDX_SEQ = 0,
  17149. POLICYINFOASN_IDX_ID,
  17150. POLICYINFOASN_IDX_QUALI
  17151. };
  17152. /* Number of items in ASN.1 template for PolicyInformation. */
  17153. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  17154. #endif
  17155. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  17156. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  17157. {
  17158. #ifndef WOLFSSL_ASN_TEMPLATE
  17159. word32 idx = 0;
  17160. word32 oldIdx;
  17161. int policy_length = 0;
  17162. int ret;
  17163. int total_length = 0;
  17164. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17165. !defined(WOLFSSL_DUP_CERTPOL)
  17166. int i;
  17167. #endif
  17168. WOLFSSL_ENTER("DecodeCertPolicy");
  17169. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17170. /* Check if cert is null before dereferencing below */
  17171. if (cert == NULL)
  17172. return BAD_FUNC_ARG;
  17173. #else
  17174. (void)cert;
  17175. #endif
  17176. #if defined(WOLFSSL_CERT_EXT)
  17177. cert->extCertPoliciesNb = 0;
  17178. #endif
  17179. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  17180. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  17181. return ASN_PARSE_E;
  17182. }
  17183. /* Validate total length */
  17184. if (total_length > (int)(sz - idx)) {
  17185. WOLFSSL_MSG("\tCertPolicy length mismatch");
  17186. return ASN_PARSE_E;
  17187. }
  17188. /* Unwrap certificatePolicies */
  17189. do {
  17190. int length = 0;
  17191. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  17192. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  17193. return ASN_PARSE_E;
  17194. }
  17195. oldIdx = idx;
  17196. ret = GetASNObjectId(input, &idx, &length, sz);
  17197. if (ret != 0)
  17198. return ret;
  17199. policy_length -= (int)(idx - oldIdx);
  17200. if (length > 0) {
  17201. /* Verify length won't overrun buffer */
  17202. if (length > (int)(sz - idx)) {
  17203. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  17204. return ASN_PARSE_E;
  17205. }
  17206. #if defined(WOLFSSL_SEP)
  17207. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  17208. DYNAMIC_TYPE_X509_EXT);
  17209. if (cert->deviceType == NULL) {
  17210. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17211. return MEMORY_E;
  17212. }
  17213. cert->deviceTypeSz = length;
  17214. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  17215. break;
  17216. #elif defined(WOLFSSL_CERT_EXT)
  17217. /* decode cert policy */
  17218. if (DecodePolicyOID(cert->extCertPolicies[
  17219. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  17220. input + idx, length) <= 0) {
  17221. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17222. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17223. return ASN_PARSE_E;
  17224. }
  17225. #ifndef WOLFSSL_DUP_CERTPOL
  17226. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17227. * NOT appear more than once in a certificate policies
  17228. * extension". This is a sanity check for duplicates.
  17229. * extCertPolicies should only have OID values, additional
  17230. * qualifiers need to be stored in a separate array. */
  17231. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  17232. if (XMEMCMP(cert->extCertPolicies[i],
  17233. cert->extCertPolicies[cert->extCertPoliciesNb],
  17234. MAX_CERTPOL_SZ) == 0) {
  17235. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17236. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17237. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17238. return CERTPOLICIES_E;
  17239. }
  17240. }
  17241. #endif /* !WOLFSSL_DUP_CERTPOL */
  17242. cert->extCertPoliciesNb++;
  17243. #else
  17244. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17245. return 0;
  17246. #endif
  17247. }
  17248. idx += (word32)policy_length;
  17249. } while((int)idx < total_length
  17250. #if defined(WOLFSSL_CERT_EXT)
  17251. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  17252. #endif
  17253. );
  17254. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17255. return 0;
  17256. #else /* WOLFSSL_ASN_TEMPLATE */
  17257. word32 idx = 0;
  17258. int ret = 0;
  17259. int total_length = 0;
  17260. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17261. !defined(WOLFSSL_DUP_CERTPOL)
  17262. int i;
  17263. #endif
  17264. WOLFSSL_ENTER("DecodeCertPolicy");
  17265. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17266. /* Check if cert is null before dereferencing below */
  17267. if (cert == NULL)
  17268. ret = BAD_FUNC_ARG;
  17269. #endif
  17270. if (ret == 0) {
  17271. #if defined(WOLFSSL_CERT_EXT)
  17272. cert->extCertPoliciesNb = 0;
  17273. #endif
  17274. /* Strip SEQUENCE OF and check using all data. */
  17275. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  17276. {
  17277. ret = ASN_PARSE_E;
  17278. }
  17279. }
  17280. /* Unwrap certificatePolicies */
  17281. while ((ret == 0) && ((int)idx < total_length)
  17282. #if defined(WOLFSSL_CERT_EXT)
  17283. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  17284. #endif
  17285. ) {
  17286. ASNGetData dataASN[policyInfoASN_Length];
  17287. byte* data = NULL;
  17288. word32 length = 0;
  17289. /* Clear dynamic data and check OID is a cert policy type. */
  17290. XMEMSET(dataASN, 0, sizeof(dataASN));
  17291. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  17292. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  17293. input, &idx, (word32)sz);
  17294. if (ret == 0) {
  17295. /* Get the OID. */
  17296. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  17297. if (length == 0) {
  17298. ret = ASN_PARSE_E;
  17299. }
  17300. }
  17301. #if defined(WOLFSSL_SEP)
  17302. /* Store OID in device type. */
  17303. if (ret == 0) {
  17304. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17305. DYNAMIC_TYPE_X509_EXT);
  17306. if (cert->deviceType == NULL) {
  17307. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17308. ret = MEMORY_E;
  17309. }
  17310. }
  17311. if (ret == 0) {
  17312. /* Store device type data and length. */
  17313. cert->deviceTypeSz = (int)length;
  17314. XMEMCPY(cert->deviceType, data, length);
  17315. break;
  17316. }
  17317. #elif defined(WOLFSSL_CERT_EXT)
  17318. if (ret == 0) {
  17319. /* Decode cert policy. */
  17320. if (DecodePolicyOID(
  17321. cert->extCertPolicies[cert->extCertPoliciesNb],
  17322. MAX_CERTPOL_SZ, data, length) <= 0) {
  17323. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17324. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17325. ret = ASN_PARSE_E;
  17326. }
  17327. }
  17328. #ifndef WOLFSSL_DUP_CERTPOL
  17329. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17330. * NOT appear more than once in a certificate policies
  17331. * extension". This is a sanity check for duplicates.
  17332. * extCertPolicies should only have OID values, additional
  17333. * qualifiers need to be stored in a seperate array. */
  17334. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  17335. if (XMEMCMP(cert->extCertPolicies[i],
  17336. cert->extCertPolicies[cert->extCertPoliciesNb],
  17337. MAX_CERTPOL_SZ) == 0) {
  17338. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17339. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17340. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17341. ret = CERTPOLICIES_E;
  17342. }
  17343. }
  17344. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  17345. if (ret == 0) {
  17346. /* Keep count of policies seen. */
  17347. cert->extCertPoliciesNb++;
  17348. }
  17349. #else
  17350. (void)data;
  17351. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17352. break;
  17353. #endif
  17354. }
  17355. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17356. return ret;
  17357. #endif /* WOLFSSL_ASN_TEMPLATE */
  17358. }
  17359. #endif /* WOLFSSL_SEP */
  17360. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17361. #ifdef WOLFSSL_ASN_TEMPLATE
  17362. /* ASN.1 template for subject dir attribute.
  17363. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17364. */
  17365. static const ASNItem subjDirAttrASN[] = {
  17366. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17367. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  17368. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  17369. };
  17370. enum {
  17371. SUBJDIRATTRASN_IDX_SEQ = 0,
  17372. SUBJDIRATTRASN_IDX_OID,
  17373. SUBJDIRATTRASN_IDX_SET,
  17374. };
  17375. /* Number of items in ASN.1 template for BasicContraints. */
  17376. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  17377. #endif
  17378. /* Decode subject directory attributes extension in a certificate.
  17379. *
  17380. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17381. *
  17382. * @param [in] input Buffer holding data.
  17383. * @param [in] sz Size of data in buffer.
  17384. * @param [in, out] cert Certificate object.
  17385. * @return 0 on success.
  17386. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17387. * is invalid.
  17388. */
  17389. static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
  17390. {
  17391. #ifndef WOLFSSL_ASN_TEMPLATE
  17392. word32 idx = 0;
  17393. int length = 0;
  17394. int ret = 0;
  17395. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17396. #ifdef OPENSSL_ALL
  17397. cert->extSubjDirAttrSrc = input;
  17398. cert->extSubjDirAttrSz = sz;
  17399. #endif /* OPENSSL_ALL */
  17400. /* Unwrap the list of Attributes */
  17401. if (GetSequence(input, &idx, &length, sz) < 0)
  17402. return ASN_PARSE_E;
  17403. if (length == 0) {
  17404. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  17405. If the subjectDirectoryAttributes extension is present, the
  17406. sequence MUST contain at least one entry. */
  17407. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17408. return ASN_PARSE_E;
  17409. }
  17410. /* length is the length of the list contents */
  17411. while (idx < (word32)sz) {
  17412. word32 oid;
  17413. if (GetSequence(input, &idx, &length, sz) < 0)
  17414. return ASN_PARSE_E;
  17415. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  17416. return ASN_PARSE_E;
  17417. if (GetSet(input, &idx, &length, sz) < 0)
  17418. return ASN_PARSE_E;
  17419. /* There may be more than one countryOfCitizenship, but save the
  17420. * first one for now. */
  17421. if (oid == SDA_COC_OID) {
  17422. byte tag;
  17423. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  17424. return ASN_PARSE_E;
  17425. if (length != COUNTRY_CODE_LEN)
  17426. return ASN_PARSE_E;
  17427. if (tag == ASN_PRINTABLE_STRING) {
  17428. XMEMCPY(cert->countryOfCitizenship,
  17429. input + idx, COUNTRY_CODE_LEN);
  17430. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17431. }
  17432. }
  17433. idx += length;
  17434. }
  17435. return ret;
  17436. #else
  17437. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  17438. int ret = 0;
  17439. word32 idx = 0;
  17440. int length;
  17441. WOLFSSL_ENTER("DecodeSubjDirAttr");
  17442. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  17443. /* Strip outer SEQUENCE. */
  17444. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  17445. ret = ASN_PARSE_E;
  17446. }
  17447. /* Handle each inner SEQUENCE. */
  17448. while ((ret == 0) && (idx < (word32)sz)) {
  17449. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  17450. input, &idx, sz);
  17451. /* There may be more than one countryOfCitizenship, but save the
  17452. * first one for now. */
  17453. if ((ret == 0) &&
  17454. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  17455. int cuLen;
  17456. word32 setIdx = 0;
  17457. byte* setData;
  17458. word32 setLen;
  17459. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  17460. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  17461. setLen) < 0) {
  17462. ret = ASN_PARSE_E;
  17463. }
  17464. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  17465. ret = ASN_PARSE_E;
  17466. }
  17467. if (ret == 0) {
  17468. XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
  17469. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  17470. }
  17471. }
  17472. }
  17473. FREE_ASNGETDATA(dataASN, cert->heap);
  17474. return ret;
  17475. #endif /* WOLFSSL_ASN_TEMPLATE */
  17476. }
  17477. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  17478. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17479. /* Decode subject infomation access extension in a certificate.
  17480. *
  17481. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  17482. *
  17483. * @param [in] input Buffer holding data.
  17484. * @param [in] sz Size of data in buffer.
  17485. * @param [in, out] cert Certificate object.
  17486. * @return 0 on success.
  17487. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17488. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17489. * is invalid.
  17490. * @return MEMORY_E on dynamic memory allocation failure.
  17491. */
  17492. static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
  17493. {
  17494. word32 idx = 0;
  17495. int length = 0;
  17496. int ret = 0;
  17497. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  17498. #ifdef OPENSSL_ALL
  17499. cert->extSubjAltNameSrc = input;
  17500. cert->extSubjAltNameSz = sz;
  17501. #endif /* OPENSSL_ALL */
  17502. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  17503. if (GetSequence(input, &idx, &length, sz) < 0)
  17504. return ASN_PARSE_E;
  17505. if (length == 0) {
  17506. /* RFC 5280 4.2.2.2. Subject Information Access
  17507. If the subjectInformationAccess extension is present, the
  17508. sequence MUST contain at least one entry. */
  17509. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17510. return ASN_PARSE_E;
  17511. }
  17512. /* Per fpkx-x509-cert-profile-common... section 5.3.
  17513. * [The] subjectInfoAccess extension must contain at least one
  17514. * instance of the id-ad-caRepository access method containing a
  17515. * publicly accessible HTTP URI which returns as certs-only
  17516. * CMS.
  17517. */
  17518. while (idx < (word32)sz) {
  17519. word32 oid = 0;
  17520. byte b;
  17521. /* Unwrap an AccessDescription */
  17522. if (GetSequence(input, &idx, &length, sz) < 0)
  17523. return ASN_PARSE_E;
  17524. /* Get the accessMethod */
  17525. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  17526. return ASN_PARSE_E;
  17527. /* Only supporting URIs right now. */
  17528. if (GetASNTag(input, &idx, &b, sz) < 0)
  17529. return ASN_PARSE_E;
  17530. if (GetLength(input, &idx, &length, sz) < 0)
  17531. return ASN_PARSE_E;
  17532. /* Set caRepo entry */
  17533. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  17534. cert->extSubjInfoAccCaRepoSz = length;
  17535. cert->extSubjInfoAccCaRepo = input + idx;
  17536. break;
  17537. }
  17538. idx += length;
  17539. }
  17540. if (cert->extSubjInfoAccCaRepo == NULL ||
  17541. cert->extSubjInfoAccCaRepoSz == 0) {
  17542. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  17543. ret = ASN_PARSE_E;
  17544. }
  17545. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  17546. return ret;
  17547. }
  17548. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  17549. /* Macro to check if bit is set, if not sets and return success.
  17550. Otherwise returns failure */
  17551. /* Macro required here because bit-field operation */
  17552. #ifndef WOLFSSL_NO_ASN_STRICT
  17553. #define VERIFY_AND_SET_OID(bit) \
  17554. if ((bit) == 0) \
  17555. (bit) = 1; \
  17556. else \
  17557. return ASN_OBJECT_ID_E;
  17558. #else
  17559. /* With no strict defined, the verify is skipped */
  17560. #define VERIFY_AND_SET_OID(bit) bit = 1;
  17561. #endif
  17562. /* Parse extension type specific data based on OID sum.
  17563. *
  17564. * Supported extensions:
  17565. * Basic Constraints - BASIC_CA_OID
  17566. * CRL Distribution Points - CRL_DIST_OID
  17567. * Authority Information Access - AUTH_INFO_OID
  17568. * Subject Alternative Name - ALT_NAMES_OID
  17569. * Authority Key Identifier - AUTH_KEY_OID
  17570. * Subject Key Identifier - SUBJ_KEY_OID
  17571. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  17572. * Key Usage - KEY_USAGE_OID
  17573. * Extended Key Usage - EXT_KEY_USAGE_OID
  17574. * Name Constraints - NAME_CONS_OID
  17575. * Inhibit anyPolicy - INHIBIT_ANY_OID
  17576. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  17577. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  17578. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  17579. * Subject Information Access - SUBJ_INFO_ACC_OID
  17580. * Unsupported extensions from RFC 5280:
  17581. * 4.2.1.5 - Policy mappings
  17582. * 4.2.1.7 - Issuer Alternative Name
  17583. * 4.2.1.11 - Policy Constraints
  17584. * 4.2.1.15 - Freshest CRL
  17585. *
  17586. * @param [in] input Buffer containing extension type specific data.
  17587. * @param [in] length Length of data.
  17588. * @param [in] oid OID sum for extension.
  17589. * @param [in] critical Whether extension is critical.
  17590. * @param [in, out] cert Certificate object.
  17591. * @return 0 on success.
  17592. * @return ASN_PARSE_E when BER encoding is invalid.
  17593. * @return MEMORY_E on dynamic memory allocation failure.
  17594. * @return Other negative values on error.
  17595. */
  17596. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  17597. byte critical, DecodedCert* cert,
  17598. int *isUnknownExt)
  17599. {
  17600. int ret = 0;
  17601. word32 idx = 0;
  17602. if (isUnknownExt != NULL)
  17603. *isUnknownExt = 0;
  17604. switch (oid) {
  17605. /* Basic Constraints. */
  17606. case BASIC_CA_OID:
  17607. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  17608. cert->extBasicConstCrit = critical ? 1 : 0;
  17609. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  17610. ret = ASN_PARSE_E;
  17611. }
  17612. break;
  17613. /* CRL Distribution point. */
  17614. case CRL_DIST_OID:
  17615. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  17616. cert->extCRLdistCrit = critical ? 1 : 0;
  17617. if (DecodeCrlDist(input, length, cert) < 0) {
  17618. ret = ASN_PARSE_E;
  17619. }
  17620. break;
  17621. /* Authority information access. */
  17622. case AUTH_INFO_OID:
  17623. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  17624. cert->extAuthInfoCrit = critical ? 1 : 0;
  17625. if (DecodeAuthInfo(input, length, cert) < 0) {
  17626. ret = ASN_PARSE_E;
  17627. }
  17628. break;
  17629. /* Subject alternative name. */
  17630. case ALT_NAMES_OID:
  17631. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  17632. cert->extSubjAltNameCrit = critical ? 1 : 0;
  17633. ret = DecodeAltNames(input, length, cert);
  17634. break;
  17635. /* Authority Key Identifier. */
  17636. case AUTH_KEY_OID:
  17637. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  17638. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  17639. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  17640. /* This check is added due to RFC 5280 section 4.2.1.1
  17641. * stating that conforming CA's must mark this extension
  17642. * as non-critical. When parsing extensions check that
  17643. * certificate was made in compliance with this. */
  17644. if (critical) {
  17645. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  17646. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  17647. ret = ASN_CRIT_EXT_E;
  17648. }
  17649. #endif
  17650. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  17651. ret = ASN_PARSE_E;
  17652. }
  17653. break;
  17654. /* Subject Key Identifier. */
  17655. case SUBJ_KEY_OID:
  17656. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  17657. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  17658. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  17659. /* This check is added due to RFC 5280 section 4.2.1.2
  17660. * stating that conforming CA's must mark this extension
  17661. * as non-critical. When parsing extensions check that
  17662. * certificate was made in compliance with this. */
  17663. if (critical) {
  17664. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  17665. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  17666. ret = ASN_CRIT_EXT_E;
  17667. }
  17668. #endif
  17669. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  17670. ret = ASN_PARSE_E;
  17671. }
  17672. break;
  17673. /* Certificate policies. */
  17674. case CERT_POLICY_OID:
  17675. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  17676. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  17677. #if defined(OPENSSL_EXTRA) || \
  17678. defined(OPENSSL_EXTRA_X509_SMALL)
  17679. cert->extCertPolicyCrit = critical ? 1 : 0;
  17680. #endif
  17681. #endif
  17682. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  17683. defined(WOLFSSL_QT)
  17684. if (DecodeCertPolicy(input, length, cert) < 0) {
  17685. ret = ASN_PARSE_E;
  17686. }
  17687. #else
  17688. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  17689. #endif
  17690. break;
  17691. /* Key usage. */
  17692. case KEY_USAGE_OID:
  17693. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  17694. cert->extKeyUsageCrit = critical ? 1 : 0;
  17695. if (DecodeKeyUsage(input, length, cert) < 0) {
  17696. ret = ASN_PARSE_E;
  17697. }
  17698. break;
  17699. /* Extended key usage. */
  17700. case EXT_KEY_USAGE_OID:
  17701. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  17702. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  17703. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  17704. ret = ASN_PARSE_E;
  17705. }
  17706. break;
  17707. #ifndef IGNORE_NAME_CONSTRAINTS
  17708. /* Name constraints. */
  17709. case NAME_CONS_OID:
  17710. #ifndef WOLFSSL_NO_ASN_STRICT
  17711. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  17712. "The name constraints extension,
  17713. which MUST be used only in a CA certificate" */
  17714. if (!cert->isCA) {
  17715. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  17716. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  17717. ret = ASN_NAME_INVALID_E;
  17718. }
  17719. #endif
  17720. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  17721. cert->extNameConstraintCrit = critical ? 1 : 0;
  17722. if (DecodeNameConstraints(input, length, cert) < 0) {
  17723. ret = ASN_PARSE_E;
  17724. }
  17725. break;
  17726. #endif /* IGNORE_NAME_CONSTRAINTS */
  17727. /* Inhibit anyPolicy. */
  17728. case INHIBIT_ANY_OID:
  17729. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  17730. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  17731. break;
  17732. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17733. /* Netscape's certificate type. */
  17734. case NETSCAPE_CT_OID:
  17735. if (DecodeNsCertType(input, (int)length, cert) < 0)
  17736. ret = ASN_PARSE_E;
  17737. break;
  17738. #endif
  17739. #ifdef HAVE_OCSP
  17740. /* OCSP no check. */
  17741. case OCSP_NOCHECK_OID:
  17742. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  17743. ret = GetASNNull(input, &idx, length);
  17744. if (ret != 0) {
  17745. ret = ASN_PARSE_E;
  17746. }
  17747. break;
  17748. #endif
  17749. case POLICY_CONST_OID:
  17750. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  17751. cert->extPolicyConstCrit = critical ? 1 : 0;
  17752. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  17753. return ASN_PARSE_E;
  17754. break;
  17755. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17756. case SUBJ_DIR_ATTR_OID:
  17757. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  17758. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  17759. return ASN_PARSE_E;
  17760. break;
  17761. #endif
  17762. #ifdef WOLFSSL_SUBJ_INFO_ACC
  17763. case SUBJ_INFO_ACC_OID:
  17764. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  17765. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  17766. return ASN_PARSE_E;
  17767. break;
  17768. #endif
  17769. default:
  17770. if (isUnknownExt != NULL)
  17771. *isUnknownExt = 1;
  17772. #ifndef WOLFSSL_NO_ASN_STRICT
  17773. /* While it is a failure to not support critical extensions,
  17774. * still parse the certificate ignoring the unsupported
  17775. * extension to allow caller to accept it with the verify
  17776. * callback. */
  17777. if (critical) {
  17778. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  17779. ret = ASN_CRIT_EXT_E;
  17780. }
  17781. #endif
  17782. break;
  17783. }
  17784. return ret;
  17785. }
  17786. #ifdef WOLFSSL_ASN_TEMPLATE
  17787. /* ASN.1 template for extensions.
  17788. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17789. */
  17790. static const ASNItem certExtHdrASN[] = {
  17791. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  17792. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17793. };
  17794. enum {
  17795. CERTEXTHDRASN_IDX_EXTTAG = 0,
  17796. CERTEXTHDRASN_IDX_EXTSEQ
  17797. };
  17798. /* Number of itesm in ASN.1 template for extensions. */
  17799. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  17800. /* ASN.1 template for Extension.
  17801. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  17802. */
  17803. static const ASNItem certExtASN[] = {
  17804. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17805. /* Extension object id */
  17806. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17807. /* critical - when true, must be parseable. */
  17808. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  17809. /* Data for extension - leave index at start of data. */
  17810. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  17811. };
  17812. enum {
  17813. CERTEXTASN_IDX_SEQ = 0,
  17814. CERTEXTASN_IDX_OID,
  17815. CERTEXTASN_IDX_CRIT,
  17816. CERTEXTASN_IDX_VAL
  17817. };
  17818. /* Number of items in ASN.1 template for Extension. */
  17819. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  17820. #endif
  17821. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  17822. && defined(HAVE_OID_DECODING)
  17823. int wc_SetUnknownExtCallback(DecodedCert* cert,
  17824. wc_UnknownExtCallback cb) {
  17825. if (cert == NULL) {
  17826. return BAD_FUNC_ARG;
  17827. }
  17828. cert->unknownExtCallback = cb;
  17829. return 0;
  17830. }
  17831. #endif
  17832. /*
  17833. * Processing the Certificate Extensions. This does not modify the current
  17834. * index. It is works starting with the recorded extensions pointer.
  17835. */
  17836. static int DecodeCertExtensions(DecodedCert* cert)
  17837. {
  17838. #ifndef WOLFSSL_ASN_TEMPLATE
  17839. int ret = 0;
  17840. word32 idx = 0;
  17841. word32 sz = (word32)cert->extensionsSz;
  17842. const byte* input = cert->extensions;
  17843. int length;
  17844. word32 oid;
  17845. byte critical = 0;
  17846. byte criticalFail = 0;
  17847. byte tag = 0;
  17848. WOLFSSL_ENTER("DecodeCertExtensions");
  17849. if (input == NULL || sz == 0)
  17850. return BAD_FUNC_ARG;
  17851. #ifdef WOLFSSL_CERT_REQ
  17852. if (!cert->isCSR)
  17853. #endif
  17854. { /* Not included in CSR */
  17855. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  17856. return ASN_PARSE_E;
  17857. }
  17858. if (tag != ASN_EXTENSIONS) {
  17859. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  17860. return ASN_PARSE_E;
  17861. }
  17862. if (GetLength(input, &idx, &length, sz) < 0) {
  17863. WOLFSSL_MSG("\tfail: invalid length");
  17864. return ASN_PARSE_E;
  17865. }
  17866. }
  17867. if (GetSequence(input, &idx, &length, sz) < 0) {
  17868. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  17869. return ASN_PARSE_E;
  17870. }
  17871. while (idx < (word32)sz) {
  17872. word32 localIdx;
  17873. if (GetSequence(input, &idx, &length, sz) < 0) {
  17874. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17875. return ASN_PARSE_E;
  17876. }
  17877. oid = 0;
  17878. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  17879. WOLFSSL_MSG("\tfail: OBJECT ID");
  17880. return ret;
  17881. }
  17882. /* check for critical flag */
  17883. critical = 0;
  17884. if ((idx + 1) > (word32)sz) {
  17885. WOLFSSL_MSG("\tfail: malformed buffer");
  17886. return BUFFER_E;
  17887. }
  17888. localIdx = idx;
  17889. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  17890. if (tag == ASN_BOOLEAN) {
  17891. ret = GetBoolean(input, &idx, sz);
  17892. if (ret < 0) {
  17893. WOLFSSL_MSG("\tfail: critical boolean");
  17894. return ret;
  17895. }
  17896. critical = (byte)ret;
  17897. }
  17898. }
  17899. /* process the extension based on the OID */
  17900. ret = GetOctetString(input, &idx, &length, sz);
  17901. if (ret < 0) {
  17902. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  17903. return ret;
  17904. }
  17905. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  17906. cert, NULL);
  17907. if (ret == ASN_CRIT_EXT_E) {
  17908. ret = 0;
  17909. criticalFail = 1;
  17910. }
  17911. if (ret < 0)
  17912. goto end;
  17913. idx += (word32)length;
  17914. }
  17915. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  17916. end:
  17917. return ret;
  17918. #else
  17919. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  17920. ASNGetData dataExtsASN[certExtHdrASN_Length];
  17921. int ret = 0;
  17922. const byte* input = cert->extensions;
  17923. int sz = cert->extensionsSz;
  17924. word32 idx = 0;
  17925. int criticalRet = 0;
  17926. int offset = 0;
  17927. WOLFSSL_ENTER("DecodeCertExtensions");
  17928. if (input == NULL || sz == 0)
  17929. ret = BAD_FUNC_ARG;
  17930. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  17931. #ifdef WOLFSSL_CERT_REQ
  17932. if (cert->isCSR) {
  17933. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  17934. }
  17935. #endif
  17936. if (ret == 0) {
  17937. /* Clear dynamic data. */
  17938. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  17939. /* Parse extensions header. */
  17940. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  17941. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  17942. input, &idx, (word32)sz);
  17943. }
  17944. /* Parse each extension. */
  17945. while ((ret == 0) && (idx < (word32)sz)) {
  17946. byte critical = 0;
  17947. int isUnknownExt = 0;
  17948. /* Clear dynamic data. */
  17949. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  17950. /* Ensure OID is an extention type. */
  17951. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  17952. /* Set criticality variable. */
  17953. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  17954. /* Parse extension wrapper. */
  17955. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  17956. &idx, (word32)sz);
  17957. if (ret == 0) {
  17958. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  17959. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  17960. /* Decode the extension by type. */
  17961. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  17962. &isUnknownExt);
  17963. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  17964. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  17965. word16 decOid[MAX_OID_SZ];
  17966. word32 decOidSz = sizeof(decOid);
  17967. ret = DecodeObjectId(
  17968. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  17969. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  17970. decOid, &decOidSz);
  17971. if (ret != 0) {
  17972. /* Should never get here as the extension was successfully
  17973. * decoded earlier. Something might be corrupted. */
  17974. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  17975. WOLFSSL_ERROR(ret);
  17976. }
  17977. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  17978. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  17979. dataASN[CERTEXTASN_IDX_VAL].length);
  17980. }
  17981. #endif
  17982. (void)isUnknownExt;
  17983. /* Move index on to next extension. */
  17984. idx += length;
  17985. }
  17986. /* Don't fail criticality until all other extensions have been checked.
  17987. */
  17988. if (ret == ASN_CRIT_EXT_E) {
  17989. criticalRet = ASN_CRIT_EXT_E;
  17990. ret = 0;
  17991. }
  17992. }
  17993. if (ret == 0) {
  17994. /* Use criticality return. */
  17995. ret = criticalRet;
  17996. }
  17997. FREE_ASNGETDATA(dataASN, cert->heap);
  17998. return ret;
  17999. #endif
  18000. }
  18001. #ifdef WOLFSSL_ASN_TEMPLATE
  18002. /* ASN template for an X509 certificate.
  18003. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18004. */
  18005. static const ASNItem x509CertASN[] = {
  18006. /* Certificate ::= SEQUENCE */
  18007. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18008. /* tbsCertificate TBSCertificate */
  18009. /* TBSCertificate ::= SEQUENCE */
  18010. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18011. /* version [0] EXPLICT Version DEFAULT v1 */
  18012. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  18013. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  18014. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18015. /* serialNumber CertificateSerialNumber */
  18016. /* CetificateSerialNumber ::= INTEGER */
  18017. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18018. /* signature AlgorithmIdentifier */
  18019. /* AlgorithmIdentifier ::= SEQUENCE */
  18020. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18021. /* Algorithm OBJECT IDENTIFIER */
  18022. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18023. /* parameters ANY defined by algorithm OPTIONAL */
  18024. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18025. #ifdef WC_RSA_PSS
  18026. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18027. #endif
  18028. /* issuer Name */
  18029. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18030. /* validity Validity */
  18031. /* Validity ::= SEQUENCE */
  18032. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18033. /* notBefore Time */
  18034. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18035. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18036. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18037. /* notAfter Time */
  18038. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18039. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18040. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18041. /* subject Name */
  18042. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18043. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18044. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18045. /* algorithm AlgorithmIdentifier */
  18046. /* AlgorithmIdentifier ::= SEQUENCE */
  18047. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18048. /* Algorithm OBJECT IDENTIFIER */
  18049. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18050. /* parameters ANY defined by algorithm OPTIONAL */
  18051. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18052. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18053. #ifdef WC_RSA_PSS
  18054. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18055. #endif
  18056. /* subjectPublicKey BIT STRING */
  18057. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18058. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18059. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18060. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18061. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18062. /* extensions Extensions OPTIONAL */
  18063. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18064. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18065. /* signatureAlgorithm AlgorithmIdentifier */
  18066. /* AlgorithmIdentifier ::= SEQUENCE */
  18067. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18068. /* Algorithm OBJECT IDENTIFIER */
  18069. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18070. /* parameters ANY defined by algorithm OPTIONAL */
  18071. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18072. #ifdef WC_RSA_PSS
  18073. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18074. #endif
  18075. /* signature BIT STRING */
  18076. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18077. };
  18078. enum {
  18079. X509CERTASN_IDX_SEQ = 0,
  18080. X509CERTASN_IDX_TBS_SEQ,
  18081. X509CERTASN_IDX_TBS_VER,
  18082. X509CERTASN_IDX_TBS_VER_INT,
  18083. X509CERTASN_IDX_TBS_SERIAL,
  18084. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  18085. X509CERTASN_IDX_TBS_ALGOID_OID,
  18086. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  18087. #ifdef WC_RSA_PSS
  18088. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  18089. #endif
  18090. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  18091. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  18092. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  18093. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  18094. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  18095. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  18096. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  18097. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  18098. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  18099. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  18100. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  18101. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  18102. #ifdef WC_RSA_PSS
  18103. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  18104. #endif
  18105. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  18106. X509CERTASN_IDX_TBS_ISSUERUID,
  18107. X509CERTASN_IDX_TBS_SUBJECTUID,
  18108. X509CERTASN_IDX_TBS_EXT,
  18109. X509CERTASN_IDX_TBS_EXT_SEQ,
  18110. X509CERTASN_IDX_SIGALGO_SEQ,
  18111. X509CERTASN_IDX_SIGALGO_OID,
  18112. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  18113. #ifdef WC_RSA_PSS
  18114. X509CERTASN_IDX_SIGALGO_PARAMS,
  18115. #endif
  18116. X509CERTASN_IDX_SIGNATURE,
  18117. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  18118. };
  18119. /* Number of items in ASN template for an X509 certificate. */
  18120. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  18121. /* Check the data data.
  18122. *
  18123. * @param [in] dataASN ASN template dynamic data item.
  18124. * @param [in] dataType BEFORE or AFTER date.
  18125. * @return 0 on success.
  18126. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  18127. * @return ASN_DATE_SZ_E when time data is not supported.
  18128. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18129. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18130. */
  18131. static int CheckDate(ASNGetData *dataASN, int dateType)
  18132. {
  18133. int ret = 0;
  18134. /* Check BER tag is valid. */
  18135. if ((dataASN->tag != ASN_UTC_TIME) &&
  18136. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  18137. ret = ASN_TIME_E;
  18138. }
  18139. /* Check date length is valid. */
  18140. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  18141. (dataASN->length < MIN_DATE_SIZE))) {
  18142. ret = ASN_DATE_SZ_E;
  18143. }
  18144. #ifndef NO_ASN_TIME_CHECK
  18145. /* Check date is a valid string and BEFORE or AFTER now. */
  18146. if ((ret == 0) &&
  18147. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  18148. if (dateType == BEFORE) {
  18149. ret = ASN_BEFORE_DATE_E;
  18150. }
  18151. else {
  18152. ret = ASN_AFTER_DATE_E;
  18153. }
  18154. }
  18155. #endif
  18156. (void)dateType;
  18157. return ret;
  18158. }
  18159. /* Decode a certificate. Internal/non-public API.
  18160. *
  18161. * @param [in] cert Certificate object.
  18162. * @param [in] verify Whether to verify dates before and after now.
  18163. * @param [out] criticalExt Critical extension return code.
  18164. * @param [out] badDateRet Bad date return code.
  18165. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  18166. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  18167. * @return 0 on success.
  18168. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18169. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18170. * @return ASN_DATE_SZ_E when time data is not supported.
  18171. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18172. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18173. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18174. * is invalid.
  18175. * @return BUFFER_E when data in buffer is too small.
  18176. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18177. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18178. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18179. * non-zero length.
  18180. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18181. */
  18182. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  18183. int* badDateRet, int stopAtPubKey,
  18184. int stopAfterPubKey)
  18185. {
  18186. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  18187. int ret = 0;
  18188. int badDate = 0;
  18189. byte version;
  18190. word32 idx;
  18191. word32 serialSz;
  18192. const unsigned char* issuer = NULL;
  18193. word32 issuerSz = 0;
  18194. const unsigned char* subject = NULL;
  18195. word32 subjectSz = 0;
  18196. word32 pubKeyOffset = 0;
  18197. word32 pubKeyEnd = 0;
  18198. int done = 0;
  18199. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  18200. if (ret == 0) {
  18201. version = 0;
  18202. serialSz = EXTERNAL_SERIAL_SIZE;
  18203. /* Get the version and put the serial number into the buffer. */
  18204. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  18205. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  18206. &serialSz);
  18207. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  18208. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  18209. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  18210. oidKeyType);
  18211. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  18212. oidCurveType);
  18213. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  18214. /* Parse the X509 certificate. */
  18215. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  18216. cert->source, &cert->srcIdx, cert->maxIdx);
  18217. #ifdef WOLFSSL_CLANG_TIDY
  18218. /* work around clang-tidy false positive re cert->source. */
  18219. if ((ret == 0) && (cert->source == NULL)) {
  18220. ret = ASN_PARSE_E;
  18221. }
  18222. #endif
  18223. }
  18224. /* Check version is valid/supported - can't be negative. */
  18225. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18226. WOLFSSL_MSG("Unexpected certificate version");
  18227. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18228. ret = ASN_PARSE_E;
  18229. }
  18230. if (ret == 0) {
  18231. int i;
  18232. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18233. /* Set fields extracted from data. */
  18234. cert->version = version;
  18235. cert->serialSz = (int)serialSz;
  18236. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  18237. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18238. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  18239. /* No bad date error - don't always care. */
  18240. badDate = 0;
  18241. /* Find the item with the BEFORE date and check it. */
  18242. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  18243. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  18244. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  18245. if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
  18246. badDate = ASN_BEFORE_DATE_E;
  18247. }
  18248. /* Store reference to BEFOREdate. */
  18249. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  18250. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18251. /* Find the item with the AFTER date and check it. */
  18252. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  18253. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  18254. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  18255. if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
  18256. badDate = ASN_AFTER_DATE_E;
  18257. }
  18258. /* Store reference to AFTER date. */
  18259. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  18260. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18261. /* Get the issuer name. */
  18262. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18263. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  18264. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18265. /* Get the subject name. */
  18266. subject = cert->source +
  18267. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18268. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  18269. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18270. }
  18271. if ((ret == 0) && stopAtPubKey) {
  18272. /* Return any bad date error through badDateRet and return offset of
  18273. * subjectPublicKeyInfo.
  18274. */
  18275. if (badDateRet != NULL) {
  18276. *badDateRet = badDate;
  18277. }
  18278. done = 1;
  18279. }
  18280. if ((ret == 0) && (!done)) {
  18281. /* Store the signature information. */
  18282. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18283. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  18284. &cert->signature, &cert->sigLength);
  18285. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  18286. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  18287. != cert->signatureOID) {
  18288. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  18289. ret = ASN_SIG_OID_E;
  18290. }
  18291. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  18292. else if (IsSigAlgoECC(cert->signatureOID)) {
  18293. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  18294. #ifdef WC_RSA_PSS
  18295. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  18296. #endif
  18297. ) {
  18298. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18299. ret = ASN_PARSE_E;
  18300. }
  18301. }
  18302. #ifdef WC_RSA_PSS
  18303. /* Check parameters starting with a SEQUENCE. */
  18304. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  18305. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  18306. word32 sigAlgParamsSz = 0;
  18307. /* Parameters only with RSA PSS. */
  18308. if (oid != CTC_RSASSAPSS) {
  18309. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18310. ret = ASN_PARSE_E;
  18311. }
  18312. if (ret == 0) {
  18313. const byte* tbsParams;
  18314. word32 tbsParamsSz;
  18315. const byte* sigAlgParams;
  18316. /* Check RSA PSS parameters are the same. */
  18317. tbsParams =
  18318. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18319. cert->source);
  18320. tbsParamsSz =
  18321. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18322. cert->source);
  18323. sigAlgParams =
  18324. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18325. cert->source);
  18326. sigAlgParamsSz =
  18327. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18328. cert->source);
  18329. if ((tbsParamsSz != sigAlgParamsSz) ||
  18330. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  18331. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18332. ret = ASN_PARSE_E;
  18333. }
  18334. }
  18335. if (ret == 0) {
  18336. /* Store parameters for use in signature verification. */
  18337. cert->sigParamsIndex =
  18338. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  18339. cert->sigParamsLength = sigAlgParamsSz;
  18340. }
  18341. }
  18342. #endif
  18343. }
  18344. if ((ret == 0) && (!done)) {
  18345. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  18346. if (stopAfterPubKey) {
  18347. /* Return any bad date error through badDateRed and return offset
  18348. * after subjectPublicKeyInfo.
  18349. */
  18350. if (badDateRet != NULL) {
  18351. *badDateRet = badDate;
  18352. }
  18353. done = 1;
  18354. }
  18355. }
  18356. if ((ret == 0) && (!done) &&
  18357. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  18358. #ifndef ALLOW_V1_EXTENSIONS
  18359. /* Certificate extensions were only defined in version 2. */
  18360. if (cert->version < 2) {
  18361. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  18362. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  18363. ret = ASN_VERSION_E;
  18364. }
  18365. #endif
  18366. if (ret == 0) {
  18367. /* Save references to extension data. */
  18368. cert->extensions = GetASNItem_Addr(
  18369. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18370. cert->extensionsSz = (int)GetASNItem_Length(
  18371. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18372. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  18373. /* Advance past extensions. */
  18374. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18375. }
  18376. }
  18377. /* Dispose of memory before allocating for extension decoding. */
  18378. FREE_ASNGETDATA(dataASN, cert->heap);
  18379. if ((ret == 0) && (issuer != NULL)) {
  18380. idx = 0;
  18381. /* Put issuer into cert and calculate hash. */
  18382. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  18383. &idx, issuerSz);
  18384. }
  18385. if ((ret == 0) && (subject != NULL)) {
  18386. idx = 0;
  18387. /* Put subject into cert and calculate hash. */
  18388. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18389. subject, &idx, subjectSz);
  18390. }
  18391. if (ret == 0) {
  18392. /* Determine if self signed by comparing issuer and subject hashes. */
  18393. #ifdef WOLFSSL_CERT_REQ
  18394. if (cert->isCSR) {
  18395. cert->selfSigned = 1;
  18396. }
  18397. else
  18398. #endif
  18399. {
  18400. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  18401. KEYID_SIZE) == 0);
  18402. }
  18403. if (stopAtPubKey) {
  18404. ret = (int)pubKeyOffset;
  18405. }
  18406. }
  18407. if ((ret == 0) && (!stopAtPubKey)) {
  18408. /* Parse the public key. */
  18409. idx = pubKeyOffset;
  18410. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  18411. }
  18412. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  18413. (cert->extensions != NULL)) {
  18414. /* Decode the extension data starting at [3]. */
  18415. ret = DecodeCertExtensions(cert);
  18416. if (criticalExt != NULL) {
  18417. if (ret == ASN_CRIT_EXT_E) {
  18418. /* Return critical extension not recognized. */
  18419. *criticalExt = ret;
  18420. ret = 0;
  18421. }
  18422. else {
  18423. /* No critical extension error. */
  18424. *criticalExt = 0;
  18425. }
  18426. }
  18427. }
  18428. if ((ret == 0) && (!done) && (badDate != 0)) {
  18429. /* Parsed whole certificate fine but return any date errors. */
  18430. ret = badDate;
  18431. }
  18432. return ret;
  18433. }
  18434. /* Decode BER/DER data into certificate object.
  18435. *
  18436. * BER/DER data information held in source, srcIdx and maxIdx fields of
  18437. * certificate object.
  18438. *
  18439. * @param [in] cert Decoded certificate object.
  18440. * @param [in] verify Whether to find CA and verify certificate.
  18441. * @param [in] criticalExt Any error for critical extensions not recognized.
  18442. * @return 0 on success.
  18443. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18444. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18445. * @return ASN_DATE_SZ_E when time data is not supported.
  18446. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18447. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18448. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18449. * is invalid.
  18450. * @return BUFFER_E when data in buffer is too small.
  18451. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18452. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18453. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18454. * non-zero length.
  18455. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18456. */
  18457. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  18458. {
  18459. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  18460. }
  18461. #ifdef WOLFSSL_CERT_REQ
  18462. /* ASN.1 template for certificate request Attribute.
  18463. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  18464. */
  18465. static const ASNItem reqAttrASN[] = {
  18466. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18467. /* type */
  18468. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18469. /* values */
  18470. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  18471. };
  18472. enum {
  18473. REQATTRASN_IDX_SEQ = 0,
  18474. REQATTRASN_IDX_TYPE,
  18475. REQATTRASN_IDX_VALS
  18476. };
  18477. /* Number of items in ASN.1 template for certificate request Attribute. */
  18478. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  18479. /* ASN.1 template for a string choice. */
  18480. static const ASNItem strAttrASN[] = {
  18481. { 0, 0, 0, 0, 0 },
  18482. };
  18483. enum {
  18484. STRATTRASN_IDX_STR = 0
  18485. };
  18486. /* Number of items in ASN.1 template for a string choice. */
  18487. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  18488. /* ASN.1 choices for types for a string in an attribute. */
  18489. static const byte strAttrChoice[] = {
  18490. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  18491. };
  18492. /* Decode a certificate request attribute's value.
  18493. *
  18494. * @param [in] cert Certificate request object.
  18495. * @param [out] criticalExt Critical extension return code.
  18496. * @param [in] oid OID decribing which attribute was found.
  18497. * @param [in] aIdx Index into certificate source to start parsing.
  18498. * @param [in] input Attribute value data.
  18499. * @param [in] maxIdx Maximum index to parse to.
  18500. * @return 0 on success.
  18501. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18502. * is invalid.
  18503. */
  18504. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  18505. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  18506. {
  18507. int ret = 0;
  18508. word32 idx = 0;
  18509. ASNGetData strDataASN[strAttrASN_Length];
  18510. switch (oid) {
  18511. case PKCS9_CONTENT_TYPE_OID:
  18512. /* Clear dynamic data and specify choices acceptable. */
  18513. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18514. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18515. /* Parse a string. */
  18516. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18517. 1, input, &idx, maxIdx);
  18518. if (ret == 0) {
  18519. /* Store references to password data. */
  18520. cert->contentType =
  18521. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18522. cert->contentTypeLen =
  18523. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  18524. }
  18525. break;
  18526. /* A password by which the entity may request certificate revocation.
  18527. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  18528. */
  18529. case CHALLENGE_PASSWORD_OID:
  18530. /* Clear dynamic data and specify choices acceptable. */
  18531. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18532. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18533. /* Parse a string. */
  18534. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18535. 1, input, &idx, maxIdx);
  18536. if (ret == 0) {
  18537. /* Store references to password data. */
  18538. cert->cPwd =
  18539. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18540. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  18541. data.ref.length;
  18542. }
  18543. break;
  18544. /* Requested serial number to issue with.
  18545. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  18546. * (References: ISO/IEC 9594-6:1997)
  18547. */
  18548. case SERIAL_NUMBER_OID:
  18549. /* Clear dynamic data and specify choices acceptable. */
  18550. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  18551. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  18552. /* Parse a string. */
  18553. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  18554. 1, input, &idx, maxIdx);
  18555. if (ret == 0) {
  18556. /* Store references to serial number. */
  18557. cert->sNum =
  18558. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  18559. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  18560. data.ref.length;
  18561. /* Store serial number if small enough. */
  18562. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  18563. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  18564. cert->serialSz = cert->sNumLen;
  18565. }
  18566. }
  18567. break;
  18568. /* Certificate extensions to be included in generated certificate.
  18569. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  18570. */
  18571. case EXTENSION_REQUEST_OID:
  18572. /* Store references to all extensions. */
  18573. cert->extensions = input;
  18574. cert->extensionsSz = (int)maxIdx;
  18575. cert->extensionsIdx = aIdx;
  18576. /* Decode and validate extensions. */
  18577. ret = DecodeCertExtensions(cert);
  18578. if (ret == ASN_CRIT_EXT_E) {
  18579. /* Return critical extension not recognized. */
  18580. *criticalExt = ret;
  18581. ret = 0;
  18582. }
  18583. else {
  18584. /* No critical extension error. */
  18585. *criticalExt = 0;
  18586. }
  18587. break;
  18588. default:
  18589. ret = ASN_PARSE_E;
  18590. break;
  18591. }
  18592. return ret;
  18593. }
  18594. /* Decode attributes of a BER encoded certificate request.
  18595. *
  18596. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  18597. *
  18598. * Outer sequence has been removed.
  18599. *
  18600. * @param [in] cert Certificate request object.
  18601. * @param [out] criticalExt Critical extension return code.
  18602. * @param [in] idx Index into certificate source to start parsing.
  18603. * @param [in] maxIdx Maximum index to parse to.
  18604. * @return 0 on success.
  18605. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18606. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18607. * is invalid.
  18608. * @return BUFFER_E when data in buffer is too small.
  18609. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18610. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18611. * non-zero length.
  18612. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18613. */
  18614. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  18615. word32 idx, word32 maxIdx)
  18616. {
  18617. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  18618. int ret = 0;
  18619. WOLFSSL_ENTER("DecodeCertReqAttributes");
  18620. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  18621. /* Parse each attribute until all data used up. */
  18622. while ((ret == 0) && (idx < maxIdx)) {
  18623. /* Clear dynamic data. */
  18624. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  18625. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  18626. /* Parse an attribute. */
  18627. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  18628. cert->source, &idx, maxIdx);
  18629. /* idx is now at end of attribute data. */
  18630. if (ret == 0) {
  18631. ret = DecodeCertReqAttrValue(cert, criticalExt,
  18632. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  18633. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  18634. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  18635. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  18636. }
  18637. }
  18638. FREE_ASNGETDATA(dataASN, cert->heap);
  18639. return ret;
  18640. }
  18641. /* ASN.1 template for a certificate request.
  18642. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  18643. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  18644. */
  18645. static const ASNItem certReqASN[] = {
  18646. /* CertificationRequest */
  18647. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18648. /* CertificationRequestInfo */
  18649. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18650. /* version INTEGER { v1(0), v2(1), v3(2) */
  18651. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  18652. /* subject Name */
  18653. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18654. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18655. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18656. /* algorithm AlgorithmIdentifier */
  18657. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18658. /* Algorithm OBJECT IDENTIFIER */
  18659. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18660. /* parameters ANY defined by algorithm OPTIONAL */
  18661. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  18662. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  18663. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  18664. /* subjectPublicKey BIT STRING */
  18665. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18666. /* attributes [0] Attributes */
  18667. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  18668. /* signatureAlgorithm AlgorithmIdentifier */
  18669. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18670. /* Algorithm OBJECT IDENTIFIER */
  18671. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18672. /* parameters ANY defined by algorithm OPTIONAL */
  18673. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  18674. /* signature BIT STRING */
  18675. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18676. };
  18677. enum {
  18678. CERTREQASN_IDX_SEQ = 0,
  18679. CERTREQASN_IDX_INFO_SEQ,
  18680. CERTREQASN_IDX_INFO_VER,
  18681. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  18682. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  18683. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  18684. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  18685. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  18686. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  18687. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  18688. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  18689. CERTREQASN_IDX_INFO_ATTRS,
  18690. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  18691. CERTREQASN_IDX_INFO_SIGALGO_OID,
  18692. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  18693. CERTREQASN_IDX_INFO_SIGNATURE
  18694. };
  18695. /* Number of items in ASN.1 template for a certificate request. */
  18696. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  18697. /* Parse BER encoded certificate request.
  18698. *
  18699. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  18700. *
  18701. * @param [in] cert Certificate request object.
  18702. * @param [out] criticalExt Critical extension return code.
  18703. * @return 0 on success.
  18704. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18705. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18706. * is invalid.
  18707. * @return BUFFER_E when data in buffer is too small.
  18708. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18709. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18710. * non-zero length.
  18711. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18712. * @return MEMORY_E on dynamic memory allocation failure.
  18713. */
  18714. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  18715. {
  18716. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  18717. int ret = 0;
  18718. byte version;
  18719. word32 idx;
  18720. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  18721. if (ret == 0) {
  18722. /* Default version is 0. */
  18723. version = 0;
  18724. /* Set version var and OID types to expect. */
  18725. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  18726. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  18727. oidKeyType);
  18728. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  18729. oidCurveType);
  18730. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  18731. /* Parse a certificate request. */
  18732. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  18733. cert->source, &cert->srcIdx, cert->maxIdx);
  18734. }
  18735. /* Check version is valid/supported - can't be negative. */
  18736. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18737. WOLFSSL_MSG("Unexpected certificate request version");
  18738. ret = ASN_PARSE_E;
  18739. }
  18740. if (ret == 0) {
  18741. /* Set fields of certificate request. */
  18742. cert->version = version;
  18743. cert->signatureOID =
  18744. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  18745. cert->keyOID =
  18746. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  18747. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  18748. /* Parse the subject name. */
  18749. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  18750. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18751. cert->source, &idx,
  18752. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  18753. }
  18754. if (ret == 0) {
  18755. /* Parse the certificate request Attributes. */
  18756. ret = DecodeCertReqAttributes(cert, criticalExt,
  18757. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  18758. cert->source),
  18759. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  18760. }
  18761. if (ret == 0) {
  18762. /* Parse the certificate request's key. */
  18763. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  18764. ret = GetCertKey(cert, cert->source, &idx,
  18765. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  18766. }
  18767. if (ret == 0) {
  18768. /* Store references to signature. */
  18769. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  18770. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  18771. &cert->signature, &cert->sigLength);
  18772. }
  18773. FREE_ASNGETDATA(dataASN, cert->heap);
  18774. return ret;
  18775. }
  18776. #endif /* WOLFSSL_CERT_REQ */
  18777. #endif
  18778. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  18779. {
  18780. int ret;
  18781. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18782. defined(WOLFSSL_DYN_CERT)
  18783. char* ptr;
  18784. #endif
  18785. ret = ParseCertRelative(cert, type, verify, cm);
  18786. if (ret < 0)
  18787. return ret;
  18788. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18789. defined(WOLFSSL_DYN_CERT)
  18790. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
  18791. if (cert->subjectCNLen > 0) {
  18792. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  18793. DYNAMIC_TYPE_SUBJECT_CN);
  18794. if (ptr == NULL)
  18795. return MEMORY_E;
  18796. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  18797. ptr[cert->subjectCNLen] = '\0';
  18798. cert->subjectCN = ptr;
  18799. cert->subjectCNStored = 1;
  18800. }
  18801. #endif
  18802. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  18803. defined(WOLFSSL_DYN_CERT)
  18804. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  18805. if ((cert->keyOID == RSAk
  18806. #ifdef WC_RSA_PSS
  18807. || cert->keyOID == RSAPSSk
  18808. #endif
  18809. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  18810. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  18811. DYNAMIC_TYPE_PUBLIC_KEY);
  18812. if (ptr == NULL)
  18813. return MEMORY_E;
  18814. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  18815. cert->publicKey = (byte *)ptr;
  18816. cert->pubKeyStored = 1;
  18817. }
  18818. #endif
  18819. return ret;
  18820. }
  18821. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  18822. {
  18823. return ParseCert(cert, type, verify, cm);
  18824. }
  18825. #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
  18826. !defined(GetCA)
  18827. /* from SSL proper, for locking can't do find here anymore.
  18828. * brought in from internal.h if built with compat layer.
  18829. * if defined(GetCA), it's a predefined macro and these prototypes
  18830. * would conflict.
  18831. */
  18832. #ifdef __cplusplus
  18833. extern "C" {
  18834. #endif
  18835. Signer* GetCA(void* signers, byte* hash);
  18836. #ifndef NO_SKID
  18837. Signer* GetCAByName(void* signers, byte* hash);
  18838. #endif
  18839. #ifdef __cplusplus
  18840. }
  18841. #endif
  18842. #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
  18843. #if defined(WOLFCRYPT_ONLY)
  18844. /* dummy functions, not using wolfSSL so don't need actual ones */
  18845. Signer* GetCA(void* signers, byte* hash)
  18846. {
  18847. (void)hash;
  18848. return (Signer*)signers;
  18849. }
  18850. #ifndef NO_SKID
  18851. Signer* GetCAByName(void* signers, byte* hash)
  18852. {
  18853. (void)hash;
  18854. return (Signer*)signers;
  18855. }
  18856. #endif /* NO_SKID */
  18857. #endif /* WOLFCRYPT_ONLY */
  18858. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  18859. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  18860. {
  18861. Signer* ca = NULL;
  18862. if (cert->extSubjKeyIdSet)
  18863. ca = GetCA(cm, cert->extSubjKeyId);
  18864. if (ca == NULL)
  18865. ca = GetCAByName(cm, cert->subjectHash);
  18866. if (ca) {
  18867. if ((ca->pubKeySize == cert->pubKeySize) &&
  18868. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  18869. return ca;
  18870. }
  18871. }
  18872. return NULL;
  18873. }
  18874. #endif
  18875. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  18876. #ifdef WOLFSSL_ASN_TEMPLATE
  18877. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  18878. *
  18879. * @param [in] input Input data.
  18880. * @param [in] maxIdx Maximum index for data.
  18881. * @param [out] hash Hash of AKI.
  18882. * @param [out] set Whether the hash buffer was set.
  18883. * @param [in] heap Dynamic memory allocation hint.
  18884. * @return 0 on success.
  18885. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18886. * is invalid.
  18887. * @return MEMORY_E on dynamic memory allocation failure.
  18888. */
  18889. static int GetAKIHash(const byte* input, word32 maxIdx, byte* hash, int* set,
  18890. void* heap)
  18891. {
  18892. /* AKI and Certificate Extenion ASN.1 templates are the same length. */
  18893. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18894. int ret = 0;
  18895. word32 idx = 0;
  18896. word32 extEndIdx;
  18897. byte* extData;
  18898. word32 extDataSz;
  18899. byte critical;
  18900. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  18901. (void)heap;
  18902. extEndIdx = idx + maxIdx;
  18903. /* Step through each extension looking for AKI. */
  18904. while ((ret == 0) && (idx < extEndIdx)) {
  18905. /* Clear dynamic data and check for certificate extension type OIDs. */
  18906. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18907. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18908. /* Set criticality variable. */
  18909. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18910. /* Parse an extension. */
  18911. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18912. &idx, extEndIdx);
  18913. if (ret == 0) {
  18914. /* Get reference to extension data and move index on past this
  18915. * extension. */
  18916. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  18917. idx += extDataSz;
  18918. /* Check whether we have the AKI extension. */
  18919. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  18920. /* Clear dynamic data. */
  18921. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  18922. /* Start parsing extension data from the start. */
  18923. idx = 0;
  18924. /* Parse AKI extension data. */
  18925. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  18926. 1, extData, &idx, extDataSz);
  18927. if ((ret == 0) &&
  18928. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  18929. != NULL)) {
  18930. /* We parsed successfully and have data. */
  18931. *set = 1;
  18932. /* Get the hash or hash of the hash if wrong size. */
  18933. ret = GetHashId(
  18934. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  18935. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  18936. hash);
  18937. }
  18938. break;
  18939. }
  18940. }
  18941. }
  18942. FREE_ASNGETDATA(dataASN, heap);
  18943. return ret;
  18944. }
  18945. #endif
  18946. /* Only quick step through the certificate to find fields that are then used
  18947. * in certificate signature verification.
  18948. * Must use the signature OID from the signed part of the certificate.
  18949. * Works also on certificate signing requests.
  18950. *
  18951. * This is only for minimizing dynamic memory usage during TLS certificate
  18952. * chain processing.
  18953. * Doesn't support:
  18954. * OCSP Only: alt lookup using subject and pub key w/o sig check
  18955. */
  18956. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  18957. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  18958. {
  18959. #ifndef WOLFSSL_ASN_TEMPLATE
  18960. #ifndef WOLFSSL_SMALL_STACK
  18961. SignatureCtx sigCtx[1];
  18962. #else
  18963. SignatureCtx* sigCtx;
  18964. #endif
  18965. byte hash[KEYID_SIZE];
  18966. Signer* ca = NULL;
  18967. word32 idx = 0;
  18968. int len;
  18969. word32 tbsCertIdx = 0;
  18970. word32 sigIndex = 0;
  18971. word32 signatureOID = 0;
  18972. word32 oid = 0;
  18973. word32 issuerIdx = 0;
  18974. word32 issuerSz = 0;
  18975. #ifndef NO_SKID
  18976. int extLen = 0;
  18977. word32 extIdx = 0;
  18978. word32 extEndIdx = 0;
  18979. int extAuthKeyIdSet = 0;
  18980. #endif
  18981. int ret = 0;
  18982. word32 localIdx;
  18983. byte tag;
  18984. const byte* sigParams = NULL;
  18985. word32 sigParamsSz = 0;
  18986. if (cert == NULL) {
  18987. return BAD_FUNC_ARG;
  18988. }
  18989. #ifdef WOLFSSL_SMALL_STACK
  18990. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  18991. if (sigCtx == NULL)
  18992. return MEMORY_E;
  18993. #endif
  18994. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  18995. /* Certificate SEQUENCE */
  18996. if (GetSequence(cert, &idx, &len, certSz) < 0)
  18997. ret = ASN_PARSE_E;
  18998. if (ret == 0) {
  18999. tbsCertIdx = idx;
  19000. /* TBSCertificate SEQUENCE */
  19001. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19002. ret = ASN_PARSE_E;
  19003. }
  19004. if (ret == 0) {
  19005. sigIndex = len + idx;
  19006. if ((idx + 1) > certSz)
  19007. ret = BUFFER_E;
  19008. }
  19009. if (ret == 0) {
  19010. /* version - optional */
  19011. localIdx = idx;
  19012. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19013. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19014. idx++;
  19015. if (GetLength(cert, &idx, &len, certSz) < 0)
  19016. ret = ASN_PARSE_E;
  19017. idx += len;
  19018. }
  19019. }
  19020. }
  19021. if (ret == 0) {
  19022. /* serialNumber */
  19023. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19024. ret = ASN_PARSE_E;
  19025. }
  19026. if (ret == 0) {
  19027. idx += len;
  19028. /* signature */
  19029. if (!req) {
  19030. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  19031. ret = ASN_PARSE_E;
  19032. #ifdef WC_RSA_PSS
  19033. else if (signatureOID == CTC_RSASSAPSS) {
  19034. int start = idx;
  19035. sigParams = cert + idx;
  19036. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19037. ret = ASN_PARSE_E;
  19038. if (ret == 0) {
  19039. idx += len;
  19040. sigParamsSz = idx - start;
  19041. }
  19042. }
  19043. #endif
  19044. }
  19045. }
  19046. if (ret == 0) {
  19047. issuerIdx = idx;
  19048. /* issuer for cert or subject for csr */
  19049. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19050. ret = ASN_PARSE_E;
  19051. }
  19052. if (ret == 0) {
  19053. issuerSz = len + idx - issuerIdx;
  19054. }
  19055. #ifndef NO_SKID
  19056. if (!req && ret == 0) {
  19057. idx += len;
  19058. /* validity */
  19059. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19060. ret = ASN_PARSE_E;
  19061. }
  19062. if (!req && ret == 0) {
  19063. idx += len;
  19064. /* subject */
  19065. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19066. ret = ASN_PARSE_E;
  19067. }
  19068. if (ret == 0) {
  19069. idx += len;
  19070. /* subjectPublicKeyInfo */
  19071. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19072. ret = ASN_PARSE_E;
  19073. }
  19074. if (req && ret == 0) {
  19075. idx += len;
  19076. /* attributes */
  19077. if (GetASNHeader_ex(cert,
  19078. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  19079. &len, certSz, 1) < 0)
  19080. ret = ASN_PARSE_E;
  19081. }
  19082. if (!req) {
  19083. if (ret == 0) {
  19084. idx += len;
  19085. if ((idx + 1) > certSz)
  19086. ret = BUFFER_E;
  19087. }
  19088. if (ret == 0) {
  19089. /* issuerUniqueID - optional */
  19090. localIdx = idx;
  19091. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19092. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  19093. idx++;
  19094. if (GetLength(cert, &idx, &len, certSz) < 0)
  19095. ret = ASN_PARSE_E;
  19096. idx += len;
  19097. }
  19098. }
  19099. }
  19100. if (ret == 0) {
  19101. if ((idx + 1) > certSz)
  19102. ret = BUFFER_E;
  19103. }
  19104. if (ret == 0) {
  19105. /* subjectUniqueID - optional */
  19106. localIdx = idx;
  19107. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19108. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  19109. idx++;
  19110. if (GetLength(cert, &idx, &len, certSz) < 0)
  19111. ret = ASN_PARSE_E;
  19112. idx += len;
  19113. }
  19114. }
  19115. }
  19116. if (ret == 0) {
  19117. if ((idx + 1) > certSz)
  19118. ret = BUFFER_E;
  19119. }
  19120. /* extensions - optional */
  19121. localIdx = idx;
  19122. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19123. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  19124. idx++;
  19125. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  19126. ret = ASN_PARSE_E;
  19127. if (ret == 0) {
  19128. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  19129. ret = ASN_PARSE_E;
  19130. }
  19131. if (ret == 0) {
  19132. extEndIdx = idx + extLen;
  19133. /* Check each extension for the ones we want. */
  19134. while (ret == 0 && idx < extEndIdx) {
  19135. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19136. ret = ASN_PARSE_E;
  19137. if (ret == 0) {
  19138. extIdx = idx;
  19139. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  19140. certSz) < 0) {
  19141. ret = ASN_PARSE_E;
  19142. }
  19143. if (ret == 0) {
  19144. if ((extIdx + 1) > certSz)
  19145. ret = BUFFER_E;
  19146. }
  19147. }
  19148. if (ret == 0) {
  19149. localIdx = extIdx;
  19150. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19151. tag == ASN_BOOLEAN) {
  19152. if (GetBoolean(cert, &extIdx, certSz) < 0)
  19153. ret = ASN_PARSE_E;
  19154. }
  19155. }
  19156. if (ret == 0) {
  19157. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  19158. ret = ASN_PARSE_E;
  19159. }
  19160. if (ret == 0) {
  19161. switch (oid) {
  19162. case AUTH_KEY_OID:
  19163. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  19164. ret = ASN_PARSE_E;
  19165. if (ret == 0 && (extIdx + 1) >= certSz)
  19166. ret = BUFFER_E;
  19167. if (ret == 0 &&
  19168. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  19169. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  19170. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  19171. ret = ASN_PARSE_E;
  19172. if (ret == 0) {
  19173. extAuthKeyIdSet = 1;
  19174. /* Get the hash or hash of the hash if wrong
  19175. * size. */
  19176. ret = GetHashId(cert + extIdx, extLen,
  19177. hash);
  19178. }
  19179. }
  19180. break;
  19181. default:
  19182. break;
  19183. }
  19184. }
  19185. idx += len;
  19186. }
  19187. }
  19188. }
  19189. }
  19190. else if (ret == 0) {
  19191. idx += len;
  19192. }
  19193. if (ret == 0 && pubKey == NULL) {
  19194. if (extAuthKeyIdSet)
  19195. ca = GetCA(cm, hash);
  19196. if (ca == NULL) {
  19197. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19198. if (ret == 0)
  19199. ca = GetCAByName(cm, hash);
  19200. }
  19201. }
  19202. #else
  19203. if (ret == 0 && pubKey == NULL) {
  19204. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  19205. if (ret == 0)
  19206. ca = GetCA(cm, hash);
  19207. }
  19208. #endif /* !NO_SKID */
  19209. if (ca == NULL && pubKey == NULL)
  19210. ret = ASN_NO_SIGNER_E;
  19211. if (ret == 0) {
  19212. idx = sigIndex;
  19213. /* signatureAlgorithm */
  19214. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  19215. ret = ASN_PARSE_E;
  19216. #ifdef WC_RSA_PSS
  19217. else if (signatureOID == CTC_RSASSAPSS) {
  19218. word32 sz = idx;
  19219. const byte* params = cert + idx;
  19220. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19221. ret = ASN_PARSE_E;
  19222. if (ret == 0) {
  19223. idx += len;
  19224. sz = idx - sz;
  19225. if (req) {
  19226. if ((sz != sigParamsSz) ||
  19227. (XMEMCMP(sigParams, params, sz) != 0)) {
  19228. ret = ASN_PARSE_E;
  19229. }
  19230. }
  19231. else {
  19232. sigParams = params;
  19233. sigParamsSz = sz;
  19234. }
  19235. }
  19236. }
  19237. #endif
  19238. /* In CSR signature data is not present in body */
  19239. if (req)
  19240. signatureOID = oid;
  19241. }
  19242. if (ret == 0) {
  19243. if (oid != signatureOID)
  19244. ret = ASN_SIG_OID_E;
  19245. }
  19246. if (ret == 0) {
  19247. /* signatureValue */
  19248. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  19249. ret = ASN_PARSE_E;
  19250. }
  19251. if (ret == 0) {
  19252. if (pubKey != NULL) {
  19253. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19254. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  19255. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  19256. }
  19257. else {
  19258. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19259. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  19260. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  19261. sigParamsSz, NULL);
  19262. }
  19263. if (ret != 0) {
  19264. WOLFSSL_ERROR_VERBOSE(ret);
  19265. WOLFSSL_MSG("Confirm signature failed");
  19266. }
  19267. }
  19268. FreeSignatureCtx(sigCtx);
  19269. #ifdef WOLFSSL_SMALL_STACK
  19270. if (sigCtx != NULL)
  19271. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19272. #endif
  19273. return ret;
  19274. #else /* WOLFSSL_ASN_TEMPLATE */
  19275. /* X509 ASN.1 template longer than Certificate Request template. */
  19276. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19277. #ifndef WOLFSSL_SMALL_STACK
  19278. SignatureCtx sigCtx[1];
  19279. #else
  19280. SignatureCtx* sigCtx = NULL;
  19281. #endif
  19282. byte hash[KEYID_SIZE];
  19283. Signer* ca = NULL;
  19284. int ret = 0;
  19285. word32 idx = 0;
  19286. #ifndef NO_SKID
  19287. int extAuthKeyIdSet = 0;
  19288. #endif
  19289. const byte* tbs = NULL;
  19290. word32 tbsSz = 0;
  19291. #ifdef WC_RSA_PSS
  19292. const byte* tbsParams = NULL;
  19293. word32 tbsParamsSz = 0;
  19294. #endif
  19295. const byte* sig = NULL;
  19296. word32 sigSz = 0;
  19297. word32 sigOID = 0;
  19298. const byte* sigParams = NULL;
  19299. word32 sigParamsSz = 0;
  19300. const byte* caName = NULL;
  19301. word32 caNameLen = 0;
  19302. #ifndef NO_SKID
  19303. const byte* akiData = NULL;
  19304. word32 akiLen = 0;
  19305. #endif
  19306. (void)req;
  19307. (void)heap;
  19308. if (cert == NULL) {
  19309. ret = BAD_FUNC_ARG;
  19310. }
  19311. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  19312. if ((ret == 0) && (!req)) {
  19313. /* Clear dynamic data for certificate items. */
  19314. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  19315. /* Set OID types expected for signature and public key. */
  19316. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19317. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19318. oidKeyType);
  19319. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19320. oidCurveType);
  19321. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19322. /* Parse certificate. */
  19323. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  19324. &idx, certSz);
  19325. /* Check signature OIDs match. */
  19326. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  19327. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  19328. ret = ASN_SIG_OID_E;
  19329. }
  19330. /* Store the data for verification in the certificate. */
  19331. if (ret == 0) {
  19332. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19333. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19334. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19335. cert);
  19336. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19337. cert);
  19338. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19339. #ifdef WC_RSA_PSS
  19340. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  19341. tbsParams =
  19342. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19343. cert);
  19344. tbsParamsSz =
  19345. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19346. cert);
  19347. }
  19348. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19349. sigParams =
  19350. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19351. cert);
  19352. sigParamsSz =
  19353. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19354. cert);
  19355. }
  19356. #endif
  19357. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  19358. #ifdef WC_RSA_PSS
  19359. if (tbsParamsSz != sigParamsSz) {
  19360. ret = ASN_PARSE_E;
  19361. }
  19362. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  19363. ret = ASN_PARSE_E;
  19364. }
  19365. else if ((tbsParamsSz > 0) &&
  19366. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  19367. ret = ASN_PARSE_E;
  19368. }
  19369. #endif
  19370. }
  19371. }
  19372. else if (ret == 0) {
  19373. #ifndef WOLFSSL_CERT_REQ
  19374. ret = NOT_COMPILED_IN;
  19375. #else
  19376. /* Clear dynamic data for certificate request items. */
  19377. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  19378. /* Set OID types expected for signature and public key. */
  19379. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19380. oidKeyType);
  19381. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19382. oidCurveType);
  19383. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19384. /* Parse certificate request. */
  19385. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  19386. &idx, certSz);
  19387. if (ret == 0) {
  19388. /* Store the data for verification in the certificate. */
  19389. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19390. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19391. caName = GetASNItem_Addr(
  19392. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19393. caNameLen = GetASNItem_Length(
  19394. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  19395. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19396. #ifdef WC_RSA_PSS
  19397. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19398. cert);
  19399. sigParamsSz =
  19400. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19401. cert);
  19402. #endif
  19403. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  19404. &sigSz);
  19405. }
  19406. #endif
  19407. }
  19408. #ifndef NO_SKID
  19409. if ((ret == 0) && (pubKey == NULL) && !req) {
  19410. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  19411. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  19412. }
  19413. #endif
  19414. FREE_ASNGETDATA(dataASN, heap);
  19415. /* If no public passed, then find the CA. */
  19416. if ((ret == 0) && (pubKey == NULL)) {
  19417. #ifndef NO_SKID
  19418. /* Find the AKI extension in list of extensions and get hash. */
  19419. if ((!req) && (akiData != NULL)) {
  19420. /* TODO: test case */
  19421. ret = GetAKIHash(akiData, akiLen, hash, &extAuthKeyIdSet, heap);
  19422. }
  19423. /* Get the CA by hash one was found. */
  19424. if (extAuthKeyIdSet) {
  19425. ca = GetCA(cm, hash);
  19426. }
  19427. if (ca == NULL)
  19428. #endif
  19429. {
  19430. /* Try hash of issuer name. */
  19431. ret = CalcHashId(caName, caNameLen, hash);
  19432. if (ret == 0) {
  19433. ca = GetCAByName(cm, hash);
  19434. }
  19435. }
  19436. if (ca != NULL) {
  19437. /* Extract public key information. */
  19438. pubKey = ca->publicKey;
  19439. pubKeySz = ca->pubKeySize;
  19440. pubKeyOID = ca->keyOID;
  19441. }
  19442. else {
  19443. /* No public key to verify with. */
  19444. ret = ASN_NO_SIGNER_E;
  19445. }
  19446. }
  19447. if (ret == 0) {
  19448. #ifdef WOLFSSL_SMALL_STACK
  19449. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  19450. DYNAMIC_TYPE_SIGNATURE);
  19451. if (sigCtx == NULL) {
  19452. ret = MEMORY_E;
  19453. }
  19454. if (ret == 0)
  19455. #endif
  19456. {
  19457. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19458. /* Check signature. */
  19459. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  19460. pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
  19461. if (ret != 0) {
  19462. WOLFSSL_MSG("Confirm signature failed");
  19463. }
  19464. FreeSignatureCtx(sigCtx);
  19465. #ifdef WOLFSSL_SMALL_STACK
  19466. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19467. #endif
  19468. }
  19469. }
  19470. return ret;
  19471. #endif /* WOLFSSL_ASN_TEMPLATE */
  19472. }
  19473. #ifdef OPENSSL_EXTRA
  19474. /* Call CheckCertSignature_ex using a public key buffer for verification
  19475. */
  19476. int CheckCertSignaturePubKey(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, 0);
  19481. }
  19482. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  19483. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19484. {
  19485. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  19486. pubKeyOID);
  19487. }
  19488. #ifdef WOLFSSL_CERT_REQ
  19489. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  19490. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  19491. {
  19492. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  19493. pubKey, pubKeySz, pubKeyOID, 1);
  19494. }
  19495. #endif /* WOLFSSL_CERT_REQ */
  19496. #endif /* OPENSSL_EXTRA */
  19497. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  19498. /* Call CheckCertSignature_ex using a certificate manager (cm)
  19499. */
  19500. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  19501. {
  19502. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  19503. }
  19504. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  19505. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  19506. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  19507. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  19508. /* ASN.1 DER decode instruction. */
  19509. typedef struct DecodeInstr {
  19510. /* Tag expected. */
  19511. byte tag;
  19512. /* Operation to perform: step in or go over */
  19513. byte op:1;
  19514. /* ASN.1 item is optional. */
  19515. byte optional:1;
  19516. } DecodeInstr;
  19517. /* Step into ASN.1 item. */
  19518. #define DECODE_INSTR_IN 0
  19519. /* Step over ASN.1 item. */
  19520. #define DECODE_INSTR_OVER 1
  19521. /* Get the public key data from the DER encoded X.509 certificate.
  19522. *
  19523. * Assumes data has previously been parsed for complete validity.
  19524. *
  19525. * @param [in] cert DER encoded X.509 certificate data.
  19526. * @param [in] certSz Length of DER encoding.
  19527. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  19528. * @param [out] pubKeySz Length of public key data in bytes.
  19529. * @return 0 on success.
  19530. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  19531. * @return ASN_PARSE_E when certificate encoding is invalid.
  19532. */
  19533. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  19534. const unsigned char** pubKey, word32* pubKeySz)
  19535. {
  19536. int ret = 0;
  19537. int l;
  19538. word32 o = 0;
  19539. int i;
  19540. static DecodeInstr ops[] = {
  19541. /* Outer SEQ */
  19542. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19543. /* TBSCertificate: SEQ */
  19544. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19545. /* Version: [0] */
  19546. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  19547. DECODE_INSTR_OVER, 1 },
  19548. /* CertificateSerialNumber: INT */
  19549. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  19550. /* AlgorithmIdentifier: SEQ */
  19551. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19552. /* issuer: SEQ */
  19553. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19554. /* Validity: SEQ */
  19555. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19556. /* subject: SEQ */
  19557. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19558. /* subjectPublicKeyInfo SEQ */
  19559. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  19560. /* AlgorithmIdentifier: SEQ */
  19561. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  19562. /* PublicKey: BIT_STRING */
  19563. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  19564. };
  19565. /* Validate parameters. */
  19566. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  19567. ret = BAD_FUNC_ARG;
  19568. }
  19569. /* Process each instruction to take us to public key data. */
  19570. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  19571. DecodeInstr op = ops[i];
  19572. /* Check the current ASN.1 item has the expected tag. */
  19573. if (cert[o] != op.tag) {
  19574. /* If not optional then error, otherwise skip op. */
  19575. if (!op.optional) {
  19576. ret = ASN_PARSE_E;
  19577. }
  19578. }
  19579. else {
  19580. /* Move past tag. */
  19581. o++;
  19582. /* Get the length of ASN.1 item and move past length encoding. */
  19583. if (GetLength(cert, &o, &l, certSz) < 0) {
  19584. ret = ASN_PARSE_E;
  19585. }
  19586. /* Skip data if required. */
  19587. else if (op.op == DECODE_INSTR_OVER) {
  19588. o += l;
  19589. }
  19590. }
  19591. }
  19592. if (ret == 0) {
  19593. /* Return the public key data and length.
  19594. * Skip first byte of BIT_STRING data: unused bits. */
  19595. *pubKey = cert + o + 1;
  19596. *pubKeySz = l - 1;
  19597. }
  19598. return ret;
  19599. }
  19600. #endif
  19601. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  19602. {
  19603. int ret = 0;
  19604. #ifndef WOLFSSL_ASN_TEMPLATE
  19605. word32 confirmOID = 0;
  19606. #ifdef WOLFSSL_CERT_REQ
  19607. int len = 0;
  19608. #endif
  19609. #endif
  19610. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  19611. int idx = 0;
  19612. #endif
  19613. byte* sce_tsip_encRsaKeyIdx;
  19614. if (cert == NULL) {
  19615. return BAD_FUNC_ARG;
  19616. }
  19617. #ifdef WOLFSSL_CERT_REQ
  19618. if (type == CERTREQ_TYPE)
  19619. cert->isCSR = 1;
  19620. #endif
  19621. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  19622. #ifndef WOLFSSL_ASN_TEMPLATE
  19623. cert->badDate = 0;
  19624. cert->criticalExt = 0;
  19625. if ((ret = DecodeToKey(cert, verify)) < 0) {
  19626. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  19627. cert->badDate = ret;
  19628. if (verify == VERIFY_SKIP_DATE)
  19629. ret = 0;
  19630. }
  19631. else
  19632. return ret;
  19633. }
  19634. WOLFSSL_MSG("Parsed Past Key");
  19635. #ifdef WOLFSSL_CERT_REQ
  19636. /* Read attributes */
  19637. if (cert->isCSR) {
  19638. if (GetASNHeader_ex(cert->source,
  19639. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  19640. &len, cert->maxIdx, 1) < 0) {
  19641. WOLFSSL_MSG("GetASNHeader_ex error");
  19642. return ASN_PARSE_E;
  19643. }
  19644. if (len) {
  19645. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  19646. word32 oid;
  19647. byte tag;
  19648. if (attrMaxIdx > cert->maxIdx) {
  19649. WOLFSSL_MSG("Attribute length greater than CSR length");
  19650. return ASN_PARSE_E;
  19651. }
  19652. while (cert->srcIdx < attrMaxIdx) {
  19653. /* Attributes have the structure:
  19654. * SEQ -> OID -> SET -> ATTRIBUTE */
  19655. if (GetSequence(cert->source, &cert->srcIdx, &len,
  19656. attrMaxIdx) < 0) {
  19657. WOLFSSL_MSG("attr GetSequence error");
  19658. return ASN_PARSE_E;
  19659. }
  19660. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  19661. oidCsrAttrType, attrMaxIdx) < 0) {
  19662. WOLFSSL_MSG("attr GetObjectId error");
  19663. return ASN_PARSE_E;
  19664. }
  19665. if (GetSet(cert->source, &cert->srcIdx, &len,
  19666. attrMaxIdx) < 0) {
  19667. WOLFSSL_MSG("attr GetSet error");
  19668. return ASN_PARSE_E;
  19669. }
  19670. switch (oid) {
  19671. case PKCS9_CONTENT_TYPE_OID:
  19672. if (GetHeader(cert->source, &tag,
  19673. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19674. WOLFSSL_MSG("attr GetHeader error");
  19675. return ASN_PARSE_E;
  19676. }
  19677. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19678. tag != ASN_IA5_STRING) {
  19679. WOLFSSL_MSG("Unsupported attribute value format");
  19680. return ASN_PARSE_E;
  19681. }
  19682. cert->contentType = (char*)cert->source + cert->srcIdx;
  19683. cert->contentTypeLen = len;
  19684. cert->srcIdx += (word32)len;
  19685. break;
  19686. case CHALLENGE_PASSWORD_OID:
  19687. if (GetHeader(cert->source, &tag,
  19688. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19689. WOLFSSL_MSG("attr GetHeader error");
  19690. return ASN_PARSE_E;
  19691. }
  19692. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19693. tag != ASN_IA5_STRING) {
  19694. WOLFSSL_MSG("Unsupported attribute value format");
  19695. return ASN_PARSE_E;
  19696. }
  19697. cert->cPwd = (char*)cert->source + cert->srcIdx;
  19698. cert->cPwdLen = len;
  19699. cert->srcIdx += (word32)len;
  19700. break;
  19701. case SERIAL_NUMBER_OID:
  19702. if (GetHeader(cert->source, &tag,
  19703. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19704. WOLFSSL_MSG("attr GetHeader error");
  19705. return ASN_PARSE_E;
  19706. }
  19707. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  19708. tag != ASN_IA5_STRING) {
  19709. WOLFSSL_MSG("Unsupported attribute value format");
  19710. return ASN_PARSE_E;
  19711. }
  19712. cert->sNum = (char*)cert->source + cert->srcIdx;
  19713. cert->sNumLen = len;
  19714. cert->srcIdx += (word32)len;
  19715. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19716. XMEMCPY(cert->serial, cert->sNum,
  19717. (size_t)cert->sNumLen);
  19718. cert->serialSz = cert->sNumLen;
  19719. }
  19720. break;
  19721. case DNQUALIFIER_OID:
  19722. if (GetHeader(cert->source, &tag,
  19723. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19724. WOLFSSL_MSG("attr GetHeader error");
  19725. return ASN_PARSE_E;
  19726. }
  19727. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  19728. cert->dnQualifierLen = len;
  19729. cert->srcIdx += (word32)len;
  19730. break;
  19731. case INITIALS_OID:
  19732. if (GetHeader(cert->source, &tag,
  19733. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19734. WOLFSSL_MSG("attr GetHeader error");
  19735. return ASN_PARSE_E;
  19736. }
  19737. cert->initials = (char*)cert->source + cert->srcIdx;
  19738. cert->initialsLen = len;
  19739. cert->srcIdx += (word32)len;
  19740. break;
  19741. case SURNAME_OID:
  19742. if (GetHeader(cert->source, &tag,
  19743. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19744. WOLFSSL_MSG("attr GetHeader error");
  19745. return ASN_PARSE_E;
  19746. }
  19747. cert->surname = (char*)cert->source + cert->srcIdx;
  19748. cert->surnameLen = len;
  19749. cert->srcIdx += (word32)len;
  19750. break;
  19751. case GIVEN_NAME_OID:
  19752. if (GetHeader(cert->source, &tag,
  19753. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19754. WOLFSSL_MSG("attr GetHeader error");
  19755. return ASN_PARSE_E;
  19756. }
  19757. cert->givenName = (char*)cert->source + cert->srcIdx;
  19758. cert->givenNameLen = len;
  19759. cert->srcIdx += (word32)len;
  19760. break;
  19761. case UNSTRUCTURED_NAME_OID:
  19762. if (GetHeader(cert->source, &tag,
  19763. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  19764. WOLFSSL_MSG("attr GetHeader error");
  19765. return ASN_PARSE_E;
  19766. }
  19767. cert->unstructuredName =
  19768. (char*)cert->source + cert->srcIdx;
  19769. cert->unstructuredNameLen = len;
  19770. cert->srcIdx += (word32)len;
  19771. break;
  19772. case EXTENSION_REQUEST_OID:
  19773. /* save extensions */
  19774. cert->extensions = &cert->source[cert->srcIdx];
  19775. cert->extensionsSz = len;
  19776. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  19777. if ((ret = DecodeCertExtensions(cert)) < 0) {
  19778. if (ret == ASN_CRIT_EXT_E) {
  19779. cert->criticalExt = ret;
  19780. }
  19781. else {
  19782. return ret;
  19783. }
  19784. }
  19785. cert->srcIdx += (word32)len;
  19786. break;
  19787. default:
  19788. WOLFSSL_MSG("Unsupported attribute type");
  19789. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19790. return ASN_PARSE_E;
  19791. }
  19792. }
  19793. }
  19794. }
  19795. #endif
  19796. if (cert->srcIdx < cert->sigIndex) {
  19797. #ifndef ALLOW_V1_EXTENSIONS
  19798. if (cert->version < 2) {
  19799. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  19800. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  19801. return ASN_VERSION_E;
  19802. }
  19803. #endif
  19804. /* save extensions */
  19805. cert->extensions = &cert->source[cert->srcIdx];
  19806. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  19807. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  19808. if ((ret = DecodeCertExtensions(cert)) < 0) {
  19809. if (ret == ASN_CRIT_EXT_E)
  19810. cert->criticalExt = ret;
  19811. else
  19812. return ret;
  19813. }
  19814. #ifdef HAVE_OCSP
  19815. if (verify == VERIFY_OCSP_CERT) {
  19816. /* trust for the lifetime of the responder's cert*/
  19817. if (cert->ocspNoCheckSet)
  19818. verify = VERIFY;
  19819. else
  19820. verify = VERIFY_OCSP;
  19821. }
  19822. #endif
  19823. /* advance past extensions */
  19824. cert->srcIdx = cert->sigIndex;
  19825. }
  19826. if ((ret = GetSigAlg(cert,
  19827. #ifdef WOLFSSL_CERT_REQ
  19828. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  19829. #else
  19830. &confirmOID,
  19831. #endif
  19832. cert->maxIdx)) < 0) {
  19833. return ret;
  19834. }
  19835. if ((ret = GetSignature(cert)) < 0) {
  19836. return ret;
  19837. }
  19838. if (confirmOID != cert->signatureOID
  19839. #ifdef WOLFSSL_CERT_REQ
  19840. && !cert->isCSR
  19841. #endif
  19842. ) {
  19843. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  19844. return ASN_SIG_OID_E;
  19845. }
  19846. #else
  19847. #ifdef WOLFSSL_CERT_REQ
  19848. if (cert->isCSR) {
  19849. ret = DecodeCertReq(cert, &cert->criticalExt);
  19850. if (ret < 0) {
  19851. return ret;
  19852. }
  19853. }
  19854. else
  19855. #endif
  19856. {
  19857. ret = DecodeCert(cert, verify, &cert->criticalExt);
  19858. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  19859. cert->badDate = ret;
  19860. if (verify == VERIFY_SKIP_DATE)
  19861. ret = 0;
  19862. }
  19863. else if (ret < 0) {
  19864. WOLFSSL_ERROR_VERBOSE(ret);
  19865. return ret;
  19866. }
  19867. }
  19868. #endif
  19869. #ifndef NO_SKID
  19870. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  19871. cert->pubKeySize > 0) {
  19872. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  19873. cert->extSubjKeyId);
  19874. if (ret != 0) {
  19875. WOLFSSL_ERROR_VERBOSE(ret);
  19876. return ret;
  19877. }
  19878. }
  19879. #endif /* !NO_SKID */
  19880. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  19881. type != TRUSTED_PEER_TYPE)) {
  19882. cert->ca = NULL;
  19883. #ifndef NO_SKID
  19884. if (cert->extAuthKeyIdSet) {
  19885. cert->ca = GetCA(cm, cert->extAuthKeyId);
  19886. }
  19887. if (cert->ca == NULL && cert->extSubjKeyIdSet
  19888. && verify != VERIFY_OCSP) {
  19889. cert->ca = GetCA(cm, cert->extSubjKeyId);
  19890. }
  19891. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  19892. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  19893. cert->ca = NULL;
  19894. }
  19895. if (cert->ca == NULL) {
  19896. cert->ca = GetCAByName(cm, cert->issuerHash);
  19897. /* If AKID is available then this CA doesn't have the public
  19898. * key required */
  19899. if (cert->ca && cert->extAuthKeyIdSet) {
  19900. WOLFSSL_MSG("CA SKID doesn't match AKID");
  19901. cert->ca = NULL;
  19902. }
  19903. }
  19904. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  19905. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  19906. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  19907. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  19908. if (cert->ca) {
  19909. ret = 0; /* success */
  19910. goto exit_pcr;
  19911. }
  19912. }
  19913. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  19914. #else
  19915. cert->ca = GetCA(cm, cert->issuerHash);
  19916. #endif /* !NO_SKID */
  19917. if (cert->ca) {
  19918. WOLFSSL_MSG("CA found");
  19919. }
  19920. }
  19921. if (cert->selfSigned) {
  19922. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  19923. } else {
  19924. /* RFC 5280 Section 4.2.1.9:
  19925. *
  19926. * load/receive check
  19927. *
  19928. * 1) Is CA boolean set?
  19929. * No - SKIP CHECK
  19930. * Yes - Check key usage
  19931. * 2) Is Key usage extension present?
  19932. * No - goto 3
  19933. * Yes - check keyCertSign assertion
  19934. * 2.a) Is keyCertSign asserted?
  19935. * No - goto 4
  19936. * Yes - goto 3
  19937. * 3) Is pathLen set?
  19938. * No - goto 4
  19939. * Yes - check pathLen against maxPathLen.
  19940. * 3.a) Is pathLen less than maxPathLen?
  19941. * No - goto 4
  19942. * Yes - set maxPathLen to pathLen and EXIT
  19943. * 4) Is maxPathLen > 0?
  19944. * Yes - Reduce by 1
  19945. * No - ERROR
  19946. */
  19947. if (cert->ca && cert->pathLengthSet) {
  19948. int checkPathLen = 0;
  19949. int decrementMaxPathLen = 0;
  19950. cert->maxPathLen = cert->pathLength;
  19951. if (cert->isCA) {
  19952. WOLFSSL_MSG("\tCA boolean set");
  19953. if (cert->extKeyUsageSet) {
  19954. WOLFSSL_MSG("\tExtension Key Usage Set");
  19955. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  19956. checkPathLen = 1;
  19957. }
  19958. else {
  19959. decrementMaxPathLen = 1;
  19960. }
  19961. }
  19962. else {
  19963. checkPathLen = 1;
  19964. } /* !cert->ca check */
  19965. } /* cert is not a CA (assuming entity cert) */
  19966. if (checkPathLen && cert->pathLengthSet) {
  19967. if (cert->pathLength < cert->ca->maxPathLen) {
  19968. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  19969. cert->maxPathLen = cert->pathLength;
  19970. }
  19971. else {
  19972. decrementMaxPathLen = 1;
  19973. }
  19974. }
  19975. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  19976. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  19977. cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
  19978. if (verify != NO_VERIFY && type != CA_TYPE &&
  19979. type != TRUSTED_PEER_TYPE) {
  19980. WOLFSSL_MSG("\tmaxPathLen status: OK");
  19981. }
  19982. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  19983. cert->maxPathLen = 0;
  19984. if (verify != NO_VERIFY && type != CA_TYPE &&
  19985. type != TRUSTED_PEER_TYPE) {
  19986. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  19987. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  19988. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  19989. return ASN_PATHLEN_INV_E;
  19990. }
  19991. }
  19992. } else if (cert->ca && cert->isCA) {
  19993. /* case where cert->pathLength extension is not set */
  19994. if (cert->ca->maxPathLen > 0) {
  19995. cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
  19996. } else {
  19997. cert->maxPathLen = 0;
  19998. if (verify != NO_VERIFY && type != CA_TYPE &&
  19999. type != TRUSTED_PEER_TYPE) {
  20000. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20001. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20002. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20003. return ASN_PATHLEN_INV_E;
  20004. }
  20005. }
  20006. }
  20007. }
  20008. #ifdef HAVE_OCSP
  20009. if (verify != NO_VERIFY && type != CA_TYPE &&
  20010. type != TRUSTED_PEER_TYPE) {
  20011. if (cert->ca) {
  20012. /* Need the CA's public key hash for OCSP */
  20013. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20014. KEYID_SIZE);
  20015. }
  20016. }
  20017. #endif /* HAVE_OCSP */
  20018. }
  20019. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20020. /* prepare for TSIP TLS cert verification API use */
  20021. if (cert->keyOID == RSAk) {
  20022. /* to call TSIP API, it needs keys position info in bytes */
  20023. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20024. cert->pubKeySize,
  20025. &cert->sigCtx.CertAtt.pubkey_n_start,
  20026. &cert->sigCtx.CertAtt.pubkey_n_len,
  20027. &cert->sigCtx.CertAtt.pubkey_e_start,
  20028. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20029. WOLFSSL_MSG("Decoding index from cert failed.");
  20030. return ret;
  20031. }
  20032. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20033. } else if (cert->keyOID == ECDSAk) {
  20034. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20035. }
  20036. /* check if we can use TSIP for cert verification */
  20037. /* if the ca is verified as tsip root ca. */
  20038. /* TSIP can only handle 2048 bits(256 byte) key. */
  20039. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20040. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20041. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20042. /* assign memory to encrypted tsip Rsa key index */
  20043. if (!cert->sce_tsip_encRsaKeyIdx)
  20044. cert->sce_tsip_encRsaKeyIdx =
  20045. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20046. cert->heap, DYNAMIC_TYPE_RSA);
  20047. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20048. return MEMORY_E;
  20049. }
  20050. else {
  20051. if (cert->ca) {
  20052. /* TSIP isn't usable */
  20053. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  20054. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  20055. "by TSIP.");
  20056. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  20057. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  20058. "RSA 2048.");
  20059. else
  20060. WOLFSSL_MSG("SCE-TSIP isn't usable");
  20061. }
  20062. cert->sce_tsip_encRsaKeyIdx = NULL;
  20063. }
  20064. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  20065. #else
  20066. sce_tsip_encRsaKeyIdx = NULL;
  20067. #endif
  20068. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  20069. if (cert->ca) {
  20070. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20071. verify == VERIFY_SKIP_DATE) {
  20072. /* try to confirm/verify signature */
  20073. if ((ret = ConfirmSignature(&cert->sigCtx,
  20074. cert->source + cert->certBegin,
  20075. cert->sigIndex - cert->certBegin,
  20076. cert->ca->publicKey, cert->ca->pubKeySize,
  20077. cert->ca->keyOID, cert->signature,
  20078. cert->sigLength, cert->signatureOID,
  20079. #ifdef WC_RSA_PSS
  20080. cert->source + cert->sigParamsIndex,
  20081. cert->sigParamsLength,
  20082. #else
  20083. NULL, 0,
  20084. #endif
  20085. sce_tsip_encRsaKeyIdx)) != 0) {
  20086. if (ret != WC_PENDING_E) {
  20087. WOLFSSL_MSG("Confirm signature failed");
  20088. }
  20089. WOLFSSL_ERROR_VERBOSE(ret);
  20090. return ret;
  20091. }
  20092. }
  20093. #ifndef IGNORE_NAME_CONSTRAINTS
  20094. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20095. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  20096. /* check that this cert's name is permitted by the signer's
  20097. * name constraints */
  20098. if (!ConfirmNameConstraints(cert->ca, cert)) {
  20099. WOLFSSL_MSG("Confirm name constraint failed");
  20100. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  20101. return ASN_NAME_INVALID_E;
  20102. }
  20103. }
  20104. #endif /* IGNORE_NAME_CONSTRAINTS */
  20105. }
  20106. #ifdef WOLFSSL_CERT_REQ
  20107. else if (type == CERTREQ_TYPE) {
  20108. if ((ret = ConfirmSignature(&cert->sigCtx,
  20109. cert->source + cert->certBegin,
  20110. cert->sigIndex - cert->certBegin,
  20111. cert->publicKey, cert->pubKeySize,
  20112. cert->keyOID, cert->signature,
  20113. cert->sigLength, cert->signatureOID,
  20114. #ifdef WC_RSA_PSS
  20115. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  20116. #else
  20117. NULL, 0,
  20118. #endif
  20119. sce_tsip_encRsaKeyIdx)) != 0) {
  20120. if (ret != WC_PENDING_E) {
  20121. WOLFSSL_MSG("Confirm signature failed");
  20122. }
  20123. WOLFSSL_ERROR_VERBOSE(ret);
  20124. return ret;
  20125. }
  20126. }
  20127. #endif
  20128. else {
  20129. /* no signer */
  20130. WOLFSSL_MSG("No CA signer to verify with");
  20131. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  20132. /* ret needs to be self-signer error for Qt compat */
  20133. if (cert->selfSigned) {
  20134. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  20135. return ASN_SELF_SIGNED_E;
  20136. }
  20137. else
  20138. #endif
  20139. {
  20140. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  20141. return ASN_NO_SIGNER_E;
  20142. }
  20143. }
  20144. }
  20145. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20146. exit_pcr:
  20147. #endif
  20148. if (cert->badDate != 0) {
  20149. if (verify != VERIFY_SKIP_DATE) {
  20150. return cert->badDate;
  20151. }
  20152. WOLFSSL_MSG("Date error: Verify option is skipping");
  20153. }
  20154. if (cert->criticalExt != 0)
  20155. return cert->criticalExt;
  20156. return ret;
  20157. }
  20158. /* Create and init an new signer */
  20159. Signer* MakeSigner(void* heap)
  20160. {
  20161. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  20162. DYNAMIC_TYPE_SIGNER);
  20163. if (signer) {
  20164. XMEMSET(signer, 0, sizeof(Signer));
  20165. }
  20166. (void)heap;
  20167. return signer;
  20168. }
  20169. /* Free an individual signer.
  20170. *
  20171. * Used by Certificate Manager.
  20172. *
  20173. * @param [in, out] signer On in, signer object.
  20174. * On out, pointer is no longer valid.
  20175. * @param [in] heap Dynamic memory hint.
  20176. */
  20177. void FreeSigner(Signer* signer, void* heap)
  20178. {
  20179. (void)signer;
  20180. (void)heap;
  20181. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20182. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  20183. #ifndef IGNORE_NAME_CONSTRAINTS
  20184. if (signer->permittedNames)
  20185. FreeNameSubtrees(signer->permittedNames, heap);
  20186. if (signer->excludedNames)
  20187. FreeNameSubtrees(signer->excludedNames, heap);
  20188. #endif
  20189. #ifdef WOLFSSL_SIGNER_DER_CERT
  20190. FreeDer(&signer->derCert);
  20191. #endif
  20192. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  20193. }
  20194. /* Free the whole singer table with number of rows.
  20195. *
  20196. * Each table entry is a linked list of signers.
  20197. * Used by Certificate Manager.
  20198. *
  20199. * @param [in, out] table Array of signer objects.
  20200. * @param [in] rows Number of entries in table.
  20201. * @param [in] heap Dynamic memory hint.
  20202. */
  20203. void FreeSignerTable(Signer** table, int rows, void* heap)
  20204. {
  20205. int i;
  20206. for (i = 0; i < rows; i++) {
  20207. Signer* signer = table[i];
  20208. while (signer) {
  20209. Signer* next = signer->next;
  20210. FreeSigner(signer, heap);
  20211. signer = next;
  20212. }
  20213. table[i] = NULL;
  20214. }
  20215. }
  20216. #ifdef WOLFSSL_TRUST_PEER_CERT
  20217. /* Free an individual trusted peer cert.
  20218. *
  20219. * @param [in, out] tp Trusted peer certificate object.
  20220. * @param [in] heap Dynamic memory hint.
  20221. */
  20222. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  20223. {
  20224. if (tp == NULL) {
  20225. return;
  20226. }
  20227. if (tp->name) {
  20228. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20229. }
  20230. if (tp->sig) {
  20231. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  20232. }
  20233. #ifndef IGNORE_NAME_CONSTRAINTS
  20234. if (tp->permittedNames)
  20235. FreeNameSubtrees(tp->permittedNames, heap);
  20236. if (tp->excludedNames)
  20237. FreeNameSubtrees(tp->excludedNames, heap);
  20238. #endif
  20239. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  20240. (void)heap;
  20241. }
  20242. /* Free the whole Trusted Peer linked list.
  20243. *
  20244. * Each table entry is a linked list of trusted peer certificates.
  20245. * Used by Certificate Manager.
  20246. *
  20247. * @param [in, out] table Array of trusted peer certificate objects.
  20248. * @param [in] rows Number of entries in table.
  20249. * @param [in] heap Dynamic memory hint.
  20250. */
  20251. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  20252. {
  20253. int i;
  20254. for (i = 0; i < rows; i++) {
  20255. TrustedPeerCert* tp = table[i];
  20256. while (tp) {
  20257. TrustedPeerCert* next = tp->next;
  20258. FreeTrustedPeer(tp, heap);
  20259. tp = next;
  20260. }
  20261. table[i] = NULL;
  20262. }
  20263. }
  20264. #endif /* WOLFSSL_TRUST_PEER_CERT */
  20265. int SetMyVersion(word32 version, byte* output, int header)
  20266. {
  20267. int i = 0;
  20268. if (output == NULL)
  20269. return BAD_FUNC_ARG;
  20270. if (header) {
  20271. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  20272. output[i++] = 3;
  20273. }
  20274. output[i++] = ASN_INTEGER;
  20275. output[i++] = 0x01;
  20276. output[i++] = (byte)version;
  20277. return i;
  20278. }
  20279. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  20280. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  20281. word32 outputSz, int maxSnSz)
  20282. {
  20283. int i;
  20284. int snSzInt = (int)snSz;
  20285. if (sn == NULL || output == NULL || snSzInt < 0)
  20286. return BAD_FUNC_ARG;
  20287. /* remove leading zeros */
  20288. while (snSzInt > 0 && sn[0] == 0) {
  20289. snSzInt--;
  20290. sn++;
  20291. }
  20292. /* RFC 5280 - 4.1.2.2:
  20293. * Serial numbers must be a positive value (and not zero) */
  20294. if (snSzInt == 0) {
  20295. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  20296. return BAD_FUNC_ARG;
  20297. }
  20298. if (sn[0] & 0x80)
  20299. maxSnSz--;
  20300. /* truncate if input is too long */
  20301. if (snSzInt > maxSnSz)
  20302. snSzInt = maxSnSz;
  20303. i = SetASNInt(snSzInt, sn[0], NULL);
  20304. /* truncate if input is too long */
  20305. if (snSzInt > (int)outputSz - i)
  20306. snSzInt = (int)outputSz - i;
  20307. /* sanity check number of bytes to copy */
  20308. if (snSzInt <= 0) {
  20309. return BUFFER_E;
  20310. }
  20311. /* write out ASN.1 Integer */
  20312. (void)SetASNInt(snSzInt, sn[0], output);
  20313. XMEMCPY(output + i, sn, (size_t)snSzInt);
  20314. /* compute final length */
  20315. i += snSzInt;
  20316. return i;
  20317. }
  20318. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20319. #endif /* !NO_CERTS */
  20320. #ifndef WOLFSSL_ASN_TEMPLATE
  20321. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  20322. byte* serial, int* serialSz, word32 maxIdx)
  20323. {
  20324. int result = 0;
  20325. int ret;
  20326. WOLFSSL_ENTER("wc_GetSerialNumber");
  20327. if (serial == NULL || input == NULL || serialSz == NULL) {
  20328. return BAD_FUNC_ARG;
  20329. }
  20330. /* First byte is ASN type */
  20331. if ((*inOutIdx+1) > maxIdx) {
  20332. WOLFSSL_MSG("Bad idx first");
  20333. return BUFFER_E;
  20334. }
  20335. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  20336. if (ret != 0)
  20337. return ret;
  20338. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  20339. WOLFSSL_MSG("Serial size bad");
  20340. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20341. return ASN_PARSE_E;
  20342. }
  20343. /* return serial */
  20344. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  20345. *inOutIdx += (word32)*serialSz;
  20346. return result;
  20347. }
  20348. #endif
  20349. #ifndef NO_CERTS
  20350. /* TODO: consider moving PEM code out to a different file. */
  20351. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20352. {
  20353. int ret = BAD_FUNC_ARG;
  20354. if (pDer) {
  20355. int dynType = 0;
  20356. DerBuffer* der;
  20357. /* Determine dynamic type */
  20358. switch (type) {
  20359. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  20360. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  20361. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  20362. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  20363. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  20364. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  20365. default: dynType = DYNAMIC_TYPE_KEY; break;
  20366. }
  20367. /* Setup new buffer */
  20368. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  20369. if (*pDer == NULL) {
  20370. return MEMORY_E;
  20371. }
  20372. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  20373. der = *pDer;
  20374. der->type = type;
  20375. der->dynType = dynType; /* Cache this for FreeDer */
  20376. der->heap = heap;
  20377. der->buffer = (byte*)der + sizeof(DerBuffer);
  20378. der->length = length;
  20379. ret = 0; /* Success */
  20380. }
  20381. return ret;
  20382. }
  20383. void FreeDer(DerBuffer** pDer)
  20384. {
  20385. if (pDer && *pDer)
  20386. {
  20387. DerBuffer* der = (DerBuffer*)*pDer;
  20388. /* ForceZero private keys */
  20389. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  20390. ForceZero(der->buffer, der->length);
  20391. }
  20392. der->buffer = NULL;
  20393. der->length = 0;
  20394. XFREE(der, der->heap, der->dynType);
  20395. *pDer = NULL;
  20396. }
  20397. }
  20398. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20399. {
  20400. return AllocDer(pDer, length, type, heap);
  20401. }
  20402. void wc_FreeDer(DerBuffer** pDer)
  20403. {
  20404. FreeDer(pDer);
  20405. }
  20406. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  20407. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  20408. updated to reflect maximum length and pem_struct_min_sz
  20409. to reflect minimum size */
  20410. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  20411. wcchar END_CERT = "-----END CERTIFICATE-----";
  20412. #ifdef WOLFSSL_CERT_REQ
  20413. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  20414. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  20415. #endif
  20416. #ifndef NO_DH
  20417. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  20418. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  20419. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  20420. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  20421. #endif
  20422. #ifndef NO_DSA
  20423. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  20424. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  20425. #endif
  20426. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  20427. wcchar END_X509_CRL = "-----END X509 CRL-----";
  20428. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  20429. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  20430. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  20431. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  20432. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  20433. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  20434. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  20435. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  20436. #ifdef HAVE_ECC
  20437. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  20438. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  20439. #ifdef OPENSSL_EXTRA
  20440. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  20441. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  20442. #endif
  20443. #endif
  20444. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  20445. !defined(NO_DSA)
  20446. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  20447. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  20448. #endif
  20449. #ifdef OPENSSL_EXTRA
  20450. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  20451. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  20452. const char END_PRIV_KEY_PREFIX[] = "-----END";
  20453. #endif
  20454. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  20455. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  20456. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20457. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  20458. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  20459. #endif
  20460. #if defined(HAVE_PQC)
  20461. #if defined(HAVE_FALCON)
  20462. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  20463. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  20464. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  20465. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  20466. #endif /* HAVE_FALCON */
  20467. #if defined(HAVE_DILITHIUM)
  20468. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20469. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  20470. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20471. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  20472. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20473. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  20474. #endif /* HAVE_DILITHIUM */
  20475. #if defined(HAVE_SPHINCS)
  20476. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20477. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  20478. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20479. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  20480. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20481. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  20482. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20483. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  20484. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20485. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  20486. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20487. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  20488. #endif /* HAVE_SPHINCS */
  20489. #endif /* HAVE_PQC */
  20490. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  20491. "-----END X509 CRL-----");
  20492. #ifdef WOLFSSL_PEM_TO_DER
  20493. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  20494. const char* endOfLine)
  20495. {
  20496. /* eat end of line characters */
  20497. while (line < endOfLine &&
  20498. (line[0] == '\r' || line[0] == '\n')) {
  20499. line++;
  20500. }
  20501. return line;
  20502. }
  20503. #endif
  20504. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  20505. {
  20506. int ret = BAD_FUNC_ARG;
  20507. switch (type) {
  20508. case CA_TYPE: /* same as below */
  20509. case TRUSTED_PEER_TYPE:
  20510. case CERT_TYPE:
  20511. if (header) *header = BEGIN_CERT;
  20512. if (footer) *footer = END_CERT;
  20513. ret = 0;
  20514. break;
  20515. case CRL_TYPE:
  20516. if (header) *header = BEGIN_X509_CRL;
  20517. if (footer) *footer = END_X509_CRL;
  20518. ret = 0;
  20519. break;
  20520. #ifndef NO_DH
  20521. case DH_PARAM_TYPE:
  20522. if (header) *header = BEGIN_DH_PARAM;
  20523. if (footer) *footer = END_DH_PARAM;
  20524. ret = 0;
  20525. break;
  20526. case X942_PARAM_TYPE:
  20527. if (header) *header = BEGIN_X942_PARAM;
  20528. if (footer) *footer = END_X942_PARAM;
  20529. ret = 0;
  20530. break;
  20531. #endif
  20532. #ifndef NO_DSA
  20533. case DSA_PARAM_TYPE:
  20534. if (header) *header = BEGIN_DSA_PARAM;
  20535. if (footer) *footer = END_DSA_PARAM;
  20536. ret = 0;
  20537. break;
  20538. #endif
  20539. #ifdef WOLFSSL_CERT_REQ
  20540. case CERTREQ_TYPE:
  20541. if (header) *header = BEGIN_CERT_REQ;
  20542. if (footer) *footer = END_CERT_REQ;
  20543. ret = 0;
  20544. break;
  20545. #endif
  20546. #ifndef NO_DSA
  20547. case DSA_TYPE:
  20548. case DSA_PRIVATEKEY_TYPE:
  20549. if (header) *header = BEGIN_DSA_PRIV;
  20550. if (footer) *footer = END_DSA_PRIV;
  20551. ret = 0;
  20552. break;
  20553. #endif
  20554. #ifdef HAVE_ECC
  20555. case ECC_TYPE:
  20556. case ECC_PRIVATEKEY_TYPE:
  20557. if (header) *header = BEGIN_EC_PRIV;
  20558. if (footer) *footer = END_EC_PRIV;
  20559. ret = 0;
  20560. break;
  20561. #ifdef OPENSSL_EXTRA
  20562. case ECC_PARAM_TYPE:
  20563. if (header) *header = BEGIN_EC_PARAM;
  20564. if (footer) *footer = END_EC_PARAM;
  20565. ret = 0;
  20566. break;
  20567. #endif
  20568. #endif
  20569. case RSA_TYPE:
  20570. case PRIVATEKEY_TYPE:
  20571. if (header) *header = BEGIN_RSA_PRIV;
  20572. if (footer) *footer = END_RSA_PRIV;
  20573. ret = 0;
  20574. break;
  20575. #ifdef HAVE_ED25519
  20576. case ED25519_TYPE:
  20577. #endif
  20578. #ifdef HAVE_ED448
  20579. case ED448_TYPE:
  20580. #endif
  20581. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  20582. case EDDSA_PRIVATEKEY_TYPE:
  20583. if (header) *header = BEGIN_EDDSA_PRIV;
  20584. if (footer) *footer = END_EDDSA_PRIV;
  20585. ret = 0;
  20586. break;
  20587. #endif
  20588. #ifdef HAVE_PQC
  20589. #ifdef HAVE_FALCON
  20590. case FALCON_LEVEL1_TYPE:
  20591. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  20592. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  20593. ret = 0;
  20594. break;
  20595. case FALCON_LEVEL5_TYPE:
  20596. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  20597. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  20598. ret = 0;
  20599. break;
  20600. #endif /* HAVE_FALCON */
  20601. #ifdef HAVE_DILITHIUM
  20602. case DILITHIUM_LEVEL2_TYPE:
  20603. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  20604. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  20605. ret = 0;
  20606. break;
  20607. case DILITHIUM_LEVEL3_TYPE:
  20608. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  20609. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  20610. ret = 0;
  20611. break;
  20612. case DILITHIUM_LEVEL5_TYPE:
  20613. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  20614. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  20615. ret = 0;
  20616. break;
  20617. #endif /* HAVE_DILITHIUM */
  20618. #ifdef HAVE_SPHINCS
  20619. case SPHINCS_FAST_LEVEL1_TYPE:
  20620. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  20621. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  20622. ret = 0;
  20623. break;
  20624. case SPHINCS_FAST_LEVEL3_TYPE:
  20625. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  20626. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  20627. ret = 0;
  20628. break;
  20629. case SPHINCS_FAST_LEVEL5_TYPE:
  20630. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  20631. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  20632. ret = 0;
  20633. break;
  20634. case SPHINCS_SMALL_LEVEL1_TYPE:
  20635. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  20636. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  20637. ret = 0;
  20638. break;
  20639. case SPHINCS_SMALL_LEVEL3_TYPE:
  20640. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  20641. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  20642. ret = 0;
  20643. break;
  20644. case SPHINCS_SMALL_LEVEL5_TYPE:
  20645. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  20646. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  20647. ret = 0;
  20648. break;
  20649. #endif /* HAVE_SPHINCS */
  20650. #endif /* HAVE_PQC */
  20651. case PUBLICKEY_TYPE:
  20652. case ECC_PUBLICKEY_TYPE:
  20653. if (header) *header = BEGIN_PUB_KEY;
  20654. if (footer) *footer = END_PUB_KEY;
  20655. ret = 0;
  20656. break;
  20657. case RSA_PUBLICKEY_TYPE:
  20658. if (header) *header = BEGIN_RSA_PUB;
  20659. if (footer) *footer = END_RSA_PUB;
  20660. ret = 0;
  20661. break;
  20662. #ifndef NO_DH
  20663. case DH_PRIVATEKEY_TYPE:
  20664. #endif
  20665. case PKCS8_PRIVATEKEY_TYPE:
  20666. if (header) *header = BEGIN_PRIV_KEY;
  20667. if (footer) *footer = END_PRIV_KEY;
  20668. ret = 0;
  20669. break;
  20670. case PKCS8_ENC_PRIVATEKEY_TYPE:
  20671. if (header) *header = BEGIN_ENC_PRIV_KEY;
  20672. if (footer) *footer = END_ENC_PRIV_KEY;
  20673. ret = 0;
  20674. break;
  20675. default:
  20676. break;
  20677. }
  20678. return ret;
  20679. }
  20680. #ifdef WOLFSSL_ENCRYPTED_KEYS
  20681. static wcchar kProcTypeHeader = "Proc-Type";
  20682. static wcchar kDecInfoHeader = "DEK-Info";
  20683. #ifdef WOLFSSL_PEM_TO_DER
  20684. #ifndef NO_DES3
  20685. static wcchar kEncTypeDes = "DES-CBC";
  20686. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  20687. #endif
  20688. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  20689. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  20690. #endif
  20691. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  20692. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  20693. #endif
  20694. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  20695. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  20696. #endif
  20697. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  20698. {
  20699. int ret = 0;
  20700. if (info == NULL || cipherInfo == NULL)
  20701. return BAD_FUNC_ARG;
  20702. /* determine cipher information */
  20703. #ifndef NO_DES3
  20704. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  20705. info->cipherType = WC_CIPHER_DES;
  20706. info->keySz = DES_KEY_SIZE;
  20707. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  20708. * block size. */
  20709. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  20710. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  20711. #else
  20712. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  20713. #endif
  20714. }
  20715. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  20716. info->cipherType = WC_CIPHER_DES3;
  20717. info->keySz = DES3_KEY_SIZE;
  20718. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  20719. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  20720. #else
  20721. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  20722. #endif
  20723. }
  20724. else
  20725. #endif /* !NO_DES3 */
  20726. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  20727. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  20728. info->cipherType = WC_CIPHER_AES_CBC;
  20729. info->keySz = AES_128_KEY_SIZE;
  20730. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20731. }
  20732. else
  20733. #endif
  20734. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  20735. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  20736. info->cipherType = WC_CIPHER_AES_CBC;
  20737. info->keySz = AES_192_KEY_SIZE;
  20738. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20739. }
  20740. else
  20741. #endif
  20742. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  20743. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  20744. info->cipherType = WC_CIPHER_AES_CBC;
  20745. info->keySz = AES_256_KEY_SIZE;
  20746. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  20747. }
  20748. else
  20749. #endif
  20750. {
  20751. ret = NOT_COMPILED_IN;
  20752. }
  20753. return ret;
  20754. }
  20755. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  20756. size_t bufSz)
  20757. {
  20758. int err = 0;
  20759. const char* bufferStart;
  20760. const char* bufferEnd;
  20761. char* line;
  20762. if (info == NULL || pBuffer == NULL || bufSz == 0)
  20763. return BAD_FUNC_ARG;
  20764. bufferStart = *pBuffer;
  20765. bufferEnd = bufferStart + bufSz;
  20766. /* find encrypted info marker */
  20767. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  20768. min((word32)bufSz, PEM_LINE_LEN));
  20769. if (line != NULL) {
  20770. word32 lineSz;
  20771. char* finish;
  20772. char* start;
  20773. word32 startSz;
  20774. const char* newline = NULL;
  20775. if (line >= bufferEnd) {
  20776. return BUFFER_E;
  20777. }
  20778. lineSz = (word32)(bufferEnd - line);
  20779. /* find DEC-Info marker */
  20780. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  20781. if (start == NULL)
  20782. return BUFFER_E;
  20783. /* skip dec-info and ": " */
  20784. start += XSTRLEN(kDecInfoHeader);
  20785. if (start >= bufferEnd)
  20786. return BUFFER_E;
  20787. if (start[0] == ':') {
  20788. start++;
  20789. if (start >= bufferEnd)
  20790. return BUFFER_E;
  20791. }
  20792. if (start[0] == ' ')
  20793. start++;
  20794. startSz = (word32)(bufferEnd - start);
  20795. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  20796. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  20797. word32 finishSz;
  20798. if (finish >= bufferEnd) {
  20799. return BUFFER_E;
  20800. }
  20801. finishSz = (word32)(bufferEnd - finish);
  20802. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  20803. /* get cipher name */
  20804. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  20805. return BUFFER_E;
  20806. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  20807. return BUFFER_E;
  20808. info->name[finish - start] = '\0'; /* null term */
  20809. /* populate info */
  20810. err = wc_EncryptedInfoGet(info, info->name);
  20811. if (err != 0)
  20812. return err;
  20813. /* get IV */
  20814. if (finishSz < info->ivSz + 1)
  20815. return BUFFER_E;
  20816. if (newline == NULL) {
  20817. newline = XSTRNSTR(finish, "\n", min(finishSz,
  20818. PEM_LINE_LEN));
  20819. }
  20820. if ((newline != NULL) && (newline > finish)) {
  20821. finish++;
  20822. info->ivSz = (word32)(newline - finish);
  20823. if (info->ivSz > IV_SZ)
  20824. return BUFFER_E;
  20825. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  20826. return BUFFER_E;
  20827. info->set = 1;
  20828. }
  20829. else
  20830. return BUFFER_E;
  20831. }
  20832. else
  20833. return BUFFER_E;
  20834. /* eat end of line characters */
  20835. newline = SkipEndOfLineChars(newline, bufferEnd);
  20836. /* return new headerEnd */
  20837. *pBuffer = newline;
  20838. }
  20839. return err;
  20840. }
  20841. #endif /* WOLFSSL_PEM_TO_DER */
  20842. #ifdef WOLFSSL_DER_TO_PEM
  20843. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  20844. {
  20845. if (cipherInfo != NULL) {
  20846. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  20847. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  20848. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  20849. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  20850. /* strncat's src length needs to include the NULL */
  20851. XSTRNCAT(dest, kProcTypeHeader, 10);
  20852. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  20853. XSTRNCAT(dest, kDecInfoHeader, 9);
  20854. XSTRNCAT(dest, ": ", 3);
  20855. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  20856. XSTRNCAT(dest, "\n\n", 4);
  20857. }
  20858. }
  20859. return 0;
  20860. }
  20861. #endif /* WOLFSSL_DER_TO_PEM */
  20862. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  20863. #ifdef WOLFSSL_DER_TO_PEM
  20864. /* Used for compatibility API */
  20865. WOLFSSL_ABI
  20866. int wc_DerToPem(const byte* der, word32 derSz,
  20867. byte* output, word32 outSz, int type)
  20868. {
  20869. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  20870. }
  20871. /* convert der buffer to pem into output, can't do inplace, der and output
  20872. need to be different */
  20873. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  20874. byte *cipher_info, int type)
  20875. {
  20876. const char* headerStr = NULL;
  20877. const char* footerStr = NULL;
  20878. #ifdef WOLFSSL_SMALL_STACK
  20879. char* header = NULL;
  20880. char* footer = NULL;
  20881. #else
  20882. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  20883. char footer[MAX_X509_HEADER_SZ];
  20884. #endif
  20885. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  20886. int footerLen = MAX_X509_HEADER_SZ;
  20887. int i;
  20888. int err;
  20889. int outLen; /* return length or error */
  20890. (void)cipher_info;
  20891. if (der == output) /* no in place conversion */
  20892. return BAD_FUNC_ARG;
  20893. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  20894. if (err != 0)
  20895. return err;
  20896. #ifdef WOLFSSL_SMALL_STACK
  20897. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20898. if (header == NULL)
  20899. return MEMORY_E;
  20900. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20901. if (footer == NULL) {
  20902. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20903. return MEMORY_E;
  20904. }
  20905. #endif
  20906. /* build header and footer based on type */
  20907. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  20908. header[headerLen - 2] = 0;
  20909. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  20910. footer[footerLen - 2] = 0;
  20911. /* add new line to end */
  20912. XSTRNCAT(header, "\n", 2);
  20913. XSTRNCAT(footer, "\n", 2);
  20914. #ifdef WOLFSSL_ENCRYPTED_KEYS
  20915. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  20916. if (err != 0) {
  20917. #ifdef WOLFSSL_SMALL_STACK
  20918. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20919. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20920. #endif
  20921. return err;
  20922. }
  20923. #endif
  20924. headerLen = (int)XSTRLEN(header);
  20925. footerLen = (int)XSTRLEN(footer);
  20926. /* if null output and 0 size passed in then return size needed */
  20927. if (!output && outSz == 0) {
  20928. #ifdef WOLFSSL_SMALL_STACK
  20929. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20930. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20931. #endif
  20932. outLen = 0;
  20933. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  20934. != LENGTH_ONLY_E) {
  20935. WOLFSSL_ERROR_VERBOSE(err);
  20936. return err;
  20937. }
  20938. return headerLen + footerLen + outLen;
  20939. }
  20940. if (!der || !output) {
  20941. #ifdef WOLFSSL_SMALL_STACK
  20942. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20943. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20944. #endif
  20945. return BAD_FUNC_ARG;
  20946. }
  20947. /* don't even try if outSz too short */
  20948. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  20949. #ifdef WOLFSSL_SMALL_STACK
  20950. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20951. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20952. #endif
  20953. return BAD_FUNC_ARG;
  20954. }
  20955. /* header */
  20956. XMEMCPY(output, header, (size_t)headerLen);
  20957. i = headerLen;
  20958. #ifdef WOLFSSL_SMALL_STACK
  20959. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20960. #endif
  20961. /* body */
  20962. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  20963. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  20964. #ifdef WOLFSSL_SMALL_STACK
  20965. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20966. #endif
  20967. WOLFSSL_ERROR_VERBOSE(err);
  20968. return err;
  20969. }
  20970. i += outLen;
  20971. /* footer */
  20972. if ( (i + footerLen) > (int)outSz) {
  20973. #ifdef WOLFSSL_SMALL_STACK
  20974. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20975. #endif
  20976. return BAD_FUNC_ARG;
  20977. }
  20978. XMEMCPY(output + i, footer, (size_t)footerLen);
  20979. #ifdef WOLFSSL_SMALL_STACK
  20980. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  20981. #endif
  20982. return outLen + headerLen + footerLen;
  20983. }
  20984. #endif /* WOLFSSL_DER_TO_PEM */
  20985. #ifdef WOLFSSL_PEM_TO_DER
  20986. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  20987. info->consumed tracks of PEM bytes consumed in case multiple parts */
  20988. int PemToDer(const unsigned char* buff, long longSz, int type,
  20989. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  20990. {
  20991. const char* header = NULL;
  20992. const char* footer = NULL;
  20993. const char* headerEnd;
  20994. const char* footerEnd;
  20995. const char* consumedEnd;
  20996. const char* bufferEnd = (const char*)(buff + longSz);
  20997. long neededSz;
  20998. int ret = 0;
  20999. int sz = (int)longSz;
  21000. int encrypted_key = 0;
  21001. DerBuffer* der;
  21002. word32 algId = 0;
  21003. word32 idx;
  21004. #ifdef OPENSSL_EXTRA
  21005. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21006. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21007. #endif
  21008. WOLFSSL_ENTER("PemToDer");
  21009. /* get PEM header and footer based on type */
  21010. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  21011. if (ret != 0)
  21012. return ret;
  21013. /* map header if not found for type */
  21014. for (;;) {
  21015. headerEnd = XSTRNSTR((char*)buff, header, (word32)sz);
  21016. if (headerEnd) {
  21017. break;
  21018. }
  21019. if (type == PRIVATEKEY_TYPE) {
  21020. if (header == BEGIN_RSA_PRIV) {
  21021. header = BEGIN_PRIV_KEY;
  21022. footer = END_PRIV_KEY;
  21023. }
  21024. else if (header == BEGIN_PRIV_KEY) {
  21025. header = BEGIN_ENC_PRIV_KEY;
  21026. footer = END_ENC_PRIV_KEY;
  21027. }
  21028. #ifdef HAVE_ECC
  21029. else if (header == BEGIN_ENC_PRIV_KEY) {
  21030. header = BEGIN_EC_PRIV;
  21031. footer = END_EC_PRIV;
  21032. }
  21033. else if (header == BEGIN_EC_PRIV) {
  21034. header = BEGIN_DSA_PRIV;
  21035. footer = END_DSA_PRIV;
  21036. }
  21037. #endif
  21038. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21039. #ifdef HAVE_ECC
  21040. else if (header == BEGIN_DSA_PRIV) {
  21041. #else
  21042. else if (header == BEGIN_ENC_PRIV_KEY) {
  21043. #endif
  21044. header = BEGIN_EDDSA_PRIV;
  21045. footer = END_EDDSA_PRIV;
  21046. }
  21047. #endif
  21048. else {
  21049. #ifdef WOLF_PRIVATE_KEY_ID
  21050. /* allow loading a public key for use with crypto or PK callbacks */
  21051. type = PUBLICKEY_TYPE;
  21052. header = BEGIN_PUB_KEY;
  21053. footer = END_PUB_KEY;
  21054. #else
  21055. break;
  21056. #endif
  21057. }
  21058. }
  21059. else if (type == PUBLICKEY_TYPE) {
  21060. if (header == BEGIN_PUB_KEY) {
  21061. header = BEGIN_RSA_PUB;
  21062. footer = END_RSA_PUB;
  21063. }
  21064. else {
  21065. break;
  21066. }
  21067. }
  21068. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  21069. else if (type == ECC_PARAM_TYPE) {
  21070. if (header == BEGIN_EC_PARAM) {
  21071. header = BEGIN_EC_PARAM;
  21072. footer = END_EC_PARAM;
  21073. }
  21074. else {
  21075. break;
  21076. }
  21077. }
  21078. #endif
  21079. #ifdef HAVE_CRL
  21080. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  21081. header = BEGIN_X509_CRL;
  21082. footer = END_X509_CRL;
  21083. }
  21084. #endif
  21085. else {
  21086. break;
  21087. }
  21088. }
  21089. if (!headerEnd) {
  21090. #ifdef OPENSSL_EXTRA
  21091. if (type == PRIVATEKEY_TYPE) {
  21092. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  21093. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  21094. if (headerEnd) {
  21095. const char* beginEnd;
  21096. int endLen;
  21097. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  21098. if (beginEnd >= (char*)buff + sz) {
  21099. return BUFFER_E;
  21100. }
  21101. /* back up to BEGIN_PRIV_KEY_PREFIX */
  21102. while (headerEnd > (char*)buff &&
  21103. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21104. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  21105. *headerEnd != '\n') {
  21106. headerEnd--;
  21107. }
  21108. if (headerEnd <= (char*)buff ||
  21109. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21110. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  21111. beginEnd - headerEnd > PEM_LINE_LEN) {
  21112. WOLFSSL_MSG("Couldn't find PEM header");
  21113. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21114. return ASN_NO_PEM_HEADER;
  21115. }
  21116. /* headerEnd now points to beginning of header */
  21117. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  21118. beginBuf[beginEnd - headerEnd] = '\0';
  21119. /* look for matching footer */
  21120. footer = XSTRNSTR(beginEnd,
  21121. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  21122. (unsigned int)((char*)buff + sz - beginEnd));
  21123. if (!footer) {
  21124. WOLFSSL_MSG("Couldn't find PEM footer");
  21125. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21126. return ASN_NO_PEM_HEADER;
  21127. }
  21128. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  21129. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  21130. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  21131. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  21132. WOLFSSL_MSG("Unexpected footer for PEM");
  21133. return BUFFER_E;
  21134. }
  21135. endLen = (unsigned int)(beginEnd - headerEnd -
  21136. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  21137. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  21138. XMEMCPY(endBuf, footer, endLen);
  21139. endBuf[endLen] = '\0';
  21140. header = beginBuf;
  21141. footer = endBuf;
  21142. headerEnd = beginEnd;
  21143. }
  21144. }
  21145. if (!headerEnd) {
  21146. WOLFSSL_MSG("Couldn't find PEM header");
  21147. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21148. return ASN_NO_PEM_HEADER;
  21149. }
  21150. #else
  21151. WOLFSSL_MSG("Couldn't find PEM header");
  21152. return ASN_NO_PEM_HEADER;
  21153. #endif
  21154. } else {
  21155. headerEnd += XSTRLEN(header);
  21156. }
  21157. /* eat end of line characters */
  21158. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  21159. if (keyFormat) {
  21160. /* keyFormat is Key_Sum enum */
  21161. if (type == PRIVATEKEY_TYPE) {
  21162. #ifndef NO_RSA
  21163. if (header == BEGIN_RSA_PRIV)
  21164. *keyFormat = RSAk;
  21165. #endif
  21166. #ifdef HAVE_ECC
  21167. if (header == BEGIN_EC_PRIV)
  21168. *keyFormat = ECDSAk;
  21169. #endif
  21170. #ifndef NO_DSA
  21171. if (header == BEGIN_DSA_PRIV)
  21172. *keyFormat = DSAk;
  21173. #endif
  21174. }
  21175. #ifdef WOLF_PRIVATE_KEY_ID
  21176. else if (type == PUBLICKEY_TYPE) {
  21177. #ifndef NO_RSA
  21178. if (header == BEGIN_RSA_PUB)
  21179. *keyFormat = RSAk;
  21180. #endif
  21181. }
  21182. #endif
  21183. }
  21184. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21185. if (info) {
  21186. ret = wc_EncryptedInfoParse(info, &headerEnd,
  21187. (size_t)(bufferEnd - headerEnd));
  21188. if (ret < 0)
  21189. return ret;
  21190. if (info->set)
  21191. encrypted_key = 1;
  21192. }
  21193. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21194. /* find footer */
  21195. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  21196. sz - headerEnd));
  21197. if (!footerEnd) {
  21198. if (info)
  21199. info->consumed = longSz; /* No more certs if no footer */
  21200. return BUFFER_E;
  21201. }
  21202. consumedEnd = footerEnd + XSTRLEN(footer);
  21203. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  21204. /* eat end of line characters */
  21205. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  21206. /* skip possible null term */
  21207. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  21208. consumedEnd++;
  21209. }
  21210. if (info)
  21211. info->consumed = (long)(consumedEnd - (const char*)buff);
  21212. /* set up der buffer */
  21213. neededSz = (long)(footerEnd - headerEnd);
  21214. if (neededSz > sz || neededSz <= 0)
  21215. return BUFFER_E;
  21216. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  21217. if (ret < 0) {
  21218. return ret;
  21219. }
  21220. der = *pDer;
  21221. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  21222. der->buffer, &der->length) < 0) {
  21223. WOLFSSL_ERROR(BUFFER_E);
  21224. return BUFFER_E;
  21225. }
  21226. if ((header == BEGIN_PRIV_KEY
  21227. #ifdef OPENSSL_EXTRA
  21228. || header == beginBuf
  21229. #endif
  21230. #ifdef HAVE_ECC
  21231. || header == BEGIN_EC_PRIV
  21232. #endif
  21233. ) && !encrypted_key)
  21234. {
  21235. /* detect pkcs8 key and get alg type */
  21236. /* keep PKCS8 header */
  21237. idx = 0;
  21238. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  21239. if (ret > 0) {
  21240. if (keyFormat)
  21241. *keyFormat = (int)algId;
  21242. }
  21243. else {
  21244. /* ignore failure here and assume key is not pkcs8 wrapped */
  21245. }
  21246. return 0;
  21247. }
  21248. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21249. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  21250. int passwordSz = NAME_SZ;
  21251. #ifdef WOLFSSL_SMALL_STACK
  21252. char* password = NULL;
  21253. #else
  21254. char password[NAME_SZ];
  21255. #endif
  21256. if (!info || !info->passwd_cb) {
  21257. WOLFSSL_MSG("No password callback set");
  21258. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21259. return NO_PASSWORD;
  21260. }
  21261. #ifdef WOLFSSL_SMALL_STACK
  21262. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  21263. if (password == NULL) {
  21264. return MEMORY_E;
  21265. }
  21266. #endif
  21267. /* get password */
  21268. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  21269. info->passwd_userdata);
  21270. if (ret >= 0) {
  21271. passwordSz = ret;
  21272. #ifdef WOLFSSL_CHECK_MEM_ZERO
  21273. wc_MemZero_Add("PEM password", password, passwordSz);
  21274. #endif
  21275. /* convert and adjust length */
  21276. if (header == BEGIN_ENC_PRIV_KEY) {
  21277. #ifndef NO_PWDBASED
  21278. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  21279. password, passwordSz);
  21280. if (ret > 0) {
  21281. /* update length by decrypted content */
  21282. der->length = (word32)ret;
  21283. idx = 0;
  21284. /* detect pkcs8 key and get alg type */
  21285. /* keep PKCS8 header */
  21286. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  21287. &algId);
  21288. if (ret >= 0) {
  21289. if (keyFormat)
  21290. *keyFormat = (int)algId;
  21291. ret = 0;
  21292. }
  21293. }
  21294. #else
  21295. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  21296. ret = NOT_COMPILED_IN;
  21297. #endif
  21298. }
  21299. /* decrypt the key */
  21300. else {
  21301. if (passwordSz == 0) {
  21302. /* The key is encrypted but does not have a password */
  21303. WOLFSSL_MSG("No password for encrypted key");
  21304. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21305. ret = NO_PASSWORD;
  21306. }
  21307. else {
  21308. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  21309. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21310. defined(HAVE_AES_DECRYPT))) && \
  21311. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  21312. int padVal = 0;
  21313. #endif
  21314. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  21315. (byte*)password, passwordSz, WC_MD5);
  21316. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  21317. #ifndef NO_DES3
  21318. if (info->cipherType == WC_CIPHER_DES3) {
  21319. /* Assuming there is padding:
  21320. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  21321. * (der->length % DES_BLOCK_SIZE) != 0)
  21322. * and assuming the last value signifies the number of
  21323. * padded bytes IE if last value is 0x08 then there are
  21324. * 8 bytes of padding:
  21325. * padVal = der->buffer[der->length-1];
  21326. * then strip this padding before proceeding:
  21327. * der->length -= padVal;
  21328. */
  21329. if (der->length > DES_BLOCK_SIZE &&
  21330. (der->length % DES_BLOCK_SIZE) != 0) {
  21331. padVal = der->buffer[der->length-1];
  21332. if (padVal < DES_BLOCK_SIZE) {
  21333. der->length -= (word32)padVal;
  21334. }
  21335. }
  21336. }
  21337. #endif /* !NO_DES3 */
  21338. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21339. defined(HAVE_AES_DECRYPT)
  21340. if (info->cipherType == WC_CIPHER_AES_CBC) {
  21341. if (der->length > AES_BLOCK_SIZE) {
  21342. padVal = der->buffer[der->length-1];
  21343. if (padVal <= AES_BLOCK_SIZE) {
  21344. der->length -= (word32)padVal;
  21345. }
  21346. }
  21347. }
  21348. #endif
  21349. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  21350. }
  21351. }
  21352. #ifdef OPENSSL_EXTRA
  21353. if (ret) {
  21354. PEMerr(0, PEM_R_BAD_DECRYPT);
  21355. }
  21356. #endif
  21357. ForceZero(password, (word32)passwordSz);
  21358. }
  21359. #ifdef OPENSSL_EXTRA
  21360. else {
  21361. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  21362. }
  21363. #endif
  21364. #ifdef WOLFSSL_SMALL_STACK
  21365. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  21366. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  21367. wc_MemZero_Check(password, NAME_SZ);
  21368. #endif
  21369. }
  21370. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21371. return ret;
  21372. }
  21373. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  21374. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21375. {
  21376. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  21377. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  21378. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  21379. DerBuffer* der = *pDer;
  21380. /* if a PKCS8 key header exists remove it */
  21381. ret = ToTraditional(der->buffer, der->length);
  21382. if (ret > 0) {
  21383. der->length = (word32)ret;
  21384. }
  21385. ret = 0; /* ignore error removing PKCS8 header */
  21386. }
  21387. #endif
  21388. return ret;
  21389. }
  21390. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21391. /* our KeyPemToDer password callback, password in userData */
  21392. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  21393. {
  21394. (void)rw;
  21395. if (userdata == NULL)
  21396. return 0;
  21397. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  21398. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  21399. }
  21400. #endif
  21401. /* Return bytes written to buff or < 0 for error */
  21402. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  21403. unsigned char* buff, int buffSz, const char* pass)
  21404. {
  21405. int ret;
  21406. DerBuffer* der = NULL;
  21407. #ifdef WOLFSSL_SMALL_STACK
  21408. EncryptedInfo* info = NULL;
  21409. #else
  21410. EncryptedInfo info[1];
  21411. #endif
  21412. WOLFSSL_ENTER("wc_KeyPemToDer");
  21413. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  21414. WOLFSSL_MSG("Bad pem der args");
  21415. return BAD_FUNC_ARG;
  21416. }
  21417. #ifdef WOLFSSL_SMALL_STACK
  21418. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  21419. DYNAMIC_TYPE_ENCRYPTEDINFO);
  21420. if (info == NULL)
  21421. return MEMORY_E;
  21422. #endif
  21423. XMEMSET(info, 0, sizeof(EncryptedInfo));
  21424. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21425. info->passwd_cb = KeyPemToDerPassCb;
  21426. info->passwd_userdata = (void*)pass;
  21427. #else
  21428. (void)pass;
  21429. #endif
  21430. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  21431. #ifdef WOLFSSL_SMALL_STACK
  21432. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  21433. #endif
  21434. if (ret < 0 || der == NULL) {
  21435. WOLFSSL_MSG("Bad Pem To Der");
  21436. }
  21437. else if (buff == NULL) {
  21438. WOLFSSL_MSG("Return needed der buff length");
  21439. ret = (int)der->length;
  21440. }
  21441. else if (der->length <= (word32)buffSz) {
  21442. XMEMCPY(buff, der->buffer, der->length);
  21443. ret = (int)der->length;
  21444. }
  21445. else {
  21446. WOLFSSL_MSG("Bad der length");
  21447. ret = BAD_FUNC_ARG;
  21448. }
  21449. FreeDer(&der);
  21450. return ret;
  21451. }
  21452. /* Return bytes written to buff or < 0 for error */
  21453. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  21454. unsigned char* buff, int buffSz, int type)
  21455. {
  21456. int ret;
  21457. DerBuffer* der = NULL;
  21458. WOLFSSL_ENTER("wc_CertPemToDer");
  21459. if (pem == NULL || buff == NULL || buffSz <= 0) {
  21460. WOLFSSL_MSG("Bad pem der args");
  21461. return BAD_FUNC_ARG;
  21462. }
  21463. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  21464. WOLFSSL_MSG("Bad cert type");
  21465. return BAD_FUNC_ARG;
  21466. }
  21467. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  21468. if (ret < 0 || der == NULL) {
  21469. WOLFSSL_MSG("Bad Pem To Der");
  21470. }
  21471. else {
  21472. if (der->length <= (word32)buffSz) {
  21473. XMEMCPY(buff, der->buffer, der->length);
  21474. ret = (int)der->length;
  21475. }
  21476. else {
  21477. WOLFSSL_MSG("Bad der length");
  21478. ret = BAD_FUNC_ARG;
  21479. }
  21480. }
  21481. FreeDer(&der);
  21482. return ret;
  21483. }
  21484. #endif /* WOLFSSL_PEM_TO_DER */
  21485. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  21486. #ifdef WOLFSSL_PEM_TO_DER
  21487. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21488. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  21489. zero for error */
  21490. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  21491. unsigned char* buff, int buffSz)
  21492. {
  21493. int ret;
  21494. DerBuffer* der = NULL;
  21495. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  21496. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  21497. WOLFSSL_MSG("Bad pem der args");
  21498. return BAD_FUNC_ARG;
  21499. }
  21500. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  21501. if (ret < 0 || der == NULL) {
  21502. WOLFSSL_MSG("Bad Pem To Der");
  21503. }
  21504. else if (buff == NULL) {
  21505. WOLFSSL_MSG("Return needed der buff length");
  21506. ret = (int)der->length;
  21507. }
  21508. else if (der->length <= (word32)buffSz) {
  21509. XMEMCPY(buff, der->buffer, der->length);
  21510. ret = (int)der->length;
  21511. }
  21512. else {
  21513. WOLFSSL_MSG("Bad der length");
  21514. ret = BAD_FUNC_ARG;
  21515. }
  21516. FreeDer(&der);
  21517. return ret;
  21518. }
  21519. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21520. #endif /* WOLFSSL_PEM_TO_DER */
  21521. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  21522. #ifdef WOLFSSL_CERT_GEN
  21523. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  21524. {
  21525. #ifndef WOLFSSL_SMALL_STACK
  21526. byte staticBuffer[FILE_BUFFER_SIZE];
  21527. #endif
  21528. byte* fileBuf = NULL;
  21529. int ret = 0;
  21530. XFILE file = XBADFILE;
  21531. int dynamic = 0;
  21532. long sz = 0;
  21533. WOLFSSL_ENTER("wc_PemCertToDer");
  21534. if (fileName == NULL) {
  21535. ret = BAD_FUNC_ARG;
  21536. }
  21537. else {
  21538. file = XFOPEN(fileName, "rb");
  21539. if (file == XBADFILE) {
  21540. ret = IO_FAILED_E;
  21541. }
  21542. }
  21543. if (ret == 0) {
  21544. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21545. ret = IO_FAILED_E;
  21546. }
  21547. }
  21548. if (ret == 0) {
  21549. sz = XFTELL(file);
  21550. if (sz <= 0) {
  21551. ret = IO_FAILED_E;
  21552. }
  21553. }
  21554. if (ret == 0) {
  21555. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  21556. ret = IO_FAILED_E;
  21557. }
  21558. }
  21559. if (ret == 0) {
  21560. #ifndef WOLFSSL_SMALL_STACK
  21561. if (sz <= (long)sizeof(staticBuffer))
  21562. fileBuf = staticBuffer;
  21563. else
  21564. #endif
  21565. {
  21566. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  21567. if (fileBuf == NULL)
  21568. ret = MEMORY_E;
  21569. else
  21570. dynamic = 1;
  21571. }
  21572. }
  21573. if (ret == 0) {
  21574. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  21575. ret = IO_FAILED_E;
  21576. }
  21577. else {
  21578. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  21579. }
  21580. }
  21581. if (file != XBADFILE)
  21582. XFCLOSE(file);
  21583. if (dynamic)
  21584. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  21585. return ret;
  21586. }
  21587. /* load pem cert from file into der buffer, return der size or error */
  21588. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  21589. {
  21590. int ret;
  21591. DerBuffer* converted = NULL;
  21592. ret = wc_PemCertToDer_ex(fileName, &converted);
  21593. if (ret == 0) {
  21594. if (converted->length < (word32)derSz) {
  21595. XMEMCPY(derBuf, converted->buffer, converted->length);
  21596. ret = (int)converted->length;
  21597. }
  21598. else
  21599. ret = BUFFER_E;
  21600. FreeDer(&converted);
  21601. }
  21602. return ret;
  21603. }
  21604. #endif /* WOLFSSL_CERT_GEN */
  21605. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  21606. /* load pem public key from file into der buffer, return der size or error */
  21607. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  21608. {
  21609. #ifndef WOLFSSL_SMALL_STACK
  21610. byte staticBuffer[FILE_BUFFER_SIZE];
  21611. #endif
  21612. byte* fileBuf = NULL;
  21613. int dynamic = 0;
  21614. int ret = 0;
  21615. long sz = 0;
  21616. XFILE file = XBADFILE;
  21617. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  21618. if (fileName == NULL) {
  21619. ret = BAD_FUNC_ARG;
  21620. }
  21621. else {
  21622. file = XFOPEN(fileName, "rb");
  21623. if (file == XBADFILE) {
  21624. ret = IO_FAILED_E;
  21625. }
  21626. }
  21627. if (ret == 0) {
  21628. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  21629. ret = IO_FAILED_E;
  21630. }
  21631. }
  21632. if (ret == 0) {
  21633. sz = XFTELL(file);
  21634. if (sz <= 0) {
  21635. ret = IO_FAILED_E;
  21636. }
  21637. }
  21638. if (ret == 0) {
  21639. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  21640. ret = IO_FAILED_E;
  21641. }
  21642. }
  21643. if (ret == 0) {
  21644. #ifndef WOLFSSL_SMALL_STACK
  21645. if (sz <= (long)sizeof(staticBuffer))
  21646. fileBuf = staticBuffer;
  21647. else
  21648. #endif
  21649. {
  21650. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  21651. if (fileBuf == NULL)
  21652. ret = MEMORY_E;
  21653. else
  21654. dynamic = 1;
  21655. }
  21656. }
  21657. if (ret == 0) {
  21658. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  21659. ret = BUFFER_E;
  21660. }
  21661. else {
  21662. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  21663. 0, NULL, NULL);
  21664. }
  21665. }
  21666. if (file != XBADFILE)
  21667. XFCLOSE(file);
  21668. if (dynamic)
  21669. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  21670. return ret;
  21671. }
  21672. /* load pem public key from file into der buffer, return der size or error */
  21673. int wc_PemPubKeyToDer(const char* fileName,
  21674. unsigned char* derBuf, int derSz)
  21675. {
  21676. int ret;
  21677. DerBuffer* converted = NULL;
  21678. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  21679. if (ret == 0) {
  21680. if (converted->length < (word32)derSz) {
  21681. XMEMCPY(derBuf, converted->buffer, converted->length);
  21682. ret = (int)converted->length;
  21683. }
  21684. else
  21685. ret = BUFFER_E;
  21686. FreeDer(&converted);
  21687. }
  21688. return ret;
  21689. }
  21690. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  21691. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  21692. /* Get public key in DER format from a populated DecodedCert struct.
  21693. *
  21694. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  21695. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  21696. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  21697. * wc_InitDecodedCert().
  21698. *
  21699. * cert - populated DecodedCert struct holding X.509 certificate
  21700. * derKey - output buffer to place DER/ASN.1 encoded public key
  21701. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  21702. * on return. If derKey is passed in as NULL, derKeySz
  21703. * will be set to required buffer size for public key
  21704. * and LENGTH_ONLY_E will be returned from function.
  21705. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  21706. * if derKey is NULL and returning length only.
  21707. */
  21708. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  21709. byte* derKey, word32* derKeySz)
  21710. {
  21711. int ret = 0;
  21712. /* derKey may be NULL to return length only */
  21713. if (cert == NULL || derKeySz == NULL ||
  21714. (derKey != NULL && *derKeySz == 0)) {
  21715. return BAD_FUNC_ARG;
  21716. }
  21717. if (cert->publicKey == NULL) {
  21718. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  21719. return BAD_FUNC_ARG;
  21720. }
  21721. /* if derKey is NULL, return required output buffer size in derKeySz */
  21722. if (derKey == NULL) {
  21723. *derKeySz = cert->pubKeySize;
  21724. ret = LENGTH_ONLY_E;
  21725. }
  21726. if (ret == 0) {
  21727. if (cert->pubKeySize > *derKeySz) {
  21728. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  21729. ret = BAD_FUNC_ARG;
  21730. }
  21731. else {
  21732. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  21733. *derKeySz = cert->pubKeySize;
  21734. }
  21735. }
  21736. return ret;
  21737. }
  21738. #ifdef WOLFSSL_FPKI
  21739. /* Search through list for first matching alt name of the same type
  21740. * If 'current' is null then the search starts at the head of the list
  21741. * otherwise the search starts from the node after 'current' alt name.
  21742. * Returns 0 on success
  21743. */
  21744. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  21745. DNS_entry* current)
  21746. {
  21747. DNS_entry* entry;
  21748. if (current == NULL) {
  21749. entry = cert->altNames;
  21750. }
  21751. else {
  21752. entry = current->next;
  21753. }
  21754. /* cycle through alt names to check for needed types */
  21755. while (entry != NULL) {
  21756. if (entry->type == nameType) {
  21757. break;
  21758. }
  21759. entry = entry->next;
  21760. }
  21761. return entry;
  21762. }
  21763. /* returns 0 on success */
  21764. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  21765. {
  21766. int ret = ALT_NAME_E;
  21767. DNS_entry* id = NULL;
  21768. do {
  21769. id = FindAltName(cert, ASN_URI_TYPE, id);
  21770. if (id != NULL) {
  21771. /* check if URI string matches expected format for UUID */
  21772. if (id->len != DEFAULT_UUID_SZ) {
  21773. continue; /* size not right not a UUID URI */
  21774. }
  21775. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  21776. continue; /* beginning text not right for a UUID URI */
  21777. }
  21778. if (uuid == NULL) {
  21779. *uuidSz = id->len;
  21780. return LENGTH_ONLY_E;
  21781. }
  21782. if ((int)*uuidSz < id->len) {
  21783. return BUFFER_E;
  21784. }
  21785. XMEMCPY(uuid, id->name, id->len);
  21786. ret = 0; /* success */
  21787. break;
  21788. }
  21789. } while (id != NULL);
  21790. return ret;
  21791. }
  21792. /* reutrns 0 on success */
  21793. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  21794. {
  21795. int ret = ALT_NAME_E;
  21796. DNS_entry* id = NULL;
  21797. do {
  21798. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  21799. if (id != NULL && id->oidSum == FASCN_OID) {
  21800. if (fascn == NULL) {
  21801. *fascnSz = id->len;
  21802. return LENGTH_ONLY_E;
  21803. }
  21804. if ((int)*fascnSz < id->len) {
  21805. return BUFFER_E;
  21806. }
  21807. XMEMCPY(fascn, id->name, id->len);
  21808. ret = 0; /* success */
  21809. }
  21810. } while (id != NULL);
  21811. return ret;
  21812. }
  21813. #endif /* WOLFSSL_FPKI */
  21814. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  21815. defined(WOLFSSL_KCAPI_RSA) || \
  21816. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  21817. /* USER RSA ifdef portions used instead of refactor in consideration for
  21818. possible fips build */
  21819. /* Encode a public RSA key to output.
  21820. *
  21821. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21822. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21823. *
  21824. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  21825. * (RSAPublicKey).
  21826. *
  21827. * @param [out] output Buffer to put encoded data in.
  21828. * @param [in] key RSA key object.
  21829. * @param [in] outLen Size of the output buffer in bytes.
  21830. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  21831. * @return Size of encoded data in bytes on success.
  21832. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  21833. * minimum length (5 bytes).
  21834. * @return MEMORY_E when dynamic memory allocation failed.
  21835. */
  21836. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  21837. int with_header)
  21838. {
  21839. #ifndef WOLFSSL_ASN_TEMPLATE
  21840. int nSz, eSz;
  21841. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  21842. byte seq[MAX_SEQ_SZ];
  21843. byte headSeq[MAX_SEQ_SZ];
  21844. byte bitString[1 + MAX_LENGTH_SZ + 1];
  21845. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  21846. if (key == NULL) {
  21847. return BAD_FUNC_ARG;
  21848. }
  21849. #ifdef HAVE_USER_RSA
  21850. nSz = SetASNIntRSA(key->n, NULL);
  21851. #else
  21852. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  21853. #endif
  21854. if (nSz < 0)
  21855. return nSz;
  21856. #ifdef HAVE_USER_RSA
  21857. eSz = SetASNIntRSA(key->e, NULL);
  21858. #else
  21859. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  21860. #endif
  21861. if (eSz < 0)
  21862. return eSz;
  21863. seqSz = SetSequence((word32)(nSz + eSz), seq);
  21864. /* headers */
  21865. if (with_header) {
  21866. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  21867. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  21868. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  21869. headSeq);
  21870. }
  21871. /* if getting length only */
  21872. if (output == NULL) {
  21873. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  21874. }
  21875. /* check output size */
  21876. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  21877. return BUFFER_E;
  21878. }
  21879. /* write output */
  21880. idx = 0;
  21881. if (with_header) {
  21882. /* header size */
  21883. XMEMCPY(output + idx, headSeq, headSz);
  21884. idx += headSz;
  21885. /* algo */
  21886. XMEMCPY(output + idx, algo, algoSz);
  21887. idx += algoSz;
  21888. /* bit string */
  21889. XMEMCPY(output + idx, bitString, bitStringSz);
  21890. idx += bitStringSz;
  21891. }
  21892. /* seq */
  21893. XMEMCPY(output + idx, seq, seqSz);
  21894. idx += seqSz;
  21895. /* n */
  21896. #ifdef HAVE_USER_RSA
  21897. nSz = SetASNIntRSA(key->n, output + idx);
  21898. #else
  21899. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  21900. #endif
  21901. idx += (word32)nSz;
  21902. /* e */
  21903. #ifdef HAVE_USER_RSA
  21904. eSz = SetASNIntRSA(key->e, output + idx);
  21905. #else
  21906. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  21907. #endif
  21908. idx += (word32)eSz;
  21909. return (int)idx;
  21910. #else
  21911. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  21912. int sz = 0;
  21913. int ret = 0;
  21914. int o = 0;
  21915. /* Check parameter validity. */
  21916. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  21917. ret = BAD_FUNC_ARG;
  21918. }
  21919. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  21920. if (ret == 0) {
  21921. if (!with_header) {
  21922. /* Start encoding with items after header. */
  21923. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  21924. }
  21925. /* Set OID for RSA key. */
  21926. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  21927. #ifdef WC_RSA_PSS
  21928. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  21929. #endif
  21930. /* Set public key mp_ints. */
  21931. #ifdef HAVE_USER_RSA
  21932. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  21933. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  21934. #else
  21935. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  21936. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  21937. #endif
  21938. /* Calculate size of RSA public key. */
  21939. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  21940. (int)rsaPublicKeyASN_Length - o, &sz);
  21941. }
  21942. /* Check output buffer is big enough for encoding. */
  21943. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  21944. ret = BUFFER_E;
  21945. }
  21946. if ((ret == 0) && (output != NULL)) {
  21947. /* Encode RSA public key. */
  21948. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  21949. (int)rsaPublicKeyASN_Length - o, output);
  21950. }
  21951. if (ret == 0) {
  21952. /* Return size of encoding. */
  21953. ret = sz;
  21954. }
  21955. FREE_ASNSETDATA(dataASN, key->heap);
  21956. return ret;
  21957. #endif /* WOLFSSL_ASN_TEMPLATE */
  21958. }
  21959. /* Calculate size of encoded public RSA key in bytes.
  21960. *
  21961. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21962. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21963. *
  21964. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  21965. * (RSAPublicKey).
  21966. *
  21967. * @param [in] key RSA key object.
  21968. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  21969. * @return Size of encoded data in bytes on success.
  21970. * @return BAD_FUNC_ARG when key is NULL.
  21971. * @return MEMORY_E when dynamic memory allocation failed.
  21972. */
  21973. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  21974. {
  21975. return SetRsaPublicKey(NULL, key, 0, with_header);
  21976. }
  21977. /* Encode public RSA key in DER format.
  21978. *
  21979. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  21980. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  21981. *
  21982. * @param [in] key RSA key object.
  21983. * @param [out] output Buffer to put encoded data in.
  21984. * @param [in] inLen Size of buffer in bytes.
  21985. * @return Size of encoded data in bytes on success.
  21986. * @return BAD_FUNC_ARG when key or output is NULL.
  21987. * @return MEMORY_E when dynamic memory allocation failed.
  21988. */
  21989. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  21990. {
  21991. return SetRsaPublicKey(output, key, (int)inLen, 1);
  21992. }
  21993. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  21994. * seq + n + e is returned in ASN.1 DER format */
  21995. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  21996. int with_header)
  21997. {
  21998. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  21999. }
  22000. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  22001. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  22002. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  22003. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  22004. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  22005. /* Encode private RSA key in DER format.
  22006. *
  22007. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  22008. *
  22009. * @param [in] key RSA key object.
  22010. * @param [out] output Buffer to put encoded data in.
  22011. * @param [in] inLen Size of buffer in bytes.
  22012. * @return Size of encoded data in bytes on success.
  22013. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22014. * @return MEMORY_E when dynamic memory allocation failed.
  22015. */
  22016. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22017. {
  22018. #ifndef WOLFSSL_ASN_TEMPLATE
  22019. int ret = 0, i;
  22020. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
  22021. word32 sizes[RSA_INTS];
  22022. byte seq[MAX_SEQ_SZ];
  22023. byte ver[MAX_VERSION_SZ];
  22024. byte* tmps[RSA_INTS];
  22025. if (key == NULL)
  22026. return BAD_FUNC_ARG;
  22027. if (key->type != RSA_PRIVATE)
  22028. return BAD_FUNC_ARG;
  22029. for (i = 0; i < RSA_INTS; i++)
  22030. tmps[i] = NULL;
  22031. /* write all big ints from key to DER tmps */
  22032. for (i = 0; i < RSA_INTS; i++) {
  22033. mp_int* keyInt = GetRsaInt(key, i);
  22034. int mpSz;
  22035. word32 rawLen;
  22036. ret = mp_unsigned_bin_size(keyInt);
  22037. if (ret < 0)
  22038. return ret;
  22039. rawLen = (word32)ret + 1;
  22040. ret = 0;
  22041. if (output != NULL) {
  22042. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22043. DYNAMIC_TYPE_RSA);
  22044. if (tmps[i] == NULL) {
  22045. ret = MEMORY_E;
  22046. break;
  22047. }
  22048. }
  22049. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  22050. if (mpSz < 0) {
  22051. ret = mpSz;
  22052. break;
  22053. }
  22054. sizes[i] = (word32)mpSz;
  22055. intTotalLen += (word32)mpSz;
  22056. }
  22057. if (ret == 0) {
  22058. /* make headers */
  22059. ret = SetMyVersion(0, ver, FALSE);
  22060. }
  22061. if (ret >= 0) {
  22062. verSz = (word32)ret;
  22063. ret = 0;
  22064. seqSz = SetSequence(verSz + intTotalLen, seq);
  22065. outLen = seqSz + verSz + intTotalLen;
  22066. if (output != NULL && outLen > inLen)
  22067. ret = BUFFER_E;
  22068. }
  22069. if (ret == 0 && output != NULL) {
  22070. word32 j;
  22071. /* write to output */
  22072. XMEMCPY(output, seq, seqSz);
  22073. j = seqSz;
  22074. XMEMCPY(output + j, ver, verSz);
  22075. j += verSz;
  22076. for (i = 0; i < RSA_INTS; i++) {
  22077. XMEMCPY(output + j, tmps[i], sizes[i]);
  22078. j += sizes[i];
  22079. }
  22080. }
  22081. for (i = 0; i < RSA_INTS; i++) {
  22082. if (tmps[i])
  22083. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  22084. }
  22085. if (ret == 0)
  22086. ret = (int)outLen;
  22087. return ret;
  22088. #else
  22089. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  22090. int i;
  22091. int sz = 0;
  22092. int ret = 0;
  22093. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  22094. ret = BAD_FUNC_ARG;
  22095. }
  22096. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  22097. if (ret == 0) {
  22098. /* Set the version. */
  22099. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  22100. /* Set all the mp_ints in private key. */
  22101. for (i = 0; i < RSA_INTS; i++) {
  22102. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  22103. }
  22104. /* Calculate size of RSA private key encoding. */
  22105. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  22106. }
  22107. /* Check output buffer has enough space for encoding. */
  22108. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  22109. ret = BAD_FUNC_ARG;
  22110. }
  22111. if ((ret == 0) && (output != NULL)) {
  22112. /* Encode RSA private key. */
  22113. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  22114. }
  22115. if (ret == 0) {
  22116. /* Return size of encoding. */
  22117. ret = sz;
  22118. }
  22119. FREE_ASNSETDATA(dataASN, key->heap);
  22120. return ret;
  22121. #endif
  22122. }
  22123. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  22124. #ifdef WOLFSSL_CERT_GEN
  22125. /* Initialize and Set Certificate defaults:
  22126. version = 3 (0x2)
  22127. serial = 0
  22128. sigType = SHA_WITH_RSA
  22129. issuer = blank
  22130. daysValid = 500
  22131. selfSigned = 1 (true) use subject as issuer
  22132. subject = blank
  22133. */
  22134. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  22135. {
  22136. #ifdef WOLFSSL_MULTI_ATTRIB
  22137. int i = 0;
  22138. #endif
  22139. if (cert == NULL) {
  22140. return BAD_FUNC_ARG;
  22141. }
  22142. XMEMSET(cert, 0, sizeof(Cert));
  22143. cert->version = 2; /* version 3 is hex 2 */
  22144. #ifndef NO_SHA
  22145. cert->sigType = CTC_SHAwRSA;
  22146. #elif !defined(NO_SHA256)
  22147. cert->sigType = CTC_SHA256wRSA;
  22148. #else
  22149. cert->sigType = 0;
  22150. #endif
  22151. cert->daysValid = 500;
  22152. cert->selfSigned = 1;
  22153. cert->keyType = RSA_KEY;
  22154. cert->issuer.countryEnc = CTC_PRINTABLE;
  22155. cert->issuer.stateEnc = CTC_UTF8;
  22156. cert->issuer.streetEnc = CTC_UTF8;
  22157. cert->issuer.localityEnc = CTC_UTF8;
  22158. cert->issuer.surEnc = CTC_UTF8;
  22159. #ifdef WOLFSSL_CERT_NAME_ALL
  22160. cert->issuer.givenNameEnc = CTC_UTF8;
  22161. cert->issuer.initialsEnc = CTC_UTF8;
  22162. cert->issuer.dnQualifierEnc = CTC_UTF8;
  22163. cert->issuer.dnNameEnc = CTC_UTF8;
  22164. #endif
  22165. cert->issuer.orgEnc = CTC_UTF8;
  22166. cert->issuer.unitEnc = CTC_UTF8;
  22167. cert->issuer.commonNameEnc = CTC_UTF8;
  22168. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  22169. cert->issuer.userIdEnc = CTC_UTF8;
  22170. cert->issuer.postalCodeEnc = CTC_UTF8;
  22171. #ifdef WOLFSSL_CERT_EXT
  22172. cert->issuer.busCatEnc = CTC_UTF8;
  22173. cert->issuer.joiCEnc = CTC_UTF8;
  22174. cert->issuer.joiStEnc = CTC_UTF8;
  22175. #endif
  22176. cert->subject.countryEnc = CTC_PRINTABLE;
  22177. cert->subject.stateEnc = CTC_UTF8;
  22178. cert->subject.streetEnc = CTC_UTF8;
  22179. cert->subject.localityEnc = CTC_UTF8;
  22180. cert->subject.surEnc = CTC_UTF8;
  22181. #ifdef WOLFSSL_CERT_NAME_ALL
  22182. cert->subject.givenNameEnc = CTC_UTF8;
  22183. cert->subject.initialsEnc = CTC_UTF8;
  22184. cert->subject.dnQualifierEnc = CTC_UTF8;
  22185. cert->subject.dnNameEnc = CTC_UTF8;
  22186. #endif
  22187. cert->subject.orgEnc = CTC_UTF8;
  22188. cert->subject.unitEnc = CTC_UTF8;
  22189. cert->subject.commonNameEnc = CTC_UTF8;
  22190. cert->subject.serialDevEnc = CTC_PRINTABLE;
  22191. cert->subject.userIdEnc = CTC_UTF8;
  22192. cert->subject.postalCodeEnc = CTC_UTF8;
  22193. #ifdef WOLFSSL_CERT_EXT
  22194. cert->subject.busCatEnc = CTC_UTF8;
  22195. cert->subject.joiCEnc = CTC_UTF8;
  22196. cert->subject.joiStEnc = CTC_UTF8;
  22197. #endif
  22198. #ifdef WOLFSSL_MULTI_ATTRIB
  22199. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  22200. cert->issuer.name[i].type = CTC_UTF8;
  22201. cert->subject.name[i].type = CTC_UTF8;
  22202. }
  22203. #endif /* WOLFSSL_MULTI_ATTRIB */
  22204. cert->heap = heap;
  22205. (void)devId; /* future */
  22206. return 0;
  22207. }
  22208. WOLFSSL_ABI
  22209. int wc_InitCert(Cert* cert)
  22210. {
  22211. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  22212. }
  22213. WOLFSSL_ABI
  22214. Cert* wc_CertNew(void* heap)
  22215. {
  22216. Cert* certNew;
  22217. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  22218. if (certNew) {
  22219. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  22220. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  22221. certNew = NULL;
  22222. }
  22223. }
  22224. return certNew;
  22225. }
  22226. WOLFSSL_ABI
  22227. void wc_CertFree(Cert* cert)
  22228. {
  22229. if (cert) {
  22230. void* heap = cert->heap;
  22231. ForceZero(cert, sizeof(Cert));
  22232. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  22233. (void)heap;
  22234. }
  22235. }
  22236. /* DER encoded x509 Certificate */
  22237. typedef struct DerCert {
  22238. byte size[MAX_LENGTH_SZ]; /* length encoded */
  22239. byte version[MAX_VERSION_SZ]; /* version encoded */
  22240. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  22241. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  22242. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  22243. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  22244. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  22245. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  22246. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  22247. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  22248. #ifdef WOLFSSL_CERT_EXT
  22249. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  22250. byte akid[MAX_KID_SZ
  22251. #ifdef WOLFSSL_AKID_NAME
  22252. + sizeof(CertName) + CTC_SERIAL_SIZE
  22253. #endif
  22254. ]; /* Authority Key Identifier extension */
  22255. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  22256. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  22257. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22258. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  22259. #endif
  22260. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  22261. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  22262. #endif
  22263. #ifdef WOLFSSL_CERT_REQ
  22264. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  22265. #ifdef WOLFSSL_CUSTOM_OID
  22266. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  22267. #endif
  22268. #endif
  22269. #ifdef WOLFSSL_ALT_NAMES
  22270. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  22271. #endif
  22272. int sizeSz; /* encoded size length */
  22273. int versionSz; /* encoded version length */
  22274. int serialSz; /* encoded serial length */
  22275. int sigAlgoSz; /* encoded sig algo length */
  22276. int issuerSz; /* encoded issuer length */
  22277. int subjectSz; /* encoded subject length */
  22278. int validitySz; /* encoded validity length */
  22279. int publicKeySz; /* encoded public key length */
  22280. int caSz; /* encoded CA extension length */
  22281. #ifdef WOLFSSL_CERT_EXT
  22282. int skidSz; /* encoded SKID extension length */
  22283. int akidSz; /* encoded SKID extension length */
  22284. int keyUsageSz; /* encoded KeyUsage extension length */
  22285. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  22286. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22287. int nsCertTypeSz; /* encoded Netscape Certifcate Type
  22288. * extension length */
  22289. #endif
  22290. int certPoliciesSz; /* encoded CertPolicies extension length*/
  22291. int crlInfoSz; /* encoded CRL Dist Points length */
  22292. #endif
  22293. #ifdef WOLFSSL_ALT_NAMES
  22294. int altNamesSz; /* encoded AltNames extension length */
  22295. #endif
  22296. int extensionsSz; /* encoded extensions total length */
  22297. int total; /* total encoded lengths */
  22298. #ifdef WOLFSSL_CERT_REQ
  22299. int attribSz;
  22300. #ifdef WOLFSSL_CUSTOM_OID
  22301. int extCustomSz;
  22302. #endif
  22303. #endif
  22304. } DerCert;
  22305. #ifdef WOLFSSL_CERT_REQ
  22306. #ifndef WOLFSSL_ASN_TEMPLATE
  22307. /* Write a set header to output */
  22308. static word32 SetPrintableString(word32 len, byte* output)
  22309. {
  22310. output[0] = ASN_PRINTABLE_STRING;
  22311. return SetLength(len, output + 1) + 1;
  22312. }
  22313. static word32 SetUTF8String(word32 len, byte* output)
  22314. {
  22315. output[0] = ASN_UTF8STRING;
  22316. return SetLength(len, output + 1) + 1;
  22317. }
  22318. #endif
  22319. #endif /* WOLFSSL_CERT_REQ */
  22320. #ifndef WOLFSSL_CERT_GEN_CACHE
  22321. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  22322. static
  22323. #endif
  22324. WOLFSSL_ABI
  22325. void wc_SetCert_Free(Cert* cert)
  22326. {
  22327. if (cert != NULL) {
  22328. cert->der = NULL;
  22329. if (cert->decodedCert) {
  22330. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  22331. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  22332. cert->decodedCert = NULL;
  22333. }
  22334. }
  22335. }
  22336. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  22337. int devId)
  22338. {
  22339. int ret;
  22340. if (cert == NULL) {
  22341. ret = BAD_FUNC_ARG;
  22342. }
  22343. else {
  22344. /* Allocate DecodedCert struct and Zero */
  22345. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22346. DYNAMIC_TYPE_DCERT);
  22347. if (cert->decodedCert == NULL) {
  22348. ret = MEMORY_E;
  22349. }
  22350. else {
  22351. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  22352. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  22353. cert->heap, devId);
  22354. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  22355. CERT_TYPE, 0, NULL);
  22356. if (ret >= 0) {
  22357. cert->der = (byte*)der;
  22358. }
  22359. else {
  22360. wc_SetCert_Free(cert);
  22361. }
  22362. }
  22363. }
  22364. return ret;
  22365. }
  22366. #endif /* WOLFSSL_CERT_GEN */
  22367. #ifdef HAVE_ECC
  22368. #ifdef WOLFSSL_ASN_TEMPLATE
  22369. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  22370. * RFC 5480, 2 - Subject Public Key Information Fields
  22371. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  22372. * X9.62 ECC point format.
  22373. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  22374. */
  22375. static const ASNItem eccPublicKeyASN[] = {
  22376. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  22377. /* AlgorithmIdentifier */
  22378. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  22379. /* algorithm */
  22380. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  22381. /* namedCurve */
  22382. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  22383. /* specifiedCurve - explicit parameters */
  22384. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  22385. /* Public Key */
  22386. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  22387. };
  22388. enum {
  22389. ECCPUBLICKEYASN_IDX_SEQ = 0,
  22390. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  22391. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  22392. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  22393. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  22394. ECCPUBLICKEYASN_IDX_PUBKEY
  22395. };
  22396. /* Number of items in ASN.1 template for ECC public key. */
  22397. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  22398. #endif /* WOLFSSL_ASN_TEMPLATE */
  22399. #endif /* HAVE_ECC */
  22400. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  22401. /* Encode public ECC key in DER format.
  22402. *
  22403. * RFC 5480, 2 - Subject Public Key Information Fields
  22404. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  22405. * X9.62 ECC point format.
  22406. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  22407. *
  22408. * @param [out] output Buffer to put encoded data in.
  22409. * @param [in] key ECC key object.
  22410. * @param [in] outLen Size of buffer in bytes.
  22411. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  22412. * @return Size of encoded data in bytes on success.
  22413. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  22414. * @return MEMORY_E when dynamic memory allocation failed.
  22415. */
  22416. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  22417. int with_header, int comp)
  22418. {
  22419. #ifndef WOLFSSL_ASN_TEMPLATE
  22420. int ret;
  22421. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  22422. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  22423. byte algo[MAX_ALGO_SZ]; /* 20 */
  22424. /* public size */
  22425. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  22426. if (comp)
  22427. pubSz = 1 + pubSz;
  22428. else
  22429. pubSz = 1 + 2 * pubSz;
  22430. /* check for buffer overflow */
  22431. if (output != NULL && pubSz > (word32)outLen) {
  22432. return BUFFER_E;
  22433. }
  22434. /* headers */
  22435. if (with_header) {
  22436. ret = SetCurve(key, NULL, 0);
  22437. if (ret <= 0) {
  22438. return ret;
  22439. }
  22440. curveSz = (word32)ret;
  22441. ret = 0;
  22442. /* calculate size */
  22443. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  22444. bitStringSz = SetBitString(pubSz, 0, bitString);
  22445. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  22446. /* check for buffer overflow */
  22447. if (output != NULL &&
  22448. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  22449. return BUFFER_E;
  22450. }
  22451. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  22452. output);
  22453. /* algo */
  22454. if (output)
  22455. XMEMCPY(output + idx, algo, algoSz);
  22456. idx += algoSz;
  22457. /* curve */
  22458. if (output)
  22459. (void)SetCurve(key, output + idx, curveSz);
  22460. idx += curveSz;
  22461. /* bit string */
  22462. if (output)
  22463. XMEMCPY(output + idx, bitString, bitStringSz);
  22464. idx += bitStringSz;
  22465. }
  22466. /* pub */
  22467. if (output) {
  22468. PRIVATE_KEY_UNLOCK();
  22469. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  22470. PRIVATE_KEY_LOCK();
  22471. if (ret != 0) {
  22472. return ret;
  22473. }
  22474. }
  22475. idx += pubSz;
  22476. return (int)idx;
  22477. #else
  22478. word32 pubSz = 0;
  22479. int sz = 0;
  22480. int ret = 0;
  22481. int curveIdSz = 0;
  22482. byte* curveOid = NULL;
  22483. /* Check key validity. */
  22484. if ((key == NULL) || (key->dp == NULL)) {
  22485. ret = BAD_FUNC_ARG;
  22486. }
  22487. if (ret == 0) {
  22488. /* Calculate the size of the encoded public point. */
  22489. PRIVATE_KEY_UNLOCK();
  22490. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  22491. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  22492. /* in earlier versions of FIPS the get length functionality is not
  22493. * available with compressed keys */
  22494. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  22495. if (comp)
  22496. pubSz = 1 + pubSz;
  22497. else
  22498. pubSz = 1 + 2 * pubSz;
  22499. ret = LENGTH_ONLY_E;
  22500. #else
  22501. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  22502. #endif
  22503. PRIVATE_KEY_LOCK();
  22504. /* LENGTH_ONLY_E on success. */
  22505. if (ret == LENGTH_ONLY_E) {
  22506. ret = 0;
  22507. }
  22508. }
  22509. if ((ret == 0) && with_header) {
  22510. /* Including SubjectPublicKeyInfo header. */
  22511. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  22512. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  22513. /* Get the length of the named curve OID to put into the encoding. */
  22514. curveIdSz = SetCurve(key, NULL, 0);
  22515. if (curveIdSz < 0) {
  22516. ret = curveIdSz;
  22517. }
  22518. if (ret == 0) {
  22519. /* Set the key type OID. */
  22520. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  22521. oidKeyType);
  22522. /* Set the curve OID. */
  22523. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  22524. NULL, (word32)curveIdSz);
  22525. /* Don't try to write out explicit parameters. */
  22526. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  22527. /* Set size of public point to ensure space is made for it. */
  22528. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  22529. /* Calculate size of ECC public key. */
  22530. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  22531. eccPublicKeyASN_Length, &sz);
  22532. }
  22533. /* Check buffer, if passed in, is big enough for encoded data. */
  22534. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22535. ret = BUFFER_E;
  22536. }
  22537. if ((ret == 0) && (output != NULL)) {
  22538. /* Encode ECC public key. */
  22539. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  22540. output);
  22541. /* Skip to where public point is to be encoded. */
  22542. output += sz - (int)pubSz;
  22543. /* Cache the location to place the name curve OID. */
  22544. curveOid = (byte*)
  22545. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  22546. }
  22547. FREE_ASNSETDATA(dataASN, key->heap);
  22548. }
  22549. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  22550. ret = BUFFER_E;
  22551. }
  22552. else {
  22553. /* Total size is the public point size. */
  22554. sz = (int)pubSz;
  22555. }
  22556. if ((ret == 0) && (output != NULL)) {
  22557. /* Put named curve OID data into encoding. */
  22558. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  22559. if (curveIdSz < 0) {
  22560. ret = curveIdSz;
  22561. }
  22562. }
  22563. if ((ret == 0) && (output != NULL)) {
  22564. /* Encode public point. */
  22565. PRIVATE_KEY_UNLOCK();
  22566. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  22567. PRIVATE_KEY_LOCK();
  22568. }
  22569. if (ret == 0) {
  22570. /* Return the size of the encoding. */
  22571. ret = sz;
  22572. }
  22573. return ret;
  22574. #endif
  22575. }
  22576. /* Encode the public part of an ECC key in a DER.
  22577. *
  22578. * Pass NULL for output to get the size of the encoding.
  22579. *
  22580. * @param [in] key ECC key object.
  22581. * @param [out] output Buffer to hold DER encoding.
  22582. * @param [in] inLen Size of buffer in bytes.
  22583. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  22584. * @return Size of encoded data in bytes on success.
  22585. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  22586. * @return MEMORY_E when dynamic memory allocation failed.
  22587. */
  22588. WOLFSSL_ABI
  22589. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  22590. int with_AlgCurve)
  22591. {
  22592. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  22593. }
  22594. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  22595. int with_AlgCurve, int comp)
  22596. {
  22597. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  22598. }
  22599. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  22600. {
  22601. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  22602. }
  22603. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  22604. #ifdef WOLFSSL_ASN_TEMPLATE
  22605. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  22606. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  22607. * RFC 8410, 4 - Subject Public Key Fields
  22608. */
  22609. static const ASNItem edPubKeyASN[] = {
  22610. /* SubjectPublicKeyInfo */
  22611. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  22612. /* AlgorithmIdentifier */
  22613. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  22614. /* Ed25519/Ed448 OID */
  22615. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  22616. /* Public key stream */
  22617. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  22618. };
  22619. enum {
  22620. EDPUBKEYASN_IDX_SEQ = 0,
  22621. EDPUBKEYASN_IDX_ALGOID_SEQ,
  22622. EDPUBKEYASN_IDX_ALGOID_OID,
  22623. EDPUBKEYASN_IDX_PUBKEY
  22624. };
  22625. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  22626. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  22627. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  22628. #endif /* WOLFSSL_ASN_TEMPLATE */
  22629. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  22630. /* Build ASN.1 formatted public key based on RFC 8410
  22631. *
  22632. * Pass NULL for output to get the size of the encoding.
  22633. *
  22634. * @param [in] pubKey public key buffer
  22635. * @param [in] pubKeyLen public ket buffer length
  22636. * @param [out] output Buffer to put encoded data in (optional)
  22637. * @param [in] outLen Size of buffer in bytes
  22638. * @param [in] keyType is "enum Key_Sum" like ED25519k
  22639. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  22640. * @return Size of encoded data in bytes on success
  22641. * @return BAD_FUNC_ARG when key is NULL.
  22642. * @return MEMORY_E when dynamic memory allocation failed.
  22643. */
  22644. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  22645. byte* output, word32 outLen, int keyType, int withHeader)
  22646. {
  22647. int ret = 0;
  22648. #ifndef WOLFSSL_ASN_TEMPLATE
  22649. word32 idx = 0;
  22650. word32 seqDataSz = 0;
  22651. word32 sz;
  22652. #else
  22653. int sz = 0;
  22654. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  22655. #endif
  22656. if (pubKey == NULL) {
  22657. return BAD_FUNC_ARG;
  22658. }
  22659. #ifndef WOLFSSL_ASN_TEMPLATE
  22660. /* calculate size */
  22661. if (withHeader) {
  22662. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  22663. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  22664. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  22665. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  22666. }
  22667. else {
  22668. sz = pubKeyLen;
  22669. }
  22670. /* checkout output size */
  22671. if (output != NULL && sz > outLen) {
  22672. ret = BUFFER_E;
  22673. }
  22674. /* headers */
  22675. if (ret == 0 && output != NULL && withHeader) {
  22676. /* sequence */
  22677. idx = SetSequence(seqDataSz, output);
  22678. /* algo */
  22679. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  22680. /* bit string */
  22681. idx += SetBitString(pubKeyLen, 0, output + idx);
  22682. }
  22683. if (ret == 0 && output != NULL) {
  22684. /* pub */
  22685. XMEMCPY(output + idx, pubKey, pubKeyLen);
  22686. idx += pubKeyLen;
  22687. sz = idx;
  22688. }
  22689. if (ret == 0) {
  22690. ret = (int)sz;
  22691. }
  22692. #else
  22693. if (withHeader) {
  22694. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  22695. if (ret == 0) {
  22696. /* Set the OID. */
  22697. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  22698. oidKeyType);
  22699. /* Leave space for public point. */
  22700. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  22701. /* Calculate size of public key encoding. */
  22702. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  22703. }
  22704. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  22705. ret = BUFFER_E;
  22706. }
  22707. if ((ret == 0) && (output != NULL)) {
  22708. /* Encode public key. */
  22709. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  22710. /* Set location to encode public point. */
  22711. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  22712. }
  22713. FREE_ASNSETDATA(dataASN, NULL);
  22714. }
  22715. else if ((output != NULL) && (pubKeyLen > outLen)) {
  22716. ret = BUFFER_E;
  22717. }
  22718. else if (ret == 0) {
  22719. sz = (int)pubKeyLen;
  22720. }
  22721. if ((ret == 0) && (output != NULL)) {
  22722. /* Put public key into space provided. */
  22723. XMEMCPY(output, pubKey, pubKeyLen);
  22724. }
  22725. if (ret == 0) {
  22726. ret = sz;
  22727. }
  22728. #endif /* WOLFSSL_ASN_TEMPLATE */
  22729. return ret;
  22730. }
  22731. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  22732. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  22733. /* Encode the public part of an Ed25519 key in DER.
  22734. *
  22735. * Pass NULL for output to get the size of the encoding.
  22736. *
  22737. * @param [in] key Ed25519 key object.
  22738. * @param [out] output Buffer to put encoded data in.
  22739. * @param [in] outLen Size of buffer in bytes.
  22740. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  22741. * @return Size of encoded data in bytes on success.
  22742. * @return BAD_FUNC_ARG when key is NULL.
  22743. * @return MEMORY_E when dynamic memory allocation failed.
  22744. */
  22745. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  22746. int withAlg)
  22747. {
  22748. int ret;
  22749. byte pubKey[ED25519_PUB_KEY_SIZE];
  22750. word32 pubKeyLen = (word32)sizeof(pubKey);
  22751. if (key == NULL) {
  22752. return BAD_FUNC_ARG;
  22753. }
  22754. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  22755. if (ret == 0) {
  22756. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  22757. ED25519k, withAlg);
  22758. }
  22759. return ret;
  22760. }
  22761. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  22762. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  22763. /* Encode the public part of an Ed448 key in DER.
  22764. *
  22765. * Pass NULL for output to get the size of the encoding.
  22766. *
  22767. * @param [in] key Ed448 key object.
  22768. * @param [out] output Buffer to put encoded data in.
  22769. * @param [in] outLen Size of buffer in bytes.
  22770. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  22771. * @return Size of encoded data in bytes on success.
  22772. * @return BAD_FUNC_ARG when key is NULL.
  22773. * @return MEMORY_E when dynamic memory allocation failed.
  22774. */
  22775. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  22776. int withAlg)
  22777. {
  22778. int ret;
  22779. byte pubKey[ED448_PUB_KEY_SIZE];
  22780. word32 pubKeyLen = (word32)sizeof(pubKey);
  22781. if (key == NULL) {
  22782. return BAD_FUNC_ARG;
  22783. }
  22784. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  22785. if (ret == 0) {
  22786. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  22787. ED448k, withAlg);
  22788. }
  22789. return ret;
  22790. }
  22791. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  22792. #ifdef WOLFSSL_CERT_GEN
  22793. #ifndef NO_ASN_TIME
  22794. static WC_INLINE byte itob(int number)
  22795. {
  22796. return (byte)number + 0x30;
  22797. }
  22798. /* write time to output, format */
  22799. static void SetTime(struct tm* date, byte* output)
  22800. {
  22801. int i = 0;
  22802. output[i++] = itob((date->tm_year % 10000) / 1000);
  22803. output[i++] = itob((date->tm_year % 1000) / 100);
  22804. output[i++] = itob((date->tm_year % 100) / 10);
  22805. output[i++] = itob( date->tm_year % 10);
  22806. output[i++] = itob(date->tm_mon / 10);
  22807. output[i++] = itob(date->tm_mon % 10);
  22808. output[i++] = itob(date->tm_mday / 10);
  22809. output[i++] = itob(date->tm_mday % 10);
  22810. output[i++] = itob(date->tm_hour / 10);
  22811. output[i++] = itob(date->tm_hour % 10);
  22812. output[i++] = itob(date->tm_min / 10);
  22813. output[i++] = itob(date->tm_min % 10);
  22814. output[i++] = itob(date->tm_sec / 10);
  22815. output[i++] = itob(date->tm_sec % 10);
  22816. output[i] = 'Z'; /* Zulu profile */
  22817. }
  22818. #endif
  22819. #ifndef WOLFSSL_ASN_TEMPLATE
  22820. /* Copy Dates from cert, return bytes written */
  22821. static int CopyValidity(byte* output, Cert* cert)
  22822. {
  22823. word32 seqSz;
  22824. WOLFSSL_ENTER("CopyValidity");
  22825. /* headers and output */
  22826. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  22827. output);
  22828. if (output) {
  22829. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  22830. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  22831. (size_t)cert->afterDateSz);
  22832. }
  22833. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  22834. }
  22835. #endif /* !WOLFSSL_ASN_TEMPLATE */
  22836. /* Simple name OID size. */
  22837. #define NAME_OID_SZ 3
  22838. /* Domain name OIDs. */
  22839. static const byte nameOid[][NAME_OID_SZ] = {
  22840. { 0x55, 0x04, ASN_COUNTRY_NAME },
  22841. { 0x55, 0x04, ASN_STATE_NAME },
  22842. { 0x55, 0x04, ASN_STREET_ADDR },
  22843. { 0x55, 0x04, ASN_LOCALITY_NAME },
  22844. #ifdef WOLFSSL_CERT_NAME_ALL
  22845. { 0x55, 0x04, ASN_NAME },
  22846. { 0x55, 0x04, ASN_GIVEN_NAME },
  22847. { 0x55, 0x04, ASN_INITIALS },
  22848. { 0x55, 0x04, ASN_DNQUALIFIER },
  22849. #endif
  22850. { 0x55, 0x04, ASN_SUR_NAME },
  22851. { 0x55, 0x04, ASN_ORG_NAME },
  22852. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  22853. /* list all DC values before OUs */
  22854. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  22855. { 0x55, 0x04, ASN_COMMON_NAME },
  22856. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  22857. #ifdef WOLFSSL_CERT_EXT
  22858. { 0x55, 0x04, ASN_BUS_CAT },
  22859. #endif
  22860. { 0x55, 0x04, ASN_POSTAL_CODE },
  22861. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  22862. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  22863. #ifdef WOLFSSL_CUSTOM_OID
  22864. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  22865. #endif
  22866. };
  22867. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  22868. /* Get ASN Name from index */
  22869. byte GetCertNameId(int idx)
  22870. {
  22871. if (idx < NAME_ENTRIES)
  22872. return nameOid[idx][2];
  22873. return 0;
  22874. }
  22875. /* Get Which Name from index */
  22876. const char* GetOneCertName(CertName* name, int idx)
  22877. {
  22878. byte type = GetCertNameId(idx);
  22879. switch (type) {
  22880. case ASN_COUNTRY_NAME:
  22881. return name->country;
  22882. case ASN_STATE_NAME:
  22883. return name->state;
  22884. case ASN_STREET_ADDR:
  22885. return name->street;
  22886. case ASN_LOCALITY_NAME:
  22887. return name->locality;
  22888. #ifdef WOLFSSL_CERT_NAME_ALL
  22889. case ASN_NAME:
  22890. return name->dnName;
  22891. case ASN_GIVEN_NAME:
  22892. return name->givenName;
  22893. case ASN_INITIALS:
  22894. return name->initials;
  22895. case ASN_DNQUALIFIER:
  22896. return name->dnQualifier;
  22897. #endif /* WOLFSSL_CERT_NAME_ALL */
  22898. case ASN_SUR_NAME:
  22899. return name->sur;
  22900. case ASN_ORG_NAME:
  22901. return name->org;
  22902. case ASN_ORGUNIT_NAME:
  22903. return name->unit;
  22904. case ASN_COMMON_NAME:
  22905. return name->commonName;
  22906. case ASN_SERIAL_NUMBER:
  22907. return name->serialDev;
  22908. case ASN_USER_ID:
  22909. return name->userId;
  22910. case ASN_POSTAL_CODE:
  22911. return name->postalCode;
  22912. case ASN_EMAIL_NAME:
  22913. return name->email;
  22914. #ifdef WOLFSSL_CERT_EXT
  22915. case ASN_BUS_CAT:
  22916. return name->busCat;
  22917. #endif
  22918. #ifdef WOLFSSL_CUSTOM_OID
  22919. case ASN_CUSTOM_NAME:
  22920. return (const char*)name->custom.val;
  22921. #endif
  22922. default:
  22923. return NULL;
  22924. }
  22925. }
  22926. /* Get Which Name Encoding from index */
  22927. static char GetNameType(CertName* name, int idx)
  22928. {
  22929. byte type = GetCertNameId(idx);
  22930. switch (type) {
  22931. case ASN_COUNTRY_NAME:
  22932. return name->countryEnc;
  22933. case ASN_STATE_NAME:
  22934. return name->stateEnc;
  22935. case ASN_STREET_ADDR:
  22936. return name->streetEnc;
  22937. case ASN_LOCALITY_NAME:
  22938. return name->localityEnc;
  22939. #ifdef WOLFSSL_CERT_NAME_ALL
  22940. case ASN_NAME:
  22941. return name->dnNameEnc;
  22942. case ASN_GIVEN_NAME:
  22943. return name->givenNameEnc;
  22944. case ASN_INITIALS:
  22945. return name->initialsEnc;
  22946. case ASN_DNQUALIFIER:
  22947. return name->dnQualifierEnc;
  22948. #endif /* WOLFSSL_CERT_NAME_ALL */
  22949. case ASN_SUR_NAME:
  22950. return name->surEnc;
  22951. case ASN_ORG_NAME:
  22952. return name->orgEnc;
  22953. case ASN_ORGUNIT_NAME:
  22954. return name->unitEnc;
  22955. case ASN_COMMON_NAME:
  22956. return name->commonNameEnc;
  22957. case ASN_SERIAL_NUMBER:
  22958. return name->serialDevEnc;
  22959. case ASN_USER_ID:
  22960. return name->userIdEnc;
  22961. case ASN_POSTAL_CODE:
  22962. return name->postalCodeEnc;
  22963. case ASN_EMAIL_NAME:
  22964. return 0; /* special */
  22965. #ifdef WOLFSSL_CERT_EXT
  22966. case ASN_BUS_CAT:
  22967. return name->busCatEnc;
  22968. #endif
  22969. #ifdef WOLFSSL_CUSTOM_OID
  22970. case ASN_CUSTOM_NAME:
  22971. return name->custom.enc;
  22972. #endif
  22973. default:
  22974. return 0;
  22975. }
  22976. }
  22977. #ifndef WOLFSSL_ASN_TEMPLATE
  22978. /*
  22979. Extensions ::= SEQUENCE OF Extension
  22980. Extension ::= SEQUENCE {
  22981. extnId OBJECT IDENTIFIER,
  22982. critical BOOLEAN DEFAULT FALSE,
  22983. extnValue OCTET STRING }
  22984. */
  22985. /* encode all extensions, return total bytes written */
  22986. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  22987. const byte* ext, int extSz)
  22988. {
  22989. if (out == NULL || IdxInOut == NULL || ext == NULL)
  22990. return BAD_FUNC_ARG;
  22991. if (outSz < (word32)(*IdxInOut+extSz))
  22992. return BUFFER_E;
  22993. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  22994. *IdxInOut += extSz;
  22995. return *IdxInOut;
  22996. }
  22997. /* encode extensions header, return total bytes written */
  22998. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  22999. {
  23000. byte sequence[MAX_SEQ_SZ];
  23001. byte len[MAX_LENGTH_SZ];
  23002. word32 seqSz, lenSz, idx = 0;
  23003. if (out == NULL)
  23004. return BAD_FUNC_ARG;
  23005. if (outSz < 3)
  23006. return BUFFER_E;
  23007. seqSz = SetSequence(extSz, sequence);
  23008. /* encode extensions length provided */
  23009. lenSz = SetLength(extSz+seqSz, len);
  23010. if (outSz < (word32)(lenSz+seqSz+1))
  23011. return BUFFER_E;
  23012. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  23013. XMEMCPY(&out[idx], len, lenSz); /* length */
  23014. idx += lenSz;
  23015. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  23016. idx += seqSz;
  23017. return (int)idx;
  23018. }
  23019. /* encode CA basic constraints true with path length
  23020. * return total bytes written */
  23021. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  23022. {
  23023. /* ASN1->DER sequence for Basic Constraints True and path length */
  23024. const byte caPathLenBasicConstASN1[] = {
  23025. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  23026. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  23027. 0x00
  23028. };
  23029. if (out == NULL)
  23030. return BAD_FUNC_ARG;
  23031. if (outSz < sizeof(caPathLenBasicConstASN1))
  23032. return BUFFER_E;
  23033. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23034. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23035. return (int)sizeof(caPathLenBasicConstASN1);
  23036. }
  23037. /* encode CA basic constraints true
  23038. * return total bytes written */
  23039. static int SetCa(byte* out, word32 outSz)
  23040. {
  23041. /* ASN1->DER sequence for Basic Constraints True */
  23042. const byte caBasicConstASN1[] = {
  23043. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23044. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23045. };
  23046. if (out == NULL)
  23047. return BAD_FUNC_ARG;
  23048. if (outSz < sizeof(caBasicConstASN1))
  23049. return BUFFER_E;
  23050. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23051. return (int)sizeof(caBasicConstASN1);
  23052. }
  23053. /* encode basic constraints without CA Boolean
  23054. * return total bytes written */
  23055. static int SetBC(byte* out, word32 outSz)
  23056. {
  23057. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23058. const byte BasicConstASN1[] = {
  23059. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23060. 0x02, 0x30, 0x00
  23061. };
  23062. if (out == NULL)
  23063. return BAD_FUNC_ARG;
  23064. if (outSz < sizeof(BasicConstASN1))
  23065. return BUFFER_E;
  23066. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23067. return (int)sizeof(BasicConstASN1);
  23068. }
  23069. #endif
  23070. #ifdef WOLFSSL_CERT_EXT
  23071. #ifndef WOLFSSL_ASN_TEMPLATE
  23072. /* encode OID and associated value, return total bytes written */
  23073. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23074. byte *in, word32 inSz)
  23075. {
  23076. word32 idx = 0;
  23077. if (out == NULL || oid == NULL || in == NULL)
  23078. return BAD_FUNC_ARG;
  23079. if (outSz < 3)
  23080. return BUFFER_E;
  23081. /* sequence, + 1 => byte to put value size */
  23082. idx = SetSequence(inSz + oidSz + 1, out);
  23083. if ((idx + inSz + oidSz + 1) > outSz)
  23084. return BUFFER_E;
  23085. XMEMCPY(out+idx, oid, oidSz);
  23086. idx += oidSz;
  23087. out[idx++] = (byte)inSz;
  23088. XMEMCPY(out+idx, in, inSz);
  23089. return (int)(idx+inSz);
  23090. }
  23091. /* encode Subject Key Identifier, return total bytes written
  23092. * RFC5280 : non-critical */
  23093. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23094. {
  23095. byte skid_len[1 + MAX_LENGTH_SZ];
  23096. byte skid_enc_len[MAX_LENGTH_SZ];
  23097. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  23098. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23099. if (output == NULL || input == NULL)
  23100. return BAD_FUNC_ARG;
  23101. /* Octet String header */
  23102. skid_lenSz = SetOctetString(length, skid_len);
  23103. /* length of encoded value */
  23104. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23105. if (outSz < 3)
  23106. return BUFFER_E;
  23107. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  23108. skid_enc_lenSz, output);
  23109. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23110. return BUFFER_E;
  23111. /* put oid */
  23112. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23113. idx += sizeof(skid_oid);
  23114. /* put encoded len */
  23115. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23116. idx += skid_enc_lenSz;
  23117. /* put octet header */
  23118. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23119. idx += skid_lenSz;
  23120. /* put value */
  23121. XMEMCPY(output+idx, input, length);
  23122. idx += length;
  23123. return (int)idx;
  23124. }
  23125. /* encode Authority Key Identifier, return total bytes written
  23126. * RFC5280 : non-critical */
  23127. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23128. byte rawAkid)
  23129. {
  23130. int enc_valSz;
  23131. byte enc_val_buf[MAX_KID_SZ];
  23132. byte* enc_val;
  23133. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23134. const byte akid_cs[] = { 0x80 };
  23135. word32 inSeqSz, idx;
  23136. (void)rawAkid;
  23137. if (output == NULL || input == NULL)
  23138. return BAD_FUNC_ARG;
  23139. #ifdef WOLFSSL_AKID_NAME
  23140. if (rawAkid) {
  23141. enc_val = input;
  23142. enc_valSz = length;
  23143. }
  23144. else
  23145. #endif
  23146. {
  23147. enc_val = enc_val_buf;
  23148. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  23149. if (enc_valSz > (int)sizeof(enc_val_buf))
  23150. return BAD_FUNC_ARG;
  23151. /* sequence for ContentSpec & value */
  23152. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  23153. sizeof(akid_cs), input, length);
  23154. if (enc_valSz <= 0)
  23155. return enc_valSz;
  23156. }
  23157. /* The size of the extension sequence contents */
  23158. inSeqSz = (word32)sizeof(akid_oid) +
  23159. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  23160. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23161. return BAD_FUNC_ARG;
  23162. /* Write out the sequence header */
  23163. idx = SetSequence(inSeqSz, output);
  23164. /* Write out OID */
  23165. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23166. idx += sizeof(akid_oid);
  23167. /* Write out AKID */
  23168. idx += SetOctetString((word32)enc_valSz, output + idx);
  23169. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  23170. return (int)idx + enc_valSz;
  23171. }
  23172. /* encode Key Usage, return total bytes written
  23173. * RFC5280 : critical */
  23174. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23175. {
  23176. byte ku[5];
  23177. word32 idx;
  23178. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23179. 0x01, 0x01, 0xff, 0x04};
  23180. if (output == NULL)
  23181. return BAD_FUNC_ARG;
  23182. idx = SetBitString16Bit(input, ku);
  23183. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23184. ku, idx);
  23185. }
  23186. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  23187. const byte* oid, word32 oidSz)
  23188. {
  23189. /* verify room */
  23190. if (*idx + 2 + oidSz >= outSz)
  23191. return ASN_PARSE_E;
  23192. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  23193. XMEMCPY(&output[*idx], oid, oidSz);
  23194. *idx += oidSz;
  23195. return 0;
  23196. }
  23197. #endif
  23198. #ifdef WOLFSSL_ASN_TEMPLATE
  23199. /* ASN.1 template for extended key usage.
  23200. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23201. * Dynamic creation of template for encoding.
  23202. */
  23203. static const ASNItem ekuASN[] = {
  23204. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23205. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23206. };
  23207. enum {
  23208. EKUASN_IDX_SEQ = 0,
  23209. EKUASN_IDX_OID
  23210. };
  23211. /* OIDs corresponding to extended key usage. */
  23212. struct {
  23213. const byte* oid;
  23214. word32 oidSz;
  23215. } ekuOid[] = {
  23216. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23217. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23218. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23219. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23220. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23221. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23222. };
  23223. #define EKU_OID_LO 1
  23224. #define EKU_OID_HI 6
  23225. #endif /* WOLFSSL_ASN_TEMPLATE */
  23226. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23227. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23228. {
  23229. #ifndef WOLFSSL_ASN_TEMPLATE
  23230. word32 idx = 0, oidListSz = 0, totalSz;
  23231. int ret = 0;
  23232. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23233. if (output == NULL)
  23234. return BAD_FUNC_ARG;
  23235. /* Skip to OID List */
  23236. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23237. idx = totalSz;
  23238. /* Build OID List */
  23239. /* If any set, then just use it */
  23240. if (input & EXTKEYUSE_ANY) {
  23241. ret |= SetOjectIdValue(output, outSz, &idx,
  23242. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23243. }
  23244. else {
  23245. if (input & EXTKEYUSE_SERVER_AUTH)
  23246. ret |= SetOjectIdValue(output, outSz, &idx,
  23247. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23248. if (input & EXTKEYUSE_CLIENT_AUTH)
  23249. ret |= SetOjectIdValue(output, outSz, &idx,
  23250. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23251. if (input & EXTKEYUSE_CODESIGN)
  23252. ret |= SetOjectIdValue(output, outSz, &idx,
  23253. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23254. if (input & EXTKEYUSE_EMAILPROT)
  23255. ret |= SetOjectIdValue(output, outSz, &idx,
  23256. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23257. if (input & EXTKEYUSE_TIMESTAMP)
  23258. ret |= SetOjectIdValue(output, outSz, &idx,
  23259. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23260. if (input & EXTKEYUSE_OCSP_SIGN)
  23261. ret |= SetOjectIdValue(output, outSz, &idx,
  23262. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23263. #ifdef WOLFSSL_EKU_OID
  23264. /* iterate through OID values */
  23265. if (input & EXTKEYUSE_USER) {
  23266. int i, sz;
  23267. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23268. sz = cert->extKeyUsageOIDSz[i];
  23269. if (sz > 0) {
  23270. ret |= SetOjectIdValue(output, outSz, &idx,
  23271. cert->extKeyUsageOID[i], sz);
  23272. }
  23273. }
  23274. }
  23275. #endif /* WOLFSSL_EKU_OID */
  23276. }
  23277. if (ret != 0)
  23278. return ASN_PARSE_E;
  23279. /* Calculate Sizes */
  23280. oidListSz = idx - totalSz;
  23281. totalSz = idx - 2; /* exclude first seq/len (2) */
  23282. /* 1. Seq + Total Len (2) */
  23283. idx = SetSequence(totalSz, output);
  23284. /* 2. Object ID (2) */
  23285. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23286. idx += sizeof(extkeyusage_oid);
  23287. /* 3. Octet String (2) */
  23288. idx += SetOctetString(totalSz - idx, &output[idx]);
  23289. /* 4. Seq + OidListLen (2) */
  23290. idx += SetSequence(oidListSz, &output[idx]);
  23291. /* 5. Oid List (already set in-place above) */
  23292. idx += oidListSz;
  23293. (void)cert;
  23294. return (int)idx;
  23295. #else
  23296. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23297. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23298. ASNSetData* dataASN;
  23299. ASNItem* extKuASN = NULL;
  23300. int asnIdx = 1;
  23301. size_t cnt = 1 + EKU_OID_HI;
  23302. int i;
  23303. int ret = 0;
  23304. int sz = 0;
  23305. #ifdef WOLFSSL_EKU_OID
  23306. cnt += CTC_MAX_EKU_NB;
  23307. #endif
  23308. /* Allocate memory for dynamic data items. */
  23309. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23310. DYNAMIC_TYPE_TMP_BUFFER);
  23311. if (dataASN == NULL) {
  23312. ret = MEMORY_E;
  23313. }
  23314. if (ret == 0) {
  23315. /* Allocate memory for dynamic ASN.1 template. */
  23316. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23317. DYNAMIC_TYPE_TMP_BUFFER);
  23318. if (extKuASN == NULL) {
  23319. ret = MEMORY_E;
  23320. }
  23321. }
  23322. if (ret == 0) {
  23323. /* Copy Sequence into dynamic ASN.1 template. */
  23324. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23325. /* Clear dynamic data. */
  23326. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23327. /* Build up the template and data. */
  23328. /* If 'any' set, then just use it. */
  23329. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23330. /* Set template item. */
  23331. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23332. sizeof(ASNItem));
  23333. /* Set data item. */
  23334. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23335. sizeof(extExtKeyUsageAnyOid));
  23336. asnIdx++;
  23337. }
  23338. else {
  23339. /* Step through the flagged purposes. */
  23340. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23341. if ((input & (1 << i)) != 0) {
  23342. /* Set template item. */
  23343. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23344. sizeof(ASNItem));
  23345. /* Set data item. */
  23346. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23347. ekuOid[i - 1].oidSz);
  23348. asnIdx++;
  23349. }
  23350. }
  23351. #ifdef WOLFSSL_EKU_OID
  23352. if (input & EXTKEYUSE_USER) {
  23353. /* Iterate through OID values */
  23354. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23355. sz = cert->extKeyUsageOIDSz[i];
  23356. if (sz > 0) {
  23357. /* Set template item. */
  23358. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23359. sizeof(ASNItem));
  23360. /* Set data item. */
  23361. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23362. sz);
  23363. asnIdx++;
  23364. }
  23365. }
  23366. }
  23367. #endif /* WOLFSSL_EKU_OID */
  23368. (void)cert;
  23369. }
  23370. /* Calculate size of encoding. */
  23371. sz = 0;
  23372. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23373. }
  23374. /* When buffer to write to, ensure it's big enough. */
  23375. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23376. ret = BUFFER_E;
  23377. }
  23378. if ((ret == 0) && (output != NULL)) {
  23379. /* Encode extended key usage. */
  23380. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23381. }
  23382. if (ret == 0) {
  23383. /* Return the encoding size. */
  23384. ret = sz;
  23385. }
  23386. /* Dispose of allocated data. */
  23387. if (extKuASN != NULL) {
  23388. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23389. }
  23390. if (dataASN != NULL) {
  23391. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23392. }
  23393. return ret;
  23394. #endif
  23395. }
  23396. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23397. #ifndef WOLFSSL_ASN_TEMPLATE
  23398. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23399. {
  23400. word32 idx;
  23401. byte unusedBits = 0;
  23402. byte nsCertType = input;
  23403. word32 totalSz;
  23404. word32 bitStrSz;
  23405. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23406. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23407. if (cert == NULL || output == NULL ||
  23408. input == 0)
  23409. return BAD_FUNC_ARG;
  23410. totalSz = sizeof(nscerttype_oid);
  23411. /* Get amount of lsb zero's */
  23412. for (;(input & 1) == 0; input >>= 1)
  23413. unusedBits++;
  23414. /* 1 byte of NS Cert Type extension */
  23415. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23416. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23417. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23418. return BAD_FUNC_ARG;
  23419. /* 1. Seq + Total Len */
  23420. idx = SetSequence(totalSz, output);
  23421. /* 2. Object ID */
  23422. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23423. idx += sizeof(nscerttype_oid);
  23424. /* 3. Octet String */
  23425. idx += SetOctetString(bitStrSz, &output[idx]);
  23426. /* 4. Bit String */
  23427. idx += SetBitString(1, unusedBits, &output[idx]);
  23428. output[idx++] = nsCertType;
  23429. return (int)idx;
  23430. }
  23431. #endif
  23432. #endif
  23433. #ifndef WOLFSSL_ASN_TEMPLATE
  23434. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23435. int inSz)
  23436. {
  23437. word32 idx;
  23438. word32 totalSz;
  23439. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23440. if (cert == NULL || output == NULL ||
  23441. input == 0 || inSz <= 0)
  23442. return BAD_FUNC_ARG;
  23443. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  23444. (word32)inSz;
  23445. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23446. return BAD_FUNC_ARG;
  23447. /* 1. Seq + Total Len */
  23448. idx = SetSequence(totalSz, output);
  23449. /* 2. Object ID */
  23450. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23451. idx += sizeof(crlinfo_oid);
  23452. /* 3. Octet String */
  23453. idx += SetOctetString((word32)inSz, &output[idx]);
  23454. /* 4. CRL Info */
  23455. XMEMCPY(&output[idx], input, (size_t)inSz);
  23456. idx += (word32)inSz;
  23457. return (int)idx;
  23458. }
  23459. #endif
  23460. /* encode Certificate Policies, return total bytes written
  23461. * each input value must be ITU-T X.690 formatted : a.b.c...
  23462. * input must be an array of values with a NULL terminated for the latest
  23463. * RFC5280 : non-critical */
  23464. static int SetCertificatePolicies(byte *output,
  23465. word32 outputSz,
  23466. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23467. word16 nb_certpol,
  23468. void* heap)
  23469. {
  23470. #ifndef WOLFSSL_ASN_TEMPLATE
  23471. byte oid[MAX_OID_SZ];
  23472. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  23473. byte out[MAX_CERTPOL_SZ];
  23474. word32 oidSz;
  23475. word32 outSz;
  23476. word32 i = 0;
  23477. word32 der_oidSz[MAX_CERTPOL_NB];
  23478. int ret;
  23479. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  23480. const byte oid_oid[] = { 0x06 };
  23481. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  23482. return BAD_FUNC_ARG;
  23483. for (i = 0; i < nb_certpol; i++) {
  23484. oidSz = sizeof(oid);
  23485. XMEMSET(oid, 0, oidSz);
  23486. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23487. if (ret != 0)
  23488. return ret;
  23489. /* compute sequence value for the oid */
  23490. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  23491. sizeof(oid_oid), oid, oidSz);
  23492. if (ret <= 0)
  23493. return ret;
  23494. else
  23495. der_oidSz[i] = (word32)ret;
  23496. }
  23497. /* concatenate oid, keep two byte for sequence/size of the created value */
  23498. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  23499. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  23500. outSz += der_oidSz[i];
  23501. }
  23502. /* add sequence */
  23503. ret = (int)SetSequence(outSz-2, out);
  23504. if (ret <= 0)
  23505. return ret;
  23506. /* add Policy OID to compute final value */
  23507. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  23508. out, outSz);
  23509. #else
  23510. int i;
  23511. int ret = 0;
  23512. byte oid[MAX_OID_SZ];
  23513. word32 oidSz;
  23514. word32 sz = 0;
  23515. int piSz;
  23516. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  23517. ret = BAD_FUNC_ARG;
  23518. }
  23519. /* Put in policyIdentifier but not policyQualifiers. */
  23520. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  23521. ASNSetData dataASN[policyInfoASN_Length];
  23522. oidSz = sizeof(oid);
  23523. XMEMSET(oid, 0, oidSz);
  23524. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  23525. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23526. if (ret == 0) {
  23527. XMEMSET(dataASN, 0, sizeof(dataASN));
  23528. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  23529. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23530. &piSz);
  23531. }
  23532. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  23533. ret = BUFFER_E;
  23534. }
  23535. if (ret == 0) {
  23536. if (output != NULL) {
  23537. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23538. output);
  23539. output += piSz;
  23540. }
  23541. sz += (word32)piSz;
  23542. }
  23543. }
  23544. if (ret == 0) {
  23545. ret = (int)sz;
  23546. }
  23547. return ret;
  23548. #endif
  23549. }
  23550. #endif /* WOLFSSL_CERT_EXT */
  23551. #ifdef WOLFSSL_ALT_NAMES
  23552. #ifndef WOLFSSL_ASN_TEMPLATE
  23553. /* encode Alternative Names, return total bytes written */
  23554. static int SetAltNames(byte *output, word32 outSz,
  23555. const byte *input, word32 length, int critical)
  23556. {
  23557. byte san_len[1 + MAX_LENGTH_SZ];
  23558. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  23559. const byte san_crit[] = { 0x01, 0x01, 0xff };
  23560. word32 seqSz, san_lenSz, idx = 0;
  23561. if (output == NULL || input == NULL)
  23562. return BAD_FUNC_ARG;
  23563. if (outSz < length)
  23564. return BUFFER_E;
  23565. /* Octet String header */
  23566. san_lenSz = SetOctetString(length, san_len);
  23567. if (outSz < MAX_SEQ_SZ)
  23568. return BUFFER_E;
  23569. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  23570. if (critical)
  23571. seqSz += sizeof(san_crit);
  23572. idx = SetSequence(seqSz, output);
  23573. if (seqSz > outSz)
  23574. return BUFFER_E;
  23575. /* put oid */
  23576. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  23577. idx += sizeof(san_oid);
  23578. if (critical) {
  23579. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  23580. idx += sizeof(san_crit);
  23581. }
  23582. /* put octet header */
  23583. XMEMCPY(output+idx, san_len, san_lenSz);
  23584. idx += san_lenSz;
  23585. /* put value */
  23586. XMEMCPY(output+idx, input, length);
  23587. idx += length;
  23588. return (int)idx;
  23589. }
  23590. #endif /* WOLFSSL_ASN_TEMPLATE */
  23591. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  23592. {
  23593. word32 idx;
  23594. const DNS_entry* curName;
  23595. word32 namesSz = 0;
  23596. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23597. word32 i;
  23598. #endif
  23599. if (output == NULL)
  23600. return BAD_FUNC_ARG;
  23601. if (names == NULL)
  23602. return 0;
  23603. curName = names;
  23604. do {
  23605. namesSz += (word32)curName->len + 2 +
  23606. ((curName->len < ASN_LONG_LENGTH) ? 0
  23607. : BytePrecision((word32)curName->len));
  23608. curName = curName->next;
  23609. } while (curName != NULL);
  23610. if (outputSz < MAX_SEQ_SZ + namesSz)
  23611. return BUFFER_E;
  23612. idx = SetSequence(namesSz, output);
  23613. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23614. namesSz += idx;
  23615. i = namesSz;
  23616. #endif
  23617. curName = names;
  23618. do {
  23619. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23620. word32 len = SetLength(curName->len, NULL);
  23621. idx = i - curName->len - len - 1;
  23622. i = idx;
  23623. #endif
  23624. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  23625. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  23626. output[idx] |= ASN_CONSTRUCTED;
  23627. }
  23628. idx++;
  23629. idx += SetLength((word32)curName->len, output + idx);
  23630. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  23631. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  23632. idx += (word32)curName->len;
  23633. #endif
  23634. curName = curName->next;
  23635. } while (curName != NULL);
  23636. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23637. idx = namesSz;
  23638. #endif
  23639. return (int)idx;
  23640. }
  23641. #endif /* WOLFSSL_ALT_NAMES */
  23642. #endif /* WOLFSSL_CERT_GEN */
  23643. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23644. /* Simple domain name OID size. */
  23645. #define DN_OID_SZ 3
  23646. /* Encodes one attribute of the name (issuer/subject)
  23647. *
  23648. * name structure to hold result of encoding
  23649. * nameStr value to be encoded
  23650. * nameTag tag of encoding i.e CTC_UTF8
  23651. * type id of attribute i.e ASN_COMMON_NAME
  23652. * emailTag tag of email i.e CTC_UTF8
  23653. * returns length on success
  23654. */
  23655. static int EncodeName(EncodedName* name, const char* nameStr,
  23656. byte nameTag, byte type, byte emailTag, CertName* cname)
  23657. {
  23658. #if !defined(WOLFSSL_ASN_TEMPLATE)
  23659. word32 idx = 0;
  23660. /* bottom up */
  23661. byte firstLen[1 + MAX_LENGTH_SZ];
  23662. byte secondLen[MAX_LENGTH_SZ];
  23663. byte sequence[MAX_SEQ_SZ];
  23664. byte set[MAX_SET_SZ];
  23665. word32 strLen;
  23666. word32 thisLen;
  23667. word32 firstSz, secondSz, seqSz, setSz;
  23668. if (nameStr == NULL) {
  23669. name->used = 0;
  23670. return 0;
  23671. }
  23672. thisLen = strLen = (word32)XSTRLEN(nameStr);
  23673. #ifdef WOLFSSL_CUSTOM_OID
  23674. if (type == ASN_CUSTOM_NAME) {
  23675. if (cname == NULL || cname->custom.oidSz == 0) {
  23676. name->used = 0;
  23677. return 0;
  23678. }
  23679. thisLen = strLen = (word32)cname->custom.valSz;
  23680. }
  23681. #else
  23682. (void)cname;
  23683. #endif
  23684. if (strLen == 0) { /* no user data for this item */
  23685. name->used = 0;
  23686. return 0;
  23687. }
  23688. /* Restrict country code size */
  23689. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  23690. WOLFSSL_MSG("Country code size error");
  23691. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  23692. return ASN_COUNTRY_SIZE_E;
  23693. }
  23694. secondSz = SetLength(strLen, secondLen);
  23695. thisLen += secondSz;
  23696. switch (type) {
  23697. case ASN_EMAIL_NAME: /* email */
  23698. thisLen += (int)sizeof(attrEmailOid);
  23699. firstSz = (int)sizeof(attrEmailOid);
  23700. break;
  23701. case ASN_DOMAIN_COMPONENT:
  23702. thisLen += (int)sizeof(dcOid);
  23703. firstSz = (int)sizeof(dcOid);
  23704. break;
  23705. case ASN_USER_ID:
  23706. thisLen += (int)sizeof(uidOid);
  23707. firstSz = (int)sizeof(uidOid);
  23708. break;
  23709. case ASN_FAVOURITE_DRINK:
  23710. thisLen += (int)sizeof(fvrtDrk);
  23711. firstSz = (int)sizeof(fvrtDrk);
  23712. break;
  23713. #ifdef WOLFSSL_CUSTOM_OID
  23714. case ASN_CUSTOM_NAME:
  23715. thisLen += cname->custom.oidSz;
  23716. firstSz = cname->custom.oidSz;
  23717. break;
  23718. #endif
  23719. default:
  23720. thisLen += DN_OID_SZ;
  23721. firstSz = DN_OID_SZ;
  23722. }
  23723. thisLen++; /* id type */
  23724. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  23725. thisLen += firstSz;
  23726. seqSz = SetSequence(thisLen, sequence);
  23727. thisLen += seqSz;
  23728. setSz = SetSet(thisLen, set);
  23729. thisLen += setSz;
  23730. if (thisLen > (int)sizeof(name->encoded)) {
  23731. return BUFFER_E;
  23732. }
  23733. /* store it */
  23734. idx = 0;
  23735. /* set */
  23736. XMEMCPY(name->encoded, set, setSz);
  23737. idx += setSz;
  23738. /* seq */
  23739. XMEMCPY(name->encoded + idx, sequence, seqSz);
  23740. idx += seqSz;
  23741. /* asn object id */
  23742. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  23743. idx += firstSz;
  23744. switch (type) {
  23745. case ASN_EMAIL_NAME:
  23746. /* email joint id */
  23747. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  23748. idx += (int)sizeof(attrEmailOid);
  23749. name->encoded[idx++] = emailTag;
  23750. break;
  23751. case ASN_DOMAIN_COMPONENT:
  23752. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  23753. idx += (int)sizeof(dcOid)-1;
  23754. /* id type */
  23755. name->encoded[idx++] = type;
  23756. /* str type */
  23757. name->encoded[idx++] = nameTag;
  23758. break;
  23759. case ASN_USER_ID:
  23760. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  23761. idx += (int)sizeof(uidOid);
  23762. /* str type */
  23763. name->encoded[idx++] = nameTag;
  23764. break;
  23765. case ASN_FAVOURITE_DRINK:
  23766. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  23767. idx += (int)sizeof(fvrtDrk);
  23768. /* str type */
  23769. name->encoded[idx++] = nameTag;
  23770. break;
  23771. #ifdef WOLFSSL_CUSTOM_OID
  23772. case ASN_CUSTOM_NAME:
  23773. XMEMCPY(name->encoded + idx, cname->custom.oid,
  23774. cname->custom.oidSz);
  23775. idx += cname->custom.oidSz;
  23776. /* str type */
  23777. name->encoded[idx++] = nameTag;
  23778. break;
  23779. #endif
  23780. default:
  23781. name->encoded[idx++] = 0x55;
  23782. name->encoded[idx++] = 0x04;
  23783. /* id type */
  23784. name->encoded[idx++] = type;
  23785. /* str type */
  23786. name->encoded[idx++] = nameTag;
  23787. }
  23788. /* second length */
  23789. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  23790. idx += secondSz;
  23791. /* str value */
  23792. XMEMCPY(name->encoded + idx, nameStr, strLen);
  23793. idx += strLen;
  23794. name->type = type;
  23795. name->totalLen = (int)idx;
  23796. name->used = 1;
  23797. return (int)idx;
  23798. #else
  23799. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  23800. ASNItem namesASN[rdnASN_Length];
  23801. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  23802. int ret = 0;
  23803. int sz = 0;
  23804. const byte* oid;
  23805. word32 oidSz;
  23806. word32 nameSz;
  23807. /* Validate input parameters. */
  23808. if ((name == NULL) || (nameStr == NULL)) {
  23809. ret = BAD_FUNC_ARG;
  23810. }
  23811. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  23812. if (ret == 0) {
  23813. nameSz = (word32)XSTRLEN(nameStr);
  23814. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  23815. * based on type. */
  23816. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  23817. /* Set OID and ASN.1 tag for name depending on type. */
  23818. switch (type) {
  23819. case ASN_EMAIL_NAME:
  23820. /* email OID different to standard types. */
  23821. oid = attrEmailOid;
  23822. oidSz = sizeof(attrEmailOid);
  23823. /* Use email specific type/tag. */
  23824. nameTag = emailTag;
  23825. break;
  23826. case ASN_DOMAIN_COMPONENT:
  23827. /* Domain component OID different to standard types. */
  23828. oid = dcOid;
  23829. oidSz = sizeof(dcOid);
  23830. break;
  23831. case ASN_USER_ID:
  23832. /* Domain component OID different to standard types. */
  23833. oid = uidOid;
  23834. oidSz = sizeof(uidOid);
  23835. break;
  23836. case ASN_FAVOURITE_DRINK:
  23837. oid = fvrtDrk;
  23838. oidSz = sizeof(fvrtDrk);
  23839. break;
  23840. #ifdef WOLFSSL_CUSTOM_OID
  23841. case ASN_CUSTOM_NAME:
  23842. nameSz = cname->custom.valSz;
  23843. oid = cname->custom.oid;
  23844. oidSz = cname->custom.oidSz;
  23845. break;
  23846. #endif
  23847. default:
  23848. /* Construct OID using type. */
  23849. dnOid[2] = type;
  23850. oid = dnOid;
  23851. oidSz = DN_OID_SZ;
  23852. break;
  23853. }
  23854. /* Set OID corresponding to the name type. */
  23855. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23856. /* Set name string. */
  23857. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  23858. /* Set the ASN.1 tag for the name string. */
  23859. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  23860. /* Calculate size of encoded name and indexes of components. */
  23861. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  23862. }
  23863. /* Check if name's buffer is big enough. */
  23864. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  23865. ret = BUFFER_E;
  23866. }
  23867. if (ret == 0) {
  23868. /* Encode name into the buffer. */
  23869. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  23870. /* Cache the type and size, and set that it is used. */
  23871. name->type = type;
  23872. name->totalLen = sz;
  23873. name->used = 1;
  23874. /* Return size of encoding. */
  23875. ret = sz;
  23876. }
  23877. (void)cname;
  23878. FREE_ASNSETDATA(dataASN, NULL);
  23879. return ret;
  23880. #endif /* WOLFSSL_ASN_TEMPLATE */
  23881. }
  23882. /* canonical encoding one attribute of the name (issuer/subject)
  23883. * call EncodeName with CTC_UTF8 for email type
  23884. *
  23885. * name structure to hold result of encoding
  23886. * nameStr value to be encoded
  23887. * nameType type of encoding i.e CTC_UTF8
  23888. * type id of attribute i.e ASN_COMMON_NAME
  23889. *
  23890. * returns length on success
  23891. */
  23892. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  23893. char nameType, byte type)
  23894. {
  23895. return EncodeName(name, nameStr, (byte)nameType, type,
  23896. ASN_UTF8STRING, NULL);
  23897. }
  23898. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  23899. #ifdef WOLFSSL_CERT_GEN
  23900. /* Encodes one attribute of the name (issuer/subject)
  23901. * call we_EncodeName_ex with 0x16, IA5String for email type
  23902. * name structure to hold result of encoding
  23903. * nameStr value to be encoded
  23904. * nameType type of encoding i.e CTC_UTF8
  23905. * type id of attribute i.e ASN_COMMON_NAME
  23906. *
  23907. * returns length on success
  23908. */
  23909. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  23910. byte type)
  23911. {
  23912. return EncodeName(name, nameStr, (byte)nameType, type,
  23913. ASN_IA5_STRING, NULL);
  23914. }
  23915. #ifdef WOLFSSL_ASN_TEMPLATE
  23916. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  23917. word32 oidSz, byte tag, const byte* data, word32 sz)
  23918. {
  23919. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  23920. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  23921. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  23922. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  23923. }
  23924. #ifdef WOLFSSL_MULTI_ATTRIB
  23925. static int FindMultiAttrib(CertName* name, int id, int* idx)
  23926. {
  23927. int i;
  23928. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  23929. if (name->name[i].sz > 0 && name->name[i].id == id) {
  23930. break;
  23931. }
  23932. }
  23933. if (i == CTC_MAX_ATTRIB) {
  23934. i = -1;
  23935. }
  23936. *idx = i;
  23937. return i >= 0;
  23938. }
  23939. #endif
  23940. /* ASN.1 template for the SEQUENCE around the RDNs.
  23941. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  23942. */
  23943. static const ASNItem nameASN[] = {
  23944. { 0, ASN_SEQUENCE, 1, 1, 0 },
  23945. };
  23946. enum {
  23947. NAMEASN_IDX_SEQ = 0
  23948. };
  23949. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  23950. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  23951. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  23952. int maxIdx, CertName* name)
  23953. {
  23954. int i;
  23955. int idx;
  23956. int ret = 0;
  23957. word32 nameLen[NAME_ENTRIES];
  23958. #ifdef WOLFSSL_MULTI_ATTRIB
  23959. int j;
  23960. #endif
  23961. for (i = 0; i < NAME_ENTRIES; i++) {
  23962. /* Keep name length to identify component is to be encoded. */
  23963. const char* nameStr = GetOneCertName(name, i);
  23964. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  23965. }
  23966. idx = nameASN_Length;
  23967. for (i = 0; i < NAME_ENTRIES; i++) {
  23968. int type = GetCertNameId(i);
  23969. #ifdef WOLFSSL_MULTI_ATTRIB
  23970. j = -1;
  23971. /* Put DomainComponents before OrgUnitName. */
  23972. while (FindMultiAttrib(name, type, &j)) {
  23973. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  23974. continue;
  23975. }
  23976. if (dataASN != NULL && namesASN != NULL) {
  23977. if (idx > maxIdx - (int)rdnASN_Length) {
  23978. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23979. ret = BUFFER_E;
  23980. break;
  23981. }
  23982. /* Copy data into dynamic vars. */
  23983. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  23984. sizeof(dcOid), (byte)name->name[j].type,
  23985. (byte*)name->name[j].value,
  23986. (word32)name->name[j].sz);
  23987. }
  23988. idx += (int)rdnASN_Length;
  23989. }
  23990. if (ret != 0)
  23991. break;
  23992. #endif
  23993. if (nameLen[i] > 0) {
  23994. if (dataASN != NULL) {
  23995. if (idx > maxIdx - (int)rdnASN_Length) {
  23996. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  23997. ret = BUFFER_E;
  23998. break;
  23999. }
  24000. /* Write out first instance of attribute type. */
  24001. if (type == ASN_EMAIL_NAME) {
  24002. /* Copy email data into dynamic vars. */
  24003. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  24004. sizeof(attrEmailOid), ASN_IA5_STRING,
  24005. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24006. }
  24007. else if (type == ASN_USER_ID) {
  24008. /* Copy userID data into dynamic vars. */
  24009. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  24010. sizeof(uidOid), (byte)GetNameType(name, i),
  24011. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24012. }
  24013. else if (type == ASN_FAVOURITE_DRINK) {
  24014. /* Copy favourite drink data into dynamic vars. */
  24015. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  24016. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  24017. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24018. }
  24019. else if (type == ASN_CUSTOM_NAME) {
  24020. #ifdef WOLFSSL_CUSTOM_OID
  24021. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  24022. name->custom.oidSz, name->custom.enc,
  24023. name->custom.val, name->custom.valSz);
  24024. #endif
  24025. }
  24026. else {
  24027. /* Copy name data into dynamic vars. */
  24028. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24029. NAME_OID_SZ, (byte)GetNameType(name, i),
  24030. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24031. }
  24032. }
  24033. idx += (int)rdnASN_Length;
  24034. }
  24035. #ifdef WOLFSSL_MULTI_ATTRIB
  24036. j = -1;
  24037. /* Write all other attributes of this type. */
  24038. while (FindMultiAttrib(name, type, &j)) {
  24039. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  24040. continue;
  24041. }
  24042. if (dataASN != NULL && namesASN != NULL) {
  24043. if (idx > maxIdx - (int)rdnASN_Length) {
  24044. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24045. ret = BUFFER_E;
  24046. break;
  24047. }
  24048. /* Copy data into dynamic vars. */
  24049. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24050. NAME_OID_SZ, (byte)name->name[j].type,
  24051. (byte*)name->name[j].value, (word32)name->name[j].sz);
  24052. }
  24053. idx += (int)rdnASN_Length;
  24054. }
  24055. if (ret != 0)
  24056. break;
  24057. #endif
  24058. }
  24059. if (ret == 0)
  24060. ret = idx;
  24061. return ret;
  24062. }
  24063. #endif
  24064. /* encode CertName into output, return total bytes written */
  24065. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24066. {
  24067. #ifndef WOLFSSL_ASN_TEMPLATE
  24068. int ret;
  24069. int i;
  24070. word32 idx, totalBytes = 0;
  24071. #ifdef WOLFSSL_SMALL_STACK
  24072. EncodedName* names = NULL;
  24073. #else
  24074. EncodedName names[NAME_ENTRIES];
  24075. #endif
  24076. #ifdef WOLFSSL_MULTI_ATTRIB
  24077. EncodedName addNames[CTC_MAX_ATTRIB];
  24078. int j, type;
  24079. #endif
  24080. if (output == NULL || name == NULL)
  24081. return BAD_FUNC_ARG;
  24082. if (outputSz < 3)
  24083. return BUFFER_E;
  24084. #ifdef WOLFSSL_SMALL_STACK
  24085. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24086. DYNAMIC_TYPE_TMP_BUFFER);
  24087. if (names == NULL)
  24088. return MEMORY_E;
  24089. #endif
  24090. for (i = 0; i < NAME_ENTRIES; i++) {
  24091. const char* nameStr = GetOneCertName(name, i);
  24092. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  24093. GetCertNameId(i), ASN_IA5_STRING, name);
  24094. if (ret < 0) {
  24095. #ifdef WOLFSSL_SMALL_STACK
  24096. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24097. #endif
  24098. WOLFSSL_MSG("EncodeName failed");
  24099. return BUFFER_E;
  24100. }
  24101. totalBytes += (word32)ret;
  24102. }
  24103. #ifdef WOLFSSL_MULTI_ATTRIB
  24104. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24105. if (name->name[i].sz > 0) {
  24106. ret = EncodeName(&addNames[i], name->name[i].value,
  24107. (byte)name->name[i].type, (byte)name->name[i].id,
  24108. ASN_IA5_STRING, NULL);
  24109. if (ret < 0) {
  24110. #ifdef WOLFSSL_SMALL_STACK
  24111. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24112. #endif
  24113. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24114. return BUFFER_E;
  24115. }
  24116. totalBytes += (word32)ret;
  24117. }
  24118. else {
  24119. addNames[i].used = 0;
  24120. }
  24121. }
  24122. #endif /* WOLFSSL_MULTI_ATTRIB */
  24123. /* header */
  24124. idx = SetSequence(totalBytes, output);
  24125. totalBytes += idx;
  24126. if (totalBytes > WC_ASN_NAME_MAX) {
  24127. #ifdef WOLFSSL_SMALL_STACK
  24128. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24129. #endif
  24130. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24131. return BUFFER_E;
  24132. }
  24133. for (i = 0; i < NAME_ENTRIES; i++) {
  24134. #ifdef WOLFSSL_MULTI_ATTRIB
  24135. type = GetCertNameId(i);
  24136. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24137. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24138. if (outputSz < idx + (word32)addNames[j].totalLen) {
  24139. #ifdef WOLFSSL_SMALL_STACK
  24140. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24141. #endif
  24142. WOLFSSL_MSG("Not enough space left for DC value");
  24143. return BUFFER_E;
  24144. }
  24145. XMEMCPY(output + idx, addNames[j].encoded,
  24146. (size_t)addNames[j].totalLen);
  24147. idx += (word32)addNames[j].totalLen;
  24148. }
  24149. }
  24150. #endif /* WOLFSSL_MULTI_ATTRIB */
  24151. if (names[i].used) {
  24152. if (outputSz < idx + (word32)names[i].totalLen) {
  24153. #ifdef WOLFSSL_SMALL_STACK
  24154. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24155. #endif
  24156. return BUFFER_E;
  24157. }
  24158. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  24159. idx += (word32)names[i].totalLen;
  24160. }
  24161. }
  24162. #ifdef WOLFSSL_SMALL_STACK
  24163. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24164. #endif
  24165. (void)heap;
  24166. return (int)totalBytes;
  24167. #else
  24168. /* TODO: consider calculating size of entries, putting length into
  24169. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24170. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24171. ASNItem* namesASN = NULL;
  24172. word32 items = 0;
  24173. int ret = 0;
  24174. int sz = 0;
  24175. /* Calculate length of name entries and size for allocating. */
  24176. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24177. if (ret > 0) {
  24178. items = (word32)ret;
  24179. ret = 0;
  24180. }
  24181. /* Allocate dynamic data items. */
  24182. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24183. DYNAMIC_TYPE_TMP_BUFFER);
  24184. if (dataASN == NULL) {
  24185. ret = MEMORY_E;
  24186. }
  24187. else {
  24188. /* Allocate dynamic ASN.1 template items. */
  24189. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24190. DYNAMIC_TYPE_TMP_BUFFER);
  24191. if (namesASN == NULL) {
  24192. ret = MEMORY_E;
  24193. }
  24194. }
  24195. if (ret == 0) {
  24196. /* Clear the dynamic data. */
  24197. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24198. /* Copy in the outer sequence. */
  24199. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24200. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  24201. if (ret == (int)items)
  24202. ret = 0;
  24203. else if (ret > 0) {
  24204. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24205. ret = BUFFER_E;
  24206. }
  24207. }
  24208. if (ret == 0) {
  24209. /* Calculate size of encoding. */
  24210. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  24211. }
  24212. /* Check buffer size if passed in. */
  24213. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24214. ret = BUFFER_E;
  24215. }
  24216. if (ret == 0) {
  24217. if (output != NULL) {
  24218. /* Encode Name. */
  24219. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  24220. }
  24221. else {
  24222. /* Return the encoding size. */
  24223. ret = sz;
  24224. }
  24225. }
  24226. if (namesASN != NULL)
  24227. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24228. if (dataASN != NULL)
  24229. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24230. (void)heap;
  24231. return ret;
  24232. #endif
  24233. }
  24234. int SetName(byte* output, word32 outputSz, CertName* name)
  24235. {
  24236. return SetNameEx(output, outputSz, name, NULL);
  24237. }
  24238. #ifdef WOLFSSL_ASN_TEMPLATE
  24239. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24240. RsaKey* rsaKey, ecc_key* eccKey,
  24241. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24242. DsaKey* dsaKey)
  24243. {
  24244. int ret = 0;
  24245. (void)outLen;
  24246. (void)rsaKey;
  24247. (void)eccKey;
  24248. (void)ed25519Key;
  24249. (void)ed448Key;
  24250. (void)dsaKey;
  24251. switch (keyType) {
  24252. #ifndef NO_RSA
  24253. case RSA_KEY:
  24254. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24255. if (ret <= 0) {
  24256. ret = PUBLIC_KEY_E;
  24257. }
  24258. break;
  24259. #endif
  24260. #ifdef HAVE_ECC
  24261. case ECC_KEY:
  24262. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24263. if (ret <= 0) {
  24264. ret = PUBLIC_KEY_E;
  24265. }
  24266. break;
  24267. #endif /* HAVE_ECC */
  24268. #ifdef HAVE_ED25519
  24269. case ED25519_KEY:
  24270. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  24271. (word32)outLen, 1);
  24272. if (ret <= 0) {
  24273. ret = PUBLIC_KEY_E;
  24274. }
  24275. break;
  24276. #endif
  24277. #ifdef HAVE_ED448
  24278. case ED448_KEY:
  24279. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  24280. if (ret <= 0) {
  24281. ret = PUBLIC_KEY_E;
  24282. }
  24283. break;
  24284. #endif
  24285. default:
  24286. ret = PUBLIC_KEY_E;
  24287. break;
  24288. }
  24289. return ret;
  24290. }
  24291. /* ASN.1 template for certificate extensions.
  24292. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24293. * All extensions supported for encoding are described.
  24294. */
  24295. static const ASNItem static_certExtsASN[] = {
  24296. /* Basic Constraints Extension - 4.2.1.9 */
  24297. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24298. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24299. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24300. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24301. /* cA */
  24302. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24303. /* pathLenConstraint */
  24304. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24305. /* Subject Alternative Name - 4.2.1.6 */
  24306. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24307. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24308. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24309. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24310. /* Subject Key Identifier - 4.2.1.2 */
  24311. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24312. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24313. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24314. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24315. /* Authority Key Identifier - 4.2.1.1 */
  24316. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24317. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24318. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24319. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24320. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24321. /* Key Usage - 4.2.1.3 */
  24322. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24323. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24324. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24325. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24326. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24327. /* Extended Key Usage - 4,2,1,12 */
  24328. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24329. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24330. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24331. /* Certificate Policies - 4.2.1.4 */
  24332. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24333. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24334. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24335. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24336. /* Netscape Certificate Type */
  24337. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24338. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24339. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24340. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24341. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24342. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24343. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24344. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24345. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24346. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24347. };
  24348. enum {
  24349. CERTEXTSASN_IDX_BC_SEQ = 0,
  24350. CERTEXTSASN_IDX_BC_OID,
  24351. CERTEXTSASN_IDX_BC_STR,
  24352. CERTEXTSASN_IDX_BC_STR_SEQ,
  24353. CERTEXTSASN_IDX_BC_CA,
  24354. CERTEXTSASN_IDX_BC_PATHLEN,
  24355. CERTEXTSASN_IDX_SAN_SEQ,
  24356. CERTEXTSASN_IDX_SAN_OID,
  24357. CERTEXTSASN_IDX_SAN_CRIT,
  24358. CERTEXTSASN_IDX_SAN_STR,
  24359. CERTEXTSASN_IDX_SKID_SEQ,
  24360. CERTEXTSASN_IDX_SKID_OID,
  24361. CERTEXTSASN_IDX_SKID_STR,
  24362. CERTEXTSASN_IDX_SKID_KEYID,
  24363. CERTEXTSASN_IDX_AKID_SEQ,
  24364. CERTEXTSASN_IDX_AKID_OID,
  24365. CERTEXTSASN_IDX_AKID_STR,
  24366. CERTEXTSASN_IDX_AKID_STR_SEQ,
  24367. CERTEXTSASN_IDX_AKID_KEYID,
  24368. CERTEXTSASN_IDX_KU_SEQ,
  24369. CERTEXTSASN_IDX_KU_OID,
  24370. CERTEXTSASN_IDX_KU_CRIT,
  24371. CERTEXTSASN_IDX_KU_STR,
  24372. CERTEXTSASN_IDX_KU_USAGE,
  24373. CERTEXTSASN_IDX_EKU_SEQ,
  24374. CERTEXTSASN_IDX_EKU_OID,
  24375. CERTEXTSASN_IDX_EKU_STR,
  24376. CERTEXTSASN_IDX_POLICIES_SEQ,
  24377. CERTEXTSASN_IDX_POLICIES_OID,
  24378. CERTEXTSASN_IDX_POLICIES_STR,
  24379. CERTEXTSASN_IDX_POLICIES_INFO,
  24380. CERTEXTSASN_IDX_NSTYPE_SEQ,
  24381. CERTEXTSASN_IDX_NSTYPE_OID,
  24382. CERTEXTSASN_IDX_NSTYPE_STR,
  24383. CERTEXTSASN_IDX_NSTYPE_USAGE,
  24384. CERTEXTSASN_IDX_CRLINFO_SEQ,
  24385. CERTEXTSASN_IDX_CRLINFO_OID,
  24386. CERTEXTSASN_IDX_CRLINFO_STR,
  24387. CERTEXTSASN_IDX_CUSTOM_SEQ,
  24388. CERTEXTSASN_IDX_CUSTOM_OID,
  24389. CERTEXTSASN_IDX_CUSTOM_STR,
  24390. CERTEXTSASN_IDX_START_CUSTOM
  24391. };
  24392. /* Number of items in ASN.1 template for certificate extensions. We multiply
  24393. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  24394. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  24395. + (NUM_CUSTOM_EXT * 4))
  24396. static const ASNItem customExtASN[] = {
  24397. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24398. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24399. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24400. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24401. };
  24402. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  24403. int forRequest)
  24404. {
  24405. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  24406. int sz;
  24407. int ret = 0;
  24408. int i = 0;
  24409. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  24410. #ifdef WOLFSSL_ALT_NAMES
  24411. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  24412. #endif
  24413. #ifdef WOLFSSL_CERT_EXT
  24414. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  24415. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  24416. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  24417. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  24418. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  24419. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  24420. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24421. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  24422. #endif
  24423. #ifdef WOLFSSL_SMALL_STACK
  24424. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24425. byte *encodedOids;
  24426. #endif
  24427. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  24428. sizeof(ASNItem), cert->heap,
  24429. DYNAMIC_TYPE_TMP_BUFFER);
  24430. if (certExtsASN == NULL) {
  24431. return MEMORY_E;
  24432. }
  24433. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24434. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  24435. DYNAMIC_TYPE_TMP_BUFFER);
  24436. if (encodedOids == NULL) {
  24437. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24438. return MEMORY_E;
  24439. }
  24440. #endif
  24441. #else
  24442. ASNItem certExtsASN[certExtsASN_Length];
  24443. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24444. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  24445. #endif
  24446. #endif
  24447. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  24448. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  24449. * above definition of certExtsASN_Length. */
  24450. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  24451. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  24452. i < (int)certExtsASN_Length; i += 4) {
  24453. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  24454. }
  24455. (void)forRequest;
  24456. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  24457. if (ret == 0) {
  24458. if (cert->isCA) {
  24459. /* Set Basic Constraints to be a Certificate Authority. */
  24460. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  24461. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24462. if (cert->pathLenSet
  24463. #ifdef WOLFSSL_CERT_EXT
  24464. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24465. #endif
  24466. ) {
  24467. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  24468. cert->pathLen);
  24469. }
  24470. else {
  24471. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24472. }
  24473. }
  24474. else if (cert->basicConstSet) {
  24475. /* Set Basic Constraints to be a non Certificate Authority. */
  24476. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24477. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  24478. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24479. }
  24480. else {
  24481. /* Don't write out Basic Constraints extension items. */
  24482. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  24483. CERTEXTSASN_IDX_BC_PATHLEN);
  24484. }
  24485. #ifdef WOLFSSL_ALT_NAMES
  24486. if (cert->altNamesSz > 0) {
  24487. /* Set Subject Alternative Name OID and data. */
  24488. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  24489. sanOID, sizeof(sanOID));
  24490. if (cert->altNamesCrit) {
  24491. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  24492. }
  24493. else {
  24494. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  24495. }
  24496. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  24497. cert->altNames, (word32)cert->altNamesSz);
  24498. }
  24499. else
  24500. #endif
  24501. {
  24502. /* Don't write out Subject Alternative Name extension items. */
  24503. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  24504. CERTEXTSASN_IDX_SAN_STR);
  24505. }
  24506. #ifdef WOLFSSL_CERT_EXT
  24507. if (cert->skidSz > 0) {
  24508. /* Set Subject Key Identifier OID and data. */
  24509. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  24510. skidOID, sizeof(skidOID));
  24511. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  24512. cert->skid, (word32)cert->skidSz);
  24513. }
  24514. else
  24515. #endif
  24516. {
  24517. /* Don't write out Subject Key Identifier extension items. */
  24518. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  24519. CERTEXTSASN_IDX_SKID_KEYID);
  24520. }
  24521. #ifdef WOLFSSL_CERT_EXT
  24522. if (cert->akidSz > 0) {
  24523. /* Set Authority Key Identifier OID and data. */
  24524. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  24525. akidOID, sizeof(akidOID));
  24526. #ifdef WOLFSSL_AKID_NAME
  24527. if (cert->rawAkid) {
  24528. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  24529. cert->akid, cert->akidSz);
  24530. /* cert->akid contains the internal ext structure */
  24531. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  24532. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  24533. }
  24534. else
  24535. #endif
  24536. {
  24537. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  24538. cert->akid, (word32)cert->akidSz);
  24539. }
  24540. }
  24541. else
  24542. #endif
  24543. {
  24544. /* Don't write out Authority Key Identifier extension items. */
  24545. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  24546. CERTEXTSASN_IDX_AKID_KEYID);
  24547. }
  24548. #ifdef WOLFSSL_CERT_EXT
  24549. if (cert->keyUsage != 0) {
  24550. /* Set Key Usage OID, critical and value. */
  24551. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  24552. kuOID, sizeof(kuOID));
  24553. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  24554. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  24555. cert->keyUsage);
  24556. }
  24557. else
  24558. #endif
  24559. {
  24560. /* Don't write out Key Usage extension items. */
  24561. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  24562. CERTEXTSASN_IDX_KU_USAGE);
  24563. }
  24564. #ifdef WOLFSSL_CERT_EXT
  24565. if (cert->extKeyUsage != 0) {
  24566. /* Calculate size of Extended Key Usage data. */
  24567. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  24568. if (sz <= 0) {
  24569. ret = KEYUSAGE_E;
  24570. }
  24571. /* Set Extended Key Usage OID and data. */
  24572. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  24573. ekuOID, sizeof(ekuOID));
  24574. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  24575. NULL, (word32)sz);
  24576. }
  24577. else
  24578. #endif
  24579. {
  24580. /* Don't write out Extended Key Usage extension items. */
  24581. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  24582. CERTEXTSASN_IDX_EKU_STR);
  24583. }
  24584. #ifdef WOLFSSL_CERT_EXT
  24585. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24586. /* Calculate size of certificate policies. */
  24587. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  24588. cert->certPoliciesNb, cert->heap);
  24589. if (sz > 0) {
  24590. /* Set Certificate Policies OID. */
  24591. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  24592. cpOID, sizeof(cpOID));
  24593. /* Make space for data. */
  24594. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  24595. NULL, (word32)sz);
  24596. }
  24597. else {
  24598. ret = CERTPOLICIES_E;
  24599. }
  24600. }
  24601. else
  24602. #endif
  24603. {
  24604. /* Don't write out Certificate Policies extension items. */
  24605. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  24606. CERTEXTSASN_IDX_POLICIES_INFO);
  24607. }
  24608. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  24609. /* Netscape Certificate Type */
  24610. if (cert->nsCertType != 0) {
  24611. /* Set Netscape Certificate Type OID and data. */
  24612. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  24613. nsCertOID, sizeof(nsCertOID));
  24614. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  24615. &cert->nsCertType, 1);
  24616. }
  24617. else
  24618. #endif
  24619. {
  24620. /* Don't write out Netscape Certificate Type. */
  24621. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  24622. CERTEXTSASN_IDX_NSTYPE_USAGE);
  24623. }
  24624. #ifdef WOLFSSL_CERT_EXT
  24625. if (cert->crlInfoSz > 0) {
  24626. /* Set CRL Distribution Points OID and data. */
  24627. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  24628. crlInfoOID, sizeof(crlInfoOID));
  24629. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  24630. cert->crlInfo, (word32)cert->crlInfoSz);
  24631. }
  24632. else
  24633. #endif
  24634. {
  24635. /* Don't write out CRL Distribution Points. */
  24636. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  24637. CERTEXTSASN_IDX_CRLINFO_STR);
  24638. }
  24639. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24640. /* encode a custom oid and value */
  24641. if (cert->extCustom.oidSz > 0) {
  24642. /* Set CRL Distribution Points OID and data. */
  24643. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  24644. cert->extCustom.oid, cert->extCustom.oidSz);
  24645. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  24646. cert->extCustom.val, cert->extCustom.valSz);
  24647. }
  24648. else
  24649. #endif
  24650. {
  24651. /* Don't write out custom OID. */
  24652. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  24653. CERTEXTSASN_IDX_CUSTOM_STR);
  24654. }
  24655. i = 0;
  24656. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24657. for (; i < cert->customCertExtCount; i++) {
  24658. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  24659. word32 encodedOidSz = MAX_OID_SZ;
  24660. idx++; /* Skip one for for SEQ. */
  24661. /* EncodePolicyOID() will never return error since we parsed this
  24662. * OID when it was set. */
  24663. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  24664. cert->customCertExt[i].oid, NULL);
  24665. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  24666. encodedOidSz);
  24667. idx++;
  24668. if (cert->customCertExt[i].crit) {
  24669. SetASN_Boolean(&dataASN[idx], 1);
  24670. } else {
  24671. dataASN[idx].noOut = 1;
  24672. }
  24673. idx++;
  24674. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  24675. cert->customCertExt[i].valSz);
  24676. }
  24677. #endif
  24678. while (i < NUM_CUSTOM_EXT) {
  24679. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  24680. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  24681. i++;
  24682. }
  24683. }
  24684. if (ret == 0) {
  24685. /* Calculate size of encoded extensions. */
  24686. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  24687. }
  24688. if (ret == 0) {
  24689. /* Only SEQUENCE - don't encode extensions. */
  24690. if (sz == 2) {
  24691. sz = 0;
  24692. }
  24693. /* Check buffer is big enough. */
  24694. else if ((output != NULL) && (sz > (int)maxSz)) {
  24695. ret = BUFFER_E;
  24696. }
  24697. }
  24698. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  24699. /* Encode certificate extensions into buffer. */
  24700. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  24701. #ifdef WOLFSSL_CERT_EXT
  24702. if (cert->extKeyUsage != 0){
  24703. /* Encode Extended Key Usage into space provided. */
  24704. if (SetExtKeyUsage(cert,
  24705. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  24706. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  24707. cert->extKeyUsage) <= 0) {
  24708. ret = KEYUSAGE_E;
  24709. }
  24710. }
  24711. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24712. /* Encode Certificate Policies into space provided. */
  24713. if (SetCertificatePolicies(
  24714. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  24715. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  24716. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  24717. ret = CERTPOLICIES_E;
  24718. }
  24719. }
  24720. #endif
  24721. }
  24722. if (ret == 0) {
  24723. /* Return the encoding size. */
  24724. ret = sz;
  24725. }
  24726. FREE_ASNSETDATA(dataASN, cert->heap);
  24727. #ifdef WOLFSSL_SMALL_STACK
  24728. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24729. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24730. #endif
  24731. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24732. #endif
  24733. return ret;
  24734. }
  24735. #endif /* WOLFSSL_ASN_TEMPLATE */
  24736. #ifndef WOLFSSL_ASN_TEMPLATE
  24737. /* Set Date validity from now until now + daysValid
  24738. * return size in bytes written to output, 0 on error */
  24739. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  24740. * "MUST always encode certificate validity dates through the year 2049 as
  24741. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  24742. * GeneralizedTime." */
  24743. static int SetValidity(byte* output, int daysValid)
  24744. {
  24745. #ifndef NO_ASN_TIME
  24746. byte before[MAX_DATE_SIZE];
  24747. byte after[MAX_DATE_SIZE];
  24748. word32 beforeSz, afterSz, seqSz;
  24749. time_t now;
  24750. time_t then;
  24751. struct tm* tmpTime;
  24752. struct tm* expandedTime;
  24753. struct tm localTime;
  24754. #if defined(NEED_TMP_TIME)
  24755. /* for use with gmtime_r */
  24756. struct tm tmpTimeStorage;
  24757. tmpTime = &tmpTimeStorage;
  24758. #else
  24759. tmpTime = NULL;
  24760. #endif
  24761. (void)tmpTime;
  24762. now = wc_Time(0);
  24763. /* before now */
  24764. before[0] = ASN_GENERALIZED_TIME;
  24765. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  24766. /* subtract 1 day of seconds for more compliance */
  24767. then = now - 86400;
  24768. expandedTime = XGMTIME(&then, tmpTime);
  24769. if (expandedTime == NULL) {
  24770. WOLFSSL_MSG("XGMTIME failed");
  24771. return 0; /* error */
  24772. }
  24773. localTime = *expandedTime;
  24774. /* adjust */
  24775. localTime.tm_year += 1900;
  24776. localTime.tm_mon += 1;
  24777. SetTime(&localTime, before + beforeSz);
  24778. beforeSz += ASN_GEN_TIME_SZ;
  24779. after[0] = ASN_GENERALIZED_TIME;
  24780. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  24781. /* add daysValid of seconds */
  24782. then = now + (daysValid * (time_t)86400);
  24783. expandedTime = XGMTIME(&then, tmpTime);
  24784. if (expandedTime == NULL) {
  24785. WOLFSSL_MSG("XGMTIME failed");
  24786. return 0; /* error */
  24787. }
  24788. localTime = *expandedTime;
  24789. /* adjust */
  24790. localTime.tm_year += 1900;
  24791. localTime.tm_mon += 1;
  24792. SetTime(&localTime, after + afterSz);
  24793. afterSz += ASN_GEN_TIME_SZ;
  24794. /* headers and output */
  24795. seqSz = SetSequence(beforeSz + afterSz, output);
  24796. XMEMCPY(output + seqSz, before, beforeSz);
  24797. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  24798. return (int)(seqSz + beforeSz + afterSz);
  24799. #else
  24800. (void)output;
  24801. (void)daysValid;
  24802. return NOT_COMPILED_IN;
  24803. #endif
  24804. }
  24805. #else
  24806. static int SetValidity(byte* before, byte* after, int daysValid)
  24807. {
  24808. #ifndef NO_ASN_TIME
  24809. int ret = 0;
  24810. time_t now;
  24811. time_t then;
  24812. struct tm* tmpTime;
  24813. struct tm* expandedTime;
  24814. struct tm localTime;
  24815. #if defined(NEED_TMP_TIME)
  24816. /* for use with gmtime_r */
  24817. struct tm tmpTimeStorage;
  24818. tmpTime = &tmpTimeStorage;
  24819. #else
  24820. tmpTime = NULL;
  24821. #endif
  24822. (void)tmpTime;
  24823. now = wc_Time(0);
  24824. /* subtract 1 day of seconds for more compliance */
  24825. then = now - 86400;
  24826. expandedTime = XGMTIME(&then, tmpTime);
  24827. if (expandedTime == NULL) {
  24828. WOLFSSL_MSG("XGMTIME failed");
  24829. ret = DATE_E;
  24830. }
  24831. if (ret == 0) {
  24832. localTime = *expandedTime;
  24833. /* adjust */
  24834. localTime.tm_year += 1900;
  24835. localTime.tm_mon += 1;
  24836. SetTime(&localTime, before);
  24837. /* add daysValid of seconds */
  24838. then = now + (daysValid * (time_t)86400);
  24839. expandedTime = XGMTIME(&then, tmpTime);
  24840. if (expandedTime == NULL) {
  24841. WOLFSSL_MSG("XGMTIME failed");
  24842. ret = DATE_E;
  24843. }
  24844. }
  24845. if (ret == 0) {
  24846. localTime = *expandedTime;
  24847. /* adjust */
  24848. localTime.tm_year += 1900;
  24849. localTime.tm_mon += 1;
  24850. SetTime(&localTime, after);
  24851. }
  24852. return ret;
  24853. #else
  24854. (void)before;
  24855. (void)after;
  24856. (void)daysValid;
  24857. return NOT_COMPILED_IN;
  24858. #endif
  24859. }
  24860. #endif /* WOLFSSL_ASN_TEMPLATE */
  24861. #ifndef WOLFSSL_ASN_TEMPLATE
  24862. /* encode info from cert into DER encoded format */
  24863. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  24864. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  24865. ed448_key* ed448Key, falcon_key* falconKey,
  24866. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  24867. {
  24868. int ret;
  24869. if (cert == NULL || der == NULL || rng == NULL)
  24870. return BAD_FUNC_ARG;
  24871. /* make sure at least one key type is provided */
  24872. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  24873. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  24874. dilithiumKey == NULL && sphincsKey == NULL) {
  24875. return PUBLIC_KEY_E;
  24876. }
  24877. /* init */
  24878. XMEMSET(der, 0, sizeof(DerCert));
  24879. /* version */
  24880. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  24881. /* serial number (must be positive) */
  24882. if (cert->serialSz == 0) {
  24883. /* generate random serial */
  24884. cert->serialSz = CTC_GEN_SERIAL_SZ;
  24885. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  24886. if (ret != 0)
  24887. return ret;
  24888. /* Clear the top bit to avoid a negative value */
  24889. cert->serial[0] &= 0x7f;
  24890. }
  24891. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  24892. der->serial, sizeof(der->serial),
  24893. CTC_SERIAL_SIZE);
  24894. if (der->serialSz < 0)
  24895. return der->serialSz;
  24896. /* signature algo */
  24897. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  24898. if (der->sigAlgoSz <= 0)
  24899. return ALGO_ID_E;
  24900. /* public key */
  24901. #ifndef NO_RSA
  24902. if (cert->keyType == RSA_KEY) {
  24903. if (rsaKey == NULL)
  24904. return PUBLIC_KEY_E;
  24905. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  24906. sizeof(der->publicKey), 1);
  24907. }
  24908. #endif
  24909. #ifdef HAVE_ECC
  24910. if (cert->keyType == ECC_KEY) {
  24911. if (eccKey == NULL)
  24912. return PUBLIC_KEY_E;
  24913. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  24914. sizeof(der->publicKey), 1, 0);
  24915. }
  24916. #endif
  24917. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  24918. if (cert->keyType == DSA_KEY) {
  24919. if (dsaKey == NULL)
  24920. return PUBLIC_KEY_E;
  24921. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  24922. sizeof(der->publicKey), 1);
  24923. }
  24924. #endif
  24925. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  24926. if (cert->keyType == ED25519_KEY) {
  24927. if (ed25519Key == NULL)
  24928. return PUBLIC_KEY_E;
  24929. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  24930. (word32)sizeof(der->publicKey), 1);
  24931. }
  24932. #endif
  24933. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  24934. if (cert->keyType == ED448_KEY) {
  24935. if (ed448Key == NULL)
  24936. return PUBLIC_KEY_E;
  24937. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  24938. (word32)sizeof(der->publicKey), 1);
  24939. }
  24940. #endif
  24941. #if defined(HAVE_PQC)
  24942. #if defined(HAVE_FALCON)
  24943. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  24944. (cert->keyType == FALCON_LEVEL5_KEY)) {
  24945. if (falconKey == NULL)
  24946. return PUBLIC_KEY_E;
  24947. der->publicKeySz =
  24948. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  24949. (word32)sizeof(der->publicKey), 1);
  24950. }
  24951. #endif /* HAVE_FALCON */
  24952. #if defined(HAVE_DILITHIUM)
  24953. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  24954. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  24955. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  24956. if (dilithiumKey == NULL)
  24957. return PUBLIC_KEY_E;
  24958. der->publicKeySz =
  24959. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  24960. (word32)sizeof(der->publicKey), 1);
  24961. }
  24962. #endif /* HAVE_DILITHIUM */
  24963. #if defined(HAVE_SPHINCS)
  24964. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  24965. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  24966. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  24967. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  24968. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  24969. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  24970. if (sphincsKey == NULL)
  24971. return PUBLIC_KEY_E;
  24972. der->publicKeySz =
  24973. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  24974. (word32)sizeof(der->publicKey), 1);
  24975. }
  24976. #endif /* HAVE_SPHINCS */
  24977. #endif /* HAVE_PQC */
  24978. if (der->publicKeySz <= 0)
  24979. return PUBLIC_KEY_E;
  24980. der->validitySz = 0;
  24981. /* copy date validity if already set in cert struct */
  24982. if (cert->beforeDateSz && cert->afterDateSz) {
  24983. der->validitySz = CopyValidity(der->validity, cert);
  24984. if (der->validitySz <= 0)
  24985. return DATE_E;
  24986. }
  24987. /* set date validity using daysValid if not set already */
  24988. if (der->validitySz == 0) {
  24989. der->validitySz = SetValidity(der->validity, cert->daysValid);
  24990. if (der->validitySz <= 0)
  24991. return DATE_E;
  24992. }
  24993. /* subject name */
  24994. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  24995. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  24996. /* Use the raw subject */
  24997. word32 idx;
  24998. der->subjectSz = (int)min((word32)sizeof(der->subject),
  24999. (word32)XSTRLEN((const char*)cert->sbjRaw));
  25000. /* header */
  25001. idx = SetSequence((word32)der->subjectSz, der->subject);
  25002. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  25003. return SUBJECT_E;
  25004. }
  25005. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  25006. (size_t)der->subjectSz);
  25007. der->subjectSz += (int)idx;
  25008. }
  25009. else
  25010. #endif
  25011. {
  25012. /* Use the name structure */
  25013. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  25014. &cert->subject, cert->heap);
  25015. }
  25016. if (der->subjectSz <= 0)
  25017. return SUBJECT_E;
  25018. /* issuer name */
  25019. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25020. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  25021. /* Use the raw issuer */
  25022. word32 idx;
  25023. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  25024. (word32)XSTRLEN((const char*)cert->issRaw));
  25025. /* header */
  25026. idx = SetSequence((word32)der->issuerSz, der->issuer);
  25027. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  25028. return ISSUER_E;
  25029. }
  25030. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  25031. (size_t)der->issuerSz);
  25032. der->issuerSz += (int)idx;
  25033. }
  25034. else
  25035. #endif
  25036. {
  25037. /* Use the name structure */
  25038. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  25039. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25040. }
  25041. if (der->issuerSz <= 0)
  25042. return ISSUER_E;
  25043. /* set the extensions */
  25044. der->extensionsSz = 0;
  25045. /* RFC 5280 : 4.2.1.9. Basic Constraints
  25046. * The pathLenConstraint field is meaningful only if the CA boolean is
  25047. * asserted and the key usage extension, if present, asserts the
  25048. * keyCertSign bit */
  25049. /* Set CA and path length */
  25050. if ((cert->isCA) && (cert->pathLenSet)
  25051. #ifdef WOLFSSL_CERT_EXT
  25052. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25053. #endif
  25054. ) {
  25055. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  25056. if (der->caSz <= 0)
  25057. return CA_TRUE_E;
  25058. der->extensionsSz += der->caSz;
  25059. }
  25060. /* Set CA */
  25061. else if (cert->isCA) {
  25062. der->caSz = SetCa(der->ca, sizeof(der->ca));
  25063. if (der->caSz <= 0)
  25064. return CA_TRUE_E;
  25065. der->extensionsSz += der->caSz;
  25066. }
  25067. /* Set Basic Constraint */
  25068. else if (cert->basicConstSet) {
  25069. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25070. if (der->caSz <= 0)
  25071. return EXTENSIONS_E;
  25072. der->extensionsSz += der->caSz;
  25073. }
  25074. else
  25075. der->caSz = 0;
  25076. #ifdef WOLFSSL_ALT_NAMES
  25077. /* Alternative Name */
  25078. if (cert->altNamesSz) {
  25079. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25080. cert->altNames, (word32)cert->altNamesSz,
  25081. cert->altNamesCrit);
  25082. if (der->altNamesSz <= 0)
  25083. return ALT_NAME_E;
  25084. der->extensionsSz += der->altNamesSz;
  25085. }
  25086. else
  25087. der->altNamesSz = 0;
  25088. #endif
  25089. #ifdef WOLFSSL_CERT_EXT
  25090. /* SKID */
  25091. if (cert->skidSz) {
  25092. /* check the provided SKID size */
  25093. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25094. return SKID_E;
  25095. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25096. cert (CTC_MAX_SKID_SIZE). */
  25097. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25098. cert->skid, (word32)cert->skidSz);
  25099. if (der->skidSz <= 0)
  25100. return SKID_E;
  25101. der->extensionsSz += der->skidSz;
  25102. }
  25103. else
  25104. der->skidSz = 0;
  25105. /* AKID */
  25106. if (cert->akidSz) {
  25107. /* check the provided AKID size */
  25108. if ((
  25109. #ifdef WOLFSSL_AKID_NAME
  25110. !cert->rawAkid &&
  25111. #endif
  25112. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25113. #ifdef WOLFSSL_AKID_NAME
  25114. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25115. #endif
  25116. )
  25117. return AKID_E;
  25118. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25119. (word32)cert->akidSz,
  25120. #ifdef WOLFSSL_AKID_NAME
  25121. cert->rawAkid
  25122. #else
  25123. 0
  25124. #endif
  25125. );
  25126. if (der->akidSz <= 0)
  25127. return AKID_E;
  25128. der->extensionsSz += der->akidSz;
  25129. }
  25130. else
  25131. der->akidSz = 0;
  25132. /* Key Usage */
  25133. if (cert->keyUsage != 0){
  25134. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25135. cert->keyUsage);
  25136. if (der->keyUsageSz <= 0)
  25137. return KEYUSAGE_E;
  25138. der->extensionsSz += der->keyUsageSz;
  25139. }
  25140. else
  25141. der->keyUsageSz = 0;
  25142. /* Extended Key Usage */
  25143. if (cert->extKeyUsage != 0){
  25144. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25145. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25146. if (der->extKeyUsageSz <= 0)
  25147. return EXTKEYUSAGE_E;
  25148. der->extensionsSz += der->extKeyUsageSz;
  25149. }
  25150. else
  25151. der->extKeyUsageSz = 0;
  25152. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25153. /* Netscape Certificate Type */
  25154. if (cert->nsCertType != 0) {
  25155. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25156. sizeof(der->nsCertType), cert->nsCertType);
  25157. if (der->nsCertTypeSz <= 0)
  25158. return EXTENSIONS_E;
  25159. der->extensionsSz += der->nsCertTypeSz;
  25160. }
  25161. else
  25162. der->nsCertTypeSz = 0;
  25163. #endif
  25164. if (cert->crlInfoSz > 0) {
  25165. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25166. cert->crlInfo, cert->crlInfoSz);
  25167. if (der->crlInfoSz <= 0)
  25168. return EXTENSIONS_E;
  25169. der->extensionsSz += der->crlInfoSz;
  25170. }
  25171. else
  25172. der->crlInfoSz = 0;
  25173. /* Certificate Policies */
  25174. if (cert->certPoliciesNb != 0) {
  25175. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25176. sizeof(der->certPolicies),
  25177. cert->certPolicies,
  25178. cert->certPoliciesNb,
  25179. cert->heap);
  25180. if (der->certPoliciesSz <= 0)
  25181. return CERTPOLICIES_E;
  25182. der->extensionsSz += der->certPoliciesSz;
  25183. }
  25184. else
  25185. der->certPoliciesSz = 0;
  25186. #endif /* WOLFSSL_CERT_EXT */
  25187. /* put extensions */
  25188. if (der->extensionsSz > 0) {
  25189. /* put the start of extensions sequence (ID, Size) */
  25190. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25191. sizeof(der->extensions),
  25192. (word32)der->extensionsSz);
  25193. if (der->extensionsSz <= 0)
  25194. return EXTENSIONS_E;
  25195. /* put CA */
  25196. if (der->caSz) {
  25197. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25198. &der->extensionsSz,
  25199. der->ca, der->caSz);
  25200. if (ret == 0)
  25201. return EXTENSIONS_E;
  25202. }
  25203. #ifdef WOLFSSL_ALT_NAMES
  25204. /* put Alternative Names */
  25205. if (der->altNamesSz) {
  25206. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25207. &der->extensionsSz,
  25208. der->altNames, der->altNamesSz);
  25209. if (ret <= 0)
  25210. return EXTENSIONS_E;
  25211. }
  25212. #endif
  25213. #ifdef WOLFSSL_CERT_EXT
  25214. /* put SKID */
  25215. if (der->skidSz) {
  25216. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25217. &der->extensionsSz,
  25218. der->skid, der->skidSz);
  25219. if (ret <= 0)
  25220. return EXTENSIONS_E;
  25221. }
  25222. /* put AKID */
  25223. if (der->akidSz) {
  25224. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25225. &der->extensionsSz,
  25226. der->akid, der->akidSz);
  25227. if (ret <= 0)
  25228. return EXTENSIONS_E;
  25229. }
  25230. /* put CRL Distribution Points */
  25231. if (der->crlInfoSz) {
  25232. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25233. &der->extensionsSz,
  25234. der->crlInfo, der->crlInfoSz);
  25235. if (ret <= 0)
  25236. return EXTENSIONS_E;
  25237. }
  25238. /* put KeyUsage */
  25239. if (der->keyUsageSz) {
  25240. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25241. &der->extensionsSz,
  25242. der->keyUsage, der->keyUsageSz);
  25243. if (ret <= 0)
  25244. return EXTENSIONS_E;
  25245. }
  25246. /* put ExtendedKeyUsage */
  25247. if (der->extKeyUsageSz) {
  25248. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25249. &der->extensionsSz,
  25250. der->extKeyUsage, der->extKeyUsageSz);
  25251. if (ret <= 0)
  25252. return EXTENSIONS_E;
  25253. }
  25254. /* put Netscape Cert Type */
  25255. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25256. if (der->nsCertTypeSz) {
  25257. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25258. &der->extensionsSz,
  25259. der->nsCertType, der->nsCertTypeSz);
  25260. if (ret <= 0)
  25261. return EXTENSIONS_E;
  25262. }
  25263. #endif
  25264. /* put Certificate Policies */
  25265. if (der->certPoliciesSz) {
  25266. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25267. &der->extensionsSz,
  25268. der->certPolicies, der->certPoliciesSz);
  25269. if (ret <= 0)
  25270. return EXTENSIONS_E;
  25271. }
  25272. #endif /* WOLFSSL_CERT_EXT */
  25273. }
  25274. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25275. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25276. der->extensionsSz;
  25277. return 0;
  25278. }
  25279. /* write DER encoded cert to buffer, size already checked */
  25280. static int WriteCertBody(DerCert* der, byte* buf)
  25281. {
  25282. word32 idx;
  25283. /* signed part header */
  25284. idx = SetSequence((word32)der->total, buf);
  25285. /* version */
  25286. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  25287. idx += (word32)der->versionSz;
  25288. /* serial */
  25289. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  25290. idx += (word32)der->serialSz;
  25291. /* sig algo */
  25292. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  25293. idx += (word32)der->sigAlgoSz;
  25294. /* issuer */
  25295. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  25296. idx += (word32)der->issuerSz;
  25297. /* validity */
  25298. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  25299. idx += (word32)der->validitySz;
  25300. /* subject */
  25301. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  25302. idx += (word32)der->subjectSz;
  25303. /* public key */
  25304. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  25305. idx += (word32)der->publicKeySz;
  25306. if (der->extensionsSz) {
  25307. /* extensions */
  25308. XMEMCPY(buf + idx, der->extensions,
  25309. min((word32)der->extensionsSz,
  25310. (word32)sizeof(der->extensions)));
  25311. idx += (word32)der->extensionsSz;
  25312. }
  25313. return (int)idx;
  25314. }
  25315. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25316. /* Make signature from buffer (sz), write to sig (sigSz) */
  25317. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  25318. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25319. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25320. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25321. word32 sigAlgoType, void* heap)
  25322. {
  25323. int digestSz = 0, typeH = 0, ret = 0;
  25324. (void)digestSz;
  25325. (void)typeH;
  25326. (void)buf;
  25327. (void)sz;
  25328. (void)sig;
  25329. (void)sigSz;
  25330. (void)rsaKey;
  25331. (void)eccKey;
  25332. (void)ed25519Key;
  25333. (void)ed448Key;
  25334. (void)falconKey;
  25335. (void)dilithiumKey;
  25336. (void)sphincsKey;
  25337. (void)rng;
  25338. (void)heap;
  25339. switch (certSignCtx->state) {
  25340. case CERTSIGN_STATE_BEGIN:
  25341. case CERTSIGN_STATE_DIGEST:
  25342. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  25343. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  25344. DYNAMIC_TYPE_TMP_BUFFER);
  25345. if (certSignCtx->digest == NULL) {
  25346. ret = MEMORY_E; goto exit_ms;
  25347. }
  25348. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  25349. &typeH, &digestSz, 0);
  25350. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  25351. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  25352. if (ret != 0) {
  25353. goto exit_ms;
  25354. }
  25355. FALL_THROUGH;
  25356. case CERTSIGN_STATE_ENCODE:
  25357. #ifndef NO_RSA
  25358. if (rsaKey) {
  25359. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  25360. DYNAMIC_TYPE_TMP_BUFFER);
  25361. if (certSignCtx->encSig == NULL) {
  25362. ret = MEMORY_E; goto exit_ms;
  25363. }
  25364. /* signature */
  25365. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  25366. certSignCtx->digest, (word32)digestSz, typeH);
  25367. }
  25368. #endif /* !NO_RSA */
  25369. FALL_THROUGH;
  25370. case CERTSIGN_STATE_DO:
  25371. certSignCtx->state = CERTSIGN_STATE_DO;
  25372. ret = ALGO_ID_E; /* default to error */
  25373. #ifndef NO_RSA
  25374. if (rsaKey) {
  25375. /* signature */
  25376. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  25377. (word32)certSignCtx->encSigSz,
  25378. sig, sigSz, rsaKey, rng);
  25379. }
  25380. #endif /* !NO_RSA */
  25381. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  25382. if (!rsaKey && eccKey) {
  25383. word32 outSz = sigSz;
  25384. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  25385. sig, &outSz, rng, eccKey);
  25386. if (ret == 0)
  25387. ret = (int)outSz;
  25388. }
  25389. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  25390. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  25391. if (!rsaKey && !eccKey && ed25519Key) {
  25392. word32 outSz = sigSz;
  25393. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  25394. if (ret == 0)
  25395. ret = (int)outSz;
  25396. }
  25397. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  25398. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  25399. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  25400. word32 outSz = sigSz;
  25401. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  25402. if (ret == 0)
  25403. ret = (int)outSz;
  25404. }
  25405. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  25406. #if defined(HAVE_PQC)
  25407. #if defined(HAVE_FALCON)
  25408. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  25409. word32 outSz = sigSz;
  25410. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  25411. if (ret == 0)
  25412. ret = outSz;
  25413. }
  25414. #endif /* HAVE_FALCON */
  25415. #if defined(HAVE_DILITHIUM)
  25416. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25417. dilithiumKey) {
  25418. word32 outSz = sigSz;
  25419. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  25420. if (ret == 0)
  25421. ret = outSz;
  25422. }
  25423. #endif /* HAVE_DILITHIUM */
  25424. #if defined(HAVE_SPHINCS)
  25425. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25426. !dilithiumKey && sphincsKey) {
  25427. word32 outSz = sigSz;
  25428. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  25429. if (ret == 0)
  25430. ret = outSz;
  25431. }
  25432. #endif /* HAVE_SPHINCS */
  25433. #endif /* HAVE_PQC */
  25434. break;
  25435. }
  25436. exit_ms:
  25437. #ifdef WOLFSSL_ASYNC_CRYPT
  25438. if (ret == WC_PENDING_E) {
  25439. return ret;
  25440. }
  25441. #endif
  25442. #ifndef NO_RSA
  25443. if (rsaKey) {
  25444. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25445. }
  25446. #endif /* !NO_RSA */
  25447. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25448. certSignCtx->digest = NULL;
  25449. /* reset state */
  25450. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  25451. if (ret < 0) {
  25452. WOLFSSL_ERROR_VERBOSE(ret);
  25453. }
  25454. return ret;
  25455. }
  25456. #ifdef WOLFSSL_ASN_TEMPLATE
  25457. /* Generate a random integer value of at most len bytes.
  25458. *
  25459. * Most-significant bit will not be set when maximum size.
  25460. * Random value may be smaller than maximum size in bytes.
  25461. *
  25462. * @param [in] rng Random number generator.
  25463. * @param [out] out Buffer to hold integer value.
  25464. * @param [in] len Maximum number of bytes of integer.
  25465. * @return 0 on success.
  25466. * @return -ve when random number generation failed.
  25467. */
  25468. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  25469. {
  25470. int ret;
  25471. /* Generate random number. */
  25472. ret = wc_RNG_GenerateBlock(rng, out, len);
  25473. if (ret == 0) {
  25474. int i;
  25475. /* Clear the top bit to make positive. */
  25476. out[0] &= 0x7f;
  25477. /* Find first non-zero byte. One zero byte is valid though. */
  25478. for (i = 0; i < (int)len - 1; i++) {
  25479. if (out[i] != 0) {
  25480. break;
  25481. }
  25482. }
  25483. if (i != 0) {
  25484. /* Remove leading zeros. */
  25485. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  25486. }
  25487. }
  25488. return ret;
  25489. }
  25490. /* ASN.1 template for a Certificate.
  25491. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25492. */
  25493. static const ASNItem sigASN[] = {
  25494. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25495. /* tbsCertificate */
  25496. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25497. /* signatureAlgorithm */
  25498. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25499. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25500. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  25501. /* signatureValue */
  25502. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25503. };
  25504. enum {
  25505. SIGASN_IDX_SEQ = 0,
  25506. SIGASN_IDX_TBS_SEQ,
  25507. SIGASN_IDX_SIGALGO_SEQ,
  25508. SIGASN_IDX_SIGALGO_OID,
  25509. SIGASN_IDX_SIGALGO_NULL,
  25510. SIGASN_IDX_SIGNATURE
  25511. };
  25512. /* Number of items in ASN.1 template for a Certificate. */
  25513. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  25514. #endif
  25515. /* add signature to end of buffer, size of buffer assumed checked, return
  25516. new length */
  25517. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  25518. int sigAlgoType)
  25519. {
  25520. #ifndef WOLFSSL_ASN_TEMPLATE
  25521. byte seq[MAX_SEQ_SZ];
  25522. word32 idx, seqSz;
  25523. if ((bodySz < 0) || (sigSz < 0))
  25524. return BUFFER_E;
  25525. idx = (word32)bodySz;
  25526. /* algo */
  25527. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  25528. /* bit string */
  25529. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  25530. /* signature */
  25531. if (buf)
  25532. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  25533. idx += (word32)sigSz;
  25534. /* make room for overall header */
  25535. seqSz = SetSequence(idx, seq);
  25536. if (buf) {
  25537. XMEMMOVE(buf + seqSz, buf, idx);
  25538. XMEMCPY(buf, seq, seqSz);
  25539. }
  25540. return (int)(idx + seqSz);
  25541. #else
  25542. DECL_ASNSETDATA(dataASN, sigASN_Length);
  25543. word32 seqSz;
  25544. int sz;
  25545. int ret = 0;
  25546. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  25547. /* In place, put body between SEQUENCE and signature. */
  25548. if (ret == 0) {
  25549. /* Set sigature OID and signature data. */
  25550. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  25551. oidSigType);
  25552. if (IsSigAlgoECC((word32)sigAlgoType)) {
  25553. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  25554. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  25555. }
  25556. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  25557. /* Calculate size of signature data. */
  25558. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  25559. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  25560. }
  25561. if (ret == 0) {
  25562. /* Calculate size of outer sequence by calculating size of the encoded
  25563. * length and adding 1 for tag. */
  25564. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  25565. if (buf != NULL) {
  25566. /* Move body to after sequence. */
  25567. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  25568. }
  25569. /* Leave space for body in encoding. */
  25570. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  25571. (word32)bodySz);
  25572. /* Calculate overall size and put in offsets and lengths. */
  25573. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  25574. }
  25575. if ((ret == 0) && (buf != NULL)) {
  25576. /* Write SEQUENCE and signature around body. */
  25577. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  25578. }
  25579. if (ret == 0) {
  25580. /* Return the encoding size. */
  25581. ret = sz;
  25582. }
  25583. FREE_ASNSETDATA(dataASN, NULL);
  25584. return ret;
  25585. #endif /* WOLFSSL_ASN_TEMPLATE */
  25586. }
  25587. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  25588. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  25589. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  25590. DsaKey* dsaKey, ed25519_key* ed25519Key,
  25591. ed448_key* ed448Key, falcon_key* falconKey,
  25592. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25593. {
  25594. #ifndef WOLFSSL_ASN_TEMPLATE
  25595. int ret;
  25596. #ifdef WOLFSSL_SMALL_STACK
  25597. DerCert* der;
  25598. #else
  25599. DerCert der[1];
  25600. #endif
  25601. if (derBuffer == NULL)
  25602. return BAD_FUNC_ARG;
  25603. if (eccKey)
  25604. cert->keyType = ECC_KEY;
  25605. else if (rsaKey)
  25606. cert->keyType = RSA_KEY;
  25607. else if (dsaKey)
  25608. cert->keyType = DSA_KEY;
  25609. else if (ed25519Key)
  25610. cert->keyType = ED25519_KEY;
  25611. else if (ed448Key)
  25612. cert->keyType = ED448_KEY;
  25613. #ifdef HAVE_PQC
  25614. #ifdef HAVE_FALCON
  25615. else if ((falconKey != NULL) && (falconKey->level == 1))
  25616. cert->keyType = FALCON_LEVEL1_KEY;
  25617. else if ((falconKey != NULL) && (falconKey->level == 5))
  25618. cert->keyType = FALCON_LEVEL5_KEY;
  25619. #endif /* HAVE_FALCON */
  25620. #ifdef HAVE_DILITHIUM
  25621. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  25622. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25623. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  25624. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25625. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  25626. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25627. #endif /* HAVE_DILITHIUM */
  25628. #ifdef HAVE_SPHINCS
  25629. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25630. && (sphincsKey->optim == FAST_VARIANT))
  25631. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25632. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25633. && (sphincsKey->optim == FAST_VARIANT))
  25634. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25635. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25636. && (sphincsKey->optim == FAST_VARIANT))
  25637. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25638. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25639. && (sphincsKey->optim == SMALL_VARIANT))
  25640. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25641. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25642. && (sphincsKey->optim == SMALL_VARIANT))
  25643. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25644. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25645. && (sphincsKey->optim == SMALL_VARIANT))
  25646. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25647. #endif /* HAVE_SPHINCS */
  25648. #endif /* HAVE_PQC */
  25649. else
  25650. return BAD_FUNC_ARG;
  25651. #ifdef WOLFSSL_SMALL_STACK
  25652. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25653. if (der == NULL)
  25654. return MEMORY_E;
  25655. #endif
  25656. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  25657. ed448Key, falconKey, dilithiumKey, sphincsKey);
  25658. if (ret == 0) {
  25659. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  25660. ret = BUFFER_E;
  25661. else
  25662. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  25663. }
  25664. #ifdef WOLFSSL_SMALL_STACK
  25665. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25666. #endif
  25667. return ret;
  25668. #else
  25669. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  25670. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  25671. word32 publicKeySz = 0;
  25672. word32 issuerSz = 0;
  25673. word32 subjectSz = 0;
  25674. word32 extSz = 0;
  25675. int sz = 0;
  25676. int ret = 0;
  25677. word32 issRawLen = 0;
  25678. word32 sbjRawLen = 0;
  25679. /* Unused without OQS */
  25680. (void)falconKey;
  25681. (void)dilithiumKey;
  25682. (void)sphincsKey;
  25683. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  25684. if (ret == 0) {
  25685. /* Set key type into certificate object based on key passed in. */
  25686. if (rsaKey) {
  25687. cert->keyType = RSA_KEY;
  25688. }
  25689. else if (eccKey) {
  25690. cert->keyType = ECC_KEY;
  25691. }
  25692. else if (dsaKey) {
  25693. cert->keyType = DSA_KEY;
  25694. }
  25695. else if (ed25519Key) {
  25696. cert->keyType = ED25519_KEY;
  25697. }
  25698. else if (ed448Key) {
  25699. cert->keyType = ED448_KEY;
  25700. }
  25701. #ifdef HAVE_PQC
  25702. #ifdef HAVE_FALCON
  25703. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  25704. cert->keyType = FALCON_LEVEL1_KEY;
  25705. }
  25706. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  25707. cert->keyType = FALCON_LEVEL5_KEY;
  25708. }
  25709. #endif /* HAVE_FALCON */
  25710. #ifdef HAVE_DILITHIUM
  25711. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  25712. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25713. }
  25714. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  25715. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25716. }
  25717. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  25718. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25719. }
  25720. #endif /* HAVE_DILITHIUM */
  25721. #ifdef HAVE_SPHINCS
  25722. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25723. && (sphincsKey->optim == FAST_VARIANT)) {
  25724. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25725. }
  25726. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25727. && (sphincsKey->optim == FAST_VARIANT)) {
  25728. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25729. }
  25730. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25731. && (sphincsKey->optim == FAST_VARIANT)) {
  25732. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25733. }
  25734. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25735. && (sphincsKey->optim == SMALL_VARIANT)) {
  25736. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25737. }
  25738. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25739. && (sphincsKey->optim == SMALL_VARIANT)) {
  25740. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25741. }
  25742. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25743. && (sphincsKey->optim == SMALL_VARIANT)) {
  25744. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25745. }
  25746. #endif /* HAVE_SPHINCS */
  25747. #endif /* HAVE_PQC */
  25748. else {
  25749. ret = BAD_FUNC_ARG;
  25750. }
  25751. }
  25752. if ((ret == 0) && (cert->serialSz == 0)) {
  25753. /* Generate random serial number. */
  25754. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25755. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  25756. }
  25757. if (ret == 0) {
  25758. /* Determine issuer name size. */
  25759. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25760. defined(WOLFSSL_CERT_REQ)
  25761. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  25762. if (issRawLen > 0) {
  25763. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  25764. }
  25765. else
  25766. #endif
  25767. {
  25768. /* Calculate issuer name encoding size. If the cert is self-signed
  25769. * use the subject instead of the issuer. */
  25770. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  25771. &cert->subject : &cert->issuer, cert->heap);
  25772. issuerSz = (word32)ret;
  25773. }
  25774. }
  25775. if (ret >= 0) {
  25776. /* Determine subject name size. */
  25777. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25778. defined(WOLFSSL_CERT_REQ)
  25779. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  25780. if (sbjRawLen > 0) {
  25781. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  25782. }
  25783. else
  25784. #endif
  25785. {
  25786. /* Calculate subject name encoding size. */
  25787. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  25788. cert->heap);
  25789. subjectSz = (word32)ret;
  25790. }
  25791. }
  25792. if (ret >= 0) {
  25793. /* Calculate public key encoding size. */
  25794. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  25795. eccKey, ed25519Key, ed448Key, dsaKey);
  25796. publicKeySz = (word32)ret;
  25797. }
  25798. if (ret >= 0) {
  25799. /* Calculate extensions encoding size - may be 0. */
  25800. ret = EncodeExtensions(cert, NULL, 0, 0);
  25801. extSz = (word32)ret;
  25802. }
  25803. if (ret >= 0) {
  25804. /* Don't write out outer sequence - only doing body. */
  25805. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  25806. /* Set version, serial number and signature OID */
  25807. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  25808. (byte)cert->version);
  25809. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  25810. (word32)cert->serialSz);
  25811. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  25812. (word32)cert->sigType, oidSigType);
  25813. if (IsSigAlgoECC((word32)cert->sigType)) {
  25814. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  25815. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  25816. }
  25817. #ifdef WC_RSA_PSS
  25818. /* TODO: Encode RSA PSS parameters. */
  25819. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  25820. #endif
  25821. if (issRawLen > 0) {
  25822. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25823. defined(WOLFSSL_CERT_REQ)
  25824. /* Put in encoded issuer name. */
  25825. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25826. cert->issRaw, issuerSz);
  25827. #endif
  25828. }
  25829. else {
  25830. /* Leave space for issuer name. */
  25831. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  25832. NULL, issuerSz);
  25833. }
  25834. if (cert->beforeDateSz && cert->afterDateSz) {
  25835. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  25836. /* Make space for before date data. */
  25837. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  25838. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  25839. /* Don't put out Generalized Time before data. */
  25840. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  25841. }
  25842. else {
  25843. /* Don't put out UTC before data. */
  25844. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25845. /* Make space for before date data. */
  25846. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25847. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  25848. }
  25849. if (cert->afterDate[0] == ASN_UTC_TIME) {
  25850. /* Make space for after date data. */
  25851. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  25852. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  25853. /* Don't put out UTC Generalized Time after data. */
  25854. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  25855. }
  25856. else {
  25857. /* Don't put out UTC after data. */
  25858. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25859. /* Make space for after date data. */
  25860. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25861. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  25862. }
  25863. }
  25864. else
  25865. {
  25866. /* Don't put out UTC before data. */
  25867. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  25868. /* Make space for before date data. */
  25869. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  25870. NULL, ASN_GEN_TIME_SZ);
  25871. /* Don't put out UTC after data. */
  25872. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  25873. /* Make space for after date data. */
  25874. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  25875. NULL, ASN_GEN_TIME_SZ);
  25876. }
  25877. if (sbjRawLen > 0) {
  25878. /* Put in encoded subject name. */
  25879. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25880. defined(WOLFSSL_CERT_REQ)
  25881. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25882. cert->sbjRaw, subjectSz);
  25883. #endif
  25884. }
  25885. else {
  25886. /* Leave space for subject name. */
  25887. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  25888. NULL, subjectSz);
  25889. }
  25890. /* Leave space for public key. */
  25891. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  25892. NULL, publicKeySz);
  25893. /* Replacement buffer instead of algorithm identifier items. */
  25894. SetASNItem_NoOut(dataASN,
  25895. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  25896. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  25897. /* issuerUniqueID and subjectUniqueID not supported. */
  25898. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  25899. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  25900. /* Leave space for extensions if any set into certificate object. */
  25901. if (extSz > 0) {
  25902. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  25903. }
  25904. else {
  25905. SetASNItem_NoOutNode(dataASN, x509CertASN,
  25906. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  25907. }
  25908. /* No signature - added later. */
  25909. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  25910. X509CERTASN_IDX_SIGNATURE);
  25911. /* Calculate encoded certificate body size. */
  25912. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  25913. }
  25914. /* Check buffer is big enough for encoded data. */
  25915. if ((ret == 0) && (sz > (int)derSz)) {
  25916. ret = BUFFER_E;
  25917. }
  25918. if (ret == 0) {
  25919. /* Encode certificate body into buffer. */
  25920. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  25921. if (issRawLen == 0) {
  25922. /* Encode issuer name into buffer. Use the subject as the issuer
  25923. * if it is self-signed. Size will be correct because we did the
  25924. * same for size. */
  25925. ret = SetNameEx(
  25926. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  25927. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  25928. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25929. }
  25930. }
  25931. if ((ret >= 0) && (sbjRawLen == 0)) {
  25932. /* Encode subject name into buffer. */
  25933. ret = SetNameEx(
  25934. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  25935. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  25936. &cert->subject, cert->heap);
  25937. }
  25938. if (ret >= 0) {
  25939. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  25940. {
  25941. /* Encode validity into buffer. */
  25942. ret = SetValidity(
  25943. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  25944. .data.buffer.data,
  25945. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  25946. .data.buffer.data, cert->daysValid);
  25947. }
  25948. }
  25949. if (ret >= 0) {
  25950. /* Encode public key into buffer. */
  25951. ret = EncodePublicKey(cert->keyType,
  25952. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25953. .data.buffer.data,
  25954. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  25955. .data.buffer.length,
  25956. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  25957. }
  25958. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  25959. /* Encode extensions into buffer. */
  25960. ret = EncodeExtensions(cert,
  25961. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  25962. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  25963. }
  25964. if (ret >= 0) {
  25965. /* Store encoded certifcate body size. */
  25966. cert->bodySz = sz;
  25967. /* Return the encoding size. */
  25968. ret = sz;
  25969. }
  25970. FREE_ASNSETDATA(dataASN, cert->heap);
  25971. return ret;
  25972. #endif
  25973. }
  25974. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  25975. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  25976. void* key, WC_RNG* rng)
  25977. {
  25978. RsaKey* rsaKey = NULL;
  25979. DsaKey* dsaKey = NULL;
  25980. ecc_key* eccKey = NULL;
  25981. ed25519_key* ed25519Key = NULL;
  25982. ed448_key* ed448Key = NULL;
  25983. falcon_key* falconKey = NULL;
  25984. dilithium_key* dilithiumKey = NULL;
  25985. sphincs_key* sphincsKey = NULL;
  25986. if (keyType == RSA_TYPE)
  25987. rsaKey = (RsaKey*)key;
  25988. else if (keyType == DSA_TYPE)
  25989. dsaKey = (DsaKey*)key;
  25990. else if (keyType == ECC_TYPE)
  25991. eccKey = (ecc_key*)key;
  25992. else if (keyType == ED25519_TYPE)
  25993. ed25519Key = (ed25519_key*)key;
  25994. else if (keyType == ED448_TYPE)
  25995. ed448Key = (ed448_key*)key;
  25996. else if (keyType == FALCON_LEVEL1_TYPE)
  25997. falconKey = (falcon_key*)key;
  25998. else if (keyType == FALCON_LEVEL5_TYPE)
  25999. falconKey = (falcon_key*)key;
  26000. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26001. dilithiumKey = (dilithium_key*)key;
  26002. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26003. dilithiumKey = (dilithium_key*)key;
  26004. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26005. dilithiumKey = (dilithium_key*)key;
  26006. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26007. sphincsKey = (sphincs_key*)key;
  26008. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26009. sphincsKey = (sphincs_key*)key;
  26010. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26011. sphincsKey = (sphincs_key*)key;
  26012. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26013. sphincsKey = (sphincs_key*)key;
  26014. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26015. sphincsKey = (sphincs_key*)key;
  26016. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26017. sphincsKey = (sphincs_key*)key;
  26018. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  26019. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26020. sphincsKey);
  26021. }
  26022. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26023. WOLFSSL_ABI
  26024. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  26025. ecc_key* eccKey, WC_RNG* rng)
  26026. {
  26027. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  26028. NULL, NULL, NULL, NULL);
  26029. }
  26030. #ifdef WOLFSSL_CERT_REQ
  26031. #ifndef WOLFSSL_ASN_TEMPLATE
  26032. /* return size of data set on success
  26033. * if getting size only then attr and oid should be NULL
  26034. */
  26035. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  26036. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  26037. word32 extSz)
  26038. {
  26039. word32 totalSz = 0;
  26040. word32 seqSz = 0;
  26041. word32 setSz = 0;
  26042. word32 strSz = 0;
  26043. byte seq[MAX_SEQ_SZ];
  26044. byte set[MAX_SET_SZ];
  26045. byte str[MAX_PRSTR_SZ];
  26046. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  26047. totalSz += oidSz;
  26048. if (extSz > 0) {
  26049. totalSz += setSz = SetSet(extSz, set);
  26050. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26051. totalSz += extSz;
  26052. }
  26053. else {
  26054. if (printable) {
  26055. strSz = SetPrintableString(attrSz, str);
  26056. totalSz += strSz;
  26057. }
  26058. else {
  26059. totalSz += strSz = SetUTF8String(attrSz, str);
  26060. }
  26061. totalSz += setSz = SetSet(strSz + attrSz, set);
  26062. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26063. totalSz += attrSz;
  26064. }
  26065. if (oid) {
  26066. XMEMCPY(&output[*idx], seq, seqSz);
  26067. *idx += seqSz;
  26068. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  26069. XMEMCPY(&output[*idx], oid, oidSz);
  26070. *idx += oidSz;
  26071. XMEMCPY(&output[*idx], set, setSz);
  26072. *idx += setSz;
  26073. if (strSz > 0) {
  26074. XMEMCPY(&output[*idx], str, strSz);
  26075. *idx += strSz;
  26076. if (attrSz > 0) {
  26077. XMEMCPY(&output[*idx], attr, attrSz);
  26078. *idx += attrSz;
  26079. }
  26080. }
  26081. }
  26082. return totalSz;
  26083. }
  26084. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  26085. {
  26086. word32 sz = 0; /* overall size */
  26087. word32 setSz = 0;
  26088. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26089. sz++;
  26090. if (cert->challengePw[0]) {
  26091. setSz += SetReqAttribSingle(output, &sz, NULL,
  26092. (word32)XSTRLEN(cert->challengePw), NULL,
  26093. sizeof(attrChallengePasswordOid),
  26094. (byte)cert->challengePwPrintableString, 0);
  26095. }
  26096. if (cert->unstructuredName[0]) {
  26097. setSz += SetReqAttribSingle(output, &sz, NULL,
  26098. (word32)XSTRLEN(cert->unstructuredName), NULL,
  26099. sizeof(attrUnstructuredNameOid), 1, 0);
  26100. }
  26101. if (extSz) {
  26102. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26103. sizeof(attrExtensionRequestOid), 1, extSz);
  26104. }
  26105. /* Put the pieces together. */
  26106. sz += SetLength(setSz, &output[sz]);
  26107. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26108. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26109. return REQ_ATTRIBUTE_E;
  26110. }
  26111. if (cert->challengePw[0]) {
  26112. SetReqAttribSingle(output, &sz, cert->challengePw,
  26113. (word32)XSTRLEN(cert->challengePw),
  26114. &attrChallengePasswordOid[0],
  26115. sizeof(attrChallengePasswordOid),
  26116. (byte)cert->challengePwPrintableString, 0);
  26117. }
  26118. if (cert->unstructuredName[0]) {
  26119. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26120. (word32)XSTRLEN(cert->unstructuredName),
  26121. &attrUnstructuredNameOid[0],
  26122. sizeof(attrUnstructuredNameOid), 1, 0);
  26123. }
  26124. if (extSz) {
  26125. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26126. sizeof(attrExtensionRequestOid), 1, extSz);
  26127. /* The actual extension data will be tacked onto the output later. */
  26128. }
  26129. return (int)sz;
  26130. }
  26131. #ifdef WOLFSSL_CUSTOM_OID
  26132. /* encode a custom oid and value */
  26133. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26134. CertOidField* custom)
  26135. {
  26136. int idx = 0, cust_lenSz, cust_oidSz;
  26137. if (cert == NULL || output == NULL || custom == NULL) {
  26138. return BAD_FUNC_ARG;
  26139. }
  26140. if (custom->oid == NULL || custom->oidSz <= 0) {
  26141. return 0; /* none set */
  26142. }
  26143. /* Octet String header */
  26144. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26145. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26146. /* check for output buffer room */
  26147. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26148. outSz) {
  26149. return BUFFER_E;
  26150. }
  26151. /* put sequence with total */
  26152. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26153. output);
  26154. /* put oid header */
  26155. idx += SetObjectId(custom->oidSz, output+idx);
  26156. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26157. idx += custom->oidSz;
  26158. /* put value */
  26159. idx += SetOctetString(custom->valSz, output+idx);
  26160. XMEMCPY(output+idx, custom->val, custom->valSz);
  26161. idx += custom->valSz;
  26162. return idx;
  26163. }
  26164. #endif /* WOLFSSL_CUSTOM_OID */
  26165. /* encode info from cert into DER encoded format */
  26166. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26167. DsaKey* dsaKey, ecc_key* eccKey,
  26168. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26169. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26170. sphincs_key* sphincsKey)
  26171. {
  26172. int ret;
  26173. (void)eccKey;
  26174. (void)ed25519Key;
  26175. (void)ed448Key;
  26176. (void)falconKey;
  26177. (void)dilithiumKey;
  26178. (void)sphincsKey;
  26179. if (cert == NULL || der == NULL)
  26180. return BAD_FUNC_ARG;
  26181. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26182. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26183. falconKey == NULL) {
  26184. return PUBLIC_KEY_E;
  26185. }
  26186. /* init */
  26187. XMEMSET(der, 0, sizeof(DerCert));
  26188. /* version */
  26189. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  26190. /* subject name */
  26191. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26192. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26193. /* Use the raw subject */
  26194. int idx;
  26195. der->subjectSz = (int)min(sizeof(der->subject),
  26196. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26197. /* header */
  26198. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  26199. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26200. return SUBJECT_E;
  26201. }
  26202. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26203. (size_t)der->subjectSz);
  26204. der->subjectSz += idx;
  26205. }
  26206. else
  26207. #endif
  26208. {
  26209. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26210. &cert->subject, cert->heap);
  26211. }
  26212. if (der->subjectSz <= 0)
  26213. return SUBJECT_E;
  26214. /* public key */
  26215. #ifndef NO_RSA
  26216. if (cert->keyType == RSA_KEY) {
  26217. if (rsaKey == NULL)
  26218. return PUBLIC_KEY_E;
  26219. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26220. sizeof(der->publicKey), 1);
  26221. }
  26222. #endif
  26223. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26224. if (cert->keyType == DSA_KEY) {
  26225. if (dsaKey == NULL)
  26226. return PUBLIC_KEY_E;
  26227. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26228. sizeof(der->publicKey), 1);
  26229. }
  26230. #endif
  26231. #ifdef HAVE_ECC
  26232. if (cert->keyType == ECC_KEY) {
  26233. if (eccKey == NULL)
  26234. return PUBLIC_KEY_E;
  26235. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26236. sizeof(der->publicKey), 1, 0);
  26237. }
  26238. #endif
  26239. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26240. if (cert->keyType == ED25519_KEY) {
  26241. if (ed25519Key == NULL)
  26242. return PUBLIC_KEY_E;
  26243. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26244. (word32)sizeof(der->publicKey), 1);
  26245. }
  26246. #endif
  26247. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26248. if (cert->keyType == ED448_KEY) {
  26249. if (ed448Key == NULL)
  26250. return PUBLIC_KEY_E;
  26251. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26252. (word32)sizeof(der->publicKey), 1);
  26253. }
  26254. #endif
  26255. #if defined(HAVE_PQC)
  26256. #if defined(HAVE_FALCON)
  26257. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26258. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26259. if (falconKey == NULL)
  26260. return PUBLIC_KEY_E;
  26261. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26262. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26263. }
  26264. #endif
  26265. #if defined(HAVE_DILITHIUM)
  26266. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26267. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26268. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26269. if (dilithiumKey == NULL)
  26270. return PUBLIC_KEY_E;
  26271. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26272. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26273. }
  26274. #endif
  26275. #if defined(HAVE_SPHINCS)
  26276. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26277. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26278. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26279. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26280. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26281. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26282. if (sphincsKey == NULL)
  26283. return PUBLIC_KEY_E;
  26284. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26285. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26286. }
  26287. #endif
  26288. #endif /* HAVE_PQC */
  26289. if (der->publicKeySz <= 0)
  26290. return PUBLIC_KEY_E;
  26291. /* set the extensions */
  26292. der->extensionsSz = 0;
  26293. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26294. * The pathLenConstraint field is meaningful only if the CA boolean is
  26295. * asserted and the key usage extension, if present, asserts the
  26296. * keyCertSign bit */
  26297. /* Set CA and path length */
  26298. if ((cert->isCA) && (cert->pathLenSet)
  26299. #ifdef WOLFSSL_CERT_EXT
  26300. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26301. #endif
  26302. ) {
  26303. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26304. if (der->caSz <= 0)
  26305. return CA_TRUE_E;
  26306. der->extensionsSz += der->caSz;
  26307. }
  26308. /* Set CA */
  26309. else if (cert->isCA) {
  26310. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26311. if (der->caSz <= 0)
  26312. return CA_TRUE_E;
  26313. der->extensionsSz += der->caSz;
  26314. }
  26315. /* Set Basic Constraint */
  26316. else if (cert->basicConstSet) {
  26317. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26318. if (der->caSz <= 0)
  26319. return EXTENSIONS_E;
  26320. der->extensionsSz += der->caSz;
  26321. }
  26322. else
  26323. der->caSz = 0;
  26324. #ifdef WOLFSSL_ALT_NAMES
  26325. /* Alternative Name */
  26326. if (cert->altNamesSz) {
  26327. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26328. cert->altNames, (word32)cert->altNamesSz,
  26329. cert->altNamesCrit);
  26330. if (der->altNamesSz <= 0)
  26331. return ALT_NAME_E;
  26332. der->extensionsSz += der->altNamesSz;
  26333. }
  26334. else
  26335. der->altNamesSz = 0;
  26336. #endif
  26337. #ifdef WOLFSSL_CERT_EXT
  26338. /* SKID */
  26339. if (cert->skidSz) {
  26340. /* check the provided SKID size */
  26341. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26342. return SKID_E;
  26343. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26344. cert->skid, (word32)cert->skidSz);
  26345. if (der->skidSz <= 0)
  26346. return SKID_E;
  26347. der->extensionsSz += der->skidSz;
  26348. }
  26349. else
  26350. der->skidSz = 0;
  26351. /* Key Usage */
  26352. if (cert->keyUsage != 0) {
  26353. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26354. cert->keyUsage);
  26355. if (der->keyUsageSz <= 0)
  26356. return KEYUSAGE_E;
  26357. der->extensionsSz += der->keyUsageSz;
  26358. }
  26359. else
  26360. der->keyUsageSz = 0;
  26361. /* Extended Key Usage */
  26362. if (cert->extKeyUsage != 0) {
  26363. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26364. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26365. if (der->extKeyUsageSz <= 0)
  26366. return EXTKEYUSAGE_E;
  26367. der->extensionsSz += der->extKeyUsageSz;
  26368. }
  26369. else
  26370. der->extKeyUsageSz = 0;
  26371. #endif /* WOLFSSL_CERT_EXT */
  26372. #ifdef WOLFSSL_CUSTOM_OID
  26373. /* encode a custom oid and value */
  26374. /* zero returns, means none set */
  26375. ret = SetCustomObjectId(cert, der->extCustom,
  26376. sizeof(der->extCustom), &cert->extCustom);
  26377. if (ret < 0)
  26378. return ret;
  26379. der->extCustomSz = ret;
  26380. der->extensionsSz += der->extCustomSz;
  26381. #endif
  26382. /* put extensions */
  26383. if (der->extensionsSz > 0) {
  26384. /* put the start of sequence (ID, Size) */
  26385. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  26386. der->extensions);
  26387. if (der->extensionsSz <= 0)
  26388. return EXTENSIONS_E;
  26389. /* put CA */
  26390. if (der->caSz) {
  26391. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26392. &der->extensionsSz,
  26393. der->ca, der->caSz);
  26394. if (ret <= 0)
  26395. return EXTENSIONS_E;
  26396. }
  26397. #ifdef WOLFSSL_ALT_NAMES
  26398. /* put Alternative Names */
  26399. if (der->altNamesSz) {
  26400. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26401. &der->extensionsSz,
  26402. der->altNames, der->altNamesSz);
  26403. if (ret <= 0)
  26404. return EXTENSIONS_E;
  26405. }
  26406. #endif
  26407. #ifdef WOLFSSL_CERT_EXT
  26408. /* put SKID */
  26409. if (der->skidSz) {
  26410. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26411. &der->extensionsSz,
  26412. der->skid, der->skidSz);
  26413. if (ret <= 0)
  26414. return EXTENSIONS_E;
  26415. }
  26416. /* put AKID */
  26417. if (der->akidSz) {
  26418. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26419. &der->extensionsSz,
  26420. der->akid, der->akidSz);
  26421. if (ret <= 0)
  26422. return EXTENSIONS_E;
  26423. }
  26424. /* put KeyUsage */
  26425. if (der->keyUsageSz) {
  26426. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26427. &der->extensionsSz,
  26428. der->keyUsage, der->keyUsageSz);
  26429. if (ret <= 0)
  26430. return EXTENSIONS_E;
  26431. }
  26432. /* put ExtendedKeyUsage */
  26433. if (der->extKeyUsageSz) {
  26434. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26435. &der->extensionsSz,
  26436. der->extKeyUsage, der->extKeyUsageSz);
  26437. if (ret <= 0)
  26438. return EXTENSIONS_E;
  26439. }
  26440. #ifdef WOLFSSL_CUSTOM_OID
  26441. if (der->extCustomSz) {
  26442. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26443. &der->extensionsSz,
  26444. der->extCustom, der->extCustomSz);
  26445. if (ret <= 0)
  26446. return EXTENSIONS_E;
  26447. }
  26448. #endif
  26449. #endif /* WOLFSSL_CERT_EXT */
  26450. }
  26451. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  26452. if (der->attribSz <= 0)
  26453. return REQ_ATTRIBUTE_E;
  26454. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  26455. der->extensionsSz + der->attribSz;
  26456. return 0;
  26457. }
  26458. /* write DER encoded cert req to buffer, size already checked */
  26459. static int WriteCertReqBody(DerCert* der, byte* buf)
  26460. {
  26461. int idx;
  26462. /* signed part header */
  26463. idx = (int)SetSequence((word32)der->total, buf);
  26464. /* version */
  26465. if (buf)
  26466. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  26467. idx += der->versionSz;
  26468. /* subject */
  26469. if (buf)
  26470. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  26471. idx += der->subjectSz;
  26472. /* public key */
  26473. if (buf)
  26474. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  26475. idx += der->publicKeySz;
  26476. /* attributes */
  26477. if (buf)
  26478. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  26479. idx += der->attribSz;
  26480. /* extensions */
  26481. if (der->extensionsSz) {
  26482. if (buf)
  26483. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  26484. sizeof(der->extensions)));
  26485. idx += der->extensionsSz;
  26486. }
  26487. return idx;
  26488. }
  26489. #endif
  26490. #ifdef WOLFSSL_ASN_TEMPLATE
  26491. /* ASN.1 template for Certificate Request body.
  26492. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  26493. */
  26494. static const ASNItem certReqBodyASN[] = {
  26495. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26496. /* version */
  26497. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  26498. /* subject */
  26499. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26500. /* subjectPKInfo */
  26501. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26502. /* attributes*/
  26503. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26504. /* Challenge Password Attribute */
  26505. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26506. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26507. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  26508. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  26509. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  26510. /* Extensions Attribute */
  26511. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26512. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26513. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  26514. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  26515. };
  26516. enum {
  26517. CERTREQBODYASN_IDX_SEQ = 0,
  26518. CERTREQBODYASN_IDX_VER,
  26519. CERTREQBODYASN_IDX_SUBJ_SEQ,
  26520. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  26521. CERTREQBODYASN_IDX_ATTRS,
  26522. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  26523. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  26524. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  26525. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  26526. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  26527. CERTREQBODYASN_IDX_EXT_SEQ,
  26528. CERTREQBODYASN_IDX_EXT_OID,
  26529. CERTREQBODYASN_IDX_EXT_SET,
  26530. CERTREQBODYASN_IDX_EXT_BODY
  26531. };
  26532. /* Number of items in ASN.1 template for Certificate Request body. */
  26533. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  26534. #endif
  26535. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26536. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  26537. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26538. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26539. sphincs_key* sphincsKey)
  26540. {
  26541. #ifndef WOLFSSL_ASN_TEMPLATE
  26542. int ret;
  26543. #ifdef WOLFSSL_SMALL_STACK
  26544. DerCert* der;
  26545. #else
  26546. DerCert der[1];
  26547. #endif
  26548. if (eccKey)
  26549. cert->keyType = ECC_KEY;
  26550. else if (rsaKey)
  26551. cert->keyType = RSA_KEY;
  26552. else if (dsaKey)
  26553. cert->keyType = DSA_KEY;
  26554. else if (ed25519Key)
  26555. cert->keyType = ED25519_KEY;
  26556. else if (ed448Key)
  26557. cert->keyType = ED448_KEY;
  26558. #ifdef HAVE_PQC
  26559. #ifdef HAVE_FALCON
  26560. else if ((falconKey != NULL) && (falconKey->level == 1))
  26561. cert->keyType = FALCON_LEVEL1_KEY;
  26562. else if ((falconKey != NULL) && (falconKey->level == 5))
  26563. cert->keyType = FALCON_LEVEL5_KEY;
  26564. #endif /* HAVE_FALCON */
  26565. #ifdef HAVE_DILITHIUM
  26566. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26567. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26568. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26569. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26570. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26571. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26572. #endif /* HAVE_DILITHIUM */
  26573. #ifdef HAVE_SPHINCS
  26574. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26575. && (sphincsKey->optim == FAST_VARIANT))
  26576. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26577. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26578. && (sphincsKey->optim == FAST_VARIANT))
  26579. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26580. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26581. && (sphincsKey->optim == FAST_VARIANT))
  26582. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26583. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26584. && (sphincsKey->optim == SMALL_VARIANT))
  26585. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26586. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26587. && (sphincsKey->optim == SMALL_VARIANT))
  26588. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26589. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26590. && (sphincsKey->optim == SMALL_VARIANT))
  26591. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26592. #endif /* HAVE_SPHINCS */
  26593. #endif /* HAVE_PQC */
  26594. else
  26595. return BAD_FUNC_ARG;
  26596. #ifdef WOLFSSL_SMALL_STACK
  26597. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  26598. DYNAMIC_TYPE_TMP_BUFFER);
  26599. if (der == NULL)
  26600. return MEMORY_E;
  26601. #endif
  26602. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  26603. falconKey, dilithiumKey, sphincsKey);
  26604. if (ret == 0) {
  26605. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26606. ret = BUFFER_E;
  26607. else
  26608. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  26609. }
  26610. #ifdef WOLFSSL_SMALL_STACK
  26611. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26612. #endif
  26613. return ret;
  26614. #else
  26615. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  26616. word32 publicKeySz = 0;
  26617. word32 subjectSz = 0;
  26618. word32 extSz = 0;
  26619. int sz = 0;
  26620. int ret = 0;
  26621. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26622. word32 sbjRawSz = 0;
  26623. #endif
  26624. /* Unused without OQS */
  26625. (void)falconKey;
  26626. (void)dilithiumKey;
  26627. (void)sphincsKey;
  26628. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  26629. if (ret == 0) {
  26630. /* Set key type into certificate object based on key passed in. */
  26631. if (rsaKey != NULL) {
  26632. cert->keyType = RSA_KEY;
  26633. }
  26634. else if (eccKey != NULL) {
  26635. cert->keyType = ECC_KEY;
  26636. }
  26637. else if (dsaKey != NULL) {
  26638. cert->keyType = DSA_KEY;
  26639. }
  26640. else if (ed25519Key != NULL) {
  26641. cert->keyType = ED25519_KEY;
  26642. }
  26643. else if (ed448Key != NULL) {
  26644. cert->keyType = ED448_KEY;
  26645. }
  26646. #ifdef HAVE_PQC
  26647. #ifdef HAVE_FALCON
  26648. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26649. cert->keyType = FALCON_LEVEL1_KEY;
  26650. }
  26651. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26652. cert->keyType = FALCON_LEVEL5_KEY;
  26653. }
  26654. #endif /* HAVE_FALCON */
  26655. #ifdef HAVE_DILITHIUM
  26656. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26657. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26658. }
  26659. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26660. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26661. }
  26662. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26663. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26664. }
  26665. #endif /* HAVE_DILITHIUM */
  26666. #ifdef HAVE_SPHINCS
  26667. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26668. && (sphincsKey->optim == FAST_VARIANT)) {
  26669. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26670. }
  26671. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26672. && (sphincsKey->optim == FAST_VARIANT)) {
  26673. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26674. }
  26675. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26676. && (sphincsKey->optim == FAST_VARIANT)) {
  26677. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26678. }
  26679. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26680. && (sphincsKey->optim == SMALL_VARIANT)) {
  26681. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26682. }
  26683. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26684. && (sphincsKey->optim == SMALL_VARIANT)) {
  26685. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26686. }
  26687. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26688. && (sphincsKey->optim == SMALL_VARIANT)) {
  26689. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26690. }
  26691. #endif /* HAVE_SPHINCS */
  26692. #endif /* HAVE_PQC */
  26693. else {
  26694. ret = BAD_FUNC_ARG;
  26695. }
  26696. }
  26697. if (ret == 0) {
  26698. /* Determine subject name size. */
  26699. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26700. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26701. if (sbjRawSz > 0) {
  26702. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  26703. }
  26704. else
  26705. #endif
  26706. {
  26707. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  26708. subjectSz = (word32)ret;
  26709. }
  26710. }
  26711. if (ret >= 0) {
  26712. /* Determine encode public key size. */
  26713. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26714. eccKey, ed25519Key, ed448Key, dsaKey);
  26715. publicKeySz = (word32)ret;
  26716. }
  26717. if (ret >= 0) {
  26718. /* Determine encode extensions size. */
  26719. ret = EncodeExtensions(cert, NULL, 0, 1);
  26720. extSz = (word32)ret;
  26721. }
  26722. if (ret >= 0) {
  26723. /* Set version. */
  26724. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  26725. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26726. if (sbjRawSz > 0) {
  26727. /* Put in encoded subject name. */
  26728. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  26729. subjectSz);
  26730. }
  26731. else
  26732. #endif
  26733. {
  26734. /* Leave space for subject name. */
  26735. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  26736. subjectSz);
  26737. }
  26738. /* Leave space for public key. */
  26739. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  26740. NULL, publicKeySz);
  26741. if (cert->challengePw[0] != '\0') {
  26742. /* Add challenge password attribute. */
  26743. /* Set challenge password OID. */
  26744. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  26745. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  26746. /* Enable the ASN template item with the appropriate tag. */
  26747. if (cert->challengePwPrintableString) {
  26748. /* PRINTABLE_STRING - set buffer */
  26749. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  26750. (byte*)cert->challengePw,
  26751. (word32)XSTRLEN(cert->challengePw));
  26752. /* UTF8STRING - don't encode */
  26753. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  26754. }
  26755. else {
  26756. /* PRINTABLE_STRING - don't encode */
  26757. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  26758. /* UTF8STRING - set buffer */
  26759. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  26760. (byte*)cert->challengePw,
  26761. (word32)XSTRLEN(cert->challengePw));
  26762. }
  26763. }
  26764. else {
  26765. /* Leave out challenge password attribute items. */
  26766. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26767. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  26768. }
  26769. if (extSz > 0) {
  26770. /* Set extension attribute OID. */
  26771. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  26772. sizeof(attrExtensionRequestOid));
  26773. /* Leave space for data. */
  26774. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  26775. }
  26776. else {
  26777. /* Leave out extension attribute items. */
  26778. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26779. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  26780. }
  26781. /* Calculate size of encoded certificate request body. */
  26782. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  26783. &sz);
  26784. }
  26785. /* Check buffer is big enough for encoded data. */
  26786. if ((ret == 0) && (sz > (int)derSz)) {
  26787. ret = BUFFER_E;
  26788. }
  26789. if (ret == 0 && derBuffer != NULL) {
  26790. /* Encode certificate request body into buffer. */
  26791. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  26792. /* Put in generated data */
  26793. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26794. if (sbjRawSz == 0)
  26795. #endif
  26796. {
  26797. /* Encode subject name into space in buffer. */
  26798. ret = SetNameEx(
  26799. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  26800. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  26801. &cert->subject, cert->heap);
  26802. }
  26803. }
  26804. if (ret >= 0 && derBuffer != NULL) {
  26805. /* Encode public key into space in buffer. */
  26806. ret = EncodePublicKey(cert->keyType,
  26807. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  26808. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  26809. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26810. }
  26811. if ((ret >= 0 && derBuffer != NULL) &&
  26812. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  26813. /* Encode extensions into space in buffer. */
  26814. ret = EncodeExtensions(cert,
  26815. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  26816. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  26817. }
  26818. if (ret >= 0) {
  26819. /* Store encoded certifcate request body size. */
  26820. cert->bodySz = sz;
  26821. /* Return the encoding size. */
  26822. ret = sz;
  26823. }
  26824. FREE_ASNSETDATA(dataASN, cert->heap);
  26825. return ret;
  26826. #endif /* WOLFSSL_ASN_TEMPLATE */
  26827. }
  26828. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26829. void* key)
  26830. {
  26831. RsaKey* rsaKey = NULL;
  26832. DsaKey* dsaKey = NULL;
  26833. ecc_key* eccKey = NULL;
  26834. ed25519_key* ed25519Key = NULL;
  26835. ed448_key* ed448Key = NULL;
  26836. falcon_key* falconKey = NULL;
  26837. dilithium_key* dilithiumKey = NULL;
  26838. sphincs_key* sphincsKey = NULL;
  26839. if (keyType == RSA_TYPE)
  26840. rsaKey = (RsaKey*)key;
  26841. else if (keyType == DSA_TYPE)
  26842. dsaKey = (DsaKey*)key;
  26843. else if (keyType == ECC_TYPE)
  26844. eccKey = (ecc_key*)key;
  26845. else if (keyType == ED25519_TYPE)
  26846. ed25519Key = (ed25519_key*)key;
  26847. else if (keyType == ED448_TYPE)
  26848. ed448Key = (ed448_key*)key;
  26849. else if (keyType == FALCON_LEVEL1_TYPE)
  26850. falconKey = (falcon_key*)key;
  26851. else if (keyType == FALCON_LEVEL5_TYPE)
  26852. falconKey = (falcon_key*)key;
  26853. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26854. dilithiumKey = (dilithium_key*)key;
  26855. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26856. dilithiumKey = (dilithium_key*)key;
  26857. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26858. dilithiumKey = (dilithium_key*)key;
  26859. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26860. sphincsKey = (sphincs_key*)key;
  26861. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26862. sphincsKey = (sphincs_key*)key;
  26863. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26864. sphincsKey = (sphincs_key*)key;
  26865. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26866. sphincsKey = (sphincs_key*)key;
  26867. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26868. sphincsKey = (sphincs_key*)key;
  26869. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26870. sphincsKey = (sphincs_key*)key;
  26871. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  26872. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26873. sphincsKey);
  26874. }
  26875. WOLFSSL_ABI
  26876. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26877. RsaKey* rsaKey, ecc_key* eccKey)
  26878. {
  26879. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  26880. NULL, NULL, NULL, NULL);
  26881. }
  26882. #endif /* WOLFSSL_CERT_REQ */
  26883. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26884. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  26885. ed448_key* ed448Key, falcon_key* falconKey,
  26886. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  26887. WC_RNG* rng)
  26888. {
  26889. int sigSz = 0;
  26890. void* heap = NULL;
  26891. CertSignCtx certSignCtx_lcl;
  26892. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  26893. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  26894. if (requestSz < 0)
  26895. return requestSz;
  26896. /* locate ctx */
  26897. if (rsaKey) {
  26898. #ifndef NO_RSA
  26899. #ifdef WOLFSSL_ASYNC_CRYPT
  26900. certSignCtx = &rsaKey->certSignCtx;
  26901. #endif
  26902. heap = rsaKey->heap;
  26903. #else
  26904. return NOT_COMPILED_IN;
  26905. #endif /* NO_RSA */
  26906. }
  26907. else if (eccKey) {
  26908. #ifdef HAVE_ECC
  26909. #ifdef WOLFSSL_ASYNC_CRYPT
  26910. certSignCtx = &eccKey->certSignCtx;
  26911. #endif
  26912. heap = eccKey->heap;
  26913. #else
  26914. return NOT_COMPILED_IN;
  26915. #endif /* HAVE_ECC */
  26916. }
  26917. if (certSignCtx->sig == NULL) {
  26918. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  26919. DYNAMIC_TYPE_TMP_BUFFER);
  26920. if (certSignCtx->sig == NULL)
  26921. return MEMORY_E;
  26922. }
  26923. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  26924. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  26925. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  26926. #ifdef WOLFSSL_ASYNC_CRYPT
  26927. if (sigSz == WC_PENDING_E) {
  26928. /* Not free'ing certSignCtx->sig here because it could still be in use
  26929. * with async operations. */
  26930. return sigSz;
  26931. }
  26932. #endif
  26933. if (sigSz >= 0) {
  26934. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  26935. sigSz = BUFFER_E;
  26936. else
  26937. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  26938. sType);
  26939. }
  26940. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26941. certSignCtx->sig = NULL;
  26942. return sigSz;
  26943. }
  26944. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  26945. int keyType, void* key, WC_RNG* rng)
  26946. {
  26947. RsaKey* rsaKey = NULL;
  26948. ecc_key* eccKey = NULL;
  26949. ed25519_key* ed25519Key = NULL;
  26950. ed448_key* ed448Key = NULL;
  26951. falcon_key* falconKey = NULL;
  26952. dilithium_key* dilithiumKey = NULL;
  26953. sphincs_key* sphincsKey = NULL;
  26954. if (keyType == RSA_TYPE)
  26955. rsaKey = (RsaKey*)key;
  26956. else if (keyType == ECC_TYPE)
  26957. eccKey = (ecc_key*)key;
  26958. else if (keyType == ED25519_TYPE)
  26959. ed25519Key = (ed25519_key*)key;
  26960. else if (keyType == ED448_TYPE)
  26961. ed448Key = (ed448_key*)key;
  26962. else if (keyType == FALCON_LEVEL1_TYPE)
  26963. falconKey = (falcon_key*)key;
  26964. else if (keyType == FALCON_LEVEL5_TYPE)
  26965. falconKey = (falcon_key*)key;
  26966. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26967. dilithiumKey = (dilithium_key*)key;
  26968. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26969. dilithiumKey = (dilithium_key*)key;
  26970. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26971. dilithiumKey = (dilithium_key*)key;
  26972. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26973. sphincsKey = (sphincs_key*)key;
  26974. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26975. sphincsKey = (sphincs_key*)key;
  26976. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26977. sphincsKey = (sphincs_key*)key;
  26978. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26979. sphincsKey = (sphincs_key*)key;
  26980. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26981. sphincsKey = (sphincs_key*)key;
  26982. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26983. sphincsKey = (sphincs_key*)key;
  26984. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  26985. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  26986. }
  26987. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  26988. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  26989. {
  26990. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  26991. NULL, NULL, NULL, rng);
  26992. }
  26993. WOLFSSL_ABI
  26994. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  26995. RsaKey* key, WC_RNG* rng)
  26996. {
  26997. int ret;
  26998. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  26999. if (ret < 0)
  27000. return ret;
  27001. return wc_SignCert(cert->bodySz, cert->sigType,
  27002. buf, buffSz, key, NULL, rng);
  27003. }
  27004. #ifdef WOLFSSL_CERT_EXT
  27005. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  27006. The raw subject pointer will only be valid while "cert" is valid. */
  27007. WOLFSSL_ABI
  27008. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  27009. {
  27010. int rc = BAD_FUNC_ARG;
  27011. if ((subjectRaw != NULL) && (cert != NULL)) {
  27012. *subjectRaw = cert->sbjRaw;
  27013. rc = 0;
  27014. }
  27015. return rc;
  27016. }
  27017. /* Set KID from public key */
  27018. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27019. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27020. falcon_key* falconKey,
  27021. dilithium_key* dilithiumKey,
  27022. sphincs_key *sphincsKey, int kid_type)
  27023. {
  27024. byte *buf;
  27025. int bufferSz, ret;
  27026. if (cert == NULL ||
  27027. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27028. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27029. sphincsKey == NULL) ||
  27030. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27031. return BAD_FUNC_ARG;
  27032. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27033. DYNAMIC_TYPE_TMP_BUFFER);
  27034. if (buf == NULL)
  27035. return MEMORY_E;
  27036. /* Public Key */
  27037. bufferSz = -1;
  27038. #ifndef NO_RSA
  27039. /* RSA public key */
  27040. if (rsakey != NULL)
  27041. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27042. #endif
  27043. #ifdef HAVE_ECC
  27044. /* ECC public key */
  27045. if (eckey != NULL)
  27046. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27047. #endif
  27048. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27049. /* ED25519 public key */
  27050. if (ed25519Key != NULL) {
  27051. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27052. }
  27053. #endif
  27054. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27055. /* ED448 public key */
  27056. if (ed448Key != NULL) {
  27057. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27058. }
  27059. #endif
  27060. #if defined(HAVE_PQC)
  27061. #if defined(HAVE_FALCON)
  27062. if (falconKey != NULL) {
  27063. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27064. 0);
  27065. }
  27066. #endif
  27067. #if defined(HAVE_DILITHIUM)
  27068. if (dilithiumKey != NULL) {
  27069. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27070. MAX_PUBLIC_KEY_SZ, 0);
  27071. }
  27072. #endif
  27073. #if defined(HAVE_SPHINCS)
  27074. if (sphincsKey != NULL) {
  27075. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27076. MAX_PUBLIC_KEY_SZ, 0);
  27077. }
  27078. #endif
  27079. #endif /* HAVE_PQC */
  27080. if (bufferSz <= 0) {
  27081. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27082. return PUBLIC_KEY_E;
  27083. }
  27084. /* Compute SKID by hashing public key */
  27085. if (kid_type == SKID_TYPE) {
  27086. ret = CalcHashId(buf, (word32)bufferSz, cert->skid);
  27087. cert->skidSz = KEYID_SIZE;
  27088. }
  27089. else if (kid_type == AKID_TYPE) {
  27090. ret = CalcHashId(buf, (word32)bufferSz, cert->akid);
  27091. cert->akidSz = KEYID_SIZE;
  27092. }
  27093. else
  27094. ret = BAD_FUNC_ARG;
  27095. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27096. return ret;
  27097. }
  27098. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27099. {
  27100. RsaKey* rsaKey = NULL;
  27101. ecc_key* eccKey = NULL;
  27102. ed25519_key* ed25519Key = NULL;
  27103. ed448_key* ed448Key = NULL;
  27104. falcon_key* falconKey = NULL;
  27105. dilithium_key* dilithiumKey = NULL;
  27106. sphincs_key* sphincsKey = NULL;
  27107. if (keyType == RSA_TYPE)
  27108. rsaKey = (RsaKey*)key;
  27109. else if (keyType == ECC_TYPE)
  27110. eccKey = (ecc_key*)key;
  27111. else if (keyType == ED25519_TYPE)
  27112. ed25519Key = (ed25519_key*)key;
  27113. else if (keyType == ED448_TYPE)
  27114. ed448Key = (ed448_key*)key;
  27115. else if (keyType == FALCON_LEVEL1_TYPE)
  27116. falconKey = (falcon_key*)key;
  27117. else if (keyType == FALCON_LEVEL5_TYPE)
  27118. falconKey = (falcon_key*)key;
  27119. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27120. dilithiumKey = (dilithium_key*)key;
  27121. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27122. dilithiumKey = (dilithium_key*)key;
  27123. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27124. dilithiumKey = (dilithium_key*)key;
  27125. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27126. sphincsKey = (sphincs_key*)key;
  27127. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27128. sphincsKey = (sphincs_key*)key;
  27129. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27130. sphincsKey = (sphincs_key*)key;
  27131. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27132. sphincsKey = (sphincs_key*)key;
  27133. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27134. sphincsKey = (sphincs_key*)key;
  27135. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27136. sphincsKey = (sphincs_key*)key;
  27137. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27138. falconKey, dilithiumKey, sphincsKey,
  27139. SKID_TYPE);
  27140. }
  27141. /* Set SKID from RSA or ECC public key */
  27142. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27143. {
  27144. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27145. NULL, SKID_TYPE);
  27146. }
  27147. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27148. {
  27149. RsaKey* rsaKey = NULL;
  27150. ecc_key* eccKey = NULL;
  27151. ed25519_key* ed25519Key = NULL;
  27152. ed448_key* ed448Key = NULL;
  27153. falcon_key* falconKey = NULL;
  27154. dilithium_key* dilithiumKey = NULL;
  27155. sphincs_key* sphincsKey = NULL;
  27156. if (keyType == RSA_TYPE)
  27157. rsaKey = (RsaKey*)key;
  27158. else if (keyType == ECC_TYPE)
  27159. eccKey = (ecc_key*)key;
  27160. else if (keyType == ED25519_TYPE)
  27161. ed25519Key = (ed25519_key*)key;
  27162. else if (keyType == ED448_TYPE)
  27163. ed448Key = (ed448_key*)key;
  27164. else if (keyType == FALCON_LEVEL1_TYPE)
  27165. falconKey = (falcon_key*)key;
  27166. else if (keyType == FALCON_LEVEL5_TYPE)
  27167. falconKey = (falcon_key*)key;
  27168. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27169. dilithiumKey = (dilithium_key*)key;
  27170. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27171. dilithiumKey = (dilithium_key*)key;
  27172. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27173. dilithiumKey = (dilithium_key*)key;
  27174. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27175. sphincsKey = (sphincs_key*)key;
  27176. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27177. sphincsKey = (sphincs_key*)key;
  27178. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27179. sphincsKey = (sphincs_key*)key;
  27180. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27181. sphincsKey = (sphincs_key*)key;
  27182. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27183. sphincsKey = (sphincs_key*)key;
  27184. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27185. sphincsKey = (sphincs_key*)key;
  27186. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27187. falconKey, dilithiumKey, sphincsKey,
  27188. AKID_TYPE);
  27189. }
  27190. /* Set SKID from RSA or ECC public key */
  27191. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27192. {
  27193. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27194. NULL, AKID_TYPE);
  27195. }
  27196. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27197. /* Set SKID from public key file in PEM */
  27198. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27199. {
  27200. int ret, derSz;
  27201. byte* der;
  27202. word32 idx;
  27203. RsaKey *rsakey = NULL;
  27204. ecc_key *eckey = NULL;
  27205. if (cert == NULL || file == NULL)
  27206. return BAD_FUNC_ARG;
  27207. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27208. if (der == NULL) {
  27209. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27210. return MEMORY_E;
  27211. }
  27212. derSz = MAX_PUBLIC_KEY_SZ;
  27213. XMEMSET(der, 0, (size_t)derSz);
  27214. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27215. if (derSz <= 0) {
  27216. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27217. return derSz;
  27218. }
  27219. /* Load PubKey in internal structure */
  27220. #ifndef NO_RSA
  27221. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27222. if (rsakey == NULL) {
  27223. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27224. return MEMORY_E;
  27225. }
  27226. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27227. WOLFSSL_MSG("wc_InitRsaKey failure");
  27228. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27229. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27230. return MEMORY_E;
  27231. }
  27232. idx = 0;
  27233. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  27234. if (ret != 0)
  27235. #endif
  27236. {
  27237. #ifndef NO_RSA
  27238. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27239. wc_FreeRsaKey(rsakey);
  27240. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27241. rsakey = NULL;
  27242. #endif
  27243. #ifdef HAVE_ECC
  27244. /* Check to load ecc public key */
  27245. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27246. DYNAMIC_TYPE_ECC);
  27247. if (eckey == NULL) {
  27248. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27249. return MEMORY_E;
  27250. }
  27251. if (wc_ecc_init(eckey) != 0) {
  27252. WOLFSSL_MSG("wc_ecc_init failure");
  27253. wc_ecc_free(eckey);
  27254. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27255. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27256. return MEMORY_E;
  27257. }
  27258. idx = 0;
  27259. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  27260. if (ret != 0) {
  27261. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27262. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27263. wc_ecc_free(eckey);
  27264. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27265. return PUBLIC_KEY_E;
  27266. }
  27267. #else
  27268. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27269. return PUBLIC_KEY_E;
  27270. #endif /* HAVE_ECC */
  27271. }
  27272. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27273. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27274. #ifndef NO_RSA
  27275. wc_FreeRsaKey(rsakey);
  27276. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27277. #endif
  27278. #ifdef HAVE_ECC
  27279. wc_ecc_free(eckey);
  27280. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27281. #endif
  27282. return ret;
  27283. }
  27284. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27285. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27286. {
  27287. int ret = 0;
  27288. /* Subject Key Id not found !! */
  27289. if (decoded->extSubjKeyIdSet == 0) {
  27290. ret = ASN_NO_SKID;
  27291. }
  27292. /* SKID invalid size */
  27293. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27294. ret = MEMORY_E;
  27295. }
  27296. else {
  27297. /* Put the SKID of CA to AKID of certificate */
  27298. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  27299. cert->akidSz = KEYID_SIZE;
  27300. }
  27301. return ret;
  27302. }
  27303. /* Set AKID from certificate contains in buffer (DER encoded) */
  27304. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  27305. {
  27306. int ret = 0;
  27307. if (cert == NULL) {
  27308. ret = BAD_FUNC_ARG;
  27309. }
  27310. else {
  27311. /* Check if decodedCert is cached */
  27312. if (cert->der != der) {
  27313. /* Allocate cache for the decoded cert */
  27314. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27315. }
  27316. if (ret >= 0) {
  27317. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27318. #ifndef WOLFSSL_CERT_GEN_CACHE
  27319. wc_SetCert_Free(cert);
  27320. #endif
  27321. }
  27322. }
  27323. return ret;
  27324. }
  27325. #ifndef NO_FILESYSTEM
  27326. /* Set AKID from certificate file in PEM */
  27327. int wc_SetAuthKeyId(Cert *cert, const char* file)
  27328. {
  27329. int ret;
  27330. DerBuffer* der = NULL;
  27331. if (cert == NULL || file == NULL)
  27332. return BAD_FUNC_ARG;
  27333. ret = wc_PemCertToDer_ex(file, &der);
  27334. if (ret == 0)
  27335. {
  27336. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  27337. FreeDer(&der);
  27338. }
  27339. return ret;
  27340. }
  27341. #endif /* !NO_FILESYSTEM */
  27342. /* Set KeyUsage from human readable string */
  27343. int wc_SetKeyUsage(Cert *cert, const char *value)
  27344. {
  27345. int ret = 0;
  27346. char *token, *str, *ptr;
  27347. word32 len;
  27348. if (cert == NULL || value == NULL)
  27349. return BAD_FUNC_ARG;
  27350. cert->keyUsage = 0;
  27351. /* duplicate string (including terminator) */
  27352. len = (word32)XSTRLEN(value);
  27353. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27354. if (str == NULL)
  27355. return MEMORY_E;
  27356. XMEMCPY(str, value, len+1);
  27357. /* parse value, and set corresponding Key Usage value */
  27358. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27359. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27360. return KEYUSAGE_E;
  27361. }
  27362. while (token != NULL)
  27363. {
  27364. if (!XSTRCASECMP(token, "digitalSignature"))
  27365. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  27366. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  27367. !XSTRCASECMP(token, "contentCommitment"))
  27368. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  27369. else if (!XSTRCASECMP(token, "keyEncipherment"))
  27370. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  27371. else if (!XSTRCASECMP(token, "dataEncipherment"))
  27372. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  27373. else if (!XSTRCASECMP(token, "keyAgreement"))
  27374. cert->keyUsage |= KEYUSE_KEY_AGREE;
  27375. else if (!XSTRCASECMP(token, "keyCertSign"))
  27376. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  27377. else if (!XSTRCASECMP(token, "cRLSign"))
  27378. cert->keyUsage |= KEYUSE_CRL_SIGN;
  27379. else if (!XSTRCASECMP(token, "encipherOnly"))
  27380. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  27381. else if (!XSTRCASECMP(token, "decipherOnly"))
  27382. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  27383. else {
  27384. ret = KEYUSAGE_E;
  27385. break;
  27386. }
  27387. token = XSTRTOK(NULL, ",", &ptr);
  27388. }
  27389. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27390. return ret;
  27391. }
  27392. /* Set ExtendedKeyUsage from human readable string */
  27393. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  27394. {
  27395. int ret = 0;
  27396. char *token, *str, *ptr;
  27397. word32 len;
  27398. if (cert == NULL || value == NULL)
  27399. return BAD_FUNC_ARG;
  27400. cert->extKeyUsage = 0;
  27401. /* duplicate string (including terminator) */
  27402. len = (word32)XSTRLEN(value);
  27403. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27404. if (str == NULL)
  27405. return MEMORY_E;
  27406. XMEMCPY(str, value, len+1);
  27407. /* parse value, and set corresponding Key Usage value */
  27408. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27409. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27410. return EXTKEYUSAGE_E;
  27411. }
  27412. while (token != NULL)
  27413. {
  27414. if (!XSTRCASECMP(token, "any"))
  27415. cert->extKeyUsage |= EXTKEYUSE_ANY;
  27416. else if (!XSTRCASECMP(token, "serverAuth"))
  27417. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  27418. else if (!XSTRCASECMP(token, "clientAuth"))
  27419. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  27420. else if (!XSTRCASECMP(token, "codeSigning"))
  27421. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  27422. else if (!XSTRCASECMP(token, "emailProtection"))
  27423. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  27424. else if (!XSTRCASECMP(token, "timeStamping"))
  27425. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  27426. else if (!XSTRCASECMP(token, "OCSPSigning"))
  27427. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  27428. else {
  27429. ret = EXTKEYUSAGE_E;
  27430. break;
  27431. }
  27432. token = XSTRTOK(NULL, ",", &ptr);
  27433. }
  27434. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27435. return ret;
  27436. }
  27437. #ifdef WOLFSSL_EKU_OID
  27438. /*
  27439. * cert structure to set EKU oid in
  27440. * oid the oid in byte representation
  27441. * sz size of oid buffer
  27442. * idx index of array to place oid
  27443. *
  27444. * returns 0 on success
  27445. */
  27446. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  27447. void* heap)
  27448. {
  27449. byte oid[MAX_OID_SZ];
  27450. word32 oidSz = MAX_OID_SZ;
  27451. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  27452. WOLFSSL_MSG("Either idx or sz was too large");
  27453. return BAD_FUNC_ARG;
  27454. }
  27455. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  27456. return BUFFER_E;
  27457. }
  27458. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  27459. cert->extKeyUsageOIDSz[idx] = oidSz;
  27460. cert->extKeyUsage |= EXTKEYUSE_USER;
  27461. return 0;
  27462. }
  27463. #endif /* WOLFSSL_EKU_OID */
  27464. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  27465. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  27466. defined(WOLFSSL_CERT_EXT)
  27467. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  27468. const byte *der, word32 derSz) {
  27469. CertExtension *ext;
  27470. byte encodedOid[MAX_OID_SZ];
  27471. word32 encodedOidSz = MAX_OID_SZ;
  27472. int ret;
  27473. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  27474. return BAD_FUNC_ARG;
  27475. }
  27476. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  27477. return MEMORY_E;
  27478. }
  27479. /* Make sure we can properly parse the OID. */
  27480. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  27481. if (ret != 0) {
  27482. return ret;
  27483. }
  27484. ext = &cert->customCertExt[cert->customCertExtCount];
  27485. ext->oid = oid;
  27486. ext->crit = (critical == 0) ? 0 : 1;
  27487. ext->val = der;
  27488. ext->valSz = derSz;
  27489. cert->customCertExtCount++;
  27490. return 0;
  27491. }
  27492. #endif
  27493. #endif /* WOLFSSL_CERT_EXT */
  27494. #ifdef WOLFSSL_ALT_NAMES
  27495. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  27496. {
  27497. int ret = 0;
  27498. cert->altNamesSz = 0;
  27499. if (decoded->altNames) {
  27500. ret = FlattenAltNames(cert->altNames,
  27501. sizeof(cert->altNames), decoded->altNames);
  27502. if (ret >= 0) {
  27503. cert->altNamesSz = ret;
  27504. ret = 0;
  27505. }
  27506. }
  27507. return ret;
  27508. }
  27509. #ifndef NO_FILESYSTEM
  27510. /* Set Alt Names from der cert, return 0 on success */
  27511. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  27512. int devId)
  27513. {
  27514. int ret;
  27515. #ifdef WOLFSSL_SMALL_STACK
  27516. DecodedCert* decoded;
  27517. #else
  27518. DecodedCert decoded[1];
  27519. #endif
  27520. if (derSz < 0)
  27521. return derSz;
  27522. #ifdef WOLFSSL_SMALL_STACK
  27523. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  27524. DYNAMIC_TYPE_TMP_BUFFER);
  27525. if (decoded == NULL)
  27526. return MEMORY_E;
  27527. #endif
  27528. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27529. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27530. if (ret < 0) {
  27531. WOLFSSL_MSG("ParseCertRelative error");
  27532. }
  27533. else {
  27534. ret = SetAltNamesFromDcert(cert, decoded);
  27535. }
  27536. FreeDecodedCert(decoded);
  27537. #ifdef WOLFSSL_SMALL_STACK
  27538. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27539. #endif
  27540. return ret < 0 ? ret : 0;
  27541. }
  27542. #endif
  27543. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  27544. {
  27545. int ret = 0;
  27546. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  27547. WOLFSSL_MSG("Couldn't extract dates");
  27548. ret = -1;
  27549. }
  27550. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  27551. decoded->afterDateLen > MAX_DATE_SIZE) {
  27552. WOLFSSL_MSG("Bad date size");
  27553. ret = -1;
  27554. }
  27555. else {
  27556. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  27557. (size_t)decoded->beforeDateLen);
  27558. XMEMCPY(cert->afterDate, decoded->afterDate,
  27559. (size_t)decoded->afterDateLen);
  27560. cert->beforeDateSz = decoded->beforeDateLen;
  27561. cert->afterDateSz = decoded->afterDateLen;
  27562. }
  27563. return ret;
  27564. }
  27565. #endif /* WOLFSSL_ALT_NAMES */
  27566. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  27567. {
  27568. int sz;
  27569. if (decoded->subjectCN) {
  27570. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  27571. : CTC_NAME_SIZE - 1;
  27572. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  27573. cn->commonName[sz] = '\0';
  27574. cn->commonNameEnc = decoded->subjectCNEnc;
  27575. }
  27576. if (decoded->subjectC) {
  27577. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  27578. : CTC_NAME_SIZE - 1;
  27579. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  27580. cn->country[sz] = '\0';
  27581. cn->countryEnc = decoded->subjectCEnc;
  27582. }
  27583. if (decoded->subjectST) {
  27584. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  27585. : CTC_NAME_SIZE - 1;
  27586. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  27587. cn->state[sz] = '\0';
  27588. cn->stateEnc = decoded->subjectSTEnc;
  27589. }
  27590. if (decoded->subjectL) {
  27591. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  27592. : CTC_NAME_SIZE - 1;
  27593. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  27594. cn->locality[sz] = '\0';
  27595. cn->localityEnc = decoded->subjectLEnc;
  27596. }
  27597. if (decoded->subjectO) {
  27598. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  27599. : CTC_NAME_SIZE - 1;
  27600. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  27601. cn->org[sz] = '\0';
  27602. cn->orgEnc = decoded->subjectOEnc;
  27603. }
  27604. if (decoded->subjectOU) {
  27605. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  27606. : CTC_NAME_SIZE - 1;
  27607. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  27608. cn->unit[sz] = '\0';
  27609. cn->unitEnc = decoded->subjectOUEnc;
  27610. }
  27611. if (decoded->subjectSN) {
  27612. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  27613. : CTC_NAME_SIZE - 1;
  27614. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  27615. cn->sur[sz] = '\0';
  27616. cn->surEnc = decoded->subjectSNEnc;
  27617. }
  27618. if (decoded->subjectSND) {
  27619. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  27620. : CTC_NAME_SIZE - 1;
  27621. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  27622. cn->serialDev[sz] = '\0';
  27623. cn->serialDevEnc = decoded->subjectSNDEnc;
  27624. }
  27625. if (decoded->subjectUID) {
  27626. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  27627. : CTC_NAME_SIZE - 1;
  27628. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  27629. cn->userId[sz] = '\0';
  27630. cn->userIdEnc = decoded->subjectUIDEnc;
  27631. }
  27632. #ifdef WOLFSSL_CERT_EXT
  27633. if (decoded->subjectBC) {
  27634. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  27635. : CTC_NAME_SIZE - 1;
  27636. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  27637. cn->busCat[sz] = '\0';
  27638. cn->busCatEnc = decoded->subjectBCEnc;
  27639. }
  27640. if (decoded->subjectJC) {
  27641. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  27642. : CTC_NAME_SIZE - 1;
  27643. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  27644. cn->joiC[sz] = '\0';
  27645. cn->joiCEnc = decoded->subjectJCEnc;
  27646. }
  27647. if (decoded->subjectJS) {
  27648. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  27649. : CTC_NAME_SIZE - 1;
  27650. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  27651. cn->joiSt[sz] = '\0';
  27652. cn->joiStEnc = decoded->subjectJSEnc;
  27653. }
  27654. #endif
  27655. if (decoded->subjectEmail) {
  27656. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  27657. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  27658. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  27659. cn->email[sz] = '\0';
  27660. }
  27661. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  27662. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  27663. if (decoded->subjectN) {
  27664. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  27665. : CTC_NAME_SIZE - 1;
  27666. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  27667. cn->dnName[sz] = '\0';
  27668. cn->dnNameEnc = decoded->subjectNEnc;
  27669. }
  27670. if (decoded->subjectI) {
  27671. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  27672. : CTC_NAME_SIZE - 1;
  27673. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  27674. cn->initials[sz] = '\0';
  27675. cn->initialsEnc = decoded->subjectIEnc;
  27676. }
  27677. if (decoded->subjectGN) {
  27678. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  27679. : CTC_NAME_SIZE - 1;
  27680. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  27681. cn->givenName[sz] = '\0';
  27682. cn->givenNameEnc = decoded->subjectGNEnc;
  27683. }
  27684. if (decoded->subjectDNQ) {
  27685. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  27686. : CTC_NAME_SIZE - 1;
  27687. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  27688. cn->dnQualifier[sz] = '\0';
  27689. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  27690. }
  27691. #endif /* WOLFSSL_CERT_NAME_ALL */
  27692. }
  27693. #ifndef NO_FILESYSTEM
  27694. /* Set cn name from der buffer, return 0 on success */
  27695. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  27696. {
  27697. int ret;
  27698. #ifdef WOLFSSL_SMALL_STACK
  27699. DecodedCert* decoded;
  27700. #else
  27701. DecodedCert decoded[1];
  27702. #endif
  27703. if (derSz < 0)
  27704. return derSz;
  27705. #ifdef WOLFSSL_SMALL_STACK
  27706. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  27707. DYNAMIC_TYPE_TMP_BUFFER);
  27708. if (decoded == NULL)
  27709. return MEMORY_E;
  27710. #endif
  27711. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27712. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27713. if (ret < 0) {
  27714. WOLFSSL_MSG("ParseCertRelative error");
  27715. }
  27716. else {
  27717. SetNameFromDcert(cn, decoded);
  27718. }
  27719. FreeDecodedCert(decoded);
  27720. #ifdef WOLFSSL_SMALL_STACK
  27721. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  27722. #endif
  27723. return ret < 0 ? ret : 0;
  27724. }
  27725. /* Set cert issuer from issuerFile in PEM */
  27726. WOLFSSL_ABI
  27727. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  27728. {
  27729. int ret;
  27730. DerBuffer* der = NULL;
  27731. if (cert == NULL || issuerFile == NULL)
  27732. return BAD_FUNC_ARG;
  27733. ret = wc_PemCertToDer_ex(issuerFile, &der);
  27734. if (ret == 0) {
  27735. cert->selfSigned = 0;
  27736. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  27737. INVALID_DEVID);
  27738. FreeDer(&der);
  27739. }
  27740. return ret;
  27741. }
  27742. /* Set cert subject from subjectFile in PEM */
  27743. WOLFSSL_ABI
  27744. int wc_SetSubject(Cert* cert, const char* subjectFile)
  27745. {
  27746. int ret;
  27747. DerBuffer* der = NULL;
  27748. if (cert == NULL || subjectFile == NULL)
  27749. return BAD_FUNC_ARG;
  27750. ret = wc_PemCertToDer_ex(subjectFile, &der);
  27751. if (ret == 0) {
  27752. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  27753. INVALID_DEVID);
  27754. FreeDer(&der);
  27755. }
  27756. return ret;
  27757. }
  27758. #ifdef WOLFSSL_ALT_NAMES
  27759. /* Set alt names from file in PEM */
  27760. WOLFSSL_ABI
  27761. int wc_SetAltNames(Cert* cert, const char* file)
  27762. {
  27763. int ret;
  27764. DerBuffer* der = NULL;
  27765. if (cert == NULL) {
  27766. return BAD_FUNC_ARG;
  27767. }
  27768. ret = wc_PemCertToDer_ex(file, &der);
  27769. if (ret == 0) {
  27770. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  27771. INVALID_DEVID);
  27772. FreeDer(&der);
  27773. }
  27774. return ret;
  27775. }
  27776. #endif /* WOLFSSL_ALT_NAMES */
  27777. #endif /* !NO_FILESYSTEM */
  27778. /* Set cert issuer from DER buffer */
  27779. WOLFSSL_ABI
  27780. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  27781. {
  27782. int ret = 0;
  27783. if (cert == NULL) {
  27784. ret = BAD_FUNC_ARG;
  27785. }
  27786. else {
  27787. cert->selfSigned = 0;
  27788. /* Check if decodedCert is cached */
  27789. if (cert->der != der) {
  27790. /* Allocate cache for the decoded cert */
  27791. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27792. }
  27793. if (ret >= 0) {
  27794. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  27795. #ifndef WOLFSSL_CERT_GEN_CACHE
  27796. wc_SetCert_Free(cert);
  27797. #endif
  27798. }
  27799. }
  27800. return ret;
  27801. }
  27802. /* Set cert subject from DER buffer */
  27803. WOLFSSL_ABI
  27804. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  27805. {
  27806. int ret = 0;
  27807. if (cert == NULL) {
  27808. ret = BAD_FUNC_ARG;
  27809. }
  27810. else {
  27811. /* Check if decodedCert is cached */
  27812. if (cert->der != der) {
  27813. /* Allocate cache for the decoded cert */
  27814. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27815. }
  27816. if (ret >= 0) {
  27817. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  27818. #ifndef WOLFSSL_CERT_GEN_CACHE
  27819. wc_SetCert_Free(cert);
  27820. #endif
  27821. }
  27822. }
  27823. return ret;
  27824. }
  27825. #ifdef WOLFSSL_CERT_EXT
  27826. /* Set cert raw subject from DER buffer */
  27827. WOLFSSL_ABI
  27828. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  27829. {
  27830. int ret = 0;
  27831. if (cert == NULL) {
  27832. ret = BAD_FUNC_ARG;
  27833. }
  27834. else {
  27835. /* Check if decodedCert is cached */
  27836. if (cert->der != der) {
  27837. /* Allocate cache for the decoded cert */
  27838. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27839. }
  27840. if (ret >= 0) {
  27841. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27842. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27843. (int)sizeof(CertName))) {
  27844. XMEMCPY(cert->sbjRaw,
  27845. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27846. (size_t)((DecodedCert*)cert->decodedCert)->
  27847. subjectRawLen);
  27848. }
  27849. #ifndef WOLFSSL_CERT_GEN_CACHE
  27850. wc_SetCert_Free(cert);
  27851. #endif
  27852. }
  27853. }
  27854. return ret;
  27855. }
  27856. /* Set cert raw issuer from DER buffer */
  27857. WOLFSSL_ABI
  27858. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  27859. {
  27860. int ret = 0;
  27861. if (cert == NULL) {
  27862. ret = BAD_FUNC_ARG;
  27863. }
  27864. else {
  27865. /* Check if decodedCert is cached */
  27866. if (cert->der != der) {
  27867. /* Allocate cache for the decoded cert */
  27868. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27869. }
  27870. if (ret >= 0) {
  27871. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  27872. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  27873. (int)sizeof(CertName))) {
  27874. /* Copy the subject to the issuer field */
  27875. XMEMCPY(cert->issRaw,
  27876. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  27877. (size_t)((DecodedCert*)cert->decodedCert)->
  27878. subjectRawLen);
  27879. }
  27880. #ifndef WOLFSSL_CERT_GEN_CACHE
  27881. wc_SetCert_Free(cert);
  27882. #endif
  27883. }
  27884. }
  27885. return ret;
  27886. }
  27887. #endif
  27888. #ifdef WOLFSSL_ALT_NAMES
  27889. /* Set cert alt names from DER buffer */
  27890. WOLFSSL_ABI
  27891. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  27892. {
  27893. int ret = 0;
  27894. if (cert == NULL) {
  27895. ret = BAD_FUNC_ARG;
  27896. }
  27897. else {
  27898. /* Check if decodedCert is cached */
  27899. if (cert->der != der) {
  27900. /* Allocate cache for the decoded cert */
  27901. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27902. }
  27903. if (ret >= 0) {
  27904. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27905. #ifndef WOLFSSL_CERT_GEN_CACHE
  27906. wc_SetCert_Free(cert);
  27907. #endif
  27908. }
  27909. }
  27910. return(ret);
  27911. }
  27912. /* Set cert dates from DER buffer */
  27913. WOLFSSL_ABI
  27914. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  27915. {
  27916. int ret = 0;
  27917. if (cert == NULL) {
  27918. ret = BAD_FUNC_ARG;
  27919. }
  27920. else {
  27921. /* Check if decodedCert is cached */
  27922. if (cert->der != der) {
  27923. /* Allocate cache for the decoded cert */
  27924. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27925. }
  27926. if (ret >= 0) {
  27927. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27928. #ifndef WOLFSSL_CERT_GEN_CACHE
  27929. wc_SetCert_Free(cert);
  27930. #endif
  27931. }
  27932. }
  27933. return(ret);
  27934. }
  27935. #endif /* WOLFSSL_ALT_NAMES */
  27936. #endif /* WOLFSSL_CERT_GEN */
  27937. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  27938. || defined(OPENSSL_EXTRA)
  27939. /* Encode OID string representation to ITU-T X.690 format */
  27940. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  27941. {
  27942. word32 idx = 0, nb_val;
  27943. char *token, *str, *ptr;
  27944. word32 len;
  27945. (void)heap;
  27946. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  27947. return BAD_FUNC_ARG;
  27948. /* duplicate string (including terminator) */
  27949. len = (word32)XSTRLEN(in);
  27950. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27951. if (str == NULL)
  27952. return MEMORY_E;
  27953. XMEMCPY(str, in, len+1);
  27954. nb_val = 0;
  27955. /* parse value, and set corresponding Policy OID value */
  27956. token = XSTRTOK(str, ".", &ptr);
  27957. while (token != NULL)
  27958. {
  27959. word32 val = (word32)XATOI(token);
  27960. if (nb_val == 0) {
  27961. if (val > 2) {
  27962. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27963. return ASN_OBJECT_ID_E;
  27964. }
  27965. out[idx] = (byte)(40 * val);
  27966. }
  27967. else if (nb_val == 1) {
  27968. if (val > 127) {
  27969. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27970. return ASN_OBJECT_ID_E;
  27971. }
  27972. if (idx > *outSz) {
  27973. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27974. return BUFFER_E;
  27975. }
  27976. out[idx++] += (byte)val;
  27977. }
  27978. else {
  27979. word32 tb = 0;
  27980. int i = 0;
  27981. byte oid[MAX_OID_SZ];
  27982. while (val >= 128) {
  27983. word32 x = val % 128;
  27984. val /= 128;
  27985. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  27986. }
  27987. if ((idx+(word32)i) >= *outSz) {
  27988. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27989. return BUFFER_E;
  27990. }
  27991. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  27992. /* push value in the right order */
  27993. while (i >= 0)
  27994. out[idx++] = oid[i--];
  27995. }
  27996. token = XSTRTOK(NULL, ".", &ptr);
  27997. nb_val++;
  27998. }
  27999. *outSz = idx;
  28000. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28001. return 0;
  28002. }
  28003. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  28004. #endif /* !NO_CERTS */
  28005. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  28006. /* Helper function for wolfSSL_i2d_DHparams */
  28007. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  28008. {
  28009. #ifndef WOLFSSL_ASN_TEMPLATE
  28010. word32 idx = 0;
  28011. word32 total;
  28012. WOLFSSL_ENTER("StoreDHparams");
  28013. if (out == NULL) {
  28014. WOLFSSL_MSG("Null buffer error");
  28015. return BUFFER_E;
  28016. }
  28017. /* determine size */
  28018. /* integer - g */
  28019. idx = SetASNIntMP(g, -1, NULL);
  28020. /* integer - p */
  28021. idx += SetASNIntMP(p, -1, NULL);
  28022. total = idx;
  28023. /* sequence */
  28024. idx += SetSequence(idx, NULL);
  28025. /* make sure output fits in buffer */
  28026. if (idx > *outLen) {
  28027. return BUFFER_E;
  28028. }
  28029. /* write DH parameters */
  28030. /* sequence - for P and G only */
  28031. idx = SetSequence(total, out);
  28032. /* integer - p */
  28033. idx += SetASNIntMP(p, -1, out + idx);
  28034. /* integer - g */
  28035. idx += SetASNIntMP(g, -1, out + idx);
  28036. *outLen = idx;
  28037. return 0;
  28038. #else
  28039. ASNSetData dataASN[dhParamASN_Length];
  28040. int ret = 0;
  28041. int sz = 0;
  28042. WOLFSSL_ENTER("StoreDHparams");
  28043. if (out == NULL) {
  28044. ret = BUFFER_E;
  28045. }
  28046. if (ret == 0) {
  28047. XMEMSET(dataASN, 0, sizeof(dataASN));
  28048. /* Set mp_int containing p and g. */
  28049. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28050. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28051. /* privateValueLength not encoded. */
  28052. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28053. /* Calculate the size of the DH parameters. */
  28054. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28055. }
  28056. /* Check buffer is big enough for encoding. */
  28057. if ((ret == 0) && ((int)*outLen < sz)) {
  28058. ret = BUFFER_E;
  28059. }
  28060. if (ret == 0) {
  28061. /* Encode the DH parameters into buffer. */
  28062. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28063. /* Set the actual encoding size. */
  28064. *outLen = sz;
  28065. }
  28066. return ret;
  28067. #endif /* WOLFSSL_ASN_TEMPLATE */
  28068. }
  28069. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28070. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28071. #ifdef WOLFSSL_ASN_TEMPLATE
  28072. /* ASN.1 template for DSA signature.
  28073. * RFC 5912, 6 - DSA-Sig-Value
  28074. */
  28075. static const ASNItem dsaSigASN[] = {
  28076. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28077. /* r */
  28078. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28079. /* s */
  28080. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28081. };
  28082. enum {
  28083. DSASIGASN_IDX_SEQ = 0,
  28084. DSASIGASN_IDX_R,
  28085. DSASIGASN_IDX_S
  28086. };
  28087. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28088. #endif
  28089. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28090. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28091. {
  28092. #ifndef WOLFSSL_ASN_TEMPLATE
  28093. word32 idx = 0;
  28094. int rSz; /* encoding size */
  28095. int sSz;
  28096. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28097. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28098. int rLeadingZero = mp_leading_bit(r);
  28099. int sLeadingZero = mp_leading_bit(s);
  28100. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28101. int sLen = mp_unsigned_bin_size(s);
  28102. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  28103. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  28104. return BUFFER_E;
  28105. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  28106. headerSz), out);
  28107. /* store r */
  28108. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  28109. if (rSz < 0)
  28110. return rSz;
  28111. idx += (word32)rSz;
  28112. /* store s */
  28113. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  28114. if (sSz < 0)
  28115. return sSz;
  28116. idx += (word32)sSz;
  28117. *outLen = idx;
  28118. return 0;
  28119. #else
  28120. ASNSetData dataASN[dsaSigASN_Length];
  28121. int ret;
  28122. int sz;
  28123. /* Clear dynamic data and set mp_ints r and s */
  28124. XMEMSET(dataASN, 0, sizeof(dataASN));
  28125. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28126. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28127. /* Calculate size of encoding. */
  28128. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28129. /* Check buffer is big enough for encoding. */
  28130. if ((ret == 0) && ((int)*outLen < sz)) {
  28131. ret = BUFFER_E;
  28132. }
  28133. if (ret == 0) {
  28134. /* Encode DSA signature into buffer. */
  28135. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28136. /* Set the actual encoding size. */
  28137. *outLen = (word32)sz;
  28138. }
  28139. return ret;
  28140. #endif /* WOLFSSL_ASN_TEMPLATE */
  28141. }
  28142. #ifndef WOLFSSL_ASN_TEMPLATE
  28143. /* determine if leading bit is set */
  28144. static word32 is_leading_bit_set(const byte* input, word32 sz)
  28145. {
  28146. byte c = 0;
  28147. if (sz > 0)
  28148. c = input[0];
  28149. return (c & 0x80) != 0;
  28150. }
  28151. static word32 trim_leading_zeros(const byte** input, word32 sz)
  28152. {
  28153. int i;
  28154. word32 leadingZeroCount = 0;
  28155. const byte* tmp = *input;
  28156. for (i=0; i<(int)sz; i++) {
  28157. if (tmp[i] != 0)
  28158. break;
  28159. leadingZeroCount++;
  28160. }
  28161. /* catch all zero case */
  28162. if (sz > 0 && leadingZeroCount == sz) {
  28163. leadingZeroCount--;
  28164. }
  28165. *input += leadingZeroCount;
  28166. sz -= leadingZeroCount;
  28167. return sz;
  28168. }
  28169. #endif
  28170. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28171. /* All input/outputs are assumed to be big-endian */
  28172. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28173. const byte* s, word32 sLen)
  28174. {
  28175. #ifndef WOLFSSL_ASN_TEMPLATE
  28176. int ret;
  28177. word32 idx;
  28178. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28179. word32 rAddLeadZero, sAddLeadZero;
  28180. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28181. return BAD_FUNC_ARG;
  28182. /* Trim leading zeros */
  28183. rLen = trim_leading_zeros(&r, rLen);
  28184. sLen = trim_leading_zeros(&s, sLen);
  28185. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28186. /* Add leading zero if MSB is set */
  28187. rAddLeadZero = is_leading_bit_set(r, rLen);
  28188. sAddLeadZero = is_leading_bit_set(s, sLen);
  28189. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28190. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28191. return BUFFER_E;
  28192. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28193. /* store r */
  28194. ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28195. if (ret < 0)
  28196. return ret;
  28197. idx += (word32)ret;
  28198. XMEMCPY(&out[idx], r, rLen);
  28199. idx += rLen;
  28200. /* store s */
  28201. ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28202. if (ret < 0)
  28203. return ret;
  28204. idx += (word32)ret;
  28205. XMEMCPY(&out[idx], s, sLen);
  28206. idx += sLen;
  28207. *outLen = idx;
  28208. return 0;
  28209. #else
  28210. ASNSetData dataASN[dsaSigASN_Length];
  28211. int ret;
  28212. int sz;
  28213. /* Clear dynamic data and set buffers for r and s */
  28214. XMEMSET(dataASN, 0, sizeof(dataASN));
  28215. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28216. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28217. /* Calculate size of encoding. */
  28218. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28219. /* Check buffer is big enough for encoding. */
  28220. if ((ret == 0) && ((int)*outLen < sz)) {
  28221. ret = BUFFER_E;
  28222. }
  28223. if (ret == 0) {
  28224. /* Encode DSA signature into buffer. */
  28225. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28226. /* Set the actual encoding size. */
  28227. *outLen = (word32)sz;
  28228. }
  28229. return ret;
  28230. #endif /* WOLFSSL_ASN_TEMPLATE */
  28231. }
  28232. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28233. /* All input/outputs are assumed to be big-endian */
  28234. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28235. byte* s, word32* sLen)
  28236. {
  28237. #ifndef WOLFSSL_ASN_TEMPLATE
  28238. int ret;
  28239. word32 idx = 0;
  28240. int len = 0;
  28241. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28242. return ASN_ECC_KEY_E;
  28243. }
  28244. #ifndef NO_STRICT_ECDSA_LEN
  28245. /* enable strict length checking for signature */
  28246. if (sigLen != idx + (word32)len) {
  28247. return ASN_ECC_KEY_E;
  28248. }
  28249. #else
  28250. /* allow extra signature bytes at end */
  28251. if ((word32)len > (sigLen - idx)) {
  28252. return ASN_ECC_KEY_E;
  28253. }
  28254. #endif
  28255. ret = GetASNInt(sig, &idx, &len, sigLen);
  28256. if (ret != 0)
  28257. return ret;
  28258. if (rLen)
  28259. *rLen = (word32)len;
  28260. if (r)
  28261. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  28262. idx += (word32)len;
  28263. ret = GetASNInt(sig, &idx, &len, sigLen);
  28264. if (ret != 0)
  28265. return ret;
  28266. if (sLen)
  28267. *sLen = (word32)len;
  28268. if (s)
  28269. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  28270. #ifndef NO_STRICT_ECDSA_LEN
  28271. /* sanity check that the index has been advanced all the way to the end of
  28272. * the buffer */
  28273. if (idx + (word32)len != sigLen) {
  28274. ret = ASN_ECC_KEY_E;
  28275. }
  28276. #endif
  28277. return ret;
  28278. #else
  28279. ASNGetData dataASN[dsaSigASN_Length];
  28280. word32 idx = 0;
  28281. /* Clear dynamic data and set buffers to put r and s into. */
  28282. XMEMSET(dataASN, 0, sizeof(dataASN));
  28283. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28284. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28285. /* Decode the DSA signature. */
  28286. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28287. sigLen);
  28288. #endif /* WOLFSSL_ASN_TEMPLATE */
  28289. }
  28290. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28291. {
  28292. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  28293. }
  28294. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  28295. int init)
  28296. {
  28297. #ifndef WOLFSSL_ASN_TEMPLATE
  28298. word32 idx = 0;
  28299. int len = 0;
  28300. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28301. return ASN_ECC_KEY_E;
  28302. }
  28303. #ifndef NO_STRICT_ECDSA_LEN
  28304. /* enable strict length checking for signature */
  28305. if (sigLen != idx + (word32)len) {
  28306. return ASN_ECC_KEY_E;
  28307. }
  28308. #else
  28309. /* allow extra signature bytes at end */
  28310. if ((word32)len > (sigLen - idx)) {
  28311. return ASN_ECC_KEY_E;
  28312. }
  28313. #endif
  28314. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  28315. return ASN_ECC_KEY_E;
  28316. }
  28317. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  28318. mp_clear(r);
  28319. return ASN_ECC_KEY_E;
  28320. }
  28321. #ifndef NO_STRICT_ECDSA_LEN
  28322. /* sanity check that the index has been advanced all the way to the end of
  28323. * the buffer */
  28324. if (idx != sigLen) {
  28325. mp_clear(r);
  28326. mp_clear(s);
  28327. return ASN_ECC_KEY_E;
  28328. }
  28329. #endif
  28330. return 0;
  28331. #else
  28332. ASNGetData dataASN[dsaSigASN_Length];
  28333. word32 idx = 0;
  28334. int ret;
  28335. /* Clear dynamic data and set mp_ints to put r and s into. */
  28336. XMEMSET(dataASN, 0, sizeof(dataASN));
  28337. if (init) {
  28338. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28339. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28340. }
  28341. else {
  28342. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  28343. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  28344. }
  28345. /* Decode the DSA signature. */
  28346. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  28347. sigLen);
  28348. #ifndef NO_STRICT_ECDSA_LEN
  28349. /* sanity check that the index has been advanced all the way to the end of
  28350. * the buffer */
  28351. if ((ret == 0) && (idx != sigLen)) {
  28352. ret = ASN_ECC_KEY_E;
  28353. }
  28354. #endif
  28355. if (ret != 0) {
  28356. mp_clear(r);
  28357. mp_clear(s);
  28358. }
  28359. return ret;
  28360. #endif /* WOLFSSL_ASN_TEMPLATE */
  28361. }
  28362. #endif
  28363. #ifdef WOLFSSL_ASN_TEMPLATE
  28364. #ifdef WOLFSSL_CUSTOM_CURVES
  28365. /* Convert data to hex string.
  28366. *
  28367. * Big-endian byte array is converted to big-endian hexadecimal string.
  28368. *
  28369. * @param [in] input Buffer containing data.
  28370. * @param [in] inSz Size of data in buffer.
  28371. * @param [out] out Buffer to hold hex string.
  28372. */
  28373. static void DataToHexString(const byte* input, word32 inSz, char* out)
  28374. {
  28375. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  28376. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  28377. word32 i;
  28378. /* Converting a byte of data at a time to two hex characters. */
  28379. for (i = 0; i < inSz; i++) {
  28380. out[i*2 + 0] = hexChar[input[i] >> 4];
  28381. out[i*2 + 1] = hexChar[input[i] & 0xf];
  28382. }
  28383. /* NUL terminate string. */
  28384. out[i * 2] = '\0';
  28385. }
  28386. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28387. /* Convert data to hex string and place in allocated buffer.
  28388. *
  28389. * Big-endian byte array is converted to big-endian hexadecimal string.
  28390. *
  28391. * @param [in] input Buffer containing data.
  28392. * @param [in] inSz Size of data in buffer.
  28393. * @param [out] out Allocated buffer holding hex string.
  28394. * @param [in] heap Dynamic memory allocation hint.
  28395. * @param [in] heapType Type of heap to use.
  28396. * @return 0 on succcess.
  28397. * @return MEMORY_E when dynamic memory allocation fails.
  28398. */
  28399. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  28400. void* heap, int heapType)
  28401. {
  28402. int ret = 0;
  28403. char* str;
  28404. /* Allocate for 2 string characters ber byte plus NUL. */
  28405. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  28406. if (str == NULL) {
  28407. ret = MEMORY_E;
  28408. }
  28409. else {
  28410. /* Convert to hex string. */
  28411. DataToHexString(input, inSz, str);
  28412. *out = str;
  28413. }
  28414. (void)heap;
  28415. (void)heapType;
  28416. return ret;
  28417. }
  28418. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28419. /* ASN.1 template for SpecifiedECDomain.
  28420. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  28421. * NOTE: characteristic-two-field not supported. */
  28422. static const ASNItem eccSpecifiedASN[] = {
  28423. /* version */
  28424. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28425. /* fieldID */
  28426. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28427. /* prime-field or characteristic-two-field */
  28428. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  28429. /* Prime-p */
  28430. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  28431. /* fieldID */
  28432. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28433. /* a */
  28434. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28435. /* b */
  28436. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28437. /* seed */
  28438. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  28439. /* base */
  28440. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  28441. /* order */
  28442. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28443. /* cofactor */
  28444. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  28445. /* hash */
  28446. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  28447. };
  28448. enum {
  28449. ECCSPECIFIEDASN_IDX_VER = 0,
  28450. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  28451. ECCSPECIFIEDASN_IDX_PRIME_OID,
  28452. ECCSPECIFIEDASN_IDX_PRIME_P,
  28453. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  28454. ECCSPECIFIEDASN_IDX_PARAM_A,
  28455. ECCSPECIFIEDASN_IDX_PARAM_B,
  28456. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  28457. ECCSPECIFIEDASN_IDX_BASE,
  28458. ECCSPECIFIEDASN_IDX_ORDER,
  28459. ECCSPECIFIEDASN_IDX_COFACTOR,
  28460. ECCSPECIFIEDASN_IDX_HASH_SEQ
  28461. };
  28462. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  28463. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  28464. /* OID indicating the prime field is explicity defined. */
  28465. static const byte primeFieldOID[] = {
  28466. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  28467. };
  28468. static const char ecSetCustomName[] = "Custom";
  28469. /* Explicit EC parameter values. */
  28470. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  28471. ecc_key* key)
  28472. {
  28473. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  28474. int ret = 0;
  28475. ecc_set_type* curve;
  28476. word32 idx = 0;
  28477. byte version;
  28478. byte cofactor;
  28479. const byte *base;
  28480. word32 baseLen;
  28481. /* Allocate a new parameter set. */
  28482. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28483. DYNAMIC_TYPE_ECC_BUFFER);
  28484. if (curve == NULL) {
  28485. ret = MEMORY_E;
  28486. }
  28487. else {
  28488. /* Clear out parameters and set fields to indicate it is custom. */
  28489. XMEMSET(curve, 0, sizeof(*curve));
  28490. }
  28491. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  28492. if (ret == 0) {
  28493. /* Set name to be: "Custom" */
  28494. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28495. curve->name = ecSetCustomName;
  28496. #else
  28497. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  28498. #endif
  28499. curve->id = ECC_CURVE_CUSTOM;
  28500. /* Get version, must have prime field OID and get co-factor. */
  28501. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  28502. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  28503. primeFieldOID, sizeof(primeFieldOID));
  28504. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  28505. /* Decode the explicit parameters. */
  28506. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  28507. input, &idx, inSz);
  28508. }
  28509. /* Version must be 1 or 2 for supporting explicit parameters. */
  28510. if ((ret == 0) && (version < 1 || version > 3)) {
  28511. ret = ASN_PARSE_E;
  28512. }
  28513. #ifndef WOLFSSL_NO_ASN_STRICT
  28514. /* Only version 2 and above can have a seed. */
  28515. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  28516. (version < 2)) {
  28517. ret = ASN_PARSE_E;
  28518. }
  28519. #endif
  28520. /* Only version 2 and above can have a hash algorithm. */
  28521. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  28522. (version < 2)) {
  28523. ret = ASN_PARSE_E;
  28524. }
  28525. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  28526. /* Store optional co-factor. */
  28527. curve->cofactor = cofactor;
  28528. }
  28529. if (ret == 0) {
  28530. /* Length of the prime in bytes is the curve size. */
  28531. curve->size =
  28532. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  28533. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  28534. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  28535. &baseLen);
  28536. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  28537. ret = ASN_PARSE_E;
  28538. }
  28539. }
  28540. /* Put the curve parameters into the set.
  28541. * Convert the big-endian number byte array to a big-endian string.
  28542. */
  28543. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28544. /* Allocate buffer to put hex strings into. */
  28545. if (ret == 0) {
  28546. /* Base X-ordinate */
  28547. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  28548. (char**)&curve->Gx, key->heap,
  28549. DYNAMIC_TYPE_ECC_BUFFER);
  28550. }
  28551. if (ret == 0) {
  28552. /* Base Y-ordinate */
  28553. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  28554. (char**)&curve->Gy, key->heap,
  28555. DYNAMIC_TYPE_ECC_BUFFER);
  28556. }
  28557. if (ret == 0) {
  28558. /* Prime */
  28559. ret = DataToHexStringAlloc(
  28560. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28561. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28562. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28563. }
  28564. if (ret == 0) {
  28565. /* Parameter A */
  28566. ret = DataToHexStringAlloc(
  28567. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28568. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28569. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28570. }
  28571. if (ret == 0) {
  28572. /* Parameter B */
  28573. ret = DataToHexStringAlloc(
  28574. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28575. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28576. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28577. }
  28578. if (ret == 0) {
  28579. /* Order of curve */
  28580. ret = DataToHexStringAlloc(
  28581. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28582. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28583. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28584. }
  28585. #else
  28586. if (ret == 0) {
  28587. /* Base X-ordinate */
  28588. DataToHexString(base + 1, curve->size, curve->Gx);
  28589. /* Base Y-ordinate */
  28590. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  28591. /* Prime */
  28592. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28593. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28594. curve->prime);
  28595. /* Parameter A */
  28596. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28597. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28598. curve->Af);
  28599. /* Parameter B */
  28600. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28601. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28602. curve->Bf);
  28603. /* Order of curve */
  28604. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28605. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28606. curve->order);
  28607. }
  28608. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28609. /* Store parameter set in key. */
  28610. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  28611. ret = ASN_PARSE_E;
  28612. }
  28613. if (ret == 0) {
  28614. /* The parameter set was allocated.. */
  28615. key->deallocSet = 1;
  28616. }
  28617. if ((ret != 0) && (curve != NULL)) {
  28618. /* Failed to set parameters so free paramter set. */
  28619. wc_ecc_free_curve(curve, key->heap);
  28620. }
  28621. FREE_ASNGETDATA(dataASN, key->heap);
  28622. return ret;
  28623. }
  28624. #endif /* WOLFSSL_CUSTOM_CURVES */
  28625. #endif /* WOLFSSL_ASN_TEMPLATE */
  28626. #ifdef HAVE_ECC
  28627. #ifdef WOLFSSL_ASN_TEMPLATE
  28628. /* ASN.1 template for ECC private key.
  28629. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  28630. */
  28631. static const ASNItem eccKeyASN[] = {
  28632. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28633. /* version */
  28634. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  28635. /* privateKey */
  28636. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28637. /* parameters */
  28638. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  28639. /* named */
  28640. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  28641. /* specified */
  28642. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  28643. /* publicKey */
  28644. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  28645. /* Uncompressed point - X9.62. */
  28646. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  28647. };
  28648. enum {
  28649. ECCKEYASN_IDX_SEQ = 0,
  28650. ECCKEYASN_IDX_VER,
  28651. ECCKEYASN_IDX_PKEY,
  28652. ECCKEYASN_IDX_PARAMS,
  28653. ECCKEYASN_IDX_CURVEID,
  28654. ECCKEYASN_IDX_CURVEPARAMS,
  28655. ECCKEYASN_IDX_PUBKEY,
  28656. ECCKEYASN_IDX_PUBKEY_VAL
  28657. };
  28658. /* Number of items in ASN.1 template for ECC private key. */
  28659. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  28660. #endif
  28661. WOLFSSL_ABI
  28662. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  28663. word32 inSz)
  28664. {
  28665. #ifndef WOLFSSL_ASN_TEMPLATE
  28666. word32 oidSum;
  28667. int version, length;
  28668. int privSz, pubSz = 0;
  28669. byte b;
  28670. int ret = 0;
  28671. int curve_id = ECC_CURVE_DEF;
  28672. #ifdef WOLFSSL_SMALL_STACK
  28673. byte* priv;
  28674. byte* pub = NULL;
  28675. #else
  28676. byte priv[ECC_MAXSIZE+1];
  28677. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  28678. #endif
  28679. word32 algId = 0;
  28680. byte* pubData = NULL;
  28681. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28682. return BAD_FUNC_ARG;
  28683. /* if has pkcs8 header skip it */
  28684. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28685. /* ignore error, did not have pkcs8 header */
  28686. }
  28687. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28688. return ASN_PARSE_E;
  28689. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  28690. return ASN_PARSE_E;
  28691. if (*inOutIdx >= inSz)
  28692. return ASN_PARSE_E;
  28693. b = input[*inOutIdx];
  28694. *inOutIdx += 1;
  28695. /* priv type */
  28696. if (b != 4 && b != 6 && b != 7)
  28697. return ASN_PARSE_E;
  28698. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28699. return ASN_PARSE_E;
  28700. privSz = length;
  28701. if (privSz > ECC_MAXSIZE)
  28702. return BUFFER_E;
  28703. #ifdef WOLFSSL_SMALL_STACK
  28704. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28705. if (priv == NULL)
  28706. return MEMORY_E;
  28707. #endif
  28708. /* priv key */
  28709. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  28710. *inOutIdx += (word32)length;
  28711. if ((*inOutIdx + 1) < inSz) {
  28712. /* prefix 0, may have */
  28713. b = input[*inOutIdx];
  28714. if (b == ECC_PREFIX_0) {
  28715. *inOutIdx += 1;
  28716. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28717. ret = ASN_PARSE_E;
  28718. else {
  28719. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  28720. inSz);
  28721. if (ret == 0) {
  28722. if ((ret = CheckCurve(oidSum)) < 0)
  28723. ret = ECC_CURVE_OID_E;
  28724. else {
  28725. curve_id = ret;
  28726. ret = 0;
  28727. }
  28728. }
  28729. }
  28730. }
  28731. }
  28732. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  28733. /* prefix 1 */
  28734. b = input[*inOutIdx];
  28735. *inOutIdx += 1;
  28736. if (b != ECC_PREFIX_1) {
  28737. ret = ASN_ECC_KEY_E;
  28738. }
  28739. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  28740. ret = ASN_PARSE_E;
  28741. }
  28742. else {
  28743. /* key header */
  28744. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  28745. if (ret == 0) {
  28746. /* pub key */
  28747. pubSz = length;
  28748. if (pubSz > 2*(ECC_MAXSIZE+1))
  28749. ret = BUFFER_E;
  28750. else {
  28751. #ifdef WOLFSSL_SMALL_STACK
  28752. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28753. if (pub == NULL)
  28754. ret = MEMORY_E;
  28755. else
  28756. #endif
  28757. {
  28758. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  28759. *inOutIdx += (word32)length;
  28760. pubData = pub;
  28761. }
  28762. }
  28763. }
  28764. }
  28765. }
  28766. if (ret == 0) {
  28767. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  28768. (word32)pubSz, key, curve_id);
  28769. }
  28770. #ifdef WOLFSSL_SMALL_STACK
  28771. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28772. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28773. #endif
  28774. return ret;
  28775. #else
  28776. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  28777. byte version;
  28778. int ret = 0;
  28779. int curve_id = ECC_CURVE_DEF;
  28780. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28781. word32 algId = 0;
  28782. #endif
  28783. /* Validate parameters. */
  28784. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  28785. ret = BAD_FUNC_ARG;
  28786. }
  28787. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  28788. /* if has pkcs8 header skip it */
  28789. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28790. /* ignore error, did not have pkcs8 header */
  28791. }
  28792. #endif
  28793. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  28794. if (ret == 0) {
  28795. /* Get the version and set the expected OID type. */
  28796. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  28797. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  28798. /* Decode the private ECC key. */
  28799. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  28800. inOutIdx, inSz);
  28801. }
  28802. /* Only version 1 supported. */
  28803. if ((ret == 0) && (version != 1)) {
  28804. ret = ASN_PARSE_E;
  28805. }
  28806. /* Curve Parameters are optional. */
  28807. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  28808. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  28809. /* Named curve - check and get id. */
  28810. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  28811. if (curve_id < 0) {
  28812. ret = ECC_CURVE_OID_E;
  28813. }
  28814. }
  28815. else {
  28816. #ifdef WOLFSSL_CUSTOM_CURVES
  28817. /* Parse explicit parameters. */
  28818. ret = EccSpecifiedECDomainDecode(
  28819. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  28820. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  28821. #else
  28822. /* Explicit parameters not supported in build configuration. */
  28823. ret = ASN_PARSE_E;
  28824. #endif
  28825. }
  28826. }
  28827. if (ret == 0) {
  28828. /* Import private key value and public point (may be NULL). */
  28829. ret = wc_ecc_import_private_key_ex(
  28830. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  28831. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  28832. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  28833. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  28834. key, curve_id);
  28835. }
  28836. FREE_ASNGETDATA(dataASN, key->heap);
  28837. return ret;
  28838. #endif
  28839. }
  28840. #ifdef WOLFSSL_CUSTOM_CURVES
  28841. #ifndef WOLFSSL_ASN_TEMPLATE
  28842. /* returns 0 on success */
  28843. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  28844. word32 inSz, void* heap, int heapType)
  28845. {
  28846. int len;
  28847. int i;
  28848. char* str;
  28849. word32 localIdx;
  28850. byte tag;
  28851. if (*inOutIdx >= inSz) {
  28852. return BUFFER_E;
  28853. }
  28854. localIdx = *inOutIdx;
  28855. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  28856. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  28857. return ASN_PARSE_E;
  28858. }
  28859. else {
  28860. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  28861. return ASN_PARSE_E;
  28862. }
  28863. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  28864. if (str == NULL) {
  28865. return MEMORY_E;
  28866. }
  28867. for (i=0; i<len; i++)
  28868. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  28869. str[len*2] = '\0';
  28870. *inOutIdx += (word32)len;
  28871. *out = str;
  28872. (void)heap;
  28873. (void)heapType;
  28874. return 0;
  28875. }
  28876. static int EccKeyParamCopy(char** dst, char* src)
  28877. {
  28878. int ret = 0;
  28879. #ifdef WOLFSSL_ECC_CURVE_STATIC
  28880. word32 length;
  28881. #endif
  28882. if (dst == NULL || src == NULL)
  28883. return BAD_FUNC_ARG;
  28884. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28885. *dst = src;
  28886. #else
  28887. length = (int)XSTRLEN(src) + 1;
  28888. if (length > MAX_ECC_STRING) {
  28889. WOLFSSL_MSG("ECC Param too large for buffer");
  28890. ret = BUFFER_E;
  28891. }
  28892. else {
  28893. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  28894. }
  28895. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28896. #endif
  28897. return ret;
  28898. }
  28899. #endif /* !WOLFSSL_ASN_TEMPLATE */
  28900. #endif /* WOLFSSL_CUSTOM_CURVES */
  28901. WOLFSSL_ABI
  28902. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  28903. ecc_key* key, word32 inSz)
  28904. {
  28905. #ifndef WOLFSSL_ASN_TEMPLATE
  28906. int ret;
  28907. int version, length;
  28908. int curve_id = ECC_CURVE_DEF;
  28909. word32 oidSum, localIdx;
  28910. byte tag, isPrivFormat = 0;
  28911. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28912. return BAD_FUNC_ARG;
  28913. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28914. return ASN_PARSE_E;
  28915. /* Check if ECC private key is being used and skip private portion */
  28916. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  28917. isPrivFormat = 1;
  28918. /* Type private key */
  28919. if (*inOutIdx >= inSz)
  28920. return ASN_PARSE_E;
  28921. tag = input[*inOutIdx];
  28922. *inOutIdx += 1;
  28923. if (tag != 4 && tag != 6 && tag != 7)
  28924. return ASN_PARSE_E;
  28925. /* Skip Private Key */
  28926. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28927. return ASN_PARSE_E;
  28928. if (length > ECC_MAXSIZE)
  28929. return BUFFER_E;
  28930. *inOutIdx += (word32)length;
  28931. /* Private Curve Header */
  28932. if (*inOutIdx >= inSz)
  28933. return ASN_PARSE_E;
  28934. tag = input[*inOutIdx];
  28935. *inOutIdx += 1;
  28936. if (tag != ECC_PREFIX_0)
  28937. return ASN_ECC_KEY_E;
  28938. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28939. return ASN_PARSE_E;
  28940. }
  28941. /* Standard ECC public key */
  28942. else {
  28943. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28944. return ASN_PARSE_E;
  28945. ret = SkipObjectId(input, inOutIdx, inSz);
  28946. if (ret != 0)
  28947. return ret;
  28948. }
  28949. if (*inOutIdx >= inSz) {
  28950. return BUFFER_E;
  28951. }
  28952. localIdx = *inOutIdx;
  28953. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  28954. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  28955. #ifdef WOLFSSL_CUSTOM_CURVES
  28956. ecc_set_type* curve;
  28957. int len;
  28958. char* point = NULL;
  28959. ret = 0;
  28960. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28961. DYNAMIC_TYPE_ECC_BUFFER);
  28962. if (curve == NULL)
  28963. ret = MEMORY_E;
  28964. if (ret == 0) {
  28965. static const char customName[] = "Custom";
  28966. XMEMSET(curve, 0, sizeof(*curve));
  28967. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28968. curve->name = customName;
  28969. #else
  28970. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  28971. #endif
  28972. curve->id = ECC_CURVE_CUSTOM;
  28973. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28974. ret = ASN_PARSE_E;
  28975. }
  28976. if (ret == 0) {
  28977. GetInteger7Bit(input, inOutIdx, inSz);
  28978. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28979. ret = ASN_PARSE_E;
  28980. }
  28981. if (ret == 0) {
  28982. char* p = NULL;
  28983. SkipObjectId(input, inOutIdx, inSz);
  28984. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  28985. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28986. if (ret == 0) {
  28987. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28988. ret = EccKeyParamCopy((char**)&curve->prime, p);
  28989. #else
  28990. const char *_tmp_ptr = &curve->prime[0];
  28991. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  28992. #endif
  28993. }
  28994. }
  28995. if (ret == 0) {
  28996. curve->size = (int)XSTRLEN(curve->prime) / 2;
  28997. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28998. ret = ASN_PARSE_E;
  28999. }
  29000. if (ret == 0) {
  29001. char* af = NULL;
  29002. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  29003. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29004. if (ret == 0) {
  29005. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29006. ret = EccKeyParamCopy((char**)&curve->Af, af);
  29007. #else
  29008. const char *_tmp_ptr = &curve->Af[0];
  29009. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  29010. #endif
  29011. }
  29012. }
  29013. if (ret == 0) {
  29014. char* bf = NULL;
  29015. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  29016. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29017. if (ret == 0) {
  29018. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29019. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29020. #else
  29021. const char *_tmp_ptr = &curve->Bf[0];
  29022. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29023. #endif
  29024. }
  29025. }
  29026. if (ret == 0) {
  29027. localIdx = *inOutIdx;
  29028. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29029. == 0 && tag == ASN_BIT_STRING) {
  29030. len = 0;
  29031. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29032. if (ret > 0)
  29033. ret = 0; /* reset on success */
  29034. *inOutIdx += (word32)len;
  29035. }
  29036. }
  29037. if (ret == 0) {
  29038. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29039. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29040. /* sanity check that point buffer is not smaller than the expected
  29041. * size to hold ( 0 4 || Gx || Gy )
  29042. * where Gx and Gy are each the size of curve->size * 2 */
  29043. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29044. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29045. ret = BUFFER_E;
  29046. }
  29047. }
  29048. if (ret == 0) {
  29049. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29050. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29051. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29052. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29053. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29054. if (curve->Gx == NULL || curve->Gy == NULL) {
  29055. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29056. ret = MEMORY_E;
  29057. }
  29058. #else
  29059. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29060. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29061. ret = BUFFER_E;
  29062. }
  29063. #endif
  29064. }
  29065. if (ret == 0) {
  29066. char* o = NULL;
  29067. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  29068. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29069. (size_t)curve->size * 2);
  29070. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29071. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29072. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29073. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29074. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29075. if (ret == 0) {
  29076. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29077. ret = EccKeyParamCopy((char**)&curve->order, o);
  29078. #else
  29079. const char *_tmp_ptr = &curve->order[0];
  29080. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29081. #endif
  29082. }
  29083. }
  29084. if (ret == 0) {
  29085. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29086. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29087. curve->oid = NULL;
  29088. #else
  29089. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29090. #endif
  29091. curve->oidSz = 0;
  29092. curve->oidSum = 0;
  29093. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29094. ret = ASN_PARSE_E;
  29095. }
  29096. key->deallocSet = 1;
  29097. curve = NULL;
  29098. }
  29099. if (curve != NULL)
  29100. wc_ecc_free_curve(curve, key->heap);
  29101. if (ret < 0)
  29102. return ret;
  29103. #else
  29104. return ASN_PARSE_E;
  29105. #endif /* WOLFSSL_CUSTOM_CURVES */
  29106. }
  29107. else {
  29108. /* ecc params information */
  29109. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29110. if (ret != 0)
  29111. return ret;
  29112. /* get curve id */
  29113. if ((ret = CheckCurve(oidSum)) < 0)
  29114. return ECC_CURVE_OID_E;
  29115. else {
  29116. curve_id = ret;
  29117. }
  29118. }
  29119. if (isPrivFormat) {
  29120. /* Public Curve Header - skip */
  29121. if (*inOutIdx >= inSz)
  29122. return ASN_PARSE_E;
  29123. tag = input[*inOutIdx];
  29124. *inOutIdx += 1;
  29125. if (tag != ECC_PREFIX_1)
  29126. return ASN_ECC_KEY_E;
  29127. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29128. return ASN_PARSE_E;
  29129. }
  29130. /* key header */
  29131. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29132. if (ret != 0)
  29133. return ret;
  29134. /* This is the raw point data compressed or uncompressed. */
  29135. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  29136. curve_id) != 0) {
  29137. return ASN_ECC_KEY_E;
  29138. }
  29139. *inOutIdx += (word32)length;
  29140. return 0;
  29141. #else
  29142. /* eccKeyASN is longer than eccPublicKeyASN. */
  29143. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29144. int ret = 0;
  29145. int curve_id = ECC_CURVE_DEF;
  29146. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29147. #ifdef WOLFSSL_CUSTOM_CURVES
  29148. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29149. #endif
  29150. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29151. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29152. ret = BAD_FUNC_ARG;
  29153. }
  29154. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29155. if (ret == 0) {
  29156. /* Clear dynamic data for ECC public key. */
  29157. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29158. /* Set required ECDSA OID and ignore the curve OID type. */
  29159. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29160. sizeof(keyEcdsaOid));
  29161. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29162. /* Decode the public ECC key. */
  29163. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29164. input, inOutIdx, inSz);
  29165. if (ret != 0) {
  29166. oidIdx = ECCKEYASN_IDX_CURVEID;
  29167. #ifdef WOLFSSL_CUSTOM_CURVES
  29168. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29169. #endif
  29170. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29171. /* Clear dynamic data for ECC private key. */
  29172. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29173. /* Check named curve OID type. */
  29174. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  29175. /* Try private key format .*/
  29176. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29177. inOutIdx, inSz);
  29178. if (ret != 0) {
  29179. ret = ASN_PARSE_E;
  29180. }
  29181. }
  29182. }
  29183. if (ret == 0) {
  29184. if (dataASN[oidIdx].tag != 0) {
  29185. /* Named curve - check and get id. */
  29186. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29187. if (curve_id < 0) {
  29188. ret = ASN_OBJECT_ID_E;
  29189. }
  29190. }
  29191. else {
  29192. #ifdef WOLFSSL_CUSTOM_CURVES
  29193. /* Parse explicit parameters. */
  29194. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29195. dataASN[specIdx].data.ref.length, key);
  29196. #else
  29197. /* Explicit parameters not supported in build configuration. */
  29198. ret = ASN_PARSE_E;
  29199. #endif
  29200. }
  29201. }
  29202. if (ret == 0) {
  29203. /* Import public point. */
  29204. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29205. dataASN[pubIdx].data.ref.length, key, curve_id);
  29206. if (ret != 0) {
  29207. ret = ASN_ECC_KEY_E;
  29208. }
  29209. }
  29210. FREE_ASNGETDATA(dataASN, key->heap);
  29211. return ret;
  29212. #endif /* WOLFSSL_ASN_TEMPLATE */
  29213. }
  29214. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29215. /* build DER formatted ECC key, include optional public key if requested,
  29216. * return length on success, negative on error */
  29217. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29218. int pubIn, int curveIn)
  29219. {
  29220. #ifndef WOLFSSL_ASN_TEMPLATE
  29221. byte curve[MAX_ALGO_SZ+2];
  29222. byte ver[MAX_VERSION_SZ];
  29223. byte seq[MAX_SEQ_SZ];
  29224. int ret, curveSz, verSz;
  29225. word32 totalSz;
  29226. int privHdrSz = ASN_ECC_HEADER_SZ;
  29227. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29228. #ifdef WOLFSSL_NO_MALLOC
  29229. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29230. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29231. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29232. #else
  29233. byte *prv = NULL, *pub = NULL;
  29234. #endif
  29235. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29236. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29237. if (key == NULL || (output == NULL && inLen == NULL))
  29238. return BAD_FUNC_ARG;
  29239. if (curveIn) {
  29240. /* curve */
  29241. curve[curveidx++] = ECC_PREFIX_0;
  29242. curveidx++ /* to put the size after computation */;
  29243. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29244. if (curveSz < 0)
  29245. return curveSz;
  29246. /* set computed size */
  29247. curve[1] = (byte)curveSz;
  29248. curveidx += (word32)curveSz;
  29249. }
  29250. /* private */
  29251. privSz = (word32)key->dp->size;
  29252. #ifdef WOLFSSL_QNX_CAAM
  29253. /* check if is a black key, and add MAC size if needed */
  29254. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29255. privSz = privSz + WC_CAAM_MAC_SZ;
  29256. }
  29257. #endif
  29258. #ifndef WOLFSSL_NO_MALLOC
  29259. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  29260. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29261. if (prv == NULL) {
  29262. return MEMORY_E;
  29263. }
  29264. #else
  29265. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29266. return BUFFER_E;
  29267. }
  29268. #endif
  29269. if (privSz < ASN_LONG_LENGTH) {
  29270. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29271. }
  29272. else {
  29273. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29274. }
  29275. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29276. if (ret < 0) {
  29277. #ifndef WOLFSSL_NO_MALLOC
  29278. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29279. #endif
  29280. return ret;
  29281. }
  29282. prvidx += privSz;
  29283. /* pubIn */
  29284. if (pubIn) {
  29285. PRIVATE_KEY_UNLOCK();
  29286. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29287. PRIVATE_KEY_LOCK();
  29288. if (ret != LENGTH_ONLY_E) {
  29289. #ifndef WOLFSSL_NO_MALLOC
  29290. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29291. #endif
  29292. return ret;
  29293. }
  29294. #ifndef WOLFSSL_NO_MALLOC
  29295. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  29296. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29297. if (pub == NULL) {
  29298. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29299. return MEMORY_E;
  29300. }
  29301. #else
  29302. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29303. return BUFFER_E;
  29304. }
  29305. #endif
  29306. pub[pubidx++] = ECC_PREFIX_1;
  29307. if (pubSz > 128) /* leading zero + extra size byte */
  29308. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29309. else /* leading zero */
  29310. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29311. /* SetBitString adds leading zero */
  29312. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29313. PRIVATE_KEY_UNLOCK();
  29314. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29315. PRIVATE_KEY_LOCK();
  29316. if (ret != 0) {
  29317. #ifndef WOLFSSL_NO_MALLOC
  29318. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29319. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29320. #endif
  29321. return ret;
  29322. }
  29323. pubidx += pubSz;
  29324. }
  29325. /* make headers */
  29326. verSz = SetMyVersion(1, ver, FALSE);
  29327. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  29328. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  29329. if (output == NULL) {
  29330. *inLen = totalSz;
  29331. #ifndef WOLFSSL_NO_MALLOC
  29332. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29333. if (pubIn) {
  29334. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29335. }
  29336. #endif
  29337. return LENGTH_ONLY_E;
  29338. }
  29339. if (inLen != NULL && totalSz > *inLen) {
  29340. #ifndef WOLFSSL_NO_MALLOC
  29341. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29342. if (pubIn) {
  29343. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29344. }
  29345. #endif
  29346. return BAD_FUNC_ARG;
  29347. }
  29348. /* write out */
  29349. /* seq */
  29350. XMEMCPY(output + idx, seq, seqSz);
  29351. idx = seqSz;
  29352. /* ver */
  29353. XMEMCPY(output + idx, ver, (size_t)verSz);
  29354. idx += (word32)verSz;
  29355. /* private */
  29356. XMEMCPY(output + idx, prv, prvidx);
  29357. idx += prvidx;
  29358. #ifndef WOLFSSL_NO_MALLOC
  29359. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29360. #endif
  29361. /* curve */
  29362. XMEMCPY(output + idx, curve, curveidx);
  29363. idx += curveidx;
  29364. /* pubIn */
  29365. if (pubIn) {
  29366. XMEMCPY(output + idx, pub, pubidx);
  29367. /* idx += pubidx; not used after write, if more data remove comment */
  29368. #ifndef WOLFSSL_NO_MALLOC
  29369. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29370. #endif
  29371. }
  29372. return (int)totalSz;
  29373. #else
  29374. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  29375. word32 privSz, pubSz;
  29376. int sz = 0;
  29377. int ret = 0;
  29378. int curveIdSz = 0;
  29379. /* Check validity of parameters. */
  29380. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  29381. ret = BAD_FUNC_ARG;
  29382. }
  29383. /* Check key has parameters when encoding curve. */
  29384. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  29385. ret = BAD_FUNC_ARG;
  29386. }
  29387. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29388. if (ret == 0) {
  29389. /* Private key size is the curve size. */
  29390. privSz = (word32)key->dp->size;
  29391. if (pubIn) {
  29392. /* Get the length of the public key. */
  29393. PRIVATE_KEY_UNLOCK();
  29394. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29395. PRIVATE_KEY_LOCK();
  29396. if (ret == LENGTH_ONLY_E)
  29397. ret = 0;
  29398. }
  29399. }
  29400. if (ret == 0) {
  29401. /* Version: 1 */
  29402. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  29403. /* Leave space for private key. */
  29404. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  29405. if (curveIn) {
  29406. /* Get length of the named curve OID to put into the encoding. */
  29407. curveIdSz = SetCurve(key, NULL, 0);
  29408. if (curveIdSz < 0) {
  29409. ret = curveIdSz;
  29410. }
  29411. /* Curve OID */
  29412. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  29413. (word32)curveIdSz);
  29414. /* TODO: add support for SpecifiedECDomain curve. */
  29415. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  29416. }
  29417. else {
  29418. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  29419. eccKeyASN_Length);
  29420. }
  29421. if (ret == 0) {
  29422. if (pubIn) {
  29423. /* Leave space for public key. */
  29424. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  29425. }
  29426. else {
  29427. /* Don't write out public key. */
  29428. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  29429. eccKeyASN_Length);
  29430. }
  29431. /* Calculate size of the private key encoding. */
  29432. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  29433. }
  29434. }
  29435. /* Return the size if no buffer. */
  29436. if ((ret == 0) && (output == NULL)) {
  29437. *inLen = (word32)sz;
  29438. ret = LENGTH_ONLY_E;
  29439. }
  29440. /* Check the buffer is big enough. */
  29441. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  29442. ret = BAD_FUNC_ARG;
  29443. }
  29444. if ((ret == 0) && (output != NULL)) {
  29445. /* Encode the private key. */
  29446. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  29447. if (curveIn) {
  29448. /* Put named curve OID data into encoding. */
  29449. curveIdSz = SetCurve(key,
  29450. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  29451. (size_t)curveIdSz);
  29452. if (curveIdSz < 0) {
  29453. ret = curveIdSz;
  29454. }
  29455. }
  29456. if (ret == 0) {
  29457. /* Export the private value into the buffer. */
  29458. ret = wc_ecc_export_private_only(key,
  29459. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  29460. }
  29461. if ((ret == 0) && pubIn) {
  29462. /* Export the public point into the buffer. */
  29463. PRIVATE_KEY_UNLOCK();
  29464. ret = wc_ecc_export_x963(key,
  29465. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  29466. &pubSz);
  29467. PRIVATE_KEY_LOCK();
  29468. }
  29469. }
  29470. if (ret == 0) {
  29471. /* Return the encoding size. */
  29472. ret = sz;
  29473. }
  29474. FREE_ASNSETDATA(dataASN, key->heap);
  29475. return ret;
  29476. #endif
  29477. }
  29478. /* Write a Private ecc key, including public to DER format,
  29479. * length on success else < 0 */
  29480. WOLFSSL_ABI
  29481. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29482. {
  29483. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  29484. }
  29485. /* Write only private ecc key to DER format,
  29486. * length on success else < 0 */
  29487. int wc_EccKeyDerSize(ecc_key* key, int pub)
  29488. {
  29489. word32 sz = 0;
  29490. int ret;
  29491. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  29492. if (ret != LENGTH_ONLY_E) {
  29493. return ret;
  29494. }
  29495. return (int)sz;
  29496. }
  29497. /* Write only private ecc key to DER format,
  29498. * length on success else < 0 */
  29499. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29500. {
  29501. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  29502. }
  29503. #ifdef HAVE_PKCS8
  29504. /* Write only private ecc key or both private and public parts to unencrypted
  29505. * PKCS#8 format.
  29506. *
  29507. * If output is NULL, places required PKCS#8 buffer size in outLen and
  29508. * returns LENGTH_ONLY_E.
  29509. *
  29510. * return length on success else < 0 */
  29511. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  29512. int includePublic)
  29513. {
  29514. int ret;
  29515. word32 tmpDerSz;
  29516. int algoID = 0;
  29517. word32 oidSz = 0;
  29518. word32 pkcs8Sz = 0;
  29519. const byte* curveOID = NULL;
  29520. #ifdef WOLFSSL_NO_MALLOC
  29521. byte tmpDer[ECC_BUFSIZE];
  29522. #else
  29523. byte* tmpDer = NULL;
  29524. #endif
  29525. word32 sz = ECC_BUFSIZE;
  29526. if (key == NULL || key->dp == NULL || outLen == NULL)
  29527. return BAD_FUNC_ARG;
  29528. /* set algoID, get curve OID */
  29529. algoID = ECDSAk;
  29530. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  29531. if (ret < 0)
  29532. return ret;
  29533. #ifndef WOLFSSL_NO_MALLOC
  29534. /* temp buffer for plain DER key */
  29535. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29536. if (tmpDer == NULL)
  29537. return MEMORY_E;
  29538. #endif
  29539. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  29540. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  29541. if (ret < 0) {
  29542. #ifndef WOLFSSL_NO_MALLOC
  29543. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29544. #endif
  29545. return ret;
  29546. }
  29547. tmpDerSz = (word32)ret;
  29548. /* get pkcs8 expected output size */
  29549. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  29550. curveOID, oidSz);
  29551. if (ret != LENGTH_ONLY_E) {
  29552. #ifndef WOLFSSL_NO_MALLOC
  29553. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29554. #endif
  29555. return ret;
  29556. }
  29557. if (output == NULL) {
  29558. #ifndef WOLFSSL_NO_MALLOC
  29559. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29560. #endif
  29561. *outLen = pkcs8Sz;
  29562. return LENGTH_ONLY_E;
  29563. }
  29564. else if (*outLen < pkcs8Sz) {
  29565. #ifndef WOLFSSL_NO_MALLOC
  29566. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29567. #endif
  29568. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  29569. return BUFFER_E;
  29570. }
  29571. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  29572. algoID, curveOID, oidSz);
  29573. if (ret < 0) {
  29574. #ifndef WOLFSSL_NO_MALLOC
  29575. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29576. #endif
  29577. return ret;
  29578. }
  29579. #ifndef WOLFSSL_NO_MALLOC
  29580. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29581. #endif
  29582. *outLen = (word32)ret;
  29583. return ret;
  29584. }
  29585. /* Write only private ecc key to unencrypted PKCS#8 format.
  29586. *
  29587. * return length on success else < 0 */
  29588. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  29589. {
  29590. return eccToPKCS8(key, output, outLen, 0);
  29591. }
  29592. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  29593. *
  29594. * return length on success else < 0 */
  29595. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  29596. word32* outLen)
  29597. {
  29598. return eccToPKCS8(key, output, outLen, 1);
  29599. }
  29600. #endif /* HAVE_PKCS8 */
  29601. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  29602. #endif /* HAVE_ECC */
  29603. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  29604. #ifdef WOLFSSL_ASN_TEMPLATE
  29605. /* ASN.1 template for Ed25519 and Ed448 private key.
  29606. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  29607. */
  29608. static const ASNItem edKeyASN[] = {
  29609. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29610. /* Version */
  29611. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  29612. /* privateKeyAlgorithm */
  29613. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  29614. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  29615. /* privateKey */
  29616. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  29617. /* CurvePrivateKey */
  29618. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  29619. /* attributes */
  29620. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  29621. /* publicKey */
  29622. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  29623. };
  29624. enum {
  29625. EDKEYASN_IDX_SEQ = 0,
  29626. EDKEYASN_IDX_VER,
  29627. EDKEYASN_IDX_PKEYALGO_SEQ,
  29628. EDKEYASN_IDX_PKEYALGO_OID,
  29629. EDKEYASN_IDX_PKEY,
  29630. EDKEYASN_IDX_PKEY_CURVEPKEY,
  29631. EDKEYASN_IDX_ATTRS,
  29632. EDKEYASN_IDX_PUBKEY
  29633. };
  29634. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  29635. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  29636. #endif
  29637. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  29638. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  29639. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  29640. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  29641. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  29642. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  29643. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  29644. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  29645. byte* privKey, word32* privKeyLen,
  29646. byte* pubKey, word32* pubKeyLen, int keyType)
  29647. {
  29648. #ifndef WOLFSSL_ASN_TEMPLATE
  29649. word32 oid;
  29650. int version, length, endKeyIdx, privSz, pubSz;
  29651. const byte* priv;
  29652. const byte* pub;
  29653. #else
  29654. int ret = 0;
  29655. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  29656. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29657. #endif
  29658. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  29659. privKey == NULL || privKeyLen == NULL) {
  29660. return BAD_FUNC_ARG;
  29661. }
  29662. #ifndef WOLFSSL_ASN_TEMPLATE
  29663. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  29664. endKeyIdx = (int)*inOutIdx + length;
  29665. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  29666. return ASN_PARSE_E;
  29667. if (version != 0) {
  29668. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  29669. return ASN_PARSE_E;
  29670. }
  29671. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29672. return ASN_PARSE_E;
  29673. if (oid != (word32)keyType)
  29674. return ASN_PARSE_E;
  29675. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  29676. return ASN_PARSE_E;
  29677. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29678. return ASN_PARSE_E;
  29679. priv = input + *inOutIdx;
  29680. *inOutIdx += (word32)privSz;
  29681. }
  29682. else {
  29683. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29684. return ASN_PARSE_E;
  29685. priv = input + *inOutIdx;
  29686. *inOutIdx += (word32)privSz;
  29687. endKeyIdx = (int)*inOutIdx;
  29688. }
  29689. if ((word32)privSz > *privKeyLen)
  29690. return BUFFER_E;
  29691. if (endKeyIdx == (int)*inOutIdx) {
  29692. *privKeyLen = (word32)privSz;
  29693. XMEMCPY(privKey, priv, *privKeyLen);
  29694. if (pubKeyLen != NULL)
  29695. *pubKeyLen = 0;
  29696. }
  29697. else {
  29698. if (pubKeyLen == NULL) {
  29699. return BAD_FUNC_ARG;
  29700. }
  29701. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  29702. inOutIdx, &pubSz, inSz) < 0) {
  29703. return ASN_PARSE_E;
  29704. }
  29705. if ((word32)pubSz > *pubKeyLen)
  29706. return BUFFER_E;
  29707. pub = input + *inOutIdx;
  29708. *inOutIdx += (word32)pubSz;
  29709. *privKeyLen = (word32)privSz;
  29710. XMEMCPY(privKey, priv, *privKeyLen);
  29711. *pubKeyLen = (word32)pubSz;
  29712. if (pubKey != NULL)
  29713. XMEMCPY(pubKey, pub, *pubKeyLen);
  29714. }
  29715. if (endKeyIdx != (int)*inOutIdx)
  29716. return ASN_PARSE_E;
  29717. return 0;
  29718. #else
  29719. if (ret == 0) {
  29720. /* Require OID. */
  29721. word32 oidSz;
  29722. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  29723. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  29724. /* Parse full private key. */
  29725. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  29726. inOutIdx, inSz);
  29727. if (ret != 0) {
  29728. /* Parse just the OCTET_STRING. */
  29729. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  29730. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  29731. inOutIdx, inSz);
  29732. if (ret != 0) {
  29733. ret = ASN_PARSE_E;
  29734. }
  29735. }
  29736. }
  29737. /* Check the private value length is correct. */
  29738. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  29739. > *privKeyLen) {
  29740. ret = ASN_PARSE_E;
  29741. }
  29742. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  29743. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29744. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29745. *privKeyLen);
  29746. if (pubKeyLen != NULL)
  29747. *pubKeyLen = 0;
  29748. }
  29749. else if ((ret == 0) &&
  29750. (pubKeyLen != NULL) &&
  29751. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29752. ret = ASN_PARSE_E;
  29753. }
  29754. else if (ret == 0) {
  29755. /* Import private and public value. */
  29756. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29757. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29758. *privKeyLen);
  29759. if (pubKeyLen != NULL)
  29760. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  29761. if (pubKey != NULL && pubKeyLen != NULL)
  29762. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  29763. *pubKeyLen);
  29764. }
  29765. FREE_ASNGETDATA(dataASN, NULL);
  29766. return ret;
  29767. #endif /* WOLFSSL_ASN_TEMPLATE */
  29768. }
  29769. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  29770. byte* pubKey, word32* pubKeyLen, int keyType)
  29771. {
  29772. int ret = 0;
  29773. #ifndef WOLFSSL_ASN_TEMPLATE
  29774. int length;
  29775. word32 oid;
  29776. #else
  29777. word32 len;
  29778. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  29779. #endif
  29780. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  29781. pubKey == NULL || pubKeyLen == NULL) {
  29782. return BAD_FUNC_ARG;
  29783. }
  29784. #ifndef WOLFSSL_ASN_TEMPLATE
  29785. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29786. return ASN_PARSE_E;
  29787. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29788. return ASN_PARSE_E;
  29789. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29790. return ASN_PARSE_E;
  29791. if (oid != (word32)keyType)
  29792. return ASN_PARSE_E;
  29793. /* key header */
  29794. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29795. if (ret != 0)
  29796. return ret;
  29797. /* check that the value found is not too large for pubKey buffer */
  29798. if ((word32)length > *pubKeyLen)
  29799. return ASN_PARSE_E;
  29800. /* check that input buffer is exhausted */
  29801. if (*inOutIdx + (word32)length != inSz)
  29802. return ASN_PARSE_E;
  29803. /* This is the raw point data compressed or uncompressed. */
  29804. *pubKeyLen = (word32)length;
  29805. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  29806. #else
  29807. len = inSz - *inOutIdx;
  29808. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  29809. if (ret == 0) {
  29810. /* Require OID. */
  29811. word32 oidSz;
  29812. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  29813. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  29814. /* Decode Ed25519 private key. */
  29815. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  29816. inOutIdx, inSz);
  29817. if (ret != 0)
  29818. ret = ASN_PARSE_E;
  29819. /* check that input buffer is exhausted */
  29820. if (*inOutIdx != inSz)
  29821. ret = ASN_PARSE_E;
  29822. }
  29823. /* Check the public value length is correct. */
  29824. if ((ret == 0) &&
  29825. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29826. ret = ASN_PARSE_E;
  29827. }
  29828. /* Check that the all the buffer was used. */
  29829. if ((ret == 0) &&
  29830. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  29831. ret = ASN_PARSE_E;
  29832. }
  29833. if (ret == 0) {
  29834. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  29835. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  29836. *pubKeyLen);
  29837. }
  29838. FREE_ASNGETDATA(dataASN, NULL);
  29839. #endif /* WOLFSSL_ASN_TEMPLATE */
  29840. return ret;
  29841. }
  29842. #endif
  29843. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  29844. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  29845. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  29846. ed25519_key* key, word32 inSz)
  29847. {
  29848. int ret;
  29849. byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
  29850. word32 privKeyLen = (word32)sizeof(privKey);
  29851. word32 pubKeyLen = (word32)sizeof(pubKey);
  29852. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29853. return BAD_FUNC_ARG;
  29854. }
  29855. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  29856. pubKey, &pubKeyLen, ED25519k);
  29857. if (ret == 0) {
  29858. if (pubKeyLen == 0) {
  29859. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  29860. }
  29861. else {
  29862. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  29863. pubKey, pubKeyLen, key);
  29864. }
  29865. }
  29866. return ret;
  29867. }
  29868. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  29869. ed25519_key* key, word32 inSz)
  29870. {
  29871. int ret;
  29872. byte pubKey[ED25519_PUB_KEY_SIZE];
  29873. word32 pubKeyLen = (word32)sizeof(pubKey);
  29874. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29875. return BAD_FUNC_ARG;
  29876. }
  29877. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  29878. pubKey, &pubKeyLen, ED25519k);
  29879. if (ret == 0) {
  29880. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  29881. }
  29882. return ret;
  29883. }
  29884. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  29885. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  29886. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  29887. curve25519_key* key, word32 inSz)
  29888. {
  29889. int ret;
  29890. byte privKey[CURVE25519_KEYSIZE];
  29891. word32 privKeyLen = CURVE25519_KEYSIZE;
  29892. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29893. return BAD_FUNC_ARG;
  29894. }
  29895. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  29896. NULL, NULL, X25519k);
  29897. if (ret == 0) {
  29898. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  29899. }
  29900. return ret;
  29901. }
  29902. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  29903. curve25519_key* key, word32 inSz)
  29904. {
  29905. int ret;
  29906. byte pubKey[CURVE25519_KEYSIZE];
  29907. word32 pubKeyLen = (word32)sizeof(pubKey);
  29908. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  29909. return BAD_FUNC_ARG;
  29910. }
  29911. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  29912. pubKey, &pubKeyLen, X25519k);
  29913. if (ret == 0) {
  29914. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  29915. }
  29916. return ret;
  29917. }
  29918. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  29919. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  29920. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  29921. *
  29922. * Pass NULL for output to get the size of the encoding.
  29923. *
  29924. * @param [in] privKey private key buffer
  29925. * @param [in] privKeyLen private ket buffer length
  29926. * @param [in] pubKey public key buffer (optional)
  29927. * @param [in] pubKeyLen public ket buffer length
  29928. * @param [out] output Buffer to put encoded data in (optional)
  29929. * @param [in] outLen Size of buffer in bytes
  29930. * @param [in] keyType is "enum Key_Sum" like ED25519k
  29931. * @return Size of encoded data in bytes on success
  29932. * @return BAD_FUNC_ARG when key is NULL.
  29933. * @return MEMORY_E when dynamic memory allocation failed.
  29934. */
  29935. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  29936. const byte* pubKey, word32 pubKeyLen,
  29937. byte* output, word32 outLen, int keyType)
  29938. {
  29939. int ret = 0;
  29940. #ifndef WOLFSSL_ASN_TEMPLATE
  29941. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  29942. #else
  29943. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  29944. int sz;
  29945. #endif
  29946. /* Validate parameters. */
  29947. if (privKey == NULL || outLen == 0) {
  29948. return BAD_FUNC_ARG;
  29949. }
  29950. #ifndef WOLFSSL_ASN_TEMPLATE
  29951. /* calculate size */
  29952. if (pubKey) {
  29953. pubSz = 2 + pubKeyLen;
  29954. }
  29955. privSz = 2 + 2 + privKeyLen;
  29956. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  29957. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  29958. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  29959. sz = seqSz + verSz + algoSz + privSz + pubSz;
  29960. /* checkout output size */
  29961. if (output != NULL && sz > outLen) {
  29962. ret = BAD_FUNC_ARG;
  29963. }
  29964. if (ret == 0 && output != NULL) {
  29965. /* write out */
  29966. /* seq */
  29967. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  29968. idx = seqSz;
  29969. /* ver */
  29970. SetMyVersion(0, output + idx, FALSE);
  29971. idx += verSz;
  29972. /* algo */
  29973. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  29974. idx += algoSz;
  29975. /* privKey */
  29976. idx += SetOctetString(2 + privKeyLen, output + idx);
  29977. idx += SetOctetString(privKeyLen, output + idx);
  29978. XMEMCPY(output + idx, privKey, privKeyLen);
  29979. idx += privKeyLen;
  29980. /* pubKey */
  29981. if (pubKey) {
  29982. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  29983. 1, pubKeyLen, output + idx);
  29984. XMEMCPY(output + idx, pubKey, pubKeyLen);
  29985. idx += pubKeyLen;
  29986. }
  29987. sz = idx;
  29988. }
  29989. if (ret == 0) {
  29990. /* Return size of encoding. */
  29991. ret = (int)sz;
  29992. }
  29993. #else
  29994. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29995. if (ret == 0) {
  29996. /* Set version = 0 */
  29997. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  29998. /* Set OID. */
  29999. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
  30000. oidKeyType);
  30001. /* Leave space for private key. */
  30002. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  30003. /* Don't write out attributes. */
  30004. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  30005. if (pubKey) {
  30006. /* Leave space for public key. */
  30007. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  30008. }
  30009. else {
  30010. /* Don't put out public part. */
  30011. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  30012. edKeyASN_Length);
  30013. }
  30014. /* Calculate the size of encoding. */
  30015. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  30016. }
  30017. /* Check buffer is big enough. */
  30018. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30019. ret = BAD_FUNC_ARG;
  30020. }
  30021. if ((ret == 0) && (output != NULL)) {
  30022. /* Encode private key. */
  30023. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30024. /* Put private value into space provided. */
  30025. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30026. privKey, privKeyLen);
  30027. if (pubKey != NULL) {
  30028. /* Put public value into space provided. */
  30029. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30030. pubKey, pubKeyLen);
  30031. }
  30032. }
  30033. if (ret == 0) {
  30034. /* Return size of encoding. */
  30035. ret = sz;
  30036. }
  30037. FREE_ASNSETDATA(dataASN, NULL);
  30038. #endif
  30039. return ret;
  30040. }
  30041. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30042. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30043. /* Write a Private ED25519 key, including public to DER format,
  30044. * length on success else < 0 */
  30045. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30046. {
  30047. if (key == NULL) {
  30048. return BAD_FUNC_ARG;
  30049. }
  30050. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30051. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30052. }
  30053. /* Write only private ED25519 key to DER format,
  30054. * length on success else < 0 */
  30055. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30056. {
  30057. if (key == NULL) {
  30058. return BAD_FUNC_ARG;
  30059. }
  30060. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30061. NULL, 0, output, inLen, ED25519k);
  30062. }
  30063. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30064. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30065. /* Write only private Curve25519 key to DER format,
  30066. * length on success else < 0 */
  30067. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30068. {
  30069. int ret;
  30070. byte privKey[CURVE25519_KEYSIZE];
  30071. word32 privKeyLen = CURVE25519_KEYSIZE;
  30072. if (key == NULL) {
  30073. return BAD_FUNC_ARG;
  30074. }
  30075. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30076. if (ret == 0) {
  30077. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30078. X25519k);
  30079. }
  30080. return ret;
  30081. }
  30082. /* Write a public Curve25519 key to DER format,
  30083. * length on success else < 0 */
  30084. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30085. int withAlg)
  30086. {
  30087. int ret;
  30088. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30089. word32 pubKeyLen = (word32)sizeof(pubKey);
  30090. if (key == NULL || output == NULL) {
  30091. return BAD_FUNC_ARG;
  30092. }
  30093. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30094. if (ret == 0) {
  30095. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30096. X25519k, withAlg);
  30097. }
  30098. return ret;
  30099. }
  30100. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30101. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30102. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30103. ed448_key* key, word32 inSz)
  30104. {
  30105. int ret;
  30106. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30107. word32 privKeyLen = (word32)sizeof(privKey);
  30108. word32 pubKeyLen = (word32)sizeof(pubKey);
  30109. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30110. return BAD_FUNC_ARG;
  30111. }
  30112. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30113. pubKey, &pubKeyLen, ED448k);
  30114. if (ret == 0) {
  30115. if (pubKeyLen == 0) {
  30116. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30117. }
  30118. else {
  30119. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30120. pubKey, pubKeyLen, key);
  30121. }
  30122. }
  30123. return ret;
  30124. }
  30125. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30126. ed448_key* key, word32 inSz)
  30127. {
  30128. int ret;
  30129. byte pubKey[ED448_PUB_KEY_SIZE];
  30130. word32 pubKeyLen = (word32)sizeof(pubKey);
  30131. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30132. return BAD_FUNC_ARG;
  30133. }
  30134. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30135. pubKey, &pubKeyLen, ED448k);
  30136. if (ret == 0) {
  30137. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30138. }
  30139. return ret;
  30140. }
  30141. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30142. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30143. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30144. curve448_key* key, word32 inSz)
  30145. {
  30146. int ret;
  30147. byte privKey[CURVE448_KEY_SIZE];
  30148. word32 privKeyLen = CURVE448_KEY_SIZE;
  30149. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30150. return BAD_FUNC_ARG;
  30151. }
  30152. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30153. NULL, NULL, X448k);
  30154. if (ret == 0) {
  30155. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30156. }
  30157. return ret;
  30158. }
  30159. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30160. curve448_key* key, word32 inSz)
  30161. {
  30162. int ret;
  30163. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30164. word32 pubKeyLen = (word32)sizeof(pubKey);
  30165. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30166. return BAD_FUNC_ARG;
  30167. }
  30168. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30169. pubKey, &pubKeyLen, X448k);
  30170. if (ret == 0) {
  30171. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30172. }
  30173. return ret;
  30174. }
  30175. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30176. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30177. /* Write a Private ecc key, including public to DER format,
  30178. * length on success else < 0 */
  30179. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30180. {
  30181. if (key == NULL) {
  30182. return BAD_FUNC_ARG;
  30183. }
  30184. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30185. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30186. }
  30187. /* Write only private ecc key to DER format,
  30188. * length on success else < 0 */
  30189. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30190. {
  30191. if (key == NULL) {
  30192. return BAD_FUNC_ARG;
  30193. }
  30194. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30195. NULL, 0, output, inLen, ED448k);
  30196. }
  30197. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30198. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30199. /* Write private Curve448 key to DER format,
  30200. * length on success else < 0 */
  30201. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30202. {
  30203. int ret;
  30204. byte privKey[CURVE448_KEY_SIZE];
  30205. word32 privKeyLen = CURVE448_KEY_SIZE;
  30206. if (key == NULL) {
  30207. return BAD_FUNC_ARG;
  30208. }
  30209. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30210. if (ret == 0) {
  30211. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30212. X448k);
  30213. }
  30214. return ret;
  30215. }
  30216. /* Write a public Curve448 key to DER format,
  30217. * length on success else < 0 */
  30218. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30219. int withAlg)
  30220. {
  30221. int ret;
  30222. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30223. word32 pubKeyLen = (word32)sizeof(pubKey);
  30224. if (key == NULL || output == NULL) {
  30225. return BAD_FUNC_ARG;
  30226. }
  30227. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30228. if (ret == 0) {
  30229. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30230. X448k, withAlg);
  30231. }
  30232. return ret;
  30233. }
  30234. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30235. #ifndef WOLFSSL_ASN_TEMPLATE
  30236. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30237. /* Get raw Date only, no processing, 0 on success */
  30238. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30239. byte* format, int maxIdx)
  30240. {
  30241. int ret, length;
  30242. const byte *datePtr = NULL;
  30243. WOLFSSL_ENTER("GetBasicDate");
  30244. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30245. if (ret < 0)
  30246. return ret;
  30247. XMEMCPY(date, datePtr, length);
  30248. return 0;
  30249. }
  30250. #endif /* HAVE_OCSP || HAVE_CRL */
  30251. #endif /* WOLFSSL_ASN_TEMPLATE */
  30252. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30253. #ifndef WOLFSSL_ASN_TEMPLATE
  30254. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30255. int sz)
  30256. {
  30257. word32 idx = *inOutIdx;
  30258. word32 len;
  30259. byte tag;
  30260. WOLFSSL_ENTER("GetEnumerated");
  30261. *value = 0;
  30262. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30263. return ASN_PARSE_E;
  30264. if (tag != ASN_ENUMERATED)
  30265. return ASN_PARSE_E;
  30266. if ((int)idx >= sz)
  30267. return BUFFER_E;
  30268. len = input[idx++];
  30269. if (len > 4 || (int)(len + idx) > sz)
  30270. return ASN_PARSE_E;
  30271. while (len--) {
  30272. *value = *value << 8 | input[idx++];
  30273. }
  30274. *inOutIdx = idx;
  30275. return *value;
  30276. }
  30277. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30278. #ifdef WOLFSSL_ASN_TEMPLATE
  30279. /* ASN.1 template for OCSP single response.
  30280. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30281. */
  30282. static const ASNItem singleResponseASN[] = {
  30283. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30284. /* certId */
  30285. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30286. /* hashAlgorithm */
  30287. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30288. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30289. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30290. /* issuerNameHash */
  30291. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30292. /* issuerKeyHash */
  30293. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30294. /* serialNumber */
  30295. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30296. /* certStatus - CHOICE */
  30297. /* good [0] IMPLICIT NULL */
  30298. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30299. /* revoked [1] IMPLICIT RevokedInfo */
  30300. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30301. /* revocationTime */
  30302. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30303. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30304. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30305. /* crlReason */
  30306. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30307. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30308. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30309. /* thisUpdate */
  30310. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30311. /* nextUpdate */
  30312. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30313. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30314. /* singleExtensions */
  30315. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30316. };
  30317. enum {
  30318. SINGLERESPONSEASN_IDX_SEQ = 0,
  30319. SINGLERESPONSEASN_IDX_CID_SEQ,
  30320. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30321. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30322. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30323. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30324. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30325. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30326. SINGLERESPONSEASN_IDX_CS_GOOD,
  30327. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30328. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30329. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30330. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30331. SINGLERESPONSEASN_IDX_UNKNOWN,
  30332. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30333. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30334. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30335. SINGLERESPONSEASN_IDX_EXT,
  30336. };
  30337. /* Number of items in ASN.1 template for OCSP single response. */
  30338. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30339. #endif
  30340. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  30341. int wrapperSz, OcspEntry* single)
  30342. {
  30343. #ifndef WOLFSSL_ASN_TEMPLATE
  30344. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  30345. int length;
  30346. int ret;
  30347. byte tag;
  30348. WOLFSSL_ENTER("DecodeSingleResponse");
  30349. prevIndex = idx;
  30350. /* Wrapper around the Single Response */
  30351. if (GetSequence(source, &idx, &length, size) < 0)
  30352. return ASN_PARSE_E;
  30353. /* Wrapper around the CertID */
  30354. certIdIdx = idx;
  30355. if (GetSequence(source, &idx, &length, size) < 0)
  30356. return ASN_PARSE_E;
  30357. single->rawCertId = source + certIdIdx;
  30358. /* Hash algorithm */
  30359. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  30360. if (ret < 0)
  30361. return ret;
  30362. single->hashAlgoOID = oid;
  30363. /* Save reference to the hash of CN */
  30364. ret = GetOctetString(source, &idx, &length, size);
  30365. if (ret < 0)
  30366. return ret;
  30367. if (length > (int)sizeof(single->issuerHash))
  30368. return BUFFER_E;
  30369. XMEMCPY(single->issuerHash, source + idx, length);
  30370. idx += length;
  30371. /* Save reference to the hash of the issuer public key */
  30372. ret = GetOctetString(source, &idx, &length, size);
  30373. if (ret < 0)
  30374. return ret;
  30375. if (length > (int)sizeof(single->issuerKeyHash))
  30376. return BUFFER_E;
  30377. XMEMCPY(single->issuerKeyHash, source + idx, length);
  30378. idx += length;
  30379. /* Get serial number */
  30380. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  30381. &single->status->serialSz, size) < 0)
  30382. return ASN_PARSE_E;
  30383. single->rawCertIdSize = idx - certIdIdx;
  30384. if (idx >= size)
  30385. return BUFFER_E;
  30386. /* CertStatus */
  30387. switch (source[idx++])
  30388. {
  30389. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  30390. single->status->status = CERT_GOOD;
  30391. idx++;
  30392. break;
  30393. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  30394. single->status->status = CERT_REVOKED;
  30395. if (GetLength(source, &idx, &length, size) < 0)
  30396. return ASN_PARSE_E;
  30397. idx += length;
  30398. break;
  30399. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  30400. single->status->status = CERT_UNKNOWN;
  30401. idx++;
  30402. break;
  30403. default:
  30404. return ASN_PARSE_E;
  30405. }
  30406. if (idx >= size)
  30407. return BUFFER_E;
  30408. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30409. single->status->thisDateAsn = source + idx;
  30410. localIdx = 0;
  30411. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  30412. (byte*)&single->status->thisDateParsed.type,
  30413. &single->status->thisDateParsed.length, size - idx) < 0)
  30414. return ASN_PARSE_E;
  30415. if (idx + localIdx >= size)
  30416. return BUFFER_E;
  30417. XMEMCPY(single->status->thisDateParsed.data,
  30418. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  30419. single->status->thisDateParsed.length);
  30420. #endif
  30421. if (GetBasicDate(source, &idx, single->status->thisDate,
  30422. &single->status->thisDateFormat, size) < 0)
  30423. return ASN_PARSE_E;
  30424. #ifndef NO_ASN_TIME_CHECK
  30425. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30426. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  30427. return ASN_BEFORE_DATE_E;
  30428. #endif
  30429. #endif
  30430. /* The following items are optional. Only check for them if there is more
  30431. * unprocessed data in the singleResponse wrapper. */
  30432. localIdx = idx;
  30433. if (((int)(idx - prevIndex) < wrapperSz) &&
  30434. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30435. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  30436. {
  30437. idx++;
  30438. if (GetLength(source, &idx, &length, size) < 0)
  30439. return ASN_PARSE_E;
  30440. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30441. single->status->nextDateAsn = source + idx;
  30442. localIdx = 0;
  30443. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  30444. (byte*)&single->status->nextDateParsed.type,
  30445. &single->status->nextDateParsed.length, size - idx) < 0)
  30446. return ASN_PARSE_E;
  30447. if (idx + localIdx >= size)
  30448. return BUFFER_E;
  30449. XMEMCPY(single->status->nextDateParsed.data,
  30450. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  30451. single->status->nextDateParsed.length);
  30452. #endif
  30453. if (GetBasicDate(source, &idx, single->status->nextDate,
  30454. &single->status->nextDateFormat, size) < 0)
  30455. return ASN_PARSE_E;
  30456. #ifndef NO_ASN_TIME_CHECK
  30457. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30458. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  30459. return ASN_AFTER_DATE_E;
  30460. #endif
  30461. #endif
  30462. }
  30463. /* Skip the optional extensions in singleResponse. */
  30464. localIdx = idx;
  30465. if (((int)(idx - prevIndex) < wrapperSz) &&
  30466. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30467. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30468. {
  30469. idx++;
  30470. if (GetLength(source, &idx, &length, size) < 0)
  30471. return ASN_PARSE_E;
  30472. idx += length;
  30473. }
  30474. *ioIndex = idx;
  30475. return 0;
  30476. #else
  30477. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  30478. int ret = 0;
  30479. CertStatus* cs = NULL;
  30480. word32 serialSz;
  30481. word32 issuerHashLen;
  30482. word32 issuerKeyHashLen;
  30483. word32 thisDateLen;
  30484. word32 nextDateLen;
  30485. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30486. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30487. WOLFSSL_ASN1_TIME *at;
  30488. #endif
  30489. (void)wrapperSz;
  30490. WOLFSSL_ENTER("DecodeSingleResponse");
  30491. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  30492. if (ret == 0) {
  30493. /* Certificate Status field. */
  30494. cs = single->status;
  30495. /* Set maximum lengths for data. */
  30496. issuerHashLen = OCSP_DIGEST_SIZE;
  30497. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  30498. serialSz = EXTERNAL_SERIAL_SIZE;
  30499. thisDateLen = MAX_DATE_SIZE;
  30500. nextDateLen = MAX_DATE_SIZE;
  30501. /* Set OID type, buffers to hold data and variables to hold size. */
  30502. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  30503. oidHashType);
  30504. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  30505. single->issuerHash, &issuerHashLen);
  30506. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  30507. single->issuerKeyHash, &issuerKeyHashLen);
  30508. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  30509. &serialSz);
  30510. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  30511. cs->thisDate, &thisDateLen);
  30512. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  30513. cs->nextDate, &nextDateLen);
  30514. /* TODO: decode revoked time and reason. */
  30515. /* Decode OCSP single response. */
  30516. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  30517. 1, source, ioIndex, size);
  30518. }
  30519. /* Validate the issuer hash length is the size required. */
  30520. if ((ret == 0) && (issuerHashLen != OCSP_DIGEST_SIZE)) {
  30521. ret = ASN_PARSE_E;
  30522. }
  30523. /* Validate the issuer key hash length is the size required. */
  30524. if ((ret == 0) && (issuerKeyHashLen != OCSP_DIGEST_SIZE)) {
  30525. ret = ASN_PARSE_E;
  30526. }
  30527. if (ret == 0) {
  30528. /* Store serial size. */
  30529. cs->serialSz = serialSz;
  30530. /* Determine status by which item was found. */
  30531. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  30532. cs->status = CERT_GOOD;
  30533. }
  30534. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  30535. cs->status = CERT_REVOKED;
  30536. }
  30537. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  30538. cs->status = CERT_UNKNOWN;
  30539. }
  30540. /* Store the thisDate format - only one possible. */
  30541. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  30542. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30543. /* Check date is a valid string and BEFORE now. */
  30544. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  30545. ret = ASN_BEFORE_DATE_E;
  30546. }
  30547. }
  30548. if (ret == 0) {
  30549. #endif
  30550. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30551. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30552. /* Store ASN.1 version of thisDate. */
  30553. cs->thisDateAsn = GetASNItem_Addr(
  30554. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  30555. at = &cs->thisDateParsed;
  30556. at->type = ASN_GENERALIZED_TIME;
  30557. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  30558. at->length = thisDateLen;
  30559. #endif
  30560. }
  30561. if ((ret == 0) &&
  30562. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30563. /* Store the nextDate format - only one possible. */
  30564. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  30565. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30566. /* Check date is a valid string and AFTER now. */
  30567. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  30568. ret = ASN_AFTER_DATE_E;
  30569. }
  30570. }
  30571. if ((ret == 0) &&
  30572. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30573. #endif
  30574. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30575. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30576. /* Store ASN.1 version of thisDate. */
  30577. cs->nextDateAsn = GetASNItem_Addr(
  30578. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  30579. at = &cs->nextDateParsed;
  30580. at->type = ASN_GENERALIZED_TIME;
  30581. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  30582. at->length = nextDateLen;
  30583. #endif
  30584. }
  30585. if (ret == 0) {
  30586. /* OcspEntry now used. */
  30587. single->used = 1;
  30588. }
  30589. FREE_ASNGETDATA(dataASN, NULL);
  30590. return ret;
  30591. #endif
  30592. }
  30593. #ifdef WOLFSSL_ASN_TEMPLATE
  30594. /* ASN.1 template for OCSP response extension header.
  30595. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30596. */
  30597. static const ASNItem respExtHdrASN[] = {
  30598. /* responseExtensions */
  30599. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  30600. /* extensions */
  30601. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30602. };
  30603. enum {
  30604. RESPEXTHDRASN_IDX_EXT = 0,
  30605. RESPEXTHDRASN_IDX_EXT_SEQ,
  30606. };
  30607. /* Number of items in ASN.1 template for OCSP response extension header. */
  30608. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  30609. #endif
  30610. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  30611. OcspResponse* resp, word32 sz)
  30612. {
  30613. #ifndef WOLFSSL_ASN_TEMPLATE
  30614. word32 idx = *ioIndex;
  30615. int length;
  30616. int ext_bound; /* boundary index for the sequence of extensions */
  30617. word32 oid;
  30618. int ret;
  30619. byte tag;
  30620. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30621. if ((idx + 1) > sz)
  30622. return BUFFER_E;
  30623. if (GetASNTag(source, &idx, &tag, sz) < 0)
  30624. return ASN_PARSE_E;
  30625. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30626. return ASN_PARSE_E;
  30627. if (GetLength(source, &idx, &length, sz) < 0)
  30628. return ASN_PARSE_E;
  30629. if (GetSequence(source, &idx, &length, sz) < 0)
  30630. return ASN_PARSE_E;
  30631. ext_bound = idx + length;
  30632. while (idx < (word32)ext_bound) {
  30633. word32 localIdx;
  30634. if (GetSequence(source, &idx, &length, sz) < 0) {
  30635. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  30636. return ASN_PARSE_E;
  30637. }
  30638. oid = 0;
  30639. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  30640. WOLFSSL_MSG("\tfail: OBJECT ID");
  30641. return ASN_PARSE_E;
  30642. }
  30643. /* check for critical flag */
  30644. if ((idx + 1) > (word32)sz) {
  30645. WOLFSSL_MSG("\tfail: malformed buffer");
  30646. return BUFFER_E;
  30647. }
  30648. localIdx = idx;
  30649. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  30650. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  30651. ret = GetBoolean(source, &idx, sz);
  30652. if (ret < 0)
  30653. return ret;
  30654. }
  30655. ret = GetOctetString(source, &idx, &length, sz);
  30656. if (ret < 0)
  30657. return ret;
  30658. if (oid == OCSP_NONCE_OID) {
  30659. /* get data inside extra OCTET_STRING */
  30660. ret = GetOctetString(source, &idx, &length, sz);
  30661. if (ret < 0)
  30662. return ret;
  30663. resp->nonce = source + idx;
  30664. resp->nonceSz = length;
  30665. }
  30666. idx += length;
  30667. }
  30668. *ioIndex = idx;
  30669. return 0;
  30670. #else
  30671. /* certExtASN_Length is greater than respExtHdrASN_Length */
  30672. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  30673. int ret = 0;
  30674. word32 idx = *ioIndex;
  30675. word32 maxIdx = 0;
  30676. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30677. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  30678. if (ret == 0) {
  30679. /* Check for header and move past. */
  30680. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  30681. source, &idx, sz);
  30682. }
  30683. if (ret == 0) {
  30684. /* Keep end extensions index for total length check. */
  30685. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  30686. }
  30687. /* Step through all extensions. */
  30688. while ((ret == 0) && (idx < maxIdx)) {
  30689. /* Clear dynamic data, set OID type to expect. */
  30690. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  30691. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  30692. /* TODO: check criticality. */
  30693. /* Decode OCSP response extension. */
  30694. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  30695. source, &idx, sz);
  30696. if (ret == 0) {
  30697. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  30698. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  30699. if (oid == OCSP_NONCE_OID) {
  30700. /* Extract nonce data. */
  30701. ret = GetOctetString(source, &idx, &length, sz);
  30702. if (ret >= 0) {
  30703. ret = 0;
  30704. /* get data inside extra OCTET_STRING */
  30705. resp->nonce = source + idx;
  30706. resp->nonceSz = length;
  30707. }
  30708. }
  30709. /* Ignore all other extension types. */
  30710. /* Skip over rest of extension. */
  30711. idx += length;
  30712. }
  30713. }
  30714. /* Return index after extensions. */
  30715. *ioIndex = idx;
  30716. FREE_ASNGETDATA(dataASN, resp->heap);
  30717. return ret;
  30718. #endif
  30719. }
  30720. #ifdef WOLFSSL_ASN_TEMPLATE
  30721. /* ASN.1 template for OCSP ResponseData.
  30722. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30723. */
  30724. static const ASNItem ocspRespDataASN[] = {
  30725. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30726. /* version DEFAULT v1 */
  30727. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30728. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  30729. /* byName */
  30730. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  30731. /* byKey */
  30732. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  30733. /* producedAt */
  30734. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  30735. /* responses */
  30736. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  30737. /* responseExtensions */
  30738. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  30739. };
  30740. enum {
  30741. OCSPRESPDATAASN_IDX_SEQ = 0,
  30742. OCSPRESPDATAASN_IDX_VER_PRESENT,
  30743. OCSPRESPDATAASN_IDX_VER,
  30744. OCSPRESPDATAASN_IDX_BYNAME,
  30745. OCSPRESPDATAASN_IDX_BYKEY,
  30746. OCSPRESPDATAASN_IDX_PA,
  30747. OCSPRESPDATAASN_IDX_RESP,
  30748. OCSPRESPDATAASN_IDX_RESPEXT,
  30749. };
  30750. /* Number of items in ASN.1 template for OCSP ResponseData. */
  30751. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  30752. #endif
  30753. static int DecodeResponseData(byte* source, word32* ioIndex,
  30754. OcspResponse* resp, word32 size)
  30755. {
  30756. #ifndef WOLFSSL_ASN_TEMPLATE
  30757. word32 idx = *ioIndex, prev_idx, localIdx;
  30758. int length;
  30759. int version;
  30760. int ret;
  30761. byte tag;
  30762. int wrapperSz;
  30763. OcspEntry* single;
  30764. WOLFSSL_ENTER("DecodeResponseData");
  30765. resp->response = source + idx;
  30766. prev_idx = idx;
  30767. if (GetSequence(source, &idx, &length, size) < 0)
  30768. return ASN_PARSE_E;
  30769. resp->responseSz = length + idx - prev_idx;
  30770. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  30771. * item isn't an EXPLICIT[0], then set version to zero and move
  30772. * onto the next item.
  30773. */
  30774. localIdx = idx;
  30775. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30776. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  30777. {
  30778. idx += 2; /* Eat the value and length */
  30779. if (GetMyVersion(source, &idx, &version, size) < 0)
  30780. return ASN_PARSE_E;
  30781. } else
  30782. version = 0;
  30783. localIdx = idx;
  30784. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30785. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  30786. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  30787. {
  30788. idx++; /* advance past ASN tag */
  30789. if (GetLength(source, &idx, &length, size) < 0)
  30790. return ASN_PARSE_E;
  30791. idx += length;
  30792. }
  30793. else
  30794. return ASN_PARSE_E;
  30795. /* save pointer to the producedAt time */
  30796. if (GetBasicDate(source, &idx, resp->producedDate,
  30797. &resp->producedDateFormat, size) < 0)
  30798. return ASN_PARSE_E;
  30799. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  30800. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  30801. return ASN_PARSE_E;
  30802. localIdx = idx;
  30803. single = resp->single;
  30804. while (idx - localIdx < (word32)wrapperSz) {
  30805. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  30806. if (ret < 0)
  30807. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  30808. if (idx - localIdx < (word32)wrapperSz) {
  30809. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30810. DYNAMIC_TYPE_OCSP_ENTRY);
  30811. if (single->next == NULL) {
  30812. return MEMORY_E;
  30813. }
  30814. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30815. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30816. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30817. if (single->next->status == NULL) {
  30818. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30819. single->next = NULL;
  30820. return MEMORY_E;
  30821. }
  30822. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30823. single->next->isDynamic = 1;
  30824. single = single->next;
  30825. }
  30826. }
  30827. /*
  30828. * Check the length of the ResponseData against the current index to
  30829. * see if there are extensions, they are optional.
  30830. */
  30831. if (idx - prev_idx < resp->responseSz)
  30832. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  30833. return ASN_PARSE_E;
  30834. *ioIndex = idx;
  30835. return 0;
  30836. #else
  30837. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  30838. int ret = 0;
  30839. byte version;
  30840. word32 dateSz, idx = *ioIndex;
  30841. OcspEntry* single = NULL;
  30842. WOLFSSL_ENTER("DecodeResponseData");
  30843. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  30844. if (ret == 0) {
  30845. resp->response = source + idx;
  30846. /* Default, not present, is v1 = 0. */
  30847. version = 0;
  30848. /* Max size of date supported. */
  30849. dateSz = MAX_DATE_SIZE;
  30850. /* Set the where to put version an produced date. */
  30851. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  30852. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  30853. &dateSz);
  30854. /* Decode the ResponseData. */
  30855. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  30856. 1, source, ioIndex, size);
  30857. }
  30858. /* Only support v1 == 0 */
  30859. if ((ret == 0) && (version != 0)) {
  30860. ret = ASN_PARSE_E;
  30861. }
  30862. /* Ensure date is a minimal size. */
  30863. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  30864. ret = ASN_PARSE_E;
  30865. }
  30866. if (ret == 0) {
  30867. /* TODO: use byName/byKey fields. */
  30868. /* Store size of response. */
  30869. resp->responseSz = *ioIndex - idx;
  30870. /* Store date format/tag. */
  30871. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  30872. /* Get the index of the responses SEQUENCE. */
  30873. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  30874. /* Start with the pre-existing OcspEntry. */
  30875. single = resp->single;
  30876. }
  30877. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  30878. /* Allocate and use a new OCSP entry if this is used. */
  30879. if (single->used) {
  30880. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  30881. DYNAMIC_TYPE_OCSP_ENTRY);
  30882. if (single->next == NULL) {
  30883. ret = MEMORY_E;
  30884. }
  30885. else {
  30886. XMEMSET(single->next, 0, sizeof(OcspEntry));
  30887. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  30888. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  30889. if (single->next->status == NULL) {
  30890. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  30891. single->next = NULL;
  30892. ret = MEMORY_E;
  30893. }
  30894. else {
  30895. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  30896. /* Entry to be freed. */
  30897. single->next->isDynamic = 1;
  30898. /* used will be 0 (false) */
  30899. single = single->next;
  30900. }
  30901. }
  30902. }
  30903. if (ret == 0) {
  30904. /* Decode SingleResponse into OcspEntry. */
  30905. ret = DecodeSingleResponse(source, &idx,
  30906. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  30907. dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  30908. /* single->used set on successful decode. */
  30909. }
  30910. }
  30911. /* Check if there were extensions. */
  30912. if ((ret == 0) &&
  30913. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  30914. /* Get index of [1] */
  30915. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  30916. /* Decode the response extensions. */
  30917. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  30918. ret = ASN_PARSE_E;
  30919. }
  30920. }
  30921. FREE_ASNGETDATA(dataASN, resp->heap);
  30922. return ret;
  30923. #endif
  30924. }
  30925. #ifndef WOLFSSL_ASN_TEMPLATE
  30926. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30927. static int DecodeCerts(byte* source,
  30928. word32* ioIndex, OcspResponse* resp, word32 size)
  30929. {
  30930. word32 idx = *ioIndex;
  30931. byte tag;
  30932. WOLFSSL_ENTER("DecodeCerts");
  30933. if (GetASNTag(source, &idx, &tag, size) < 0)
  30934. return ASN_PARSE_E;
  30935. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  30936. {
  30937. int length;
  30938. if (GetLength(source, &idx, &length, size) < 0)
  30939. return ASN_PARSE_E;
  30940. if (GetSequence(source, &idx, &length, size) < 0)
  30941. return ASN_PARSE_E;
  30942. resp->cert = source + idx;
  30943. resp->certSz = length;
  30944. idx += length;
  30945. }
  30946. *ioIndex = idx;
  30947. return 0;
  30948. }
  30949. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  30950. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30951. #ifdef WOLFSSL_ASN_TEMPLATE
  30952. /* ASN.1 template for BasicOCSPResponse.
  30953. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30954. */
  30955. static const ASNItem ocspBasicRespASN[] = {
  30956. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30957. /* tbsResponseData */
  30958. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  30959. /* signatureAlgorithm */
  30960. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  30961. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  30962. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  30963. /* parameters */
  30964. #ifdef WC_RSA_PSS
  30965. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  30966. #endif
  30967. /* signature */
  30968. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  30969. /* certs */
  30970. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30971. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  30972. };
  30973. enum {
  30974. OCSPBASICRESPASN_IDX_SEQ = 0,
  30975. OCSPBASICRESPASN_IDX_TBS_SEQ,
  30976. OCSPBASICRESPASN_IDX_SIGALGO,
  30977. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  30978. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  30979. #ifdef WC_RSA_PSS
  30980. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  30981. #endif
  30982. OCSPBASICRESPASN_IDX_SIGNATURE,
  30983. OCSPBASICRESPASN_IDX_CERTS,
  30984. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  30985. };
  30986. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  30987. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  30988. #endif /* WOLFSSL_ASN_TEMPLATE */
  30989. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  30990. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  30991. {
  30992. #ifndef WOLFSSL_ASN_TEMPLATE
  30993. int length;
  30994. word32 idx = *ioIndex;
  30995. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  30996. word32 end_index;
  30997. #endif
  30998. int ret;
  30999. int sigLength;
  31000. const byte* sigParams = NULL;
  31001. word32 sigParamsSz = 0;
  31002. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31003. (void)heap;
  31004. if (GetSequence(source, &idx, &length, size) < 0)
  31005. return ASN_PARSE_E;
  31006. if (idx + length > size)
  31007. return ASN_INPUT_E;
  31008. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31009. end_index = idx + length;
  31010. #endif
  31011. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  31012. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31013. /* Get the signature algorithm */
  31014. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  31015. return ASN_PARSE_E;
  31016. }
  31017. #ifdef WC_RSA_PSS
  31018. else if (resp->sigOID == CTC_RSASSAPSS) {
  31019. word32 sz;
  31020. int len;
  31021. const byte* params;
  31022. sz = idx;
  31023. params = source + idx;
  31024. if (GetSequence(source, &idx, &len, size) < 0)
  31025. ret = ASN_PARSE_E;
  31026. if (ret == 0) {
  31027. idx += len;
  31028. sigParams = params;
  31029. sigParamsSz = idx - sz;
  31030. }
  31031. }
  31032. #endif
  31033. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31034. if (ret != 0)
  31035. return ret;
  31036. resp->sigSz = sigLength;
  31037. resp->sig = source + idx;
  31038. idx += sigLength;
  31039. /*
  31040. * Check the length of the BasicOcspResponse against the current index to
  31041. * see if there are certificates, they are optional.
  31042. */
  31043. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31044. if (idx < end_index)
  31045. {
  31046. int cert_inited = 0;
  31047. #ifdef WOLFSSL_SMALL_STACK
  31048. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31049. DYNAMIC_TYPE_TMP_BUFFER);
  31050. if (cert == NULL)
  31051. return MEMORY_E;
  31052. #else
  31053. DecodedCert cert[1];
  31054. #endif
  31055. do {
  31056. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31057. ret = ASN_PARSE_E;
  31058. break;
  31059. }
  31060. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31061. cert_inited = 1;
  31062. /* Don't verify if we don't have access to Cert Manager. */
  31063. ret = ParseCertRelative(cert, CERT_TYPE,
  31064. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31065. cm);
  31066. if (ret < 0) {
  31067. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31068. break;
  31069. }
  31070. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31071. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31072. if (XMEMCMP(cert->subjectHash,
  31073. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31074. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31075. }
  31076. else {
  31077. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31078. #ifdef OPENSSL_EXTRA
  31079. resp->verifyError = OCSP_BAD_ISSUER;
  31080. #else
  31081. ret = BAD_OCSP_RESPONDER;
  31082. break;
  31083. #endif
  31084. }
  31085. }
  31086. #endif
  31087. /* ConfirmSignature is blocking here */
  31088. ret = ConfirmSignature(
  31089. &cert->sigCtx,
  31090. resp->response, resp->responseSz,
  31091. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31092. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31093. NULL);
  31094. if (ret != 0) {
  31095. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31096. ret = ASN_OCSP_CONFIRM_E;
  31097. break;
  31098. }
  31099. } while(0);
  31100. if (cert_inited)
  31101. FreeDecodedCert(cert);
  31102. #ifdef WOLFSSL_SMALL_STACK
  31103. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31104. #endif
  31105. if (ret != 0)
  31106. return ret;
  31107. }
  31108. else
  31109. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31110. {
  31111. Signer* ca;
  31112. int sigValid = -1;
  31113. #ifndef NO_SKID
  31114. ca = GetCA(cm, resp->single->issuerKeyHash);
  31115. #else
  31116. ca = GetCA(cm, resp->single->issuerHash);
  31117. #endif
  31118. if (ca) {
  31119. SignatureCtx sigCtx;
  31120. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31121. /* ConfirmSignature is blocking here */
  31122. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31123. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31124. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31125. NULL);
  31126. }
  31127. if (ca == NULL || sigValid != 0) {
  31128. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31129. return ASN_OCSP_CONFIRM_E;
  31130. }
  31131. (void)noVerify;
  31132. }
  31133. *ioIndex = idx;
  31134. return 0;
  31135. #else
  31136. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31137. int ret = 0;
  31138. word32 idx = *ioIndex;
  31139. const byte* sigParams = NULL;
  31140. word32 sigParamsSz = 0;
  31141. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31142. #ifdef WOLFSSL_SMALL_STACK
  31143. DecodedCert* cert = NULL;
  31144. #else
  31145. DecodedCert cert[1];
  31146. #endif
  31147. int certInit = 0;
  31148. #endif
  31149. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31150. (void)heap;
  31151. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31152. if (ret == 0) {
  31153. /* Set expecting signature OID. */
  31154. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31155. /* Decode BasicOCSPResponse. */
  31156. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31157. 1, source, &idx, size);
  31158. }
  31159. if (ret == 0) {
  31160. word32 dataIdx = 0;
  31161. /* Decode the response data. */
  31162. if (DecodeResponseData(
  31163. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31164. &dataIdx, resp,
  31165. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31166. ) < 0) {
  31167. ret = ASN_PARSE_E;
  31168. }
  31169. }
  31170. #ifdef WC_RSA_PSS
  31171. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31172. sigParams = GetASNItem_Addr(
  31173. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31174. source);
  31175. sigParamsSz =
  31176. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31177. source);
  31178. }
  31179. #endif
  31180. if (ret == 0) {
  31181. /* Get the signature OID and signature. */
  31182. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31183. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31184. &resp->sigSz);
  31185. }
  31186. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31187. if ((ret == 0) &&
  31188. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31189. /* TODO: support more than one certificate. */
  31190. /* Store reference to certificate BER data. */
  31191. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31192. &resp->certSz);
  31193. /* Allocate a certificate object to decode cert into. */
  31194. #ifdef WOLFSSL_SMALL_STACK
  31195. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31196. DYNAMIC_TYPE_TMP_BUFFER);
  31197. if (cert == NULL) {
  31198. ret = MEMORY_E;
  31199. }
  31200. }
  31201. if ((ret == 0) &&
  31202. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31203. #endif
  31204. /* Initialize the crtificate object. */
  31205. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31206. certInit = 1;
  31207. /* Parse the certificate and don't verify if we don't have access to
  31208. * Cert Manager. */
  31209. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31210. cm);
  31211. if (ret < 0) {
  31212. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31213. }
  31214. }
  31215. if ((ret == 0) &&
  31216. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31217. /* TODO: ConfirmSignature is blocking here */
  31218. /* Check the signature of the response. */
  31219. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31220. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31221. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31222. if (ret != 0) {
  31223. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31224. ret = ASN_OCSP_CONFIRM_E;
  31225. }
  31226. }
  31227. if ((ret == 0) &&
  31228. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31229. #else
  31230. if (ret == 0)
  31231. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31232. {
  31233. Signer* ca;
  31234. int sigValid = -1;
  31235. /* Resonse didn't have a certificate - lookup CA. */
  31236. #ifndef NO_SKID
  31237. ca = GetCA(cm, resp->single->issuerKeyHash);
  31238. #else
  31239. ca = GetCA(cm, resp->single->issuerHash);
  31240. #endif
  31241. if (ca) {
  31242. SignatureCtx sigCtx;
  31243. /* Initialize he signature context. */
  31244. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31245. /* TODO: ConfirmSignature is blocking here */
  31246. /* Check the signature of the response CA public key. */
  31247. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31248. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31249. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31250. NULL);
  31251. }
  31252. if ((ca == NULL) || (sigValid != 0)) {
  31253. /* Didn't find certificate or signature verificate failed. */
  31254. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31255. ret = ASN_OCSP_CONFIRM_E;
  31256. }
  31257. }
  31258. if (ret == 0) {
  31259. /* Update the position to after response data. */
  31260. *ioIndex = idx;
  31261. }
  31262. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31263. if (certInit) {
  31264. FreeDecodedCert(cert);
  31265. }
  31266. #ifdef WOLFSSL_SMALL_STACK
  31267. if (cert != NULL) {
  31268. /* Dispose of certificate object. */
  31269. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31270. }
  31271. #endif
  31272. #endif
  31273. FREE_ASNGETDATA(dataASN, heap);
  31274. return ret;
  31275. #endif /* WOLFSSL_ASN_TEMPLATE */
  31276. }
  31277. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31278. byte* source, word32 inSz, void* heap)
  31279. {
  31280. WOLFSSL_ENTER("InitOcspResponse");
  31281. XMEMSET(status, 0, sizeof(CertStatus));
  31282. XMEMSET(single, 0, sizeof(OcspEntry));
  31283. XMEMSET(resp, 0, sizeof(OcspResponse));
  31284. single->status = status;
  31285. resp->responseStatus = -1;
  31286. resp->single = single;
  31287. resp->source = source;
  31288. resp->maxIdx = inSz;
  31289. resp->heap = heap;
  31290. }
  31291. void FreeOcspResponse(OcspResponse* resp)
  31292. {
  31293. OcspEntry *single, *next;
  31294. if (resp != NULL) {
  31295. for (single = resp->single; single; single = next) {
  31296. next = single->next;
  31297. if (single->isDynamic) {
  31298. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31299. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31300. }
  31301. }
  31302. }
  31303. }
  31304. #ifdef WOLFSSL_ASN_TEMPLATE
  31305. /* ASN.1 template for OCSPResponse.
  31306. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31307. */
  31308. static const ASNItem ocspResponseASN[] = {
  31309. /* OCSPResponse ::= SEQUENCE */
  31310. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31311. /* responseStatus OCSPResponseStatus */
  31312. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31313. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31314. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31315. /* ResponseBytes ::= SEQUENCE */
  31316. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31317. /* responseType OBJECT IDENTIFIER */
  31318. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31319. /* response OCTET STRING */
  31320. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  31321. };
  31322. enum {
  31323. OCSPRESPONSEASN_IDX_SEQ = 0,
  31324. OCSPRESPONSEASN_IDX_STATUS,
  31325. OCSPRESPONSEASN_IDX_BYTES,
  31326. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  31327. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  31328. OCSPRESPONSEASN_IDX_BYTES_VAL,
  31329. };
  31330. /* Number of items in ASN.1 template for OCSPResponse. */
  31331. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  31332. #endif /* WOLFSSL_ASN_TEMPLATE */
  31333. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  31334. {
  31335. #ifndef WOLFSSL_ASN_TEMPLATE
  31336. int ret;
  31337. int length = 0;
  31338. word32 idx = 0;
  31339. byte* source = resp->source;
  31340. word32 size = resp->maxIdx;
  31341. word32 oid;
  31342. byte tag;
  31343. WOLFSSL_ENTER("OcspResponseDecode");
  31344. /* peel the outer SEQUENCE wrapper */
  31345. if (GetSequence(source, &idx, &length, size) < 0) {
  31346. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31347. return ASN_PARSE_E;
  31348. }
  31349. /* First get the responseStatus, an ENUMERATED */
  31350. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  31351. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31352. return ASN_PARSE_E;
  31353. }
  31354. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  31355. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31356. return 0;
  31357. }
  31358. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  31359. if (idx >= size) {
  31360. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31361. return ASN_PARSE_E;
  31362. }
  31363. if (GetASNTag(source, &idx, &tag, size) < 0) {
  31364. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31365. return ASN_PARSE_E;
  31366. }
  31367. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  31368. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31369. return ASN_PARSE_E;
  31370. }
  31371. if (GetLength(source, &idx, &length, size) < 0) {
  31372. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31373. return ASN_PARSE_E;
  31374. }
  31375. /* Get the responseBytes SEQUENCE */
  31376. if (GetSequence(source, &idx, &length, size) < 0) {
  31377. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31378. return ASN_PARSE_E;
  31379. }
  31380. /* Check ObjectID for the resposeBytes */
  31381. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  31382. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31383. return ASN_PARSE_E;
  31384. }
  31385. if (oid != OCSP_BASIC_OID) {
  31386. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31387. return ASN_PARSE_E;
  31388. }
  31389. ret = GetOctetString(source, &idx, &length, size);
  31390. if (ret < 0) {
  31391. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31392. return ret;
  31393. }
  31394. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  31395. if (ret < 0) {
  31396. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31397. return ret;
  31398. }
  31399. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31400. return 0;
  31401. #else
  31402. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  31403. int ret = 0;
  31404. word32 idx = 0, size = resp->maxIdx;
  31405. byte* source = resp->source;
  31406. byte status;
  31407. byte* basic;
  31408. word32 basicSz;
  31409. WOLFSSL_ENTER("OcspResponseDecode");
  31410. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  31411. if (ret == 0) {
  31412. /* Set variable to put status in and expect OCSP OID. */
  31413. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  31414. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  31415. /* Decode OCSPResponse (and ResponseBytes). */
  31416. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  31417. source, &idx, size);
  31418. }
  31419. if (ret == 0) {
  31420. /* Get response. */
  31421. resp->responseStatus = status;
  31422. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  31423. == OCSP_BASIC_OID) {
  31424. /* Get reference to BasicOCSPResponse. */
  31425. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  31426. &basicSz);
  31427. idx = 0;
  31428. /* Decode BasicOCSPResponse. */
  31429. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  31430. noVerify);
  31431. }
  31432. /* Only support BasicOCSPResponse. */
  31433. else {
  31434. ret = ASN_PARSE_E;
  31435. }
  31436. }
  31437. FREE_ASNGETDATA(dataASN, resp->heap);
  31438. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31439. return ret;
  31440. #endif /* WOLFSSL_ASN_TEMPLATE */
  31441. }
  31442. #ifdef WOLFSSL_ASN_TEMPLATE
  31443. /* ASN.1 template for OCSP nonce extension.
  31444. * RFC 6960, 4.4.1 - Nonce
  31445. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  31446. */
  31447. static const ASNItem ocspNonceExtASN[] = {
  31448. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31449. /* Extension */
  31450. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31451. /* extnId */
  31452. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  31453. /* critcal not encoded. */
  31454. /* extnValue */
  31455. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  31456. /* nonce */
  31457. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  31458. };
  31459. enum {
  31460. OCSPNONCEEXTASN_IDX_SEQ = 0,
  31461. OCSPNONCEEXTASN_IDX_EXT,
  31462. OCSPNONCEEXTASN_IDX_EXT_OID,
  31463. OCSPNONCEEXTASN_IDX_EXT_VAL,
  31464. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  31465. };
  31466. /* Number of items in ASN.1 template for OCSP nonce extension. */
  31467. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  31468. #endif /* WOLFSSL_ASN_TEMPLATE */
  31469. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  31470. {
  31471. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  31472. 0x30, 0x01, 0x02 };
  31473. #ifndef WOLFSSL_ASN_TEMPLATE
  31474. byte seqArray[5][MAX_SEQ_SZ];
  31475. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  31476. WOLFSSL_ENTER("SetOcspReqExtensions");
  31477. if (!req || !output || !req->nonceSz)
  31478. return 0;
  31479. totalSz += req->nonceSz;
  31480. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  31481. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  31482. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  31483. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  31484. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  31485. if (totalSz > size)
  31486. return 0;
  31487. totalSz = 0;
  31488. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  31489. totalSz += seqSz[4];
  31490. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  31491. totalSz += seqSz[3];
  31492. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  31493. totalSz += seqSz[2];
  31494. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  31495. totalSz += (word32)sizeof(NonceObjId);
  31496. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  31497. totalSz += seqSz[1];
  31498. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  31499. totalSz += seqSz[0];
  31500. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  31501. totalSz += req->nonceSz;
  31502. return totalSz;
  31503. #else
  31504. int ret = 0;
  31505. WOLFSSL_ENTER("SetOcspReqExtensions");
  31506. /* Check request has nonce to write in extension. */
  31507. if (req != NULL && req->nonceSz != 0) {
  31508. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  31509. int sz;
  31510. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  31511. /* Set nonce extension OID and nonce. */
  31512. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  31513. sizeof(NonceObjId));
  31514. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  31515. req->nonceSz);
  31516. /* Calculate size of nonce extension. */
  31517. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31518. &sz);
  31519. /* Check buffer big enough for encoding if supplied. */
  31520. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31521. ret = BUFFER_E;
  31522. }
  31523. if ((ret == 0) && (output != NULL)) {
  31524. /* Encode nonce extension. */
  31525. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31526. output);
  31527. }
  31528. if (ret == 0) {
  31529. /* Return size of encoding. */
  31530. ret = sz;
  31531. }
  31532. FREE_ASNSETDATA(dataASN, req->heap);
  31533. }
  31534. return ret;
  31535. #endif /* WOLFSSL_ASN_TEMPLATE */
  31536. }
  31537. #ifdef WOLFSSL_ASN_TEMPLATE
  31538. /* ASN.1 template for OCSPRequest.
  31539. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  31540. */
  31541. static const ASNItem ocspRequestASN[] = {
  31542. /* OCSPRequest */
  31543. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31544. /* tbsRequest */
  31545. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31546. /* version not written - v1 */
  31547. /* requestorName not written */
  31548. /* requestList */
  31549. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31550. /* Request */
  31551. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  31552. /* reqCert */
  31553. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  31554. /* hashAlgorithm */
  31555. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  31556. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  31557. /* issuerNameHash */
  31558. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31559. /* issuerKeyHash */
  31560. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31561. /* serialNumber */
  31562. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  31563. /* requestExtensions */
  31564. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  31565. /* optionalSignature not written. */
  31566. };
  31567. enum {
  31568. OCSPREQUESTASN_IDX_SEQ = 0,
  31569. OCSPREQUESTASN_IDX_TBS,
  31570. OCSPREQUESTASN_IDX_TBS_SEQ,
  31571. OCSPREQUESTASN_IDX_TBS_LIST,
  31572. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  31573. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  31574. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  31575. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  31576. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  31577. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  31578. OCSPREQUESTASN_IDX_TBS_REQEXT,
  31579. };
  31580. /* Number of items in ASN.1 template for OCSPRequest. */
  31581. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  31582. #endif
  31583. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  31584. {
  31585. #ifndef WOLFSSL_ASN_TEMPLATE
  31586. byte seqArray[5][MAX_SEQ_SZ];
  31587. /* The ASN.1 of the OCSP Request is an onion of sequences */
  31588. byte algoArray[MAX_ALGO_SZ];
  31589. byte issuerArray[MAX_ENCODED_DIG_SZ];
  31590. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  31591. byte snArray[MAX_SN_SZ];
  31592. byte extArray[MAX_OCSP_EXT_SZ];
  31593. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  31594. int i, snSz;
  31595. WOLFSSL_ENTER("EncodeOcspRequest");
  31596. #ifdef NO_SHA
  31597. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  31598. #else
  31599. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  31600. #endif
  31601. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  31602. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  31603. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  31604. MAX_SN_SZ, MAX_SN_SZ);
  31605. extSz = 0;
  31606. if (snSz < 0)
  31607. return snSz;
  31608. if (req->nonceSz) {
  31609. /* TLS Extensions use this function too - put extensions after
  31610. * ASN.1: Context Specific [2].
  31611. */
  31612. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  31613. OCSP_NONCE_EXT_SZ);
  31614. extSz += SetExplicit(2, extSz, extArray);
  31615. }
  31616. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  31617. for (i = 4; i >= 0; i--) {
  31618. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  31619. totalSz += seqSz[i];
  31620. if (i == 2) totalSz += extSz;
  31621. }
  31622. if (output == NULL)
  31623. return totalSz;
  31624. if (totalSz > size)
  31625. return BUFFER_E;
  31626. totalSz = 0;
  31627. for (i = 0; i < 5; i++) {
  31628. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  31629. totalSz += seqSz[i];
  31630. }
  31631. XMEMCPY(output + totalSz, algoArray, algoSz);
  31632. totalSz += algoSz;
  31633. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  31634. totalSz += issuerSz;
  31635. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  31636. totalSz += issuerKeySz;
  31637. XMEMCPY(output + totalSz, snArray, snSz);
  31638. totalSz += snSz;
  31639. if (extSz != 0) {
  31640. XMEMCPY(output + totalSz, extArray, extSz);
  31641. totalSz += extSz;
  31642. }
  31643. return totalSz;
  31644. #else
  31645. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  31646. word32 extSz = 0;
  31647. int sz = 0;
  31648. int ret = 0;
  31649. WOLFSSL_ENTER("EncodeOcspRequest");
  31650. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  31651. if (ret == 0) {
  31652. /* Set OID of hash algorithm use on issuer and key. */
  31653. #ifdef NO_SHA
  31654. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  31655. oidHashType);
  31656. #else
  31657. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  31658. oidHashType);
  31659. #endif
  31660. /* Set issuer, issuer key hash and serial number of certificate being
  31661. * checked. */
  31662. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  31663. req->issuerHash, KEYID_SIZE);
  31664. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  31665. req->issuerKeyHash, KEYID_SIZE);
  31666. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  31667. req->serial, req->serialSz);
  31668. /* Only extension to write is nonce - check if one to encode. */
  31669. if (req->nonceSz) {
  31670. /* Get size of extensions and leave space for them in encoding. */
  31671. ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
  31672. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  31673. if (ret > 0) {
  31674. ret = 0;
  31675. }
  31676. }
  31677. else {
  31678. /* Don't write out extensions. */
  31679. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  31680. }
  31681. }
  31682. if (ret == 0) {
  31683. /* Calculate size of encoding. */
  31684. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  31685. &sz);
  31686. }
  31687. /* Check buffer big enough for encoding if supplied. */
  31688. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31689. ret = BUFFER_E;
  31690. }
  31691. if ((ret == 0) && (output != NULL)) {
  31692. /* Encode OCSPRequest. */
  31693. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  31694. if (req->nonceSz) {
  31695. /* Encode extensions into space provided. */
  31696. ret = EncodeOcspRequestExtensions(req,
  31697. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  31698. extSz);
  31699. if (ret > 0) {
  31700. ret = 0;
  31701. }
  31702. }
  31703. }
  31704. if (ret == 0) {
  31705. /* Return size of encoding. */
  31706. ret = sz;
  31707. }
  31708. FREE_ASNSETDATA(dataASN, req->heap);
  31709. return ret;
  31710. #endif /* WOLFSSL_ASN_TEMPLATE */
  31711. }
  31712. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  31713. void* heap)
  31714. {
  31715. int ret;
  31716. WOLFSSL_ENTER("InitOcspRequest");
  31717. if (req == NULL)
  31718. return BAD_FUNC_ARG;
  31719. XMEMSET(req, 0, sizeof(OcspRequest));
  31720. req->heap = heap;
  31721. if (cert) {
  31722. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  31723. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  31724. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  31725. DYNAMIC_TYPE_OCSP_REQUEST);
  31726. if (req->serial == NULL)
  31727. return MEMORY_E;
  31728. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  31729. req->serialSz = cert->serialSz;
  31730. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  31731. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  31732. DYNAMIC_TYPE_OCSP_REQUEST);
  31733. if (req->url == NULL) {
  31734. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  31735. req->serial = NULL;
  31736. return MEMORY_E;
  31737. }
  31738. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  31739. req->urlSz = cert->extAuthInfoSz;
  31740. req->url[req->urlSz] = 0;
  31741. }
  31742. }
  31743. if (useNonce) {
  31744. WC_RNG rng;
  31745. #ifndef HAVE_FIPS
  31746. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  31747. #else
  31748. ret = wc_InitRng(&rng);
  31749. #endif
  31750. if (ret != 0) {
  31751. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  31752. } else {
  31753. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  31754. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  31755. else
  31756. req->nonceSz = MAX_OCSP_NONCE_SZ;
  31757. wc_FreeRng(&rng);
  31758. }
  31759. }
  31760. return 0;
  31761. }
  31762. void FreeOcspRequest(OcspRequest* req)
  31763. {
  31764. WOLFSSL_ENTER("FreeOcspRequest");
  31765. if (req) {
  31766. if (req->serial)
  31767. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31768. req->serial = NULL;
  31769. #ifdef OPENSSL_EXTRA
  31770. if (req->serialInt) {
  31771. if (req->serialInt->isDynamic) {
  31772. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  31773. }
  31774. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  31775. }
  31776. req->serialInt = NULL;
  31777. #endif
  31778. if (req->url)
  31779. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  31780. req->url = NULL;
  31781. }
  31782. }
  31783. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  31784. {
  31785. int cmp = -1; /* default as not matching, cmp gets set on each check */
  31786. OcspEntry *single, *next, *prev = NULL, *top;
  31787. WOLFSSL_ENTER("CompareOcspReqResp");
  31788. if (req == NULL) {
  31789. WOLFSSL_MSG("\tReq missing");
  31790. return -1;
  31791. }
  31792. if (resp == NULL || resp->single == NULL) {
  31793. WOLFSSL_MSG("\tResp missing");
  31794. return 1;
  31795. }
  31796. /* Nonces are not critical. The responder may not necessarily add
  31797. * the nonce to the response. */
  31798. if (req->nonceSz && resp->nonce != NULL
  31799. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  31800. && resp->nonceSz != 0
  31801. #endif
  31802. ) {
  31803. cmp = req->nonceSz - resp->nonceSz;
  31804. if (cmp != 0) {
  31805. WOLFSSL_MSG("\tnonceSz mismatch");
  31806. return cmp;
  31807. }
  31808. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  31809. if (cmp != 0) {
  31810. WOLFSSL_MSG("\tnonce mismatch");
  31811. return cmp;
  31812. }
  31813. }
  31814. /* match based on found status and return */
  31815. for (single = resp->single; single; single = next) {
  31816. cmp = req->serialSz - single->status->serialSz;
  31817. if (cmp == 0) {
  31818. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  31819. || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
  31820. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
  31821. if (cmp == 0) {
  31822. /* match found */
  31823. if (resp->single != single && prev) {
  31824. /* move to top of list */
  31825. top = resp->single;
  31826. resp->single = single;
  31827. prev->next = single->next;
  31828. single->next = top;
  31829. }
  31830. break;
  31831. }
  31832. }
  31833. next = single->next;
  31834. prev = single;
  31835. }
  31836. if (cmp != 0) {
  31837. WOLFSSL_MSG("\trequest and response mismatch");
  31838. return cmp;
  31839. }
  31840. return 0;
  31841. }
  31842. #endif /* HAVE_OCSP */
  31843. #ifdef WOLFSSL_ASN_TEMPLATE
  31844. /* ASN.1 template for certificate name hash. */
  31845. static const ASNItem nameHashASN[] = {
  31846. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  31847. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  31848. };
  31849. enum {
  31850. NAMEHASHASN_IDX_OID = 0,
  31851. NAMEHASHASN_IDX_NAME
  31852. };
  31853. /* Number of items in ASN.1 template for certificate name hash. */
  31854. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  31855. #endif /* WOLFSSL_ASN_TEMPLATE */
  31856. /* store WC_SHA hash of NAME */
  31857. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  31858. {
  31859. #ifndef WOLFSSL_ASN_TEMPLATE
  31860. int length; /* length of all distinguished names */
  31861. int ret;
  31862. word32 dummy;
  31863. byte tag;
  31864. WOLFSSL_ENTER("GetNameHash");
  31865. dummy = *idx;
  31866. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  31867. tag == ASN_OBJECT_ID) {
  31868. WOLFSSL_MSG("Trying optional prefix...");
  31869. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  31870. return ASN_PARSE_E;
  31871. *idx += (word32)length;
  31872. WOLFSSL_MSG("Got optional prefix");
  31873. }
  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. dummy = *idx;
  31878. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  31879. return ASN_PARSE_E;
  31880. ret = CalcHashId(source + dummy, (word32)length + *idx - dummy, hash);
  31881. *idx += (word32)length;
  31882. return ret;
  31883. #else
  31884. ASNGetData dataASN[nameHashASN_Length];
  31885. int ret;
  31886. XMEMSET(dataASN, 0, sizeof(dataASN));
  31887. /* Ignore the OID even when present. */
  31888. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  31889. /* Decode certificate name. */
  31890. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  31891. (word32)maxIdx);
  31892. if (ret == 0) {
  31893. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  31894. * calculated over the entire DER encoding of the Name field, including
  31895. * the tag and length. */
  31896. /* Calculate hash of complete name including SEQUENCE. */
  31897. ret = CalcHashId(
  31898. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  31899. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  31900. hash);
  31901. }
  31902. return ret;
  31903. #endif /* WOLFSSL_ASN_TEMPLATE */
  31904. }
  31905. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  31906. #ifdef OPENSSL_EXTRA
  31907. static char* GetNameFromDer(const byte* source, int sz)
  31908. {
  31909. char* out;
  31910. out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
  31911. if (out == NULL) {
  31912. WOLFSSL_MSG("Name malloc failed");
  31913. return NULL;
  31914. }
  31915. XMEMCPY(out, source, sz);
  31916. return out;
  31917. }
  31918. #endif
  31919. /* initialize decoded CRL */
  31920. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  31921. {
  31922. WOLFSSL_MSG("InitDecodedCRL");
  31923. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  31924. dcrl->heap = heap;
  31925. #ifdef WOLFSSL_HEAP_TEST
  31926. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  31927. #endif
  31928. }
  31929. /* free decoded CRL resources */
  31930. void FreeDecodedCRL(DecodedCRL* dcrl)
  31931. {
  31932. RevokedCert* tmp = dcrl->certs;
  31933. WOLFSSL_MSG("FreeDecodedCRL");
  31934. while(tmp) {
  31935. RevokedCert* next = tmp->next;
  31936. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  31937. tmp = next;
  31938. }
  31939. #ifdef OPENSSL_EXTRA
  31940. if (dcrl->issuer != NULL)
  31941. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  31942. #endif
  31943. }
  31944. #ifdef WOLFSSL_ASN_TEMPLATE
  31945. /* ASN.1 template for revoked certificates.
  31946. * X.509: RFC 5280, 5.1 - CRL Fields
  31947. */
  31948. static const ASNItem revokedASN[] = {
  31949. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31950. /* userCertificate CertificateSerialNumber */
  31951. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  31952. /* revocationDate Time */
  31953. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  31954. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  31955. /* crlEntryExensions Extensions */
  31956. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  31957. };
  31958. enum {
  31959. REVOKEDASN_IDX_SEQ = 0,
  31960. REVOKEDASN_IDX_CERT,
  31961. REVOKEDASN_IDX_TIME_UTC,
  31962. REVOKEDASN_IDX_TIME_GT,
  31963. REVOKEDASN_IDX_TIME_EXT,
  31964. };
  31965. /* Number of items in ASN.1 template for revoked certificates. */
  31966. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  31967. #endif
  31968. /* Get Revoked Cert list, 0 on success */
  31969. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  31970. DecodedCRL* dcrl, int maxIdx)
  31971. {
  31972. #ifndef WOLFSSL_ASN_TEMPLATE
  31973. int ret;
  31974. int len;
  31975. word32 end;
  31976. RevokedCert* rc;
  31977. #ifdef CRL_STATIC_REVOKED_LIST
  31978. int totalCerts = 0;
  31979. #endif
  31980. WOLFSSL_ENTER("GetRevoked");
  31981. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  31982. return ASN_PARSE_E;
  31983. end = *idx + len;
  31984. #ifdef CRL_STATIC_REVOKED_LIST
  31985. totalCerts = dcrl->totalCerts;
  31986. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  31987. return MEMORY_E;
  31988. }
  31989. rc = &rcert[totalCerts];
  31990. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  31991. if (ret < 0) {
  31992. WOLFSSL_MSG("wc_GetSerialNumber error");
  31993. return ret;
  31994. }
  31995. #else
  31996. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  31997. DYNAMIC_TYPE_REVOKED);
  31998. if (rc == NULL) {
  31999. WOLFSSL_MSG("Alloc Revoked Cert failed");
  32000. return MEMORY_E;
  32001. }
  32002. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32003. if (ret < 0) {
  32004. WOLFSSL_MSG("wc_GetSerialNumber error");
  32005. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32006. return ret;
  32007. }
  32008. /* add to list */
  32009. rc->next = dcrl->certs;
  32010. dcrl->certs = rc;
  32011. (void)rcert;
  32012. #endif /* CRL_STATIC_REVOKED_LIST */
  32013. dcrl->totalCerts++;
  32014. /* get date */
  32015. #ifndef NO_ASN_TIME
  32016. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  32017. if (ret < 0) {
  32018. WOLFSSL_MSG("Expecting Date");
  32019. return ret;
  32020. }
  32021. #endif
  32022. /* skip extensions */
  32023. *idx = end;
  32024. return 0;
  32025. #else
  32026. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32027. int ret = 0;
  32028. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32029. word32 revDateSz = MAX_DATE_SIZE;
  32030. RevokedCert* rc;
  32031. #ifdef CRL_STATIC_REVOKED_LIST
  32032. int totalCerts = dcrl->totalCerts;
  32033. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32034. return MEMORY_E;
  32035. }
  32036. rc = &rcert[totalCerts];
  32037. #else
  32038. /* Allocate a new revoked certificate object. */
  32039. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32040. DYNAMIC_TYPE_CRL);
  32041. if (rc == NULL) {
  32042. ret = MEMORY_E;
  32043. }
  32044. #endif /* CRL_STATIC_REVOKED_LIST */
  32045. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32046. if (ret == 0) {
  32047. /* Set buffer to place serial number into. */
  32048. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32049. &serialSz);
  32050. /* Set buffer to store revocation date. */
  32051. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32052. &revDateSz);
  32053. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32054. &revDateSz);
  32055. /* Decode the Revoked */
  32056. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32057. maxIdx);
  32058. }
  32059. if (ret == 0) {
  32060. /* Store size of serial number. */
  32061. rc->serialSz = serialSz;
  32062. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32063. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32064. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32065. /* TODO: use extensions, only v2 */
  32066. /* Add revoked certificate to chain. */
  32067. #ifndef CRL_STATIC_REVOKED_LIST
  32068. rc->next = dcrl->certs;
  32069. dcrl->certs = rc;
  32070. #endif
  32071. dcrl->totalCerts++;
  32072. }
  32073. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32074. #ifndef CRL_STATIC_REVOKED_LIST
  32075. if ((ret != 0) && (rc != NULL)) {
  32076. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32077. }
  32078. (void)rcert;
  32079. #endif
  32080. return ret;
  32081. #endif /* WOLFSSL_ASN_TEMPLATE */
  32082. }
  32083. #ifdef WOLFSSL_ASN_TEMPLATE
  32084. /* Parse the revoked certificates of a CRL.
  32085. *
  32086. * @param [in] dcrl Decoded CRL object.
  32087. * @param [in] buff Buffer holding CRL.
  32088. * @param [in] idx Index into buffer of revoked certificates.
  32089. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32090. * @return 0 on success.
  32091. * @return ASN_PARSE_E on failure.
  32092. */
  32093. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32094. const byte* buff, word32 idx, word32 maxIdx)
  32095. {
  32096. int ret = 0;
  32097. /* Parse each revoked cerificate. */
  32098. while ((ret == 0) && (idx < maxIdx)) {
  32099. /* Parse a revoked certificate. */
  32100. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32101. ret = ASN_PARSE_E;
  32102. }
  32103. }
  32104. return ret;
  32105. }
  32106. #endif /* WOLFSSL_ASN_TEMPLATE */
  32107. #ifndef WOLFSSL_ASN_TEMPLATE
  32108. /* Get CRL Signature, 0 on success */
  32109. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32110. int maxIdx)
  32111. {
  32112. int length;
  32113. int ret;
  32114. WOLFSSL_ENTER("GetCRL_Signature");
  32115. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32116. if (ret != 0)
  32117. return ret;
  32118. dcrl->sigLength = length;
  32119. dcrl->signature = (byte*)&source[*idx];
  32120. *idx += dcrl->sigLength;
  32121. return 0;
  32122. }
  32123. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32124. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32125. word32 tbsSz, const byte* signature, word32 sigSz,
  32126. word32 signatureOID, Signer *ca, void* heap)
  32127. {
  32128. /* try to confirm/verify signature */
  32129. #ifndef IGNORE_KEY_EXTENSIONS
  32130. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32131. WOLFSSL_MSG("CA cannot sign CRLs");
  32132. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32133. return ASN_CRL_NO_SIGNER_E;
  32134. }
  32135. #endif /* IGNORE_KEY_EXTENSIONS */
  32136. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32137. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32138. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32139. signatureOID, NULL, 0, NULL) != 0) {
  32140. WOLFSSL_MSG("CRL Confirm signature failed");
  32141. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32142. return ASN_CRL_CONFIRM_E;
  32143. }
  32144. return 0;
  32145. }
  32146. #ifdef WOLFSSL_ASN_TEMPLATE
  32147. /* Find the signer for the CRL and verify the signature.
  32148. *
  32149. * @param [in] dcrl Decoded CRL object.
  32150. * @param [in] buff Buffer holding CRL.
  32151. * @param [in] cm Certificate manager object.
  32152. * @return 0 on success.
  32153. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32154. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32155. */
  32156. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32157. {
  32158. int ret = 0;
  32159. Signer* ca = NULL;
  32160. SignatureCtx sigCtx;
  32161. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32162. * If experiencing issues uncomment NO_SKID define in CRL section of
  32163. * wolfssl/wolfcrypt/settings.h */
  32164. #ifndef NO_SKID
  32165. if (dcrl->extAuthKeyIdSet) {
  32166. /* more unique than issuerHash */
  32167. ca = GetCA(cm, dcrl->extAuthKeyId);
  32168. }
  32169. /* Check issuerHash matched CA's subjectNameHash. */
  32170. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32171. KEYID_SIZE) != 0)) {
  32172. ca = NULL;
  32173. }
  32174. if (ca == NULL) {
  32175. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32176. /* If AKID is available then this CA doesn't have the public
  32177. * key required */
  32178. if (ca && dcrl->extAuthKeyIdSet) {
  32179. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32180. ca = NULL;
  32181. }
  32182. }
  32183. #else
  32184. ca = GetCA(cm, dcrl->issuerHash);
  32185. #endif /* !NO_SKID */
  32186. WOLFSSL_MSG("About to verify CRL signature");
  32187. if (ca == NULL) {
  32188. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32189. ret = ASN_CRL_NO_SIGNER_E;
  32190. WOLFSSL_ERROR_VERBOSE(ret);
  32191. }
  32192. if (ret == 0) {
  32193. WOLFSSL_MSG("Found CRL issuer CA");
  32194. /* Verify CRL signature with CA. */
  32195. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32196. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32197. dcrl->signatureOID, ca, dcrl->heap);
  32198. }
  32199. return ret;
  32200. }
  32201. #endif
  32202. #ifndef WOLFSSL_ASN_TEMPLATE
  32203. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32204. const byte* buf,word32* inOutIdx, int sz, int verify)
  32205. {
  32206. word32 oid, dateIdx, idx, checkIdx;
  32207. int length;
  32208. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32209. int doNextDate = 1;
  32210. #endif
  32211. byte tag;
  32212. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32213. return BAD_FUNC_ARG;
  32214. }
  32215. /* may have version */
  32216. idx = *inOutIdx;
  32217. checkIdx = idx;
  32218. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32219. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32220. return ASN_PARSE_E;
  32221. dcrl->version++;
  32222. }
  32223. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32224. return ASN_PARSE_E;
  32225. checkIdx = idx;
  32226. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32227. return ASN_PARSE_E;
  32228. }
  32229. #ifdef OPENSSL_EXTRA
  32230. dcrl->issuerSz = length + (checkIdx - idx);
  32231. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32232. #endif
  32233. if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
  32234. return ASN_PARSE_E;
  32235. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32236. return ASN_PARSE_E;
  32237. dateIdx = idx;
  32238. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32239. {
  32240. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32241. (void)dateIdx;
  32242. return ASN_PARSE_E;
  32243. #else
  32244. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32245. doNextDate = 0;
  32246. idx = dateIdx;
  32247. #endif
  32248. }
  32249. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32250. if (doNextDate)
  32251. #endif
  32252. {
  32253. #ifndef NO_ASN_TIME
  32254. if (verify != NO_VERIFY &&
  32255. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32256. WOLFSSL_MSG("CRL after date is no longer valid");
  32257. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32258. return CRL_CERT_DATE_ERR;
  32259. }
  32260. #else
  32261. (void)verify;
  32262. #endif
  32263. }
  32264. checkIdx = idx;
  32265. if (idx != dcrl->sigIndex &&
  32266. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32267. int len;
  32268. if (GetSequence(buf, &idx, &len, sz) < 0)
  32269. return ASN_PARSE_E;
  32270. len += idx;
  32271. while (idx < (word32)len) {
  32272. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32273. return ASN_PARSE_E;
  32274. }
  32275. }
  32276. *inOutIdx = idx;
  32277. return 0;
  32278. }
  32279. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32280. #ifndef NO_SKID
  32281. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32282. {
  32283. #ifndef WOLFSSL_ASN_TEMPLATE
  32284. word32 idx = 0;
  32285. int length = 0, ret = 0;
  32286. byte tag;
  32287. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32288. if (GetSequence(input, &idx, &length, sz) < 0) {
  32289. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32290. return ASN_PARSE_E;
  32291. }
  32292. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  32293. return ASN_PARSE_E;
  32294. }
  32295. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  32296. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32297. return 0;
  32298. }
  32299. if (GetLength(input, &idx, &length, sz) <= 0) {
  32300. WOLFSSL_MSG("\tfail: extension data length");
  32301. return ASN_PARSE_E;
  32302. }
  32303. dcrl->extAuthKeyIdSet = 1;
  32304. /* Get the hash or hash of the hash if wrong size. */
  32305. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId);
  32306. return ret;
  32307. #else
  32308. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  32309. int ret = 0;
  32310. word32 idx = 0;
  32311. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32312. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  32313. if (ret == 0) {
  32314. /* Parse an authority key identifier. */
  32315. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  32316. &idx, sz);
  32317. }
  32318. if (ret == 0) {
  32319. /* Key id is optional. */
  32320. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  32321. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32322. }
  32323. else {
  32324. /* Get the hash or hash of the hash if wrong size. */
  32325. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  32326. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  32327. dcrl->extAuthKeyId);
  32328. }
  32329. }
  32330. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32331. return ret;
  32332. #endif /* WOLFSSL_ASN_TEMPLATE */
  32333. }
  32334. #endif
  32335. #ifndef WOLFSSL_ASN_TEMPLATE
  32336. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  32337. word32* inOutIdx, word32 sz)
  32338. {
  32339. int length;
  32340. word32 idx;
  32341. word32 ext_bound; /* boundary index for the sequence of extensions */
  32342. word32 oid;
  32343. byte tag;
  32344. WOLFSSL_ENTER("ParseCRL_Extensions");
  32345. (void)dcrl;
  32346. if (inOutIdx == NULL)
  32347. return BAD_FUNC_ARG;
  32348. idx = *inOutIdx;
  32349. /* CRL Extensions are optional */
  32350. if ((idx + 1) > sz)
  32351. return 0;
  32352. /* CRL Extensions are optional */
  32353. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  32354. return 0;
  32355. /* CRL Extensions are optional */
  32356. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  32357. return 0;
  32358. if (GetLength(buf, &idx, &length, sz) < 0)
  32359. return ASN_PARSE_E;
  32360. if (GetSequence(buf, &idx, &length, sz) < 0)
  32361. return ASN_PARSE_E;
  32362. ext_bound = idx + length;
  32363. while (idx < (word32)ext_bound) {
  32364. word32 localIdx;
  32365. int ret;
  32366. if (GetSequence(buf, &idx, &length, sz) < 0) {
  32367. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32368. return ASN_PARSE_E;
  32369. }
  32370. oid = 0;
  32371. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  32372. WOLFSSL_MSG("\tfail: OBJECT ID");
  32373. return ASN_PARSE_E;
  32374. }
  32375. /* check for critical flag */
  32376. if ((idx + 1) > (word32)sz) {
  32377. WOLFSSL_MSG("\tfail: malformed buffer");
  32378. return BUFFER_E;
  32379. }
  32380. localIdx = idx;
  32381. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32382. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32383. ret = GetBoolean(buf, &idx, sz);
  32384. if (ret < 0)
  32385. return ret;
  32386. }
  32387. ret = GetOctetString(buf, &idx, &length, sz);
  32388. if (ret < 0)
  32389. return ret;
  32390. if (oid == AUTH_KEY_OID) {
  32391. #ifndef NO_SKID
  32392. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32393. if (ret < 0) {
  32394. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32395. return ret;
  32396. }
  32397. #endif
  32398. }
  32399. else if (oid == CRL_NUMBER_OID) {
  32400. localIdx = idx;
  32401. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  32402. tag == ASN_INTEGER) {
  32403. ret = GetASNInt(buf, &idx, &length, sz);
  32404. if (ret < 0) {
  32405. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  32406. return ret;
  32407. }
  32408. else {
  32409. if (length > 1) {
  32410. int i;
  32411. #ifdef WOLFSSL_SMALL_STACK
  32412. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  32413. DYNAMIC_TYPE_BIGINT);
  32414. if (m == NULL) {
  32415. return MEMORY_E;
  32416. }
  32417. #else
  32418. mp_int m[1];
  32419. #endif
  32420. if (mp_init(m) != MP_OKAY) {
  32421. ret = MP_INIT_E;
  32422. }
  32423. if (ret == 0)
  32424. ret = mp_read_unsigned_bin(m, buf + idx, length);
  32425. if (ret != MP_OKAY)
  32426. ret = BUFFER_E;
  32427. if (ret == 0) {
  32428. dcrl->crlNumber = 0;
  32429. for (i = 0; i < (int)(*m).used; ++i) {
  32430. if (i > (CHAR_BIT *
  32431. (int)sizeof(word32) / DIGIT_BIT)) {
  32432. break;
  32433. }
  32434. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  32435. (DIGIT_BIT * i);
  32436. }
  32437. }
  32438. mp_free(m);
  32439. #ifdef WOLFSSL_SMALL_STACK
  32440. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  32441. #endif
  32442. if (ret != 0)
  32443. return ret;
  32444. }
  32445. else if (length == 1) {
  32446. dcrl->crlNumber = buf[idx];
  32447. }
  32448. }
  32449. }
  32450. }
  32451. idx += length;
  32452. }
  32453. *inOutIdx = idx;
  32454. return 0;
  32455. }
  32456. #else
  32457. /* Parse the extensions of a CRL.
  32458. *
  32459. * @param [in] dcrl Decoded CRL object.
  32460. * @param [in] buff Buffer holding CRL.
  32461. * @param [in] idx Index into buffer of extensions.
  32462. * @param [in] maxIdx Maximum index of extension data.
  32463. * @return 0 on success.
  32464. * @return ASN_PARSE_E on failure.
  32465. */
  32466. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  32467. word32 maxIdx)
  32468. {
  32469. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32470. int ret = 0;
  32471. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  32472. while ((ret == 0) && (idx < maxIdx)) {
  32473. byte critical = 0;
  32474. /* Clear dynamic data. */
  32475. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32476. /* Ensure OID is an extention type. */
  32477. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  32478. /* Set criticality variable. */
  32479. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  32480. /* Parse extension wrapper. */
  32481. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  32482. maxIdx);
  32483. if (ret == 0) {
  32484. /* OID in extension. */
  32485. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32486. /* Length of extension data. */
  32487. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  32488. if (oid == AUTH_KEY_OID) {
  32489. #ifndef NO_SKID
  32490. /* Parse Authority Key Id extesion.
  32491. * idx is at start of OCTET_STRING data. */
  32492. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32493. if (ret != 0) {
  32494. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32495. }
  32496. #endif
  32497. }
  32498. /* TODO: Parse CRL Number extension */
  32499. /* TODO: check criticality */
  32500. /* Move index on to next extension. */
  32501. idx += length;
  32502. }
  32503. }
  32504. if (ret < 0) {
  32505. ret = ASN_PARSE_E;
  32506. }
  32507. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32508. return ret;
  32509. }
  32510. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32511. #ifdef WOLFSSL_ASN_TEMPLATE
  32512. /* ASN.1 template for a CRL- CertificateList.
  32513. * X.509: RFC 5280, 5.1 - CRL Fields
  32514. */
  32515. static const ASNItem crlASN[] = {
  32516. /* CertificateList */
  32517. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32518. /* tbsCertList */
  32519. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32520. /* version Version OPTIONAL if present must be v2 */
  32521. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  32522. /* signature */
  32523. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32524. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32525. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  32526. /* issuer */
  32527. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  32528. /* thisUpdate */
  32529. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  32530. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32531. /* nextUpdate */
  32532. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  32533. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  32534. /* revokedCertificates */
  32535. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32536. /* crlExtensions */
  32537. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32538. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  32539. /* signatureAlgorithm */
  32540. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32541. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32542. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32543. /* signatureValue */
  32544. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32545. };
  32546. enum {
  32547. CRLASN_IDX_SEQ = 0,
  32548. CRLASN_IDX_TBS,
  32549. CRLASN_IDX_TBS_VER,
  32550. CRLASN_IDX_TBS_SIGALGO,
  32551. CRLASN_IDX_TBS_SIGALGO_OID,
  32552. CRLASN_IDX_TBS_SIGALGO_NULL,
  32553. CRLASN_IDX_TBS_ISSUER,
  32554. CRLASN_IDX_TBS_THISUPDATE_UTC,
  32555. CRLASN_IDX_TBS_THISUPDATE_GT,
  32556. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  32557. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  32558. CRLASN_IDX_TBS_REVOKEDCERTS,
  32559. CRLASN_IDX_TBS_EXT,
  32560. CRLASN_IDX_TBS_EXT_SEQ,
  32561. CRLASN_IDX_SIGALGO,
  32562. CRLASN_IDX_SIGALGO_OID,
  32563. CRLASN_IDX_SIGALGO_NULL,
  32564. CRLASN_IDX_SIGNATURE,
  32565. };
  32566. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  32567. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  32568. #endif
  32569. /* parse crl buffer into decoded state, 0 on success */
  32570. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  32571. int verify, void* cm)
  32572. {
  32573. #ifndef WOLFSSL_ASN_TEMPLATE
  32574. Signer* ca = NULL;
  32575. SignatureCtx sigCtx;
  32576. int ret = 0;
  32577. int len;
  32578. word32 idx = 0;
  32579. WOLFSSL_MSG("ParseCRL");
  32580. /* raw crl hash */
  32581. /* hash here if needed for optimized comparisons
  32582. * wc_Sha sha;
  32583. * wc_InitSha(&sha);
  32584. * wc_ShaUpdate(&sha, buff, sz);
  32585. * wc_ShaFinal(&sha, dcrl->crlHash); */
  32586. if (GetSequence(buff, &idx, &len, sz) < 0)
  32587. return ASN_PARSE_E;
  32588. dcrl->certBegin = idx;
  32589. /* Normalize sz for the length inside the outer sequence. */
  32590. sz = len + idx;
  32591. if (GetSequence(buff, &idx, &len, sz) < 0)
  32592. return ASN_PARSE_E;
  32593. dcrl->sigIndex = len + idx;
  32594. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  32595. return ASN_PARSE_E;
  32596. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  32597. return ASN_PARSE_E;
  32598. idx = dcrl->sigIndex;
  32599. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  32600. return ASN_PARSE_E;
  32601. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  32602. return ASN_PARSE_E;
  32603. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  32604. if experiencing issues uncomment NO_SKID define in CRL section of
  32605. wolfssl/wolfcrypt/settings.h */
  32606. #ifndef NO_SKID
  32607. if (dcrl->extAuthKeyIdSet) {
  32608. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  32609. }
  32610. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32611. KEYID_SIZE) != 0) {
  32612. ca = NULL;
  32613. }
  32614. if (ca == NULL) {
  32615. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32616. /* If AKID is available then this CA doesn't have the public
  32617. * key required */
  32618. if (ca && dcrl->extAuthKeyIdSet) {
  32619. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32620. ca = NULL;
  32621. }
  32622. }
  32623. #else
  32624. ca = GetCA(cm, dcrl->issuerHash);
  32625. #endif /* !NO_SKID */
  32626. WOLFSSL_MSG("About to verify CRL signature");
  32627. if (ca == NULL) {
  32628. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32629. ret = ASN_CRL_NO_SIGNER_E;
  32630. WOLFSSL_ERROR_VERBOSE(ret);
  32631. goto end;
  32632. }
  32633. WOLFSSL_MSG("Found CRL issuer CA");
  32634. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32635. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32636. dcrl->signatureOID, ca, dcrl->heap);
  32637. end:
  32638. return ret;
  32639. #else
  32640. DECL_ASNGETDATA(dataASN, crlASN_Length);
  32641. int ret = 0;
  32642. /* Default version - v1 = 0 */
  32643. byte version = 0;
  32644. word32 idx = 0;
  32645. /* Size of buffer for date. */
  32646. word32 lastDateSz = MAX_DATE_SIZE;
  32647. word32 nextDateSz = MAX_DATE_SIZE;
  32648. /* When NO_ASN_TIME is defined, verify not used. */
  32649. (void)verify;
  32650. WOLFSSL_MSG("ParseCRL");
  32651. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  32652. if (ret == 0) {
  32653. /* Set variable to store version. */
  32654. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  32655. /* Set expecting signature OID. */
  32656. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  32657. /* Set buffer to put last and next date into. */
  32658. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  32659. &lastDateSz);
  32660. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  32661. &lastDateSz);
  32662. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  32663. &nextDateSz);
  32664. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  32665. &nextDateSz);
  32666. /* Set expecting signature OID. */
  32667. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  32668. /* Decode the CRL. */
  32669. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  32670. }
  32671. /* Version must be v2 = 1 if present. */
  32672. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  32673. (version != 1)) {
  32674. ret = ASN_PARSE_E;
  32675. }
  32676. /* Check minimum size of last date. */
  32677. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  32678. ret = ASN_PARSE_E;
  32679. }
  32680. /* Check minimum size of next date. */
  32681. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  32682. ret = ASN_PARSE_E;
  32683. }
  32684. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  32685. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  32686. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  32687. ret = ASN_PARSE_E;
  32688. }
  32689. if (ret == 0) {
  32690. /* Store version */
  32691. dcrl->version = ++version;
  32692. /* Store offset of to be signed part. */
  32693. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  32694. /* Store index of signature. */
  32695. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  32696. /* Store address and length of signature data. */
  32697. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  32698. &dcrl->sigLength);
  32699. /* Get the signature OID. */
  32700. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  32701. /* Get the format/tag of the last and next date. */
  32702. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  32703. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  32704. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  32705. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  32706. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  32707. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  32708. #ifndef NO_ASN_TIME
  32709. if (dcrl->nextDateFormat != 0) {
  32710. /* Next date was set, so validate it. */
  32711. if (verify != NO_VERIFY &&
  32712. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32713. WOLFSSL_MSG("CRL after date is no longer valid");
  32714. ret = CRL_CERT_DATE_ERR;
  32715. WOLFSSL_ERROR_VERBOSE(ret);
  32716. }
  32717. }
  32718. }
  32719. if (ret == 0) {
  32720. #endif
  32721. #ifdef OPENSSL_EXTRA
  32722. /* Parse and store the issuer name. */
  32723. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  32724. buff);
  32725. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  32726. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32727. (int)dcrl->issuerSz);
  32728. #endif
  32729. /* Calculate the Hash id from the issuer name. */
  32730. ret = CalcHashId(GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32731. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32732. dcrl->issuerHash);
  32733. if (ret < 0) {
  32734. ret = ASN_PARSE_E;
  32735. }
  32736. }
  32737. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  32738. /* Parse revoked cerificates - starting after SEQUENCE OF. */
  32739. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  32740. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  32741. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  32742. }
  32743. if (ret == 0) {
  32744. /* Parse the extensions - starting after SEQUENCE OF. */
  32745. ret = ParseCRL_Extensions(dcrl, buff,
  32746. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  32747. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  32748. }
  32749. if (ret == 0) {
  32750. /* Find signer and verify signature. */
  32751. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  32752. }
  32753. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32754. return ret;
  32755. #endif /* WOLFSSL_ASN_TEMPLATE */
  32756. }
  32757. #endif /* HAVE_CRL */
  32758. #ifdef WOLFSSL_CERT_PIV
  32759. #ifdef WOLFSSL_ASN_TEMPLATE
  32760. /* Template for PIV. */
  32761. static const ASNItem pivASN[] = {
  32762. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  32763. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  32764. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  32765. };
  32766. enum {
  32767. PIVASN_IDX_CERT = 0,
  32768. PIVASN_IDX_NONCE,
  32769. PIVASN_IDX_SIGNEDNONCE,
  32770. };
  32771. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  32772. static const ASNItem pivCertASN[] = {
  32773. /* 0x53 = 0x40 | 0x13 */
  32774. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  32775. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  32776. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  32777. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  32778. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  32779. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  32780. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  32781. };
  32782. enum {
  32783. PIVCERTASN_IDX_CERT,
  32784. PIVCERTASN_IDX_X509,
  32785. PIVCERTASN_IDX_INFO,
  32786. PIVCERTASN_IDX_ERR,
  32787. };
  32788. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  32789. #endif
  32790. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  32791. {
  32792. #ifndef WOLFSSL_ASN_TEMPLATE
  32793. int length = 0;
  32794. word32 idx = 0;
  32795. WOLFSSL_ENTER("wc_ParseCertPIV");
  32796. if (piv == NULL || buf == NULL || totalSz == 0)
  32797. return BAD_FUNC_ARG;
  32798. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  32799. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  32800. /* Certificate (0A 82 05FA) */
  32801. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  32802. /* Identiv Type PIV card */
  32803. piv->isIdentiv = 1;
  32804. piv->cert = &buf[idx];
  32805. piv->certSz = length;
  32806. idx += length;
  32807. /* Nonce (0B 14) */
  32808. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  32809. piv->nonce = &buf[idx];
  32810. piv->nonceSz = length;
  32811. idx += length;
  32812. }
  32813. /* Signed Nonce (0C 82 0100) */
  32814. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  32815. piv->signedNonce = &buf[idx];
  32816. piv->signedNonceSz = length;
  32817. }
  32818. idx = 0;
  32819. buf = piv->cert;
  32820. totalSz = piv->certSz;
  32821. }
  32822. /* Certificate Buffer Total Size (53 82 05F6) */
  32823. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  32824. &length, totalSz) < 0) {
  32825. return ASN_PARSE_E;
  32826. }
  32827. /* PIV Certificate (70 82 05ED) */
  32828. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  32829. totalSz) < 0) {
  32830. return ASN_PARSE_E;
  32831. }
  32832. /* Capture certificate buffer pointer and length */
  32833. piv->cert = &buf[idx];
  32834. piv->certSz = length;
  32835. idx += length;
  32836. /* PIV Certificate Info (71 01 00) */
  32837. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  32838. totalSz) >= 0) {
  32839. if (length >= 1) {
  32840. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  32841. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  32842. }
  32843. idx += length;
  32844. }
  32845. /* PIV Error Detection (FE 00) */
  32846. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  32847. totalSz) >= 0) {
  32848. piv->certErrDet = &buf[idx];
  32849. piv->certErrDetSz = length;
  32850. idx += length;
  32851. }
  32852. return 0;
  32853. #else
  32854. /* pivCertASN_Length is longer than pivASN_Length */
  32855. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  32856. int ret = 0;
  32857. word32 idx;
  32858. byte info;
  32859. WOLFSSL_ENTER("wc_ParseCertPIV");
  32860. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  32861. if (ret == 0) {
  32862. /* Clear dynamic data. */
  32863. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  32864. /* Start parsing from start of buffer. */
  32865. idx = 0;
  32866. /* Parse Identiv wrapper. */
  32867. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  32868. totalSz);
  32869. if (ret == 0) {
  32870. /* Identiv wrapper found. */
  32871. piv->isIdentiv = 1;
  32872. /* Get nonce reference. */
  32873. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  32874. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  32875. &piv->nonceSz);
  32876. }
  32877. /* Get signedNonce reference. */
  32878. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  32879. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  32880. &piv->signedNonce, &piv->signedNonceSz);
  32881. }
  32882. /* Get the certificate data for parsing. */
  32883. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  32884. }
  32885. ret = 0;
  32886. }
  32887. if (ret == 0) {
  32888. /* Clear dynamic data and set variable to put cert info into. */
  32889. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  32890. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  32891. /* Start parsing from start of buffer. */
  32892. idx = 0;
  32893. /* Parse PIV cetificate data. */
  32894. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  32895. totalSz);
  32896. if (ret == 0) {
  32897. /* Get X.509 certificate reference. */
  32898. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  32899. &piv->certSz);
  32900. /* Set the certificate info if available. */
  32901. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  32902. /* Bits 1 and 2 are compression. */
  32903. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  32904. /* Bits 3 is X509 flag. */
  32905. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  32906. }
  32907. /* Get X.509 certificate error detection reference. */
  32908. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  32909. &piv->certErrDetSz);
  32910. }
  32911. ret = 0;
  32912. }
  32913. FREE_ASNGETDATA(dataASN, NULL);
  32914. return ret;
  32915. #endif /* WOLFSSL_ASN_TEMPLATE */
  32916. }
  32917. #endif /* WOLFSSL_CERT_PIV */
  32918. #ifdef HAVE_SMIME
  32919. /*****************************************************************************
  32920. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  32921. * and parameters into headers. Will continue until in has no more content.
  32922. *
  32923. * RETURNS:
  32924. * returns zero on success, non-zero on error.
  32925. */
  32926. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  32927. {
  32928. MimeHdr* nextHdr = NULL;
  32929. MimeHdr* curHdr = NULL;
  32930. MimeParam* nextParam = NULL;
  32931. size_t start = 0;
  32932. size_t end = 0;
  32933. char* nameAttr = NULL;
  32934. char* bodyVal = NULL;
  32935. MimeTypes mimeType = MIME_HDR;
  32936. MimeStatus mimeStatus = MIME_NAMEATTR;
  32937. int ret = -1;
  32938. size_t pos = 0;
  32939. size_t lineLen = 0;
  32940. char* curLine = NULL;
  32941. char* ptr = NULL;
  32942. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  32943. ret = BAD_FUNC_ARG;
  32944. goto error;
  32945. }
  32946. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  32947. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  32948. DYNAMIC_TYPE_PKCS7);
  32949. if (nextHdr == NULL || nextParam == NULL) {
  32950. ret = MEMORY_E;
  32951. goto error;
  32952. }
  32953. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  32954. XMEMSET(nextParam, 0, sizeof(MimeParam));
  32955. curLine = XSTRTOK(in, "\r\n", &ptr);
  32956. if (curLine == NULL) {
  32957. ret = ASN_PARSE_E;
  32958. goto error;
  32959. }
  32960. while (curLine != NULL) {
  32961. /* Leftover from previous line, add params to previous header. */
  32962. if (curLine[0] == ' ' && curHdr) {
  32963. mimeType = MIME_PARAM;
  32964. }
  32965. else {
  32966. mimeType = MIME_HDR;
  32967. }
  32968. start = 0;
  32969. lineLen = XSTRLEN(curLine);
  32970. if (lineLen == 0) {
  32971. ret = BAD_FUNC_ARG;
  32972. goto error;
  32973. }
  32974. for (pos = 0; pos < lineLen; pos++) {
  32975. char cur = curLine[pos];
  32976. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  32977. mimeType == MIME_HDR) || (cur == '=' &&
  32978. mimeType == MIME_PARAM)) && pos >= 1) {
  32979. mimeStatus = MIME_BODYVAL;
  32980. end = pos-1;
  32981. if (nameAttr != NULL)
  32982. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  32983. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  32984. if (ret) {
  32985. goto error;
  32986. }
  32987. start = pos+1;
  32988. }
  32989. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  32990. end = pos-1;
  32991. if (bodyVal != NULL)
  32992. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  32993. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  32994. if (ret) {
  32995. goto error;
  32996. }
  32997. if (mimeType == MIME_HDR) {
  32998. nextHdr->name = nameAttr;
  32999. nameAttr = NULL;
  33000. nextHdr->body = bodyVal;
  33001. bodyVal = NULL;
  33002. nextHdr->next = curHdr;
  33003. curHdr = nextHdr;
  33004. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33005. DYNAMIC_TYPE_PKCS7);
  33006. if (nextHdr == NULL) {
  33007. ret = MEMORY_E;
  33008. goto error;
  33009. }
  33010. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33011. }
  33012. else {
  33013. nextParam->attribute = nameAttr;
  33014. nameAttr = NULL;
  33015. nextParam->value = bodyVal;
  33016. bodyVal = NULL;
  33017. nextParam->next = curHdr->params;
  33018. curHdr->params = nextParam;
  33019. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33020. DYNAMIC_TYPE_PKCS7);
  33021. if (nextParam == NULL) {
  33022. ret = MEMORY_E;
  33023. goto error;
  33024. }
  33025. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33026. }
  33027. mimeType = MIME_PARAM;
  33028. mimeStatus = MIME_NAMEATTR;
  33029. start = pos+1;
  33030. }
  33031. }
  33032. end = lineLen-1;
  33033. /* Omit newline characters. */
  33034. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33035. end--;
  33036. }
  33037. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33038. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33039. if (ret) {
  33040. goto error;
  33041. }
  33042. if (mimeType == MIME_HDR) {
  33043. nextHdr->name = nameAttr;
  33044. nameAttr = NULL;
  33045. nextHdr->body = bodyVal;
  33046. bodyVal = NULL;
  33047. nextHdr->next = curHdr;
  33048. curHdr = nextHdr;
  33049. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33050. DYNAMIC_TYPE_PKCS7);
  33051. if (nextHdr == NULL) {
  33052. ret = MEMORY_E;
  33053. goto error;
  33054. }
  33055. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33056. } else {
  33057. nextParam->attribute = nameAttr;
  33058. nameAttr = NULL;
  33059. nextParam->value = bodyVal;
  33060. bodyVal = NULL;
  33061. nextParam->next = curHdr->params;
  33062. curHdr->params = nextParam;
  33063. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33064. DYNAMIC_TYPE_PKCS7);
  33065. if (nextParam == NULL) {
  33066. ret = MEMORY_E;
  33067. goto error;
  33068. }
  33069. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33070. }
  33071. }
  33072. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33073. mimeStatus = MIME_NAMEATTR;
  33074. }
  33075. *headers = curHdr;
  33076. ret = 0; /* success if at this point */
  33077. error:
  33078. if (ret != 0)
  33079. wc_MIME_free_hdrs(curHdr);
  33080. wc_MIME_free_hdrs(nextHdr);
  33081. if (nameAttr != NULL)
  33082. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33083. if (bodyVal != NULL)
  33084. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33085. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33086. return ret;
  33087. }
  33088. /*****************************************************************************
  33089. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33090. * out disallowed/separator characters and places the rest into *out.
  33091. *
  33092. * RETURNS:
  33093. * returns zero on success, non-zero on error.
  33094. */
  33095. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33096. {
  33097. size_t inPos = start;
  33098. size_t outPos = 0;
  33099. size_t inLen = 0;
  33100. if (end < start || in == NULL || out == NULL) {
  33101. return BAD_FUNC_ARG;
  33102. }
  33103. inLen = XSTRLEN(in);
  33104. if (start > inLen || end > inLen) {
  33105. return BAD_FUNC_ARG;
  33106. }
  33107. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33108. DYNAMIC_TYPE_PKCS7);
  33109. if (*out == NULL) {
  33110. return MEMORY_E;
  33111. }
  33112. while (inPos <= end) {
  33113. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33114. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33115. (*out)[outPos] = in[inPos];
  33116. outPos++;
  33117. }
  33118. inPos++;
  33119. }
  33120. (*out)[outPos] = '\0';
  33121. return 0;
  33122. }
  33123. /*****************************************************************************
  33124. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33125. * a name matching the provided name is found.
  33126. *
  33127. * RETURNS:
  33128. * returns a pointer to the found header, if no match was found, returns NULL.
  33129. */
  33130. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33131. {
  33132. while (header) {
  33133. if (!XSTRCMP(name, header->name)) {
  33134. return header;
  33135. }
  33136. header = header->next;
  33137. }
  33138. return header;
  33139. }
  33140. /*****************************************************************************
  33141. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33142. * with a attribute matching the provided attribute is found.
  33143. *
  33144. * RETURNS:
  33145. * returns a pointer to the found parameter, if no match was found,
  33146. * returns NULL.
  33147. */
  33148. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33149. MimeParam* param)
  33150. {
  33151. while (param) {
  33152. if (!XSTRCMP(attribute, param->attribute)) {
  33153. return param;
  33154. }
  33155. param = param->next;
  33156. }
  33157. return param;
  33158. }
  33159. /*****************************************************************************
  33160. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33161. * line ending to CRLF.
  33162. *
  33163. * line - input line to canonicalize
  33164. * len - length of line in chars on input, length of output array on return
  33165. *
  33166. * RETURNS:
  33167. * returns a pointer to a canonicalized line on success, NULL on error.
  33168. */
  33169. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33170. {
  33171. size_t end = 0;
  33172. char* canonLine = NULL;
  33173. if (line == NULL || len == NULL || *len == 0) {
  33174. return NULL;
  33175. }
  33176. end = *len;
  33177. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33178. end--;
  33179. }
  33180. /* Need 2 chars for \r\n and 1 for EOL */
  33181. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33182. if (canonLine == NULL) {
  33183. return NULL;
  33184. }
  33185. XMEMCPY(canonLine, line, end);
  33186. canonLine[end] = '\r';
  33187. canonLine[end+1] = '\n';
  33188. canonLine[end+2] = '\0';
  33189. *len = (word32)(end + 3);
  33190. return canonLine;
  33191. }
  33192. /*****************************************************************************
  33193. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33194. * the provided header pointer.
  33195. *
  33196. * RETURNS:
  33197. * returns zero on success, non-zero on error.
  33198. */
  33199. int wc_MIME_free_hdrs(MimeHdr* head)
  33200. {
  33201. MimeHdr* curHdr = NULL;
  33202. MimeParam* curParam = NULL;
  33203. while (head) {
  33204. while (head->params) {
  33205. curParam = head->params;
  33206. head->params = head->params->next;
  33207. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33208. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33209. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33210. }
  33211. curHdr = head;
  33212. head = head->next;
  33213. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33214. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33215. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33216. }
  33217. return 0;
  33218. }
  33219. #endif /* HAVE_SMIME */
  33220. #undef ERROR_OUT
  33221. #ifdef WOLFSSL_ASN_PRINT
  33222. /*******************************************************************************
  33223. * ASN.1 Parsing and Printing Implemenation
  33224. ******************************************************************************/
  33225. /* Initialize ASN.1 print options.
  33226. *
  33227. * @param [in, out] opts ASN.1 options for printing.
  33228. * @return 0 on success.
  33229. * @return BAD_FUNC_ARG when asn1 is NULL.
  33230. */
  33231. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  33232. {
  33233. int ret = 0;
  33234. if (opts == NULL) {
  33235. ret = BAD_FUNC_ARG;
  33236. }
  33237. else {
  33238. XMEMSET(opts, 0, sizeof(*opts));
  33239. }
  33240. return ret;
  33241. }
  33242. /* Set a print option into Asn1PrintOptions object.
  33243. *
  33244. * @param [in, out] opts ASN.1 options for printing.
  33245. * @param [in] opt Option to set value of.
  33246. * @param [in] val Value to set for option.
  33247. * @return 0 on success.
  33248. * @return BAD_FUNC_ARG when asn1 is NULL.
  33249. * @return BAD_FUNC_ARG when val is out of range for option.
  33250. */
  33251. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  33252. word32 val)
  33253. {
  33254. int ret = 0;
  33255. /* Validate parameters. */
  33256. if (opts == NULL) {
  33257. ret = BAD_FUNC_ARG;
  33258. }
  33259. if (ret == 0) {
  33260. switch (opt) {
  33261. /* Offset into DER/BER data to start decoding from. */
  33262. case ASN1_PRINT_OPT_OFFSET:
  33263. opts->offset = val;
  33264. break;
  33265. /* Length of DER/BER encoding to parse. */
  33266. case ASN1_PRINT_OPT_LENGTH:
  33267. opts->length = val;
  33268. break;
  33269. /* Number of spaces to indent for each change in depth. */
  33270. case ASN1_PRINT_OPT_INDENT:
  33271. /* Only 4 bits allowed for value. */
  33272. if (val >= (1 << 4)) {
  33273. ret = BAD_FUNC_ARG;
  33274. }
  33275. else {
  33276. opts->indent = (word8)val;
  33277. }
  33278. break;
  33279. /* Draw branches instead of indenting. */
  33280. case ASN1_PRINT_OPT_DRAW_BRANCH:
  33281. /* Boolean value. */
  33282. opts->draw_branch = (val > 0);
  33283. break;
  33284. /* Show raw data of primitive types as octets. */
  33285. case ASN1_PRINT_OPT_SHOW_DATA:
  33286. /* Boolean value. */
  33287. opts->show_data = (val > 0);
  33288. break;
  33289. /* Show header data as octets. */
  33290. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  33291. /* Boolean value. */
  33292. opts->show_header_data = (val > 0);
  33293. break;
  33294. /* Show the wolfSSL OID value for OBJECT_ID. */
  33295. case ASN1_PRINT_OPT_SHOW_OID:
  33296. /* Boolean value. */
  33297. opts->show_oid = (val > 0);
  33298. break;
  33299. /* Don't show text representations of primitive types. */
  33300. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  33301. /* Boolean value. */
  33302. opts->show_no_text = (val > 0);
  33303. break;
  33304. /* Don't show dump text representations of primitive types. */
  33305. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  33306. /* Boolean value. */
  33307. opts->show_no_dump_text = (val > 0);
  33308. break;
  33309. }
  33310. }
  33311. return ret;
  33312. }
  33313. /* Initialize an ASN.1 parse object.
  33314. *
  33315. * @param [in, out] asn1 ASN.1 parse object.
  33316. * @return 0 on success.
  33317. * @return BAD_FUNC_ARG when asn1 is NULL.
  33318. */
  33319. int wc_Asn1_Init(Asn1* asn1)
  33320. {
  33321. int ret = 0;
  33322. if (asn1 == NULL) {
  33323. ret = BAD_FUNC_ARG;
  33324. }
  33325. else {
  33326. XMEMSET(asn1, 0, sizeof(*asn1));
  33327. asn1->file = XBADFILE;
  33328. }
  33329. return ret;
  33330. }
  33331. /* Set the file to use when printing.
  33332. *
  33333. * @param [in, out] asn1 ASN.1 parse object.
  33334. * @param [in] file File to print to.
  33335. * @return 0 on success.
  33336. * @return BAD_FUNC_ARG when asn1 is NULL.
  33337. * @return BAD_FUNC_ARG when file is XBADFILE.
  33338. */
  33339. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  33340. {
  33341. int ret = 0;
  33342. if ((asn1 == NULL) || (file == XBADFILE)) {
  33343. ret = BAD_FUNC_ARG;
  33344. }
  33345. else {
  33346. asn1->file = file;
  33347. }
  33348. return ret;
  33349. }
  33350. /* Maximum OID dotted form size. */
  33351. #define ASN1_OID_DOTTED_MAX_SZ 16
  33352. /* Print OID in dotted form or as hex bytes.
  33353. *
  33354. * @param [in] file File pointer to write to.
  33355. * @param [in] oid OBJECT_ID data.
  33356. * @param [in] oid_len Length of OBJECT_ID data.
  33357. */
  33358. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  33359. {
  33360. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  33361. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  33362. word32 i;
  33363. /* Decode OBJECT_ID into dotted form array. */
  33364. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  33365. /* Print out each number of dotted form. */
  33366. for (i = 0; i < num; i++) {
  33367. XFPRINTF(file, "%d", dotted_nums[i]);
  33368. /* Add separetor. */
  33369. if (i < num - 1) {
  33370. XFPRINTF(file, ".");
  33371. }
  33372. }
  33373. }
  33374. else {
  33375. /* Print out bytes as we couldn't decode. */
  33376. for (i = 0; i < len; i++) {
  33377. XFPRINTF(file, "%02x", oid[i]);
  33378. /* Add separetor. */
  33379. if (i < len - 1) {
  33380. XFPRINTF(file, ":");
  33381. }
  33382. }
  33383. }
  33384. }
  33385. /* OID value to name mapping. */
  33386. typedef struct OidName {
  33387. /* wolfSSL OID value. */
  33388. word32 oid;
  33389. /* Long name to print when OID seen. */
  33390. const char* name;
  33391. } OidName;
  33392. /* Extra OID to name mappings. */
  33393. static const OidName extraOids[] = {
  33394. { 0x005c, "commonName" },
  33395. { 0x005d, "surname" },
  33396. { 0x005e, "serialNumber" },
  33397. { 0x005f, "countryName" },
  33398. { 0x0060, "localityName" },
  33399. { 0x0061, "stateOrProvinceName" },
  33400. { 0x0062, "streetAddress" },
  33401. { 0x0063, "organizationName" },
  33402. { 0x0064, "organizationUnitName" },
  33403. { 0x0065, "title" },
  33404. { 0x0086, "certificateExtension" },
  33405. { 0x028d, "emailAddress" },
  33406. { 0x0293, "challengePassword" },
  33407. { 0x029a, "extensionReq" },
  33408. };
  33409. /* Length of table of extra OID to name mappings. */
  33410. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  33411. /* Convert OID value to long name.
  33412. *
  33413. * @param [in] oid OID value.
  33414. * @param [out] name Long name for OID when known.
  33415. * @return 1 when OID known.
  33416. * @return 0 when OID not known.
  33417. */
  33418. static int Oid2LongName(word32 oid, const char** name)
  33419. {
  33420. int ret = 0;
  33421. int i;
  33422. /* Step through each entry in table. */
  33423. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  33424. if (extraOids[i].oid == oid) {
  33425. /* Return the name associated with the OID value. */
  33426. *name = extraOids[i].name;
  33427. ret = 1;
  33428. break;
  33429. }
  33430. }
  33431. return ret;
  33432. }
  33433. /* Print the text version of the OBJECT_ID.
  33434. *
  33435. * @param [in] asn1 ASN.1 parse object.
  33436. * @param [in] opts ASN.1 options for printing.
  33437. */
  33438. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  33439. {
  33440. word32 oid = (word32)-1;
  33441. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33442. int nid;
  33443. #endif
  33444. const char* ln = NULL;
  33445. word32 i = 0;
  33446. int known = 1;
  33447. /* Get the OID value for the OBJECT_ID. */
  33448. if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  33449. asn1->item.len + 2) == ASN_PARSE_E) {
  33450. known = 0;
  33451. }
  33452. else
  33453. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33454. /* Lookup NID for OID value. */
  33455. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  33456. /* Lookup long name for NID. */
  33457. ln = wolfSSL_OBJ_nid2ln(nid);
  33458. }
  33459. else
  33460. #endif
  33461. /* Lookup long name for extra known OID values. */
  33462. if (!Oid2LongName(oid, &ln)) {
  33463. /* Unknown OID value. */
  33464. ln = NULL;
  33465. known = 0;
  33466. }
  33467. XFPRINTF(asn1->file, ":");
  33468. /* Show OID value if not known or asked to. */
  33469. if ((!known) || opts->show_oid) {
  33470. XFPRINTF(asn1->file, "(0x%x) ", oid);
  33471. }
  33472. if (ln != NULL) {
  33473. /* Print long name. */
  33474. XFPRINTF(asn1->file, "%s", ln);
  33475. }
  33476. else {
  33477. /* Print out as numbers - either dotted or hex values. */
  33478. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  33479. asn1->item.len);
  33480. }
  33481. }
  33482. /* Print ASN.1 data as a character string.
  33483. *
  33484. * @param [in] asn1 ASN.1 parse object.
  33485. */
  33486. static void PrintText(Asn1* asn1)
  33487. {
  33488. word32 i;
  33489. XFPRINTF(asn1->file, ":");
  33490. /* Print all data bytes as characters. */
  33491. for (i = 0; i < asn1->item.len; i++) {
  33492. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  33493. }
  33494. }
  33495. /* Print data as a hex bytes.
  33496. *
  33497. * @param [in] file File pointer to write to.
  33498. * @param [in] data Data to print.
  33499. * @param [in] len Number of bytes to print.
  33500. */
  33501. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  33502. {
  33503. word32 i;
  33504. /* Print data bytes as hex numbers. */
  33505. for (i = 0; i < len; i++) {
  33506. XFPRINTF(file, "%02x", data[i]);
  33507. }
  33508. }
  33509. /* Print ASN.1 data as a hex bytes.
  33510. *
  33511. * @param [in] asn1 ASN.1 parse object.
  33512. */
  33513. static void PrintHexText(Asn1* asn1)
  33514. {
  33515. XFPRINTF(asn1->file, ":");
  33516. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  33517. }
  33518. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  33519. *
  33520. * @param [in] asn1 ASN.1 parse object.
  33521. */
  33522. static void PrintBitStringText(Asn1* asn1)
  33523. {
  33524. if (asn1->item.len > 0) {
  33525. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  33526. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  33527. asn1->item.len - 1);
  33528. }
  33529. }
  33530. /* Print ASN.1 BOOLEAN data as text with value.
  33531. *
  33532. * @param [in] asn1 ASN.1 parse object.
  33533. */
  33534. static void PrintBooleanText(Asn1* asn1)
  33535. {
  33536. /* Booleans should be 1 byte of data. */
  33537. if (asn1->item.len == 1) {
  33538. XFPRINTF(asn1->file, ":%s (%d)",
  33539. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  33540. asn1->data[asn1->item.data_idx]);
  33541. }
  33542. }
  33543. /* Print ASN.1 data as single byte +/- number.
  33544. *
  33545. * @param [in] asn1 ASN.1 parse object.
  33546. */
  33547. static void PrintNumberText(Asn1* asn1)
  33548. {
  33549. /* Only supporting 1 byte of data for now. */
  33550. if (asn1->item.len == 1) {
  33551. int num = asn1->data[asn1->item.data_idx];
  33552. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  33553. }
  33554. }
  33555. /* Print ASN.1 data as a text based on the tag.
  33556. *
  33557. * TODO: handle more tags.
  33558. *
  33559. * @param [in] asn1 ASN.1 parse object.
  33560. * @param [in] opts ASN.1 options for printing.
  33561. */
  33562. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  33563. {
  33564. /* Get the long name for OBJECT_ID where possible. */
  33565. if (asn1->item.tag == ASN_OBJECT_ID) {
  33566. PrintObjectIdText(asn1, opts);
  33567. }
  33568. /* Data is an array of printable characters. */
  33569. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  33570. (asn1->item.tag == ASN_IA5_STRING) ||
  33571. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  33572. (asn1->item.tag == ASN_T61STRING) ||
  33573. (asn1->item.tag == ASN_BMPSTRING) ||
  33574. (asn1->item.tag == ASN_UTC_TIME) ||
  33575. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  33576. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  33577. (asn1->item.tag == ASN_OBJECT_DESC) ||
  33578. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  33579. PrintText(asn1);
  33580. }
  33581. /* Show TRUE and FALSE with number. */
  33582. else if (asn1->item.tag == ASN_BOOLEAN) {
  33583. PrintBooleanText(asn1);
  33584. }
  33585. /* Show number. */
  33586. else if (asn1->item.tag == ASN_ENUMERATED) {
  33587. PrintNumberText(asn1);
  33588. }
  33589. /* Dumping potentially long string of hex digites. */
  33590. else if (!opts->show_no_dump_text) {
  33591. /* Dump all bytes. */
  33592. if ((asn1->item.tag == ASN_INTEGER) ||
  33593. (asn1->item.tag == ASN_OCTET_STRING) ||
  33594. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  33595. PrintHexText(asn1);
  33596. }
  33597. /* First byte is number of unused bits in last byte.
  33598. * Print first specially and dump rest of the bytes. */
  33599. else if (asn1->item.tag == ASN_BIT_STRING) {
  33600. PrintBitStringText(asn1);
  33601. }
  33602. }
  33603. }
  33604. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  33605. /* Dump data as hex bytes.
  33606. *
  33607. * @param [in] file File pointer to write to.
  33608. * @param [in] data Data to print.
  33609. * @param [in] len Number of bytes to print.
  33610. */
  33611. static void DumpData(XFILE file, unsigned char* data, word32 len)
  33612. {
  33613. word32 i;
  33614. word32 j;
  33615. for (i = 0; i < len; i += j) {
  33616. /* Print offset. */
  33617. XFPRINTF(file, " %04x:", i);
  33618. for (j = 0; (j < 16) && (i + j < len); j++) {
  33619. /* Print byte as hex number. */
  33620. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  33621. }
  33622. /* Print spaces between hex and characters. */
  33623. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  33624. for (j = 0; (j < 16) && (i + j < len); j++) {
  33625. /* Print byte as hex number. */
  33626. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  33627. }
  33628. XFPRINTF(file, "\n");
  33629. }
  33630. }
  33631. /* Update current depth based on the current position.
  33632. *
  33633. * @param [in, out] asn1 ASN.1 parse object.
  33634. */
  33635. static void UpdateDepth(Asn1* asn1)
  33636. {
  33637. /* If current index is greater than or equal end index then it is done. */
  33638. while ((asn1->depth > 0) &&
  33639. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  33640. /* Move up a depth. */
  33641. asn1->depth--;
  33642. }
  33643. }
  33644. /* Check validity of end index of constructed ASN.1 items.
  33645. *
  33646. * @param [in, out] asn1 ASN.1 parse object.
  33647. * @return 0 on success.
  33648. * @return ASN_DEPTH_E when end offset invalid.
  33649. */
  33650. static int CheckDepth(Asn1* asn1)
  33651. {
  33652. int ret = 0;
  33653. int i;
  33654. word32 curr_end = asn1->curr + asn1->item.len;
  33655. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  33656. /* Each end index must be at least as large as the current one. */
  33657. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  33658. ret = ASN_DEPTH_E;
  33659. }
  33660. /* Each end index must be at least as large as current index. */
  33661. if (asn1->end_idx[i] < curr_end) {
  33662. ret = ASN_DEPTH_E;
  33663. }
  33664. }
  33665. return ret;
  33666. }
  33667. /* Draw branching based on depth for an ASN.1 item.
  33668. *
  33669. * @param [in] asn1 ASN.1 parse object.
  33670. */
  33671. static void DrawBranch(Asn1* asn1)
  33672. {
  33673. int i;
  33674. word32 end = asn1->curr + asn1->item.len;
  33675. /* Write out the character for all depths but current. */
  33676. for (i = 0; i < asn1->depth; i++) {
  33677. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  33678. if (i < asn1->depth - 1) {
  33679. /* Constructed or not end index and not current depth: | */
  33680. XFPRINTF(asn1->file, "\xe2\x94\x82");
  33681. }
  33682. else {
  33683. /* Constructed or not end index and current depth: |- */
  33684. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  33685. }
  33686. }
  33687. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  33688. /* End index for previous: _|_ (in top half) */
  33689. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  33690. }
  33691. else {
  33692. /* End index but not for previous: L (in top half) */
  33693. XFPRINTF(asn1->file, "\xe2\x94\x94");
  33694. }
  33695. }
  33696. /* Prefix to tag name. */
  33697. if (asn1->item.cons) {
  33698. if (asn1->depth > 0) {
  33699. /* Have other line to connect to: T (in bottom half) */
  33700. XFPRINTF(asn1->file, "\xe2\x94\xac");
  33701. }
  33702. else {
  33703. /* Have no other line to connect to: r */
  33704. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  33705. }
  33706. }
  33707. else {
  33708. /* In a sequence: - */
  33709. XFPRINTF(asn1->file, "\xe2\x94\x80");
  33710. }
  33711. }
  33712. /* Print data as hex bytes separated by space.
  33713. *
  33714. * @param [in] file File pointer to write to.
  33715. * @param [in] data Data to print.
  33716. * @param [in] len Number of bytes to print.
  33717. */
  33718. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  33719. {
  33720. word32 i;
  33721. for (i = 0; i < len; i++) {
  33722. XFPRINTF(file, " %02x", data[i]);
  33723. }
  33724. }
  33725. /* Dump header data.
  33726. *
  33727. * @param [in] asn1 ASN.1 parse object.
  33728. * @param [in] opts ASN.1 options for printing.
  33729. */
  33730. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  33731. {
  33732. /* Put on same line when not showing data too and not showing text data. */
  33733. if ((!opts->show_data) && opts->show_no_text) {
  33734. XFPRINTF(asn1->file, "%10s", "");
  33735. }
  33736. else {
  33737. /* Align with start of data. */
  33738. XFPRINTF(asn1->file, "\n%12s", "");
  33739. }
  33740. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  33741. if (asn1->curr >= asn1->offset + 1) {
  33742. /* Print the header bytes as hex bytes separated by a space. */
  33743. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  33744. asn1->curr - (asn1->offset + 1));
  33745. }
  33746. }
  33747. /* Print ASN.1 item info based on header and indeces.
  33748. *
  33749. * @param [in] asn1 ASN.1 parse object.
  33750. * @param [in] opts ASN.1 options for printing.
  33751. */
  33752. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  33753. {
  33754. /* Print offset of this ASN.1 item. */
  33755. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  33756. /* Print length of header. */
  33757. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  33758. /* Print data length. */
  33759. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  33760. asn1->item.cons ? ']' : ' ');
  33761. /* Print depth. */
  33762. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  33763. if (!opts->draw_branch) {
  33764. /* Indent to depth as required. */
  33765. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  33766. if (!opts->indent) {
  33767. /* Indicate constructed if no indent. */
  33768. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  33769. }
  33770. }
  33771. else {
  33772. /* Draw branch structure for ASN.1 item. */
  33773. XFPRINTF(asn1->file, " ");
  33774. DrawBranch(asn1);
  33775. }
  33776. /* Print tag name. */
  33777. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  33778. }
  33779. /* Expecting tag part of ASN.1 item. */
  33780. #define ASN_PART_TAG 0
  33781. /* Expecting length part of ASN.1 item. */
  33782. #define ASN_PART_LENGTH 1
  33783. /* Expecting data part of ASN.1 item. */
  33784. #define ASN_PART_DATA 2
  33785. /* Print next ASN.1 item.
  33786. *
  33787. * @param [in, out] asn1 ASN.1 parse object.
  33788. * @param [in] opts ASN.1 print options.
  33789. * @return 0 on success.
  33790. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  33791. * @return ASN_LEN_E when ASN.1 item's length too long.
  33792. * @return ASN_DEPTH_E when end offset invalid.
  33793. */
  33794. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  33795. {
  33796. int ret = 0;
  33797. /* Process tag. */
  33798. if (asn1->part == ASN_PART_TAG) {
  33799. /* Recalculate which depth we are at. */
  33800. UpdateDepth(asn1);
  33801. /* Get tag. */
  33802. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  33803. /* Store whether tag indicates constructed. */
  33804. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  33805. ASN_CONSTRUCTED;
  33806. /* Start of ASN.1 item is current index. */
  33807. asn1->offset = asn1->curr;
  33808. /* Step over tag. */
  33809. asn1->curr++;
  33810. /* Next part is length. */
  33811. asn1->part = ASN_PART_LENGTH;
  33812. }
  33813. /* Process length. */
  33814. if (asn1->part == ASN_PART_LENGTH) {
  33815. int len;
  33816. /* Decode length and step over it. */
  33817. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  33818. ret = ASN_LEN_E;
  33819. }
  33820. else {
  33821. /* Store ASN.1 item data offset. */
  33822. asn1->item.data_idx = asn1->curr;
  33823. /* Store ASN.1 item data length. */
  33824. asn1->item.len = (word32)len;
  33825. /* Print info about ASN.1 item. */
  33826. PrintInfo(asn1, opts);
  33827. if (!asn1->item.cons) {
  33828. /* Move on to print data. */
  33829. asn1->part = ASN_PART_DATA;
  33830. }
  33831. else {
  33832. /* Print header now if not printing data. */
  33833. if (opts->show_header_data) {
  33834. DumpHeader(asn1, opts);
  33835. }
  33836. XFPRINTF(asn1->file, "\n");
  33837. /* Record end offset for this depth. */
  33838. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  33839. /* Done with this ASN.1 item. */
  33840. asn1->part = ASN_PART_TAG;
  33841. }
  33842. /* Check end indeces are valid. */
  33843. ret = CheckDepth(asn1);
  33844. }
  33845. }
  33846. /* Process data. */
  33847. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  33848. if (!opts->show_no_text) {
  33849. /* Print text representation of data. */
  33850. PrintAsn1Text(asn1, opts);
  33851. }
  33852. if (opts->show_header_data) {
  33853. /* Dump header bytes. */
  33854. DumpHeader(asn1, opts);
  33855. }
  33856. XFPRINTF(asn1->file, "\n");
  33857. if (opts->show_data) {
  33858. /* Dump data bytes. */
  33859. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  33860. asn1->item.len);
  33861. }
  33862. /* Step past data to next ASN.1 item. */
  33863. asn1->curr += asn1->item.len;
  33864. /* Update the depth based on end indeces. */
  33865. UpdateDepth(asn1);
  33866. /* Done with this ASN.1 item. */
  33867. asn1->part = ASN_PART_TAG;
  33868. }
  33869. /* Make ASN.1 item printing go out. */
  33870. fflush(asn1->file);
  33871. return ret;
  33872. }
  33873. /* Print all ASN.1 items.
  33874. *
  33875. * @param [in, out] asn1 ASN.1 parse object.
  33876. * @param [in] opts ASN.1 print options.
  33877. * @param [in] data BER/DER data to print.
  33878. * @param [in] len Length of data to print in bytes.
  33879. * @return 0 on success.
  33880. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  33881. * @return ASN_LEN_E when ASN.1 item's length too long.
  33882. * @return ASN_DEPTH_E when end offset invalid.
  33883. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  33884. */
  33885. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  33886. word32 len)
  33887. {
  33888. int ret = 0;
  33889. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  33890. ret = BAD_FUNC_ARG;
  33891. }
  33892. if (ret == 0) {
  33893. /* Initialize start position. */
  33894. asn1->curr = 0;
  33895. /* Start parsing at tag. */
  33896. asn1->part = ASN_PART_TAG;
  33897. /* Start depth at 0. */
  33898. asn1->depth = 0;
  33899. /* Store the starting point of the data to parse. */
  33900. asn1->data = data + opts->offset;
  33901. if (opts->length > 0) {
  33902. /* Use user specified maximum length. */
  33903. asn1->max = opts->length;
  33904. }
  33905. else {
  33906. /* Maximum length is up to end from offset. */
  33907. asn1->max = len - opts->offset;
  33908. }
  33909. /* Keep going while no error and have data to parse. */
  33910. while ((ret == 0) && (asn1->curr < asn1->max)) {
  33911. /* Print an ASN.1 item. */
  33912. ret = wc_Asn1_Print(asn1, opts);
  33913. }
  33914. }
  33915. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  33916. /* Stopped before finishing ASN.1 item. */
  33917. ret = ASN_PARSE_E;
  33918. }
  33919. if ((ret == 0) && (asn1->depth != 0)) {
  33920. /* Stopped without seeing all items in a constructed item. */
  33921. ret = ASN_DEPTH_E;
  33922. }
  33923. return ret;
  33924. }
  33925. #endif /* WOLFSSL_ASN_PRINT */
  33926. #endif /* !NO_ASN */
  33927. /* Functions that parse, but are not using ASN.1 */
  33928. #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  33929. (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  33930. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  33931. /* this function does not use any ASN.1 parsing */
  33932. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  33933. word32 eSz, RsaKey* key)
  33934. {
  33935. if (n == NULL || e == NULL || key == NULL)
  33936. return BAD_FUNC_ARG;
  33937. key->type = RSA_PUBLIC;
  33938. if (mp_init(&key->n) != MP_OKAY)
  33939. return MP_INIT_E;
  33940. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  33941. mp_clear(&key->n);
  33942. return ASN_GETINT_E;
  33943. }
  33944. #ifdef HAVE_WOLF_BIGINT
  33945. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  33946. mp_clear(&key->n);
  33947. return ASN_GETINT_E;
  33948. }
  33949. #endif /* HAVE_WOLF_BIGINT */
  33950. if (mp_init(&key->e) != MP_OKAY) {
  33951. mp_clear(&key->n);
  33952. return MP_INIT_E;
  33953. }
  33954. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  33955. mp_clear(&key->n);
  33956. mp_clear(&key->e);
  33957. return ASN_GETINT_E;
  33958. }
  33959. #ifdef HAVE_WOLF_BIGINT
  33960. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  33961. mp_clear(&key->n);
  33962. mp_clear(&key->e);
  33963. return ASN_GETINT_E;
  33964. }
  33965. #endif /* HAVE_WOLF_BIGINT */
  33966. #ifdef WOLFSSL_XILINX_CRYPT
  33967. if (wc_InitRsaHw(key) != 0) {
  33968. return BAD_STATE_E;
  33969. }
  33970. #endif
  33971. return 0;
  33972. }
  33973. #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  33974. #ifdef WOLFSSL_SEP
  33975. #endif /* WOLFSSL_SEP */