asn.c 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590
  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 https://www.rfc-editor.org/rfc/rfc6960#section-4.2.2.2.
  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_NO_CRL_DATE_CHECK: Disable date checks for CRL's.
  71. * WOLFSSL_NO_CRL_NEXT_DATE: Do not fail if CRL next date is missing
  72. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  73. responses. The nonces are optional and may not be supported by all
  74. responders. If it can be ensured that the used responder sends nonces this
  75. option may improve security.
  76. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  77. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  78. templates.
  79. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  80. type issues for testing
  81. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  82. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  83. Only supports copying full AKID from an existing certificate.
  84. * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
  85. extensions
  86. * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
  87. lengths and encodings.
  88. * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
  89. extension.
  90. * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
  91. * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
  92. * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
  93. cost of taking up more memory. Adds initials, givenname, dnQualifer for
  94. example.
  95. * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
  96. * WOLFSSL_ALLOW_ENCODING_CA_FALSE: Allow encoding BasicConstraints CA:FALSE
  97. * which is discouraged by X.690 specification - default values shall not
  98. * be encoded.
  99. * NO_TIME_SIGNEDNESS_CHECK: Disabled the time_t signedness check.
  100. */
  101. #include <wolfssl/wolfcrypt/error-crypt.h>
  102. #ifndef NO_RSA
  103. #include <wolfssl/wolfcrypt/rsa.h>
  104. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  105. extern int wc_InitRsaHw(RsaKey* key);
  106. #endif
  107. #endif
  108. #ifndef NO_ASN
  109. #include <wolfssl/wolfcrypt/asn.h>
  110. #include <wolfssl/wolfcrypt/coding.h>
  111. #include <wolfssl/wolfcrypt/md2.h>
  112. #include <wolfssl/wolfcrypt/hmac.h>
  113. #include <wolfssl/wolfcrypt/pwdbased.h>
  114. #include <wolfssl/wolfcrypt/des3.h>
  115. #include <wolfssl/wolfcrypt/aes.h>
  116. #include <wolfssl/wolfcrypt/rc2.h>
  117. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  118. #include <wolfssl/wolfcrypt/logging.h>
  119. #include <wolfssl/wolfcrypt/random.h>
  120. #include <wolfssl/wolfcrypt/hash.h>
  121. #ifdef NO_INLINE
  122. #include <wolfssl/wolfcrypt/misc.h>
  123. #else
  124. #define WOLFSSL_MISC_INCLUDED
  125. #include <wolfcrypt/src/misc.c>
  126. #endif
  127. #ifndef NO_RC4
  128. #include <wolfssl/wolfcrypt/arc4.h>
  129. #endif
  130. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  131. #include <wolfssl/wolfcrypt/sha512.h>
  132. #endif
  133. #ifndef NO_SHA256
  134. #include <wolfssl/wolfcrypt/sha256.h>
  135. #endif
  136. #ifdef HAVE_ECC
  137. #include <wolfssl/wolfcrypt/ecc.h>
  138. #endif
  139. #ifdef WOLFSSL_SM2
  140. #include <wolfssl/wolfcrypt/sm2.h>
  141. #endif
  142. #ifdef HAVE_ED25519
  143. #include <wolfssl/wolfcrypt/ed25519.h>
  144. #endif
  145. #ifdef HAVE_CURVE25519
  146. #include <wolfssl/wolfcrypt/curve25519.h>
  147. #endif
  148. #ifdef HAVE_ED448
  149. #include <wolfssl/wolfcrypt/ed448.h>
  150. #endif
  151. #ifdef HAVE_CURVE448
  152. #include <wolfssl/wolfcrypt/curve448.h>
  153. #endif
  154. #ifdef HAVE_PQC
  155. #if defined(HAVE_FALCON)
  156. #include <wolfssl/wolfcrypt/falcon.h>
  157. #endif
  158. #if defined(HAVE_DILITHIUM)
  159. #include <wolfssl/wolfcrypt/dilithium.h>
  160. #endif
  161. #if defined(HAVE_SPHINCS)
  162. #include <wolfssl/wolfcrypt/sphincs.h>
  163. #endif
  164. #endif
  165. #ifdef WOLFSSL_QNX_CAAM
  166. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  167. #endif
  168. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  169. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  170. #endif
  171. #ifndef NO_DSA
  172. #include <wolfssl/wolfcrypt/dsa.h>
  173. #else
  174. typedef void* DsaKey;
  175. #endif
  176. #ifdef WOLF_CRYPTO_CB
  177. #include <wolfssl/wolfcrypt/cryptocb.h>
  178. #endif
  179. #ifndef WOLFCRYPT_ONLY
  180. #include <wolfssl/internal.h>
  181. #endif
  182. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  183. #include <wolfssl/openssl/objects.h>
  184. #endif
  185. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  186. !defined(WOLFCRYPT_ONLY)
  187. #define WOLFSSL_X509_NAME_AVAILABLE
  188. #endif
  189. #ifdef _MSC_VER
  190. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  191. #pragma warning(disable: 4996)
  192. #endif
  193. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  194. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  195. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  196. (!defined(HAVE_SELFTEST_VERSION) || \
  197. HAVE_SELFTEST_VERSION < 2))
  198. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  199. #define WOLFSSL_AES_KEY_SIZE_ENUM
  200. enum Asn_Misc {
  201. AES_IV_SIZE = 16,
  202. AES_128_KEY_SIZE = 16,
  203. AES_192_KEY_SIZE = 24,
  204. AES_256_KEY_SIZE = 32
  205. };
  206. #endif
  207. #endif /* HAVE_SELFTEST */
  208. #endif
  209. #if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)
  210. /* String representations of tags. */
  211. static const char* tagString[4][32] = {
  212. /* Universal */
  213. {
  214. "EOC",
  215. "BOOLEAN",
  216. "INTEGER",
  217. "BIT STRING",
  218. "OCTET STRING",
  219. "NULL",
  220. "OBJECT ID",
  221. "ObjectDescriptor",
  222. "INSTANCE OF",
  223. "REAL",
  224. "ENUMERATED",
  225. "EMBEDDED PDV",
  226. "UT8String",
  227. "RELATIVE-OID",
  228. "(0x0e) 14",
  229. "(0x0f) 15",
  230. "SEQUENCE",
  231. "SET",
  232. "NumericString",
  233. "PrintableString",
  234. "T61String",
  235. "VideotexString",
  236. "IA5String",
  237. "UTCTime",
  238. "GeneralizedTime",
  239. "GraphicString",
  240. "ISO646String",
  241. "GeneralString",
  242. "UniversalString",
  243. "CHARACTER STRING",
  244. "BMPString",
  245. "(0x1f) 31",
  246. },
  247. /* Application */
  248. {
  249. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  250. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  251. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  252. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  253. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  254. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  255. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  256. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  257. },
  258. /* Context-Specific */
  259. {
  260. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  261. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  262. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  263. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  264. },
  265. /* Private */
  266. {
  267. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  268. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  269. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  270. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  271. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  272. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  273. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  274. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  275. }
  276. };
  277. /* Converts a tag byte to string.
  278. *
  279. * @param [in] tag BER tag value to interpret.
  280. * @return String corresponding to tag.
  281. */
  282. static const char* TagString(byte tag)
  283. {
  284. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  285. }
  286. #endif
  287. /* Calculates the minimum number of bytes required to encode the value.
  288. *
  289. * @param [in] value Value to be encoded.
  290. * @return Number of bytes to encode value.
  291. */
  292. static word32 BytePrecision(word32 value)
  293. {
  294. word32 i;
  295. for (i = (word32)sizeof(value); i; --i)
  296. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  297. break;
  298. return i;
  299. }
  300. /* DER encodes the length value in output buffer.
  301. *
  302. * 0 -> 2^7-1: <len byte>.
  303. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  304. *
  305. * @param [in] length Value to encode.
  306. * @param [in, out] output Buffer to encode into.
  307. * @return Number of bytes used in encoding.
  308. */
  309. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  310. {
  311. word32 i = 0;
  312. if (length < ASN_LONG_LENGTH)
  313. output[i++] = (byte)length;
  314. else {
  315. word32 j;
  316. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  317. for (j = BytePrecision(length); j; --j) {
  318. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  319. i++;
  320. }
  321. }
  322. return i;
  323. }
  324. #ifdef WOLFSSL_ASN_TEMPLATE
  325. /* Calculate the size of a DER encoded length value.
  326. *
  327. * 0 -> 2^7-1: <length byte>.
  328. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  329. *
  330. * @param [in] length Value to encode.
  331. * @return Number of bytes required to encode.
  332. */
  333. static word32 SizeASNLength(word32 length)
  334. {
  335. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  336. }
  337. /* Calculate the size of a DER encoded header.
  338. *
  339. * Header = Tag | Encoded length
  340. *
  341. * @param [in] length Length value to encode.
  342. * @return Number of bytes required to encode a DER header.
  343. */
  344. #define SizeASNHeader(length) \
  345. (1 + SizeASNLength(length))
  346. #endif
  347. #ifdef WOLFSSL_ASN_TEMPLATE
  348. #ifdef WOLFSSL_SMALL_STACK
  349. /* Declare the variable that is the dynamic data for decoding BER data.
  350. *
  351. * @param [in] name Variable name to declare.
  352. * @param [in] cnt Number of elements required.
  353. */
  354. #define DECL_ASNGETDATA(name, cnt) \
  355. ASNGetData* name = NULL
  356. /* Allocates the dynamic BER decoding data.
  357. *
  358. * @param [in] name Variable name to declare.
  359. * @param [in] cnt Number of elements required.
  360. * @param [in, out] err Error variable.
  361. * @param [in] heap Dynamic memory allocation hint.
  362. */
  363. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  364. do { \
  365. if ((err) == 0) { \
  366. (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  367. DYNAMIC_TYPE_TMP_BUFFER); \
  368. if ((name) == NULL) { \
  369. (err) = MEMORY_E; \
  370. } \
  371. } \
  372. } \
  373. while (0)
  374. /* Allocates the dynamic BER decoding data and clears the memory.
  375. *
  376. * @param [in] name Variable name to declare.
  377. * @param [in] cnt Number of elements required.
  378. * @param [in, out] err Error variable.
  379. * @param [in] heap Dynamic memory allocation hint.
  380. */
  381. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  382. do { \
  383. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  384. if ((err) == 0) { \
  385. XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
  386. } \
  387. } \
  388. while (0)
  389. /* Disposes of the dynamic BER decoding data.
  390. *
  391. * @param [in] name Variable name to declare.
  392. * @param [in] heap Dynamic memory allocation hint.
  393. */
  394. #define FREE_ASNGETDATA(name, heap) \
  395. do { \
  396. if ((name) != NULL) { \
  397. XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
  398. } \
  399. } \
  400. while (0)
  401. /* Declare the variable that is the dynamic data for encoding DER data.
  402. *
  403. * @param [in] name Variable name to declare.
  404. * @param [in] cnt Number of elements required.
  405. */
  406. #define DECL_ASNSETDATA(name, cnt) \
  407. ASNSetData* name = NULL
  408. /* Allocates the dynamic DER encoding data.
  409. *
  410. * @param [in] name Variable name to declare.
  411. * @param [in] cnt Number of elements required.
  412. * @param [in, out] err Error variable.
  413. * @param [in] heap Dynamic memory allocation hint.
  414. */
  415. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  416. do { \
  417. if ((err) == 0) { \
  418. (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  419. DYNAMIC_TYPE_TMP_BUFFER); \
  420. if ((name) == NULL) { \
  421. (err) = MEMORY_E; \
  422. } \
  423. } \
  424. } \
  425. while (0)
  426. /* Allocates the dynamic DER encoding data and clears the memory.
  427. *
  428. * @param [in] name Variable name to declare.
  429. * @param [in] cnt Number of elements required.
  430. * @param [in, out] err Error variable.
  431. * @param [in] heap Dynamic memory allocation hint.
  432. */
  433. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  434. do { \
  435. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  436. if ((err) == 0) { \
  437. XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
  438. } \
  439. } \
  440. while (0)
  441. /* Disposes of the dynamic DER encoding data.
  442. *
  443. * @param [in] name Variable name to declare.
  444. * @param [in] heap Dynamic memory allocation hint.
  445. */
  446. #define FREE_ASNSETDATA(name, heap) \
  447. do { \
  448. if ((name) != NULL) { \
  449. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  450. } \
  451. } \
  452. while (0)
  453. #else
  454. /* Declare the variable that is the dynamic data for decoding BER data.
  455. *
  456. * @param [in] name Variable name to declare.
  457. * @param [in] cnt Number of elements required.
  458. */
  459. #define DECL_ASNGETDATA(name, cnt) \
  460. ASNGetData name[cnt]
  461. /* No implementation as declaration is static.
  462. *
  463. * @param [in] name Variable name to declare.
  464. * @param [in] cnt Number of elements required.
  465. * @param [in, out] err Error variable.
  466. * @param [in] heap Dynamic memory allocation hint.
  467. */
  468. #define ALLOC_ASNGETDATA(name, cnt, err, heap) WC_DO_NOTHING
  469. /* Clears the memory of the dynamic BER encoding data.
  470. *
  471. * @param [in] name Variable name to declare.
  472. * @param [in] cnt Number of elements required.
  473. * @param [in, out] err Error variable.
  474. * @param [in] heap Dynamic memory allocation hint.
  475. */
  476. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  477. XMEMSET(name, 0, sizeof(name))
  478. /* No implementation as declaration is static.
  479. *
  480. * @param [in] name Variable name to declare.
  481. * @param [in] heap Dynamic memory allocation hint.
  482. */
  483. #define FREE_ASNGETDATA(name, heap) WC_DO_NOTHING
  484. /* Declare the variable that is the dynamic data for encoding DER data.
  485. *
  486. * @param [in] name Variable name to declare.
  487. * @param [in] cnt Number of elements required.
  488. */
  489. #define DECL_ASNSETDATA(name, cnt) \
  490. ASNSetData name[cnt]
  491. /* No implementation as declaration is static.
  492. *
  493. * @param [in] name Variable name to declare.
  494. * @param [in] cnt Number of elements required.
  495. * @param [in, out] err Error variable.
  496. * @param [in] heap Dynamic memory allocation hint.
  497. */
  498. #define ALLOC_ASNSETDATA(name, cnt, err, heap) WC_DO_NOTHING
  499. /* Clears the memory of the dynamic BER encoding data.
  500. *
  501. * @param [in] name Variable name to declare.
  502. * @param [in] cnt Number of elements required.
  503. * @param [in, out] err Error variable.
  504. * @param [in] heap Dynamic memory allocation hint.
  505. */
  506. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  507. XMEMSET(name, 0, sizeof(name))
  508. /* No implementation as declaration is static.
  509. *
  510. * @param [in] name Variable name to declare.
  511. * @param [in] heap Dynamic memory allocation hint.
  512. */
  513. #define FREE_ASNSETDATA(name, heap) WC_DO_NOTHING
  514. #endif
  515. #ifdef DEBUG_WOLFSSL
  516. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  517. #if 0
  518. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  519. #endif
  520. #endif
  521. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  522. #include <stdarg.h>
  523. /* Log a message that has the printf format string.
  524. *
  525. * @param [in] <va_args> printf style arguments.
  526. */
  527. #define WOLFSSL_MSG_VSNPRINTF(...) \
  528. do { \
  529. char line[81]; \
  530. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  531. line[sizeof(line) - 1] = '\0'; \
  532. WOLFSSL_MSG(line); \
  533. } \
  534. while (0)
  535. #endif
  536. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  537. *
  538. * @param [in] asn ASN.1 items to encode.
  539. * @param [in] data_a Data to place in each item. Lengths set were not known.
  540. * @param [in] i Index of item to check.
  541. * @return 1 when ASN.1 item is an integer and MSB is 1.
  542. * @return 0 otherwise.
  543. */
  544. #define ASNIntMSBSet(asn, data_a, i) \
  545. (((asn)[i].tag == ASN_INTEGER) && \
  546. ((data_a)[i].data.buffer.data != NULL && \
  547. ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
  548. /* Calculate the size of a DER encoded number.
  549. *
  550. * @param [in] n Number to be encoded.
  551. * @param [in] bits Maximum number of bits to encode.
  552. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  553. * @return Number of bytes to the ASN.1 item.
  554. */
  555. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  556. {
  557. int j;
  558. word32 len;
  559. len = 1 + 1 + (word32)bits / 8;
  560. /* Discover actual size by checking for high zeros. */
  561. for (j = bits - 8; j > 0; j -= 8) {
  562. if (n >> j)
  563. break;
  564. len--;
  565. }
  566. if (tag == ASN_BIT_STRING)
  567. len++;
  568. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  569. len++;
  570. return len;
  571. }
  572. /* Calculate the size of the data in the constructed item based on the
  573. * length of the ASN.1 items below.
  574. *
  575. * @param [in] asn ASN.1 items to encode.
  576. * @param [in, out] data Data to place in each item. Lengths set were not
  577. * known.
  578. * @param [in] idx Index of item working on.
  579. */
  580. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  581. int idx, int maxIdx)
  582. {
  583. int j;
  584. data[idx].data.buffer.length = 0;
  585. /* Sum the item length of all items underneath. */
  586. for (j = idx + 1; j < maxIdx; j++) {
  587. /* Stop looking if the next ASN.1 is same level or higher. */
  588. if (asn[j].depth <= asn[idx].depth)
  589. break;
  590. /* Only add in length if it is one level below. */
  591. if (asn[j].depth - 1 == asn[idx].depth) {
  592. data[idx].data.buffer.length += data[j].length;
  593. /* The length of a header only item doesn't include the data unless
  594. * a replacement buffer is supplied.
  595. */
  596. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  597. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  598. data[idx].data.buffer.length += data[j].data.buffer.length;
  599. }
  600. }
  601. }
  602. }
  603. /* Calculate the size of the DER encoding.
  604. *
  605. * Call SetASN_Items() to write encoding to a buffer.
  606. *
  607. * @param [in] asn ASN.1 items to encode.
  608. * @param [in, out] data Data to place in each item. Lengths set where not
  609. * known.
  610. * @param [in] count Count of items to encode.
  611. * @param [out] encSz Length of the DER encoding.
  612. * @return 0 on success.
  613. * @return BAD_STATE_E when the data type is not supported.
  614. */
  615. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  616. {
  617. int i;
  618. word32 sz = 0;
  619. word32 len;
  620. word32 dataLen;
  621. int length;
  622. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  623. WOLFSSL_ENTER("SizeASN_Items");
  624. #endif
  625. for (i = count - 1; i >= 0; i--) {
  626. /* Skip this ASN.1 item when encoding. */
  627. if (data[i].noOut) {
  628. /* Set the offset to the current size - used in writing DER. */
  629. data[i].offset = sz;
  630. continue;
  631. }
  632. len = 0;
  633. switch (data[i].dataType) {
  634. /* Calculate the size of the number of different sizes. */
  635. case ASN_DATA_TYPE_WORD8:
  636. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  637. break;
  638. case ASN_DATA_TYPE_WORD16:
  639. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  640. break;
  641. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  642. /* Not used yet! */
  643. case ASN_DATA_TYPE_WORD32:
  644. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  645. break;
  646. #endif
  647. case ASN_DATA_TYPE_MP:
  648. /* Calculate the size of the MP integer data. */
  649. length = mp_unsigned_bin_size(data[i].data.mp);
  650. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  651. len = (word32)SizeASNHeader((word32)length) + (word32)length;
  652. break;
  653. case ASN_DATA_TYPE_REPLACE_BUFFER:
  654. /* Buffer is put in directly - use the length. */
  655. len = data[i].data.buffer.length;
  656. break;
  657. case ASN_DATA_TYPE_NONE:
  658. /* Calculate the size based on the data to be included.
  659. * Mostly used for constructed items.
  660. */
  661. if (asn[i].headerOnly) {
  662. if (data[i].data.buffer.data != NULL) {
  663. /* Force all child nodes to be ignored. Buffer
  664. * overwrites children. */
  665. {
  666. int ii;
  667. for (ii = i + 1; ii < count; ii++) {
  668. if (asn[ii].depth <= asn[i].depth)
  669. break;
  670. sz -= data[ii].length;
  671. data[ii].noOut = 1;
  672. }
  673. }
  674. }
  675. else {
  676. /* Calculate data length from items below if no buffer
  677. * supplied. */
  678. SizeASN_CalcDataLength(asn, data, i, count);
  679. }
  680. }
  681. if (asn[i].tag == ASN_BOOLEAN) {
  682. dataLen = 1;
  683. }
  684. else {
  685. dataLen = data[i].data.buffer.length;
  686. }
  687. /* BIT_STRING and INTEGER have one byte prepended. */
  688. if ((asn[i].tag == ASN_BIT_STRING) ||
  689. ASNIntMSBSet(asn, data, i)) {
  690. dataLen++;
  691. /* ASN.1 items are below and cannot include extra byte. */
  692. if (asn[i].headerOnly) {
  693. len++;
  694. }
  695. }
  696. /* Add in the size of tag and length. */
  697. len += SizeASNHeader(dataLen);
  698. /* Include data in length if not header only or if
  699. * buffer supplied. */
  700. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  701. len += dataLen;
  702. }
  703. break;
  704. #ifdef DEBUG_WOLFSSL
  705. default:
  706. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  707. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  708. WOLFSSL_MSG("Bad data type");
  709. #endif
  710. return BAD_STATE_E;
  711. #endif
  712. }
  713. /* Set the total length of the item. */
  714. data[i].length = len;
  715. /* Add length to total size. */
  716. sz += len;
  717. /* Set the offset to the current size - used in writing DER. */
  718. data[i].offset = sz;
  719. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  720. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  721. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  722. asn[i].depth, "", TagString(asn[i].tag));
  723. #endif
  724. }
  725. *encSz = (int)sz;
  726. return 0;
  727. }
  728. /* Create the DER encoding of a number.
  729. *
  730. * Assumes that the out buffer is large enough for encoding.
  731. *
  732. * @param [in] n Number to be encoded.
  733. * @param [in] bits Maximum number of bits to encode.
  734. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  735. */
  736. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  737. {
  738. int j;
  739. word32 idx;
  740. byte len;
  741. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  742. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  743. idx = 2;
  744. /* Set the length of the number based on maximum bit length. */
  745. len = (byte)(bits / 8);
  746. /* Discover actual size by checking for leading zero bytes. */
  747. for (j = bits - 8; j > 0; j -= 8) {
  748. if ((n >> j) != 0) {
  749. break;
  750. }
  751. len--;
  752. }
  753. /* Keep j, index of first non-zero byte, for writing out. */
  754. /* A BIT_STRING has the number of unused bits in last byte prepended to
  755. * data.
  756. */
  757. if (tag == ASN_BIT_STRING) {
  758. byte unusedBits = 0;
  759. byte lastByte = (byte)(n >> j);
  760. /* Quick check last bit. */
  761. if ((lastByte & 0x01) == 0x00) {
  762. unusedBits++;
  763. /* Check each bit for first least significant bit set. */
  764. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  765. unusedBits++;
  766. }
  767. /* Add unused bits byte. */
  768. len++;
  769. out[idx++] = unusedBits;
  770. }
  771. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  772. * value positive. */
  773. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  774. len++;
  775. out[idx++] = 0;
  776. }
  777. /* Go back and put in length. */
  778. out[1] = len;
  779. /* Place in the required bytes of the number. */
  780. for (; j >= 0; j -= 8)
  781. out[idx++] = (byte)(n >> j);
  782. }
  783. /* Creates the DER encoding of the ASN.1 items.
  784. *
  785. * Assumes the output buffer is large enough to hold encoding.
  786. * Must call SizeASN_Items() to determine size of encoding and offsets.
  787. *
  788. * @param [in] asn ASN.1 items to encode.
  789. * @param [in] data Data to place in each item.
  790. * @param [in] count Count of items to encode.
  791. * @param [in, out] output Buffer to write encoding into.
  792. * @return Size of the DER encoding in bytes.
  793. */
  794. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  795. {
  796. int i;
  797. int length;
  798. int err;
  799. word32 sz;
  800. word32 idx;
  801. byte* out;
  802. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  803. WOLFSSL_ENTER("SetASN_Items");
  804. #endif
  805. /* Offset of first item is the total length.
  806. * SizeASN_Items() calculated this. */
  807. sz = data[0].offset;
  808. /* Write out each item. */
  809. for (i = 0; i < count; i++) {
  810. /* Skip items not writing out. */
  811. if (data[i].noOut)
  812. continue;
  813. /* Start position to write item based on reverse offsets. */
  814. out = output + sz - data[i].offset;
  815. /* Index from start of item out. */
  816. idx = 0;
  817. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  818. /* Put in the tag - not dumping in DER from buffer. */
  819. out[idx++] = asn[i].tag |
  820. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  821. }
  822. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  823. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  824. sz - data[i].offset,
  825. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  826. "", TagString(asn[i].tag));
  827. #endif
  828. switch (data[i].dataType) {
  829. /* Write out the length and data of a number. */
  830. case ASN_DATA_TYPE_WORD8:
  831. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  832. break;
  833. case ASN_DATA_TYPE_WORD16:
  834. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  835. break;
  836. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  837. /* Not used yet! */
  838. case ASN_DATA_TYPE_WORD32:
  839. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  840. break;
  841. #endif
  842. /* Write out the length and data of a multi-precision number. */
  843. case ASN_DATA_TYPE_MP:
  844. /* Get length in bytes. */
  845. length = mp_unsigned_bin_size(data[i].data.mp);
  846. /* Add one for leading zero to make encoding a positive num. */
  847. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  848. /* Write out length. */
  849. idx += SetASNLength((word32)length, out + idx);
  850. /* Write out leading zero to make positive. */
  851. if (mp_leading_bit(data[i].data.mp)) {
  852. out[idx++] = 0;
  853. }
  854. /* Encode number in big-endian byte array. */
  855. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  856. if (err != MP_OKAY) {
  857. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  858. return MP_TO_E;
  859. }
  860. break;
  861. case ASN_DATA_TYPE_REPLACE_BUFFER:
  862. if (data[i].data.buffer.data == NULL) {
  863. /* Return pointer for caller to use. */
  864. data[i].data.buffer.data = out + idx;
  865. }
  866. else {
  867. /* Dump in the DER encoded data. */
  868. XMEMCPY(out + idx, data[i].data.buffer.data,
  869. data[i].data.buffer.length);
  870. }
  871. break;
  872. case ASN_DATA_TYPE_NONE:
  873. if (asn[i].tag == ASN_BOOLEAN) {
  874. /* Always one byte of data. */
  875. out[idx++] = 1;
  876. /* TRUE = 0xff, FALSE = 0x00 */
  877. out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
  878. }
  879. else if (asn[i].tag == ASN_TAG_NULL) {
  880. /* NULL tag is always a zero length item. */
  881. out[idx] = 0;
  882. }
  883. else {
  884. word32 dataLen = data[i].data.buffer.length;
  885. /* Add one to data length for BIT_STRING unused bits and
  886. * INTEGER leading zero to make positive.
  887. */
  888. if ((asn[i].tag == ASN_BIT_STRING) ||
  889. ASNIntMSBSet(asn, data, i)) {
  890. dataLen++;
  891. }
  892. /* Write out length. */
  893. idx += SetASNLength(dataLen, out + idx);
  894. if ((asn[i].tag == ASN_BIT_STRING) ||
  895. ASNIntMSBSet(asn, data, i)) {
  896. /* Write out leading byte. BIT_STRING has no unused bits
  897. * - use number data types if needed. */
  898. out[idx++] = 0x00;
  899. }
  900. /* Record pointer for caller if data not supplied. */
  901. if (data[i].data.buffer.data == NULL) {
  902. data[i].data.buffer.data = out + idx;
  903. }
  904. /* Copy supplied data if not putting out header only or
  905. * if buffer supplied. */
  906. else if (!asn[i].headerOnly ||
  907. data[i].data.buffer.data != NULL) {
  908. /* Allow data to come from output buffer. */
  909. XMEMMOVE(out + idx, data[i].data.buffer.data,
  910. data[i].data.buffer.length);
  911. }
  912. }
  913. break;
  914. #ifdef DEBUG_WOLFSSL
  915. default:
  916. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  917. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  918. #endif
  919. return BAD_STATE_E;
  920. #endif
  921. }
  922. }
  923. return (int)sz;
  924. }
  925. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  926. word32 oidType, int length);
  927. /* Maximum supported depth in ASN.1 description. */
  928. #define GET_ASN_MAX_DEPTH 7
  929. /* Maximum number of checked numbered choices. Only one of the items with the
  930. * number is allowed.
  931. */
  932. #define GET_ASN_MAX_CHOICES 2
  933. /* Use existing function to decode BER length encoding. */
  934. #define GetASN_Length GetLength_ex
  935. /* Check an INTEGER's first byte - must be a positive number.
  936. *
  937. * @param [in] input BER encoded data.
  938. * @param [in] idx Index of BIT_STRING data.
  939. * @param [in] length Length of input data.
  940. * @param [in] positive Indicates number must be positive.
  941. * @return 0 on success.
  942. * @return ASN_PARSE_E when 0 is not required but seen.
  943. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  944. */
  945. static int GetASN_Integer(const byte* input, word32 idx, int length,
  946. int positive)
  947. {
  948. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  949. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  950. /* Check contents consist of one or more octets. */
  951. if (length == 0) {
  952. WOLFSSL_MSG("Zero length INTEGER not allowed");
  953. return ASN_PARSE_E;
  954. }
  955. #endif
  956. if (input[idx] == 0) {
  957. /* Check leading zero byte required. */
  958. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  959. WOLFSSL_MSG("Zero not required on INTEGER");
  960. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  961. return ASN_PARSE_E;
  962. #endif
  963. }
  964. }
  965. /* check for invalid padding on negative integer.
  966. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  967. */
  968. else if ((length > 1) && (input[idx] == 0xff) &&
  969. ((input[idx + 1] & 0x80) != 0)) {
  970. WOLFSSL_MSG("Bad INTEGER encoding of negative");
  971. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  972. return ASN_EXPECT_0_E;
  973. #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
  974. }
  975. /* Check whether a leading zero byte was required. */
  976. else if (positive && (input[idx] & 0x80)) {
  977. WOLFSSL_MSG("INTEGER is negative");
  978. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  979. return ASN_EXPECT_0_E;
  980. #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
  981. }
  982. return 0;
  983. }
  984. /* Check a BIT_STRING's first byte - unused bits.
  985. *
  986. * @param [in] input BER encoded data.
  987. * @param [in] idx Index of BIT_STRING data.
  988. * @param [in] length Length of input data.
  989. * @return 0 on success.
  990. * @return ASN_PARSE_E when unused bits is invalid.
  991. */
  992. static int GetASN_BitString(const byte* input, word32 idx, int length)
  993. {
  994. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  995. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  996. /* Check contents consist of one or more octets. */
  997. if (length == 0) {
  998. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  999. WOLFSSL_MSG("Zero length BIT STRING not allowed");
  1000. #endif
  1001. return ASN_PARSE_E;
  1002. }
  1003. #endif
  1004. /* Ensure unused bits value is valid range. */
  1005. if (input[idx] > 7) {
  1006. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1007. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  1008. input[idx]);
  1009. #endif
  1010. return ASN_PARSE_E;
  1011. }
  1012. /* Ensure unused bits are zero. */
  1013. if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
  1014. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1015. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  1016. input[idx], input[idx + length - 1]);
  1017. #endif
  1018. return ASN_PARSE_E;
  1019. }
  1020. return 0;
  1021. }
  1022. #ifndef WOLFSSL_NO_ASN_STRICT
  1023. /* Check a UTF8STRING's data is valid.
  1024. *
  1025. * @param [in] input BER encoded data.
  1026. * @param [in] idx Index of UTF8STRING data.
  1027. * @param [in] length Length of input data.
  1028. * @return 0 on success.
  1029. * @return ASN_PARSE_E when data is invalid.
  1030. */
  1031. static int GetASN_UTF8String(const byte* input, word32 idx, int length)
  1032. {
  1033. int ret = 0;
  1034. word32 i = 0;
  1035. while ((ret == 0) && ((int)i < length)) {
  1036. int cnt;
  1037. /* Check code points and get count of following bytes. */
  1038. if ((input[idx + i] & 0x80) == 0x00) {
  1039. cnt = 0;
  1040. }
  1041. else if ((input[idx + i] & 0xe0) == 0xc0) {
  1042. cnt = 1;
  1043. }
  1044. else if ((input[idx + i] & 0xf0) == 0xe0) {
  1045. cnt = 2;
  1046. }
  1047. else if ((input[idx + i] & 0xf8) == 0xf0) {
  1048. cnt = 3;
  1049. }
  1050. else {
  1051. WOLFSSL_MSG("Invalid character in UTF8STRING\n");
  1052. ret = ASN_PARSE_E;
  1053. break;
  1054. }
  1055. /* Have checked first byte. */
  1056. i++;
  1057. /* Check each following byte. */
  1058. for (; cnt > 0; cnt--) {
  1059. /* Check we have enough data. */
  1060. if ((int)i == length) {
  1061. WOLFSSL_MSG("Missing character in UTF8STRING\n");
  1062. ret = ASN_PARSE_E;
  1063. break;
  1064. }
  1065. /* Check following byte has top bit set. */
  1066. if ((input[idx + i] & 0x80) != 0x80) {
  1067. WOLFSSL_MSG("Invalid character in UTF8STRING\n");
  1068. ret = ASN_PARSE_E;
  1069. break;
  1070. }
  1071. i++;
  1072. }
  1073. }
  1074. return ret;
  1075. }
  1076. #endif
  1077. /* Check an OBJECT IDENTIFIER's data is valid.
  1078. *
  1079. * X.690 8.19
  1080. *
  1081. * @param [in] input BER encoded data.
  1082. * @param [in] idx Index of OBJECT IDENTIFIER data.
  1083. * @param [in] length Length of input data.
  1084. * @return 0 on success.
  1085. * @return ASN_PARSE_E when data is invalid.
  1086. */
  1087. static int GetASN_ObjectId(const byte* input, word32 idx, int length)
  1088. {
  1089. int ret = 0;
  1090. /* OID data must be at least 3 bytes. */
  1091. if (length < 3) {
  1092. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1093. WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
  1094. #else
  1095. WOLFSSL_MSG("OID length less than 3");
  1096. #endif
  1097. ret = ASN_PARSE_E;
  1098. }
  1099. /* Last octet of a subidentifier has bit 8 clear. Last octet must be last
  1100. * of a subidentifier. Ensure last octet hasn't got top bit set indicating.
  1101. */
  1102. else if ((input[(int)idx + length - 1] & 0x80) != 0x00) {
  1103. WOLFSSL_MSG("OID last octet has top bit set");
  1104. ret = ASN_PARSE_E;
  1105. }
  1106. return ret;
  1107. }
  1108. /* Get the ASN.1 items from the BER encoding.
  1109. *
  1110. * @param [in] asn ASN.1 item expected.
  1111. * @param [in] data Data array to place found item into.
  1112. * @param [in] input BER encoded data.
  1113. * @param [in] idx Starting index of item data.
  1114. * @param [in] len Length of input buffer upto end of this item's data.
  1115. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  1116. * @return 0 on success.
  1117. * @return ASN_PARSE_E when BER encoded data is invalid.
  1118. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  1119. * @return MP_INIT_E when the unable to initialize an mp_int.
  1120. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1121. * @return BAD_STATE_E when the data type is not supported.
  1122. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1123. */
  1124. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  1125. const byte* input, word32 idx, int len,
  1126. int zeroPadded)
  1127. {
  1128. int i;
  1129. int err;
  1130. /* Parse data based on data type to extract. */
  1131. switch (data->dataType) {
  1132. /* Parse a data into a number of specified bits. */
  1133. case ASN_DATA_TYPE_WORD8:
  1134. /* Check data is small enough to fit. */
  1135. if (len != 1) {
  1136. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1137. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  1138. #endif
  1139. return ASN_PARSE_E;
  1140. }
  1141. /* Fill number with all of data. */
  1142. *data->data.u8 = input[idx];
  1143. break;
  1144. case ASN_DATA_TYPE_WORD16:
  1145. /* Check data is small enough to fit. */
  1146. if (len == 0 || len > 2) {
  1147. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1148. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  1149. #endif
  1150. return ASN_PARSE_E;
  1151. }
  1152. /* Fill number with all of data. */
  1153. *data->data.u16 = 0;
  1154. for (i = 0; i < len; i++) {
  1155. *data->data.u16 <<= 8;
  1156. *data->data.u16 |= input[idx + (word32)i] ;
  1157. }
  1158. break;
  1159. case ASN_DATA_TYPE_WORD32:
  1160. /* Check data is small enough to fit. */
  1161. if (len == 0 || len > 4) {
  1162. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1163. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1164. #endif
  1165. return ASN_PARSE_E;
  1166. }
  1167. /* Fill number with all of data. */
  1168. *data->data.u32 = 0;
  1169. for (i = 0; i < len; i++) {
  1170. *data->data.u32 <<= 8;
  1171. *data->data.u32 |= input[idx + (word32)i] ;
  1172. }
  1173. break;
  1174. case ASN_DATA_TYPE_BUFFER:
  1175. /* Check buffer is big enough to hold data. */
  1176. if (len > (int)*data->data.buffer.length) {
  1177. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1178. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1179. *data->data.buffer.length);
  1180. #endif
  1181. return ASN_PARSE_E;
  1182. }
  1183. /* Copy in data and record actual length seen. */
  1184. XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
  1185. *data->data.buffer.length = (word32)len;
  1186. break;
  1187. case ASN_DATA_TYPE_EXP_BUFFER:
  1188. /* Check data is same size expected. */
  1189. if (len != (int)data->data.ref.length) {
  1190. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1191. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1192. data->data.ref.length);
  1193. #endif
  1194. return ASN_PARSE_E;
  1195. }
  1196. /* Check data is same as expected. */
  1197. if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
  1198. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1199. WOLFSSL_MSG("Data not as expected");
  1200. #endif
  1201. return ASN_PARSE_E;
  1202. }
  1203. break;
  1204. case ASN_DATA_TYPE_MP:
  1205. case ASN_DATA_TYPE_MP_POS_NEG:
  1206. /* Initialize mp_int and read in big-endian byte array. */
  1207. if (mp_init(data->data.mp) != MP_OKAY) {
  1208. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1209. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1210. #endif
  1211. return MP_INIT_E;
  1212. }
  1213. FALL_THROUGH;
  1214. case ASN_DATA_TYPE_MP_INITED:
  1215. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
  1216. (word32)len);
  1217. if (err != 0) {
  1218. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1219. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1220. #endif
  1221. mp_clear(data->data.mp);
  1222. return ASN_GETINT_E;
  1223. }
  1224. #ifdef HAVE_WOLF_BIGINT
  1225. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1226. len);
  1227. if (err != 0) {
  1228. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1229. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1230. #endif
  1231. mp_clear(data->data.mp);
  1232. return ASN_GETINT_E;
  1233. }
  1234. #endif /* HAVE_WOLF_BIGINT */
  1235. #ifdef WOLFSSL_SP_INT_NEGATIVE
  1236. /* Don't always read as positive. */
  1237. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1238. (input[idx] & 0x80)) {
  1239. #ifdef MP_NEG
  1240. data->data.mp->sign = MP_NEG;
  1241. #else
  1242. #ifdef OPENSSL_EXTRA
  1243. /* public API wolfSSL_ASN1_INTEGER_get() depends
  1244. * indirectly on negative bignum handling here.
  1245. */
  1246. #error OPENSSL_EXTRA requires negative bignum support.
  1247. #endif
  1248. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1249. WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
  1250. #endif
  1251. mp_clear(data->data.mp);
  1252. return ASN_GETINT_E;
  1253. #endif
  1254. }
  1255. #else
  1256. (void)zeroPadded;
  1257. #endif
  1258. break;
  1259. case ASN_DATA_TYPE_CHOICE:
  1260. /* Check if tag matched any of the choices specified. */
  1261. for (i = 0; data->data.choice[i] != 0; i++)
  1262. if (data->data.choice[i] == data->tag)
  1263. break;
  1264. if (data->data.choice[i] == 0) {
  1265. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1266. WOLFSSL_MSG("Tag didn't match a choice");
  1267. #endif
  1268. return ASN_PARSE_E;
  1269. }
  1270. /* Store data pointer and length for caller. */
  1271. data->data.ref.data = input + idx;
  1272. data->data.ref.length = (word32)len;
  1273. break;
  1274. case ASN_DATA_TYPE_NONE:
  1275. /* Default behaviour based on tag. */
  1276. if (asn->tag == ASN_BOOLEAN) {
  1277. /* BOOLEAN has only one byte of data in BER. */
  1278. if (len != 1) {
  1279. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1280. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1281. #endif
  1282. return ASN_PARSE_E;
  1283. }
  1284. if (data->data.u8 == NULL)
  1285. return BAD_STATE_E;
  1286. /* Store C boolean value. */
  1287. *data->data.u8 = (input[idx] != 0);
  1288. break;
  1289. }
  1290. if (asn->tag == ASN_TAG_NULL) {
  1291. /* NULL has no data in BER. */
  1292. if (len != 0) {
  1293. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1294. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1295. #endif
  1296. return ASN_EXPECT_0_E;
  1297. }
  1298. data->data.ref.data = input + idx;
  1299. break;
  1300. }
  1301. if (asn->tag == ASN_OBJECT_ID) {
  1302. word32 oidIdx = 0;
  1303. /* Store OID data pointer and length */
  1304. data->data.oid.data = input + idx;
  1305. data->data.oid.length = (word32)len;
  1306. /* Get the OID sum. */
  1307. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1308. data->data.oid.type, len);
  1309. if (err < 0) {
  1310. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1311. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1312. #endif
  1313. return err;
  1314. }
  1315. break;
  1316. }
  1317. /* Otherwise store data pointer and length. */
  1318. data->data.ref.data = input + idx;
  1319. data->data.ref.length = (word32)len;
  1320. break;
  1321. #ifdef DEBUG_WOLFSSL
  1322. default:
  1323. /* Bad ASN data type. */
  1324. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1325. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1326. #endif
  1327. return BAD_STATE_E;
  1328. #endif
  1329. }
  1330. return 0;
  1331. }
  1332. /* Get the ASN.1 items from the BER encoding.
  1333. *
  1334. * @param [in] asn ASN.1 items expected.
  1335. * @param [in] data Data array to place found items into.
  1336. * @param [in] count Count of items to parse.
  1337. * @param [in] complete Whether the whole buffer is to be used up.
  1338. * @param [in] input BER encoded data.
  1339. * @param [in, out] inOutIdx On in, starting index of data.
  1340. * On out, end of parsed data.
  1341. * @param [in] length Length of input buffer.
  1342. * @return 0 on success.
  1343. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1344. * is invalid.
  1345. * @return BUFFER_E when data in buffer is too small.
  1346. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1347. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1348. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1349. * non-zero length.
  1350. * @return MP_INIT_E when the unable to initialize an mp_int.
  1351. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1352. * @return BAD_STATE_E when the data type is not supported.
  1353. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1354. */
  1355. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1356. const byte* input, word32* inOutIdx, word32 length)
  1357. {
  1358. int i;
  1359. int j;
  1360. int err;
  1361. int len;
  1362. /* Current index into buffer. */
  1363. word32 idx = *inOutIdx;
  1364. /* Declare the end index array. */
  1365. word32 endIdx[GET_ASN_MAX_DEPTH];
  1366. /* Set choices to -1 to indicate they haven't been seen or found. */
  1367. signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1368. /* Not matching a choice right now. */
  1369. int choice = 0;
  1370. /* Current depth of ASN.1 item. */
  1371. int depth;
  1372. /* Minimum depth value seen. */
  1373. int minDepth;
  1374. /* Integer had a zero prepended. */
  1375. int zeroPadded;
  1376. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1377. WOLFSSL_ENTER("GetASN_Items");
  1378. #endif
  1379. /* Set the end index at each depth to be the length. */
  1380. for (i=0; i<GET_ASN_MAX_DEPTH; i++) {
  1381. endIdx[i] = length;
  1382. }
  1383. /* Start depth at first items depth. */
  1384. minDepth = depth = asn[0].depth;
  1385. /* Check every ASN.1 item. */
  1386. for (i = 0; i < count; i++) {
  1387. /* Store offset of ASN.1 item. */
  1388. data[i].offset = idx;
  1389. /* Length of data in ASN.1 item starts empty. */
  1390. data[i].length = 0;
  1391. /* Get current item depth. */
  1392. depth = asn[i].depth;
  1393. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1394. if (depth > GET_ASN_MAX_DEPTH) {
  1395. WOLFSSL_MSG("Depth in template too large");
  1396. return ASN_PARSE_E;
  1397. }
  1398. #endif
  1399. /* Keep track of minimum depth. */
  1400. if (depth < minDepth) {
  1401. minDepth = depth;
  1402. }
  1403. /* Reset choice if different from previous. */
  1404. if (choice > 0 && asn[i].optional != choice) {
  1405. choice = 0;
  1406. }
  1407. /* Check if first of numbered choice. */
  1408. if (choice == 0 && asn[i].optional > 1) {
  1409. choice = asn[i].optional;
  1410. if (choiceMet[choice - 2] == -1) {
  1411. /* Choice seen but not found a match yet. */
  1412. choiceMet[choice - 2] = 0;
  1413. }
  1414. }
  1415. /* Check for end of data or not a choice and tag not matching. */
  1416. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1417. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1418. if (asn[i].optional) {
  1419. /* Skip over ASN.1 items underneath this optional item. */
  1420. for (j = i + 1; j < count; j++) {
  1421. if (asn[i].depth >= asn[j].depth)
  1422. break;
  1423. data[j].offset = idx;
  1424. data[j].length = 0;
  1425. }
  1426. i = j - 1;
  1427. continue;
  1428. }
  1429. /* Check for end of data. */
  1430. if (idx == length) {
  1431. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1432. WOLFSSL_MSG_VSNPRINTF(
  1433. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1434. i, data[i].offset, data[i].length,
  1435. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1436. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1437. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1438. length);
  1439. #endif
  1440. return BUFFER_E;
  1441. }
  1442. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1443. /* Show expected versus found. */
  1444. WOLFSSL_MSG_VSNPRINTF(
  1445. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1446. i, data[i].offset, data[i].length,
  1447. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1448. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1449. input[idx], TagString(input[idx]));
  1450. #endif
  1451. /* Check for end of data at this depth. */
  1452. if (idx == endIdx[depth]) {
  1453. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1454. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1455. endIdx[depth]);
  1456. #endif
  1457. return ASN_PARSE_E;
  1458. }
  1459. /* Expecting an OBJECT_ID */
  1460. if (asn[i].tag == ASN_OBJECT_ID) {
  1461. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1462. WOLFSSL_MSG("Expecting OBJECT ID");
  1463. #endif
  1464. return ASN_OBJECT_ID_E;
  1465. }
  1466. /* Expecting a BIT_STRING */
  1467. if (asn[i].tag == ASN_BIT_STRING) {
  1468. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1469. WOLFSSL_MSG("Expecting BIT STRING");
  1470. #endif
  1471. return ASN_BITSTR_E;
  1472. }
  1473. /* Not the expected tag. */
  1474. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1475. WOLFSSL_MSG("Bad tag");
  1476. #endif
  1477. return ASN_PARSE_E;
  1478. }
  1479. /* Store found tag in data. */
  1480. data[i].tag = input[idx];
  1481. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1482. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1483. /* Check constructed match expected for non-choice ASN.1 item. */
  1484. if (asn[i].constructed != constructed) {
  1485. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1486. WOLFSSL_MSG_VSNPRINTF(
  1487. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1488. i, data[i].offset, data[i].length,
  1489. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1490. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1491. input[idx], TagString(input[idx]));
  1492. if (!constructed) {
  1493. WOLFSSL_MSG("Not constructed");
  1494. }
  1495. else {
  1496. WOLFSSL_MSG("Not expected to be constructed");
  1497. }
  1498. #endif
  1499. return ASN_PARSE_E;
  1500. }
  1501. }
  1502. /* Move index to start of length. */
  1503. idx++;
  1504. /* Get the encoded length. */
  1505. if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
  1506. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1507. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1508. endIdx[depth]);
  1509. #endif
  1510. return ASN_PARSE_E;
  1511. }
  1512. /* Store length of data. */
  1513. data[i].length = (word32)len;
  1514. /* Note the max length of items under this one. */
  1515. endIdx[depth + 1] = idx + (word32)len;
  1516. if (choice > 1) {
  1517. /* Note we found a number choice. */
  1518. choiceMet[choice - 2] = 1;
  1519. }
  1520. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1521. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1522. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1523. asn[i].depth, "", TagString(data[i].tag));
  1524. #endif
  1525. /* Assume no zero padding on INTEGER. */
  1526. zeroPadded = 0;
  1527. /* Check data types that prepended a byte. */
  1528. if (asn[i].tag == ASN_INTEGER) {
  1529. /* Check validity of first byte. */
  1530. err = GetASN_Integer(input, idx, len,
  1531. data[i].dataType == ASN_DATA_TYPE_MP ||
  1532. data[i].dataType == ASN_DATA_TYPE_MP_INITED);
  1533. if (err != 0)
  1534. return err;
  1535. if (len > 1 && input[idx] == 0) {
  1536. zeroPadded = 1;
  1537. /* Move over prepended byte. */
  1538. idx++;
  1539. len--;
  1540. }
  1541. }
  1542. else if (asn[i].tag == ASN_BIT_STRING) {
  1543. /* Check prepended byte is correct. */
  1544. err = GetASN_BitString(input, idx, len);
  1545. if (err != 0)
  1546. return err;
  1547. /* Move over prepended byte. */
  1548. idx++;
  1549. len--;
  1550. }
  1551. #ifndef WOLFSSL_NO_ASN_STRICT
  1552. else if ((asn[i].tag == ASN_UTF8STRING) ||
  1553. (data[i].tag == ASN_UTF8STRING)) {
  1554. /* Check validity of data. */
  1555. err = GetASN_UTF8String(input, idx, len);
  1556. if (err != 0)
  1557. return err;
  1558. }
  1559. #endif
  1560. else if (asn[i].tag == ASN_OBJECT_ID) {
  1561. /* Check validity of data. */
  1562. err = GetASN_ObjectId(input, idx, len);
  1563. if (err != 0)
  1564. return err;
  1565. }
  1566. /* Don't parse data if only header required. */
  1567. if (asn[i].headerOnly) {
  1568. /* Store reference to data and length. */
  1569. data[i].data.ref.data = input + idx;
  1570. data[i].data.ref.length = (word32)len;
  1571. continue;
  1572. }
  1573. /* Store the data at idx in the ASN data item. */
  1574. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1575. if (err != 0) {
  1576. return err;
  1577. }
  1578. /* Move index to next item. */
  1579. idx += (word32)len;
  1580. /* When matched numbered choice ... */
  1581. if (asn[i].optional > 1) {
  1582. /* Skip over other ASN.1 items of the same number. */
  1583. for (j = i + 1; j < count; j++) {
  1584. if (asn[j].depth <= asn[i].depth &&
  1585. asn[j].optional != asn[i].optional) {
  1586. break;
  1587. }
  1588. }
  1589. i = j - 1;
  1590. }
  1591. }
  1592. if (complete) {
  1593. /* When expecting ASN.1 items to completely use data, check we did. */
  1594. for (j = depth; j > minDepth; j--) {
  1595. if (idx < endIdx[j]) {
  1596. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1597. WOLFSSL_MSG_VSNPRINTF(
  1598. "More data in constructed item at depth: %d", j - 1);
  1599. #endif
  1600. return ASN_PARSE_E;
  1601. }
  1602. }
  1603. }
  1604. /* Check all choices where met - found an item for them. */
  1605. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1606. if (choiceMet[j] == 0) {
  1607. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1608. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1609. #endif
  1610. return ASN_PARSE_E;
  1611. }
  1612. }
  1613. /* Return index after ASN.1 data has been parsed. */
  1614. *inOutIdx = idx;
  1615. return 0;
  1616. }
  1617. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1618. /* Calculate the size of the DER encoding.
  1619. *
  1620. * Call SetASN_Items() to write encoding to a buffer.
  1621. *
  1622. * @param [in] asn ASN.1 items to encode.
  1623. * @param [in, out] data Data to place in each item. Lengths set were not
  1624. * known.
  1625. * @param [in] count Count of items to encode.
  1626. * @param [out] len Length of the DER encoding.
  1627. * @return Size of the DER encoding in bytes.
  1628. */
  1629. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1630. ASNSetData *data, int count, int* encSz)
  1631. {
  1632. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1633. return SizeASN_Items(asn, data, count, encSz);
  1634. }
  1635. /* Creates the DER encoding of the ASN.1 items.
  1636. *
  1637. * Assumes the output buffer is large enough to hold encoding.
  1638. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1639. *
  1640. * Displays the template name first.
  1641. *
  1642. * @param [in] name Name of ASN.1 template.
  1643. * @param [in] asn ASN.1 items to encode.
  1644. * @param [in] data Data to place in each item.
  1645. * @param [in] count Count of items to encode.
  1646. * @param [in, out] output Buffer to write encoding into.
  1647. * @return Size of the DER encoding in bytes.
  1648. */
  1649. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1650. ASNSetData *data, int count, byte* output)
  1651. {
  1652. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1653. return SetASN_Items(asn, data, count, output);
  1654. }
  1655. /* Get the ASN.1 items from the BER encoding.
  1656. *
  1657. * Displays the template name first.
  1658. *
  1659. * @param [in] name Name of ASN.1 template.
  1660. * @param [in] asn ASN.1 items expected.
  1661. * @param [in] data Data array to place found items into.
  1662. * @param [in] count Count of items to parse.
  1663. * @param [in] complete Whether the whole buffer is to be used up.
  1664. * @param [in] input BER encoded data.
  1665. * @param [in, out] inOutIdx On in, starting index of data.
  1666. * On out, end of parsed data.
  1667. * @param [in] maxIdx Maximum index of input data.
  1668. * @return 0 on success.
  1669. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1670. * is invalid.
  1671. * @return BUFFER_E when data in buffer is too small.
  1672. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1673. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1674. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1675. * non-zero length.
  1676. * @return MP_INIT_E when the unable to initialize an mp_int.
  1677. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1678. * @return BAD_STATE_E when the data type is not supported.
  1679. */
  1680. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1681. ASNGetData *data, int count, int complete, const byte* input,
  1682. word32* inOutIdx, word32 maxIdx)
  1683. {
  1684. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1685. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1686. }
  1687. /* Calculate the size of the DER encoding.
  1688. *
  1689. * Call SetASN_Items() to write encoding to a buffer.
  1690. *
  1691. * @param [in] asn ASN.1 items to encode.
  1692. * @param [in, out] data Data to place in each item. Lengths set were not
  1693. * known.
  1694. * @param [in] count Count of items to encode.
  1695. * @param [out] len Length of the DER encoding.
  1696. * @return Size of the DER encoding in bytes.
  1697. */
  1698. #define SizeASN_Items(asn, data, count, encSz) \
  1699. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1700. /* Creates the DER encoding of the ASN.1 items.
  1701. *
  1702. * Assumes the output buffer is large enough to hold encoding.
  1703. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1704. *
  1705. * Displays the template name first.
  1706. *
  1707. * @param [in] name Name of ASN.1 template.
  1708. * @param [in] asn ASN.1 items to encode.
  1709. * @param [in] data Data to place in each item.
  1710. * @param [in] count Count of items to encode.
  1711. * @param [in, out] output Buffer to write encoding into.
  1712. * @return Size of the DER encoding in bytes.
  1713. */
  1714. #define SetASN_Items(asn, data, count, output) \
  1715. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1716. /* Get the ASN.1 items from the BER encoding.
  1717. *
  1718. * Displays the template name first.
  1719. *
  1720. * @param [in] name Name of ASN.1 template.
  1721. * @param [in] asn ASN.1 items expected.
  1722. * @param [in] data Data array to place found items into.
  1723. * @param [in] count Count of items to parse.
  1724. * @param [in] complete Whether the whole buffer is to be used up.
  1725. * @param [in] input BER encoded data.
  1726. * @param [in, out] inOutIdx On in, starting index of data.
  1727. * On out, end of parsed data.
  1728. * @param [in] maxIdx Maximum index of input data.
  1729. * @return 0 on success.
  1730. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1731. * is invalid.
  1732. * @return BUFFER_E when data in buffer is too small.
  1733. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1734. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1735. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1736. * non-zero length.
  1737. * @return MP_INIT_E when the unable to initialize an mp_int.
  1738. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1739. * @return BAD_STATE_E when the data type is not supported.
  1740. */
  1741. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1742. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1743. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1744. /* Decode a BER encoded constructed sequence.
  1745. *
  1746. * @param [in] input Buffer of BER encoded data.
  1747. * @param [in, out] inOutIdx On in, index to start decoding from.
  1748. * On out, index of next encoded byte.
  1749. * @param [out] len Length of data under SEQUENCE.
  1750. * @param [in] maxIdx Maximum index of data. Index of byte after SEQ.
  1751. * @param [in] complete All data used with SEQUENCE and data under.
  1752. * @return 0 on success.
  1753. * @return BUFFER_E when not enough data to complete decode.
  1754. * @return ASN_PARSE when decoding failed.
  1755. */
  1756. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1757. word32 maxIdx, int complete)
  1758. {
  1759. int ret = 0;
  1760. word32 idx = *inOutIdx;
  1761. /* Check buffer big enough for tag. */
  1762. if (idx + 1 > maxIdx) {
  1763. ret = BUFFER_E;
  1764. }
  1765. /* Check it is a constructed SEQUENCE. */
  1766. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1767. ret = ASN_PARSE_E;
  1768. }
  1769. /* Get the length. */
  1770. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1771. ret = ASN_PARSE_E;
  1772. }
  1773. /* Check all data used if complete set. */
  1774. if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
  1775. ret = ASN_PARSE_E;
  1776. }
  1777. if (ret == 0) {
  1778. /* Return index of next byte of encoded data. */
  1779. *inOutIdx = idx;
  1780. }
  1781. return ret;
  1782. }
  1783. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1784. /* Setup ASN data item to get an 8-bit number.
  1785. *
  1786. * @param [in] dataASN Dynamic ASN data item.
  1787. * @param [in] num Pointer to an 8-bit variable.
  1788. */
  1789. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1790. {
  1791. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1792. dataASN->data.u8 = num;
  1793. }
  1794. /* Setup ASN data item to get a 16-bit number.
  1795. *
  1796. * @param [in] dataASN Dynamic ASN data item.
  1797. * @param [in] num Pointer to a 16-bit variable.
  1798. */
  1799. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1800. {
  1801. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1802. dataASN->data.u16 = num;
  1803. }
  1804. /* Setup ASN data item to get a 32-bit number.
  1805. *
  1806. * @param [in] dataASN Dynamic ASN data item.
  1807. * @param [in] num Pointer to a 32-bit variable.
  1808. */
  1809. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1810. {
  1811. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1812. dataASN->data.u32 = num;
  1813. }
  1814. /* Setup ASN data item to get data into a buffer of a specific length.
  1815. *
  1816. * @param [in] dataASN Dynamic ASN data item.
  1817. * @param [in] data Buffer to hold data.
  1818. * @param [in] length Length of buffer in bytes.
  1819. */
  1820. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1821. {
  1822. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1823. dataASN->data.buffer.data = data;
  1824. dataASN->data.buffer.length = length;
  1825. }
  1826. /* Setup ASN data item to check parsed data against expected buffer.
  1827. *
  1828. * @param [in] dataASN Dynamic ASN data item.
  1829. * @param [in] data Buffer containing expected data.
  1830. * @param [in] length Length of buffer in bytes.
  1831. */
  1832. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1833. {
  1834. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1835. dataASN->data.ref.data = data;
  1836. dataASN->data.ref.length = length;
  1837. }
  1838. /* Setup ASN data item to get a number into an mp_int.
  1839. *
  1840. * @param [in] dataASN Dynamic ASN data item.
  1841. * @param [in] num Multi-precision number object.
  1842. */
  1843. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1844. {
  1845. dataASN->dataType = ASN_DATA_TYPE_MP;
  1846. dataASN->data.mp = num;
  1847. }
  1848. /* Setup ASN data item to get a number into an mp_int that is initialized.
  1849. *
  1850. * @param [in] dataASN Dynamic ASN data item.
  1851. * @param [in] num Multi-precision number object.
  1852. */
  1853. void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
  1854. {
  1855. dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
  1856. dataASN->data.mp = num;
  1857. }
  1858. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1859. *
  1860. * @param [in] dataASN Dynamic ASN data item.
  1861. * @param [in] num Multi-precision number object.
  1862. */
  1863. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1864. {
  1865. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1866. dataASN->data.mp = num;
  1867. }
  1868. /* Setup ASN data item to be a choice of tags.
  1869. *
  1870. * @param [in] dataASN Dynamic ASN data item.
  1871. * @param [in] options 0 terminated list of tags that are valid.
  1872. */
  1873. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1874. {
  1875. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1876. dataASN->data.choice = options;
  1877. }
  1878. /* Setup ASN data item to get a boolean value.
  1879. *
  1880. * @param [in] dataASN Dynamic ASN data item.
  1881. * @param [in] num Pointer to an 8-bit variable.
  1882. */
  1883. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1884. {
  1885. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1886. dataASN->data.choice = num;
  1887. }
  1888. /* Setup ASN data item to be a an OID of a specific type.
  1889. *
  1890. * @param [in] dataASN Dynamic ASN data item.
  1891. * @param [in] oidType Type of OID to expect.
  1892. */
  1893. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1894. {
  1895. dataASN->data.oid.type = oidType;
  1896. }
  1897. /* Get the data and length from an ASN data item.
  1898. *
  1899. * @param [in] dataASN Dynamic ASN data item.
  1900. * @param [out] data Pointer to data of item.
  1901. * @param [out] length Length of buffer in bytes.
  1902. */
  1903. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1904. {
  1905. *data = dataASN->data.ref.data;
  1906. *length = dataASN->data.ref.length;
  1907. }
  1908. /* Get the data and length from an ASN data item.
  1909. *
  1910. * @param [in] dataASN Dynamic ASN data item.
  1911. * @param [out] data Pointer to data of item.
  1912. * @param [out] length Length of buffer in bytes.
  1913. */
  1914. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1915. {
  1916. *data = (byte*)dataASN->data.ref.data;
  1917. *length = dataASN->data.ref.length;
  1918. }
  1919. /* Get the data and length from an ASN data item that is an OID.
  1920. *
  1921. * @param [in] dataASN Dynamic ASN data item.
  1922. * @param [out] data Pointer to .
  1923. * @param [out] length Length of buffer in bytes.
  1924. */
  1925. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1926. {
  1927. *data = (byte*)dataASN->data.oid.data;
  1928. *length = dataASN->data.oid.length;
  1929. }
  1930. /* Setup an ASN data item to set a boolean.
  1931. *
  1932. * @param [in] dataASN Dynamic ASN data item.
  1933. * @param [in] val Boolean value.
  1934. */
  1935. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1936. {
  1937. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1938. dataASN->data.u8 = val;
  1939. }
  1940. /* Setup an ASN data item to set an 8-bit number.
  1941. *
  1942. * @param [in] dataASN Dynamic ASN data item.
  1943. * @param [in] num 8-bit number to set.
  1944. */
  1945. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1946. {
  1947. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1948. dataASN->data.u8 = num;
  1949. }
  1950. /* Setup an ASN data item to set a 16-bit number.
  1951. *
  1952. * @param [in] dataASN Dynamic ASN data item.
  1953. * @param [in] num 16-bit number to set.
  1954. */
  1955. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1956. {
  1957. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1958. dataASN->data.u16 = num;
  1959. }
  1960. /* Setup an ASN data item to set the data in a buffer.
  1961. *
  1962. * @param [in] dataASN Dynamic ASN data item.
  1963. * @param [in] data Buffer containing data to set.
  1964. * @param [in] length Length of data in buffer in bytes.
  1965. */
  1966. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1967. {
  1968. dataASN->data.buffer.data = data;
  1969. dataASN->data.buffer.length = length;
  1970. }
  1971. /* Setup an ASN data item to set the DER encode data in a buffer.
  1972. *
  1973. * @param [in] dataASN Dynamic ASN data item.
  1974. * @param [in] data Buffer containing BER encoded data to set.
  1975. * @param [in] length Length of data in buffer in bytes.
  1976. */
  1977. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1978. {
  1979. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1980. dataASN->data.buffer.data = data;
  1981. dataASN->data.buffer.length = length;
  1982. }
  1983. /* Setup an ASN data item to set an multi-precision number.
  1984. *
  1985. * @param [in] dataASN Dynamic ASN data item.
  1986. * @param [in] num Multi-precision number.
  1987. */
  1988. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1989. {
  1990. dataASN->dataType = ASN_DATA_TYPE_MP;
  1991. dataASN->data.mp = num;
  1992. }
  1993. /* Setup an ASN data item to set an OID based on id and type.
  1994. *
  1995. * oid and oidType pair are unique.
  1996. *
  1997. * @param [in] dataASN Dynamic ASN data item.
  1998. * @param [in] oid OID identifier.
  1999. * @param [in] oidType Type of OID.
  2000. */
  2001. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  2002. {
  2003. dataASN->data.buffer.data = OidFromId(oid, oidType,
  2004. &dataASN->data.buffer.length);
  2005. }
  2006. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  2007. #ifdef CRLDP_VALIDATE_DATA
  2008. /* Get the data of the BIT_STRING as a 16-bit number.
  2009. *
  2010. * @param [in] dataASN Dynamic ASN data item.
  2011. * @param [out] val ASN.1 item's data as a 16-bit number.
  2012. * @return 0 on success.
  2013. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  2014. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  2015. */
  2016. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  2017. {
  2018. int ret;
  2019. int i;
  2020. const byte* input = dataASN->data.ref.data;
  2021. int length = dataASN->data.ref.length;
  2022. /* Validate the BIT_STRING data. */
  2023. ret = GetASN_BitString(input, 0, length);
  2024. if (ret == 0) {
  2025. /* Skip unused bits byte. */
  2026. input++;
  2027. length--;
  2028. /* Check the data is usable. */
  2029. if (length == 0 || length > 2) {
  2030. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  2031. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  2032. #endif
  2033. ret = ASN_PARSE_E;
  2034. }
  2035. }
  2036. if (ret == 0) {
  2037. /* Fill 16-bit var with all the data. */
  2038. *val = 0;
  2039. for (i = 0; i < length; i++) {
  2040. *val <<= 8;
  2041. *val |= input[i];
  2042. }
  2043. }
  2044. return ret;
  2045. }
  2046. #endif /* CRLDP_VALIDATE_DATA */
  2047. #endif /* WOLFSSL_ASN_TEMPLATE */
  2048. /* Decode the BER/DER length field.
  2049. *
  2050. * @param [in] input BER encoded data.
  2051. * @param [in, out] inOutIdx On in, starting index of length.
  2052. * On out, end of parsed length.
  2053. * @param [out] len Length value decoded.
  2054. * @param [in] maxIdx Maximum index of input data.
  2055. * @return Length on success.
  2056. * @return ASN_PARSE_E if the encoding is invalid.
  2057. * @return BUFFER_E when not enough data to complete decode.
  2058. */
  2059. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2060. {
  2061. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  2062. }
  2063. /* Decode the BER/DER length field and check the length is valid on request.
  2064. *
  2065. * BER/DER has Type-Length-Value triplets.
  2066. * When requested will check that the Length decoded, indicating the number
  2067. * of bytes in the Value, is available in the buffer after the Length bytes.
  2068. *
  2069. * Only supporting a length upto INT_MAX.
  2070. *
  2071. * @param [in] input BER encoded data.
  2072. * @param [in, out] inOutIdx On in, starting index of length.
  2073. * On out, end of parsed length.
  2074. * @param [out] len Length value decoded.
  2075. * @param [in] maxIdx Maximum index of input data.
  2076. * @param [in] check Whether to check the buffer has at least the
  2077. * decoded length of bytes remaining.
  2078. * @return Length on success.
  2079. * @return ASN_PARSE_E if the encoding is invalid.
  2080. * @return BUFFER_E when not enough data to complete decode.
  2081. */
  2082. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  2083. int check)
  2084. {
  2085. int length = 0;
  2086. word32 idx = (word32)*inOutIdx;
  2087. byte b;
  2088. /* Ensure zero return length on error. */
  2089. *len = 0;
  2090. /* Check there is at least one byte available containing length information.
  2091. */
  2092. if ((idx + 1) > maxIdx) {
  2093. WOLFSSL_MSG("GetLength - bad index on input");
  2094. return BUFFER_E;
  2095. }
  2096. /* Get the first length byte. */
  2097. b = input[idx++];
  2098. /* Check if the first byte indicates the count of bytes. */
  2099. if (b >= ASN_LONG_LENGTH) {
  2100. /* Bottom 7 bits are the number of bytes to calculate length with.
  2101. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
  2102. */
  2103. word32 bytes = (word32)b & 0x7FU;
  2104. int minLen;
  2105. /* Calculate minimum length to be encoded with bytes. */
  2106. if (b == ASN_INDEF_LENGTH) {
  2107. /* Indefinite length encoding - no length bytes. */
  2108. minLen = 0;
  2109. }
  2110. else if (bytes == 1) {
  2111. minLen = 0x80;
  2112. }
  2113. /* Only support up to the number of bytes that fit into return var. */
  2114. else if (bytes > sizeof(length)) {
  2115. WOLFSSL_MSG("GetLength - overlong data length spec");
  2116. return ASN_PARSE_E;
  2117. } else {
  2118. minLen = 1 << ((bytes - 1) * 8);
  2119. }
  2120. /* Check the number of bytes required are available. */
  2121. if ((idx + bytes) > maxIdx) {
  2122. WOLFSSL_MSG("GetLength - bad long length");
  2123. return BUFFER_E;
  2124. }
  2125. /* Big-endian encoding of number. */
  2126. while (bytes--) {
  2127. b = input[idx++];
  2128. length = (length << 8) | b;
  2129. }
  2130. /* Negative value indicates we overflowed the signed int. */
  2131. if (length < 0) {
  2132. return ASN_PARSE_E;
  2133. }
  2134. /* Don't allow lengths that are longer than strictly required. */
  2135. if (length < minLen) {
  2136. return ASN_PARSE_E;
  2137. }
  2138. }
  2139. else {
  2140. /* Length in first byte. */
  2141. length = b;
  2142. }
  2143. /* When requested, check the buffer has at least length bytes left. */
  2144. if (check && ((idx + (word32)length) > maxIdx)) {
  2145. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  2146. return BUFFER_E;
  2147. }
  2148. /* Return index after length encoding. */
  2149. *inOutIdx = idx;
  2150. /* Return length if valid. */
  2151. if (length > 0) {
  2152. *len = length;
  2153. }
  2154. /* Return length calculated or error code. */
  2155. return length;
  2156. }
  2157. /* Gets the tag of next BER/DER encoded item.
  2158. *
  2159. * Checks there is enough data in the buffer for the tag byte.
  2160. *
  2161. * @param [in] input BER encoded data.
  2162. * @param [in, out] inOutIdx On in, starting index of tag.
  2163. * On out, end of parsed tag.
  2164. * @param [out] tag Tag value found.
  2165. * @param [in] maxIdx Maximum index of input data.
  2166. *
  2167. * return 0 on success
  2168. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2169. * return BUFFER_E when not enough space in buffer for tag.
  2170. */
  2171. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2172. {
  2173. int ret = 0;
  2174. word32 idx = 0;
  2175. /* Check validity of parameters. */
  2176. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2177. ret = BAD_FUNC_ARG;
  2178. }
  2179. if (ret == 0) {
  2180. /* Get index and ensure space for tag. */
  2181. idx = *inOutIdx;
  2182. if (idx + ASN_TAG_SZ > maxIdx) {
  2183. WOLFSSL_MSG("Buffer too small for ASN tag");
  2184. ret = BUFFER_E;
  2185. }
  2186. }
  2187. if (ret == 0) {
  2188. /* Return the tag and the index after tag. */
  2189. *tag = input[idx];
  2190. *inOutIdx = idx + ASN_TAG_SZ;
  2191. }
  2192. /* Return error code. */
  2193. return ret;
  2194. }
  2195. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2196. *
  2197. * BER/DER has Type-Length-Value triplets.
  2198. * Check that the tag/type is the required value.
  2199. * When requested will check that the Length decoded, indicating the number
  2200. * of bytes in the Value, is available in the buffer after the Length bytes.
  2201. *
  2202. * Only supporting a length upto INT_MAX.
  2203. *
  2204. * @param [in] input Buffer holding DER/BER encoded data.
  2205. * @param [in] tag ASN.1 tag value expected in header.
  2206. * @param [in, out] inOutIdx On in, starting index of header.
  2207. * On out, end of parsed header.
  2208. * @param [out] len Number of bytes in the ASN.1 data.
  2209. * @param [in] maxIdx Length of data in buffer.
  2210. * @param [in] check Whether to check the buffer has at least the
  2211. * decoded length of bytes remaining.
  2212. * @return Number of bytes in the ASN.1 data on success.
  2213. * @return BUFFER_E when there is not enough data to parse.
  2214. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2215. */
  2216. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2217. int* len, word32 maxIdx, int check)
  2218. {
  2219. int ret = 0;
  2220. word32 idx = *inOutIdx;
  2221. byte tagFound;
  2222. int length = 0;
  2223. /* Get tag/type. */
  2224. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2225. ret = ASN_PARSE_E;
  2226. }
  2227. /* Ensure tag is the expected value. */
  2228. if ((ret == 0) && (tagFound != tag)) {
  2229. ret = ASN_PARSE_E;
  2230. }
  2231. /* Get the encoded length. */
  2232. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2233. ret = ASN_PARSE_E;
  2234. }
  2235. if (ret == 0) {
  2236. /* Return the length of data and index after header. */
  2237. *len = length;
  2238. *inOutIdx = idx;
  2239. ret = length;
  2240. }
  2241. /* Return number of data bytes or error code. */
  2242. return ret;
  2243. }
  2244. /* Decode the DER/BER header (Type-Length) and check the length.
  2245. *
  2246. * BER/DER has Type-Length-Value triplets.
  2247. * Check that the tag/type is the required value.
  2248. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2249. * is available in the buffer after the Length bytes.
  2250. *
  2251. * @param [in] input Buffer holding DER/BER encoded data.
  2252. * @param [in] tag ASN.1 tag value expected in header.
  2253. * @param [in, out] inOutIdx On in, starting index of header.
  2254. * On out, end of parsed header.
  2255. * @param [out] len Number of bytes in the ASN.1 data.
  2256. * @param [in] maxIdx Length of data in buffer.
  2257. * @return Number of bytes in the ASN.1 data on success.
  2258. * @return BUFFER_E when there is not enough data to parse.
  2259. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2260. */
  2261. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2262. word32 maxIdx)
  2263. {
  2264. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2265. }
  2266. #ifndef WOLFSSL_ASN_TEMPLATE
  2267. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2268. word32 maxIdx, int check)
  2269. {
  2270. word32 idx = *inOutIdx;
  2271. int length;
  2272. if ((idx + 1) > maxIdx)
  2273. return BUFFER_E;
  2274. *tag = input[idx++];
  2275. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2276. return ASN_PARSE_E;
  2277. *len = length;
  2278. *inOutIdx = idx;
  2279. return length;
  2280. }
  2281. #endif
  2282. /* Decode the header of a BER/DER encoded SEQUENCE.
  2283. *
  2284. * @param [in] input Buffer holding DER/BER encoded data.
  2285. * @param [in, out] inOutIdx On in, starting index of header.
  2286. * On out, end of parsed header.
  2287. * @param [out] len Number of bytes in the ASN.1 data.
  2288. * @param [in] maxIdx Length of data in buffer.
  2289. * @return Number of bytes in the ASN.1 data on success.
  2290. * @return BUFFER_E when there is not enough data to parse.
  2291. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2292. */
  2293. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2294. word32 maxIdx)
  2295. {
  2296. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2297. maxIdx);
  2298. }
  2299. /* Decode the header of a BER/DER encoded SEQUENCE.
  2300. *
  2301. * @param [in] input Buffer holding DER/BER encoded data.
  2302. * @param [in, out] inOutIdx On in, starting index of header.
  2303. * On out, end of parsed header.
  2304. * @param [out] len Number of bytes in the ASN.1 data.
  2305. * @param [in] maxIdx Length of data in buffer.
  2306. * @param [in] check Whether to check the buffer has at least the
  2307. * decoded length of bytes remaining.
  2308. * @return Number of bytes in the ASN.1 data on success.
  2309. * @return BUFFER_E when there is not enough data to parse.
  2310. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2311. */
  2312. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2313. word32 maxIdx, int check)
  2314. {
  2315. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2316. maxIdx, check);
  2317. }
  2318. /* Decode the header of a BER/DER encoded SET.
  2319. *
  2320. * @param [in] input Buffer holding DER/BER encoded data.
  2321. * @param [in, out] inOutIdx On in, starting index of header.
  2322. * On out, end of parsed header.
  2323. * @param [out] len Number of bytes in the ASN.1 data.
  2324. * @param [in] maxIdx Length of data in buffer.
  2325. * @return Number of bytes in the ASN.1 data on success.
  2326. * @return BUFFER_E when there is not enough data to parse.
  2327. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2328. */
  2329. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2330. word32 maxIdx)
  2331. {
  2332. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2333. maxIdx);
  2334. }
  2335. /* Decode the header of a BER/DER encoded SET.
  2336. *
  2337. * @param [in] input Buffer holding DER/BER encoded data.
  2338. * @param [in, out] inOutIdx On in, starting index of header.
  2339. * On out, end of parsed header.
  2340. * @param [out] len Number of bytes in the ASN.1 data.
  2341. * @param [in] maxIdx Length of data in buffer.
  2342. * @param [in] check Whether to check the buffer has at least the
  2343. * decoded length of bytes remaining.
  2344. * @return Number of bytes in the ASN.1 data on success.
  2345. * @return BUFFER_E when there is not enough data to parse.
  2346. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2347. */
  2348. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2349. word32 maxIdx, int check)
  2350. {
  2351. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2352. maxIdx, check);
  2353. }
  2354. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2355. /* Decode the BER/DER encoded NULL.
  2356. *
  2357. * No data in a NULL ASN.1 item.
  2358. * Ensure that the all fields are as expected and move index past the element.
  2359. *
  2360. * @param [in] input Buffer holding DER/BER encoded data.
  2361. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2362. * On out, end of parsed NULL item.
  2363. * @param [in] maxIdx Length of data in buffer.
  2364. * @return 0 on success.
  2365. * @return BUFFER_E when there is not enough data to parse.
  2366. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2367. * @return ASN_EXPECT_0_E when the length is not zero.
  2368. */
  2369. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2370. {
  2371. int ret = 0;
  2372. word32 idx = *inOutIdx;
  2373. /* Check buffer has enough data for a NULL item. */
  2374. if ((idx + 2) > maxIdx) {
  2375. ret = BUFFER_E;
  2376. }
  2377. /* Check the tag is NULL. */
  2378. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2379. ret = ASN_TAG_NULL_E;
  2380. }
  2381. /* Check the length is zero. */
  2382. if ((ret == 0) && (input[idx++] != 0)) {
  2383. ret = ASN_EXPECT_0_E;
  2384. }
  2385. if (ret == 0) {
  2386. /* Return the index after NULL tag. */
  2387. *inOutIdx = idx;
  2388. }
  2389. /* Return error code. */
  2390. return ret;
  2391. }
  2392. #endif
  2393. #ifndef WOLFSSL_ASN_TEMPLATE
  2394. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2395. *
  2396. * output Buffer to write into.
  2397. * returns the number of bytes added to the buffer.
  2398. */
  2399. static int SetASNNull(byte* output)
  2400. {
  2401. output[0] = ASN_TAG_NULL;
  2402. output[1] = 0;
  2403. return 2;
  2404. }
  2405. #endif
  2406. #ifndef NO_CERTS
  2407. #ifndef WOLFSSL_ASN_TEMPLATE
  2408. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2409. *
  2410. * input Buffer holding DER/BER encoded data.
  2411. * inOutIdx Current index into buffer to parse.
  2412. * maxIdx Length of data in buffer.
  2413. * returns BUFFER_E when there is not enough data to parse.
  2414. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2415. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2416. */
  2417. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2418. {
  2419. word32 idx = *inOutIdx;
  2420. byte b;
  2421. if ((idx + 3) > maxIdx)
  2422. return BUFFER_E;
  2423. b = input[idx++];
  2424. if (b != ASN_BOOLEAN)
  2425. return ASN_PARSE_E;
  2426. if (input[idx++] != 1)
  2427. return ASN_PARSE_E;
  2428. b = input[idx++] != 0;
  2429. *inOutIdx = idx;
  2430. return b;
  2431. }
  2432. #endif
  2433. #endif /* !NO_CERTS*/
  2434. /* Decode the header of a BER/DER encoded OCTET STRING.
  2435. *
  2436. * @param [in] input Buffer holding DER/BER encoded data.
  2437. * @param [in, out] inOutIdx On in, starting index of header.
  2438. * On out, end of parsed header.
  2439. * @param [out] len Number of bytes in the ASN.1 data.
  2440. * @param [in] maxIdx Length of data in buffer.
  2441. * @return Number of bytes in the ASN.1 data on success.
  2442. * @return BUFFER_E when there is not enough data to parse.
  2443. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2444. */
  2445. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2446. {
  2447. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2448. }
  2449. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2450. *
  2451. * Removes the leading zero byte when found.
  2452. *
  2453. * input Buffer holding DER/BER encoded data.
  2454. * inOutIdx Current index into buffer to parse.
  2455. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2456. * maxIdx Length of data in buffer.
  2457. * returns BUFFER_E when there is not enough data to parse.
  2458. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2459. * or invalid use of or missing leading zero.
  2460. * Otherwise, 0 to indicate success.
  2461. */
  2462. int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2463. word32 maxIdx)
  2464. {
  2465. int ret;
  2466. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2467. if (ret < 0)
  2468. return ret;
  2469. if (*len > 0) {
  2470. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2471. /* check for invalid padding on negative integer.
  2472. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2473. */
  2474. if (*len > 1) {
  2475. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2476. return ASN_PARSE_E;
  2477. }
  2478. #endif
  2479. /* remove leading zero, unless there is only one 0x00 byte */
  2480. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2481. (*inOutIdx)++;
  2482. (*len)--;
  2483. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2484. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2485. return ASN_PARSE_E;
  2486. #endif
  2487. }
  2488. }
  2489. return 0;
  2490. }
  2491. #ifndef WOLFSSL_ASN_TEMPLATE
  2492. #ifndef NO_CERTS
  2493. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2494. * 7 bits.
  2495. *
  2496. * input Buffer holding DER/BER encoded data.
  2497. * inOutIdx Current index into buffer to parse.
  2498. * maxIdx Length of data in buffer.
  2499. * returns BUFFER_E when there is not enough data to parse.
  2500. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2501. * Otherwise, the 7-bit value.
  2502. */
  2503. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2504. {
  2505. word32 idx = *inOutIdx;
  2506. byte b;
  2507. if ((idx + 3) > maxIdx)
  2508. return BUFFER_E;
  2509. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2510. return ASN_PARSE_E;
  2511. if (b != ASN_INTEGER)
  2512. return ASN_PARSE_E;
  2513. if (input[idx++] != 1)
  2514. return ASN_PARSE_E;
  2515. b = input[idx++];
  2516. *inOutIdx = idx;
  2517. return b;
  2518. }
  2519. #endif /* !NO_CERTS */
  2520. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  2521. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2522. * 16 bits.
  2523. *
  2524. * input Buffer holding DER/BER encoded data.
  2525. * inOutIdx Current index into buffer to parse.
  2526. * maxIdx Length of data in buffer.
  2527. * returns BUFFER_E when there is not enough data to parse.
  2528. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2529. * Otherwise, the 16-bit value.
  2530. */
  2531. static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2532. {
  2533. word32 idx = *inOutIdx;
  2534. byte tag;
  2535. word16 n;
  2536. if ((idx + 2) > maxIdx)
  2537. return BUFFER_E;
  2538. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2539. return ASN_PARSE_E;
  2540. if (tag != ASN_INTEGER)
  2541. return ASN_PARSE_E;
  2542. if (input[idx] == 1) {
  2543. idx++;
  2544. if ((idx + 1) > maxIdx) {
  2545. return ASN_PARSE_E;
  2546. }
  2547. n = input[idx++];
  2548. }
  2549. else if (input[idx] == 2) {
  2550. idx++;
  2551. if ((idx + 2) > maxIdx) {
  2552. return ASN_PARSE_E;
  2553. }
  2554. n = input[idx++];
  2555. n = (n << 8) | input[idx++];
  2556. }
  2557. else
  2558. return ASN_PARSE_E;
  2559. *inOutIdx = idx;
  2560. return n;
  2561. }
  2562. #endif /* WC_RSA_PSS && !NO_RSA */
  2563. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2564. #if !defined(NO_DSA) && !defined(NO_SHA)
  2565. static const char sigSha1wDsaName[] = "SHAwDSA";
  2566. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2567. #endif /* NO_DSA */
  2568. #ifndef NO_RSA
  2569. #ifdef WOLFSSL_MD2
  2570. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2571. #endif
  2572. #ifndef NO_MD5
  2573. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2574. #endif
  2575. #ifndef NO_SHA
  2576. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2577. #endif
  2578. #ifdef WOLFSSL_SHA224
  2579. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2580. #endif
  2581. #ifndef NO_SHA256
  2582. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2583. #endif
  2584. #ifdef WOLFSSL_SHA384
  2585. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2586. #endif
  2587. #ifdef WOLFSSL_SHA512
  2588. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2589. #endif
  2590. #ifdef WOLFSSL_SHA3
  2591. #ifndef WOLFSSL_NOSHA3_224
  2592. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2593. #endif
  2594. #ifndef WOLFSSL_NOSHA3_256
  2595. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2596. #endif
  2597. #ifndef WOLFSSL_NOSHA3_384
  2598. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2599. #endif
  2600. #ifndef WOLFSSL_NOSHA3_512
  2601. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2602. #endif
  2603. #endif
  2604. #ifdef WC_RSA_PSS
  2605. static const char sigRsaSsaPssName[] = "rsassaPss";
  2606. #endif
  2607. #endif /* NO_RSA */
  2608. #ifdef HAVE_ECC
  2609. #ifndef NO_SHA
  2610. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2611. #endif
  2612. #ifdef WOLFSSL_SHA224
  2613. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2614. #endif
  2615. #ifndef NO_SHA256
  2616. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2617. #endif
  2618. #ifdef WOLFSSL_SHA384
  2619. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2620. #endif
  2621. #ifdef WOLFSSL_SHA512
  2622. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2623. #endif
  2624. #ifdef WOLFSSL_SHA3
  2625. #ifndef WOLFSSL_NOSHA3_224
  2626. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2627. #endif
  2628. #ifndef WOLFSSL_NOSHA3_256
  2629. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2630. #endif
  2631. #ifndef WOLFSSL_NOSHA3_384
  2632. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2633. #endif
  2634. #ifndef WOLFSSL_NOSHA3_512
  2635. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2636. #endif
  2637. #endif
  2638. #endif /* HAVE_ECC */
  2639. static const char sigUnknownName[] = "Unknown";
  2640. /* Get the human readable string for a signature type
  2641. *
  2642. * oid Oid value for signature
  2643. */
  2644. const char* GetSigName(int oid) {
  2645. switch (oid) {
  2646. #if !defined(NO_DSA) && !defined(NO_SHA)
  2647. case CTC_SHAwDSA:
  2648. return sigSha1wDsaName;
  2649. case CTC_SHA256wDSA:
  2650. return sigSha256wDsaName;
  2651. #endif /* NO_DSA && NO_SHA */
  2652. #ifndef NO_RSA
  2653. #ifdef WOLFSSL_MD2
  2654. case CTC_MD2wRSA:
  2655. return sigMd2wRsaName;
  2656. #endif
  2657. #ifndef NO_MD5
  2658. case CTC_MD5wRSA:
  2659. return sigMd5wRsaName;
  2660. #endif
  2661. #ifndef NO_SHA
  2662. case CTC_SHAwRSA:
  2663. return sigSha1wRsaName;
  2664. #endif
  2665. #ifdef WOLFSSL_SHA224
  2666. case CTC_SHA224wRSA:
  2667. return sigSha224wRsaName;
  2668. #endif
  2669. #ifndef NO_SHA256
  2670. case CTC_SHA256wRSA:
  2671. return sigSha256wRsaName;
  2672. #endif
  2673. #ifdef WOLFSSL_SHA384
  2674. case CTC_SHA384wRSA:
  2675. return sigSha384wRsaName;
  2676. #endif
  2677. #ifdef WOLFSSL_SHA512
  2678. case CTC_SHA512wRSA:
  2679. return sigSha512wRsaName;
  2680. #endif
  2681. #ifdef WOLFSSL_SHA3
  2682. #ifndef WOLFSSL_NOSHA3_224
  2683. case CTC_SHA3_224wRSA:
  2684. return sigSha3_224wRsaName;
  2685. #endif
  2686. #ifndef WOLFSSL_NOSHA3_256
  2687. case CTC_SHA3_256wRSA:
  2688. return sigSha3_256wRsaName;
  2689. #endif
  2690. #ifndef WOLFSSL_NOSHA3_384
  2691. case CTC_SHA3_384wRSA:
  2692. return sigSha3_384wRsaName;
  2693. #endif
  2694. #ifndef WOLFSSL_NOSHA3_512
  2695. case CTC_SHA3_512wRSA:
  2696. return sigSha3_512wRsaName;
  2697. #endif
  2698. #endif
  2699. #ifdef WC_RSA_PSS
  2700. case CTC_RSASSAPSS:
  2701. return sigRsaSsaPssName;
  2702. #endif
  2703. #endif /* NO_RSA */
  2704. #ifdef HAVE_ECC
  2705. #ifndef NO_SHA
  2706. case CTC_SHAwECDSA:
  2707. return sigSha1wEcdsaName;
  2708. #endif
  2709. #ifdef WOLFSSL_SHA224
  2710. case CTC_SHA224wECDSA:
  2711. return sigSha224wEcdsaName;
  2712. #endif
  2713. #ifndef NO_SHA256
  2714. case CTC_SHA256wECDSA:
  2715. return sigSha256wEcdsaName;
  2716. #endif
  2717. #ifdef WOLFSSL_SHA384
  2718. case CTC_SHA384wECDSA:
  2719. return sigSha384wEcdsaName;
  2720. #endif
  2721. #ifdef WOLFSSL_SHA512
  2722. case CTC_SHA512wECDSA:
  2723. return sigSha512wEcdsaName;
  2724. #endif
  2725. #ifdef WOLFSSL_SHA3
  2726. #ifndef WOLFSSL_NOSHA3_224
  2727. case CTC_SHA3_224wECDSA:
  2728. return sigSha3_224wEcdsaName;
  2729. #endif
  2730. #ifndef WOLFSSL_NOSHA3_256
  2731. case CTC_SHA3_256wECDSA:
  2732. return sigSha3_256wEcdsaName;
  2733. #endif
  2734. #ifndef WOLFSSL_NOSHA3_384
  2735. case CTC_SHA3_384wECDSA:
  2736. return sigSha3_384wEcdsaName;
  2737. #endif
  2738. #ifndef WOLFSSL_NOSHA3_512
  2739. case CTC_SHA3_512wECDSA:
  2740. return sigSha3_512wEcdsaName;
  2741. #endif
  2742. #endif
  2743. #endif /* HAVE_ECC */
  2744. default:
  2745. return sigUnknownName;
  2746. }
  2747. }
  2748. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2749. defined(OPENSSL_EXTRA)
  2750. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2751. (!defined(NO_RSA) && \
  2752. (defined(WOLFSSL_CERT_GEN) || \
  2753. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)))))
  2754. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2755. *
  2756. * When output is NULL, calculate the header length only.
  2757. *
  2758. * @param [in] len Length of INTEGER data in bytes.
  2759. * @param [in] firstByte First byte of data, most significant byte of integer,
  2760. * to encode.
  2761. * @param [out] output Buffer to write into.
  2762. * @return Number of bytes added to the buffer.
  2763. */
  2764. int SetASNInt(int len, byte firstByte, byte* output)
  2765. {
  2766. int idx = 0;
  2767. if (output) {
  2768. /* Write out tag. */
  2769. output[idx] = ASN_INTEGER;
  2770. }
  2771. /* Step over tag. */
  2772. idx += ASN_TAG_SZ;
  2773. /* Check if first byte has top bit set in which case a 0 is needed to
  2774. * maintain positive value. */
  2775. if (firstByte & 0x80) {
  2776. /* Add pre-prepended byte to length of data in INTEGER. */
  2777. len++;
  2778. }
  2779. /* Encode length - passing NULL for output will not encode. */
  2780. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  2781. /* Put out prepended 0 as well. */
  2782. if (firstByte & 0x80) {
  2783. if (output) {
  2784. /* Write out 0 byte. */
  2785. output[idx] = 0x00;
  2786. }
  2787. /* Update index. */
  2788. idx++;
  2789. }
  2790. /* Return index after header. */
  2791. return idx;
  2792. }
  2793. #endif
  2794. #endif
  2795. #ifndef WOLFSSL_ASN_TEMPLATE
  2796. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2797. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2798. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2799. defined(OPENSSL_EXTRA)) && !defined(NO_RSA))
  2800. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2801. * The number is assumed to be positive.
  2802. *
  2803. * n Multi-precision integer to encode.
  2804. * maxSz Maximum size of the encoded integer.
  2805. * A negative value indicates no check of length requested.
  2806. * output Buffer to write into.
  2807. * returns BUFFER_E when the data is too long for the buffer.
  2808. * MP_TO_E when encoding the integer fails.
  2809. * Otherwise, the number of bytes added to the buffer.
  2810. */
  2811. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2812. {
  2813. int idx = 0;
  2814. int leadingBit;
  2815. int length;
  2816. leadingBit = mp_leading_bit(n);
  2817. length = mp_unsigned_bin_size(n);
  2818. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2819. return BUFFER_E;
  2820. idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output);
  2821. if (maxSz >= 0 && (idx + length) > maxSz)
  2822. return BUFFER_E;
  2823. if (output) {
  2824. int err = mp_to_unsigned_bin(n, output + idx);
  2825. if (err != MP_OKAY)
  2826. return MP_TO_E;
  2827. }
  2828. idx += length;
  2829. return idx;
  2830. }
  2831. #endif
  2832. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2833. #ifdef WOLFSSL_ASN_TEMPLATE
  2834. /* ASN.1 template for an INTEGER. */
  2835. static const ASNItem intASN[] = {
  2836. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2837. };
  2838. enum {
  2839. INTASN_IDX_INT = 0
  2840. };
  2841. /* Number of items in ASN.1 template for an INTEGER. */
  2842. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2843. #endif /* WOLFSSL_ASN_TEMPLATE */
  2844. /* Windows header clash for WinCE using GetVersion */
  2845. /* Decode Version - one byte INTEGER.
  2846. *
  2847. * @param [in] input Buffer of BER data.
  2848. * @param [in, out] inOutIdx On in, start of encoded Version.
  2849. * On out, start of next encode ASN.1 item.
  2850. * @param [out] version Number encoded in INTEGER.
  2851. * @param [in] maxIdx Maximum index of data in buffer.
  2852. * @return 0 on success.
  2853. * @return ASN_PARSE_E when encoding is invalid.
  2854. * @return BUFFER_E when data in buffer is too small.
  2855. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2856. */
  2857. int GetMyVersion(const byte* input, word32* inOutIdx,
  2858. int* version, word32 maxIdx)
  2859. {
  2860. #ifndef WOLFSSL_ASN_TEMPLATE
  2861. word32 idx = *inOutIdx;
  2862. byte tag;
  2863. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2864. return ASN_PARSE_E;
  2865. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2866. return ASN_PARSE_E;
  2867. if (tag != ASN_INTEGER)
  2868. return ASN_PARSE_E;
  2869. if (input[idx++] != 0x01)
  2870. return ASN_VERSION_E;
  2871. *version = input[idx++];
  2872. *inOutIdx = idx;
  2873. return *version;
  2874. #else
  2875. ASNGetData dataASN[intASN_Length];
  2876. int ret;
  2877. byte num = 0;
  2878. /* Clear dynamic data and set the version number variable. */
  2879. XMEMSET(dataASN, 0, sizeof(dataASN));
  2880. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2881. /* Decode the version (INTEGER). */
  2882. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2883. maxIdx);
  2884. if (ret == 0) {
  2885. /* Return version through variable and return value. */
  2886. *version = num;
  2887. ret = num;
  2888. }
  2889. return ret;
  2890. #endif /* WOLFSSL_ASN_TEMPLATE */
  2891. }
  2892. #ifndef NO_PWDBASED
  2893. /* Decode small integer, 32 bits or less.
  2894. *
  2895. * @param [in] input Buffer of BER data.
  2896. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2897. * On out, start of next encode ASN.1 item.
  2898. * @param [out] number Number encoded in INTEGER.
  2899. * @param [in] maxIdx Maximum index of data in buffer.
  2900. * @return 0 on success.
  2901. * @return ASN_PARSE_E when encoding is invalid.
  2902. * @return BUFFER_E when data in buffer is too small.
  2903. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2904. */
  2905. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2906. {
  2907. #ifndef WOLFSSL_ASN_TEMPLATE
  2908. word32 idx = *inOutIdx;
  2909. word32 len;
  2910. byte tag;
  2911. *number = 0;
  2912. /* check for type and length bytes */
  2913. if ((idx + 2) > maxIdx)
  2914. return BUFFER_E;
  2915. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2916. return ASN_PARSE_E;
  2917. if (tag != ASN_INTEGER)
  2918. return ASN_PARSE_E;
  2919. len = input[idx++];
  2920. if (len > 4)
  2921. return ASN_PARSE_E;
  2922. if (len + idx > maxIdx)
  2923. return ASN_PARSE_E;
  2924. while (len--) {
  2925. *number = *number << 8 | input[idx++];
  2926. }
  2927. *inOutIdx = idx;
  2928. return *number;
  2929. #else
  2930. ASNGetData dataASN[intASN_Length];
  2931. int ret;
  2932. word32 num = 0;
  2933. /* Clear dynamic data and set the 32-bit number variable. */
  2934. XMEMSET(dataASN, 0, sizeof(dataASN));
  2935. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2936. /* Decode the short int (INTEGER). */
  2937. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2938. maxIdx);
  2939. if (ret == 0) {
  2940. /* Return number through variable and return value. */
  2941. *number = (int)num;
  2942. ret = (int)num;
  2943. }
  2944. return ret;
  2945. #endif
  2946. }
  2947. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
  2948. defined(HAVE_PKCS12)
  2949. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2950. * returns total amount written including ASN tag and length byte on success */
  2951. int SetShortInt(byte* output, word32* inOutIdx, word32 number, word32 maxIdx)
  2952. {
  2953. word32 idx = *inOutIdx;
  2954. word32 len;
  2955. int i;
  2956. if (number == 0)
  2957. len = 1;
  2958. else
  2959. len = BytePrecision(number);
  2960. /* check for room for type and length bytes. */
  2961. if ((idx + 2 + len) > maxIdx)
  2962. return BUFFER_E;
  2963. /* check that MAX_SHORT_SZ allows this size of ShortInt. */
  2964. if (2 + len > MAX_SHORT_SZ)
  2965. return ASN_PARSE_E;
  2966. output[idx++] = ASN_INTEGER;
  2967. output[idx++] = (byte)len;
  2968. for (i = (int)len - 1; i >= 0; --i)
  2969. output[idx++] = (byte)(number >> (i * WOLFSSL_BIT_SIZE));
  2970. len = idx - *inOutIdx;
  2971. *inOutIdx = idx;
  2972. return (int)len;
  2973. }
  2974. #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
  2975. #endif /* !NO_PWDBASED */
  2976. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  2977. /* May not have one, not an error */
  2978. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2979. word32 maxIdx)
  2980. {
  2981. word32 idx = *inOutIdx;
  2982. byte tag;
  2983. WOLFSSL_ENTER("GetExplicitVersion");
  2984. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2985. return ASN_PARSE_E;
  2986. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2987. int ret;
  2988. *inOutIdx = ++idx; /* skip header */
  2989. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2990. if (ret >= 0) {
  2991. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2992. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2993. WOLFSSL_MSG("Unexpected certificate version");
  2994. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  2995. ret = ASN_VERSION_E;
  2996. }
  2997. }
  2998. return ret;
  2999. }
  3000. /* go back as is */
  3001. *version = 0;
  3002. return 0;
  3003. }
  3004. #endif
  3005. /* Decode small integer, 32 bits or less.
  3006. *
  3007. * mp_int is initialized.
  3008. *
  3009. * @param [out] mpi mp_int to hold number.
  3010. * @param [in] input Buffer of BER data.
  3011. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  3012. * On out, start of next encode ASN.1 item.
  3013. * @param [in] maxIdx Maximum index of data in buffer.
  3014. * @return 0 on success.
  3015. * @return ASN_PARSE_E when encoding is invalid.
  3016. * @return BUFFER_E when data in buffer is too small.
  3017. * @return ASN_EXPECT_0_E when the most significant bit is set.
  3018. * @return MP_INIT_E when the unable to initialize an mp_int.
  3019. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  3020. */
  3021. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  3022. {
  3023. #ifndef WOLFSSL_ASN_TEMPLATE
  3024. word32 idx = *inOutIdx;
  3025. int ret;
  3026. int length;
  3027. ret = GetASNInt(input, &idx, &length, maxIdx);
  3028. if (ret != 0)
  3029. return ret;
  3030. if (mp_init(mpi) != MP_OKAY)
  3031. return MP_INIT_E;
  3032. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  3033. mp_clear(mpi);
  3034. return ASN_GETINT_E;
  3035. }
  3036. #ifdef HAVE_WOLF_BIGINT
  3037. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3038. mp_clear(mpi);
  3039. return ASN_GETINT_E;
  3040. }
  3041. #endif /* HAVE_WOLF_BIGINT */
  3042. *inOutIdx = idx + (word32)length;
  3043. return 0;
  3044. #else
  3045. ASNGetData dataASN[intASN_Length];
  3046. /* Clear dynamic data and set the mp_int to fill with value. */
  3047. XMEMSET(dataASN, 0, sizeof(dataASN));
  3048. GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
  3049. /* Decode the big number (INTEGER). */
  3050. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  3051. maxIdx);
  3052. #endif
  3053. }
  3054. #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
  3055. static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
  3056. word32 maxIdx, int initNum)
  3057. {
  3058. word32 idx = *inOutIdx;
  3059. int ret;
  3060. int length;
  3061. ret = GetASNInt(input, &idx, &length, maxIdx);
  3062. if (ret != 0)
  3063. return ret;
  3064. /* should not be hit but adding in an additional sanity check */
  3065. if (idx + length > maxIdx) {
  3066. return MP_INIT_E;
  3067. }
  3068. if ((input[idx] & 0x80) == 0x80) {
  3069. if (idx < 1) {
  3070. /* needs at least one byte for length value */
  3071. return MP_INIT_E;
  3072. }
  3073. if (input[idx - 1] != 0x00) {
  3074. return MP_INIT_E;
  3075. }
  3076. }
  3077. if (initNum) {
  3078. if (mp_init(mpi) != MP_OKAY)
  3079. return MP_INIT_E;
  3080. }
  3081. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  3082. mp_clear(mpi);
  3083. return ASN_GETINT_E;
  3084. }
  3085. #ifdef HAVE_WOLF_BIGINT
  3086. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3087. mp_clear(mpi);
  3088. return ASN_GETINT_E;
  3089. }
  3090. #endif /* HAVE_WOLF_BIGINT */
  3091. *inOutIdx = idx + (word32)length;
  3092. return 0;
  3093. }
  3094. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  3095. #ifndef WOLFSSL_ASN_TEMPLATE
  3096. #if !defined(NO_RSA) || !defined(NO_DSA)
  3097. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  3098. {
  3099. word32 idx = *inOutIdx;
  3100. int ret;
  3101. int length;
  3102. ret = GetASNInt(input, &idx, &length, maxIdx);
  3103. if (ret != 0)
  3104. return ret;
  3105. *inOutIdx = idx + (word32)length;
  3106. return 0;
  3107. }
  3108. #endif
  3109. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3110. #ifdef WOLFSSL_ASN_TEMPLATE
  3111. /* ASN.1 template for a BIT_STRING. */
  3112. static const ASNItem bitStringASN[] = {
  3113. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  3114. };
  3115. enum {
  3116. BITSTRINGASN_IDX_BIT_STR = 0
  3117. };
  3118. /* Number of items in ASN.1 template for a BIT_STRING. */
  3119. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  3120. #endif
  3121. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  3122. *
  3123. * @param [in] input Buffer holding BER encoding.
  3124. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3125. * On out, start of ASN.1 item after BIT_STRING.
  3126. * @param [out] len Length of BIT_STRING data.
  3127. * @param [in] maxIdx Maximum index of data in buffer.
  3128. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3129. * @param [in] unusedBits Number of unused bits in last byte.
  3130. * @return 0 on success.
  3131. * @return ASN_PARSE_E when encoding is invalid.
  3132. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3133. * @return BUFFER_E when data in buffer is too small.
  3134. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3135. */
  3136. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3137. word32 maxIdx, int zeroBits, byte* unusedBits)
  3138. {
  3139. #ifndef WOLFSSL_ASN_TEMPLATE
  3140. word32 idx = *inOutIdx;
  3141. int length;
  3142. byte b;
  3143. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3144. return ASN_BITSTR_E;
  3145. }
  3146. if (b != ASN_BIT_STRING) {
  3147. return ASN_BITSTR_E;
  3148. }
  3149. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3150. return ASN_PARSE_E;
  3151. /* extra sanity check that length is greater than 0 */
  3152. if (length <= 0) {
  3153. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3154. return BUFFER_E;
  3155. }
  3156. if (idx + 1 > maxIdx) {
  3157. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3158. return BUFFER_E;
  3159. }
  3160. b = input[idx];
  3161. if (zeroBits && b != 0x00)
  3162. return ASN_EXPECT_0_E;
  3163. if (b >= 0x08)
  3164. return ASN_PARSE_E;
  3165. if (b != 0) {
  3166. if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
  3167. return ASN_PARSE_E;
  3168. }
  3169. idx++;
  3170. length--; /* length has been checked for greater than 0 */
  3171. *inOutIdx = idx;
  3172. if (len != NULL)
  3173. *len = length;
  3174. if (unusedBits != NULL)
  3175. *unusedBits = b;
  3176. return 0;
  3177. #else
  3178. ASNGetData dataASN[bitStringASN_Length];
  3179. int ret;
  3180. int bits;
  3181. /* Parse BIT_STRING and check validity of unused bits. */
  3182. XMEMSET(dataASN, 0, sizeof(dataASN));
  3183. /* Decode BIT_STRING. */
  3184. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3185. inOutIdx, maxIdx);
  3186. if (ret == 0) {
  3187. /* Get unused bits from dynamic ASN.1 data. */
  3188. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3189. /* Check unused bits is 0 when expected. */
  3190. if (zeroBits && (bits != 0)) {
  3191. ret = ASN_EXPECT_0_E;
  3192. }
  3193. }
  3194. if (ret == 0) {
  3195. /* Return length of data and unused bits if required. */
  3196. if (len != NULL) {
  3197. *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3198. }
  3199. if (unusedBits != NULL) {
  3200. *unusedBits = (byte)bits;
  3201. }
  3202. }
  3203. return ret;
  3204. #endif
  3205. }
  3206. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3207. * KeyGen) */
  3208. #if (!defined(NO_RSA) && \
  3209. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3210. defined(OPENSSL_EXTRA))) || \
  3211. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3212. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3213. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3214. defined(OPENSSL_EXTRA))) || \
  3215. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3216. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3217. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3218. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3219. *
  3220. * When output is NULL, calculate the header length only.
  3221. *
  3222. * @param [in] len Length of BIT STRING data.
  3223. * That is, the number of least significant zero bits
  3224. * before a one.
  3225. * The last byte is the most-significant non-zero byte
  3226. * of a number.
  3227. * @param [out] output Buffer to write into.
  3228. * @return Number of bytes added to the buffer.
  3229. */
  3230. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3231. {
  3232. word32 idx = 0;
  3233. if (output) {
  3234. /* Write out tag. */
  3235. output[idx] = ASN_BIT_STRING;
  3236. }
  3237. /* Step over tag. */
  3238. idx += ASN_TAG_SZ;
  3239. /* Encode length - passing NULL for output will not encode.
  3240. * Add one to length for unused bits. */
  3241. idx += SetLength(len + 1, output ? output + idx : NULL);
  3242. if (output) {
  3243. /* Write out unused bits. */
  3244. output[idx] = unusedBits;
  3245. }
  3246. /* Skip over unused bits. */
  3247. idx++;
  3248. /* Return index after header. */
  3249. return idx;
  3250. }
  3251. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3252. #ifdef ASN_BER_TO_DER
  3253. #ifndef BER_OCTET_LENGTH
  3254. #define BER_OCTET_LENGTH 4096
  3255. #endif
  3256. /* sets the terminating 0x00 0x00 at the end of an indefinite length
  3257. * returns the number of bytes written */
  3258. word32 SetIndefEnd(byte* output)
  3259. {
  3260. byte terminate[ASN_INDEF_END_SZ] = { 0x00, 0x00 };
  3261. if (output != NULL) {
  3262. XMEMCPY(output, terminate, ASN_INDEF_END_SZ);
  3263. }
  3264. return (word32)ASN_INDEF_END_SZ;
  3265. }
  3266. /* Breaks an octet string up into chunks for use with streaming
  3267. * returns 0 on success and updates idx */
  3268. int StreamOctetString(const byte* inBuf, word32 inBufSz, byte* out, word32* outSz,
  3269. word32* idx)
  3270. {
  3271. word32 i = 0;
  3272. word32 outIdx = *idx;
  3273. byte* tmp = out;
  3274. if (tmp) tmp += outIdx;
  3275. while (i < inBufSz) {
  3276. word32 ret, sz;
  3277. sz = BER_OCTET_LENGTH;
  3278. if ((sz + i) > inBufSz) {
  3279. sz = inBufSz - i;
  3280. }
  3281. ret = SetOctetString(sz, tmp);
  3282. if (ret > 0) {
  3283. outIdx += ret;
  3284. }
  3285. if (tmp) {
  3286. if ((word32)ret + sz + i + outIdx > *outSz) {
  3287. return BUFFER_E;
  3288. }
  3289. XMEMCPY(tmp + ret, inBuf + i, sz);
  3290. tmp += sz + ret;
  3291. }
  3292. outIdx += sz;
  3293. i += sz;
  3294. }
  3295. if (tmp) {
  3296. *idx = outIdx;
  3297. return 0;
  3298. }
  3299. else {
  3300. *outSz = outIdx;
  3301. return LENGTH_ONLY_E;
  3302. }
  3303. }
  3304. /* Convert BER to DER */
  3305. /* Pull informtation from the ASN.1 BER encoded item header */
  3306. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3307. byte* pTag, word32* pLen, int* indef)
  3308. {
  3309. int len = 0;
  3310. byte tag;
  3311. word32 i = *idx;
  3312. *indef = 0;
  3313. /* Check there is enough data for a minimal header */
  3314. if (i + 2 > maxIdx) {
  3315. return ASN_PARSE_E;
  3316. }
  3317. /* Retrieve tag */
  3318. tag = data[i++];
  3319. /* Indefinite length handled specially */
  3320. if (data[i] == ASN_INDEF_LENGTH) {
  3321. /* Check valid tag for indefinite */
  3322. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3323. return ASN_PARSE_E;
  3324. }
  3325. i++;
  3326. *indef = 1;
  3327. }
  3328. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3329. return ASN_PARSE_E;
  3330. }
  3331. /* Return tag, length and index after BER item header */
  3332. *pTag = tag;
  3333. *pLen = (word32)len;
  3334. *idx = i;
  3335. return 0;
  3336. }
  3337. #ifndef INDEF_ITEMS_MAX
  3338. #define INDEF_ITEMS_MAX 20
  3339. #endif
  3340. /* Indef length item data */
  3341. typedef struct Indef {
  3342. word32 start;
  3343. int depth;
  3344. int headerLen;
  3345. word32 len;
  3346. } Indef;
  3347. /* Indef length items */
  3348. typedef struct IndefItems
  3349. {
  3350. Indef len[INDEF_ITEMS_MAX];
  3351. int cnt;
  3352. int idx;
  3353. int depth;
  3354. } IndefItems;
  3355. /* Get header length of current item */
  3356. static int IndefItems_HeaderLen(IndefItems* items)
  3357. {
  3358. return items->len[items->idx].headerLen;
  3359. }
  3360. /* Get data length of current item */
  3361. static word32 IndefItems_Len(IndefItems* items)
  3362. {
  3363. return items->len[items->idx].len;
  3364. }
  3365. /* Add a indefinite length item */
  3366. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3367. {
  3368. int ret = 0;
  3369. int i;
  3370. if (items->cnt == INDEF_ITEMS_MAX) {
  3371. ret = MEMORY_E;
  3372. }
  3373. else {
  3374. i = items->cnt++;
  3375. items->len[i].start = start;
  3376. items->len[i].depth = items->depth++;
  3377. items->len[i].headerLen = 1;
  3378. items->len[i].len = 0;
  3379. items->idx = i;
  3380. }
  3381. return ret;
  3382. }
  3383. /* Increase data length of current item */
  3384. static void IndefItems_AddData(IndefItems* items, word32 length)
  3385. {
  3386. items->len[items->idx].len += length;
  3387. }
  3388. /* Update header length of current item to reflect data length */
  3389. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3390. {
  3391. items->len[items->idx].headerLen +=
  3392. (int)SetLength(items->len[items->idx].len, NULL);
  3393. }
  3394. /* Go to indefinite parent of current item */
  3395. static void IndefItems_Up(IndefItems* items)
  3396. {
  3397. int i;
  3398. int depth = items->len[items->idx].depth - 1;
  3399. for (i = items->cnt - 1; i >= 0; i--) {
  3400. if (items->len[i].depth == depth) {
  3401. break;
  3402. }
  3403. }
  3404. items->idx = i;
  3405. items->depth = depth + 1;
  3406. }
  3407. /* Calculate final length by adding length of indefinite child items */
  3408. static void IndefItems_CalcLength(IndefItems* items)
  3409. {
  3410. int i;
  3411. int idx = items->idx;
  3412. for (i = idx + 1; i < items->cnt; i++) {
  3413. if (items->len[i].depth == items->depth) {
  3414. items->len[idx].len += (word32)items->len[i].headerLen;
  3415. items->len[idx].len += items->len[i].len;
  3416. }
  3417. }
  3418. items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
  3419. }
  3420. /* Add more data to indefinite length item */
  3421. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3422. {
  3423. if (items->cnt > 0 && items->idx >= 0) {
  3424. items->len[items->idx].len += length;
  3425. }
  3426. }
  3427. /* Convert a BER encoding with indefinite length items to DER.
  3428. *
  3429. * ber BER encoded data.
  3430. * berSz Length of BER encoded data.
  3431. * der Buffer to hold DER encoded version of data.
  3432. * NULL indicates only the length is required.
  3433. * derSz The size of the buffer to hold the DER encoded data.
  3434. * Will be set if der is NULL, otherwise the value is checked as der is
  3435. * filled.
  3436. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3437. * derSz are NULL.
  3438. */
  3439. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3440. {
  3441. int ret = 0;
  3442. word32 i, j;
  3443. #ifdef WOLFSSL_SMALL_STACK
  3444. IndefItems* indefItems = NULL;
  3445. #else
  3446. IndefItems indefItems[1];
  3447. #endif
  3448. byte tag, basic;
  3449. word32 length;
  3450. int indef;
  3451. if (ber == NULL || derSz == NULL)
  3452. return BAD_FUNC_ARG;
  3453. #ifdef WOLFSSL_SMALL_STACK
  3454. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3455. DYNAMIC_TYPE_TMP_BUFFER);
  3456. if (indefItems == NULL) {
  3457. ret = MEMORY_E;
  3458. goto end;
  3459. }
  3460. #endif
  3461. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3462. /* Calculate indefinite item lengths */
  3463. for (i = 0; i < berSz; ) {
  3464. word32 start = i;
  3465. /* Get next BER item */
  3466. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3467. if (ret != 0) {
  3468. goto end;
  3469. }
  3470. if (indef) {
  3471. /* Indefinite item - add to list */
  3472. ret = IndefItems_AddItem(indefItems, i);
  3473. if (ret != 0) {
  3474. goto end;
  3475. }
  3476. if ((tag & 0xC0) == 0 &&
  3477. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3478. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3479. /* Constructed basic type - get repeating tag */
  3480. basic = (byte)(tag & (~ASN_CONSTRUCTED));
  3481. /* Add up lengths of each item below */
  3482. for (; i < berSz; ) {
  3483. /* Get next BER_item */
  3484. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3485. if (ret != 0) {
  3486. goto end;
  3487. }
  3488. /* End of content closes item */
  3489. if (tag == ASN_EOC) {
  3490. /* Must be zero length */
  3491. if (length != 0) {
  3492. ret = ASN_PARSE_E;
  3493. goto end;
  3494. }
  3495. break;
  3496. }
  3497. /* Must not be indefinite and tag must match parent */
  3498. if (indef || tag != basic) {
  3499. ret = ASN_PARSE_E;
  3500. goto end;
  3501. }
  3502. /* Add to length */
  3503. IndefItems_AddData(indefItems, length);
  3504. /* Skip data */
  3505. i += length;
  3506. }
  3507. /* Ensure we got an EOC and not end of data */
  3508. if (tag != ASN_EOC) {
  3509. ret = ASN_PARSE_E;
  3510. goto end;
  3511. }
  3512. /* Set the header length to include the length field */
  3513. IndefItems_UpdateHeaderLen(indefItems);
  3514. /* Go to indefinite parent item */
  3515. IndefItems_Up(indefItems);
  3516. }
  3517. }
  3518. else if (tag == ASN_EOC) {
  3519. /* End-of-content must be 0 length */
  3520. if (length != 0) {
  3521. ret = ASN_PARSE_E;
  3522. goto end;
  3523. }
  3524. /* Check there is an item to close - missing EOC */
  3525. if (indefItems->depth == 0) {
  3526. ret = ASN_PARSE_E;
  3527. goto end;
  3528. }
  3529. /* Finish calculation of data length for indefinite item */
  3530. IndefItems_CalcLength(indefItems);
  3531. /* Go to indefinite parent item */
  3532. IndefItems_Up(indefItems);
  3533. }
  3534. else {
  3535. /* Known length item to add in - make sure enough data for it */
  3536. if (i + length > berSz) {
  3537. ret = ASN_PARSE_E;
  3538. goto end;
  3539. }
  3540. /* Include all data - can't have indefinite inside definite */
  3541. i += length;
  3542. /* Add entire item to current indefinite item */
  3543. IndefItems_MoreData(indefItems, i - start);
  3544. }
  3545. }
  3546. /* Check we had a EOC for each indefinite item */
  3547. if (indefItems->depth != 0) {
  3548. ret = ASN_PARSE_E;
  3549. goto end;
  3550. }
  3551. /* Write out DER */
  3552. j = 0;
  3553. /* Reset index */
  3554. indefItems->idx = 0;
  3555. for (i = 0; i < berSz; ) {
  3556. word32 start = i;
  3557. /* Get item - checked above */
  3558. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3559. if (indef) {
  3560. if (der != NULL) {
  3561. /* Check enough space for header */
  3562. if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
  3563. ret = BUFFER_E;
  3564. goto end;
  3565. }
  3566. if ((tag & 0xC0) == 0 &&
  3567. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3568. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3569. /* Remove constructed tag for basic types */
  3570. tag &= (byte)~ASN_CONSTRUCTED;
  3571. }
  3572. /* Add tag and length */
  3573. der[j] = tag;
  3574. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3575. }
  3576. /* Add header length of indefinite item */
  3577. j += (word32)IndefItems_HeaderLen(indefItems);
  3578. if ((tag & 0xC0) == 0 &&
  3579. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3580. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3581. /* For basic type - get each child item and add data */
  3582. for (; i < berSz; ) {
  3583. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3584. if (tag == ASN_EOC) {
  3585. break;
  3586. }
  3587. if (der != NULL) {
  3588. if (j + length > *derSz) {
  3589. ret = BUFFER_E;
  3590. goto end;
  3591. }
  3592. XMEMCPY(der + j, ber + i, length);
  3593. }
  3594. j += length;
  3595. i += length;
  3596. }
  3597. }
  3598. /* Move to next indef item in list */
  3599. indefItems->idx++;
  3600. }
  3601. else if (tag == ASN_EOC) {
  3602. /* End-Of-Content is not written out in DER */
  3603. }
  3604. else {
  3605. /* Write out definite length item as is. */
  3606. i += length;
  3607. if (der != NULL) {
  3608. /* Ensure space for item */
  3609. if (j + i - start > *derSz) {
  3610. ret = BUFFER_E;
  3611. goto end;
  3612. }
  3613. /* Copy item as is */
  3614. XMEMCPY(der + j, ber + start, i - start);
  3615. }
  3616. j += i - start;
  3617. }
  3618. }
  3619. /* Return the length of the DER encoded ASN.1 */
  3620. *derSz = j;
  3621. if (der == NULL) {
  3622. ret = LENGTH_ONLY_E;
  3623. }
  3624. end:
  3625. #ifdef WOLFSSL_SMALL_STACK
  3626. if (indefItems != NULL) {
  3627. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3628. }
  3629. #endif
  3630. return ret;
  3631. }
  3632. #endif
  3633. #ifndef WOLFSSL_ASN_TEMPLATE
  3634. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3635. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3636. *
  3637. * val 16-bit value to encode.
  3638. * output Buffer to write into.
  3639. * returns the number of bytes added to the buffer.
  3640. */
  3641. static word32 SetBitString16Bit(word16 val, byte* output)
  3642. {
  3643. word32 idx;
  3644. int len;
  3645. byte lastByte;
  3646. byte unusedBits = 0;
  3647. if ((val >> 8) != 0) {
  3648. len = 2;
  3649. lastByte = (byte)(val >> 8);
  3650. }
  3651. else {
  3652. len = 1;
  3653. lastByte = (byte)val;
  3654. }
  3655. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3656. unusedBits++;
  3657. idx = SetBitString((word32)len, unusedBits, output);
  3658. output[idx++] = (byte)val;
  3659. if (len > 1)
  3660. output[idx++] = (byte)(val >> 8);
  3661. return idx;
  3662. }
  3663. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3664. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3665. /* hashType */
  3666. #ifdef WOLFSSL_MD2
  3667. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3668. #endif
  3669. #ifndef NO_MD5
  3670. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3671. #endif
  3672. #ifndef NO_SHA
  3673. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3674. #endif
  3675. #ifdef WOLFSSL_SHA224
  3676. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3677. #endif
  3678. #ifndef NO_SHA256
  3679. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3680. #endif
  3681. #ifdef WOLFSSL_SHA384
  3682. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3683. #endif
  3684. #ifdef WOLFSSL_SHA512
  3685. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3686. #ifndef WOLFSSL_NOSHA512_224
  3687. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3688. #endif
  3689. #ifndef WOLFSSL_NOSHA512_256
  3690. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3691. #endif
  3692. #endif
  3693. #ifdef WOLFSSL_SHA3
  3694. #ifndef WOLFSSL_NOSHA3_224
  3695. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3696. #endif /* WOLFSSL_NOSHA3_224 */
  3697. #ifndef WOLFSSL_NOSHA3_256
  3698. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3699. #endif /* WOLFSSL_NOSHA3_256 */
  3700. #ifndef WOLFSSL_NOSHA3_384
  3701. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3702. #endif /* WOLFSSL_NOSHA3_384 */
  3703. #ifndef WOLFSSL_NOSHA3_512
  3704. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3705. #endif /* WOLFSSL_NOSHA3_512 */
  3706. #endif /* WOLFSSL_SHA3 */
  3707. /* hmacType */
  3708. #ifndef NO_HMAC
  3709. #ifdef WOLFSSL_SHA224
  3710. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3711. #endif
  3712. #ifndef NO_SHA256
  3713. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3714. #endif
  3715. #ifdef WOLFSSL_SHA384
  3716. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3717. #endif
  3718. #ifdef WOLFSSL_SHA512
  3719. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3720. #endif
  3721. #endif
  3722. /* sigType */
  3723. #if !defined(NO_DSA) && !defined(NO_SHA)
  3724. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3725. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3726. #endif /* NO_DSA */
  3727. #ifndef NO_RSA
  3728. #ifdef WOLFSSL_MD2
  3729. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3730. #endif
  3731. #ifndef NO_MD5
  3732. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3733. #endif
  3734. #ifndef NO_SHA
  3735. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3736. #endif
  3737. #ifdef WOLFSSL_SHA224
  3738. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3739. #endif
  3740. #ifndef NO_SHA256
  3741. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3742. #endif
  3743. #ifdef WOLFSSL_SHA384
  3744. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3745. #endif
  3746. #ifdef WOLFSSL_SHA512
  3747. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3748. #endif
  3749. #ifdef WOLFSSL_SHA3
  3750. #ifndef WOLFSSL_NOSHA3_224
  3751. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3752. #endif
  3753. #ifndef WOLFSSL_NOSHA3_256
  3754. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3755. #endif
  3756. #ifndef WOLFSSL_NOSHA3_384
  3757. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3758. #endif
  3759. #ifndef WOLFSSL_NOSHA3_512
  3760. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3761. #endif
  3762. #endif
  3763. #ifdef WC_RSA_PSS
  3764. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3765. #endif
  3766. #endif /* NO_RSA */
  3767. #ifdef HAVE_ECC
  3768. #ifndef NO_SHA
  3769. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3770. #endif
  3771. #ifdef WOLFSSL_SHA224
  3772. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3773. #endif
  3774. #ifndef NO_SHA256
  3775. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3776. #endif
  3777. #ifdef WOLFSSL_SHA384
  3778. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3779. #endif
  3780. #ifdef WOLFSSL_SHA512
  3781. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3782. #endif
  3783. #ifdef WOLFSSL_SHA3
  3784. #ifndef WOLFSSL_NOSHA3_224
  3785. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3786. #endif
  3787. #ifndef WOLFSSL_NOSHA3_256
  3788. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3789. #endif
  3790. #ifndef WOLFSSL_NOSHA3_384
  3791. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3792. #endif
  3793. #ifndef WOLFSSL_NOSHA3_512
  3794. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3795. #endif
  3796. #endif
  3797. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  3798. /* 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x75 */
  3799. static const byte sigSm3wSm2Oid[] = {42, 129, 28, 207, 85, 1, 131, 117};
  3800. #endif
  3801. #endif /* HAVE_ECC */
  3802. #ifdef HAVE_ED25519
  3803. static const byte sigEd25519Oid[] = {43, 101, 112};
  3804. #endif /* HAVE_ED25519 */
  3805. #ifdef HAVE_ED448
  3806. static const byte sigEd448Oid[] = {43, 101, 113};
  3807. #endif /* HAVE_ED448 */
  3808. #ifdef HAVE_PQC
  3809. #ifdef HAVE_FALCON
  3810. /* Falcon Level 1: 1 3 9999 3 6 */
  3811. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 6};
  3812. /* Falcon Level 5: 1 3 9999 3 9 */
  3813. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 9};
  3814. #endif /* HAVE_FACON */
  3815. #ifdef HAVE_DILITHIUM
  3816. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3817. static const byte sigDilithium_Level2Oid[] =
  3818. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3819. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3820. static const byte sigDilithium_Level3Oid[] =
  3821. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3822. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3823. static const byte sigDilithium_Level5Oid[] =
  3824. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3825. #endif /* HAVE_DILITHIUM */
  3826. #ifdef HAVE_SPHINCS
  3827. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3828. static const byte sigSphincsFast_Level1Oid[] =
  3829. {43, 206, 15, 6, 7, 4};
  3830. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3831. static const byte sigSphincsFast_Level3Oid[] =
  3832. {43, 206, 15, 6, 8, 3};
  3833. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3834. static const byte sigSphincsFast_Level5Oid[] =
  3835. {43, 206, 15, 6, 9, 3};
  3836. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3837. static const byte sigSphincsSmall_Level1Oid[] =
  3838. {43, 206, 15, 6, 7, 10};
  3839. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3840. static const byte sigSphincsSmall_Level3Oid[] =
  3841. {43, 206, 15, 6, 8, 7};
  3842. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3843. static const byte sigSphincsSmall_Level5Oid[] =
  3844. {43, 206, 15, 6, 9, 7};
  3845. #endif /* HAVE_SPHINCS */
  3846. #endif /* HAVE_PQC */
  3847. /* keyType */
  3848. #ifndef NO_DSA
  3849. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3850. #endif /* NO_DSA */
  3851. #ifndef NO_RSA
  3852. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3853. #ifdef WC_RSA_PSS
  3854. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3855. #endif
  3856. #endif /* NO_RSA */
  3857. #ifdef HAVE_ECC
  3858. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3859. #endif /* HAVE_ECC */
  3860. #ifdef HAVE_ED25519
  3861. static const byte keyEd25519Oid[] = {43, 101, 112};
  3862. #endif /* HAVE_ED25519 */
  3863. #ifdef HAVE_CURVE25519
  3864. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3865. #endif
  3866. #ifdef HAVE_ED448
  3867. static const byte keyEd448Oid[] = {43, 101, 113};
  3868. #endif /* HAVE_ED448 */
  3869. #ifdef HAVE_CURVE448
  3870. static const byte keyCurve448Oid[] = {43, 101, 111};
  3871. #endif /* HAVE_CURVE448 */
  3872. #ifndef NO_DH
  3873. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3874. #endif /* !NO_DH */
  3875. #ifdef HAVE_PQC
  3876. #ifdef HAVE_FALCON
  3877. /* Falcon Level 1: 1 3 9999 3 6 */
  3878. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 6};
  3879. /* Falcon Level 5: 1 3 9999 3 9 */
  3880. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 9};
  3881. #endif /* HAVE_FALCON */
  3882. #ifdef HAVE_DILITHIUM
  3883. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3884. static const byte keyDilithium_Level2Oid[] =
  3885. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3886. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3887. static const byte keyDilithium_Level3Oid[] =
  3888. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3889. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3890. static const byte keyDilithium_Level5Oid[] =
  3891. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3892. #endif /* HAVE_DILITHIUM */
  3893. #ifdef HAVE_SPHINCS
  3894. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3895. static const byte keySphincsFast_Level1Oid[] =
  3896. {43, 206, 15, 6, 7, 4};
  3897. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3898. static const byte keySphincsFast_Level3Oid[] =
  3899. {43, 206, 15, 6, 8, 3};
  3900. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3901. static const byte keySphincsFast_Level5Oid[] =
  3902. {43, 206, 15, 6, 9, 3};
  3903. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3904. static const byte keySphincsSmall_Level1Oid[] =
  3905. {43, 206, 15, 6, 7, 10};
  3906. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3907. static const byte keySphincsSmall_Level3Oid[] =
  3908. {43, 206, 15, 6, 8, 7};
  3909. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3910. static const byte keySphincsSmall_Level5Oid[] =
  3911. {43, 206, 15, 6, 9, 7};
  3912. #endif /* HAVE_SPHINCS */
  3913. #endif /* HAVE_PQC */
  3914. /* curveType */
  3915. #ifdef HAVE_ECC
  3916. /* See "ecc_sets" table in ecc.c */
  3917. #endif /* HAVE_ECC */
  3918. #ifdef HAVE_AES_CBC
  3919. /* blkType */
  3920. #ifdef WOLFSSL_AES_128
  3921. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3922. #endif
  3923. #ifdef WOLFSSL_AES_192
  3924. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3925. #endif
  3926. #ifdef WOLFSSL_AES_256
  3927. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3928. #endif
  3929. #endif /* HAVE_AES_CBC */
  3930. #ifdef HAVE_AESGCM
  3931. #ifdef WOLFSSL_AES_128
  3932. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3933. #endif
  3934. #ifdef WOLFSSL_AES_192
  3935. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3936. #endif
  3937. #ifdef WOLFSSL_AES_256
  3938. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3939. #endif
  3940. #endif /* HAVE_AESGCM */
  3941. #ifdef HAVE_AESCCM
  3942. #ifdef WOLFSSL_AES_128
  3943. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3944. #endif
  3945. #ifdef WOLFSSL_AES_192
  3946. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3947. #endif
  3948. #ifdef WOLFSSL_AES_256
  3949. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3950. #endif
  3951. #endif /* HAVE_AESCCM */
  3952. #ifndef NO_DES3
  3953. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3954. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3955. #endif
  3956. /* keyWrapType */
  3957. #ifdef WOLFSSL_AES_128
  3958. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3959. #endif
  3960. #ifdef WOLFSSL_AES_192
  3961. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3962. #endif
  3963. #ifdef WOLFSSL_AES_256
  3964. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3965. #endif
  3966. #ifdef HAVE_PKCS7
  3967. /* From RFC 3211 */
  3968. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3969. #endif
  3970. /* cmsKeyAgreeType */
  3971. #ifndef NO_SHA
  3972. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3973. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3974. #endif
  3975. #ifdef WOLFSSL_SHA224
  3976. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3977. #endif
  3978. #ifndef NO_SHA256
  3979. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3980. #endif
  3981. #ifdef WOLFSSL_SHA384
  3982. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3983. #endif
  3984. #ifdef WOLFSSL_SHA512
  3985. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3986. #endif
  3987. /* ocspType */
  3988. #ifdef HAVE_OCSP
  3989. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3990. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3991. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3992. #endif /* HAVE_OCSP */
  3993. /* certExtType */
  3994. static const byte extBasicCaOid[] = {85, 29, 19};
  3995. static const byte extAltNamesOid[] = {85, 29, 17};
  3996. static const byte extCrlDistOid[] = {85, 29, 31};
  3997. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3998. static const byte extAuthKeyOid[] = {85, 29, 35};
  3999. static const byte extSubjKeyOid[] = {85, 29, 14};
  4000. static const byte extCertPolicyOid[] = {85, 29, 32};
  4001. static const byte extKeyUsageOid[] = {85, 29, 15};
  4002. static const byte extInhibitAnyOid[] = {85, 29, 54};
  4003. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  4004. #ifndef IGNORE_NAME_CONSTRAINTS
  4005. static const byte extNameConsOid[] = {85, 29, 30};
  4006. #endif
  4007. #ifdef HAVE_CRL
  4008. static const byte extCrlNumberOid[] = {85, 29, 20};
  4009. #endif
  4010. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4011. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  4012. #endif
  4013. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4014. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  4015. #endif
  4016. /* certAuthInfoType */
  4017. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  4018. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  4019. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4020. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  4021. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4022. /* certPolicyType */
  4023. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  4024. #ifdef WOLFSSL_FPKI
  4025. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  4026. static const byte extCertPolicyFpkiCommonAuthOid[] =
  4027. CERT_POLICY_TYPE_OID_BASE(13);
  4028. static const byte extCertPolicyFpkiPivAuthOid[] =
  4029. CERT_POLICY_TYPE_OID_BASE(40);
  4030. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  4031. CERT_POLICY_TYPE_OID_BASE(41);
  4032. static const byte extCertPolicyFpkiPiviAuthOid[] =
  4033. CERT_POLICY_TYPE_OID_BASE(45);
  4034. #endif /* WOLFSSL_FPKI */
  4035. /* certAltNameType */
  4036. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  4037. /* certKeyUseType */
  4038. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  4039. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  4040. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  4041. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  4042. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  4043. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  4044. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  4045. #ifdef WOLFSSL_WOLFSSH
  4046. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  4047. static const byte extExtKeyUsageSshClientAuthOid[] =
  4048. EXT_KEY_USAGE_OID_BASE(21);
  4049. static const byte extExtKeyUsageSshMSCLOid[] =
  4050. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  4051. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  4052. {43, 6, 1, 5, 2, 3, 4};
  4053. #endif /* WOLFSSL_WOLFSSH */
  4054. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4055. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  4056. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  4057. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  4058. static const byte extSubjDirAttrGenderOid[] =
  4059. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  4060. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  4061. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  4062. #endif
  4063. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  4064. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  4065. defined(OPENSSL_EXTRA_X509_SMALL)
  4066. /* csrAttrType */
  4067. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  4068. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  4069. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  4070. defined(WOLFSSL_ASN_TEMPLATE)
  4071. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  4072. #endif
  4073. #ifdef WOLFSSL_CERT_REQ
  4074. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  4075. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  4076. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  4077. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  4078. static const byte attrSerialNumberOid[] = {85, 4, 5};
  4079. static const byte attrDnQualifier[] = {85, 4, 46};
  4080. static const byte attrInitals[] = {85, 4, 43};
  4081. static const byte attrSurname[] = {85, 4, 4};
  4082. static const byte attrGivenName[] = {85, 4, 42};
  4083. #endif
  4084. #endif
  4085. /* kdfType */
  4086. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  4087. /* PKCS5 */
  4088. #if !defined(NO_DES3) && !defined(NO_MD5)
  4089. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  4090. #endif
  4091. #if !defined(NO_DES3) && !defined(NO_SHA)
  4092. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  4093. #endif
  4094. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  4095. /* PKCS12 */
  4096. #if !defined(NO_RC4) && !defined(NO_SHA)
  4097. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  4098. #endif
  4099. #if !defined(NO_DES3) && !defined(NO_SHA)
  4100. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  4101. #endif
  4102. #if defined(WC_RC2) && !defined(NO_SHA)
  4103. static const byte pbe40Rc2Cbc[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 6};
  4104. #endif
  4105. #ifdef HAVE_LIBZ
  4106. /* zlib compression */
  4107. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  4108. #endif
  4109. #ifdef WOLFSSL_APACHE_HTTPD
  4110. /* tlsExtType */
  4111. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  4112. /* certNameType */
  4113. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  4114. #endif
  4115. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  4116. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  4117. defined(WOLFSSL_ASN_TEMPLATE)
  4118. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  4119. #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
  4120. static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
  4121. static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
  4122. #endif
  4123. #if defined(WOLFSSL_CERT_GEN) || \
  4124. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  4125. defined(WOLFSSL_ASN_TEMPLATE)
  4126. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  4127. #endif
  4128. /* Looks up the ID/type of an OID.
  4129. *
  4130. * When known returns the OID as a byte array and its length.
  4131. * ID-type are unique.
  4132. *
  4133. * Use oidIgnoreType to autofail.
  4134. *
  4135. * @param [in] id OID id.
  4136. * @param [in] type Type of OID (enum Oid_Types).
  4137. * @param [out] oidSz Length of OID byte array returned.
  4138. * @return Array of bytes for the OID.
  4139. * @return NULL when ID/type not recognized.
  4140. */
  4141. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  4142. {
  4143. const byte* oid = NULL;
  4144. *oidSz = 0;
  4145. switch (type) {
  4146. case oidHashType:
  4147. switch (id) {
  4148. #ifdef WOLFSSL_MD2
  4149. case MD2h:
  4150. oid = hashMd2hOid;
  4151. *oidSz = sizeof(hashMd2hOid);
  4152. break;
  4153. #endif
  4154. #ifndef NO_MD5
  4155. case MD5h:
  4156. oid = hashMd5hOid;
  4157. *oidSz = sizeof(hashMd5hOid);
  4158. break;
  4159. #endif
  4160. #ifndef NO_SHA
  4161. case SHAh:
  4162. oid = hashSha1hOid;
  4163. *oidSz = sizeof(hashSha1hOid);
  4164. break;
  4165. #endif
  4166. #ifdef WOLFSSL_SHA224
  4167. case SHA224h:
  4168. oid = hashSha224hOid;
  4169. *oidSz = sizeof(hashSha224hOid);
  4170. break;
  4171. #endif
  4172. #ifndef NO_SHA256
  4173. case SHA256h:
  4174. oid = hashSha256hOid;
  4175. *oidSz = sizeof(hashSha256hOid);
  4176. break;
  4177. #endif
  4178. #ifdef WOLFSSL_SHA384
  4179. case SHA384h:
  4180. oid = hashSha384hOid;
  4181. *oidSz = sizeof(hashSha384hOid);
  4182. break;
  4183. #endif
  4184. #ifdef WOLFSSL_SHA512
  4185. #ifndef WOLFSSL_NOSHA512_224
  4186. case SHA512_224h:
  4187. oid = hashSha512_224hOid;
  4188. *oidSz = sizeof(hashSha512_224hOid);
  4189. break;
  4190. #endif
  4191. #ifndef WOLFSSL_NOSHA512_256
  4192. case SHA512_256h:
  4193. oid = hashSha512_256hOid;
  4194. *oidSz = sizeof(hashSha512_256hOid);
  4195. break;
  4196. #endif
  4197. case SHA512h:
  4198. oid = hashSha512hOid;
  4199. *oidSz = sizeof(hashSha512hOid);
  4200. break;
  4201. #endif
  4202. #ifdef WOLFSSL_SHA3
  4203. #ifndef WOLFSSL_NOSHA3_224
  4204. case SHA3_224h:
  4205. oid = hashSha3_224hOid;
  4206. *oidSz = sizeof(hashSha3_224hOid);
  4207. break;
  4208. #endif /* WOLFSSL_NOSHA3_224 */
  4209. #ifndef WOLFSSL_NOSHA3_256
  4210. case SHA3_256h:
  4211. oid = hashSha3_256hOid;
  4212. *oidSz = sizeof(hashSha3_256hOid);
  4213. break;
  4214. #endif /* WOLFSSL_NOSHA3_256 */
  4215. #ifndef WOLFSSL_NOSHA3_384
  4216. case SHA3_384h:
  4217. oid = hashSha3_384hOid;
  4218. *oidSz = sizeof(hashSha3_384hOid);
  4219. break;
  4220. #endif /* WOLFSSL_NOSHA3_384 */
  4221. #ifndef WOLFSSL_NOSHA3_512
  4222. case SHA3_512h:
  4223. oid = hashSha3_512hOid;
  4224. *oidSz = sizeof(hashSha3_512hOid);
  4225. break;
  4226. #endif /* WOLFSSL_NOSHA3_512 */
  4227. #endif /* WOLFSSL_SHA3 */
  4228. default:
  4229. break;
  4230. }
  4231. break;
  4232. case oidSigType:
  4233. switch (id) {
  4234. #if !defined(NO_DSA) && !defined(NO_SHA)
  4235. case CTC_SHAwDSA:
  4236. oid = sigSha1wDsaOid;
  4237. *oidSz = sizeof(sigSha1wDsaOid);
  4238. break;
  4239. case CTC_SHA256wDSA:
  4240. oid = sigSha256wDsaOid;
  4241. *oidSz = sizeof(sigSha256wDsaOid);
  4242. break;
  4243. #endif /* NO_DSA */
  4244. #ifndef NO_RSA
  4245. #ifdef WOLFSSL_MD2
  4246. case CTC_MD2wRSA:
  4247. oid = sigMd2wRsaOid;
  4248. *oidSz = sizeof(sigMd2wRsaOid);
  4249. break;
  4250. #endif
  4251. #ifndef NO_MD5
  4252. case CTC_MD5wRSA:
  4253. oid = sigMd5wRsaOid;
  4254. *oidSz = sizeof(sigMd5wRsaOid);
  4255. break;
  4256. #endif
  4257. #ifndef NO_SHA
  4258. case CTC_SHAwRSA:
  4259. oid = sigSha1wRsaOid;
  4260. *oidSz = sizeof(sigSha1wRsaOid);
  4261. break;
  4262. #endif
  4263. #ifdef WOLFSSL_SHA224
  4264. case CTC_SHA224wRSA:
  4265. oid = sigSha224wRsaOid;
  4266. *oidSz = sizeof(sigSha224wRsaOid);
  4267. break;
  4268. #endif
  4269. #ifndef NO_SHA256
  4270. case CTC_SHA256wRSA:
  4271. oid = sigSha256wRsaOid;
  4272. *oidSz = sizeof(sigSha256wRsaOid);
  4273. break;
  4274. #endif
  4275. #ifdef WOLFSSL_SHA384
  4276. case CTC_SHA384wRSA:
  4277. oid = sigSha384wRsaOid;
  4278. *oidSz = sizeof(sigSha384wRsaOid);
  4279. break;
  4280. #endif
  4281. #ifdef WOLFSSL_SHA512
  4282. case CTC_SHA512wRSA:
  4283. oid = sigSha512wRsaOid;
  4284. *oidSz = sizeof(sigSha512wRsaOid);
  4285. break;
  4286. #endif /* WOLFSSL_SHA512 */
  4287. #ifdef WOLFSSL_SHA3
  4288. #ifndef WOLFSSL_NOSHA3_224
  4289. case CTC_SHA3_224wRSA:
  4290. oid = sigSha3_224wRsaOid;
  4291. *oidSz = sizeof(sigSha3_224wRsaOid);
  4292. break;
  4293. #endif
  4294. #ifndef WOLFSSL_NOSHA3_256
  4295. case CTC_SHA3_256wRSA:
  4296. oid = sigSha3_256wRsaOid;
  4297. *oidSz = sizeof(sigSha3_256wRsaOid);
  4298. break;
  4299. #endif
  4300. #ifndef WOLFSSL_NOSHA3_384
  4301. case CTC_SHA3_384wRSA:
  4302. oid = sigSha3_384wRsaOid;
  4303. *oidSz = sizeof(sigSha3_384wRsaOid);
  4304. break;
  4305. #endif
  4306. #ifndef WOLFSSL_NOSHA3_512
  4307. case CTC_SHA3_512wRSA:
  4308. oid = sigSha3_512wRsaOid;
  4309. *oidSz = sizeof(sigSha3_512wRsaOid);
  4310. break;
  4311. #endif
  4312. #endif
  4313. #ifdef WC_RSA_PSS
  4314. case CTC_RSASSAPSS:
  4315. oid = sigRsaSsaPssOid;
  4316. *oidSz = sizeof(sigRsaSsaPssOid);
  4317. break;
  4318. #endif
  4319. #endif /* NO_RSA */
  4320. #ifdef HAVE_ECC
  4321. #ifndef NO_SHA
  4322. case CTC_SHAwECDSA:
  4323. oid = sigSha1wEcdsaOid;
  4324. *oidSz = sizeof(sigSha1wEcdsaOid);
  4325. break;
  4326. #endif
  4327. #ifdef WOLFSSL_SHA224
  4328. case CTC_SHA224wECDSA:
  4329. oid = sigSha224wEcdsaOid;
  4330. *oidSz = sizeof(sigSha224wEcdsaOid);
  4331. break;
  4332. #endif
  4333. #ifndef NO_SHA256
  4334. case CTC_SHA256wECDSA:
  4335. oid = sigSha256wEcdsaOid;
  4336. *oidSz = sizeof(sigSha256wEcdsaOid);
  4337. break;
  4338. #endif
  4339. #ifdef WOLFSSL_SHA384
  4340. case CTC_SHA384wECDSA:
  4341. oid = sigSha384wEcdsaOid;
  4342. *oidSz = sizeof(sigSha384wEcdsaOid);
  4343. break;
  4344. #endif
  4345. #ifdef WOLFSSL_SHA512
  4346. case CTC_SHA512wECDSA:
  4347. oid = sigSha512wEcdsaOid;
  4348. *oidSz = sizeof(sigSha512wEcdsaOid);
  4349. break;
  4350. #endif
  4351. #ifdef WOLFSSL_SHA3
  4352. #ifndef WOLFSSL_NOSHA3_224
  4353. case CTC_SHA3_224wECDSA:
  4354. oid = sigSha3_224wEcdsaOid;
  4355. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4356. break;
  4357. #endif
  4358. #ifndef WOLFSSL_NOSHA3_256
  4359. case CTC_SHA3_256wECDSA:
  4360. oid = sigSha3_256wEcdsaOid;
  4361. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4362. break;
  4363. #endif
  4364. #ifndef WOLFSSL_NOSHA3_384
  4365. case CTC_SHA3_384wECDSA:
  4366. oid = sigSha3_384wEcdsaOid;
  4367. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4368. break;
  4369. #endif
  4370. #ifndef WOLFSSL_NOSHA3_512
  4371. case CTC_SHA3_512wECDSA:
  4372. oid = sigSha3_512wEcdsaOid;
  4373. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4374. break;
  4375. #endif
  4376. #endif
  4377. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  4378. case CTC_SM3wSM2:
  4379. oid = sigSm3wSm2Oid;
  4380. *oidSz = sizeof(sigSm3wSm2Oid);
  4381. break;
  4382. #endif
  4383. #endif /* HAVE_ECC */
  4384. #ifdef HAVE_ED25519
  4385. case CTC_ED25519:
  4386. oid = sigEd25519Oid;
  4387. *oidSz = sizeof(sigEd25519Oid);
  4388. break;
  4389. #endif
  4390. #ifdef HAVE_ED448
  4391. case CTC_ED448:
  4392. oid = sigEd448Oid;
  4393. *oidSz = sizeof(sigEd448Oid);
  4394. break;
  4395. #endif
  4396. #ifdef HAVE_PQC
  4397. #ifdef HAVE_FALCON
  4398. case CTC_FALCON_LEVEL1:
  4399. oid = sigFalcon_Level1Oid;
  4400. *oidSz = sizeof(sigFalcon_Level1Oid);
  4401. break;
  4402. case CTC_FALCON_LEVEL5:
  4403. oid = sigFalcon_Level5Oid;
  4404. *oidSz = sizeof(sigFalcon_Level5Oid);
  4405. break;
  4406. #endif /* HAVE_FALCON */
  4407. #ifdef HAVE_DILITHIUM
  4408. case CTC_DILITHIUM_LEVEL2:
  4409. oid = sigDilithium_Level2Oid;
  4410. *oidSz = sizeof(sigDilithium_Level2Oid);
  4411. break;
  4412. case CTC_DILITHIUM_LEVEL3:
  4413. oid = sigDilithium_Level3Oid;
  4414. *oidSz = sizeof(sigDilithium_Level3Oid);
  4415. break;
  4416. case CTC_DILITHIUM_LEVEL5:
  4417. oid = sigDilithium_Level5Oid;
  4418. *oidSz = sizeof(sigDilithium_Level5Oid);
  4419. break;
  4420. #endif /* HAVE_DILITHIUM */
  4421. #ifdef HAVE_SPHINCS
  4422. case CTC_SPHINCS_FAST_LEVEL1:
  4423. oid = sigSphincsFast_Level1Oid;
  4424. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4425. break;
  4426. case CTC_SPHINCS_FAST_LEVEL3:
  4427. oid = sigSphincsFast_Level3Oid;
  4428. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4429. break;
  4430. case CTC_SPHINCS_FAST_LEVEL5:
  4431. oid = sigSphincsFast_Level5Oid;
  4432. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4433. break;
  4434. case CTC_SPHINCS_SMALL_LEVEL1:
  4435. oid = sigSphincsSmall_Level1Oid;
  4436. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4437. break;
  4438. case CTC_SPHINCS_SMALL_LEVEL3:
  4439. oid = sigSphincsSmall_Level3Oid;
  4440. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4441. break;
  4442. case CTC_SPHINCS_SMALL_LEVEL5:
  4443. oid = sigSphincsSmall_Level5Oid;
  4444. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4445. break;
  4446. #endif /* HAVE_SPHINCS */
  4447. #endif /* HAVE_PQC */
  4448. default:
  4449. break;
  4450. }
  4451. break;
  4452. case oidKeyType:
  4453. switch (id) {
  4454. #ifndef NO_DSA
  4455. case DSAk:
  4456. oid = keyDsaOid;
  4457. *oidSz = sizeof(keyDsaOid);
  4458. break;
  4459. #endif /* NO_DSA */
  4460. #ifndef NO_RSA
  4461. case RSAk:
  4462. oid = keyRsaOid;
  4463. *oidSz = sizeof(keyRsaOid);
  4464. break;
  4465. #ifdef WC_RSA_PSS
  4466. case RSAPSSk:
  4467. oid = keyRsaPssOid;
  4468. *oidSz = sizeof(keyRsaPssOid);
  4469. break;
  4470. #endif
  4471. #endif /* NO_RSA */
  4472. #ifdef HAVE_ECC
  4473. case ECDSAk:
  4474. oid = keyEcdsaOid;
  4475. *oidSz = sizeof(keyEcdsaOid);
  4476. break;
  4477. #endif /* HAVE_ECC */
  4478. #ifdef HAVE_ED25519
  4479. case ED25519k:
  4480. oid = keyEd25519Oid;
  4481. *oidSz = sizeof(keyEd25519Oid);
  4482. break;
  4483. #endif /* HAVE_ED25519 */
  4484. #ifdef HAVE_CURVE25519
  4485. case X25519k:
  4486. oid = keyCurve25519Oid;
  4487. *oidSz = sizeof(keyCurve25519Oid);
  4488. break;
  4489. #endif /* HAVE_CURVE25519 */
  4490. #ifdef HAVE_ED448
  4491. case ED448k:
  4492. oid = keyEd448Oid;
  4493. *oidSz = sizeof(keyEd448Oid);
  4494. break;
  4495. #endif /* HAVE_ED448 */
  4496. #ifdef HAVE_CURVE448
  4497. case X448k:
  4498. oid = keyCurve448Oid;
  4499. *oidSz = sizeof(keyCurve448Oid);
  4500. break;
  4501. #endif /* HAVE_CURVE448 */
  4502. #ifndef NO_DH
  4503. case DHk:
  4504. oid = keyDhOid;
  4505. *oidSz = sizeof(keyDhOid);
  4506. break;
  4507. #endif /* !NO_DH */
  4508. #ifdef HAVE_PQC
  4509. #ifdef HAVE_FALCON
  4510. case FALCON_LEVEL1k:
  4511. oid = keyFalcon_Level1Oid;
  4512. *oidSz = sizeof(keyFalcon_Level1Oid);
  4513. break;
  4514. case FALCON_LEVEL5k:
  4515. oid = keyFalcon_Level5Oid;
  4516. *oidSz = sizeof(keyFalcon_Level5Oid);
  4517. break;
  4518. #endif /* HAVE_FALCON */
  4519. #ifdef HAVE_DILITHIUM
  4520. case DILITHIUM_LEVEL2k:
  4521. oid = keyDilithium_Level2Oid;
  4522. *oidSz = sizeof(keyDilithium_Level2Oid);
  4523. break;
  4524. case DILITHIUM_LEVEL3k:
  4525. oid = keyDilithium_Level3Oid;
  4526. *oidSz = sizeof(keyDilithium_Level3Oid);
  4527. break;
  4528. case DILITHIUM_LEVEL5k:
  4529. oid = keyDilithium_Level5Oid;
  4530. *oidSz = sizeof(keyDilithium_Level5Oid);
  4531. break;
  4532. #endif /* HAVE_DILITHIUM */
  4533. #ifdef HAVE_SPHINCS
  4534. case SPHINCS_FAST_LEVEL1k:
  4535. oid = keySphincsFast_Level1Oid;
  4536. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4537. break;
  4538. case SPHINCS_FAST_LEVEL3k:
  4539. oid = keySphincsFast_Level3Oid;
  4540. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4541. break;
  4542. case SPHINCS_FAST_LEVEL5k:
  4543. oid = keySphincsFast_Level5Oid;
  4544. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4545. break;
  4546. case SPHINCS_SMALL_LEVEL1k:
  4547. oid = keySphincsSmall_Level1Oid;
  4548. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4549. break;
  4550. case SPHINCS_SMALL_LEVEL3k:
  4551. oid = keySphincsSmall_Level3Oid;
  4552. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4553. break;
  4554. case SPHINCS_SMALL_LEVEL5k:
  4555. oid = keySphincsSmall_Level5Oid;
  4556. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4557. break;
  4558. #endif /* HAVE_SPHINCS */
  4559. #endif /* HAVE_PQC */
  4560. default:
  4561. break;
  4562. }
  4563. break;
  4564. #ifdef HAVE_ECC
  4565. case oidCurveType:
  4566. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4567. WOLFSSL_MSG("ECC OID not found");
  4568. }
  4569. break;
  4570. #endif /* HAVE_ECC */
  4571. case oidBlkType:
  4572. switch (id) {
  4573. #ifdef HAVE_AES_CBC
  4574. #ifdef WOLFSSL_AES_128
  4575. case AES128CBCb:
  4576. oid = blkAes128CbcOid;
  4577. *oidSz = sizeof(blkAes128CbcOid);
  4578. break;
  4579. #endif
  4580. #ifdef WOLFSSL_AES_192
  4581. case AES192CBCb:
  4582. oid = blkAes192CbcOid;
  4583. *oidSz = sizeof(blkAes192CbcOid);
  4584. break;
  4585. #endif
  4586. #ifdef WOLFSSL_AES_256
  4587. case AES256CBCb:
  4588. oid = blkAes256CbcOid;
  4589. *oidSz = sizeof(blkAes256CbcOid);
  4590. break;
  4591. #endif
  4592. #endif /* HAVE_AES_CBC */
  4593. #ifdef HAVE_AESGCM
  4594. #ifdef WOLFSSL_AES_128
  4595. case AES128GCMb:
  4596. oid = blkAes128GcmOid;
  4597. *oidSz = sizeof(blkAes128GcmOid);
  4598. break;
  4599. #endif
  4600. #ifdef WOLFSSL_AES_192
  4601. case AES192GCMb:
  4602. oid = blkAes192GcmOid;
  4603. *oidSz = sizeof(blkAes192GcmOid);
  4604. break;
  4605. #endif
  4606. #ifdef WOLFSSL_AES_256
  4607. case AES256GCMb:
  4608. oid = blkAes256GcmOid;
  4609. *oidSz = sizeof(blkAes256GcmOid);
  4610. break;
  4611. #endif
  4612. #endif /* HAVE_AESGCM */
  4613. #ifdef HAVE_AESCCM
  4614. #ifdef WOLFSSL_AES_128
  4615. case AES128CCMb:
  4616. oid = blkAes128CcmOid;
  4617. *oidSz = sizeof(blkAes128CcmOid);
  4618. break;
  4619. #endif
  4620. #ifdef WOLFSSL_AES_192
  4621. case AES192CCMb:
  4622. oid = blkAes192CcmOid;
  4623. *oidSz = sizeof(blkAes192CcmOid);
  4624. break;
  4625. #endif
  4626. #ifdef WOLFSSL_AES_256
  4627. case AES256CCMb:
  4628. oid = blkAes256CcmOid;
  4629. *oidSz = sizeof(blkAes256CcmOid);
  4630. break;
  4631. #endif
  4632. #endif /* HAVE_AESCCM */
  4633. #ifndef NO_DES3
  4634. case DESb:
  4635. oid = blkDesCbcOid;
  4636. *oidSz = sizeof(blkDesCbcOid);
  4637. break;
  4638. case DES3b:
  4639. oid = blkDes3CbcOid;
  4640. *oidSz = sizeof(blkDes3CbcOid);
  4641. break;
  4642. #endif /* !NO_DES3 */
  4643. default:
  4644. break;
  4645. }
  4646. break;
  4647. #ifdef HAVE_OCSP
  4648. case oidOcspType:
  4649. switch (id) {
  4650. case OCSP_BASIC_OID:
  4651. oid = ocspBasicOid;
  4652. *oidSz = sizeof(ocspBasicOid);
  4653. break;
  4654. case OCSP_NONCE_OID:
  4655. oid = ocspNonceOid;
  4656. *oidSz = sizeof(ocspNonceOid);
  4657. break;
  4658. default:
  4659. break;
  4660. }
  4661. break;
  4662. #endif /* HAVE_OCSP */
  4663. case oidCertExtType:
  4664. switch (id) {
  4665. case BASIC_CA_OID:
  4666. oid = extBasicCaOid;
  4667. *oidSz = sizeof(extBasicCaOid);
  4668. break;
  4669. case ALT_NAMES_OID:
  4670. oid = extAltNamesOid;
  4671. *oidSz = sizeof(extAltNamesOid);
  4672. break;
  4673. case CRL_DIST_OID:
  4674. oid = extCrlDistOid;
  4675. *oidSz = sizeof(extCrlDistOid);
  4676. break;
  4677. case AUTH_INFO_OID:
  4678. oid = extAuthInfoOid;
  4679. *oidSz = sizeof(extAuthInfoOid);
  4680. break;
  4681. case AUTH_KEY_OID:
  4682. oid = extAuthKeyOid;
  4683. *oidSz = sizeof(extAuthKeyOid);
  4684. break;
  4685. case SUBJ_KEY_OID:
  4686. oid = extSubjKeyOid;
  4687. *oidSz = sizeof(extSubjKeyOid);
  4688. break;
  4689. case CERT_POLICY_OID:
  4690. oid = extCertPolicyOid;
  4691. *oidSz = sizeof(extCertPolicyOid);
  4692. break;
  4693. case KEY_USAGE_OID:
  4694. oid = extKeyUsageOid;
  4695. *oidSz = sizeof(extKeyUsageOid);
  4696. break;
  4697. case INHIBIT_ANY_OID:
  4698. oid = extInhibitAnyOid;
  4699. *oidSz = sizeof(extInhibitAnyOid);
  4700. break;
  4701. case EXT_KEY_USAGE_OID:
  4702. oid = extExtKeyUsageOid;
  4703. *oidSz = sizeof(extExtKeyUsageOid);
  4704. break;
  4705. #ifndef IGNORE_NAME_CONSTRAINTS
  4706. case NAME_CONS_OID:
  4707. oid = extNameConsOid;
  4708. *oidSz = sizeof(extNameConsOid);
  4709. break;
  4710. #endif
  4711. #ifdef HAVE_OCSP
  4712. case OCSP_NOCHECK_OID:
  4713. oid = ocspNoCheckOid;
  4714. *oidSz = sizeof(ocspNoCheckOid);
  4715. break;
  4716. #endif
  4717. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4718. case SUBJ_DIR_ATTR_OID:
  4719. oid = extSubjDirAttrOid;
  4720. *oidSz = sizeof(extSubjDirAttrOid);
  4721. break;
  4722. #endif
  4723. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4724. case SUBJ_INFO_ACC_OID:
  4725. oid = extSubjInfoAccessOid;
  4726. *oidSz = sizeof(extSubjInfoAccessOid);
  4727. break;
  4728. #endif
  4729. default:
  4730. break;
  4731. }
  4732. break;
  4733. case oidCrlExtType:
  4734. #ifdef HAVE_CRL
  4735. switch (id) {
  4736. case AUTH_KEY_OID:
  4737. oid = extAuthKeyOid;
  4738. *oidSz = sizeof(extAuthKeyOid);
  4739. break;
  4740. case CRL_NUMBER_OID:
  4741. oid = extCrlNumberOid;
  4742. *oidSz = sizeof(extCrlNumberOid);
  4743. break;
  4744. default:
  4745. break;
  4746. }
  4747. #endif
  4748. break;
  4749. case oidCertAuthInfoType:
  4750. switch (id) {
  4751. case AIA_OCSP_OID:
  4752. oid = extAuthInfoOcspOid;
  4753. *oidSz = sizeof(extAuthInfoOcspOid);
  4754. break;
  4755. case AIA_CA_ISSUER_OID:
  4756. oid = extAuthInfoCaIssuerOid;
  4757. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4758. break;
  4759. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4760. case AIA_CA_REPO_OID:
  4761. oid = extAuthInfoCaRespOid;
  4762. *oidSz = sizeof(extAuthInfoCaRespOid);
  4763. break;
  4764. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4765. default:
  4766. break;
  4767. }
  4768. break;
  4769. case oidCertPolicyType:
  4770. switch (id) {
  4771. case CP_ANY_OID:
  4772. oid = extCertPolicyAnyOid;
  4773. *oidSz = sizeof(extCertPolicyAnyOid);
  4774. break;
  4775. #if defined(WOLFSSL_FPKI)
  4776. case CP_FPKI_COMMON_AUTH_OID:
  4777. oid = extCertPolicyFpkiCommonAuthOid;
  4778. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4779. break;
  4780. case CP_FPKI_PIV_AUTH_OID:
  4781. oid = extCertPolicyFpkiPivAuthOid;
  4782. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4783. break;
  4784. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4785. oid = extCertPolicyFpkiPivAuthHwOid;
  4786. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4787. break;
  4788. case CP_FPKI_PIVI_AUTH_OID:
  4789. oid = extCertPolicyFpkiPiviAuthOid;
  4790. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4791. break;
  4792. #endif /* WOLFSSL_FPKI */
  4793. default:
  4794. break;
  4795. }
  4796. break;
  4797. case oidCertAltNameType:
  4798. switch (id) {
  4799. case HW_NAME_OID:
  4800. oid = extAltNamesHwNameOid;
  4801. *oidSz = sizeof(extAltNamesHwNameOid);
  4802. break;
  4803. default:
  4804. break;
  4805. }
  4806. break;
  4807. case oidCertKeyUseType:
  4808. switch (id) {
  4809. case EKU_ANY_OID:
  4810. oid = extExtKeyUsageAnyOid;
  4811. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4812. break;
  4813. case EKU_SERVER_AUTH_OID:
  4814. oid = extExtKeyUsageServerAuthOid;
  4815. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4816. break;
  4817. case EKU_CLIENT_AUTH_OID:
  4818. oid = extExtKeyUsageClientAuthOid;
  4819. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4820. break;
  4821. case EKU_CODESIGNING_OID:
  4822. oid = extExtKeyUsageCodeSigningOid;
  4823. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4824. break;
  4825. case EKU_EMAILPROTECT_OID:
  4826. oid = extExtKeyUsageEmailProtectOid;
  4827. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4828. break;
  4829. case EKU_TIMESTAMP_OID:
  4830. oid = extExtKeyUsageTimestampOid;
  4831. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4832. break;
  4833. case EKU_OCSP_SIGN_OID:
  4834. oid = extExtKeyUsageOcspSignOid;
  4835. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4836. break;
  4837. #ifdef WOLFSSL_WOLFSSH
  4838. case EKU_SSH_CLIENT_AUTH_OID:
  4839. oid = extExtKeyUsageSshClientAuthOid;
  4840. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4841. break;
  4842. case EKU_SSH_MSCL_OID:
  4843. oid = extExtKeyUsageSshMSCLOid;
  4844. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4845. break;
  4846. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4847. oid = extExtKeyUsageSshKpClientAuthOid;
  4848. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4849. break;
  4850. #endif /* WOLFSSL_WOLFSSH */
  4851. default:
  4852. break;
  4853. }
  4854. break;
  4855. case oidKdfType:
  4856. switch (id) {
  4857. case PBKDF2_OID:
  4858. oid = pbkdf2Oid;
  4859. *oidSz = sizeof(pbkdf2Oid);
  4860. break;
  4861. default:
  4862. break;
  4863. }
  4864. break;
  4865. case oidPBEType:
  4866. switch (id) {
  4867. #if !defined(NO_SHA) && !defined(NO_RC4)
  4868. case PBE_SHA1_RC4_128_SUM:
  4869. case PBE_SHA1_RC4_128:
  4870. oid = pbeSha1RC4128;
  4871. *oidSz = sizeof(pbeSha1RC4128);
  4872. break;
  4873. #endif
  4874. #if !defined(NO_MD5) && !defined(NO_DES3)
  4875. case PBE_MD5_DES_SUM:
  4876. case PBE_MD5_DES:
  4877. oid = pbeMd5Des;
  4878. *oidSz = sizeof(pbeMd5Des);
  4879. break;
  4880. #endif
  4881. #if !defined(NO_SHA) && !defined(NO_DES3)
  4882. case PBE_SHA1_DES_SUM:
  4883. case PBE_SHA1_DES:
  4884. oid = pbeSha1Des;
  4885. *oidSz = sizeof(pbeSha1Des);
  4886. break;
  4887. #endif
  4888. #if !defined(NO_SHA) && !defined(NO_DES3)
  4889. case PBE_SHA1_DES3_SUM:
  4890. case PBE_SHA1_DES3:
  4891. oid = pbeSha1Des3;
  4892. *oidSz = sizeof(pbeSha1Des3);
  4893. break;
  4894. #endif
  4895. #if !defined(NO_SHA) && defined(WC_RC2)
  4896. case PBE_SHA1_40RC2_CBC_SUM:
  4897. case PBE_SHA1_40RC2_CBC:
  4898. oid = pbe40Rc2Cbc;
  4899. *oidSz = sizeof(pbe40Rc2Cbc);
  4900. break;
  4901. #endif
  4902. case PBES2_SUM:
  4903. case PBES2:
  4904. oid = pbes2;
  4905. *oidSz = sizeof(pbes2);
  4906. break;
  4907. default:
  4908. break;
  4909. }
  4910. break;
  4911. case oidKeyWrapType:
  4912. switch (id) {
  4913. #ifdef WOLFSSL_AES_128
  4914. case AES128_WRAP:
  4915. oid = wrapAes128Oid;
  4916. *oidSz = sizeof(wrapAes128Oid);
  4917. break;
  4918. #endif
  4919. #ifdef WOLFSSL_AES_192
  4920. case AES192_WRAP:
  4921. oid = wrapAes192Oid;
  4922. *oidSz = sizeof(wrapAes192Oid);
  4923. break;
  4924. #endif
  4925. #ifdef WOLFSSL_AES_256
  4926. case AES256_WRAP:
  4927. oid = wrapAes256Oid;
  4928. *oidSz = sizeof(wrapAes256Oid);
  4929. break;
  4930. #endif
  4931. #ifdef HAVE_PKCS7
  4932. case PWRI_KEK_WRAP:
  4933. oid = wrapPwriKekOid;
  4934. *oidSz = sizeof(wrapPwriKekOid);
  4935. break;
  4936. #endif
  4937. default:
  4938. break;
  4939. }
  4940. break;
  4941. case oidCmsKeyAgreeType:
  4942. switch (id) {
  4943. #ifndef NO_SHA
  4944. case dhSinglePass_stdDH_sha1kdf_scheme:
  4945. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4946. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4947. break;
  4948. #endif
  4949. #ifdef WOLFSSL_SHA224
  4950. case dhSinglePass_stdDH_sha224kdf_scheme:
  4951. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4952. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4953. break;
  4954. #endif
  4955. #ifndef NO_SHA256
  4956. case dhSinglePass_stdDH_sha256kdf_scheme:
  4957. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4958. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4959. break;
  4960. #endif
  4961. #ifdef WOLFSSL_SHA384
  4962. case dhSinglePass_stdDH_sha384kdf_scheme:
  4963. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4964. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4965. break;
  4966. #endif
  4967. #ifdef WOLFSSL_SHA512
  4968. case dhSinglePass_stdDH_sha512kdf_scheme:
  4969. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4970. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4971. break;
  4972. #endif
  4973. default:
  4974. break;
  4975. }
  4976. break;
  4977. #ifndef NO_HMAC
  4978. case oidHmacType:
  4979. switch (id) {
  4980. #ifdef WOLFSSL_SHA224
  4981. case HMAC_SHA224_OID:
  4982. oid = hmacSha224Oid;
  4983. *oidSz = sizeof(hmacSha224Oid);
  4984. break;
  4985. #endif
  4986. #ifndef NO_SHA256
  4987. case HMAC_SHA256_OID:
  4988. oid = hmacSha256Oid;
  4989. *oidSz = sizeof(hmacSha256Oid);
  4990. break;
  4991. #endif
  4992. #ifdef WOLFSSL_SHA384
  4993. case HMAC_SHA384_OID:
  4994. oid = hmacSha384Oid;
  4995. *oidSz = sizeof(hmacSha384Oid);
  4996. break;
  4997. #endif
  4998. #ifdef WOLFSSL_SHA512
  4999. case HMAC_SHA512_OID:
  5000. oid = hmacSha512Oid;
  5001. *oidSz = sizeof(hmacSha512Oid);
  5002. break;
  5003. #endif
  5004. default:
  5005. break;
  5006. }
  5007. break;
  5008. #endif /* !NO_HMAC */
  5009. #ifdef HAVE_LIBZ
  5010. case oidCompressType:
  5011. switch (id) {
  5012. case ZLIBc:
  5013. oid = zlibCompress;
  5014. *oidSz = sizeof(zlibCompress);
  5015. break;
  5016. default:
  5017. break;
  5018. }
  5019. break;
  5020. #endif /* HAVE_LIBZ */
  5021. #ifdef WOLFSSL_APACHE_HTTPD
  5022. case oidCertNameType:
  5023. switch (id) {
  5024. case NID_id_on_dnsSRV:
  5025. oid = dnsSRVOid;
  5026. *oidSz = sizeof(dnsSRVOid);
  5027. break;
  5028. default:
  5029. break;
  5030. }
  5031. break;
  5032. case oidTlsExtType:
  5033. switch (id) {
  5034. case TLS_FEATURE_OID:
  5035. oid = tlsFeatureOid;
  5036. *oidSz = sizeof(tlsFeatureOid);
  5037. break;
  5038. default:
  5039. break;
  5040. }
  5041. break;
  5042. #endif /* WOLFSSL_APACHE_HTTPD */
  5043. #ifdef WOLFSSL_CERT_REQ
  5044. case oidCsrAttrType:
  5045. switch (id) {
  5046. case GIVEN_NAME_OID:
  5047. oid = attrGivenName;
  5048. *oidSz = sizeof(attrGivenName);
  5049. break;
  5050. case SURNAME_OID:
  5051. oid = attrSurname;
  5052. *oidSz = sizeof(attrSurname);
  5053. break;
  5054. case INITIALS_OID:
  5055. oid = attrInitals;
  5056. *oidSz = sizeof(attrInitals);
  5057. break;
  5058. case DNQUALIFIER_OID:
  5059. oid = attrDnQualifier;
  5060. *oidSz = sizeof(attrDnQualifier);
  5061. break;
  5062. case UNSTRUCTURED_NAME_OID:
  5063. oid = attrUnstructuredNameOid;
  5064. *oidSz = sizeof(attrUnstructuredNameOid);
  5065. break;
  5066. case PKCS9_CONTENT_TYPE_OID:
  5067. oid = attrPkcs9ContentTypeOid;
  5068. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  5069. break;
  5070. case CHALLENGE_PASSWORD_OID:
  5071. oid = attrChallengePasswordOid;
  5072. *oidSz = sizeof(attrChallengePasswordOid);
  5073. break;
  5074. case SERIAL_NUMBER_OID:
  5075. oid = attrSerialNumberOid;
  5076. *oidSz = sizeof(attrSerialNumberOid);
  5077. break;
  5078. case USER_ID_OID:
  5079. oid = uidOid;
  5080. *oidSz = sizeof(uidOid);
  5081. break;
  5082. case EXTENSION_REQUEST_OID:
  5083. oid = attrExtensionRequestOid;
  5084. *oidSz = sizeof(attrExtensionRequestOid);
  5085. break;
  5086. default:
  5087. break;
  5088. }
  5089. break;
  5090. #endif
  5091. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  5092. case oidSubjDirAttrType:
  5093. switch (id) {
  5094. case SDA_DOB_OID:
  5095. oid = extSubjDirAttrDobOid;
  5096. *oidSz = sizeof(extSubjDirAttrDobOid);
  5097. break;
  5098. case SDA_POB_OID:
  5099. oid = extSubjDirAttrPobOid;
  5100. *oidSz = sizeof(extSubjDirAttrPobOid);
  5101. break;
  5102. case SDA_GENDER_OID:
  5103. oid = extSubjDirAttrGenderOid;
  5104. *oidSz = sizeof(extSubjDirAttrGenderOid);
  5105. break;
  5106. case SDA_COC_OID:
  5107. oid = extSubjDirAttrCocOid;
  5108. *oidSz = sizeof(extSubjDirAttrCocOid);
  5109. break;
  5110. case SDA_COR_OID:
  5111. oid = extSubjDirAttrCorOid;
  5112. *oidSz = sizeof(extSubjDirAttrCorOid);
  5113. break;
  5114. default:
  5115. break;
  5116. }
  5117. break;
  5118. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  5119. case oidIgnoreType:
  5120. default:
  5121. break;
  5122. }
  5123. return oid;
  5124. }
  5125. #ifdef HAVE_ECC
  5126. /* Check the OID id is for a known elliptic curve.
  5127. *
  5128. * @param [in] oid OID id.
  5129. * @return ECC set id on success.
  5130. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  5131. */
  5132. static int CheckCurve(word32 oid)
  5133. {
  5134. int ret;
  5135. word32 oidSz;
  5136. /* Lookup OID id. */
  5137. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  5138. /* Check for error or zero length OID size (can't get OID for encoding). */
  5139. if ((ret < 0) || (oidSz == 0)) {
  5140. WOLFSSL_MSG("CheckCurve not found");
  5141. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  5142. ret = ECC_CURVE_OID_E;
  5143. }
  5144. /* Return ECC set id or error code. */
  5145. return ret;
  5146. }
  5147. #endif
  5148. #ifdef HAVE_OID_ENCODING
  5149. /* Encode dotted form of OID into byte array version.
  5150. *
  5151. * @param [in] in Dotted form of OID.
  5152. * @param [in] inSz Count of numbers in dotted form.
  5153. * @param [in] out Buffer to hold OID.
  5154. * @param [in, out] outSz On in, size of buffer.
  5155. * On out, number of bytes in buffer.
  5156. * @return 0 on success
  5157. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5158. * @return BUFFER_E when buffer too small.
  5159. */
  5160. int wc_EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5161. {
  5162. return EncodeObjectId(in, inSz, out, outSz);
  5163. }
  5164. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5165. {
  5166. int i, x, len;
  5167. word32 d, t;
  5168. /* check args */
  5169. if (in == NULL || outSz == NULL || inSz <= 0) {
  5170. return BAD_FUNC_ARG;
  5171. }
  5172. /* compute length of encoded OID */
  5173. d = (in[0] * 40) + in[1];
  5174. len = 0;
  5175. for (i = 1; i < (int)inSz; i++) {
  5176. x = 0;
  5177. t = d;
  5178. while (t) {
  5179. x++;
  5180. t >>= 1;
  5181. }
  5182. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5183. if (i < (int)inSz - 1) {
  5184. d = in[i + 1];
  5185. }
  5186. }
  5187. if (out) {
  5188. /* verify length */
  5189. if ((int)*outSz < len) {
  5190. return BUFFER_E; /* buffer provided is not large enough */
  5191. }
  5192. /* calc first byte */
  5193. d = (in[0] * 40) + in[1];
  5194. /* encode bytes */
  5195. x = 0;
  5196. for (i = 1; i < (int)inSz; i++) {
  5197. if (d) {
  5198. int y = x, z;
  5199. byte mask = 0;
  5200. while (d) {
  5201. out[x++] = (byte)((d & 0x7F) | mask);
  5202. d >>= 7;
  5203. mask |= 0x80; /* upper bit is set on all but the last byte */
  5204. }
  5205. /* now swap bytes y...x-1 */
  5206. z = x - 1;
  5207. while (y < z) {
  5208. mask = out[y];
  5209. out[y] = out[z];
  5210. out[z] = mask;
  5211. ++y;
  5212. --z;
  5213. }
  5214. }
  5215. else {
  5216. out[x++] = 0x00; /* zero value */
  5217. }
  5218. /* next word */
  5219. if (i < (int)inSz - 1) {
  5220. d = in[i + 1];
  5221. }
  5222. }
  5223. }
  5224. /* return length */
  5225. *outSz = len;
  5226. return 0;
  5227. }
  5228. #endif /* HAVE_OID_ENCODING */
  5229. #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) || \
  5230. defined(OPENSSL_ALL)
  5231. /* Encode dotted form of OID into byte array version.
  5232. *
  5233. * @param [in] in Byte array containing OID.
  5234. * @param [in] inSz Size of OID in bytes.
  5235. * @param [in] out Array to hold dotted form of OID.
  5236. * @param [in, out] outSz On in, number of elements in array.
  5237. * On out, count of numbers in dotted form.
  5238. * @return 0 on success
  5239. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5240. * @return BUFFER_E when dotted form buffer too small.
  5241. */
  5242. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5243. {
  5244. int x = 0, y = 0;
  5245. word32 t = 0;
  5246. /* check args */
  5247. if (in == NULL || outSz == NULL) {
  5248. return BAD_FUNC_ARG;
  5249. }
  5250. /* decode bytes */
  5251. while (inSz--) {
  5252. t = (t << 7) | (in[x] & 0x7F);
  5253. if (!(in[x] & 0x80)) {
  5254. if (y >= (int)*outSz) {
  5255. return BUFFER_E;
  5256. }
  5257. if (y == 0) {
  5258. out[0] = (word16)(t / 40);
  5259. out[1] = (word16)(t % 40);
  5260. y = 2;
  5261. }
  5262. else {
  5263. out[y++] = (word16)t;
  5264. }
  5265. t = 0; /* reset tmp */
  5266. }
  5267. x++;
  5268. }
  5269. /* return length */
  5270. *outSz = (word32)y;
  5271. return 0;
  5272. }
  5273. #endif /* HAVE_OID_DECODING || WOLFSSL_ASN_PRINT || OPENSSL_ALL */
  5274. /* Decode the header of a BER/DER encoded OBJECT ID.
  5275. *
  5276. * @param [in] input Buffer holding DER/BER encoded data.
  5277. * @param [in, out] inOutIdx On in, starting index of header.
  5278. * On out, end of parsed header.
  5279. * @param [out] len Number of bytes in the ASN.1 data.
  5280. * @param [in] maxIdx Length of data in buffer.
  5281. * @return 0 on success.
  5282. * @return BUFFER_E when there is not enough data to parse.
  5283. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5284. */
  5285. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5286. {
  5287. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5288. if (ret > 0) {
  5289. /* Only return 0 on success. */
  5290. ret = 0;
  5291. }
  5292. return ret;
  5293. }
  5294. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5295. *
  5296. * When output is NULL, calculate the header length only.
  5297. *
  5298. * @param [in] len Length of OBJECT ID data in bytes.
  5299. * @param [out] output Buffer to write into.
  5300. * @return Number of bytes added to the buffer.
  5301. */
  5302. int SetObjectId(int len, byte* output)
  5303. {
  5304. int idx = 0;
  5305. if (output) {
  5306. /* Write out tag. */
  5307. output[idx] = ASN_OBJECT_ID;
  5308. }
  5309. /* Skip tag. */
  5310. idx += ASN_TAG_SZ;
  5311. /* Encode length - passing NULL for output will not encode. */
  5312. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  5313. /* Return index after header. */
  5314. return idx;
  5315. }
  5316. #ifdef ASN_DUMP_OID
  5317. /* Dump the OID information.
  5318. *
  5319. * Decode the OID too if function available.
  5320. *
  5321. * @param [in] oidData OID data from buffer.
  5322. * @param [in] oidSz Size of OID data in buffer.
  5323. * @param [in] oid OID id.
  5324. * @param [in] oidType Type of OID.
  5325. * @return 0 on success.
  5326. * @return BUFFER_E when not enough bytes for proper decode.
  5327. * (HAVE_OID_DECODING)
  5328. */
  5329. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5330. word32 oidType)
  5331. {
  5332. int ret = 0;
  5333. word32 i;
  5334. /* support for dumping OID information */
  5335. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5336. /* Dump bytes in decimal. */
  5337. for (i = 0; i < oidSz; i++) {
  5338. printf("%d, ", oidData[i]);
  5339. }
  5340. printf("\n");
  5341. /* Dump bytes in hexadecimal. */
  5342. for (i = 0; i < oidSz; i++) {
  5343. printf("%02x, ", oidData[i]);
  5344. }
  5345. printf("\n");
  5346. #ifdef HAVE_OID_DECODING
  5347. {
  5348. word16 decOid[MAX_OID_SZ];
  5349. word32 decOidSz = sizeof(decOid);
  5350. /* Decode the OID into dotted form. */
  5351. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5352. if (ret == 0) {
  5353. printf(" Decoded (Sz %d): ", decOidSz);
  5354. for (i=0; i<decOidSz; i++) {
  5355. printf("%d.", decOid[i]);
  5356. }
  5357. printf("\n");
  5358. }
  5359. else {
  5360. printf("DecodeObjectId failed: %d\n", ret);
  5361. }
  5362. }
  5363. #endif /* HAVE_OID_DECODING */
  5364. return ret;
  5365. }
  5366. #endif /* ASN_DUMP_OID */
  5367. /* Get the OID data and verify it is of the type specified when compiled in.
  5368. *
  5369. * @param [in] input Buffer holding OID.
  5370. * @param [in, out] inOutIdx On in, starting index of OID.
  5371. * On out, end of parsed OID.
  5372. * @param [out] oid OID id.
  5373. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5374. * not compile in check.
  5375. * @param [in] length Length of OID data in buffer.
  5376. * @return 0 on success.
  5377. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5378. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5379. * HAVE_OID_DECODING)
  5380. */
  5381. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5382. word32 oidType, int length)
  5383. {
  5384. int ret = 0;
  5385. word32 idx = *inOutIdx;
  5386. #ifndef NO_VERIFY_OID
  5387. word32 actualOidSz;
  5388. const byte* actualOid;
  5389. const byte* checkOid = NULL;
  5390. word32 checkOidSz;
  5391. #endif /* NO_VERIFY_OID */
  5392. #ifdef HAVE_PQC
  5393. word32 found_collision = 0;
  5394. #endif
  5395. (void)oidType;
  5396. *oid = 0;
  5397. #ifndef NO_VERIFY_OID
  5398. /* Keep references to OID data and length for check. */
  5399. actualOid = &input[idx];
  5400. actualOidSz = (word32)length;
  5401. #endif /* NO_VERIFY_OID */
  5402. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS) && defined(HAVE_SPHINCS)
  5403. /* Since we are summing it up, there could be collisions...and indeed there
  5404. * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
  5405. *
  5406. * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
  5407. * 283 instead of 281; 282 is taken.
  5408. *
  5409. * These hacks will hopefully disappear when new standardized OIDs appear.
  5410. */
  5411. if (idx + (word32)sizeof(sigSphincsFast_Level3Oid) < (word32)length &&
  5412. XMEMCMP(&input[idx], sigSphincsFast_Level3Oid,
  5413. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5414. found_collision = SPHINCS_FAST_LEVEL3k;
  5415. }
  5416. #endif /* HAVE_PQC */
  5417. /* Sum it up for now. */
  5418. while (length--) {
  5419. /* odd HC08 compiler behavior here when input[idx++] */
  5420. *oid += (word32)input[idx];
  5421. idx++;
  5422. }
  5423. #ifdef HAVE_PQC
  5424. if (found_collision) {
  5425. *oid = found_collision;
  5426. }
  5427. #endif /* HAVE_PQC */
  5428. /* Return the index after the OID data. */
  5429. *inOutIdx = idx;
  5430. #ifndef NO_VERIFY_OID
  5431. /* 'Ignore' type means we don't care which OID it is. */
  5432. if (oidType != oidIgnoreType) {
  5433. /* Get the OID data for the id-type. */
  5434. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5435. #if defined(WOLFSSL_FPKI)
  5436. /* Handle OID sum collision of
  5437. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5438. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5439. */
  5440. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5441. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5442. (XMEMCMP(actualOid, blkAes256CbcOid,
  5443. sizeof(blkAes256CbcOid)) == 0)) {
  5444. checkOid = blkAes256CbcOid;
  5445. checkOidSz = sizeof(blkAes256CbcOid);
  5446. }
  5447. #endif /* HAVE_AES_CBC */
  5448. #endif /* WOLFSSL_FPKI */
  5449. #ifdef ASN_DUMP_OID
  5450. /* Dump out the data for debug. */
  5451. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5452. #endif
  5453. /* TODO: Want to fail when checkOid is NULL.
  5454. * Can't as too many situations where unknown OID is to be
  5455. * supported. Extra parameter for must not be NULL?
  5456. */
  5457. /* Check that the OID data matches what we found for the OID id. */
  5458. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5459. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5460. WOLFSSL_MSG("OID Check Failed");
  5461. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5462. ret = ASN_UNKNOWN_OID_E;
  5463. }
  5464. }
  5465. #endif /* NO_VERIFY_OID */
  5466. return ret;
  5467. }
  5468. #ifdef WOLFSSL_ASN_TEMPLATE
  5469. /* ASN.1 template for an OBJECT_ID. */
  5470. static const ASNItem objectIdASN[] = {
  5471. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5472. };
  5473. enum {
  5474. OBJECTIDASN_IDX_OID = 0
  5475. };
  5476. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5477. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5478. #endif
  5479. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5480. *
  5481. * @param [in] input Buffer holding BER encoded data.
  5482. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5483. * On out, start of ASN.1 item after OBJECT_ID.
  5484. * @param [out] oid Id of OID in OBJECT_ID data.
  5485. * @param [in] oidType Type of OID to expect.
  5486. * @param [in] maxIdx Maximum index of data in buffer.
  5487. * @return 0 on success.
  5488. * @return ASN_PARSE_E when encoding is invalid.
  5489. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5490. */
  5491. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5492. word32 oidType, word32 maxIdx)
  5493. {
  5494. #ifndef WOLFSSL_ASN_TEMPLATE
  5495. int ret, length;
  5496. WOLFSSL_ENTER("GetObjectId");
  5497. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5498. if (ret != 0)
  5499. return ret;
  5500. return GetOID(input, inOutIdx, oid, oidType, length);
  5501. #else
  5502. ASNGetData dataASN[objectIdASN_Length];
  5503. int ret;
  5504. WOLFSSL_ENTER("GetObjectId");
  5505. /* Clear dynamic data and set OID type expected. */
  5506. XMEMSET(dataASN, 0, sizeof(dataASN));
  5507. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5508. /* Decode OBJECT_ID. */
  5509. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5510. inOutIdx, maxIdx);
  5511. if (ret == 0) {
  5512. /* Return the id/sum. */
  5513. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5514. }
  5515. return ret;
  5516. #endif /* WOLFSSL_ASN_TEMPLATE */
  5517. }
  5518. #ifndef WOLFSSL_ASN_TEMPLATE
  5519. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5520. {
  5521. word32 idx = *inOutIdx;
  5522. int length;
  5523. int ret;
  5524. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5525. if (ret != 0)
  5526. return ret;
  5527. idx += (word32)length;
  5528. *inOutIdx = idx;
  5529. return 0;
  5530. }
  5531. #endif
  5532. #ifdef WOLFSSL_ASN_TEMPLATE
  5533. /* ASN.1 template for an algorithm identifier. */
  5534. static const ASNItem algoIdASN[] = {
  5535. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5536. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5537. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5538. };
  5539. enum {
  5540. ALGOIDASN_IDX_SEQ = 0,
  5541. ALGOIDASN_IDX_OID,
  5542. ALGOIDASN_IDX_NULL
  5543. };
  5544. /* Number of items in ASN.1 template for an algorithm identifier. */
  5545. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5546. #endif
  5547. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5548. *
  5549. * NULL tag is skipped if present.
  5550. *
  5551. * @param [in] input Buffer holding BER encoded data.
  5552. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5553. * On out, start of ASN.1 item after algorithm id.
  5554. * @param [out] oid Id of OID in algorithm identifier data.
  5555. * @param [in] oidType Type of OID to expect.
  5556. * @param [in] maxIdx Maximum index of data in buffer.
  5557. * @return 0 on success.
  5558. * @return ASN_PARSE_E when encoding is invalid.
  5559. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5560. */
  5561. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5562. word32 oidType, word32 maxIdx)
  5563. {
  5564. #ifndef WOLFSSL_ASN_TEMPLATE
  5565. int length;
  5566. word32 idx = *inOutIdx;
  5567. int ret;
  5568. *oid = 0;
  5569. WOLFSSL_ENTER("GetAlgoId");
  5570. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5571. return ASN_PARSE_E;
  5572. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5573. return ASN_OBJECT_ID_E;
  5574. /* could have NULL tag and 0 terminator, but may not */
  5575. if (idx < maxIdx) {
  5576. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5577. byte tag;
  5578. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5579. if (tag == ASN_TAG_NULL) {
  5580. ret = GetASNNull(input, &idx, maxIdx);
  5581. if (ret != 0)
  5582. return ret;
  5583. }
  5584. }
  5585. }
  5586. *inOutIdx = idx;
  5587. return 0;
  5588. #else
  5589. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5590. int ret = 0;
  5591. WOLFSSL_ENTER("GetAlgoId");
  5592. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5593. if (ret == 0) {
  5594. /* Set OID type expected. */
  5595. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5596. /* Decode the algorithm identifier. */
  5597. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5598. inOutIdx, maxIdx);
  5599. }
  5600. if (ret == 0) {
  5601. /* Return the OID id/sum. */
  5602. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5603. }
  5604. FREE_ASNGETDATA(dataASN, NULL);
  5605. return ret;
  5606. #endif /* WOLFSSL_ASN_TEMPLATE */
  5607. }
  5608. #ifndef NO_RSA
  5609. #ifdef WC_RSA_PSS
  5610. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5611. /* Convert a hash OID to a hash type.
  5612. *
  5613. * @param [in] oid Hash OID.
  5614. * @param [out] type Hash type.
  5615. * @return 0 on success.
  5616. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5617. */
  5618. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5619. {
  5620. int ret = 0;
  5621. switch (oid) {
  5622. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5623. #ifdef WOLFSSL_SHA224
  5624. case SHA224h:
  5625. *type = WC_HASH_TYPE_SHA224;
  5626. break;
  5627. #endif
  5628. #ifndef NO_SHA256
  5629. case SHA256h:
  5630. *type = WC_HASH_TYPE_SHA256;
  5631. break;
  5632. #endif
  5633. #ifdef WOLFSSL_SHA384
  5634. case SHA384h:
  5635. *type = WC_HASH_TYPE_SHA384;
  5636. break;
  5637. #endif
  5638. #ifdef WOLFSSL_SHA512
  5639. case SHA512h:
  5640. *type = WC_HASH_TYPE_SHA512;
  5641. break;
  5642. /* TODO: SHA512_224h */
  5643. /* TODO: SHA512_256h */
  5644. #endif
  5645. default:
  5646. ret = ASN_PARSE_E;
  5647. break;
  5648. }
  5649. return ret;
  5650. }
  5651. /* Convert a hash OID to a MGF1 type.
  5652. *
  5653. * @param [in] oid Hash OID.
  5654. * @param [out] mgf MGF type.
  5655. * @return 0 on success.
  5656. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5657. */
  5658. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5659. {
  5660. int ret = 0;
  5661. switch (oid) {
  5662. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5663. #ifdef WOLFSSL_SHA224
  5664. case SHA224h:
  5665. *mgf = WC_MGF1SHA224;
  5666. break;
  5667. #endif
  5668. #ifndef NO_SHA256
  5669. case SHA256h:
  5670. *mgf = WC_MGF1SHA256;
  5671. break;
  5672. #endif
  5673. #ifdef WOLFSSL_SHA384
  5674. case SHA384h:
  5675. *mgf = WC_MGF1SHA384;
  5676. break;
  5677. #endif
  5678. #ifdef WOLFSSL_SHA512
  5679. case SHA512h:
  5680. *mgf = WC_MGF1SHA512;
  5681. break;
  5682. /* TODO: SHA512_224h */
  5683. /* TODO: SHA512_256h */
  5684. #endif
  5685. default:
  5686. ret = ASN_PARSE_E;
  5687. break;
  5688. }
  5689. return ret;
  5690. }
  5691. #ifndef NO_CERTS
  5692. /* Convert a hash OID to a fake signature OID.
  5693. *
  5694. * @param [in] oid Hash OID.
  5695. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5696. * @return 0 on success.
  5697. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5698. */
  5699. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5700. {
  5701. int ret = 0;
  5702. switch (oid) {
  5703. #ifndef NO_SHA
  5704. case WC_HASH_TYPE_SHA:
  5705. *sigOid = CTC_SHAwRSA;
  5706. break;
  5707. #endif
  5708. #ifdef WOLFSSL_SHA224
  5709. case WC_HASH_TYPE_SHA224:
  5710. *sigOid = CTC_SHA224wRSA;
  5711. break;
  5712. #endif
  5713. #ifndef NO_SHA256
  5714. case WC_HASH_TYPE_SHA256:
  5715. *sigOid = CTC_SHA256wRSA;
  5716. break;
  5717. #endif
  5718. #ifdef WOLFSSL_SHA384
  5719. case WC_HASH_TYPE_SHA384:
  5720. *sigOid = CTC_SHA384wRSA;
  5721. break;
  5722. #endif
  5723. #ifdef WOLFSSL_SHA512
  5724. case WC_HASH_TYPE_SHA512:
  5725. *sigOid = CTC_SHA512wRSA;
  5726. break;
  5727. #endif
  5728. /* TODO: SHA512_224h */
  5729. /* TODO: SHA512_256h */
  5730. /* Not supported by HashForSignature() */
  5731. default:
  5732. ret = ASN_PARSE_E;
  5733. break;
  5734. }
  5735. return ret;
  5736. }
  5737. #endif
  5738. #ifdef WOLFSSL_ASN_TEMPLATE
  5739. /* ASN tag for hashAlgorigthm. */
  5740. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5741. /* ASN tag for maskGenAlgorithm. */
  5742. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5743. /* ASN tag for saltLength. */
  5744. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5745. /* ASN tag for trailerField. */
  5746. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5747. /* ASN.1 template for RSA PSS parameters. */
  5748. static const ASNItem rsaPssParamsASN[] = {
  5749. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5750. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5751. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5752. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5753. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5754. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5755. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5756. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5757. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5758. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5759. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5760. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5761. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5762. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5763. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5764. };
  5765. enum {
  5766. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5767. RSAPSSPARAMSASN_IDX_HASH,
  5768. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5769. RSAPSSPARAMSASN_IDX_HASHOID,
  5770. RSAPSSPARAMSASN_IDX_HASHNULL,
  5771. RSAPSSPARAMSASN_IDX_MGF,
  5772. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5773. RSAPSSPARAMSASN_IDX_MGFOID,
  5774. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5775. RSAPSSPARAMSASN_IDX_MGFHOID,
  5776. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5777. RSAPSSPARAMSASN_IDX_SALTLEN,
  5778. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5779. RSAPSSPARAMSASN_IDX_TRAILER,
  5780. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5781. };
  5782. /* Number of items in ASN.1 template for an algorithm identifier. */
  5783. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5784. #else
  5785. /* ASN tag for hashAlgorigthm. */
  5786. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5787. /* ASN tag for maskGenAlgorithm. */
  5788. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5789. /* ASN tag for saltLength. */
  5790. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5791. /* ASN tag for trailerField. */
  5792. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5793. #endif
  5794. /* Decode the RSA PSS parameters.
  5795. *
  5796. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5797. * @param [in] sz Size of data in buffer in bytes.
  5798. * @param [out] hash Hash algorithm to use on message.
  5799. * @param [out] mgf MGF algorithm to use with PSS padding.
  5800. * @param [out] saltLen Length of salt in PSS padding.
  5801. * @return BAD_FUNC_ARG when the params is NULL.
  5802. * @return ASN_PARSE_E when the decoding fails.
  5803. * @return 0 on success.
  5804. */
  5805. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5806. enum wc_HashType* hash, int* mgf, int* saltLen)
  5807. {
  5808. #ifndef WOLFSSL_ASN_TEMPLATE
  5809. int ret = 0;
  5810. word32 idx = 0;
  5811. int len = 0;
  5812. word32 oid = 0;
  5813. byte tag;
  5814. int length;
  5815. if (params == NULL) {
  5816. ret = BAD_FUNC_ARG;
  5817. }
  5818. if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
  5819. ret = ASN_PARSE_E;
  5820. }
  5821. if (ret == 0) {
  5822. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5823. /* Hash algorithm to use on message. */
  5824. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5825. ret = ASN_PARSE_E;
  5826. }
  5827. if (ret == 0) {
  5828. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5829. ret = ASN_PARSE_E;
  5830. }
  5831. }
  5832. if (ret == 0) {
  5833. ret = RsaPssHashOidToType(oid, hash);
  5834. }
  5835. }
  5836. else {
  5837. /* Default hash algorithm. */
  5838. *hash = WC_HASH_TYPE_SHA;
  5839. }
  5840. }
  5841. if (ret == 0) {
  5842. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5843. /* MGF and hash algorithm to use with padding. */
  5844. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5845. ret = ASN_PARSE_E;
  5846. }
  5847. if (ret == 0) {
  5848. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5849. ret = ASN_PARSE_E;
  5850. }
  5851. }
  5852. if ((ret == 0) && (oid != MGF1_OID)) {
  5853. ret = ASN_PARSE_E;
  5854. }
  5855. if (ret == 0) {
  5856. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5857. if (ret == 0) {
  5858. ret = RsaPssHashOidToMgf1(oid, mgf);
  5859. }
  5860. }
  5861. }
  5862. else {
  5863. /* Default MGF/Hash algorithm. */
  5864. *mgf = WC_MGF1SHA1;
  5865. }
  5866. }
  5867. if (ret == 0) {
  5868. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5869. /* Salt length to use with padding. */
  5870. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5871. ret = ASN_PARSE_E;
  5872. }
  5873. if (ret == 0) {
  5874. ret = GetInteger16Bit(params, &idx, sz);
  5875. if (ret >= 0) {
  5876. *saltLen = ret;
  5877. ret = 0;
  5878. }
  5879. }
  5880. }
  5881. else {
  5882. /* Default salt length. */
  5883. *saltLen = 20;
  5884. }
  5885. }
  5886. if (ret == 0) {
  5887. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5888. /* Unused - trialerField. */
  5889. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5890. ret = ASN_PARSE_E;
  5891. }
  5892. if (ret == 0) {
  5893. ret = GetInteger16Bit(params, &idx, sz);
  5894. if (ret > 0) {
  5895. ret = 0;
  5896. }
  5897. }
  5898. }
  5899. }
  5900. if ((ret == 0) && (idx != sz)) {
  5901. ret = ASN_PARSE_E;
  5902. }
  5903. return ret;
  5904. #else
  5905. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5906. int ret = 0;
  5907. word16 sLen = 20;
  5908. if (params == NULL) {
  5909. ret = BAD_FUNC_ARG;
  5910. }
  5911. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5912. if (ret == 0) {
  5913. word32 inOutIdx = 0;
  5914. /* Default values. */
  5915. *hash = WC_HASH_TYPE_SHA;
  5916. *mgf = WC_MGF1SHA1;
  5917. /* Set OID type expected. */
  5918. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5919. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5920. /* Place the salt length into 16-bit var sLen. */
  5921. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5922. /* Decode the algorithm identifier. */
  5923. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5924. params, &inOutIdx, sz);
  5925. }
  5926. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5927. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5928. ret = RsaPssHashOidToType(oid, hash);
  5929. }
  5930. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5931. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5932. ret = RsaPssHashOidToMgf1(oid, mgf);
  5933. }
  5934. if (ret == 0) {
  5935. *saltLen = sLen;
  5936. }
  5937. FREE_ASNGETDATA(dataASN, NULL);
  5938. return ret;
  5939. #endif /* WOLFSSL_ASN_TEMPLATE */
  5940. }
  5941. #endif /* WC_RSA_PSS */
  5942. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5943. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5944. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5945. /* Byte offset of numbers in RSA key. */
  5946. size_t rsaIntOffset[] = {
  5947. OFFSETOF(RsaKey, n),
  5948. OFFSETOF(RsaKey, e),
  5949. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5950. OFFSETOF(RsaKey, d),
  5951. OFFSETOF(RsaKey, p),
  5952. OFFSETOF(RsaKey, q),
  5953. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5954. OFFSETOF(RsaKey, dP),
  5955. OFFSETOF(RsaKey, dQ),
  5956. OFFSETOF(RsaKey, u)
  5957. #endif
  5958. #endif
  5959. };
  5960. /* Get a number from the RSA key based on an index.
  5961. *
  5962. * Order: { n, e, d, p, q, dP, dQ, u }
  5963. *
  5964. * Caller must ensure index is not invalid!
  5965. *
  5966. * @param [in] key RSA key object.
  5967. * @param [in] idx Index of number.
  5968. * @return A pointer to an mp_int when valid index.
  5969. * @return NULL when invalid index.
  5970. */
  5971. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5972. {
  5973. /* Cast key to byte array to and use offset to get to mp_int field. */
  5974. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5975. }
  5976. #endif
  5977. #ifdef WOLFSSL_ASN_TEMPLATE
  5978. /* ASN.1 template for an RSA private key.
  5979. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5980. */
  5981. static const ASNItem rsaKeyASN[] = {
  5982. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5983. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5984. /* Integers need to be in this specific order
  5985. * as asn code depends on this. */
  5986. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5987. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5988. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5989. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5990. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5991. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5992. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5993. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5994. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5995. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5996. * v2 - multiprime */
  5997. #endif
  5998. };
  5999. enum {
  6000. RSAKEYASN_IDX_SEQ = 0,
  6001. RSAKEYASN_IDX_VER,
  6002. /* Integers need to be in this specific order
  6003. * as asn code depends on this. */
  6004. RSAKEYASN_IDX_N,
  6005. RSAKEYASN_IDX_E,
  6006. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  6007. RSAKEYASN_IDX_D,
  6008. RSAKEYASN_IDX_P,
  6009. RSAKEYASN_IDX_Q,
  6010. RSAKEYASN_IDX_DP,
  6011. RSAKEYASN_IDX_DQ,
  6012. RSAKEYASN_IDX_U,
  6013. #endif
  6014. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  6015. };
  6016. /* Number of items in ASN.1 template for an RSA private key. */
  6017. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  6018. #endif
  6019. /* Decode RSA private key.
  6020. *
  6021. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6022. *
  6023. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6024. * being extracted.
  6025. *
  6026. * @param [in] input Buffer holding BER encoded data.
  6027. * @param [in, out] inOutIdx On in, start of RSA private key.
  6028. * On out, start of ASN.1 item after RSA private key.
  6029. * @param [in, out] key RSA key object. May be NULL.
  6030. * @param [out] keySz Size of key in bytes. May be NULL.
  6031. * @param [in] inSz Number of bytes in buffer.
  6032. * @return 0 on success.
  6033. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6034. * @return BAD_FUNC_ARG when key and keySz are NULL.
  6035. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6036. * is invalid.
  6037. * @return BUFFER_E when data in buffer is too small.
  6038. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6039. * non-zero length.
  6040. * @return MP_INIT_E when the unable to initialize an mp_int.
  6041. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6042. */
  6043. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  6044. RsaKey* key, int* keySz, word32 inSz)
  6045. {
  6046. #ifndef WOLFSSL_ASN_TEMPLATE
  6047. int version, length;
  6048. word32 algId = 0;
  6049. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  6050. return BAD_FUNC_ARG;
  6051. }
  6052. /* if has pkcs8 header skip it */
  6053. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  6054. /* ignore error, did not have pkcs8 header */
  6055. }
  6056. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  6057. return ASN_PARSE_E;
  6058. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  6059. return ASN_PARSE_E;
  6060. if (key == NULL) {
  6061. int i;
  6062. /* Modulus */
  6063. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  6064. return ASN_PARSE_E;
  6065. }
  6066. *inOutIdx += (word32)*keySz;
  6067. for (i = 1; i < RSA_INTS; i++) {
  6068. if (SkipInt(input, inOutIdx, inSz) < 0) {
  6069. return ASN_RSA_KEY_E;
  6070. }
  6071. }
  6072. }
  6073. else {
  6074. key->type = RSA_PRIVATE;
  6075. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6076. mp_memzero_add("Decode RSA key d", &key->d);
  6077. mp_memzero_add("Decode RSA key p", &key->p);
  6078. mp_memzero_add("Decode RSA key q", &key->q);
  6079. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  6080. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6081. mp_memzero_add("Decode RSA key dP", &key->dP);
  6082. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  6083. mp_memzero_add("Decode RSA key u", &key->u);
  6084. #endif
  6085. #endif
  6086. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  6087. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  6088. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  6089. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  6090. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  6091. GetInt(&key->q, input, inOutIdx, inSz) < 0
  6092. #else
  6093. SkipInt(input, inOutIdx, inSz) < 0 ||
  6094. SkipInt(input, inOutIdx, inSz) < 0 ||
  6095. SkipInt(input, inOutIdx, inSz) < 0
  6096. #endif
  6097. ) {
  6098. return ASN_RSA_KEY_E;
  6099. }
  6100. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  6101. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6102. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  6103. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  6104. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  6105. #else
  6106. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  6107. SkipInt(input, inOutIdx, inSz) < 0 ||
  6108. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  6109. #endif
  6110. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  6111. if (wc_InitRsaHw(key) != 0) {
  6112. return BAD_STATE_E;
  6113. }
  6114. #endif
  6115. }
  6116. return 0;
  6117. #else
  6118. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  6119. int ret = 0;
  6120. byte version = (byte)-1;
  6121. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6122. word32 algId = 0;
  6123. #endif
  6124. void* heap = NULL;
  6125. /* Check validity of parameters. */
  6126. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  6127. (keySz == NULL))) {
  6128. ret = BAD_FUNC_ARG;
  6129. }
  6130. if ((ret == 0) && (key != NULL)) {
  6131. heap = key->heap;
  6132. }
  6133. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6134. if (ret == 0) {
  6135. /* if has pkcs8 header skip it */
  6136. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  6137. /* ignore error, did not have pkcs8 header */
  6138. }
  6139. }
  6140. #endif
  6141. (void)heap;
  6142. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  6143. if (ret == 0) {
  6144. /* Register variable to hold version field. */
  6145. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  6146. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  6147. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6148. #define RSA_ASN_INTS RSA_PUB_INTS
  6149. /* Not extracting all data from BER encoding. */
  6150. #define RSA_ASN_COMPLETE 0
  6151. #else
  6152. #define RSA_ASN_INTS RSA_INTS
  6153. /* Extracting all data from BER encoding. */
  6154. #define RSA_ASN_COMPLETE 1
  6155. #endif
  6156. if (key != NULL) {
  6157. int i;
  6158. /* Extract all public fields. */
  6159. for (i = 0; i < RSA_ASN_INTS; i++) {
  6160. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  6161. GetRsaInt(key, i));
  6162. }
  6163. }
  6164. /* Parse BER encoding for RSA private key. */
  6165. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  6166. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  6167. }
  6168. /* Check version: 0 - two prime, 1 - multi-prime
  6169. * Multi-prime has optional sequence after coefficient for extra primes.
  6170. * If extra primes, parsing will fail as not all the buffer was used.
  6171. */
  6172. if ((ret == 0) && (version > PKCS1v1)) {
  6173. ret = ASN_PARSE_E;
  6174. }
  6175. if ((ret == 0) && (key != NULL)) {
  6176. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6177. /* RSA key object has all private key values. */
  6178. key->type = RSA_PRIVATE;
  6179. #else
  6180. /* RSA key object has all public key values. */
  6181. key->type = RSA_PUBLIC;
  6182. #endif
  6183. #ifdef WOLFSSL_XILINX_CRYPT
  6184. if (wc_InitRsaHw(key) != 0)
  6185. ret = BAD_STATE_E;
  6186. #endif
  6187. }
  6188. else if (ret == 0) {
  6189. /* Not filling in key but do want key size. */
  6190. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6191. /* Check whether first byte of data is 0x00 and drop it. */
  6192. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6193. (*keySz)--;
  6194. }
  6195. }
  6196. FREE_ASNGETDATA(dataASN, heap);
  6197. return ret;
  6198. #endif /* WOLFSSL_ASN_TEMPLATE */
  6199. }
  6200. /* Decode RSA private key.
  6201. *
  6202. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6203. *
  6204. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6205. * being extracted.
  6206. *
  6207. * @param [in] input Buffer holding BER encoded data.
  6208. * @param [in, out] inOutIdx On in, start of RSA private key.
  6209. * On out, start of ASN.1 item after RSA private key.
  6210. * @param [in, out] key RSA key object.
  6211. * @param [in] inSz Number of bytes in buffer.
  6212. * @return 0 on success.
  6213. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6214. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6215. * is invalid.
  6216. * @return BUFFER_E when data in buffer is too small.
  6217. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6218. * non-zero length.
  6219. * @return MP_INIT_E when the unable to initialize an mp_int.
  6220. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6221. */
  6222. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6223. word32 inSz)
  6224. {
  6225. if (key == NULL) {
  6226. return BAD_FUNC_ARG;
  6227. }
  6228. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6229. }
  6230. /* Valdidate RSA private key ASN.1 encoding.
  6231. *
  6232. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6233. *
  6234. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6235. * being extracted.
  6236. *
  6237. * @param [in] input Buffer holding BER encoded data.
  6238. * @param [in, out] inOutIdx On in, start of RSA private key.
  6239. * On out, start of ASN.1 item after RSA private key.
  6240. * @param [in] inSz Number of bytes in buffer.
  6241. * @return 0 on success.
  6242. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6243. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6244. * is invalid.
  6245. * @return BUFFER_E when data in buffer is too small.
  6246. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6247. * non-zero length.
  6248. * @return MP_INIT_E when the unable to initialize an mp_int.
  6249. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6250. */
  6251. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6252. word32 inSz)
  6253. {
  6254. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6255. }
  6256. #endif /* NO_RSA */
  6257. #ifdef WOLFSSL_ASN_TEMPLATE
  6258. /* ASN.1 template for a PKCS #8 key.
  6259. * Ignoring optional attributes and public key.
  6260. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6261. */
  6262. static const ASNItem pkcs8KeyASN[] = {
  6263. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6264. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6265. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6266. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6267. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6268. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6269. #ifdef WC_RSA_PSS
  6270. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6271. #endif
  6272. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6273. /* attributes [0] Attributes OPTIONAL */
  6274. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6275. };
  6276. enum {
  6277. PKCS8KEYASN_IDX_SEQ = 0,
  6278. PKCS8KEYASN_IDX_VER,
  6279. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6280. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6281. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6282. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6283. #ifdef WC_RSA_PSS
  6284. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6285. #endif
  6286. PKCS8KEYASN_IDX_PKEY_DATA,
  6287. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6288. };
  6289. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6290. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6291. #endif
  6292. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6293. *
  6294. * @param [in] input Buffer holding BER data.
  6295. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6296. * On out, start of encoded key.
  6297. * @param [in] sz Size of data in buffer.
  6298. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6299. * @return Length of key data on success.
  6300. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6301. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6302. * is invalid.
  6303. * @return BUFFER_E when data in buffer is too small.
  6304. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6305. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6306. * non-zero length.
  6307. */
  6308. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6309. word32* algId)
  6310. {
  6311. #ifndef WOLFSSL_ASN_TEMPLATE
  6312. word32 idx;
  6313. int version, length;
  6314. int ret;
  6315. byte tag;
  6316. if (input == NULL || inOutIdx == NULL)
  6317. return BAD_FUNC_ARG;
  6318. idx = *inOutIdx;
  6319. if (GetSequence(input, &idx, &length, sz) < 0)
  6320. return ASN_PARSE_E;
  6321. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6322. return ASN_PARSE_E;
  6323. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6324. return ASN_PARSE_E;
  6325. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6326. return ASN_PARSE_E;
  6327. idx = idx - 1; /* reset idx after finding tag */
  6328. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6329. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6330. word32 seqIdx = idx;
  6331. int seqLen;
  6332. /* Not set when -1. */
  6333. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6334. int mgf = -1;
  6335. int saltLen = 0;
  6336. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6337. return ASN_PARSE_E;
  6338. }
  6339. /* Get the private key parameters. */
  6340. ret = DecodeRsaPssParams(input + seqIdx,
  6341. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6342. if (ret != 0) {
  6343. return ASN_PARSE_E;
  6344. }
  6345. /* TODO: store parameters so that usage can be checked. */
  6346. idx += seqLen;
  6347. }
  6348. #endif /* WC_RSA_PSS && !NO_RSA */
  6349. if (tag == ASN_OBJECT_ID) {
  6350. if (SkipObjectId(input, &idx, sz) < 0)
  6351. return ASN_PARSE_E;
  6352. }
  6353. ret = GetOctetString(input, &idx, &length, sz);
  6354. if (ret < 0) {
  6355. if (ret == BUFFER_E)
  6356. return ASN_PARSE_E;
  6357. /* Some private keys don't expect an octet string */
  6358. WOLFSSL_MSG("Couldn't find Octet string");
  6359. }
  6360. *inOutIdx = idx;
  6361. return length;
  6362. #else
  6363. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6364. int ret = 0;
  6365. word32 oid = 9;
  6366. byte version = 0;
  6367. word32 idx;
  6368. /* Check validity of parameters. */
  6369. if (input == NULL || inOutIdx == NULL) {
  6370. return BAD_FUNC_ARG;
  6371. }
  6372. idx = *inOutIdx;
  6373. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6374. if (ret == 0) {
  6375. /* Get version, check key type and curve type. */
  6376. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6377. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6378. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6379. /* Parse data. */
  6380. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6381. &idx, sz);
  6382. }
  6383. if (ret == 0) {
  6384. /* Key type OID. */
  6385. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6386. /* Version 1 includes an optional public key.
  6387. * If public key is included then the parsing will fail as it did not
  6388. * use all the data.
  6389. */
  6390. if (version > PKCS8v1) {
  6391. ret = ASN_PARSE_E;
  6392. }
  6393. }
  6394. if (ret == 0) {
  6395. switch (oid) {
  6396. #ifndef NO_RSA
  6397. case RSAk:
  6398. /* Must have NULL item but not OBJECT_ID item. */
  6399. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6400. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6401. ret = ASN_PARSE_E;
  6402. }
  6403. break;
  6404. #ifdef WC_RSA_PSS
  6405. case RSAPSSk:
  6406. /* Must not have NULL item. */
  6407. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6408. ret = ASN_PARSE_E;
  6409. }
  6410. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6411. enum wc_HashType hash;
  6412. int mgf;
  6413. int saltLen;
  6414. const byte* params = GetASNItem_Addr(
  6415. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6416. word32 paramsSz = GetASNItem_Length(
  6417. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6418. /* Validate the private key parameters. */
  6419. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6420. &saltLen);
  6421. if (ret != 0) {
  6422. return ASN_PARSE_E;
  6423. }
  6424. /* TODO: store parameters so that usage can be checked. */
  6425. }
  6426. break;
  6427. #endif
  6428. #endif
  6429. #ifdef HAVE_ECC
  6430. case ECDSAk:
  6431. /* Must not have NULL item. */
  6432. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6433. ret = ASN_PARSE_E;
  6434. }
  6435. break;
  6436. #endif
  6437. #ifdef HAVE_ED25519
  6438. case ED25519k:
  6439. /* Neither NULL item nor OBJECT_ID item allowed. */
  6440. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6441. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6442. ret = ASN_PARSE_E;
  6443. }
  6444. break;
  6445. #endif
  6446. #ifdef HAVE_CURVE25519
  6447. case X25519k:
  6448. /* Neither NULL item nor OBJECT_ID item allowed. */
  6449. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6450. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6451. ret = ASN_PARSE_E;
  6452. }
  6453. break;
  6454. #endif
  6455. #ifdef HAVE_ED448
  6456. case ED448k:
  6457. /* Neither NULL item nor OBJECT_ID item allowed. */
  6458. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6459. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6460. ret = ASN_PARSE_E;
  6461. }
  6462. break;
  6463. #endif
  6464. #ifdef HAVE_CURVE448
  6465. case X448k:
  6466. /* Neither NULL item nor OBJECT_ID item allowed. */
  6467. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6468. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6469. ret = ASN_PARSE_E;
  6470. }
  6471. break;
  6472. #endif
  6473. /* DSAk not supported. */
  6474. /* Falcon, Dilithium and Sphincs not supported. */
  6475. /* Ignore OID lookup failures. */
  6476. default:
  6477. break;
  6478. }
  6479. }
  6480. if (ret == 0) {
  6481. /* Return algorithm id of internal key. */
  6482. *algId = oid;
  6483. /* Return index to start of internal key. */
  6484. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6485. /* Return value is length of internal key. */
  6486. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6487. }
  6488. FREE_ASNGETDATA(dataASN, NULL);
  6489. return ret;
  6490. #endif
  6491. }
  6492. /* TODO: test case */
  6493. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6494. {
  6495. word32 oid;
  6496. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6497. }
  6498. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6499. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6500. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6501. {
  6502. word32 inOutIdx = 0;
  6503. int length;
  6504. if (input == NULL)
  6505. return BAD_FUNC_ARG;
  6506. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6507. if (length < 0)
  6508. return length;
  6509. if ((word32)length + inOutIdx > sz)
  6510. return BUFFER_E;
  6511. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6512. return length;
  6513. }
  6514. int ToTraditional(byte* input, word32 sz)
  6515. {
  6516. word32 oid;
  6517. return ToTraditional_ex(input, sz, &oid);
  6518. }
  6519. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6520. #if defined(HAVE_PKCS8)
  6521. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6522. {
  6523. int length;
  6524. word32 algId;
  6525. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6526. return BAD_FUNC_ARG;
  6527. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6528. return length;
  6529. }
  6530. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6531. int algoID, const byte* curveOID, word32 oidSz)
  6532. {
  6533. #ifndef WOLFSSL_ASN_TEMPLATE
  6534. word32 keyIdx = 0;
  6535. word32 tmpSz = 0;
  6536. word32 sz;
  6537. word32 tmpAlgId = 0;
  6538. /* If out is NULL then return the max size needed
  6539. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6540. if (out == NULL && outSz != NULL) {
  6541. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6542. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6543. if (curveOID != NULL)
  6544. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6545. WOLFSSL_MSG("Checking size of PKCS8");
  6546. return LENGTH_ONLY_E;
  6547. }
  6548. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6549. if (key == NULL || out == NULL || outSz == NULL) {
  6550. return BAD_FUNC_ARG;
  6551. }
  6552. /* check the buffer has enough room for largest possible size */
  6553. if (curveOID != NULL) {
  6554. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6555. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6556. return BUFFER_E;
  6557. }
  6558. else {
  6559. oidSz = 0; /* with no curveOID oid size must be 0 */
  6560. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6561. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6562. return BUFFER_E;
  6563. }
  6564. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6565. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6566. (void)tmpAlgId;
  6567. return ASN_PARSE_E;
  6568. }
  6569. /* PrivateKeyInfo ::= SEQUENCE */
  6570. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6571. /* version Version
  6572. * no header information just INTEGER */
  6573. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6574. tmpSz += sz; keyIdx += sz;
  6575. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6576. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6577. if (curveOID != NULL && oidSz > 0) {
  6578. byte buf[MAX_LENGTH_SZ];
  6579. sz = SetLength(oidSz, buf);
  6580. sz += 1; /* plus one for ASN object id */
  6581. }
  6582. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6583. tmpSz += sz; keyIdx += sz;
  6584. /* privateKey PrivateKey *
  6585. * pkcs8 ecc uses slightly different format. Places curve oid in
  6586. * buffer */
  6587. if (curveOID != NULL && oidSz > 0) {
  6588. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6589. keyIdx += sz; tmpSz += sz;
  6590. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6591. keyIdx += oidSz; tmpSz += oidSz;
  6592. }
  6593. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6594. keyIdx += sz; tmpSz += sz;
  6595. XMEMCPY(out + keyIdx, key, keySz);
  6596. tmpSz += keySz;
  6597. /* attributes optional
  6598. * No attributes currently added */
  6599. /* rewind and add sequence */
  6600. sz = SetSequence(tmpSz, out);
  6601. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6602. *outSz = tmpSz + sz;
  6603. return (int)(tmpSz + sz);
  6604. #else
  6605. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6606. int sz;
  6607. int ret = 0;
  6608. word32 keyIdx = 0;
  6609. word32 tmpAlgId = 0;
  6610. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6611. /* Check validity of parameters. */
  6612. if (out == NULL && outSz != NULL) {
  6613. }
  6614. else if (key == NULL || out == NULL || outSz == NULL) {
  6615. ret = BAD_FUNC_ARG;
  6616. }
  6617. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6618. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6619. (void)tmpAlgId;
  6620. ret = ASN_PARSE_E;
  6621. }
  6622. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6623. if (ret == 0) {
  6624. /* Only support default PKCS #8 format - v0. */
  6625. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6626. /* Set key OID that corresponds to key data. */
  6627. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6628. oidKeyType);
  6629. if (curveOID != NULL && oidSz > 0) {
  6630. /* ECC key and curveOID set to write. */
  6631. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE],
  6632. curveOID, oidSz);
  6633. }
  6634. else {
  6635. /* EC curve OID to encode. */
  6636. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6637. }
  6638. /* Only RSA keys have NULL tagged item after OID. */
  6639. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6640. #ifdef WC_RSA_PSS
  6641. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6642. #endif
  6643. /* Set key data to encode. */
  6644. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6645. /* Get the size of the DER encoding. */
  6646. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6647. }
  6648. if (ret == 0) {
  6649. /* Always return the calculated size. */
  6650. *outSz = (word32)sz;
  6651. }
  6652. /* Check for buffer to encoded into. */
  6653. if ((ret == 0) && (out == NULL)) {
  6654. WOLFSSL_MSG("Checking size of PKCS8");
  6655. ret = LENGTH_ONLY_E;
  6656. }
  6657. if (ret == 0) {
  6658. /* Encode PKCS #8 key into buffer. */
  6659. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6660. ret = sz;
  6661. }
  6662. FREE_ASNSETDATA(dataASN, NULL);
  6663. return ret;
  6664. #endif /* WOLFSSL_ASN_TEMPLATE */
  6665. }
  6666. #endif /* HAVE_PKCS8 */
  6667. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6668. /* check that the private key is a pair for the public key
  6669. * return 1 (true) on match
  6670. * return 0 or negative value on failure/error
  6671. *
  6672. * privKey : buffer holding DER format private key
  6673. * privKeySz : size of private key buffer
  6674. * pubKey : buffer holding DER format public key
  6675. * pubKeySz : size of public key buffer
  6676. * ks : type of key */
  6677. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6678. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6679. {
  6680. int ret;
  6681. (void)privKeySz;
  6682. (void)pubKeySz;
  6683. (void)ks;
  6684. if (privKey == NULL || pubKey == NULL) {
  6685. return BAD_FUNC_ARG;
  6686. }
  6687. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6688. /* test if RSA key */
  6689. if (ks == RSAk
  6690. #ifdef WC_RSA_PSS
  6691. || ks == RSAPSSk
  6692. #endif
  6693. ) {
  6694. #ifdef WOLFSSL_SMALL_STACK
  6695. RsaKey* a;
  6696. RsaKey* b = NULL;
  6697. #else
  6698. RsaKey a[1], b[1];
  6699. #endif
  6700. word32 keyIdx = 0;
  6701. #ifdef WOLFSSL_SMALL_STACK
  6702. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6703. if (a == NULL)
  6704. return MEMORY_E;
  6705. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6706. if (b == NULL) {
  6707. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6708. return MEMORY_E;
  6709. }
  6710. #endif
  6711. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6712. #ifdef WOLFSSL_SMALL_STACK
  6713. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6714. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6715. #endif
  6716. return ret;
  6717. }
  6718. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6719. wc_FreeRsaKey(a);
  6720. #ifdef WOLFSSL_SMALL_STACK
  6721. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6722. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6723. #endif
  6724. return ret;
  6725. }
  6726. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6727. WOLFSSL_MSG("Checking RSA key pair");
  6728. keyIdx = 0; /* reset to 0 for parsing public key */
  6729. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6730. pubKeySz)) == 0) {
  6731. /* both keys extracted successfully now check n and e
  6732. * values are the same. This is dereferencing RsaKey */
  6733. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6734. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6735. ret = MP_CMP_E;
  6736. WOLFSSL_ERROR_VERBOSE(ret);
  6737. }
  6738. else
  6739. ret = 1;
  6740. }
  6741. else {
  6742. WOLFSSL_ERROR_VERBOSE(ret);
  6743. }
  6744. }
  6745. wc_FreeRsaKey(b);
  6746. wc_FreeRsaKey(a);
  6747. #ifdef WOLFSSL_SMALL_STACK
  6748. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6749. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6750. #endif
  6751. }
  6752. else
  6753. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6754. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6755. if (ks == ECDSAk) {
  6756. #ifdef WOLFSSL_SMALL_STACK
  6757. ecc_key* key_pair;
  6758. byte* privDer;
  6759. #else
  6760. ecc_key key_pair[1];
  6761. byte privDer[MAX_ECC_BYTES];
  6762. #endif
  6763. word32 privSz = MAX_ECC_BYTES;
  6764. word32 keyIdx = 0;
  6765. #ifdef WOLFSSL_SMALL_STACK
  6766. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6767. if (key_pair == NULL)
  6768. return MEMORY_E;
  6769. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6770. if (privDer == NULL) {
  6771. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6772. return MEMORY_E;
  6773. }
  6774. #endif
  6775. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6776. #ifdef WOLFSSL_SMALL_STACK
  6777. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6778. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6779. #endif
  6780. return ret;
  6781. }
  6782. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6783. privKeySz)) == 0) {
  6784. WOLFSSL_MSG("Checking ECC key pair");
  6785. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6786. == 0) {
  6787. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6788. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6789. #endif
  6790. wc_ecc_free(key_pair);
  6791. ret = wc_ecc_init(key_pair);
  6792. if (ret == 0) {
  6793. ret = wc_ecc_import_private_key(privDer,
  6794. privSz, pubKey,
  6795. pubKeySz, key_pair);
  6796. }
  6797. /* public and private extracted successfully now check if is
  6798. * a pair and also do sanity checks on key. wc_ecc_check_key
  6799. * checks that private * base generator equals pubkey */
  6800. if (ret == 0) {
  6801. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6802. ret = 1;
  6803. }
  6804. else {
  6805. WOLFSSL_ERROR_VERBOSE(ret);
  6806. }
  6807. }
  6808. ForceZero(privDer, privSz);
  6809. }
  6810. }
  6811. else {
  6812. WOLFSSL_ERROR_VERBOSE(ret);
  6813. }
  6814. wc_ecc_free(key_pair);
  6815. #ifdef WOLFSSL_SMALL_STACK
  6816. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6817. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6818. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6819. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6820. #endif
  6821. }
  6822. else
  6823. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6824. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6825. if (ks == ED25519k) {
  6826. #ifdef WOLFSSL_SMALL_STACK
  6827. ed25519_key* key_pair;
  6828. #else
  6829. ed25519_key key_pair[1];
  6830. #endif
  6831. word32 keyIdx = 0;
  6832. #ifdef WOLFSSL_SMALL_STACK
  6833. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6834. DYNAMIC_TYPE_ED25519);
  6835. if (key_pair == NULL)
  6836. return MEMORY_E;
  6837. #endif
  6838. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6839. #ifdef WOLFSSL_SMALL_STACK
  6840. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6841. #endif
  6842. return ret;
  6843. }
  6844. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6845. privKeySz)) == 0) {
  6846. WOLFSSL_MSG("Checking ED25519 key pair");
  6847. keyIdx = 0;
  6848. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6849. key_pair)) == 0) {
  6850. /* public and private extracted successfully no check if is
  6851. * a pair and also do sanity checks on key. wc_ecc_check_key
  6852. * checks that private * base generator equals pubkey */
  6853. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6854. ret = 1;
  6855. }
  6856. else {
  6857. WOLFSSL_ERROR_VERBOSE(ret);
  6858. }
  6859. }
  6860. }
  6861. else {
  6862. WOLFSSL_ERROR_VERBOSE(ret);
  6863. }
  6864. wc_ed25519_free(key_pair);
  6865. #ifdef WOLFSSL_SMALL_STACK
  6866. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6867. #endif
  6868. }
  6869. else
  6870. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6871. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6872. if (ks == ED448k) {
  6873. #ifdef WOLFSSL_SMALL_STACK
  6874. ed448_key* key_pair = NULL;
  6875. #else
  6876. ed448_key key_pair[1];
  6877. #endif
  6878. word32 keyIdx = 0;
  6879. #ifdef WOLFSSL_SMALL_STACK
  6880. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6881. DYNAMIC_TYPE_ED448);
  6882. if (key_pair == NULL)
  6883. return MEMORY_E;
  6884. #endif
  6885. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6886. #ifdef WOLFSSL_SMALL_STACK
  6887. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6888. #endif
  6889. return ret;
  6890. }
  6891. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6892. privKeySz)) == 0) {
  6893. WOLFSSL_MSG("Checking ED448 key pair");
  6894. keyIdx = 0;
  6895. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6896. key_pair)) == 0) {
  6897. /* public and private extracted successfully no check if is
  6898. * a pair and also do sanity checks on key. wc_ecc_check_key
  6899. * checks that private * base generator equals pubkey */
  6900. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6901. ret = 1;
  6902. }
  6903. else {
  6904. WOLFSSL_ERROR_VERBOSE(ret);
  6905. }
  6906. }
  6907. }
  6908. else {
  6909. WOLFSSL_ERROR_VERBOSE(ret);
  6910. }
  6911. wc_ed448_free(key_pair);
  6912. #ifdef WOLFSSL_SMALL_STACK
  6913. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6914. #endif
  6915. }
  6916. else
  6917. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6918. #if defined(HAVE_PQC)
  6919. #if defined(HAVE_FALCON)
  6920. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6921. #ifdef WOLFSSL_SMALL_STACK
  6922. falcon_key* key_pair = NULL;
  6923. #else
  6924. falcon_key key_pair[1];
  6925. #endif
  6926. word32 keyIdx = 0;
  6927. #ifdef WOLFSSL_SMALL_STACK
  6928. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6929. DYNAMIC_TYPE_FALCON);
  6930. if (key_pair == NULL)
  6931. return MEMORY_E;
  6932. #endif
  6933. ret = wc_falcon_init(key_pair);
  6934. if (ret < 0) {
  6935. #ifdef WOLFSSL_SMALL_STACK
  6936. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6937. #endif
  6938. return ret;
  6939. }
  6940. if (ks == FALCON_LEVEL1k) {
  6941. ret = wc_falcon_set_level(key_pair, 1);
  6942. }
  6943. else if (ks == FALCON_LEVEL5k) {
  6944. ret = wc_falcon_set_level(key_pair, 5);
  6945. }
  6946. if (ret < 0) {
  6947. #ifdef WOLFSSL_SMALL_STACK
  6948. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6949. #endif
  6950. return ret;
  6951. }
  6952. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6953. privKeySz)) == 0) {
  6954. WOLFSSL_MSG("Checking Falcon key pair");
  6955. keyIdx = 0;
  6956. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6957. key_pair)) == 0) {
  6958. /* Public and private extracted successfully. Sanity check. */
  6959. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6960. ret = 1;
  6961. }
  6962. else {
  6963. WOLFSSL_ERROR_VERBOSE(ret);
  6964. }
  6965. }
  6966. }
  6967. else {
  6968. WOLFSSL_ERROR_VERBOSE(ret);
  6969. }
  6970. wc_falcon_free(key_pair);
  6971. #ifdef WOLFSSL_SMALL_STACK
  6972. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6973. #endif
  6974. }
  6975. else
  6976. #endif /* HAVE_FALCON */
  6977. #if defined(HAVE_DILITHIUM)
  6978. if ((ks == DILITHIUM_LEVEL2k) ||
  6979. (ks == DILITHIUM_LEVEL3k) ||
  6980. (ks == DILITHIUM_LEVEL5k)) {
  6981. #ifdef WOLFSSL_SMALL_STACK
  6982. dilithium_key* key_pair = NULL;
  6983. #else
  6984. dilithium_key key_pair[1];
  6985. #endif
  6986. word32 keyIdx = 0;
  6987. #ifdef WOLFSSL_SMALL_STACK
  6988. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6989. DYNAMIC_TYPE_DILITHIUM);
  6990. if (key_pair == NULL)
  6991. return MEMORY_E;
  6992. #endif
  6993. ret = wc_dilithium_init(key_pair);
  6994. if (ret < 0) {
  6995. #ifdef WOLFSSL_SMALL_STACK
  6996. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6997. #endif
  6998. return ret;
  6999. }
  7000. if (ks == DILITHIUM_LEVEL2k) {
  7001. ret = wc_dilithium_set_level(key_pair, 2);
  7002. }
  7003. else if (ks == DILITHIUM_LEVEL3k) {
  7004. ret = wc_dilithium_set_level(key_pair, 3);
  7005. }
  7006. else if (ks == DILITHIUM_LEVEL5k) {
  7007. ret = wc_dilithium_set_level(key_pair, 5);
  7008. }
  7009. if (ret < 0) {
  7010. #ifdef WOLFSSL_SMALL_STACK
  7011. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  7012. #endif
  7013. return ret;
  7014. }
  7015. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  7016. privKeySz)) == 0) {
  7017. WOLFSSL_MSG("Checking Dilithium key pair");
  7018. keyIdx = 0;
  7019. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  7020. key_pair)) == 0) {
  7021. /* Public and private extracted successfully. Sanity check. */
  7022. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  7023. ret = 1;
  7024. }
  7025. }
  7026. wc_dilithium_free(key_pair);
  7027. #ifdef WOLFSSL_SMALL_STACK
  7028. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  7029. #endif
  7030. }
  7031. else
  7032. #endif /* HAVE_DILITHIUM */
  7033. #if defined(HAVE_SPHINCS)
  7034. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  7035. (ks == SPHINCS_FAST_LEVEL3k) ||
  7036. (ks == SPHINCS_FAST_LEVEL5k) ||
  7037. (ks == SPHINCS_SMALL_LEVEL1k) ||
  7038. (ks == SPHINCS_SMALL_LEVEL3k) ||
  7039. (ks == SPHINCS_SMALL_LEVEL5k)) {
  7040. #ifdef WOLFSSL_SMALL_STACK
  7041. sphincs_key* key_pair = NULL;
  7042. #else
  7043. sphincs_key key_pair[1];
  7044. #endif
  7045. word32 keyIdx = 0;
  7046. #ifdef WOLFSSL_SMALL_STACK
  7047. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  7048. DYNAMIC_TYPE_SPHINCS);
  7049. if (key_pair == NULL)
  7050. return MEMORY_E;
  7051. #endif
  7052. ret = wc_sphincs_init(key_pair);
  7053. if (ret < 0) {
  7054. #ifdef WOLFSSL_SMALL_STACK
  7055. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  7056. #endif
  7057. return ret;
  7058. }
  7059. if (ks == SPHINCS_FAST_LEVEL1k) {
  7060. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  7061. }
  7062. else if (ks == SPHINCS_FAST_LEVEL3k) {
  7063. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  7064. }
  7065. else if (ks == SPHINCS_FAST_LEVEL5k) {
  7066. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  7067. }
  7068. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  7069. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  7070. }
  7071. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  7072. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  7073. }
  7074. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  7075. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  7076. }
  7077. if (ret < 0) {
  7078. #ifdef WOLFSSL_SMALL_STACK
  7079. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  7080. #endif
  7081. return ret;
  7082. }
  7083. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  7084. privKeySz)) == 0) {
  7085. WOLFSSL_MSG("Checking Sphincs key pair");
  7086. keyIdx = 0;
  7087. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  7088. key_pair)) == 0) {
  7089. /* Public and private extracted successfully. Sanity check. */
  7090. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  7091. ret = 1;
  7092. }
  7093. }
  7094. wc_sphincs_free(key_pair);
  7095. #ifdef WOLFSSL_SMALL_STACK
  7096. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  7097. #endif
  7098. }
  7099. else
  7100. #endif /* HAVE_SPHINCS */
  7101. #endif /* HAVE_PQC */
  7102. {
  7103. ret = 0;
  7104. }
  7105. (void)ks;
  7106. return ret;
  7107. }
  7108. /* check that the private key is a pair for the public key in certificate
  7109. * return 1 (true) on match
  7110. * return 0 or negative value on failure/error
  7111. *
  7112. * key : buffer holding DER format key
  7113. * keySz : size of key buffer
  7114. * der : a initialized and parsed DecodedCert holding a certificate */
  7115. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  7116. {
  7117. if (key == NULL || der == NULL) {
  7118. return BAD_FUNC_ARG;
  7119. }
  7120. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  7121. der->pubKeySize, (enum Key_Sum) der->keyOID);
  7122. }
  7123. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  7124. #ifndef NO_PWDBASED
  7125. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7126. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  7127. * size of encryption algorithm.
  7128. *
  7129. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  7130. * blockSz based on encryption algorithm.
  7131. *
  7132. * @param [in] first First byte of OID to use in check.
  7133. * @param [in] second Second byte of OID to use in check.
  7134. * @param [out] id wolfSSL id for PBE algorithm.
  7135. * @param [out] version Version of PBE OID:
  7136. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7137. * @param [out] blockSz Block size of encryption algorithm.
  7138. * @return 0 on success.
  7139. * @return ALGO_ID_E when OID not supported.
  7140. * @return ASN_INPUT_E when first byte is invalid.
  7141. */
  7142. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  7143. {
  7144. int ret = 0;
  7145. (void)id;
  7146. (void)blockSz;
  7147. *version = -1;
  7148. /* pkcs-12 1 = pkcs-12PbeIds */
  7149. if (first == 1) {
  7150. /* PKCS #12: Appendix C */
  7151. switch (second) {
  7152. #if !defined(NO_SHA)
  7153. #ifndef NO_RC4
  7154. case PBE_SHA1_RC4_128:
  7155. *id = PBE_SHA1_RC4_128;
  7156. *version = PKCS12v1;
  7157. if (blockSz != NULL) {
  7158. *blockSz = 1;
  7159. }
  7160. break;
  7161. #endif
  7162. #ifndef NO_DES3
  7163. case PBE_SHA1_DES3:
  7164. *id = PBE_SHA1_DES3;
  7165. *version = PKCS12v1;
  7166. if (blockSz != NULL) {
  7167. *blockSz = DES_BLOCK_SIZE;
  7168. }
  7169. break;
  7170. #endif
  7171. #ifdef WC_RC2
  7172. case PBE_SHA1_40RC2_CBC:
  7173. *id = PBE_SHA1_40RC2_CBC;
  7174. *version = PKCS12v1;
  7175. if (blockSz != NULL) {
  7176. *blockSz = RC2_BLOCK_SIZE;
  7177. }
  7178. break;
  7179. #endif
  7180. #endif /* !NO_SHA */
  7181. default:
  7182. ret = ALGO_ID_E;
  7183. break;
  7184. }
  7185. }
  7186. else if (first != PKCS5) {
  7187. /* Bad OID. */
  7188. ret = ASN_INPUT_E;
  7189. }
  7190. /* PKCS #5 PBES2: Appendix A.4
  7191. * pkcs-5 13 = id-PBES2 */
  7192. else if (second == PBES2) {
  7193. *version = PKCS5v2;
  7194. /* Id and block size come from CheckAlgoV2() */
  7195. }
  7196. else {
  7197. /* PKCS #5 PBES1: Appendix A.3 */
  7198. /* see RFC 2898 for ids */
  7199. switch (second) {
  7200. #ifndef NO_DES3
  7201. #ifndef NO_MD5
  7202. case PBES1_MD5_DES:
  7203. *id = PBE_MD5_DES;
  7204. *version = PKCS5;
  7205. if (blockSz != NULL) {
  7206. *blockSz = DES_BLOCK_SIZE;
  7207. }
  7208. break;
  7209. #endif
  7210. #ifndef NO_SHA
  7211. case PBES1_SHA1_DES:
  7212. *id = PBE_SHA1_DES;
  7213. *version = PKCS5;
  7214. if (blockSz != NULL) {
  7215. *blockSz = DES_BLOCK_SIZE;
  7216. }
  7217. break;
  7218. #endif
  7219. #endif /* !NO_DES3 */
  7220. default:
  7221. ret = ALGO_ID_E;
  7222. break;
  7223. }
  7224. }
  7225. /* Return error code. */
  7226. return ret;
  7227. }
  7228. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7229. #ifdef HAVE_PKCS8
  7230. /* Check the encryption algorithm with PBES2 is supported and return block size
  7231. * and wolfSSL id for the PBE.
  7232. *
  7233. * @param [in] oid Encryption algorithm OID id.
  7234. * @param [out] id wolfSSL id for PBE algorithm.
  7235. * @param [out] version Version of PBE OID:
  7236. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7237. * @return 0 on success.
  7238. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7239. */
  7240. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7241. {
  7242. int ret = 0;
  7243. (void)id;
  7244. (void)blockSz;
  7245. switch (oid) {
  7246. #if !defined(NO_DES3) && !defined(NO_SHA)
  7247. case DESb:
  7248. *id = PBE_SHA1_DES;
  7249. if (blockSz != NULL) {
  7250. *blockSz = DES_BLOCK_SIZE;
  7251. }
  7252. break;
  7253. case DES3b:
  7254. *id = PBE_SHA1_DES3;
  7255. if (blockSz != NULL) {
  7256. *blockSz = DES_BLOCK_SIZE;
  7257. }
  7258. break;
  7259. #endif
  7260. #ifdef WOLFSSL_AES_256
  7261. case AES256CBCb:
  7262. *id = PBE_AES256_CBC;
  7263. if (blockSz != NULL) {
  7264. *blockSz = AES_BLOCK_SIZE;
  7265. }
  7266. break;
  7267. #endif
  7268. #ifdef WOLFSSL_AES_128
  7269. case AES128CBCb:
  7270. *id = PBE_AES128_CBC;
  7271. if (blockSz != NULL) {
  7272. *blockSz = AES_BLOCK_SIZE;
  7273. }
  7274. break;
  7275. #endif
  7276. default:
  7277. WOLFSSL_MSG("No PKCS v2 algo found");
  7278. ret = ALGO_ID_E;
  7279. break;
  7280. }
  7281. /* Return error code. */
  7282. return ret;
  7283. }
  7284. #endif /* HAVE_PKCS8 */
  7285. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7286. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7287. int* algoID, void* heap)
  7288. {
  7289. word32 tmpIdx = 0;
  7290. if (key == NULL || algoID == NULL)
  7291. return BAD_FUNC_ARG;
  7292. *algoID = 0;
  7293. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7294. {
  7295. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7296. if (rsa == NULL)
  7297. return MEMORY_E;
  7298. wc_InitRsaKey(rsa, heap);
  7299. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7300. *algoID = RSAk;
  7301. }
  7302. else {
  7303. WOLFSSL_MSG("Not RSA DER key");
  7304. }
  7305. wc_FreeRsaKey(rsa);
  7306. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7307. }
  7308. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7309. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7310. if (*algoID == 0) {
  7311. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7312. if (ecc == NULL)
  7313. return MEMORY_E;
  7314. tmpIdx = 0;
  7315. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7316. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7317. *algoID = ECDSAk;
  7318. /* now find oid */
  7319. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7320. WOLFSSL_MSG("Error getting ECC curve OID");
  7321. wc_ecc_free(ecc);
  7322. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7323. return BAD_FUNC_ARG;
  7324. }
  7325. }
  7326. else {
  7327. WOLFSSL_MSG("Not ECC DER key either");
  7328. }
  7329. wc_ecc_free(ecc);
  7330. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7331. }
  7332. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7333. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7334. if (*algoID == 0) {
  7335. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7336. DYNAMIC_TYPE_TMP_BUFFER);
  7337. if (ed25519 == NULL)
  7338. return MEMORY_E;
  7339. tmpIdx = 0;
  7340. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7341. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7342. *algoID = ED25519k;
  7343. }
  7344. else {
  7345. WOLFSSL_MSG("Not ED25519 DER key");
  7346. }
  7347. wc_ed25519_free(ed25519);
  7348. }
  7349. else {
  7350. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7351. }
  7352. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7353. }
  7354. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7355. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7356. if (*algoID == 0) {
  7357. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7358. DYNAMIC_TYPE_TMP_BUFFER);
  7359. if (ed448 == NULL)
  7360. return MEMORY_E;
  7361. tmpIdx = 0;
  7362. if (wc_ed448_init(ed448) == 0) {
  7363. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7364. *algoID = ED448k;
  7365. }
  7366. else {
  7367. WOLFSSL_MSG("Not ED448 DER key");
  7368. }
  7369. wc_ed448_free(ed448);
  7370. }
  7371. else {
  7372. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7373. }
  7374. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7375. }
  7376. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7377. #if defined(HAVE_PQC)
  7378. #if defined(HAVE_FALCON)
  7379. if (*algoID == 0) {
  7380. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7381. DYNAMIC_TYPE_TMP_BUFFER);
  7382. if (falcon == NULL)
  7383. return MEMORY_E;
  7384. if (wc_falcon_init(falcon) != 0) {
  7385. tmpIdx = 0;
  7386. if (wc_falcon_set_level(falcon, 1) == 0) {
  7387. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7388. == 0) {
  7389. *algoID = FALCON_LEVEL1k;
  7390. }
  7391. else {
  7392. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7393. }
  7394. }
  7395. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7396. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7397. == 0) {
  7398. *algoID = FALCON_LEVEL5k;
  7399. }
  7400. else {
  7401. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7402. }
  7403. }
  7404. else {
  7405. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7406. }
  7407. wc_falcon_free(falcon);
  7408. }
  7409. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7410. }
  7411. #endif /* HAVE_FALCON */
  7412. #if defined(HAVE_DILITHIUM)
  7413. if (*algoID == 0) {
  7414. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7415. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7416. if (dilithium == NULL)
  7417. return MEMORY_E;
  7418. if (wc_dilithium_init(dilithium) != 0) {
  7419. tmpIdx = 0;
  7420. if (wc_dilithium_set_level(dilithium, 2)
  7421. == 0) {
  7422. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7423. keySz) == 0) {
  7424. *algoID = DILITHIUM_LEVEL2k;
  7425. }
  7426. else {
  7427. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7428. }
  7429. }
  7430. else if (wc_dilithium_set_level(dilithium, 3)
  7431. == 0) {
  7432. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7433. keySz) == 0) {
  7434. *algoID = DILITHIUM_LEVEL3k;
  7435. }
  7436. else {
  7437. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7438. }
  7439. }
  7440. else if (wc_dilithium_set_level(dilithium, 5)
  7441. == 0) {
  7442. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7443. keySz) == 0) {
  7444. *algoID = DILITHIUM_LEVEL5k;
  7445. }
  7446. else {
  7447. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7448. }
  7449. }
  7450. else {
  7451. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7452. }
  7453. wc_dilithium_free(dilithium);
  7454. }
  7455. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7456. }
  7457. #endif /* HAVE_DILITHIUM */
  7458. #if defined(HAVE_SPHINCS)
  7459. if (*algoID == 0) {
  7460. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7461. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7462. if (sphincs == NULL)
  7463. return MEMORY_E;
  7464. if (wc_sphincs_init(sphincs) != 0) {
  7465. tmpIdx = 0;
  7466. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7467. == 0) {
  7468. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7469. keySz) == 0) {
  7470. *algoID = SPHINCS_FAST_LEVEL1k;
  7471. }
  7472. else {
  7473. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7474. }
  7475. }
  7476. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7477. == 0) {
  7478. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7479. keySz) == 0) {
  7480. *algoID = SPHINCS_FAST_LEVEL3k;
  7481. }
  7482. else {
  7483. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7484. }
  7485. }
  7486. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7487. == 0) {
  7488. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7489. keySz) == 0) {
  7490. *algoID = SPHINCS_FAST_LEVEL5k;
  7491. }
  7492. else {
  7493. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7494. }
  7495. }
  7496. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7497. == 0) {
  7498. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7499. keySz) == 0) {
  7500. *algoID = SPHINCS_SMALL_LEVEL1k;
  7501. }
  7502. else {
  7503. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7504. }
  7505. }
  7506. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7507. == 0) {
  7508. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7509. keySz) == 0) {
  7510. *algoID = SPHINCS_SMALL_LEVEL3k;
  7511. }
  7512. else {
  7513. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7514. }
  7515. }
  7516. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7517. == 0) {
  7518. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7519. keySz) == 0) {
  7520. *algoID = SPHINCS_SMALL_LEVEL5k;
  7521. }
  7522. else {
  7523. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7524. }
  7525. }
  7526. else {
  7527. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7528. }
  7529. wc_sphincs_free(sphincs);
  7530. }
  7531. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7532. }
  7533. #endif /* HAVE_SPHINCS */
  7534. #endif /* HAVE_PQC */
  7535. /* if flag is not set then this is not a key that we understand. */
  7536. if (*algoID == 0) {
  7537. WOLFSSL_MSG("Bad key DER or compile options");
  7538. return BAD_FUNC_ARG;
  7539. }
  7540. (void)tmpIdx;
  7541. (void)curveOID;
  7542. (void)oidSz;
  7543. (void)keySz;
  7544. (void)heap;
  7545. return 1;
  7546. }
  7547. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7548. #ifdef WOLFSSL_ASN_TEMPLATE
  7549. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7550. /* ASN.1 template for PBES2 parameters.
  7551. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7552. * A.2 - PBKDF2-params
  7553. * B.2 - Encryption schemes
  7554. * C - AlgorithmIdentifier
  7555. */
  7556. static const ASNItem pbes2ParamsASN[] = {
  7557. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7558. /* PBKDF2 */
  7559. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7560. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7561. /* Salt */
  7562. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7563. /* Iteration count */
  7564. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7565. /* Key length */
  7566. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7567. /* PRF - default is HMAC-SHA1 */
  7568. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7569. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7570. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7571. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7572. /* Encryption algorithm */
  7573. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7574. /* IV for CBC */
  7575. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7576. };
  7577. enum {
  7578. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7579. PBES2PARAMSASN_IDX_KDF_OID,
  7580. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7581. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7582. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7583. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7584. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7585. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7586. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7587. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7588. PBES2PARAMSASN_IDX_ENCS_OID,
  7589. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7590. };
  7591. /* Number of items in ASN.1 template for PBES2 parameters. */
  7592. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7593. /* ASN.1 template for PBES1 parameters.
  7594. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7595. */
  7596. static const ASNItem pbes1ParamsASN[] = {
  7597. /* Salt */
  7598. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7599. /* Iteration count */
  7600. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7601. };
  7602. enum {
  7603. PBES1PARAMSASN_IDX_SALT = 0,
  7604. PBES1PARAMSASN_IDX_ITER
  7605. };
  7606. /* Number of items in ASN.1 template for PBES1 parameters. */
  7607. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7608. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7609. #endif /* WOLFSSL_ASN_TEMPLATE */
  7610. #ifdef HAVE_PKCS8
  7611. /*
  7612. * Equivalent to calling TraditionalEnc with the same parameters but with
  7613. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7614. * part of the API (WOLFSSL_ASN_API).
  7615. */
  7616. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7617. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7618. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7619. {
  7620. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7621. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7622. }
  7623. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7624. int *blkSz)
  7625. {
  7626. int ret = 0;
  7627. switch (encAlgId) {
  7628. #if !defined(NO_DES3) && !defined(NO_SHA)
  7629. case DESb:
  7630. *len = sizeof(blkDesCbcOid);
  7631. *oid = blkDesCbcOid;
  7632. *id = PBE_SHA1_DES;
  7633. *blkSz = 8;
  7634. break;
  7635. case DES3b:
  7636. *len = sizeof(blkDes3CbcOid);
  7637. *oid = blkDes3CbcOid;
  7638. *id = PBE_SHA1_DES3;
  7639. *blkSz = 8;
  7640. break;
  7641. #endif
  7642. #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
  7643. case AES128CBCb:
  7644. *len = sizeof(blkAes128CbcOid);
  7645. *oid = blkAes128CbcOid;
  7646. *id = PBE_AES128_CBC;
  7647. *blkSz = 16;
  7648. break;
  7649. #endif
  7650. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7651. case AES256CBCb:
  7652. *len = sizeof(blkAes256CbcOid);
  7653. *oid = blkAes256CbcOid;
  7654. *id = PBE_AES256_CBC;
  7655. *blkSz = 16;
  7656. break;
  7657. #endif
  7658. default:
  7659. (void)len;
  7660. (void)oid;
  7661. (void)id;
  7662. (void)blkSz;
  7663. ret = ALGO_ID_E;
  7664. }
  7665. return ret;
  7666. }
  7667. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7668. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7669. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7670. void* heap)
  7671. {
  7672. #ifdef WOLFSSL_SMALL_STACK
  7673. byte* saltTmp = NULL;
  7674. #else
  7675. byte saltTmp[MAX_SALT_SIZE];
  7676. #endif
  7677. int genSalt = 0;
  7678. int ret = 0;
  7679. int version = 0;
  7680. int pbeId = 0;
  7681. int blockSz = 0;
  7682. const byte* encOid = NULL;
  7683. int encOidSz = 0;
  7684. word32 padSz = 0;
  7685. word32 innerLen = 0;
  7686. const byte* pbeOidBuf = NULL;
  7687. word32 pbeOidBufSz = 0;
  7688. word32 pbeLen = 0;
  7689. word32 kdfLen = 0;
  7690. word32 encLen = 0;
  7691. byte cbcIv[MAX_IV_SIZE];
  7692. word32 idx = 0;
  7693. word32 encIdx = 0;
  7694. (void)heap;
  7695. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7696. if (key == NULL || outSz == NULL || password == NULL) {
  7697. ret = BAD_FUNC_ARG;
  7698. }
  7699. if (ret == 0) {
  7700. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7701. }
  7702. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7703. genSalt = 1;
  7704. saltSz = 8;
  7705. }
  7706. if (ret == 0 && version == PKCS5v2) {
  7707. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7708. }
  7709. if (ret == 0) {
  7710. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7711. (blockSz - 1));
  7712. /* inner = OCT salt INT itt */
  7713. innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
  7714. if (version != PKCS5v2) {
  7715. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7716. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7717. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7718. }
  7719. else {
  7720. pbeOidBuf = pbes2;
  7721. pbeOidBufSz = sizeof(pbes2);
  7722. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7723. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7724. /* enc = OBJ enc_alg OCT iv */
  7725. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7726. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7727. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7728. (size_t)encLen);
  7729. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7730. }
  7731. }
  7732. if (ret == 0) {
  7733. /* outerLen = length of PBE encoding + octet string data */
  7734. /* Plus 2 for tag and length for pbe */
  7735. word32 outerLen = 2 + pbeLen;
  7736. /* Octet string tag, length */
  7737. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7738. /* Octet string bytes */
  7739. outerLen += keySz + padSz;
  7740. if (out == NULL) {
  7741. /* Sequence tag, length */
  7742. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7743. return LENGTH_ONLY_E;
  7744. }
  7745. SetOctetString(keySz + padSz, out);
  7746. idx += SetSequence(outerLen, out + idx);
  7747. encIdx = idx + outerLen - keySz - padSz;
  7748. /* Put Encrypted content in place. */
  7749. XMEMCPY(out + encIdx, key, keySz);
  7750. if (padSz > 0) {
  7751. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7752. keySz += padSz;
  7753. }
  7754. if (genSalt == 1) {
  7755. #ifdef WOLFSSL_SMALL_STACK
  7756. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7757. if (saltTmp == NULL) {
  7758. ret = MEMORY_E;
  7759. }
  7760. else
  7761. #endif
  7762. {
  7763. salt = saltTmp;
  7764. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7765. WOLFSSL_MSG("Error generating random salt");
  7766. }
  7767. }
  7768. }
  7769. }
  7770. if (ret == 0) {
  7771. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7772. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7773. }
  7774. if (ret == 0) {
  7775. if (version != PKCS5v2) {
  7776. /* PBE algorithm */
  7777. idx += SetSequence(pbeLen, out + idx);
  7778. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7779. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7780. idx += pbeOidBufSz;
  7781. }
  7782. else {
  7783. /* PBES2 algorithm identifier */
  7784. idx += SetSequence(pbeLen, out + idx);
  7785. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7786. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7787. idx += pbeOidBufSz;
  7788. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7789. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7790. /* KDF Algorithm Identifier */
  7791. idx += SetSequence(kdfLen, out + idx);
  7792. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7793. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7794. idx += sizeof(pbkdf2Oid);
  7795. }
  7796. idx += SetSequence(innerLen, out + idx);
  7797. idx += SetOctetString(saltSz, out + idx);
  7798. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7799. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7800. if (ret > 0)
  7801. ret = 0;
  7802. }
  7803. if (ret == 0) {
  7804. if (version == PKCS5v2) {
  7805. /* Encryption Algorithm Identifier */
  7806. idx += SetSequence(encLen, out + idx);
  7807. idx += (word32)SetObjectId(encOidSz, out + idx);
  7808. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7809. idx += (word32)encOidSz;
  7810. /* Encryption Algorithm Parameter: CBC IV */
  7811. idx += SetOctetString((word32)blockSz, out + idx);
  7812. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7813. idx += (word32)blockSz;
  7814. }
  7815. idx += SetOctetString(keySz, out + idx);
  7816. /* Default PRF - no need to write out OID */
  7817. idx += keySz;
  7818. ret = (int)idx;
  7819. }
  7820. #ifdef WOLFSSL_SMALL_STACK
  7821. if (saltTmp != NULL) {
  7822. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7823. }
  7824. #endif
  7825. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7826. return ret;
  7827. }
  7828. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7829. int passwordSz)
  7830. {
  7831. int ret;
  7832. int length;
  7833. word32 inOutIdx = 0;
  7834. if (input == NULL || password == NULL) {
  7835. return BAD_FUNC_ARG;
  7836. }
  7837. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7838. ret = ASN_PARSE_E;
  7839. }
  7840. else {
  7841. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7842. passwordSz);
  7843. if (ret > 0) {
  7844. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7845. }
  7846. }
  7847. if (ret > 0) {
  7848. /* DecryptContent will decrypt the data, but it will leave any padding
  7849. * bytes intact. This code calculates the length without the padding
  7850. * and we return that to the user. */
  7851. inOutIdx = 0;
  7852. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7853. ret = ASN_PARSE_E;
  7854. }
  7855. else {
  7856. ret = (int)inOutIdx + length;
  7857. }
  7858. }
  7859. return ret;
  7860. }
  7861. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7862. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7863. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7864. * buffer size. */
  7865. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7866. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7867. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7868. void* heap)
  7869. {
  7870. int ret = 0;
  7871. byte *pkcs8Key = NULL;
  7872. word32 pkcs8KeySz = 0;
  7873. int algId = 0;
  7874. const byte* curveOid = NULL;
  7875. word32 curveOidSz = 0;
  7876. if (ret == 0) {
  7877. /* check key type and get OID if ECC */
  7878. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7879. if (ret == 1)
  7880. ret = 0;
  7881. }
  7882. if (ret == 0) {
  7883. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7884. curveOidSz);
  7885. if (ret == LENGTH_ONLY_E)
  7886. ret = 0;
  7887. }
  7888. if (ret == 0) {
  7889. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7890. if (pkcs8Key == NULL)
  7891. ret = MEMORY_E;
  7892. }
  7893. if (ret == 0) {
  7894. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7895. curveOid, curveOidSz);
  7896. if (ret >= 0) {
  7897. pkcs8KeySz = (word32)ret;
  7898. ret = 0;
  7899. }
  7900. }
  7901. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7902. if (ret == 0) {
  7903. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7904. }
  7905. #endif
  7906. if (ret == 0) {
  7907. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7908. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7909. }
  7910. if (pkcs8Key != NULL) {
  7911. ForceZero(pkcs8Key, pkcs8KeySz);
  7912. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7913. }
  7914. (void)rng;
  7915. return ret;
  7916. }
  7917. /* Same as TraditionalEnc, but in the public API. */
  7918. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7919. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7920. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7921. WC_RNG* rng, void* heap)
  7922. {
  7923. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7924. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7925. }
  7926. #ifdef WOLFSSL_ASN_TEMPLATE
  7927. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7928. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7929. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7930. */
  7931. static const ASNItem pkcs8DecASN[] = {
  7932. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7933. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7934. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7935. /* PKCS #7 */
  7936. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7937. 0, 0, 2 },
  7938. /* PKCS #8 */
  7939. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7940. };
  7941. enum {
  7942. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7943. PKCS8DECASN_IDX_ENCALGO_OID,
  7944. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7945. PKCS8DECASN_IDX_ENCCONTENT,
  7946. PKCS8DECASN_IDX_ENCDATA
  7947. };
  7948. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7949. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7950. #endif
  7951. /* Decrypt data using PBE algorithm.
  7952. *
  7953. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7954. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7955. *
  7956. * Note: input buffer is overwritten with decrypted data!
  7957. *
  7958. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7959. *
  7960. * @param [in] input Data to decrypt and unwrap.
  7961. * @param [in] sz Size of encrypted data.
  7962. * @param [in] password Password to derive encryption key with.
  7963. * @param [in] passwordSz Size of password in bytes.
  7964. * @return Length of decrypted data on success.
  7965. * @return MEMORY_E when dynamic memory allocation fails.
  7966. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7967. * is invalid.
  7968. * @return BUFFER_E when data in buffer is too small.
  7969. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7970. * @return Other when decryption fails.
  7971. */
  7972. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7973. {
  7974. #ifndef WOLFSSL_ASN_TEMPLATE
  7975. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7976. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7977. int iterations = 0, keySz = 0;
  7978. #ifdef WOLFSSL_SMALL_STACK
  7979. byte* salt = NULL;
  7980. byte* cbcIv = NULL;
  7981. #else
  7982. byte salt[MAX_SALT_SIZE];
  7983. byte cbcIv[MAX_IV_SIZE];
  7984. #endif
  7985. byte tag;
  7986. if (passwordSz < 0) {
  7987. WOLFSSL_MSG("Bad password size");
  7988. return BAD_FUNC_ARG;
  7989. }
  7990. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7991. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7992. }
  7993. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7994. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7995. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7996. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7997. }
  7998. if (version == PKCS5v2) {
  7999. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  8000. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8001. }
  8002. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  8003. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8004. }
  8005. if (oid != PBKDF2_OID) {
  8006. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8007. }
  8008. }
  8009. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  8010. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8011. }
  8012. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  8013. * DEFAULT items. */
  8014. seqEnd = inOutIdx + (word32)length;
  8015. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  8016. if (ret < 0)
  8017. goto exit_dc;
  8018. if (saltSz > MAX_SALT_SIZE) {
  8019. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8020. }
  8021. #ifdef WOLFSSL_SMALL_STACK
  8022. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8023. if (salt == NULL) {
  8024. ERROR_OUT(MEMORY_E, exit_dc);
  8025. }
  8026. #endif
  8027. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  8028. inOutIdx += (word32)saltSz;
  8029. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  8030. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8031. }
  8032. /* OPTIONAL key length */
  8033. if (seqEnd > inOutIdx) {
  8034. word32 localIdx = inOutIdx;
  8035. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  8036. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8037. }
  8038. if (tag == ASN_INTEGER &&
  8039. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  8040. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8041. }
  8042. }
  8043. /* DEFAULT HMAC is SHA-1 */
  8044. if (seqEnd > inOutIdx) {
  8045. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  8046. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8047. }
  8048. shaOid = oid;
  8049. }
  8050. #ifdef WOLFSSL_SMALL_STACK
  8051. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8052. if (cbcIv == NULL) {
  8053. ERROR_OUT(MEMORY_E, exit_dc);
  8054. }
  8055. #endif
  8056. if (version == PKCS5v2) {
  8057. /* get encryption algo */
  8058. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  8059. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8060. }
  8061. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  8062. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  8063. }
  8064. if (shaOid == 0)
  8065. shaOid = oid;
  8066. ret = GetOctetString(input, &inOutIdx, &length, sz);
  8067. if (ret < 0)
  8068. goto exit_dc;
  8069. if (length > MAX_IV_SIZE) {
  8070. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8071. }
  8072. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  8073. inOutIdx += (word32)length;
  8074. }
  8075. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  8076. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8077. }
  8078. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  8079. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8080. }
  8081. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  8082. ERROR_OUT(ASN_PARSE_E, exit_dc);
  8083. }
  8084. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  8085. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  8086. exit_dc:
  8087. #ifdef WOLFSSL_SMALL_STACK
  8088. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8089. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8090. #endif
  8091. if (ret == 0) {
  8092. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  8093. ret = length;
  8094. }
  8095. return ret;
  8096. #else
  8097. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  8098. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  8099. int ret = 0;
  8100. int id = 0;
  8101. int version;
  8102. word32 idx = 0;
  8103. word32 pIdx = 0;
  8104. word32 iterations = 0;
  8105. word32 keySz = 0;
  8106. word32 saltSz = 0;
  8107. word32 shaOid = 0;
  8108. byte* salt = NULL;
  8109. byte* key = NULL;
  8110. byte cbcIv[MAX_IV_SIZE];
  8111. byte* params = NULL;
  8112. WOLFSSL_ENTER("DecryptContent");
  8113. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  8114. if (ret == 0) {
  8115. /* Check OID is a PBE Type */
  8116. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  8117. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  8118. &idx, sz);
  8119. }
  8120. if (ret == 0) {
  8121. /* Check the PBE algorithm and get the version and id. */
  8122. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  8123. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  8124. * Last byte: Alg or PBES2 */
  8125. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  8126. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  8127. &id, &version, NULL);
  8128. }
  8129. if (ret == 0) {
  8130. /* Get the parameters data. */
  8131. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  8132. /* Having a numbered choice means none or both will have errored out. */
  8133. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  8134. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  8135. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  8136. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  8137. else
  8138. ret = ASN_RSA_KEY_E;
  8139. }
  8140. if (ret == 0) {
  8141. if (version != PKCS5v2) {
  8142. /* Initialize for PBES1 parameters and put iterations in var. */
  8143. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  8144. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  8145. /* Parse the PBES1 parameters. */
  8146. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  8147. 0, params, &pIdx, sz);
  8148. if (ret == 0) {
  8149. /* Get the salt data. */
  8150. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  8151. }
  8152. }
  8153. else {
  8154. word32 ivSz = MAX_IV_SIZE;
  8155. /* Initialize for PBES2 parameters. Put iterations in var; match
  8156. * KDF, HMAC and cipher, and copy CBC into buffer. */
  8157. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  8158. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  8159. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  8160. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  8161. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  8162. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  8163. /* Parse the PBES2 parameters */
  8164. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  8165. 0, params, &pIdx, sz);
  8166. if (ret == 0) {
  8167. /* Get the salt data. */
  8168. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  8169. /* Get the digest and encryption algorithm id. */
  8170. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  8171. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8172. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8173. CheckAlgoV2(id, &id, NULL);
  8174. }
  8175. }
  8176. }
  8177. if (ret == 0) {
  8178. /* Decrypt the key. */
  8179. ret = wc_CryptKey(
  8180. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8181. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8182. }
  8183. if (ret == 0) {
  8184. /* Copy the decrypted key into the input (inline). */
  8185. XMEMMOVE(input, key, keySz);
  8186. ret = (int)keySz;
  8187. }
  8188. FREE_ASNGETDATA(dataASN, NULL);
  8189. return ret;
  8190. #endif
  8191. }
  8192. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8193. *
  8194. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8195. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8196. *
  8197. * Note: input buffer is overwritten with decrypted key!
  8198. *
  8199. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8200. *
  8201. * @param [in] input Data to decrypt and unwrap.
  8202. * @param [in] sz Size of encrypted data.
  8203. * @param [in] password Password to derive encryption key with.
  8204. * @param [in] passwordSz Size of password in bytes.
  8205. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8206. * @return Length of decrypted data on success.
  8207. * @return MEMORY_E when dynamic memory allocation fails.
  8208. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8209. * is invalid.
  8210. * @return BUFFER_E when data in buffer is too small.
  8211. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8212. * @return Other when decryption fails.
  8213. */
  8214. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8215. int passwordSz, word32* algId)
  8216. {
  8217. int ret;
  8218. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8219. if (ret > 0) {
  8220. ret = ToTraditional_ex(input, (word32)ret, algId);
  8221. }
  8222. return ret;
  8223. }
  8224. #endif /* HAVE_PKCS8 */
  8225. #ifdef HAVE_PKCS12
  8226. #define PKCS8_MIN_BLOCK_SIZE 8
  8227. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8228. {
  8229. int padSz;
  8230. /* calculate pad size */
  8231. padSz = blockSz - (sz & (blockSz - 1));
  8232. /* pad with padSz value */
  8233. if (buf) {
  8234. int i;
  8235. for (i = 0; i < padSz; i++) {
  8236. buf[sz+i] = (byte)(padSz & 0xFF);
  8237. }
  8238. }
  8239. /* return adjusted length */
  8240. return sz + padSz;
  8241. }
  8242. #ifdef WOLFSSL_ASN_TEMPLATE
  8243. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8244. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8245. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8246. */
  8247. static const ASNItem p8EncPbes1ASN[] = {
  8248. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8249. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8250. /* PBE algorithm */
  8251. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8252. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8253. /* Salt */
  8254. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8255. /* Iteration Count */
  8256. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8257. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8258. };
  8259. enum {
  8260. P8ENCPBES1ASN_IDX_SEQ = 0,
  8261. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8262. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8263. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8264. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8265. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8266. P8ENCPBES1ASN_IDX_ENCDATA
  8267. };
  8268. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8269. #endif
  8270. /* Wrap a private key in PKCS#8 and encrypt.
  8271. *
  8272. * Used for PKCS#12 and PKCS#7.
  8273. * vPKCS is the version of PKCS to use.
  8274. * vAlgo is the algorithm version to use.
  8275. *
  8276. * When salt is NULL, a random number is generated.
  8277. *
  8278. * data returned is :
  8279. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8280. *
  8281. * @param [in] input Data to encrypt.
  8282. * @param [in] inputSz Length of data in bytes.
  8283. * @param [out] out Buffer to write wrapped encrypted data into.
  8284. * @param [out] outSz Length of encrypted data in bytes.
  8285. * @param [in] password Password used to create encryption key.
  8286. * @param [in] passwordSz Length of password in bytes.
  8287. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8288. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8289. * @param [in] salt Salt to use with KDF.
  8290. * @param [in] saltSz Length of salt in bytes.
  8291. * @param [in] itt Number of iterations to use in KDF.
  8292. * @param [in] rng Random number generator to use to generate salt.
  8293. * @param [in] heap Dynamic memory allocator hint.
  8294. * @return The size of encrypted data on success
  8295. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8296. * @return ASN_PARSE_E when the salt size is too large.
  8297. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8298. * TraditionalEnc).
  8299. * @return MEMORY_E when dynamic memory allocation fails.
  8300. * @return Other when encryption or random number generation fails.
  8301. */
  8302. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8303. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8304. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8305. {
  8306. #ifndef WOLFSSL_ASN_TEMPLATE
  8307. word32 sz;
  8308. word32 inOutIdx = 0;
  8309. word32 tmpIdx = 0;
  8310. word32 totalSz = 0;
  8311. word32 seqSz;
  8312. word32 innerSz;
  8313. int ret;
  8314. int version, id, blockSz = 0;
  8315. #ifdef WOLFSSL_SMALL_STACK
  8316. byte* saltTmp = NULL;
  8317. byte* cbcIv = NULL;
  8318. #else
  8319. byte saltTmp[MAX_SALT_SIZE];
  8320. byte cbcIv[MAX_IV_SIZE];
  8321. #endif
  8322. byte seq[MAX_SEQ_SZ];
  8323. byte shr[MAX_SHORT_SZ];
  8324. word32 maxShr = MAX_SHORT_SZ;
  8325. word32 algoSz;
  8326. const byte* algoName;
  8327. (void)heap;
  8328. WOLFSSL_ENTER("EncryptContent");
  8329. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8330. return ASN_INPUT_E; /* Algo ID error */
  8331. if (version == PKCS5v2) {
  8332. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8333. return BAD_FUNC_ARG;
  8334. }
  8335. if (saltSz > MAX_SALT_SIZE)
  8336. return ASN_PARSE_E;
  8337. if (outSz == NULL) {
  8338. return BAD_FUNC_ARG;
  8339. }
  8340. /* calculate size */
  8341. /* size of constructed string at end */
  8342. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8343. totalSz = ASN_TAG_SZ;
  8344. totalSz += SetLength(sz, seq);
  8345. totalSz += sz;
  8346. /* size of sequence holding object id and sub sequence of salt and itt */
  8347. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8348. if (algoName == NULL) {
  8349. WOLFSSL_MSG("Unknown Algorithm");
  8350. return 0;
  8351. }
  8352. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8353. innerSz += algoSz;
  8354. /* get subsequence of salt and itt */
  8355. if (salt == NULL || saltSz == 0) {
  8356. sz = 8;
  8357. }
  8358. else {
  8359. sz = saltSz;
  8360. }
  8361. seqSz = SetOctetString(sz, seq);
  8362. seqSz += sz;
  8363. tmpIdx = 0;
  8364. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8365. if (ret >= 0) {
  8366. seqSz += (word32)ret;
  8367. }
  8368. else {
  8369. return ret;
  8370. }
  8371. innerSz += seqSz + SetSequence(seqSz, seq);
  8372. totalSz += innerSz + SetSequence(innerSz, seq);
  8373. if (out == NULL) {
  8374. *outSz = totalSz;
  8375. return LENGTH_ONLY_E;
  8376. }
  8377. inOutIdx = 0;
  8378. if (totalSz > *outSz)
  8379. return BUFFER_E;
  8380. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8381. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8382. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8383. inOutIdx += algoSz;
  8384. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8385. /* create random salt if one not provided */
  8386. if (salt == NULL || saltSz == 0) {
  8387. saltSz = 8;
  8388. #ifdef WOLFSSL_SMALL_STACK
  8389. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8390. if (saltTmp == NULL)
  8391. return MEMORY_E;
  8392. #endif
  8393. salt = saltTmp;
  8394. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8395. WOLFSSL_MSG("Error generating random salt");
  8396. #ifdef WOLFSSL_SMALL_STACK
  8397. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8398. #endif
  8399. return ret;
  8400. }
  8401. }
  8402. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8403. if (saltSz + inOutIdx > *outSz) {
  8404. #ifdef WOLFSSL_SMALL_STACK
  8405. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8406. #endif
  8407. return BUFFER_E;
  8408. }
  8409. XMEMCPY(out + inOutIdx, salt, saltSz);
  8410. inOutIdx += saltSz;
  8411. /* place iteration setting in buffer */
  8412. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8413. if (ret < 0) {
  8414. #ifdef WOLFSSL_SMALL_STACK
  8415. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8416. #endif
  8417. return ret;
  8418. }
  8419. if (inOutIdx + 1 > *outSz) {
  8420. #ifdef WOLFSSL_SMALL_STACK
  8421. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8422. #endif
  8423. return BUFFER_E;
  8424. }
  8425. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8426. /* get pad size and verify buffer room */
  8427. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8428. if (sz + inOutIdx > *outSz) {
  8429. #ifdef WOLFSSL_SMALL_STACK
  8430. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8431. #endif
  8432. return BUFFER_E;
  8433. }
  8434. inOutIdx += SetLength(sz, out + inOutIdx);
  8435. /* copy input to output buffer and pad end */
  8436. XMEMCPY(out + inOutIdx, input, inputSz);
  8437. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8438. #ifdef WOLFSSL_SMALL_STACK
  8439. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8440. if (cbcIv == NULL) {
  8441. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8442. return MEMORY_E;
  8443. }
  8444. #endif
  8445. /* encrypt */
  8446. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8447. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8448. #ifdef WOLFSSL_SMALL_STACK
  8449. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8450. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8451. #endif
  8452. return ret; /* encrypt failure */
  8453. }
  8454. #ifdef WOLFSSL_SMALL_STACK
  8455. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8456. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8457. #endif
  8458. (void)rng;
  8459. return (int)(inOutIdx + sz);
  8460. #else
  8461. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8462. int ret = 0;
  8463. int sz = 0;
  8464. int version = 0;
  8465. int id = -1;
  8466. int blockSz = 0;
  8467. word32 pkcs8Sz = 0;
  8468. (void)heap;
  8469. WOLFSSL_ENTER("EncryptContent");
  8470. /* Must have a output size to return or check. */
  8471. if (outSz == NULL) {
  8472. ret = BAD_FUNC_ARG;
  8473. }
  8474. /* Check salt size is valid. */
  8475. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8476. ret = ASN_PARSE_E;
  8477. }
  8478. /* Get algorithm parameters for algorithm identifier. */
  8479. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8480. ret = ASN_INPUT_E;
  8481. }
  8482. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8483. if ((ret == 0) && (version == PKCS5v2)) {
  8484. ret = BAD_FUNC_ARG;
  8485. }
  8486. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8487. if (ret == 0) {
  8488. /* Setup data to go into encoding including PBE algorithm, salt,
  8489. * iteration count, and padded key length. */
  8490. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8491. oidPBEType);
  8492. if (salt == NULL || saltSz == 0) {
  8493. salt = NULL;
  8494. saltSz = PKCS5_SALT_SZ;
  8495. /* Salt generated into encoding below. */
  8496. }
  8497. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8498. salt, saltSz);
  8499. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8500. (word16)itt);
  8501. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8502. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8503. /* Calculate size of encoding. */
  8504. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8505. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8506. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8507. &sz);
  8508. }
  8509. /* Return size when no output buffer. */
  8510. if ((ret == 0) && (out == NULL)) {
  8511. *outSz = (word32)sz;
  8512. ret = LENGTH_ONLY_E;
  8513. }
  8514. /* Check output buffer is big enough for encoded data. */
  8515. if ((ret == 0) && (sz > (int)*outSz)) {
  8516. ret = BAD_FUNC_ARG;
  8517. }
  8518. if (ret == 0) {
  8519. /* Encode PKCS#8 key. */
  8520. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8521. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8522. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8523. out);
  8524. if (salt == NULL) {
  8525. /* Generate salt into encoding. */
  8526. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8527. data.buffer.data;
  8528. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8529. }
  8530. }
  8531. if (ret == 0) {
  8532. byte cbcIv[MAX_IV_SIZE];
  8533. /* Store PKCS#8 key in output buffer. */
  8534. byte* pkcs8 =
  8535. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8536. XMEMCPY(pkcs8, input, inputSz);
  8537. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8538. /* Encrypt PKCS#8 key inline. */
  8539. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8540. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8541. }
  8542. if (ret == 0) {
  8543. /* Returning size on success. */
  8544. ret = sz;
  8545. }
  8546. FREE_ASNSETDATA(dataASN, heap);
  8547. return ret;
  8548. #endif /* WOLFSSL_ASN_TEMPLATE */
  8549. }
  8550. #endif /* HAVE_PKCS12 */
  8551. #endif /* NO_PWDBASED */
  8552. #ifndef NO_RSA
  8553. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  8554. /* This function is to retrieve key position information in a cert.*
  8555. * The information will be used to call TSIP TLS-linked API for *
  8556. * certificate verification. */
  8557. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8558. word32 inSz, word32* key_n,
  8559. word32* key_n_len, word32* key_e,
  8560. word32* key_e_len)
  8561. {
  8562. int ret = 0;
  8563. int length = 0;
  8564. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8565. byte b;
  8566. #endif
  8567. if (input == NULL || inOutIdx == NULL)
  8568. return BAD_FUNC_ARG;
  8569. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8570. return ASN_PARSE_E;
  8571. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8572. if ((*inOutIdx + 1) > inSz)
  8573. return BUFFER_E;
  8574. b = input[*inOutIdx];
  8575. if (b != ASN_INTEGER) {
  8576. /* not from decoded cert, will have algo id, skip past */
  8577. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8578. return ASN_PARSE_E;
  8579. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8580. return ASN_PARSE_E;
  8581. /* Option NULL ASN.1 tag */
  8582. if (*inOutIdx >= inSz) {
  8583. return BUFFER_E;
  8584. }
  8585. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8586. ret = GetASNNull(input, inOutIdx, inSz);
  8587. if (ret != 0)
  8588. return ret;
  8589. }
  8590. /* TODO: support RSA PSS */
  8591. /* should have bit tag length and seq next */
  8592. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8593. if (ret != 0)
  8594. return ret;
  8595. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8596. return ASN_PARSE_E;
  8597. }
  8598. #endif /* OPENSSL_EXTRA */
  8599. /* Get modulus */
  8600. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8601. *key_n += *inOutIdx;
  8602. if (ret < 0) {
  8603. return ASN_RSA_KEY_E;
  8604. }
  8605. if (key_n_len)
  8606. *key_n_len = length;
  8607. *inOutIdx += length;
  8608. /* Get exponent */
  8609. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8610. *key_e += *inOutIdx;
  8611. if (ret < 0) {
  8612. return ASN_RSA_KEY_E;
  8613. }
  8614. if (key_e_len)
  8615. *key_e_len = length;
  8616. return ret;
  8617. }
  8618. #endif /* WOLFSSL_RENESAS_TSIP */
  8619. #ifdef WOLFSSL_ASN_TEMPLATE
  8620. /* ASN.1 template for an RSA public key.
  8621. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8622. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8623. */
  8624. static const ASNItem rsaPublicKeyASN[] = {
  8625. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8626. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8627. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8628. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8629. #ifdef WC_RSA_PSS
  8630. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8631. #endif
  8632. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8633. /* RSAPublicKey */
  8634. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8635. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8636. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8637. };
  8638. enum {
  8639. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8640. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8641. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8642. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8643. #ifdef WC_RSA_PSS
  8644. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8645. #endif
  8646. RSAPUBLICKEYASN_IDX_PUBKEY,
  8647. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8648. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8649. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8650. };
  8651. /* Number of items in ASN.1 template for an RSA public key. */
  8652. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8653. #endif
  8654. /* Decode RSA public key.
  8655. *
  8656. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8657. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8658. *
  8659. * @param [in] input Buffer holding BER encoded data.
  8660. * @param [in, out] inOutIdx On in, start of RSA public key.
  8661. * On out, start of ASN.1 item after RSA public key.
  8662. * @param [in] inSz Number of bytes in buffer.
  8663. * @param [out] n Pointer to modulus in buffer.
  8664. * @param [out] nSz Size of modulus in bytes.
  8665. * @param [out] e Pointer to exponent in buffer.
  8666. * @param [out] eSz Size of exponent in bytes.
  8667. * @return 0 on success.
  8668. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8669. * is invalid.
  8670. * @return BUFFER_E when data in buffer is too small.
  8671. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8672. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8673. * non-zero length.
  8674. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8675. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8676. */
  8677. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8678. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8679. {
  8680. #ifndef WOLFSSL_ASN_TEMPLATE
  8681. int ret = 0;
  8682. int length = 0;
  8683. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8684. word32 localIdx;
  8685. byte tag;
  8686. #endif
  8687. if (input == NULL || inOutIdx == NULL)
  8688. return BAD_FUNC_ARG;
  8689. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8690. return ASN_PARSE_E;
  8691. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8692. localIdx = *inOutIdx;
  8693. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8694. return BUFFER_E;
  8695. if (tag != ASN_INTEGER) {
  8696. /* not from decoded cert, will have algo id, skip past */
  8697. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8698. return ASN_PARSE_E;
  8699. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8700. return ASN_PARSE_E;
  8701. /* Option NULL ASN.1 tag */
  8702. if (*inOutIdx >= inSz) {
  8703. return BUFFER_E;
  8704. }
  8705. localIdx = *inOutIdx;
  8706. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8707. return ASN_PARSE_E;
  8708. if (tag == ASN_TAG_NULL) {
  8709. ret = GetASNNull(input, inOutIdx, inSz);
  8710. if (ret != 0)
  8711. return ret;
  8712. }
  8713. #ifdef WC_RSA_PSS
  8714. /* Skip RSA PSS parameters. */
  8715. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8716. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8717. return ASN_PARSE_E;
  8718. *inOutIdx += length;
  8719. }
  8720. #endif
  8721. /* should have bit tag length and seq next */
  8722. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8723. if (ret != 0)
  8724. return ret;
  8725. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8726. return ASN_PARSE_E;
  8727. }
  8728. #endif /* OPENSSL_EXTRA */
  8729. /* Get modulus */
  8730. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8731. if (ret < 0) {
  8732. return ASN_RSA_KEY_E;
  8733. }
  8734. if (nSz)
  8735. *nSz = (word32)length;
  8736. if (n)
  8737. *n = &input[*inOutIdx];
  8738. *inOutIdx += (word32)length;
  8739. /* Get exponent */
  8740. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8741. if (ret < 0) {
  8742. return ASN_RSA_KEY_E;
  8743. }
  8744. if (eSz)
  8745. *eSz = (word32)length;
  8746. if (e)
  8747. *e = &input[*inOutIdx];
  8748. *inOutIdx += (word32)length;
  8749. return ret;
  8750. #else
  8751. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8752. int ret = 0;
  8753. #ifdef WC_RSA_PSS
  8754. word32 oid = RSAk;
  8755. #endif
  8756. /* Check validity of parameters. */
  8757. if (input == NULL || inOutIdx == NULL) {
  8758. ret = BAD_FUNC_ARG;
  8759. }
  8760. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8761. if (ret == 0) {
  8762. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8763. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8764. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8765. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8766. 0, input, inOutIdx, inSz);
  8767. if (ret != 0) {
  8768. /* Didn't work - try whole SubjectKeyInfo instead. */
  8769. #ifdef WC_RSA_PSS
  8770. /* Could be RSA or RSA PSS key. */
  8771. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8772. #else
  8773. /* Set the OID to expect. */
  8774. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8775. keyRsaOid, sizeof(keyRsaOid));
  8776. #endif
  8777. /* Decode SubjectKeyInfo. */
  8778. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8779. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8780. inSz);
  8781. }
  8782. }
  8783. #ifdef WC_RSA_PSS
  8784. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8785. /* Two possible OIDs supported - RSA and RSA PSS. */
  8786. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8787. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8788. ret = ASN_PARSE_E;
  8789. }
  8790. }
  8791. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8792. /* Can't have NULL and SEQ. */
  8793. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8794. ret = ASN_PARSE_E;
  8795. }
  8796. /* SEQ present only with RSA PSS. */
  8797. if ((ret == 0) && (oid != RSAPSSk)) {
  8798. ret = ASN_PARSE_E;
  8799. }
  8800. if (ret == 0) {
  8801. enum wc_HashType hash;
  8802. int mgf;
  8803. int saltLen;
  8804. const byte* params = GetASNItem_Addr(
  8805. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8806. word32 paramsSz = GetASNItem_Length(
  8807. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8808. /* Validate the private key parameters. */
  8809. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8810. /* TODO: store parameters so that usage can be checked. */
  8811. }
  8812. }
  8813. #endif
  8814. if (ret == 0) {
  8815. /* Return the buffers and lengths asked for. */
  8816. if (n != NULL) {
  8817. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8818. }
  8819. if (nSz != NULL) {
  8820. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8821. }
  8822. if (e != NULL) {
  8823. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8824. }
  8825. if (eSz != NULL) {
  8826. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8827. }
  8828. }
  8829. FREE_ASNGETDATA(dataASN, NULL);
  8830. return ret;
  8831. #endif /* WOLFSSL_ASN_TEMPLATE */
  8832. }
  8833. /* Decode RSA public key.
  8834. *
  8835. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8836. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8837. *
  8838. * @param [in] input Buffer holding BER encoded data.
  8839. * @param [in, out] inOutIdx On in, start of RSA public key.
  8840. * On out, start of ASN.1 item after RSA public key.
  8841. * @param [in, out] key RSA key object.
  8842. * @param [in] inSz Number of bytes in buffer.
  8843. * @return 0 on success.
  8844. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8845. * is invalid.
  8846. * @return BUFFER_E when data in buffer is too small.
  8847. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8848. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8849. * non-zero length.
  8850. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8851. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8852. */
  8853. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8854. word32 inSz)
  8855. {
  8856. int ret;
  8857. const byte *n = NULL, *e = NULL;
  8858. word32 nSz = 0, eSz = 0;
  8859. if (key == NULL)
  8860. return BAD_FUNC_ARG;
  8861. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8862. if (ret == 0) {
  8863. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8864. }
  8865. return ret;
  8866. }
  8867. #endif /* !NO_RSA */
  8868. #ifndef NO_DH
  8869. #if defined(WOLFSSL_DH_EXTRA)
  8870. /*
  8871. * Decodes DH public key to fill specified DhKey.
  8872. *
  8873. * return 0 on success, negative on failure
  8874. */
  8875. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8876. DhKey* key, word32 inSz)
  8877. {
  8878. int ret = 0;
  8879. int length;
  8880. word32 oid = 0;
  8881. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8882. return BAD_FUNC_ARG;
  8883. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8884. return ASN_PARSE_E;
  8885. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8886. return ASN_PARSE_E;
  8887. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8888. if (oid != DHk || ret < 0)
  8889. return ASN_DH_KEY_E;
  8890. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8891. return ASN_PARSE_E;
  8892. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8893. return ASN_DH_KEY_E;
  8894. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8895. mp_clear(&key->p);
  8896. return ASN_DH_KEY_E;
  8897. }
  8898. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8899. if (ret > 0) {
  8900. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8901. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8902. mp_clear(&key->p);
  8903. mp_clear(&key->g);
  8904. return ASN_DH_KEY_E;
  8905. }
  8906. }
  8907. else {
  8908. mp_clear(&key->p);
  8909. mp_clear(&key->g);
  8910. return ASN_DH_KEY_E;
  8911. }
  8912. return 0;
  8913. }
  8914. #endif /* WOLFSSL_DH_EXTRA */
  8915. #ifdef WOLFSSL_ASN_TEMPLATE
  8916. /* ASN.1 template for DH key.
  8917. * PKCS #3, 9 - DHParameter.
  8918. * (Also in: RFC 2786, 3)
  8919. */
  8920. static const ASNItem dhParamASN[] = {
  8921. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8922. /* prime */
  8923. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8924. /* base */
  8925. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8926. /* privateValueLength */
  8927. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8928. };
  8929. enum {
  8930. DHPARAMASN_IDX_SEQ = 0,
  8931. DHPARAMASN_IDX_PRIME,
  8932. DHPARAMASN_IDX_BASE,
  8933. DHPARAMASN_IDX_PRIVLEN
  8934. };
  8935. /* Number of items in ASN.1 template for DH key. */
  8936. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8937. #ifdef WOLFSSL_DH_EXTRA
  8938. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8939. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8940. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8941. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8942. */
  8943. static const ASNItem dhKeyPkcs8ASN[] = {
  8944. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8945. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8946. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8947. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8948. /* DHParameter */
  8949. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8950. /* p */
  8951. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8952. /* g */
  8953. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8954. /* q - factor of p-1 */
  8955. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8956. /* j - subgroup factor */
  8957. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8958. /* ValidationParms */
  8959. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8960. /* PrivateKey - PKCS #8 */
  8961. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8962. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8963. /* PublicKey - SubjectPublicKeyInfo. */
  8964. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8965. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8966. };
  8967. enum {
  8968. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8969. DHKEYPKCS8ASN_IDX_VER,
  8970. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8971. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8972. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8973. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8974. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8975. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8976. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8977. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8978. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8979. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8980. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8981. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8982. };
  8983. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8984. #endif
  8985. #endif
  8986. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8987. *
  8988. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8989. * object.
  8990. *
  8991. * @param [in] input BER/DER encoded data.
  8992. * @param [in, out] inOutIdx On in, start of DH key data.
  8993. * On out, end of DH key data.
  8994. * @param [in, out] key DH key object.
  8995. * @param [in] inSz Size of data in bytes.
  8996. * @return 0 on success.
  8997. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8998. * @return MEMORY_E when dynamic memory allocation fails.
  8999. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9000. * is invalid.
  9001. * @return BUFFER_E when data in buffer is too small.
  9002. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9003. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9004. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9005. * non-zero length.
  9006. * @return MP_INIT_E when the unable to initialize an mp_int.
  9007. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  9008. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9009. */
  9010. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  9011. {
  9012. #ifndef WOLFSSL_ASN_TEMPLATE
  9013. int ret = 0;
  9014. int length;
  9015. #ifdef WOLFSSL_DH_EXTRA
  9016. #if !defined(HAVE_FIPS) || \
  9017. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  9018. word32 oid = 0, temp = 0;
  9019. #endif
  9020. #endif
  9021. WOLFSSL_ENTER("wc_DhKeyDecode");
  9022. if (inOutIdx == NULL)
  9023. return BAD_FUNC_ARG;
  9024. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9025. return ASN_PARSE_E;
  9026. #ifdef WOLFSSL_DH_EXTRA
  9027. #if !defined(HAVE_FIPS) || \
  9028. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  9029. temp = *inOutIdx;
  9030. #endif
  9031. #endif
  9032. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  9033. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  9034. ret = ASN_DH_KEY_E;
  9035. }
  9036. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  9037. mp_clear(&key->p);
  9038. ret = ASN_DH_KEY_E;
  9039. }
  9040. #ifdef WOLFSSL_DH_EXTRA
  9041. #if !defined(HAVE_FIPS) || \
  9042. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  9043. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  9044. if (ret == ASN_DH_KEY_E) {
  9045. *inOutIdx = temp;
  9046. /* the version (0) - private only (for public skip) */
  9047. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  9048. *inOutIdx += (word32)length;
  9049. }
  9050. /* Size of dhKeyAgreement section */
  9051. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9052. return ASN_PARSE_E;
  9053. /* Check for dhKeyAgreement */
  9054. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  9055. if (oid != DHk || ret < 0)
  9056. return ASN_DH_KEY_E;
  9057. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9058. return ASN_PARSE_E;
  9059. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  9060. return ASN_DH_KEY_E;
  9061. }
  9062. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  9063. mp_clear(&key->p);
  9064. return ASN_DH_KEY_E;
  9065. }
  9066. }
  9067. temp = *inOutIdx;
  9068. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  9069. if (ret > 0) {
  9070. /* Found Bit String */
  9071. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  9072. WOLFSSL_MSG("Found Public Key");
  9073. ret = 0;
  9074. }
  9075. } else {
  9076. *inOutIdx = temp;
  9077. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  9078. if (ret > 0) {
  9079. /* Found Octet String */
  9080. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  9081. WOLFSSL_MSG("Found Private Key");
  9082. /* Compute public */
  9083. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  9084. }
  9085. } else {
  9086. /* Don't use length from failed CheckBitString/GetOctetString */
  9087. *inOutIdx = temp;
  9088. ret = 0;
  9089. }
  9090. }
  9091. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  9092. #endif /* WOLFSSL_DH_EXTRA */
  9093. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  9094. return ret;
  9095. #else
  9096. #ifdef WOLFSSL_DH_EXTRA
  9097. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  9098. #else
  9099. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9100. #endif
  9101. int ret = 0;
  9102. /* Check input parameters are valid. */
  9103. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9104. ret = BAD_FUNC_ARG;
  9105. }
  9106. #ifdef WOLFSSL_DH_EXTRA
  9107. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  9108. #else
  9109. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  9110. #endif
  9111. if (ret == 0) {
  9112. /* Initialize data and set mp_ints to hold p and g. */
  9113. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  9114. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9115. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9116. /* Try simple PKCS #3 template. */
  9117. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9118. inOutIdx, inSz);
  9119. #ifdef WOLFSSL_DH_EXTRA
  9120. if (ret != 0) {
  9121. mp_free(&key->p);
  9122. mp_free(&key->g);
  9123. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  9124. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  9125. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  9126. keyDhOid, sizeof(keyDhOid));
  9127. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9128. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9129. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  9130. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9131. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9132. /* Try PKCS #8 wrapped template. */
  9133. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  9134. input, inOutIdx, inSz);
  9135. if (ret == 0) {
  9136. /* VERSION only present in PKCS #8 private key structure */
  9137. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  9138. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  9139. ret = ASN_PARSE_E;
  9140. }
  9141. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  9142. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  9143. ret = ASN_PARSE_E;
  9144. }
  9145. }
  9146. if ((ret == 0) && mp_iszero(&key->pub)) {
  9147. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  9148. }
  9149. }
  9150. #endif
  9151. }
  9152. FREE_ASNGETDATA(dataASN, key->heap);
  9153. return ret;
  9154. #endif /* WOLFSSL_ASN_TEMPLATE */
  9155. }
  9156. #ifdef WOLFSSL_DH_EXTRA
  9157. /* Export DH Key (private or public) */
  9158. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  9159. {
  9160. #ifndef WOLFSSL_ASN_TEMPLATE
  9161. int ret, privSz = 0, pubSz = 0;
  9162. word32 keySz, idx, len, total;
  9163. if (key == NULL || outSz == NULL) {
  9164. return BAD_FUNC_ARG;
  9165. }
  9166. /* determine size */
  9167. if (exportPriv) {
  9168. /* octet string: priv */
  9169. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9170. if (privSz < 0)
  9171. return privSz;
  9172. idx = 1 + SetLength((word32)privSz, NULL) +
  9173. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9174. }
  9175. else {
  9176. /* bit string: public */
  9177. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9178. if (pubSz < 0)
  9179. return pubSz;
  9180. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9181. }
  9182. keySz = idx;
  9183. /* DH Parameters sequence with P and G */
  9184. total = 0;
  9185. ret = wc_DhParamsToDer(key, NULL, &total);
  9186. if (ret != LENGTH_ONLY_E)
  9187. return ret;
  9188. idx += total;
  9189. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9190. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9191. idx += (word32)sizeof(keyDhOid);
  9192. len = idx - keySz;
  9193. /* sequence - all but pub/priv */
  9194. idx += SetSequence(len, NULL);
  9195. if (exportPriv) {
  9196. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9197. idx += 3;
  9198. }
  9199. /* sequence */
  9200. total = idx + SetSequence(idx, NULL);
  9201. /* if no output, then just getting size */
  9202. if (output == NULL) {
  9203. *outSz = total;
  9204. return LENGTH_ONLY_E;
  9205. }
  9206. /* make sure output fits in buffer */
  9207. if (total > *outSz) {
  9208. return BUFFER_E;
  9209. }
  9210. total = idx;
  9211. /* sequence */
  9212. idx = SetSequence(total, output);
  9213. if (exportPriv) {
  9214. /* version: 0 */
  9215. idx += (word32)SetMyVersion(0, output + idx, 0);
  9216. }
  9217. /* sequence - all but pub/priv */
  9218. idx += SetSequence(len, output + idx);
  9219. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9220. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9221. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9222. idx += sizeof(keyDhOid);
  9223. /* DH Parameters sequence with P and G */
  9224. total = *outSz - idx;
  9225. ret = wc_DhParamsToDer(key, output + idx, &total);
  9226. if (ret < 0)
  9227. return ret;
  9228. idx += total;
  9229. /* octet string: priv */
  9230. if (exportPriv) {
  9231. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9232. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9233. }
  9234. else {
  9235. /* bit string: public */
  9236. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9237. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9238. }
  9239. *outSz = idx;
  9240. return (int)idx;
  9241. #else
  9242. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9243. int ret = 0;
  9244. int sz;
  9245. WOLFSSL_ENTER("wc_DhKeyToDer");
  9246. XMEMSET(dataASN, 0, sizeof(dataASN));
  9247. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9248. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9249. /* Set mp_int containing p and g. */
  9250. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9251. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9252. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9253. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9254. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9255. if (exportPriv) {
  9256. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9257. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9258. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9259. }
  9260. else {
  9261. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9262. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9263. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9264. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9265. }
  9266. /* Calculate the size of the DH parameters. */
  9267. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9268. if (output == NULL) {
  9269. *outSz = (word32)sz;
  9270. ret = LENGTH_ONLY_E;
  9271. }
  9272. /* Check buffer is big enough for encoding. */
  9273. if ((ret == 0) && ((int)*outSz < sz)) {
  9274. ret = BUFFER_E;
  9275. }
  9276. if (ret == 0) {
  9277. /* Encode the DH parameters into buffer. */
  9278. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9279. /* Set the actual encoding size. */
  9280. *outSz = (word32)sz;
  9281. /* Return the actual encoding size. */
  9282. ret = sz;
  9283. }
  9284. return ret;
  9285. #endif
  9286. }
  9287. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9288. {
  9289. return wc_DhKeyToDer(key, out, outSz, 0);
  9290. }
  9291. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9292. {
  9293. return wc_DhKeyToDer(key, out, outSz, 1);
  9294. }
  9295. /* Convert DH key parameters to DER format, write to output (outSz)
  9296. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9297. * returned.
  9298. *
  9299. * Note : static function due to redefinition complications with DhKey and FIPS
  9300. * version 2 build.
  9301. *
  9302. * return bytes written on success */
  9303. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9304. {
  9305. #ifndef WOLFSSL_ASN_TEMPLATE
  9306. int ret;
  9307. word32 idx, total;
  9308. if (key == NULL || outSz == NULL) {
  9309. return BAD_FUNC_ARG;
  9310. }
  9311. /* determine size */
  9312. /* integer - g */
  9313. ret = SetASNIntMP(&key->g, -1, NULL);
  9314. if (ret < 0)
  9315. return ret;
  9316. idx = (word32)ret;
  9317. /* integer - p */
  9318. ret = SetASNIntMP(&key->p, -1, NULL);
  9319. if (ret < 0)
  9320. return ret;
  9321. idx += (word32)ret;
  9322. total = idx;
  9323. /* sequence */
  9324. idx += SetSequence(idx, NULL);
  9325. if (output == NULL) {
  9326. *outSz = idx;
  9327. return LENGTH_ONLY_E;
  9328. }
  9329. /* make sure output fits in buffer */
  9330. if (idx > *outSz) {
  9331. return BUFFER_E;
  9332. }
  9333. /* write DH parameters */
  9334. /* sequence - for P and G only */
  9335. idx = SetSequence(total, output);
  9336. /* integer - p */
  9337. ret = SetASNIntMP(&key->p, -1, output + idx);
  9338. if (ret < 0)
  9339. return ret;
  9340. idx += (word32)ret;
  9341. /* integer - g */
  9342. ret = SetASNIntMP(&key->g, -1, output + idx);
  9343. if (ret < 0)
  9344. return ret;
  9345. idx += (word32)ret;
  9346. *outSz = idx;
  9347. return (int)idx;
  9348. #else
  9349. ASNSetData dataASN[dhParamASN_Length];
  9350. int ret = 0;
  9351. int sz = 0;
  9352. WOLFSSL_ENTER("wc_DhParamsToDer");
  9353. if (key == NULL || outSz == NULL) {
  9354. ret = BAD_FUNC_ARG;
  9355. }
  9356. if (ret == 0) {
  9357. XMEMSET(dataASN, 0, sizeof(dataASN));
  9358. /* Set mp_int containing p and g. */
  9359. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9360. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9361. /* privateValueLength not encoded. */
  9362. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9363. /* Calculate the size of the DH parameters. */
  9364. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9365. }
  9366. if ((ret == 0) && (output == NULL)) {
  9367. *outSz = (word32)sz;
  9368. ret = LENGTH_ONLY_E;
  9369. }
  9370. /* Check buffer is big enough for encoding. */
  9371. if ((ret == 0) && (*outSz < (word32)sz)) {
  9372. ret = BUFFER_E;
  9373. }
  9374. if (ret == 0) {
  9375. /* Encode the DH parameters into buffer. */
  9376. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9377. /* Set the actual encoding size. */
  9378. *outSz = (word32)sz;
  9379. /* Return count of bytes written. */
  9380. ret = sz;
  9381. }
  9382. return ret;
  9383. #endif
  9384. }
  9385. #endif /* WOLFSSL_DH_EXTRA */
  9386. /* Decode DH parameters.
  9387. *
  9388. * PKCS #3, 9 - DHParameter.
  9389. * (Also in: RFC 2786, 3)
  9390. *
  9391. * @param [in] input Buffer holding BER encoded data.
  9392. * @param [in, out] inOutIdx On in, start of RSA public key.
  9393. * On out, start of ASN.1 item after RSA public key.
  9394. * @param [in] inSz Number of bytes in buffer.
  9395. * @param [in, out] p Buffer to hold prime.
  9396. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9397. * On out, size of prime in bytes.
  9398. * @param [in, out] g Buffer to hold base.
  9399. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9400. * On out, size of base in bytes.
  9401. * @return 0 on success.
  9402. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9403. * is invalid.
  9404. * @return BUFFER_E when data in buffer is too small.
  9405. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9406. */
  9407. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9408. byte* g, word32* gInOutSz)
  9409. {
  9410. #ifndef WOLFSSL_ASN_TEMPLATE
  9411. word32 idx = 0;
  9412. int ret;
  9413. int length;
  9414. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9415. return ASN_PARSE_E;
  9416. ret = GetASNInt(input, &idx, &length, inSz);
  9417. if (ret != 0)
  9418. return ret;
  9419. if (length <= (int)*pInOutSz) {
  9420. XMEMCPY(p, &input[idx], (size_t)length);
  9421. *pInOutSz = (word32)length;
  9422. }
  9423. else {
  9424. return BUFFER_E;
  9425. }
  9426. idx += (word32)length;
  9427. ret = GetASNInt(input, &idx, &length, inSz);
  9428. if (ret != 0)
  9429. return ret;
  9430. if (length <= (int)*gInOutSz) {
  9431. XMEMCPY(g, &input[idx], (size_t)length);
  9432. *gInOutSz = (word32)length;
  9433. }
  9434. else {
  9435. return BUFFER_E;
  9436. }
  9437. return 0;
  9438. #else
  9439. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9440. word32 idx = 0;
  9441. int ret = 0;
  9442. /* Make sure pointers are valid before use. */
  9443. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9444. (gInOutSz == NULL)) {
  9445. ret = BAD_FUNC_ARG;
  9446. }
  9447. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9448. if (ret == 0) {
  9449. /* Set the buffers to copy p and g into. */
  9450. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9451. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9452. /* Decode the DH Parameters. */
  9453. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9454. &idx, inSz);
  9455. }
  9456. FREE_ASNGETDATA(dataASN, NULL);
  9457. return ret;
  9458. #endif /* WOLFSSL_ASN_TEMPLATE */
  9459. }
  9460. #endif /* !NO_DH */
  9461. #ifndef NO_DSA
  9462. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9463. {
  9464. if (idx == 0)
  9465. return &key->p;
  9466. if (idx == 1)
  9467. return &key->q;
  9468. if (idx == 2)
  9469. return &key->g;
  9470. if (idx == 3)
  9471. return &key->y;
  9472. if (idx == 4)
  9473. return &key->x;
  9474. return NULL;
  9475. }
  9476. #ifdef WOLFSSL_ASN_TEMPLATE
  9477. /* ASN.1 template for DSA public and private keys.
  9478. * Public key: seq, p, q, g, y
  9479. * Private key: seq, version, p, q, g, y, x
  9480. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9481. */
  9482. static const ASNItem dsaKeyASN[] = {
  9483. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9484. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9485. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9486. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9487. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9488. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9489. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9490. };
  9491. enum {
  9492. DSAKEYASN_IDX_SEQ = 0,
  9493. DSAKEYASN_IDX_VER,
  9494. DSAKEYASN_IDX_P,
  9495. DSAKEYASN_IDX_Q,
  9496. DSAKEYASN_IDX_G,
  9497. DSAKEYASN_IDX_Y,
  9498. DSAKEYASN_IDX_X
  9499. };
  9500. /* Number of items in ASN.1 template for DSA private key. */
  9501. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9502. /* Number of items in ASN.1 template for DSA public key. */
  9503. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9504. /* ASN.1 template for PublicKeyInfo with DSA.
  9505. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9506. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9507. */
  9508. static const ASNItem dsaPubKeyASN[] = {
  9509. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9510. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9511. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9512. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9513. /* p */
  9514. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9515. /* q */
  9516. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9517. /* g */
  9518. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9519. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9520. /* y */
  9521. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9522. };
  9523. enum {
  9524. DSAPUBKEYASN_IDX_SEQ = 0,
  9525. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9526. DSAPUBKEYASN_IDX_ALGOID_OID,
  9527. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9528. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9529. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9530. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9531. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9532. DSAPUBKEYASN_IDX_PUBKEY_Y
  9533. };
  9534. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9535. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9536. #endif /* WOLFSSL_ASN_TEMPLATE */
  9537. /* Decode DSA public key.
  9538. *
  9539. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9540. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9541. *
  9542. * @param [in] input Buffer holding BER encoded data.
  9543. * @param [in, out] inOutIdx On in, start of DSA public key.
  9544. * On out, start of ASN.1 item after DSA public key.
  9545. * @param [in, out] key DSA key object.
  9546. * @param [in] inSz Number of bytes in buffer.
  9547. * @return 0 on success.
  9548. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9549. * is invalid.
  9550. * @return BUFFER_E when data in buffer is too small.
  9551. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9552. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9553. * non-zero length.
  9554. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9555. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9556. */
  9557. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9558. word32 inSz)
  9559. {
  9560. #ifndef WOLFSSL_ASN_TEMPLATE
  9561. int length;
  9562. int ret = 0;
  9563. word32 oid;
  9564. word32 maxIdx;
  9565. if (input == NULL || inOutIdx == NULL || key == NULL)
  9566. return BAD_FUNC_ARG;
  9567. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9568. return ASN_PARSE_E;
  9569. maxIdx = (word32)(*inOutIdx + (word32)length);
  9570. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9571. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9572. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9573. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9574. ret = ASN_DH_KEY_E;
  9575. if (ret != 0) {
  9576. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9577. return ASN_PARSE_E;
  9578. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9579. if (ret != 0)
  9580. return ret;
  9581. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9582. return ASN_PARSE_E;
  9583. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9584. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9585. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9586. return ASN_DH_KEY_E;
  9587. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9588. return ASN_PARSE_E;
  9589. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9590. return ASN_DH_KEY_E;
  9591. ret = 0;
  9592. }
  9593. key->type = DSA_PUBLIC;
  9594. return ret;
  9595. #else
  9596. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9597. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9598. int ret = 0;
  9599. /* Validated parameters. */
  9600. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9601. ret = BAD_FUNC_ARG;
  9602. }
  9603. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9604. if (ret == 0) {
  9605. int i;
  9606. /* Clear dynamic data items. */
  9607. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9608. /* seq
  9609. * p, q, g, y
  9610. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9611. for (i = 0; i < DSA_INTS - 1; i++)
  9612. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9613. /* Parse as simple form. */
  9614. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9615. inOutIdx, inSz);
  9616. if (ret != 0) {
  9617. /* Clear dynamic data items. */
  9618. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9619. /* Set DSA OID to expect. */
  9620. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9621. keyDsaOid, sizeof(keyDsaOid));
  9622. /* p, q, g */
  9623. for (i = 0; i < DSA_INTS - 2; i++)
  9624. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9625. GetDsaInt(key, i));
  9626. /* y */
  9627. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9628. /* Parse as SubjectPublicKeyInfo. */
  9629. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9630. input, inOutIdx, inSz);
  9631. }
  9632. }
  9633. if (ret == 0) {
  9634. /* Data parsed - set type of key parsed. */
  9635. key->type = DSA_PUBLIC;
  9636. }
  9637. FREE_ASNGETDATA(dataASN, key->heap);
  9638. return ret;
  9639. #endif
  9640. }
  9641. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9642. word32 inSz)
  9643. {
  9644. int length;
  9645. word32 maxIdx;
  9646. if (input == NULL || inOutIdx == NULL || key == NULL)
  9647. return BAD_FUNC_ARG;
  9648. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9649. return ASN_PARSE_E;
  9650. maxIdx = (word32)(*inOutIdx + (word32)length);
  9651. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9652. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9653. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9654. return ASN_DH_KEY_E;
  9655. return 0;
  9656. }
  9657. #ifdef WOLFSSL_ASN_TEMPLATE
  9658. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9659. static const ASNItem dsaKeyOctASN[] = {
  9660. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9661. /* p */
  9662. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9663. /* q */
  9664. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9665. /* g */
  9666. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9667. /* Private key */
  9668. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9669. /* x */
  9670. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9671. };
  9672. enum {
  9673. DSAKEYOCTASN_IDX_SEQ = 0,
  9674. DSAKEYOCTASN_IDX_P,
  9675. DSAKEYOCTASN_IDX_Q,
  9676. DSAKEYOCTASN_IDX_G,
  9677. DSAKEYOCTASN_IDX_PKEY_STR,
  9678. DSAKEYOCTASN_IDX_X
  9679. };
  9680. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9681. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9682. #endif
  9683. /* Decode DSA private key.
  9684. *
  9685. * @param [in] input Buffer holding BER encoded data.
  9686. * @param [in, out] inOutIdx On in, start of DSA public key.
  9687. * On out, start of ASN.1 item after DSA public key.
  9688. * @param [in, out] key DSA key object.
  9689. * @param [in] inSz Number of bytes in buffer.
  9690. * @return 0 on success.
  9691. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9692. * is invalid.
  9693. * @return BUFFER_E when data in buffer is too small.
  9694. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9695. * non-zero length.
  9696. */
  9697. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9698. word32 inSz)
  9699. {
  9700. #ifndef WOLFSSL_ASN_TEMPLATE
  9701. int length, version, ret = 0, temp = 0;
  9702. word32 algId = 0;
  9703. /* Sanity checks on input */
  9704. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9705. return BAD_FUNC_ARG;
  9706. }
  9707. /* if has pkcs8 header skip it */
  9708. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9709. /* ignore error, did not have pkcs8 header */
  9710. }
  9711. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9712. return ASN_PARSE_E;
  9713. temp = (int)*inOutIdx;
  9714. /* Default case expects a certificate with OctetString but no version ID */
  9715. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9716. if (ret < 0) {
  9717. mp_clear(&key->p);
  9718. ret = ASN_PARSE_E;
  9719. }
  9720. else {
  9721. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9722. if (ret < 0) {
  9723. mp_clear(&key->p);
  9724. mp_clear(&key->q);
  9725. ret = ASN_PARSE_E;
  9726. }
  9727. else {
  9728. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9729. if (ret < 0) {
  9730. mp_clear(&key->p);
  9731. mp_clear(&key->q);
  9732. mp_clear(&key->g);
  9733. ret = ASN_PARSE_E;
  9734. }
  9735. else {
  9736. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9737. if (ret < 0) {
  9738. mp_clear(&key->p);
  9739. mp_clear(&key->q);
  9740. mp_clear(&key->g);
  9741. ret = ASN_PARSE_E;
  9742. }
  9743. else {
  9744. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9745. if (ret < 0) {
  9746. mp_clear(&key->p);
  9747. mp_clear(&key->q);
  9748. mp_clear(&key->g);
  9749. mp_clear(&key->y);
  9750. ret = ASN_PARSE_E;
  9751. }
  9752. }
  9753. }
  9754. }
  9755. }
  9756. /* An alternate pass if default certificate fails parsing */
  9757. if (ret == ASN_PARSE_E) {
  9758. *inOutIdx = (word32)temp;
  9759. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9760. return ASN_PARSE_E;
  9761. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9762. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9763. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9764. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9765. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9766. return ASN_DH_KEY_E;
  9767. }
  9768. key->type = DSA_PRIVATE;
  9769. return 0;
  9770. #else
  9771. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9772. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9773. int ret = 0;
  9774. byte version = 0;
  9775. /* Sanity checks on input */
  9776. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9777. ret = BAD_FUNC_ARG;
  9778. }
  9779. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9780. if (ret == 0) {
  9781. int i;
  9782. /* Try dsaKeyOctASN */
  9783. /* Initialize key data and set mp_ints for params */
  9784. for (i = 0; i < DSA_INTS - 2; i++) {
  9785. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9786. }
  9787. /* and priv */
  9788. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9789. /* Try simple form. */
  9790. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9791. inOutIdx, inSz);
  9792. if (ret != 0) {
  9793. /* Try dsaKeyASN */
  9794. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9795. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9796. for (i = 0; i < DSA_INTS; i++) {
  9797. mp_int* n = GetDsaInt(key, i);
  9798. mp_clear(n);
  9799. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9800. }
  9801. /* Try simple OCTET_STRING form. */
  9802. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9803. inOutIdx, inSz);
  9804. }
  9805. }
  9806. if (ret == 0) {
  9807. /* Set the contents to be a private key. */
  9808. key->type = DSA_PRIVATE;
  9809. }
  9810. FREE_ASNGETDATA(dataASN, key->heap);
  9811. return ret;
  9812. #endif
  9813. }
  9814. #ifndef WOLFSSL_ASN_TEMPLATE
  9815. /* Release Tmp DSA resources */
  9816. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9817. {
  9818. int i;
  9819. for (i = 0; i < ints; i++)
  9820. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9821. (void)heap;
  9822. }
  9823. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9824. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9825. defined(WOLFSSL_CERT_GEN))
  9826. /* Encode a DSA public key into buffer.
  9827. *
  9828. * @param [out] output Buffer to hold encoded data.
  9829. * @param [in] key DSA key object.
  9830. * @param [out] outLen Length of buffer.
  9831. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9832. * @return Size of encoded data in bytes on success.
  9833. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9834. * than a minimal size (5 bytes), or buffer size is smaller than
  9835. * encoding size.
  9836. * @return MEMORY_E when dynamic memory allocation fails.
  9837. */
  9838. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9839. {
  9840. #ifndef WOLFSSL_ASN_TEMPLATE
  9841. /* p, g, q = DSA params, y = public exponent */
  9842. #ifdef WOLFSSL_SMALL_STACK
  9843. byte* p = NULL;
  9844. byte* g = NULL;
  9845. byte* q = NULL;
  9846. byte* y = NULL;
  9847. #else
  9848. byte p[MAX_DSA_INT_SZ];
  9849. byte g[MAX_DSA_INT_SZ];
  9850. byte q[MAX_DSA_INT_SZ];
  9851. byte y[MAX_DSA_INT_SZ];
  9852. #endif
  9853. byte innerSeq[MAX_SEQ_SZ];
  9854. byte outerSeq[MAX_SEQ_SZ];
  9855. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9856. int pSz, gSz, qSz, ySz;
  9857. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9858. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9859. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9860. return BAD_FUNC_ARG;
  9861. }
  9862. /* p */
  9863. #ifdef WOLFSSL_SMALL_STACK
  9864. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9865. if (p == NULL)
  9866. return MEMORY_E;
  9867. #endif
  9868. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9869. WOLFSSL_MSG("SetASNIntMP Error with p");
  9870. #ifdef WOLFSSL_SMALL_STACK
  9871. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9872. #endif
  9873. return pSz;
  9874. }
  9875. /* q */
  9876. #ifdef WOLFSSL_SMALL_STACK
  9877. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9878. if (q == NULL)
  9879. return MEMORY_E;
  9880. #endif
  9881. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9882. WOLFSSL_MSG("SetASNIntMP Error with q");
  9883. #ifdef WOLFSSL_SMALL_STACK
  9884. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9885. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9886. #endif
  9887. return qSz;
  9888. }
  9889. /* g */
  9890. #ifdef WOLFSSL_SMALL_STACK
  9891. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9892. if (g == NULL)
  9893. return MEMORY_E;
  9894. #endif
  9895. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9896. WOLFSSL_MSG("SetASNIntMP Error with g");
  9897. #ifdef WOLFSSL_SMALL_STACK
  9898. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9899. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9900. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9901. #endif
  9902. return gSz;
  9903. }
  9904. /* y */
  9905. #ifdef WOLFSSL_SMALL_STACK
  9906. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9907. if (y == NULL)
  9908. return MEMORY_E;
  9909. #endif
  9910. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9911. WOLFSSL_MSG("SetASNIntMP Error with y");
  9912. #ifdef WOLFSSL_SMALL_STACK
  9913. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9914. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9915. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9916. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9917. #endif
  9918. return ySz;
  9919. }
  9920. if (with_header) {
  9921. word32 algoSz;
  9922. #ifdef WOLFSSL_SMALL_STACK
  9923. byte* algo = NULL;
  9924. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9925. if (algo == NULL) {
  9926. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9927. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9928. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9929. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9930. return MEMORY_E;
  9931. }
  9932. #else
  9933. byte algo[MAX_ALGO_SZ];
  9934. #endif
  9935. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9936. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9937. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9938. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9939. (word32)(pSz + qSz + gSz), outerSeq);
  9940. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9941. bitStringSz + (word32)ySz + outerSeqSz, output);
  9942. /* check output size */
  9943. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9944. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9945. {
  9946. #ifdef WOLFSSL_SMALL_STACK
  9947. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9948. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9949. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9950. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9951. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9952. #endif
  9953. WOLFSSL_MSG("Error, output size smaller than outlen");
  9954. return BUFFER_E;
  9955. }
  9956. /* outerSeq */
  9957. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9958. idx += outerSeqSz;
  9959. /* algo */
  9960. XMEMCPY(output + idx, algo, algoSz);
  9961. idx += algoSz;
  9962. #ifdef WOLFSSL_SMALL_STACK
  9963. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9964. #endif
  9965. } else {
  9966. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9967. /* check output size */
  9968. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9969. #ifdef WOLFSSL_SMALL_STACK
  9970. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9971. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9972. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9973. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9974. #endif
  9975. WOLFSSL_MSG("Error, output size smaller than outlen");
  9976. return BUFFER_E;
  9977. }
  9978. idx = 0;
  9979. }
  9980. /* innerSeq */
  9981. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9982. idx += innerSeqSz;
  9983. /* p */
  9984. XMEMCPY(output + idx, p, (size_t)pSz);
  9985. idx += (word32)pSz;
  9986. /* q */
  9987. XMEMCPY(output + idx, q, (size_t)qSz);
  9988. idx += (word32)qSz;
  9989. /* g */
  9990. XMEMCPY(output + idx, g, (size_t)gSz);
  9991. idx += (word32)gSz;
  9992. /* bit string */
  9993. if (bitStringSz > 0) {
  9994. XMEMCPY(output + idx, bitString, bitStringSz);
  9995. idx += bitStringSz;
  9996. }
  9997. /* y */
  9998. XMEMCPY(output + idx, y, (size_t)ySz);
  9999. idx += (word32)ySz;
  10000. #ifdef WOLFSSL_SMALL_STACK
  10001. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10002. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10003. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10004. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10005. #endif
  10006. return (int)idx;
  10007. #else
  10008. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  10009. int ret = 0;
  10010. int i;
  10011. int sz = 0;
  10012. const ASNItem *data = NULL;
  10013. int count = 0;
  10014. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  10015. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  10016. ret = BAD_FUNC_ARG;
  10017. }
  10018. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  10019. if (ret == 0) {
  10020. if (with_header) {
  10021. /* Using dsaPubKeyASN */
  10022. data = dsaPubKeyASN;
  10023. count = dsaPubKeyASN_Length;
  10024. /* Set the algorithm OID to write out. */
  10025. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  10026. /* Set the mp_ints to encode - parameters and public value. */
  10027. for (i = 0; i < DSA_INTS - 2; i++) {
  10028. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  10029. GetDsaInt(key, i));
  10030. }
  10031. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  10032. }
  10033. else {
  10034. /* Using dsaKeyASN */
  10035. data = dsaKeyASN;
  10036. count = dsaPublicKeyASN_Length;
  10037. /* Set the mp_ints to encode - parameters and public value. */
  10038. for (i = 0; i < DSA_INTS - 1; i++) {
  10039. /* Move all DSA ints up one slot (ignore VERSION so now
  10040. * it means P) */
  10041. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  10042. GetDsaInt(key, i));
  10043. }
  10044. }
  10045. ret = SizeASN_Items(data, dataASN, count, &sz);
  10046. }
  10047. /* Check buffer is big enough for encoding. */
  10048. if ((ret == 0) && (sz > (int)outLen)) {
  10049. ret = BAD_FUNC_ARG;
  10050. }
  10051. /* Encode the DSA public key into output buffer. */
  10052. if (ret == 0) {
  10053. ret = SetASN_Items(data, dataASN, count, output);
  10054. }
  10055. FREE_ASNSETDATA(dataASN, key->heap);
  10056. return ret;
  10057. #endif /* WOLFSSL_ASN_TEMPLATE */
  10058. }
  10059. /* Encode a DSA public key into buffer.
  10060. *
  10061. * @param [out] output Buffer to hold encoded data.
  10062. * @param [in] key DSA key object.
  10063. * @param [out] outLen Length of buffer.
  10064. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  10065. * @return Size of encoded data in bytes on success.
  10066. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  10067. * than a minimal size (5 bytes), or buffer size is smaller than
  10068. * encoding size.
  10069. * @return MEMORY_E when dynamic memory allocation fails.
  10070. */
  10071. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  10072. {
  10073. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  10074. }
  10075. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  10076. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  10077. int ints, int includeVersion)
  10078. {
  10079. #ifndef WOLFSSL_ASN_TEMPLATE
  10080. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  10081. word32 sizes[DSA_INTS];
  10082. int i, ret = 0;
  10083. byte seq[MAX_SEQ_SZ];
  10084. byte ver[MAX_VERSION_SZ];
  10085. byte* tmps[DSA_INTS];
  10086. if (ints > DSA_INTS || inLen == NULL)
  10087. return BAD_FUNC_ARG;
  10088. XMEMSET(sizes, 0, sizeof(sizes));
  10089. for (i = 0; i < ints; i++)
  10090. tmps[i] = NULL;
  10091. /* write all big ints from key to DER tmps */
  10092. for (i = 0; i < ints; i++) {
  10093. int mpSz;
  10094. mp_int* keyInt = GetDsaInt(key, i);
  10095. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  10096. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  10097. DYNAMIC_TYPE_DSA);
  10098. if (tmps[i] == NULL) {
  10099. ret = MEMORY_E;
  10100. break;
  10101. }
  10102. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  10103. if (mpSz < 0) {
  10104. ret = mpSz;
  10105. break;
  10106. }
  10107. sizes[i] = (word32)mpSz;
  10108. intTotalLen += (word32)mpSz;
  10109. }
  10110. if (ret != 0) {
  10111. FreeTmpDsas(tmps, key->heap, ints);
  10112. return ret;
  10113. }
  10114. /* make headers */
  10115. if (includeVersion)
  10116. verSz = (word32)SetMyVersion(0, ver, FALSE);
  10117. seqSz = SetSequence(verSz + intTotalLen, seq);
  10118. outLen = seqSz + verSz + intTotalLen;
  10119. *inLen = outLen;
  10120. if (output == NULL) {
  10121. FreeTmpDsas(tmps, key->heap, ints);
  10122. return LENGTH_ONLY_E;
  10123. }
  10124. if (outLen > *inLen) {
  10125. FreeTmpDsas(tmps, key->heap, ints);
  10126. return BAD_FUNC_ARG;
  10127. }
  10128. /* write to output */
  10129. XMEMCPY(output, seq, seqSz);
  10130. j = seqSz;
  10131. if (includeVersion) {
  10132. XMEMCPY(output + j, ver, verSz);
  10133. j += verSz;
  10134. }
  10135. for (i = 0; i < ints; i++) {
  10136. XMEMCPY(output + j, tmps[i], sizes[i]);
  10137. j += sizes[i];
  10138. }
  10139. FreeTmpDsas(tmps, key->heap, ints);
  10140. return (int)outLen;
  10141. #else
  10142. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  10143. int ret = 0;
  10144. int sz = 0;
  10145. (void)ints;
  10146. if ((key == NULL) || (inLen == NULL)) {
  10147. ret = BAD_FUNC_ARG;
  10148. }
  10149. if ((ret == 0) && (ints > DSA_INTS)) {
  10150. ret = BAD_FUNC_ARG;
  10151. }
  10152. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  10153. if (ret == 0) {
  10154. int i;
  10155. if (includeVersion) {
  10156. /* Set the version. */
  10157. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  10158. }
  10159. else {
  10160. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  10161. }
  10162. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10163. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10164. /* Set the mp_ints to encode - params, public and private value. */
  10165. for (i = 0; i < DSA_INTS; i++) {
  10166. if (i < ints)
  10167. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10168. else
  10169. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10170. }
  10171. /* Calculate size of the encoding. */
  10172. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10173. }
  10174. if ((ret == 0) && (output == NULL)) {
  10175. *inLen = (word32)sz;
  10176. ret = LENGTH_ONLY_E;
  10177. }
  10178. /* Check buffer is big enough for encoding. */
  10179. if ((ret == 0) && (sz > (int)*inLen)) {
  10180. ret = BAD_FUNC_ARG;
  10181. }
  10182. if (ret == 0) {
  10183. /* Encode the DSA private key into output buffer. */
  10184. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10185. /* Return the size of the encoding. */
  10186. ret = sz;
  10187. }
  10188. FREE_ASNSETDATA(dataASN, key->heap);
  10189. return ret;
  10190. #endif /* WOLFSSL_ASN_TEMPLATE */
  10191. }
  10192. /* Encode a DSA private key into buffer.
  10193. *
  10194. * @param [in] key DSA key object.
  10195. * @param [out] output Buffer to hold encoded data.
  10196. * @param [out] inLen Length of buffer.
  10197. * @return Size of encoded data in bytes on success.
  10198. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10199. * or, buffer size is smaller than encoding size.
  10200. * @return MEMORY_E when dynamic memory allocation fails.
  10201. */
  10202. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10203. {
  10204. if (!key || !output)
  10205. return BAD_FUNC_ARG;
  10206. if (key->type != DSA_PRIVATE)
  10207. return BAD_FUNC_ARG;
  10208. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10209. }
  10210. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10211. return bytes written. Version is excluded to be compatible with
  10212. OpenSSL d2i_DSAparams */
  10213. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10214. {
  10215. if (!key || !output)
  10216. return BAD_FUNC_ARG;
  10217. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10218. }
  10219. /* This version of the function allows output to be NULL. In that case, the
  10220. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10221. size will be pointed to by inLen. */
  10222. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10223. {
  10224. if (!key || !inLen)
  10225. return BAD_FUNC_ARG;
  10226. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10227. }
  10228. #endif /* NO_DSA */
  10229. #ifndef NO_CERTS
  10230. /* Initialize decoded certificate object with buffer of DER encoding.
  10231. *
  10232. * @param [in, out] cert Decoded certificate object.
  10233. * @param [in] source Buffer containing DER encoded certificate.
  10234. * @param [in] inSz Size of DER data in buffer in bytes.
  10235. * @param [in] heap Dynamic memory hint.
  10236. */
  10237. void InitDecodedCert(DecodedCert* cert,
  10238. const byte* source, word32 inSz, void* heap)
  10239. {
  10240. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10241. }
  10242. /* Initialize decoded certificate object with buffer of DER encoding.
  10243. *
  10244. * @param [in, out] cert Decoded certificate object.
  10245. * @param [in] source Buffer containing DER encoded certificate.
  10246. * @param [in] inSz Size of DER data in buffer in bytes.
  10247. * @param [in] heap Dynamic memory hint.
  10248. * @param [in] devId Crypto callback ID to use.
  10249. */
  10250. void InitDecodedCert_ex(DecodedCert* cert,
  10251. const byte* source, word32 inSz, void* heap, int devId)
  10252. {
  10253. if (cert != NULL) {
  10254. XMEMSET(cert, 0, sizeof(DecodedCert));
  10255. cert->subjectCNEnc = CTC_UTF8;
  10256. cert->issuer[0] = '\0';
  10257. cert->subject[0] = '\0';
  10258. cert->source = source; /* don't own */
  10259. cert->maxIdx = inSz; /* can't go over this index */
  10260. cert->heap = heap;
  10261. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10262. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10263. #ifdef WOLFSSL_CERT_NAME_ALL
  10264. cert->subjectNEnc = CTC_UTF8;
  10265. cert->subjectIEnc = CTC_UTF8;
  10266. cert->subjectDNQEnc = CTC_UTF8;
  10267. cert->subjectGNEnc = CTC_UTF8;
  10268. #endif
  10269. cert->subjectSNEnc = CTC_UTF8;
  10270. cert->subjectCEnc = CTC_PRINTABLE;
  10271. cert->subjectLEnc = CTC_UTF8;
  10272. cert->subjectSTEnc = CTC_UTF8;
  10273. cert->subjectOEnc = CTC_UTF8;
  10274. cert->subjectOUEnc = CTC_UTF8;
  10275. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10276. cert->issuerSNEnc = CTC_UTF8;
  10277. cert->issuerCEnc = CTC_PRINTABLE;
  10278. cert->issuerLEnc = CTC_UTF8;
  10279. cert->issuerSTEnc = CTC_UTF8;
  10280. cert->issuerOEnc = CTC_UTF8;
  10281. cert->issuerOUEnc = CTC_UTF8;
  10282. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10283. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10284. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10285. }
  10286. }
  10287. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10288. void* heap)
  10289. {
  10290. InitDecodedCert(cert, source, inSz, heap);
  10291. }
  10292. /* Free the alternative names object.
  10293. *
  10294. * Frees each linked list items and its name.
  10295. *
  10296. * @param [in, out] altNames Alternative names.
  10297. * @param [in] heap Dynamic memory hint.
  10298. */
  10299. void FreeAltNames(DNS_entry* altNames, void* heap)
  10300. {
  10301. (void)heap;
  10302. while (altNames) {
  10303. DNS_entry* tmp = altNames->next;
  10304. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10305. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10306. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10307. #endif
  10308. #if defined(OPENSSL_ALL)
  10309. XFREE(altNames->ridString, heap, DYNAMIC_TYPE_ALTNAME);
  10310. #endif
  10311. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10312. altNames = tmp;
  10313. }
  10314. }
  10315. /* malloc and initialize a new alt name structure */
  10316. DNS_entry* AltNameNew(void* heap)
  10317. {
  10318. DNS_entry* ret;
  10319. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10320. if (ret != NULL) {
  10321. XMEMSET(ret, 0, sizeof(DNS_entry));
  10322. }
  10323. (void)heap;
  10324. return ret;
  10325. }
  10326. #ifndef IGNORE_NAME_CONSTRAINTS
  10327. /* Free the subtree names object.
  10328. *
  10329. * Frees each linked list items and its name.
  10330. *
  10331. * @param [in, out] names Subtree names.
  10332. * @param [in] heap Dynamic memory hint.
  10333. */
  10334. void FreeNameSubtrees(Base_entry* names, void* heap)
  10335. {
  10336. (void)heap;
  10337. while (names) {
  10338. Base_entry* tmp = names->next;
  10339. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10340. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10341. names = tmp;
  10342. }
  10343. }
  10344. #endif /* IGNORE_NAME_CONSTRAINTS */
  10345. /* Free the decoded cert object's dynamic data.
  10346. *
  10347. * @param [in, out] cert Decoded certificate object.
  10348. */
  10349. void FreeDecodedCert(DecodedCert* cert)
  10350. {
  10351. if (cert == NULL)
  10352. return;
  10353. if (cert->subjectCNStored == 1) {
  10354. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10355. }
  10356. if (cert->pubKeyStored == 1) {
  10357. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10358. }
  10359. if (cert->weOwnAltNames && cert->altNames)
  10360. FreeAltNames(cert->altNames, cert->heap);
  10361. #ifndef IGNORE_NAME_CONSTRAINTS
  10362. if (cert->altEmailNames)
  10363. FreeAltNames(cert->altEmailNames, cert->heap);
  10364. if (cert->altDirNames)
  10365. FreeAltNames(cert->altDirNames, cert->heap);
  10366. if (cert->permittedNames)
  10367. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10368. if (cert->excludedNames)
  10369. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10370. #endif /* IGNORE_NAME_CONSTRAINTS */
  10371. #ifdef WOLFSSL_SEP
  10372. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10373. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10374. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10375. #endif /* WOLFSSL_SEP */
  10376. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10377. if (cert->issuerName != NULL)
  10378. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10379. if (cert->subjectName != NULL)
  10380. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10381. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10382. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  10383. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10384. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10385. #endif
  10386. FreeSignatureCtx(&cert->sigCtx);
  10387. }
  10388. void wc_FreeDecodedCert(DecodedCert* cert)
  10389. {
  10390. FreeDecodedCert(cert);
  10391. }
  10392. #ifndef WOLFSSL_ASN_TEMPLATE
  10393. static int GetCertHeader(DecodedCert* cert)
  10394. {
  10395. int ret = 0, len;
  10396. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10397. return ASN_PARSE_E;
  10398. /* Reset the max index for the size indicated in the outer wrapper. */
  10399. cert->maxIdx = (word32)len + cert->srcIdx;
  10400. cert->certBegin = cert->srcIdx;
  10401. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10402. return ASN_PARSE_E;
  10403. cert->sigIndex = (word32)len + cert->srcIdx;
  10404. if (cert->sigIndex > cert->maxIdx)
  10405. return ASN_PARSE_E;
  10406. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10407. cert->sigIndex) < 0)
  10408. return ASN_PARSE_E;
  10409. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10410. &cert->serialSz, cert->sigIndex) < 0)
  10411. return ASN_PARSE_E;
  10412. return ret;
  10413. }
  10414. #endif
  10415. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10416. defined(HAVE_LIBOQS))
  10417. /* Store the key data under the BIT_STRING in dynamically allocated data.
  10418. *
  10419. * @param [in, out] cert Certificate object.
  10420. * @param [in] source Buffer containing encoded key.
  10421. * @param [in, out] srcIdx On in, start of key data.
  10422. * On out, start of element after key data.
  10423. * @param [in] maxIdx Maximum index of certificate data.
  10424. */
  10425. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10426. word32 maxIdx)
  10427. {
  10428. int ret;
  10429. int length;
  10430. byte* publicKey;
  10431. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10432. if (ret == 0) {
  10433. #ifdef HAVE_OCSP
  10434. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10435. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10436. }
  10437. if (ret == 0) {
  10438. #endif
  10439. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10440. DYNAMIC_TYPE_PUBLIC_KEY);
  10441. if (publicKey == NULL) {
  10442. ret = MEMORY_E;
  10443. }
  10444. else {
  10445. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10446. cert->publicKey = publicKey;
  10447. cert->pubKeyStored = 1;
  10448. cert->pubKeySize = (word32)length;
  10449. *srcIdx += (word32)length;
  10450. }
  10451. }
  10452. return ret;
  10453. }
  10454. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10455. #endif
  10456. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10457. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  10458. {
  10459. #ifdef HAVE_OID_ENCODING
  10460. int ret;
  10461. #endif
  10462. int idx;
  10463. word32 oidSz = 0;
  10464. /* validate key */
  10465. if (key == NULL || key->dp == NULL) {
  10466. return BAD_FUNC_ARG;
  10467. }
  10468. #ifdef HAVE_OID_ENCODING
  10469. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  10470. if (ret != 0) {
  10471. return ret;
  10472. }
  10473. #else
  10474. oidSz = key->dp->oidSz;
  10475. #endif
  10476. idx = SetObjectId((int)oidSz, output);
  10477. /* length only */
  10478. if (output == NULL) {
  10479. return idx + (int)oidSz;
  10480. }
  10481. /* verify output buffer has room */
  10482. if (oidSz > outSz)
  10483. return BUFFER_E;
  10484. #ifdef HAVE_OID_ENCODING
  10485. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  10486. if (ret != 0) {
  10487. return ret;
  10488. }
  10489. #else
  10490. XMEMCPY(output+idx, key->dp->oid, oidSz);
  10491. #endif
  10492. idx += (int)oidSz;
  10493. return idx;
  10494. }
  10495. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10496. #ifdef HAVE_ECC
  10497. #ifdef WOLFSSL_ASN_TEMPLATE
  10498. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  10499. * RFC 5480, 2 - Subject Public Key Information Fields
  10500. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10501. * X9.62 ECC point format.
  10502. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  10503. */
  10504. static const ASNItem eccPublicKeyASN[] = {
  10505. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10506. /* AlgorithmIdentifier */
  10507. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10508. /* algorithm */
  10509. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  10510. /* namedCurve */
  10511. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  10512. /* specifiedCurve - explicit parameters */
  10513. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  10514. /* Public Key */
  10515. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10516. };
  10517. enum {
  10518. ECCPUBLICKEYASN_IDX_SEQ = 0,
  10519. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  10520. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  10521. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  10522. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  10523. ECCPUBLICKEYASN_IDX_PUBKEY
  10524. };
  10525. /* Number of items in ASN.1 template for ECC public key. */
  10526. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  10527. #endif /* WOLFSSL_ASN_TEMPLATE */
  10528. #endif /* HAVE_ECC */
  10529. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10530. /* Encode public ECC key in DER format.
  10531. *
  10532. * RFC 5480, 2 - Subject Public Key Information Fields
  10533. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10534. * X9.62 ECC point format.
  10535. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  10536. *
  10537. * @param [out] output Buffer to put encoded data in.
  10538. * @param [in] key ECC key object.
  10539. * @param [in] outLen Size of buffer in bytes.
  10540. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  10541. * @return Size of encoded data in bytes on success.
  10542. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10543. * @return MEMORY_E when dynamic memory allocation failed.
  10544. */
  10545. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  10546. int with_header, int comp)
  10547. {
  10548. #ifndef WOLFSSL_ASN_TEMPLATE
  10549. int ret;
  10550. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  10551. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  10552. byte algo[MAX_ALGO_SZ]; /* 20 */
  10553. /* public size */
  10554. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  10555. if (comp)
  10556. pubSz = 1 + pubSz;
  10557. else
  10558. pubSz = 1 + 2 * pubSz;
  10559. /* check for buffer overflow */
  10560. if (output != NULL && pubSz > (word32)outLen) {
  10561. return BUFFER_E;
  10562. }
  10563. /* headers */
  10564. if (with_header) {
  10565. ret = SetCurve(key, NULL, 0);
  10566. if (ret <= 0) {
  10567. return ret;
  10568. }
  10569. curveSz = (word32)ret;
  10570. ret = 0;
  10571. /* calculate size */
  10572. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  10573. bitStringSz = SetBitString(pubSz, 0, bitString);
  10574. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  10575. /* check for buffer overflow */
  10576. if (output != NULL &&
  10577. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  10578. return BUFFER_E;
  10579. }
  10580. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  10581. output);
  10582. /* algo */
  10583. if (output)
  10584. XMEMCPY(output + idx, algo, algoSz);
  10585. idx += algoSz;
  10586. /* curve */
  10587. if (output)
  10588. (void)SetCurve(key, output + idx, curveSz);
  10589. idx += curveSz;
  10590. /* bit string */
  10591. if (output)
  10592. XMEMCPY(output + idx, bitString, bitStringSz);
  10593. idx += bitStringSz;
  10594. }
  10595. /* pub */
  10596. if (output) {
  10597. PRIVATE_KEY_UNLOCK();
  10598. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  10599. PRIVATE_KEY_LOCK();
  10600. if (ret != 0) {
  10601. return ret;
  10602. }
  10603. }
  10604. idx += pubSz;
  10605. return (int)idx;
  10606. #else
  10607. word32 pubSz = 0;
  10608. int sz = 0;
  10609. int ret = 0;
  10610. int curveIdSz = 0;
  10611. byte* curveOid = NULL;
  10612. /* Check key validity. */
  10613. if ((key == NULL) || (key->dp == NULL)) {
  10614. ret = BAD_FUNC_ARG;
  10615. }
  10616. if (ret == 0) {
  10617. /* Calculate the size of the encoded public point. */
  10618. PRIVATE_KEY_UNLOCK();
  10619. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  10620. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  10621. /* in earlier versions of FIPS the get length functionality is not
  10622. * available with compressed keys */
  10623. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  10624. if (comp)
  10625. pubSz = 1 + pubSz;
  10626. else
  10627. pubSz = 1 + 2 * pubSz;
  10628. ret = LENGTH_ONLY_E;
  10629. #else
  10630. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  10631. #endif
  10632. PRIVATE_KEY_LOCK();
  10633. /* LENGTH_ONLY_E on success. */
  10634. if (ret == LENGTH_ONLY_E) {
  10635. ret = 0;
  10636. }
  10637. }
  10638. if ((ret == 0) && with_header) {
  10639. /* Including SubjectPublicKeyInfo header. */
  10640. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  10641. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  10642. /* Get the length of the named curve OID to put into the encoding. */
  10643. curveIdSz = SetCurve(key, NULL, 0);
  10644. if (curveIdSz < 0) {
  10645. ret = curveIdSz;
  10646. }
  10647. if (ret == 0) {
  10648. /* Set the key type OID. */
  10649. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  10650. oidKeyType);
  10651. /* Set the curve OID. */
  10652. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  10653. NULL, (word32)curveIdSz);
  10654. /* Don't try to write out explicit parameters. */
  10655. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  10656. /* Set size of public point to ensure space is made for it. */
  10657. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  10658. /* Calculate size of ECC public key. */
  10659. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  10660. eccPublicKeyASN_Length, &sz);
  10661. }
  10662. /* Check buffer, if passed in, is big enough for encoded data. */
  10663. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  10664. ret = BUFFER_E;
  10665. }
  10666. if ((ret == 0) && (output != NULL)) {
  10667. /* Encode ECC public key. */
  10668. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  10669. output);
  10670. /* Skip to where public point is to be encoded. */
  10671. output += sz - (int)pubSz;
  10672. /* Cache the location to place the name curve OID. */
  10673. curveOid = (byte*)
  10674. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  10675. }
  10676. FREE_ASNSETDATA(dataASN, key->heap);
  10677. }
  10678. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  10679. ret = BUFFER_E;
  10680. }
  10681. else {
  10682. /* Total size is the public point size. */
  10683. sz = (int)pubSz;
  10684. }
  10685. if ((ret == 0) && (output != NULL)) {
  10686. /* Put named curve OID data into encoding. */
  10687. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  10688. if (curveIdSz < 0) {
  10689. ret = curveIdSz;
  10690. }
  10691. }
  10692. if ((ret == 0) && (output != NULL)) {
  10693. /* Encode public point. */
  10694. PRIVATE_KEY_UNLOCK();
  10695. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  10696. PRIVATE_KEY_LOCK();
  10697. }
  10698. if (ret == 0) {
  10699. /* Return the size of the encoding. */
  10700. ret = sz;
  10701. }
  10702. return ret;
  10703. #endif
  10704. }
  10705. /* Encode the public part of an ECC key in a DER.
  10706. *
  10707. * Pass NULL for output to get the size of the encoding.
  10708. *
  10709. * @param [in] key ECC key object.
  10710. * @param [out] output Buffer to hold DER encoding.
  10711. * @param [in] inLen Size of buffer in bytes.
  10712. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  10713. * @return Size of encoded data in bytes on success.
  10714. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10715. * @return MEMORY_E when dynamic memory allocation failed.
  10716. */
  10717. WOLFSSL_ABI
  10718. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  10719. int with_AlgCurve)
  10720. {
  10721. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  10722. }
  10723. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  10724. int with_AlgCurve, int comp)
  10725. {
  10726. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  10727. }
  10728. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  10729. {
  10730. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  10731. }
  10732. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10733. #ifdef WOLFSSL_ASN_TEMPLATE
  10734. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  10735. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  10736. * RFC 8410, 4 - Subject Public Key Fields
  10737. */
  10738. static const ASNItem edPubKeyASN[] = {
  10739. /* SubjectPublicKeyInfo */
  10740. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10741. /* AlgorithmIdentifier */
  10742. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10743. /* Ed25519/Ed448 OID */
  10744. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  10745. /* Public key stream */
  10746. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10747. };
  10748. enum {
  10749. EDPUBKEYASN_IDX_SEQ = 0,
  10750. EDPUBKEYASN_IDX_ALGOID_SEQ,
  10751. EDPUBKEYASN_IDX_ALGOID_OID,
  10752. EDPUBKEYASN_IDX_PUBKEY
  10753. };
  10754. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  10755. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  10756. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  10757. #endif /* WOLFSSL_ASN_TEMPLATE */
  10758. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  10759. /* Build ASN.1 formatted public key based on RFC 8410
  10760. *
  10761. * Pass NULL for output to get the size of the encoding.
  10762. *
  10763. * @param [in] pubKey public key buffer
  10764. * @param [in] pubKeyLen public key buffer length
  10765. * @param [out] output Buffer to put encoded data in (optional)
  10766. * @param [in] outLen Size of buffer in bytes
  10767. * @param [in] keyType is "enum Key_Sum" like ED25519k
  10768. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  10769. * @return Size of encoded data in bytes on success
  10770. * @return BAD_FUNC_ARG when key is NULL.
  10771. * @return MEMORY_E when dynamic memory allocation failed.
  10772. */
  10773. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  10774. byte* output, word32 outLen, int keyType, int withHeader)
  10775. {
  10776. int ret = 0;
  10777. #ifndef WOLFSSL_ASN_TEMPLATE
  10778. word32 idx = 0;
  10779. word32 seqDataSz = 0;
  10780. word32 sz;
  10781. #else
  10782. int sz = 0;
  10783. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  10784. #endif
  10785. if (pubKey == NULL) {
  10786. return BAD_FUNC_ARG;
  10787. }
  10788. #ifndef WOLFSSL_ASN_TEMPLATE
  10789. /* calculate size */
  10790. if (withHeader) {
  10791. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  10792. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  10793. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  10794. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  10795. }
  10796. else {
  10797. sz = pubKeyLen;
  10798. }
  10799. /* checkout output size */
  10800. if (output != NULL && sz > outLen) {
  10801. ret = BUFFER_E;
  10802. }
  10803. /* headers */
  10804. if (ret == 0 && output != NULL && withHeader) {
  10805. /* sequence */
  10806. idx = SetSequence(seqDataSz, output);
  10807. /* algo */
  10808. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  10809. /* bit string */
  10810. idx += SetBitString(pubKeyLen, 0, output + idx);
  10811. }
  10812. if (ret == 0 && output != NULL) {
  10813. /* pub */
  10814. XMEMCPY(output + idx, pubKey, pubKeyLen);
  10815. idx += pubKeyLen;
  10816. sz = idx;
  10817. }
  10818. if (ret == 0) {
  10819. ret = (int)sz;
  10820. }
  10821. #else
  10822. if (withHeader) {
  10823. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  10824. if (ret == 0) {
  10825. /* Set the OID. */
  10826. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  10827. oidKeyType);
  10828. /* Leave space for public point. */
  10829. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  10830. /* Calculate size of public key encoding. */
  10831. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  10832. }
  10833. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  10834. ret = BUFFER_E;
  10835. }
  10836. if ((ret == 0) && (output != NULL)) {
  10837. /* Encode public key. */
  10838. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  10839. /* Set location to encode public point. */
  10840. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  10841. }
  10842. FREE_ASNSETDATA(dataASN, NULL);
  10843. }
  10844. else if ((output != NULL) && (pubKeyLen > outLen)) {
  10845. ret = BUFFER_E;
  10846. }
  10847. else if (ret == 0) {
  10848. sz = (int)pubKeyLen;
  10849. }
  10850. if ((ret == 0) && (output != NULL)) {
  10851. /* Put public key into space provided. */
  10852. XMEMCPY(output, pubKey, pubKeyLen);
  10853. }
  10854. if (ret == 0) {
  10855. ret = sz;
  10856. }
  10857. #endif /* WOLFSSL_ASN_TEMPLATE */
  10858. return ret;
  10859. }
  10860. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  10861. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  10862. /* Encode the public part of an Ed25519 key in DER.
  10863. *
  10864. * Pass NULL for output to get the size of the encoding.
  10865. *
  10866. * @param [in] key Ed25519 key object.
  10867. * @param [out] output Buffer to put encoded data in.
  10868. * @param [in] outLen Size of buffer in bytes.
  10869. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10870. * @return Size of encoded data in bytes on success.
  10871. * @return BAD_FUNC_ARG when key is NULL.
  10872. * @return MEMORY_E when dynamic memory allocation failed.
  10873. */
  10874. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  10875. int withAlg)
  10876. {
  10877. int ret;
  10878. byte pubKey[ED25519_PUB_KEY_SIZE];
  10879. word32 pubKeyLen = (word32)sizeof(pubKey);
  10880. if (key == NULL) {
  10881. return BAD_FUNC_ARG;
  10882. }
  10883. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  10884. if (ret == 0) {
  10885. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10886. ED25519k, withAlg);
  10887. }
  10888. return ret;
  10889. }
  10890. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  10891. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  10892. /* Encode the public part of an Ed448 key in DER.
  10893. *
  10894. * Pass NULL for output to get the size of the encoding.
  10895. *
  10896. * @param [in] key Ed448 key object.
  10897. * @param [out] output Buffer to put encoded data in.
  10898. * @param [in] outLen Size of buffer in bytes.
  10899. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10900. * @return Size of encoded data in bytes on success.
  10901. * @return BAD_FUNC_ARG when key is NULL.
  10902. * @return MEMORY_E when dynamic memory allocation failed.
  10903. */
  10904. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  10905. int withAlg)
  10906. {
  10907. int ret;
  10908. byte pubKey[ED448_PUB_KEY_SIZE];
  10909. word32 pubKeyLen = (word32)sizeof(pubKey);
  10910. if (key == NULL) {
  10911. return BAD_FUNC_ARG;
  10912. }
  10913. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  10914. if (ret == 0) {
  10915. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10916. ED448k, withAlg);
  10917. }
  10918. return ret;
  10919. }
  10920. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  10921. #if !defined(NO_RSA) && !defined(NO_CERTS)
  10922. #ifdef WOLFSSL_ASN_TEMPLATE
  10923. /* ASN.1 template for header before RSA key in certificate. */
  10924. static const ASNItem rsaCertKeyASN[] = {
  10925. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10926. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10927. };
  10928. enum {
  10929. RSACERTKEYASN_IDX_STR = 0,
  10930. RSACERTKEYASN_IDX_SEQ
  10931. };
  10932. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10933. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10934. #endif
  10935. /* Store RSA key pointer and length in certificate object.
  10936. *
  10937. * @param [in, out] cert Certificate object.
  10938. * @param [in] source Buffer containing encoded key.
  10939. * @param [in, out] srcIdx On in, start of RSA key data.
  10940. * On out, start of element after RSA key data.
  10941. * @param [in] maxIdx Maximum index of key data.
  10942. * @return 0 on success.
  10943. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10944. * is invalid.
  10945. * @return BUFFER_E when data in buffer is too small.
  10946. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10947. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10948. * non-zero length.
  10949. */
  10950. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10951. word32 maxIdx)
  10952. {
  10953. #ifndef WOLFSSL_ASN_TEMPLATE
  10954. int length;
  10955. int pubLen;
  10956. word32 pubIdx;
  10957. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10958. return ASN_PARSE_E;
  10959. pubIdx = *srcIdx;
  10960. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10961. return ASN_PARSE_E;
  10962. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  10963. cert->sigCtx.CertAtt.pubkey_n_start =
  10964. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10965. #endif
  10966. cert->pubKeySize = (word32)pubLen;
  10967. cert->publicKey = source + pubIdx;
  10968. #ifdef WOLFSSL_MAXQ10XX_TLS
  10969. cert->publicKeyIndex = pubIdx;
  10970. #endif
  10971. *srcIdx += (word32)length;
  10972. #ifdef HAVE_OCSP
  10973. return CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10974. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10975. #else
  10976. return 0;
  10977. #endif
  10978. #else
  10979. ASNGetData dataASN[rsaCertKeyASN_Length];
  10980. int ret;
  10981. /* No dynamic data. */
  10982. XMEMSET(dataASN, 0, sizeof(dataASN));
  10983. /* Decode the header before the key data. */
  10984. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10985. srcIdx, maxIdx);
  10986. if (ret == 0) {
  10987. /* Store the pointer and length in certificate object starting at
  10988. * SEQUENCE. */
  10989. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10990. &cert->publicKey, &cert->pubKeySize);
  10991. #ifdef WOLFSSL_MAXQ10XX_TLS
  10992. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10993. #endif
  10994. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  10995. /* Start of SEQUENCE. */
  10996. cert->sigCtx.CertAtt.pubkey_n_start =
  10997. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10998. #endif
  10999. #ifdef HAVE_OCSP
  11000. /* Calculate the hash of the public key for OCSP. */
  11001. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  11002. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  11003. #endif
  11004. }
  11005. return ret;
  11006. #endif /* WOLFSSL_ASN_TEMPLATE */
  11007. }
  11008. #endif /* !NO_RSA && !NO_CERTS */
  11009. #if defined(HAVE_ECC) && !defined(NO_CERTS)
  11010. #ifdef WOLFSSL_ASN_TEMPLATE
  11011. /* ASN.1 template for header before ECC key in certificate. */
  11012. static const ASNItem eccCertKeyASN[] = {
  11013. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  11014. /* Algo parameters */
  11015. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  11016. /* Subject public key */
  11017. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  11018. };
  11019. enum {
  11020. ECCCERTKEYASN_IDX_OID = 0,
  11021. ECCCERTKEYASN_IDX_PARAMS,
  11022. ECCCERTKEYASN_IDX_SUBJPUBKEY
  11023. };
  11024. /* Number of items in ASN.1 template for header before ECC key in cert. */
  11025. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  11026. #ifdef WOLFSSL_CUSTOM_CURVES
  11027. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  11028. ecc_key* key, void* heap, int* curveSz);
  11029. #endif /* WOLFSSL_CUSTOM_CURVES */
  11030. #endif /* WOLFSSL_ASN_TEMPLATE */
  11031. /* Store public ECC key in certificate object.
  11032. *
  11033. * Parse parameters and store public key data.
  11034. *
  11035. * @param [in, out] cert Certificate object.
  11036. * @param [in] source Buffer containing encoded key.
  11037. * @param [in, out] srcIdx On in, start of ECC key data.
  11038. * On out, start of element after ECC key data.
  11039. * @param [in] maxIdx Maximum index of key data.
  11040. * @param [in] pubKey Buffer holding encoded public key.
  11041. * @param [in] pubKeyLen Length of encoded public key in bytes.
  11042. * @return 0 on success.
  11043. * @return BAD_FUNC_ARG when pubKey is NULL.
  11044. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11045. * is invalid.
  11046. * @return BUFFER_E when data in buffer is too small.
  11047. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  11048. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11049. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  11050. * non-zero length.
  11051. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11052. */
  11053. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  11054. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  11055. {
  11056. #ifndef WOLFSSL_ASN_TEMPLATE
  11057. int ret;
  11058. word32 localIdx;
  11059. byte* publicKey;
  11060. byte tag;
  11061. int length;
  11062. if (pubKey == NULL) {
  11063. return BAD_FUNC_ARG;
  11064. }
  11065. localIdx = *srcIdx;
  11066. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  11067. return ASN_PARSE_E;
  11068. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  11069. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  11070. maxIdx) < 0)
  11071. return ASN_PARSE_E;
  11072. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  11073. return ECC_CURVE_OID_E;
  11074. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  11075. cert->sigCtx.CertAtt.curve_id = ret;
  11076. #else
  11077. (void)ret;
  11078. #endif
  11079. /* key header */
  11080. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  11081. if (ret != 0)
  11082. return ret;
  11083. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  11084. cert->sigCtx.CertAtt.pubkey_n_start =
  11085. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  11086. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  11087. cert->sigCtx.CertAtt.pubkey_e_start +=
  11088. cert->sigCtx.CertAtt.pubkey_n_len;
  11089. cert->sigCtx.CertAtt.pubkey_e_len =
  11090. cert->sigCtx.CertAtt.pubkey_n_len;
  11091. #endif
  11092. #ifdef WOLFSSL_MAXQ10XX_TLS
  11093. cert->publicKeyIndex = *srcIdx + 1;
  11094. #endif
  11095. #ifdef HAVE_OCSP
  11096. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  11097. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  11098. if (ret != 0)
  11099. return ret;
  11100. #endif
  11101. *srcIdx += (word32)length;
  11102. }
  11103. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  11104. if (publicKey == NULL)
  11105. return MEMORY_E;
  11106. XMEMCPY(publicKey, pubKey, pubKeyLen);
  11107. cert->publicKey = publicKey;
  11108. cert->pubKeyStored = 1;
  11109. cert->pubKeySize = pubKeyLen;
  11110. return 0;
  11111. #else
  11112. int ret = 0;
  11113. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  11114. byte* publicKey;
  11115. /* Validate parameters. */
  11116. if (pubKey == NULL) {
  11117. ret = BAD_FUNC_ARG;
  11118. }
  11119. /* Clear dynamic data and check OID is a curve. */
  11120. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  11121. if (ret == 0) {
  11122. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  11123. /* Parse ECC public key header. */
  11124. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  11125. source, srcIdx, maxIdx);
  11126. }
  11127. if (ret == 0) {
  11128. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  11129. /* Store curve OID. */
  11130. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  11131. }
  11132. else {
  11133. #ifdef WOLFSSL_CUSTOM_CURVES
  11134. /* Parse explicit parameters. */
  11135. ret = EccSpecifiedECDomainDecode(
  11136. dataASN[ECCCERTKEYASN_IDX_PARAMS].data.ref.data,
  11137. dataASN[ECCCERTKEYASN_IDX_PARAMS].data.ref.length, NULL,
  11138. NULL, &cert->pkCurveSize);
  11139. #else
  11140. /* Explicit parameters not supported in build configuration. */
  11141. ret = ASN_PARSE_E;
  11142. #endif
  11143. }
  11144. #ifdef WOLFSSL_MAXQ10XX_TLS
  11145. cert->publicKeyIndex =
  11146. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  11147. + 1;
  11148. #endif
  11149. #ifdef HAVE_OCSP
  11150. if (ret == 0) {
  11151. /* Calculate the hash of the subject public key for OCSP. */
  11152. ret = CalcHashId_ex(
  11153. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  11154. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  11155. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  11156. }
  11157. }
  11158. if (ret == 0) {
  11159. #endif
  11160. /* Store public key data length. */
  11161. cert->pubKeySize = pubKeyLen;
  11162. /* Must allocated space for key.
  11163. * Don't memcpy into constant pointer so use temp. */
  11164. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  11165. DYNAMIC_TYPE_PUBLIC_KEY);
  11166. if (publicKey == NULL) {
  11167. ret = MEMORY_E;
  11168. }
  11169. else {
  11170. /* Copy in whole public key and store pointer. */
  11171. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  11172. cert->publicKey = publicKey;
  11173. /* Indicate publicKey needs to be freed. */
  11174. cert->pubKeyStored = 1;
  11175. }
  11176. }
  11177. FREE_ASNGETDATA(dataASN, cert->heap);
  11178. return ret;
  11179. #endif /* WOLFSSL_ASN_TEMPLATE */
  11180. }
  11181. #endif /* HAVE_ECC && !NO_CERTS */
  11182. #ifndef NO_CERTS
  11183. #if !defined(NO_DSA)
  11184. #ifdef WOLFSSL_ASN_TEMPLATE
  11185. /* ASN.1 template for DSA key in certificate.
  11186. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  11187. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  11188. */
  11189. static const ASNItem dsaCertKeyASN[] = {
  11190. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  11191. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11192. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11193. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11194. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  11195. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  11196. };
  11197. /* Number of items in ASN.1 template for DSA key in certificate. */
  11198. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  11199. #endif /* WOLFSSL_ASN_TEMPLATE */
  11200. /* Parse DSA parameters to ensure valid.
  11201. *
  11202. * @param [in] source Buffer containing encoded key.
  11203. * @param [in, out] srcIdx On in, start of DSA key data.
  11204. * On out, start of element after DSA key data.
  11205. * @param [in] maxIdx Maximum index of key data.
  11206. * @param [in] heap Dynamic memory hint.
  11207. * @return 0 on success.
  11208. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11209. * is invalid.
  11210. * @return BUFFER_E when data in buffer is too small.
  11211. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11212. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  11213. * non-zero length.
  11214. */
  11215. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  11216. void* heap)
  11217. {
  11218. #ifndef WOLFSSL_ASN_TEMPLATE
  11219. int ret;
  11220. int length;
  11221. (void)heap;
  11222. ret = GetSequence(source, srcIdx, &length, maxIdx);
  11223. if (ret < 0)
  11224. return ret;
  11225. ret = SkipInt(source, srcIdx, maxIdx);
  11226. if (ret != 0)
  11227. return ret;
  11228. ret = SkipInt(source, srcIdx, maxIdx);
  11229. if (ret != 0)
  11230. return ret;
  11231. ret = SkipInt(source, srcIdx, maxIdx);
  11232. if (ret != 0)
  11233. return ret;
  11234. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  11235. if (ret != 0)
  11236. return ret;
  11237. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  11238. if (ret != 0)
  11239. return ASN_PARSE_E;
  11240. *srcIdx += (word32)length;
  11241. return 0;
  11242. #else
  11243. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  11244. int ret = 0;
  11245. (void)heap;
  11246. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  11247. if (ret == 0) {
  11248. /* Parse the DSA key data to ensure valid. */
  11249. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  11250. source, srcIdx, maxIdx);
  11251. }
  11252. FREE_ASNGETDATA(dataASN, heap);
  11253. return ret;
  11254. #endif /* WOLFSSL_ASN_TEMPLATE */
  11255. }
  11256. #endif /* !NO_DSA */
  11257. /* Decode the SubjectPublicKeyInfo block in a certificate.
  11258. *
  11259. * Stores the public key in fields of the certificate object.
  11260. * Validates the BER/DER items and does not store in a key object.
  11261. *
  11262. * @param [in, out] cert Decoded certificate object.
  11263. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  11264. * @param [in, out] inOutIdx On in, start of public key.
  11265. * On out, start of ASN.1 item after public key.
  11266. * @param [in] maxIdx Maximum index of key data.
  11267. * @return 0 on success.
  11268. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11269. * is invalid.
  11270. * @return BUFFER_E when data in buffer is too small.
  11271. */
  11272. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  11273. word32 maxIdx)
  11274. {
  11275. word32 srcIdx = *inOutIdx;
  11276. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11277. int pubLen;
  11278. #endif
  11279. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11280. int pubIdx = (int)srcIdx;
  11281. #endif
  11282. int ret = 0;
  11283. int length;
  11284. /* Validate parameters. */
  11285. if (source == NULL) {
  11286. return ASN_PARSE_E;
  11287. }
  11288. #ifndef WOLFSSL_ASN_TEMPLATE
  11289. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  11290. #else
  11291. /* Get SEQUENCE and expect all data to be accounted for. */
  11292. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  11293. #endif
  11294. {
  11295. return ASN_PARSE_E;
  11296. }
  11297. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11298. pubLen = (int)srcIdx - pubIdx + length;
  11299. #endif
  11300. maxIdx = srcIdx + (word32)length;
  11301. /* Decode the algorithm identifier for the key. */
  11302. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  11303. return ASN_PARSE_E;
  11304. }
  11305. (void)length;
  11306. /* Parse each type of public key. */
  11307. switch (cert->keyOID) {
  11308. #ifndef NO_RSA
  11309. #ifdef WC_RSA_PSS
  11310. case RSAPSSk:
  11311. if (srcIdx != maxIdx &&
  11312. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  11313. word32 seqIdx = srcIdx;
  11314. int seqLen;
  11315. /* Not set when -1. */
  11316. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  11317. int mgf = -1;
  11318. int saltLen = 0;
  11319. /* Defaults for sig algorithm parameters. */
  11320. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  11321. int sigMgf = WC_MGF1SHA1;
  11322. int sigSaltLen = 20;
  11323. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  11324. return ASN_PARSE_E;
  11325. }
  11326. /* Get the pubic key parameters. */
  11327. ret = DecodeRsaPssParams(source + seqIdx,
  11328. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  11329. if (ret != 0) {
  11330. return ASN_PARSE_E;
  11331. }
  11332. /* Get the signature parameters. */
  11333. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  11334. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  11335. if (ret != 0) {
  11336. return ASN_PARSE_E;
  11337. }
  11338. /* Validated signature params match public key params. */
  11339. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  11340. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  11341. return ASN_PARSE_E;
  11342. }
  11343. if (mgf != -1 && mgf != sigMgf) {
  11344. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  11345. return ASN_PARSE_E;
  11346. }
  11347. if (saltLen > sigSaltLen) {
  11348. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  11349. return ASN_PARSE_E;
  11350. }
  11351. srcIdx += (word32)seqLen;
  11352. }
  11353. FALL_THROUGH;
  11354. #endif /* WC_RSA_PSS */
  11355. case RSAk:
  11356. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  11357. break;
  11358. #endif /* NO_RSA */
  11359. #ifdef HAVE_ECC
  11360. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11361. case SM2k:
  11362. #endif
  11363. case ECDSAk:
  11364. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  11365. (word32)pubLen);
  11366. break;
  11367. #endif /* HAVE_ECC */
  11368. #ifdef HAVE_ED25519
  11369. case ED25519k:
  11370. cert->pkCurveOID = ED25519k;
  11371. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11372. break;
  11373. #endif /* HAVE_ED25519 */
  11374. #ifdef HAVE_ED448
  11375. case ED448k:
  11376. cert->pkCurveOID = ED448k;
  11377. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11378. break;
  11379. #endif /* HAVE_ED448 */
  11380. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  11381. #ifdef HAVE_FALCON
  11382. case FALCON_LEVEL1k:
  11383. cert->pkCurveOID = FALCON_LEVEL1k;
  11384. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11385. break;
  11386. case FALCON_LEVEL5k:
  11387. cert->pkCurveOID = FALCON_LEVEL5k;
  11388. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11389. break;
  11390. #endif /* HAVE_FALCON */
  11391. #ifdef HAVE_DILITHIUM
  11392. case DILITHIUM_LEVEL2k:
  11393. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  11394. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11395. break;
  11396. case DILITHIUM_LEVEL3k:
  11397. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  11398. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11399. break;
  11400. case DILITHIUM_LEVEL5k:
  11401. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  11402. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11403. break;
  11404. #endif /* HAVE_DILITHIUM */
  11405. #ifdef HAVE_SPHINCS
  11406. case SPHINCS_FAST_LEVEL1k:
  11407. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  11408. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11409. break;
  11410. case SPHINCS_FAST_LEVEL3k:
  11411. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  11412. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11413. break;
  11414. case SPHINCS_FAST_LEVEL5k:
  11415. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  11416. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11417. break;
  11418. case SPHINCS_SMALL_LEVEL1k:
  11419. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  11420. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11421. break;
  11422. case SPHINCS_SMALL_LEVEL3k:
  11423. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  11424. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11425. break;
  11426. case SPHINCS_SMALL_LEVEL5k:
  11427. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  11428. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11429. break;
  11430. #endif /* HAVE_SPHINCS */
  11431. #endif /* HAVE_PQC */
  11432. #ifndef NO_DSA
  11433. case DSAk:
  11434. cert->publicKey = source + pubIdx;
  11435. cert->pubKeySize = (word32)pubLen;
  11436. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  11437. break;
  11438. #endif /* NO_DSA */
  11439. default:
  11440. WOLFSSL_MSG("Unknown or not compiled in key OID");
  11441. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  11442. ret = ASN_UNKNOWN_OID_E;
  11443. }
  11444. /* Return index after public key. */
  11445. *inOutIdx = srcIdx;
  11446. /* Return error code. */
  11447. return ret;
  11448. }
  11449. #endif
  11450. /* Return the hash algorithm to use with the signature algorithm.
  11451. *
  11452. * @param [in] oidSum Signature id.
  11453. * @return Hash algorithm id.
  11454. */
  11455. int HashIdAlg(word32 oidSum)
  11456. {
  11457. (void)oidSum;
  11458. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11459. if (oidSum == CTC_SM3wSM2) {
  11460. return WC_SM3;
  11461. }
  11462. if (oidSum == SM2k) {
  11463. return WC_SM3;
  11464. }
  11465. #endif
  11466. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11467. return WC_SHA256;
  11468. #else
  11469. return WC_SHA;
  11470. #endif
  11471. }
  11472. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11473. *
  11474. * @param [in] data Data to hash.
  11475. * @param [in] len Length of data to hash.
  11476. * @param [out] hash Buffer to hold hash.
  11477. * @return 0 on success.
  11478. * @return MEMORY_E when dynamic memory allocation fails.
  11479. */
  11480. int CalcHashId(const byte* data, word32 len, byte* hash)
  11481. {
  11482. /* Use default hash algorithm. */
  11483. return CalcHashId_ex(data, len, hash,
  11484. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11485. WC_SHA256
  11486. #else
  11487. WC_SHA
  11488. #endif
  11489. );
  11490. }
  11491. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11492. *
  11493. * @param [in] data Data to hash.
  11494. * @param [in] len Length of data to hash.
  11495. * @param [out] hash Buffer to hold hash.
  11496. * @return 0 on success.
  11497. * @return MEMORY_E when dynamic memory allocation fails.
  11498. */
  11499. int CalcHashId_ex(const byte* data, word32 len, byte* hash, int hashAlg)
  11500. {
  11501. int ret;
  11502. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11503. if (hashAlg == WC_SM3) {
  11504. ret = wc_Sm3Hash(data, len, hash);
  11505. }
  11506. else
  11507. #endif
  11508. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11509. if (hashAlg == WC_SHA256) {
  11510. ret = wc_Sha256Hash(data, len, hash);
  11511. }
  11512. else
  11513. #elif !defined(NO_SHA)
  11514. if (hashAlg == WC_SHA) {
  11515. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11516. XMEMSET(hash + WC_SHA_DIGEST_SIZE, 0, KEYID_SIZE - WC_SHA_DIGEST_SIZE);
  11517. #endif
  11518. ret = wc_ShaHash(data, len, hash);
  11519. }
  11520. else
  11521. #else
  11522. (void)data;
  11523. (void)len;
  11524. (void)hash;
  11525. #endif
  11526. {
  11527. ret = NOT_COMPILED_IN;
  11528. }
  11529. return ret;
  11530. }
  11531. #ifndef NO_CERTS
  11532. /* Get the hash of the id using the SHA-1 or SHA-256.
  11533. *
  11534. * If the id is not the length of the hash, then hash it.
  11535. *
  11536. * @param [in] id Id to get hash for.
  11537. * @param [in] len Length of id in bytes.
  11538. * @param [out] hash Buffer to hold hash.
  11539. * @return 0 on success.
  11540. * @return MEMORY_E when dynamic memory allocation fails.
  11541. */
  11542. static int GetHashId(const byte* id, int length, byte* hash, int hashAlg)
  11543. {
  11544. int ret;
  11545. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11546. if (length == wc_HashGetDigestSize(wc_HashTypeConvert(hashAlg)))
  11547. #else
  11548. if (length == KEYID_SIZE)
  11549. #endif
  11550. {
  11551. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11552. XMEMSET(hash + length, 0, KEYID_SIZE - length);
  11553. #endif
  11554. XMEMCPY(hash, id, (size_t)length);
  11555. ret = 0;
  11556. }
  11557. else {
  11558. ret = CalcHashId_ex(id, (word32)length, hash, hashAlg);
  11559. }
  11560. return ret;
  11561. }
  11562. #endif /* !NO_CERTS */
  11563. #ifdef WOLFSSL_ASN_TEMPLATE
  11564. /* Id for email address. */
  11565. #define ASN_EMAIL 0x100
  11566. /* Id for domain component. */
  11567. #define ASN_DC 0x102
  11568. /* Id for jurisdiction country. */
  11569. #define ASN_JURIS_C 0x203
  11570. /* Id for jurisdiction state. */
  11571. #define ASN_JURIS_ST 0x202
  11572. /* Set the string for a name component into the subject name. */
  11573. #define SetCertNameSubject(cert, id, val) \
  11574. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  11575. /* Set the string length for a name component into the subject name. */
  11576. #define SetCertNameSubjectLen(cert, id, val) \
  11577. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  11578. /* Set the encoding for a name component into the subject name. */
  11579. #define SetCertNameSubjectEnc(cert, id, val) \
  11580. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  11581. /* Get the string of a name component from the subject name. */
  11582. #define GetCertNameSubjectStr(id) \
  11583. (certNameSubject[(id) - 3].str)
  11584. /* Get the string length of a name component from the subject name. */
  11585. #define GetCertNameSubjectStrLen(id) \
  11586. (certNameSubject[(id) - 3].strLen)
  11587. /* Get the NID of a name component from the subject name. */
  11588. #define GetCertNameSubjectNID(id) \
  11589. (certNameSubject[(id) - 3].nid)
  11590. #define ValidCertNameSubject(id) \
  11591. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  11592. (certNameSubject[(id) - 3].strLen > 0))
  11593. /* Set the string for a name component into the issuer name. */
  11594. #define SetCertNameIssuer(cert, id, val) \
  11595. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].dataI)) = (val)
  11596. /* Set the string length for a name component into the issuer name. */
  11597. #define SetCertNameIssuerLen(cert, id, val) \
  11598. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].lenI)) = (int)(val)
  11599. /* Set the encoding for a name component into the issuer name. */
  11600. #define SetCertNameIssuerEnc(cert, id, val) \
  11601. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].encI)) = (val)
  11602. /* Mapping of certificate name component to useful information. */
  11603. typedef struct CertNameData {
  11604. /* Type string of name component. */
  11605. const char* str;
  11606. /* Length of type string of name component. */
  11607. byte strLen;
  11608. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11609. /* Offset of data in subject name component. */
  11610. size_t data;
  11611. /* Offset of length in subject name component. */
  11612. size_t len;
  11613. /* Offset of encoding in subject name component. */
  11614. size_t enc;
  11615. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11616. /* Offset of data in subject name component. */
  11617. size_t dataI;
  11618. /* Offset of length in subject name component. */
  11619. size_t lenI;
  11620. /* Offset of encoding in subject name component. */
  11621. size_t encI;
  11622. #endif
  11623. #endif
  11624. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11625. /* NID of type for subject name component. */
  11626. int nid;
  11627. #endif
  11628. } CertNameData;
  11629. /* List of data for common name components. */
  11630. static const CertNameData certNameSubject[] = {
  11631. /* Common Name */
  11632. {
  11633. "/CN=", 4,
  11634. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11635. OFFSETOF(DecodedCert, subjectCN),
  11636. OFFSETOF(DecodedCert, subjectCNLen),
  11637. OFFSETOF(DecodedCert, subjectCNEnc),
  11638. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11639. OFFSETOF(DecodedCert, issuerCN),
  11640. OFFSETOF(DecodedCert, issuerCNLen),
  11641. OFFSETOF(DecodedCert, issuerCNEnc),
  11642. #endif
  11643. #endif
  11644. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11645. NID_commonName
  11646. #endif
  11647. },
  11648. /* Surname */
  11649. {
  11650. "/SN=", 4,
  11651. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11652. OFFSETOF(DecodedCert, subjectSN),
  11653. OFFSETOF(DecodedCert, subjectSNLen),
  11654. OFFSETOF(DecodedCert, subjectSNEnc),
  11655. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11656. OFFSETOF(DecodedCert, issuerSN),
  11657. OFFSETOF(DecodedCert, issuerSNLen),
  11658. OFFSETOF(DecodedCert, issuerSNEnc),
  11659. #endif
  11660. #endif
  11661. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11662. NID_surname
  11663. #endif
  11664. },
  11665. /* Serial Number */
  11666. {
  11667. "/serialNumber=", 14,
  11668. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11669. OFFSETOF(DecodedCert, subjectSND),
  11670. OFFSETOF(DecodedCert, subjectSNDLen),
  11671. OFFSETOF(DecodedCert, subjectSNDEnc),
  11672. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11673. OFFSETOF(DecodedCert, issuerSND),
  11674. OFFSETOF(DecodedCert, issuerSNDLen),
  11675. OFFSETOF(DecodedCert, issuerSNDEnc),
  11676. #endif
  11677. #endif
  11678. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11679. NID_serialNumber
  11680. #endif
  11681. },
  11682. /* Country Name */
  11683. {
  11684. "/C=", 3,
  11685. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11686. OFFSETOF(DecodedCert, subjectC),
  11687. OFFSETOF(DecodedCert, subjectCLen),
  11688. OFFSETOF(DecodedCert, subjectCEnc),
  11689. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11690. OFFSETOF(DecodedCert, issuerC),
  11691. OFFSETOF(DecodedCert, issuerCLen),
  11692. OFFSETOF(DecodedCert, issuerCEnc),
  11693. #endif
  11694. #endif
  11695. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11696. NID_countryName
  11697. #endif
  11698. },
  11699. /* Locality Name */
  11700. {
  11701. "/L=", 3,
  11702. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11703. OFFSETOF(DecodedCert, subjectL),
  11704. OFFSETOF(DecodedCert, subjectLLen),
  11705. OFFSETOF(DecodedCert, subjectLEnc),
  11706. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11707. OFFSETOF(DecodedCert, issuerL),
  11708. OFFSETOF(DecodedCert, issuerLLen),
  11709. OFFSETOF(DecodedCert, issuerLEnc),
  11710. #endif
  11711. #endif
  11712. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11713. NID_localityName
  11714. #endif
  11715. },
  11716. /* State Name */
  11717. {
  11718. "/ST=", 4,
  11719. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11720. OFFSETOF(DecodedCert, subjectST),
  11721. OFFSETOF(DecodedCert, subjectSTLen),
  11722. OFFSETOF(DecodedCert, subjectSTEnc),
  11723. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11724. OFFSETOF(DecodedCert, issuerST),
  11725. OFFSETOF(DecodedCert, issuerSTLen),
  11726. OFFSETOF(DecodedCert, issuerSTEnc),
  11727. #endif
  11728. #endif
  11729. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11730. NID_stateOrProvinceName
  11731. #endif
  11732. },
  11733. /* Street Address */
  11734. {
  11735. "/street=", 8,
  11736. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11737. OFFSETOF(DecodedCert, subjectStreet),
  11738. OFFSETOF(DecodedCert, subjectStreetLen),
  11739. OFFSETOF(DecodedCert, subjectStreetEnc),
  11740. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11741. 0,
  11742. 0,
  11743. 0,
  11744. #endif
  11745. #endif
  11746. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11747. NID_streetAddress
  11748. #endif
  11749. },
  11750. /* Organization Name */
  11751. {
  11752. "/O=", 3,
  11753. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11754. OFFSETOF(DecodedCert, subjectO),
  11755. OFFSETOF(DecodedCert, subjectOLen),
  11756. OFFSETOF(DecodedCert, subjectOEnc),
  11757. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11758. OFFSETOF(DecodedCert, issuerO),
  11759. OFFSETOF(DecodedCert, issuerOLen),
  11760. OFFSETOF(DecodedCert, issuerOEnc),
  11761. #endif
  11762. #endif
  11763. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11764. NID_organizationName
  11765. #endif
  11766. },
  11767. /* Organization Unit Name */
  11768. {
  11769. "/OU=", 4,
  11770. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11771. OFFSETOF(DecodedCert, subjectOU),
  11772. OFFSETOF(DecodedCert, subjectOULen),
  11773. OFFSETOF(DecodedCert, subjectOUEnc),
  11774. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11775. OFFSETOF(DecodedCert, issuerOU),
  11776. OFFSETOF(DecodedCert, issuerOULen),
  11777. OFFSETOF(DecodedCert, issuerOUEnc),
  11778. #endif
  11779. #endif
  11780. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11781. NID_organizationalUnitName
  11782. #endif
  11783. },
  11784. /* Title */
  11785. {
  11786. NULL, 0,
  11787. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11788. 0,
  11789. 0,
  11790. 0,
  11791. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11792. 0,
  11793. 0,
  11794. 0,
  11795. #endif
  11796. #endif
  11797. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11798. 0,
  11799. #endif
  11800. },
  11801. /* Undefined */
  11802. {
  11803. NULL, 0,
  11804. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11805. 0,
  11806. 0,
  11807. 0,
  11808. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11809. 0,
  11810. 0,
  11811. 0,
  11812. #endif
  11813. #endif
  11814. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11815. 0,
  11816. #endif
  11817. },
  11818. /* Undefined */
  11819. {
  11820. NULL, 0,
  11821. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11822. 0,
  11823. 0,
  11824. 0,
  11825. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11826. 0,
  11827. 0,
  11828. 0,
  11829. #endif
  11830. #endif
  11831. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11832. 0,
  11833. #endif
  11834. },
  11835. /* Business Category */
  11836. {
  11837. "/businessCategory=", 18,
  11838. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11839. OFFSETOF(DecodedCert, subjectBC),
  11840. OFFSETOF(DecodedCert, subjectBCLen),
  11841. OFFSETOF(DecodedCert, subjectBCEnc),
  11842. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11843. 0,
  11844. 0,
  11845. 0,
  11846. #endif
  11847. #endif
  11848. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11849. NID_businessCategory
  11850. #endif
  11851. },
  11852. /* Undefined */
  11853. {
  11854. NULL, 0,
  11855. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11856. 0,
  11857. 0,
  11858. 0,
  11859. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11860. 0,
  11861. 0,
  11862. 0,
  11863. #endif
  11864. #endif
  11865. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11866. 0,
  11867. #endif
  11868. },
  11869. /* Postal Code */
  11870. {
  11871. "/postalCode=", 12,
  11872. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11873. OFFSETOF(DecodedCert, subjectPC),
  11874. OFFSETOF(DecodedCert, subjectPCLen),
  11875. OFFSETOF(DecodedCert, subjectPCEnc),
  11876. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11877. 0,
  11878. 0,
  11879. 0,
  11880. #endif
  11881. #endif
  11882. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11883. NID_postalCode
  11884. #endif
  11885. },
  11886. /* User Id */
  11887. {
  11888. "/userid=", 8,
  11889. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11890. OFFSETOF(DecodedCert, subjectUID),
  11891. OFFSETOF(DecodedCert, subjectUIDLen),
  11892. OFFSETOF(DecodedCert, subjectUIDEnc),
  11893. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11894. 0,
  11895. 0,
  11896. 0,
  11897. #endif
  11898. #endif
  11899. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11900. NID_userId
  11901. #endif
  11902. },
  11903. #ifdef WOLFSSL_CERT_NAME_ALL
  11904. /* Name, id 41 */
  11905. {
  11906. "/N=", 3,
  11907. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11908. OFFSETOF(DecodedCert, subjectN),
  11909. OFFSETOF(DecodedCert, subjectNLen),
  11910. OFFSETOF(DecodedCert, subjectNEnc),
  11911. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11912. 0,
  11913. 0,
  11914. 0,
  11915. #endif
  11916. #endif
  11917. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11918. NID_name
  11919. #endif
  11920. },
  11921. /* Given Name, id 42 */
  11922. {
  11923. "/GN=", 4,
  11924. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11925. OFFSETOF(DecodedCert, subjectGN),
  11926. OFFSETOF(DecodedCert, subjectGNLen),
  11927. OFFSETOF(DecodedCert, subjectGNEnc),
  11928. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11929. 0,
  11930. 0,
  11931. 0,
  11932. #endif
  11933. #endif
  11934. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11935. NID_givenName
  11936. #endif
  11937. },
  11938. /* initials, id 43 */
  11939. {
  11940. "/initials=", 10,
  11941. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11942. OFFSETOF(DecodedCert, subjectI),
  11943. OFFSETOF(DecodedCert, subjectILen),
  11944. OFFSETOF(DecodedCert, subjectIEnc),
  11945. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11946. 0,
  11947. 0,
  11948. 0,
  11949. #endif
  11950. #endif
  11951. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11952. NID_initials
  11953. #endif
  11954. },
  11955. /* DN Qualifier Name, id 46 */
  11956. {
  11957. "/dnQualifier=", 13,
  11958. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11959. OFFSETOF(DecodedCert, subjectDNQ),
  11960. OFFSETOF(DecodedCert, subjectDNQLen),
  11961. OFFSETOF(DecodedCert, subjectDNQEnc),
  11962. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  11963. 0,
  11964. 0,
  11965. 0,
  11966. #endif
  11967. #endif
  11968. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11969. NID_dnQualifier
  11970. #endif
  11971. },
  11972. #endif /* WOLFSSL_CERT_NAME_ALL */
  11973. };
  11974. static const int certNameSubjectSz =
  11975. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11976. /* ASN.1 template for an RDN.
  11977. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11978. */
  11979. static const ASNItem rdnASN[] = {
  11980. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11981. /* AttributeTypeAndValue */
  11982. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11983. /* AttributeType */
  11984. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11985. /* AttributeValue: Choice of tags - rdnChoice. */
  11986. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11987. };
  11988. enum {
  11989. RDNASN_IDX_SET = 0,
  11990. RDNASN_IDX_ATTR_SEQ,
  11991. RDNASN_IDX_ATTR_TYPE,
  11992. RDNASN_IDX_ATTR_VAL
  11993. };
  11994. /* Number of items in ASN.1 template for an RDN. */
  11995. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11996. /* Supported types of encodings (tags) for RDN strings.
  11997. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11998. * (IA5 String not listed in RFC but required for alternative types)
  11999. */
  12000. static const byte rdnChoice[] = {
  12001. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  12002. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  12003. };
  12004. #endif
  12005. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  12006. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  12007. * DNS entry
  12008. * return 0 on success
  12009. */
  12010. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  12011. {
  12012. int ret = 0;
  12013. size_t nameSz = 0;
  12014. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  12015. unsigned char* ip;
  12016. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  12017. return BAD_FUNC_ARG;
  12018. }
  12019. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  12020. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  12021. WOLFSSL_MSG("Unexpected IP size");
  12022. return BAD_FUNC_ARG;
  12023. }
  12024. ip = (unsigned char*)entry->name;
  12025. /* store IP addresses as a string */
  12026. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  12027. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  12028. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  12029. >= (int)sizeof(tmpName))
  12030. {
  12031. WOLFSSL_MSG("IP buffer overrun");
  12032. return BUFFER_E;
  12033. }
  12034. }
  12035. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  12036. size_t i;
  12037. for (i = 0; i < 8; i++) {
  12038. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  12039. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  12040. (i < 7) ? ":" : "")
  12041. >= (int)sizeof(tmpName))
  12042. {
  12043. WOLFSSL_MSG("IPv6 buffer overrun");
  12044. return BUFFER_E;
  12045. }
  12046. }
  12047. }
  12048. nameSz = XSTRLEN(tmpName);
  12049. entry->ipString = (char*)XMALLOC(nameSz + 1, heap,
  12050. DYNAMIC_TYPE_ALTNAME);
  12051. if (entry->ipString == NULL) {
  12052. ret = MEMORY_E;
  12053. }
  12054. if (ret == 0) {
  12055. XMEMCPY(entry->ipString, tmpName, nameSz);
  12056. entry->ipString[nameSz] = '\0';
  12057. }
  12058. (void)heap;
  12059. return ret;
  12060. }
  12061. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  12062. #if defined(OPENSSL_ALL)
  12063. /* used to set the human readable string for the registeredID with an
  12064. * ASN_RID_TYPE DNS entry
  12065. * return 0 on success
  12066. */
  12067. static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap)
  12068. {
  12069. int i, j, ret = 0;
  12070. int nameSz = 0;
  12071. int nid = 0;
  12072. int tmpSize = MAX_OID_SZ;
  12073. word32 oid = 0;
  12074. word32 idx = 0;
  12075. word16 tmpName[MAX_OID_SZ];
  12076. char oidName[MAX_OID_SZ];
  12077. char* finalName;
  12078. if (entry == NULL || entry->type != ASN_RID_TYPE) {
  12079. return BAD_FUNC_ARG;
  12080. }
  12081. if (entry->len <= 0) {
  12082. return BAD_FUNC_ARG;
  12083. }
  12084. XMEMSET(&oidName, 0, MAX_OID_SZ);
  12085. ret = GetOID((const byte*)entry->name, &idx, &oid, oidIgnoreType,
  12086. entry->len);
  12087. if (ret == 0 && (nid = oid2nid(oid, oidCsrAttrType)) > 0) {
  12088. /* OID has known string value */
  12089. finalName = (char*)wolfSSL_OBJ_nid2ln(nid);
  12090. }
  12091. else {
  12092. /* Decode OBJECT_ID into dotted form array. */
  12093. ret = DecodeObjectId((const byte*)(entry->name),(word32)entry->len,
  12094. tmpName, (word32*)&tmpSize);
  12095. if (ret == 0) {
  12096. j = 0;
  12097. /* Append each number of dotted form. */
  12098. for (i = 0; i < tmpSize; i++) {
  12099. if (j >= MAX_OID_SZ) {
  12100. return BUFFER_E;
  12101. }
  12102. if (i < tmpSize - 1) {
  12103. ret = XSNPRINTF(oidName + j, MAX_OID_SZ - j, "%d.", tmpName[i]);
  12104. }
  12105. else {
  12106. ret = XSNPRINTF(oidName + j, MAX_OID_SZ - j, "%d", tmpName[i]);
  12107. }
  12108. if (ret >= 0) {
  12109. j += ret;
  12110. }
  12111. else {
  12112. return BUFFER_E;
  12113. }
  12114. }
  12115. ret = 0;
  12116. finalName = oidName;
  12117. }
  12118. }
  12119. if (ret == 0) {
  12120. nameSz = (int)XSTRLEN((const char*)finalName);
  12121. entry->ridString = (char*)XMALLOC(nameSz + 1, heap,
  12122. DYNAMIC_TYPE_ALTNAME);
  12123. if (entry->ridString == NULL) {
  12124. ret = MEMORY_E;
  12125. }
  12126. if (ret == 0) {
  12127. XMEMCPY(entry->ridString, finalName, nameSz + 1);
  12128. }
  12129. }
  12130. return ret;
  12131. }
  12132. #endif /* OPENSSL_ALL && WOLFSSL_ASN_TEMPLATE */
  12133. #ifdef WOLFSSL_ASN_TEMPLATE
  12134. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  12135. /* Adds a DNS entry to a list of DNS entries
  12136. *
  12137. * @param [in, out] lst Linked list of DNS name entries.
  12138. * @param [in] entry Entry to add to the list
  12139. * @return 0 on success.
  12140. */
  12141. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  12142. {
  12143. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  12144. entry->next = NULL;
  12145. if (*lst == NULL) {
  12146. /* First on list */
  12147. *lst = entry;
  12148. }
  12149. else {
  12150. DNS_entry* temp = *lst;
  12151. /* Find end */
  12152. for (; (temp->next != NULL); temp = temp->next);
  12153. /* Add to end */
  12154. temp->next = entry;
  12155. }
  12156. #else
  12157. /* Prepend entry to linked list. */
  12158. entry->next = *lst;
  12159. *lst = entry;
  12160. #endif
  12161. return 0;
  12162. }
  12163. /* Allocate a DNS entry and set the fields.
  12164. *
  12165. * @param [in] cert Certificate object.
  12166. * @param [in] str DNS name string.
  12167. * @param [in] strLen Length of DNS name string.
  12168. * @param [in] type Type of DNS name string.
  12169. * @param [in, out] entries Linked list of DNS name entries.
  12170. * @return 0 on success.
  12171. * @return MEMORY_E when dynamic memory allocation fails.
  12172. */
  12173. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  12174. int type, DNS_entry** entries)
  12175. {
  12176. DNS_entry* dnsEntry;
  12177. int ret = 0;
  12178. /* Only used for heap. */
  12179. (void)cert;
  12180. /* TODO: consider one malloc. */
  12181. /* Allocate DNS Entry object. */
  12182. dnsEntry = AltNameNew(cert->heap);
  12183. if (dnsEntry == NULL) {
  12184. ret = MEMORY_E;
  12185. }
  12186. if (ret == 0) {
  12187. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  12188. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  12189. DYNAMIC_TYPE_ALTNAME);
  12190. if (dnsEntry->name == NULL) {
  12191. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12192. ret = MEMORY_E;
  12193. }
  12194. }
  12195. if (ret == 0) {
  12196. /* Set tag type, name length, name and NUL terminate name. */
  12197. dnsEntry->type = type;
  12198. dnsEntry->len = strLen;
  12199. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  12200. dnsEntry->name[strLen] = '\0';
  12201. #if defined(OPENSSL_ALL)
  12202. /* store registeredID as a string */
  12203. if (type == ASN_RID_TYPE) {
  12204. if ((ret = GenerateDNSEntryRIDString(dnsEntry, cert->heap)) != 0) {
  12205. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12206. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12207. }
  12208. }
  12209. #endif
  12210. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  12211. /* store IP addresses as a string */
  12212. if (type == ASN_IP_TYPE) {
  12213. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  12214. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12215. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12216. }
  12217. }
  12218. }
  12219. if (ret == 0) {
  12220. #endif
  12221. ret = AddDNSEntryToList(entries, dnsEntry);
  12222. }
  12223. return ret;
  12224. }
  12225. #endif
  12226. /* Set the details of a subject name component into a certificate.
  12227. *
  12228. * @param [in, out] cert Certificate object.
  12229. * @param [in] id Id of component.
  12230. * @param [in] str String for component.
  12231. * @param [in] strLen Length of string.
  12232. * @param [in] tag BER tag representing encoding of string.
  12233. * @return 0 on success, negative values on failure.
  12234. */
  12235. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  12236. byte tag)
  12237. {
  12238. int ret = 0;
  12239. /* Put string and encoding into certificate. */
  12240. if (id == ASN_COMMON_NAME) {
  12241. cert->subjectCN = (char *)str;
  12242. cert->subjectCNLen = (int)strLen;
  12243. cert->subjectCNEnc = (char)tag;
  12244. }
  12245. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12246. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  12247. /* Use table and offsets to put data into appropriate fields. */
  12248. SetCertNameSubject(cert, id, (char*)str);
  12249. SetCertNameSubjectLen(cert, id, strLen);
  12250. SetCertNameSubjectEnc(cert, id, tag);
  12251. }
  12252. #endif
  12253. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12254. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12255. else if (id == ASN_EMAIL) {
  12256. cert->subjectEmail = (char*)str;
  12257. cert->subjectEmailLen = strLen;
  12258. }
  12259. #endif
  12260. #ifdef WOLFSSL_CERT_EXT
  12261. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  12262. else if (id == ASN_JURIS_C) {
  12263. cert->subjectJC = (char*)str;
  12264. cert->subjectJCLen = strLen;
  12265. cert->subjectJCEnc = (char)tag;
  12266. }
  12267. else if (id == ASN_JURIS_ST) {
  12268. cert->subjectJS = (char*)str;
  12269. cert->subjectJSLen = strLen;
  12270. cert->subjectJSEnc = (char)tag;
  12271. }
  12272. #endif
  12273. return ret;
  12274. }
  12275. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12276. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12277. /* Set the details of an issuer name component into a certificate.
  12278. *
  12279. * @param [in, out] cert Certificate object.
  12280. * @param [in] id Id of component.
  12281. * @param [in] str String for component.
  12282. * @param [in] strLen Length of string.
  12283. * @param [in] tag BER tag representing encoding of string.
  12284. * @return 0 on success, negative values on failure.
  12285. */
  12286. static int SetIssuer(DecodedCert* cert, int id, byte* str, int strLen,
  12287. byte tag)
  12288. {
  12289. int ret = 0;
  12290. /* Put string and encoding into certificate. */
  12291. if (id == ASN_COMMON_NAME) {
  12292. cert->issuerCN = (char *)str;
  12293. cert->issuerCNLen = (int)strLen;
  12294. cert->issuerCNEnc = (char)tag;
  12295. }
  12296. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  12297. /* Use table and offsets to put data into appropriate fields. */
  12298. SetCertNameIssuer(cert, id, (char*)str);
  12299. SetCertNameIssuerLen(cert, id, strLen);
  12300. SetCertNameIssuerEnc(cert, id, tag);
  12301. }
  12302. else if (id == ASN_EMAIL) {
  12303. cert->issuerEmail = (char*)str;
  12304. cert->issuerEmailLen = strLen;
  12305. }
  12306. return ret;
  12307. }
  12308. #endif
  12309. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  12310. *
  12311. * @param [in, out] cert Certificate object.
  12312. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  12313. * @param [in, out] idx Index int full name to place next component.
  12314. * @param [in, out] nid NID of component type.
  12315. * @param [in] isSubject Whether this data is for a subject name.
  12316. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  12317. * @return 0 on success.
  12318. * @return MEMORY_E when dynamic memory allocation fails.
  12319. * @return ASN_PARSE_E when type not supported.
  12320. */
  12321. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  12322. int isSubject, ASNGetData* dataASN)
  12323. {
  12324. int ret = 0;
  12325. const char* typeStr = NULL;
  12326. byte typeStrLen = 0;
  12327. byte* oid;
  12328. word32 oidSz;
  12329. int id = 0;
  12330. (void)nid;
  12331. /* Get name type OID from data items. */
  12332. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  12333. /* v1 name types */
  12334. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  12335. id = oid[2];
  12336. /* Check range of supported ids in table. */
  12337. if (ValidCertNameSubject(id)) {
  12338. /* Get the type string, length and NID from table. */
  12339. typeStr = GetCertNameSubjectStr(id);
  12340. typeStrLen = GetCertNameSubjectStrLen(id);
  12341. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12342. *nid = GetCertNameSubjectNID(id);
  12343. #endif
  12344. }
  12345. }
  12346. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  12347. /* Set the email id, type string, length and NID. */
  12348. id = ASN_EMAIL;
  12349. typeStr = WOLFSSL_EMAIL_ADDR;
  12350. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12351. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12352. *nid = NID_emailAddress;
  12353. #endif
  12354. }
  12355. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  12356. /* Set the user id, type string, length and NID. */
  12357. id = ASN_USER_ID;
  12358. typeStr = WOLFSSL_USER_ID;
  12359. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  12360. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12361. *nid = NID_userId;
  12362. #endif
  12363. }
  12364. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  12365. /* Set the domain component, type string, length and NID. */
  12366. id = ASN_DC;
  12367. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  12368. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12369. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12370. *nid = NID_domainComponent;
  12371. #endif
  12372. }
  12373. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  12374. /* Set the favourite drink, type string, length and NID. */
  12375. id = ASN_FAVOURITE_DRINK;
  12376. typeStr = WOLFSSL_FAVOURITE_DRINK;
  12377. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12378. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12379. *nid = NID_favouriteDrink;
  12380. #endif
  12381. }
  12382. #ifdef WOLFSSL_CERT_REQ
  12383. else if (oidSz == sizeof(attrPkcs9ContentTypeOid) &&
  12384. XMEMCMP(oid, attrPkcs9ContentTypeOid, oidSz) == 0) {
  12385. /* Set the pkcs9_contentType, type string, length and NID. */
  12386. id = ASN_CONTENT_TYPE;
  12387. typeStr = WOLFSSL_CONTENT_TYPE;
  12388. typeStrLen = sizeof(WOLFSSL_CONTENT_TYPE) - 1;
  12389. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12390. *nid = NID_pkcs9_contentType;
  12391. #endif
  12392. }
  12393. #endif
  12394. /* Other OIDs that start with the same values. */
  12395. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  12396. WOLFSSL_MSG("Unknown pilot attribute type");
  12397. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  12398. ret = ASN_PARSE_E;
  12399. }
  12400. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  12401. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  12402. /* Set the jurisdiction id. */
  12403. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  12404. /* Set the jurisdiction type string, length and NID if known. */
  12405. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  12406. typeStr = WOLFSSL_JOI_C;
  12407. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  12408. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12409. *nid = NID_jurisdictionCountryName;
  12410. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12411. }
  12412. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  12413. typeStr = WOLFSSL_JOI_ST;
  12414. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12415. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12416. *nid = NID_jurisdictionStateOrProvinceName;
  12417. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12418. }
  12419. else {
  12420. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  12421. }
  12422. }
  12423. if ((ret == 0) && (typeStr != NULL)) {
  12424. /* OID type to store for subject name and add to full string. */
  12425. byte* str;
  12426. word32 strLen;
  12427. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12428. /* Get the string reference and length. */
  12429. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12430. if (isSubject) {
  12431. /* Store subject field components. */
  12432. ret = SetSubject(cert, id, str, (int)strLen, tag);
  12433. }
  12434. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12435. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12436. /* Put issuer common name string and encoding into certificate. */
  12437. else {
  12438. ret = SetIssuer(cert, id, str, (int)strLen, tag);
  12439. }
  12440. #endif
  12441. if (ret == 0) {
  12442. /* Check there is space for this in the full name string and
  12443. * terminating NUL character. */
  12444. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  12445. {
  12446. /* Add RDN to full string. */
  12447. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  12448. *idx += typeStrLen;
  12449. XMEMCPY(&full[*idx], str, strLen);
  12450. *idx += strLen;
  12451. }
  12452. else {
  12453. WOLFSSL_MSG("ASN Name too big, skipping");
  12454. }
  12455. }
  12456. }
  12457. return ret;
  12458. }
  12459. #endif /* WOLFSSL_ASN_TEMPLATE */
  12460. /* Get a certificate name into the certificate object.
  12461. *
  12462. * @param [in, out] cert Decoded certificate object.
  12463. * @param [out] full Buffer to hold full name as a string.
  12464. * @param [out] hash Buffer to hold hash of name.
  12465. * @param [in] nameType ISSUER or SUBJECT.
  12466. * @param [in] input Buffer holding certificate name.
  12467. * @param [in, out] inOutIdx On in, start of certificate name.
  12468. * On out, start of ASN.1 item after cert name.
  12469. * @param [in] maxIdx Index of next item after certificate name.
  12470. * @return 0 on success.
  12471. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12472. * is invalid.
  12473. * @return BUFFER_E when data in buffer is too small.
  12474. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12475. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12476. * @return MEMORY_E when dynamic memory allocation fails.
  12477. */
  12478. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  12479. const byte* input, word32* inOutIdx, word32 maxIdx)
  12480. {
  12481. #ifndef WOLFSSL_ASN_TEMPLATE
  12482. int length; /* length of all distinguished names */
  12483. int dummy;
  12484. int ret;
  12485. word32 idx;
  12486. word32 srcIdx = *inOutIdx;
  12487. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12488. !defined(WOLFCRYPT_ONLY)
  12489. WOLFSSL_X509_NAME* dName = NULL;
  12490. #endif
  12491. WOLFSSL_MSG("Getting Cert Name");
  12492. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12493. * calculated over the entire DER encoding of the Name field, including
  12494. * the tag and length. */
  12495. if (CalcHashId_ex(input + *inOutIdx, maxIdx - *inOutIdx, hash,
  12496. HashIdAlg(cert->signatureOID)) != 0) {
  12497. return ASN_PARSE_E;
  12498. }
  12499. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12500. !defined(WOLFCRYPT_ONLY)
  12501. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12502. if (dName == NULL) {
  12503. return MEMORY_E;
  12504. }
  12505. #endif /* OPENSSL_EXTRA */
  12506. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  12507. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12508. !defined(WOLFCRYPT_ONLY)
  12509. wolfSSL_X509_NAME_free(dName);
  12510. #endif /* OPENSSL_EXTRA */
  12511. return ASN_PARSE_E;
  12512. }
  12513. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12514. /* store pointer to raw issuer */
  12515. if (nameType == ISSUER) {
  12516. cert->issuerRaw = &input[srcIdx];
  12517. cert->issuerRawLen = length;
  12518. }
  12519. #endif
  12520. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12521. if (nameType == SUBJECT) {
  12522. cert->subjectRaw = &input[srcIdx];
  12523. cert->subjectRawLen = length;
  12524. }
  12525. #endif
  12526. length += (int)srcIdx;
  12527. idx = 0;
  12528. while (srcIdx < (word32)length) {
  12529. byte b = 0;
  12530. byte joint[3];
  12531. byte tooBig = FALSE;
  12532. int oidSz;
  12533. const char* copy = NULL;
  12534. int copyLen = 0;
  12535. int strLen = 0;
  12536. byte id = 0;
  12537. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12538. && !defined(WOLFCRYPT_ONLY)
  12539. int nid = NID_undef;
  12540. int enc;
  12541. #endif /* OPENSSL_EXTRA */
  12542. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  12543. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  12544. }
  12545. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  12546. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12547. !defined(WOLFCRYPT_ONLY)
  12548. wolfSSL_X509_NAME_free(dName);
  12549. #endif /* OPENSSL_EXTRA */
  12550. return ASN_PARSE_E;
  12551. }
  12552. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  12553. if (ret != 0) {
  12554. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12555. !defined(WOLFCRYPT_ONLY)
  12556. wolfSSL_X509_NAME_free(dName);
  12557. #endif /* OPENSSL_EXTRA */
  12558. return ret;
  12559. }
  12560. /* make sure there is room for joint */
  12561. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  12562. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12563. !defined(WOLFCRYPT_ONLY)
  12564. wolfSSL_X509_NAME_free(dName);
  12565. #endif /* OPENSSL_EXTRA */
  12566. return ASN_PARSE_E;
  12567. }
  12568. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  12569. /* v1 name types */
  12570. if (joint[0] == 0x55 && joint[1] == 0x04) {
  12571. srcIdx += 3;
  12572. id = joint[2];
  12573. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  12574. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12575. !defined(WOLFCRYPT_ONLY)
  12576. wolfSSL_X509_NAME_free(dName);
  12577. #endif /* OPENSSL_EXTRA */
  12578. return ASN_PARSE_E;
  12579. }
  12580. if (id == ASN_COMMON_NAME) {
  12581. if (nameType == SUBJECT) {
  12582. cert->subjectCN = (char *)&input[srcIdx];
  12583. cert->subjectCNLen = strLen;
  12584. cert->subjectCNEnc = (char)b;
  12585. }
  12586. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12587. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12588. else if (nameType == ISSUER) {
  12589. cert->issuerCN = (char*)&input[srcIdx];
  12590. cert->issuerCNLen = strLen;
  12591. cert->issuerCNEnc = (char)b;
  12592. }
  12593. #endif
  12594. copy = WOLFSSL_COMMON_NAME;
  12595. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  12596. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12597. && !defined(WOLFCRYPT_ONLY)
  12598. nid = NID_commonName;
  12599. #endif /* OPENSSL_EXTRA */
  12600. }
  12601. #ifdef WOLFSSL_CERT_NAME_ALL
  12602. else if (id == ASN_NAME) {
  12603. copy = WOLFSSL_NAME;
  12604. copyLen = sizeof(WOLFSSL_NAME) - 1;
  12605. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12606. if (nameType == SUBJECT) {
  12607. cert->subjectN = (char*)&input[srcIdx];
  12608. cert->subjectNLen = strLen;
  12609. cert->subjectNEnc = b;
  12610. }
  12611. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12612. #if (defined(OPENSSL_EXTRA) || \
  12613. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12614. && !defined(WOLFCRYPT_ONLY)
  12615. nid = NID_name;
  12616. #endif /* OPENSSL_EXTRA */
  12617. }
  12618. else if (id == ASN_INITIALS) {
  12619. copy = WOLFSSL_INITIALS;
  12620. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  12621. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12622. if (nameType == SUBJECT) {
  12623. cert->subjectI = (char*)&input[srcIdx];
  12624. cert->subjectILen = strLen;
  12625. cert->subjectIEnc = b;
  12626. }
  12627. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12628. #if (defined(OPENSSL_EXTRA) || \
  12629. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12630. && !defined(WOLFCRYPT_ONLY)
  12631. nid = NID_initials;
  12632. #endif /* OPENSSL_EXTRA */
  12633. }
  12634. else if (id == ASN_GIVEN_NAME) {
  12635. copy = WOLFSSL_GIVEN_NAME;
  12636. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  12637. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12638. if (nameType == SUBJECT) {
  12639. cert->subjectGN = (char*)&input[srcIdx];
  12640. cert->subjectGNLen = strLen;
  12641. cert->subjectGNEnc = b;
  12642. }
  12643. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12644. #if (defined(OPENSSL_EXTRA) || \
  12645. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12646. && !defined(WOLFCRYPT_ONLY)
  12647. nid = NID_givenName;
  12648. #endif /* OPENSSL_EXTRA */
  12649. }
  12650. else if (id == ASN_DNQUALIFIER) {
  12651. copy = WOLFSSL_DNQUALIFIER;
  12652. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  12653. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12654. if (nameType == SUBJECT) {
  12655. cert->subjectDNQ = (char*)&input[srcIdx];
  12656. cert->subjectDNQLen = strLen;
  12657. cert->subjectDNQEnc = b;
  12658. }
  12659. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12660. #if (defined(OPENSSL_EXTRA) || \
  12661. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12662. && !defined(WOLFCRYPT_ONLY)
  12663. nid = NID_dnQualifier;
  12664. #endif /* OPENSSL_EXTRA */
  12665. }
  12666. #endif /* WOLFSSL_CERT_NAME_ALL */
  12667. else if (id == ASN_SUR_NAME) {
  12668. copy = WOLFSSL_SUR_NAME;
  12669. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  12670. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12671. if (nameType == SUBJECT) {
  12672. cert->subjectSN = (char*)&input[srcIdx];
  12673. cert->subjectSNLen = strLen;
  12674. cert->subjectSNEnc = (char)b;
  12675. }
  12676. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12677. else if (nameType == ISSUER) {
  12678. cert->issuerSN = (char*)&input[srcIdx];
  12679. cert->issuerSNLen = strLen;
  12680. cert->issuerSNEnc = (char)b;
  12681. }
  12682. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12683. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12684. #if (defined(OPENSSL_EXTRA) || \
  12685. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12686. && !defined(WOLFCRYPT_ONLY)
  12687. nid = NID_surname;
  12688. #endif /* OPENSSL_EXTRA */
  12689. }
  12690. else if (id == ASN_COUNTRY_NAME) {
  12691. copy = WOLFSSL_COUNTRY_NAME;
  12692. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  12693. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12694. if (nameType == SUBJECT) {
  12695. cert->subjectC = (char*)&input[srcIdx];
  12696. cert->subjectCLen = strLen;
  12697. cert->subjectCEnc = (char)b;
  12698. }
  12699. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12700. else if (nameType == ISSUER) {
  12701. cert->issuerC = (char*)&input[srcIdx];
  12702. cert->issuerCLen = strLen;
  12703. cert->issuerCEnc = (char)b;
  12704. }
  12705. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12706. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12707. #if (defined(OPENSSL_EXTRA) || \
  12708. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12709. && !defined(WOLFCRYPT_ONLY)
  12710. nid = NID_countryName;
  12711. #endif /* OPENSSL_EXTRA */
  12712. }
  12713. else if (id == ASN_LOCALITY_NAME) {
  12714. copy = WOLFSSL_LOCALITY_NAME;
  12715. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  12716. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12717. if (nameType == SUBJECT) {
  12718. cert->subjectL = (char*)&input[srcIdx];
  12719. cert->subjectLLen = strLen;
  12720. cert->subjectLEnc = (char)b;
  12721. }
  12722. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12723. else if (nameType == ISSUER) {
  12724. cert->issuerL = (char*)&input[srcIdx];
  12725. cert->issuerLLen = strLen;
  12726. cert->issuerLEnc = (char)b;
  12727. }
  12728. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12729. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12730. #if (defined(OPENSSL_EXTRA) || \
  12731. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12732. && !defined(WOLFCRYPT_ONLY)
  12733. nid = NID_localityName;
  12734. #endif /* OPENSSL_EXTRA */
  12735. }
  12736. else if (id == ASN_STATE_NAME) {
  12737. copy = WOLFSSL_STATE_NAME;
  12738. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  12739. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12740. if (nameType == SUBJECT) {
  12741. cert->subjectST = (char*)&input[srcIdx];
  12742. cert->subjectSTLen = strLen;
  12743. cert->subjectSTEnc = (char)b;
  12744. }
  12745. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12746. else if (nameType == ISSUER) {
  12747. cert->issuerST = (char*)&input[srcIdx];
  12748. cert->issuerSTLen = strLen;
  12749. cert->issuerSTEnc = (char)b;
  12750. }
  12751. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12752. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12753. #if (defined(OPENSSL_EXTRA) || \
  12754. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12755. && !defined(WOLFCRYPT_ONLY)
  12756. nid = NID_stateOrProvinceName;
  12757. #endif /* OPENSSL_EXTRA */
  12758. }
  12759. else if (id == ASN_ORG_NAME) {
  12760. copy = WOLFSSL_ORG_NAME;
  12761. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  12762. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12763. if (nameType == SUBJECT) {
  12764. cert->subjectO = (char*)&input[srcIdx];
  12765. cert->subjectOLen = strLen;
  12766. cert->subjectOEnc = (char)b;
  12767. }
  12768. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12769. else if (nameType == ISSUER) {
  12770. cert->issuerO = (char*)&input[srcIdx];
  12771. cert->issuerOLen = strLen;
  12772. cert->issuerOEnc = (char)b;
  12773. }
  12774. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12775. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12776. #if (defined(OPENSSL_EXTRA) || \
  12777. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12778. && !defined(WOLFCRYPT_ONLY)
  12779. nid = NID_organizationName;
  12780. #endif /* OPENSSL_EXTRA */
  12781. }
  12782. else if (id == ASN_ORGUNIT_NAME) {
  12783. copy = WOLFSSL_ORGUNIT_NAME;
  12784. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  12785. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12786. if (nameType == SUBJECT) {
  12787. cert->subjectOU = (char*)&input[srcIdx];
  12788. cert->subjectOULen = strLen;
  12789. cert->subjectOUEnc = (char)b;
  12790. }
  12791. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12792. else if (nameType == ISSUER) {
  12793. cert->issuerOU = (char*)&input[srcIdx];
  12794. cert->issuerOULen = strLen;
  12795. cert->issuerOUEnc = (char)b;
  12796. }
  12797. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12798. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12799. #if (defined(OPENSSL_EXTRA) || \
  12800. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12801. && !defined(WOLFCRYPT_ONLY)
  12802. nid = NID_organizationalUnitName;
  12803. #endif /* OPENSSL_EXTRA */
  12804. }
  12805. else if (id == ASN_SERIAL_NUMBER) {
  12806. copy = WOLFSSL_SERIAL_NUMBER;
  12807. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  12808. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12809. if (nameType == SUBJECT) {
  12810. cert->subjectSND = (char*)&input[srcIdx];
  12811. cert->subjectSNDLen = strLen;
  12812. cert->subjectSNDEnc = (char)b;
  12813. }
  12814. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12815. else if (nameType == ISSUER) {
  12816. cert->issuerSND = (char*)&input[srcIdx];
  12817. cert->issuerSNDLen = strLen;
  12818. cert->issuerSNDEnc = (char)b;
  12819. }
  12820. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12821. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12822. #if (defined(OPENSSL_EXTRA) || \
  12823. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12824. && !defined(WOLFCRYPT_ONLY)
  12825. nid = NID_serialNumber;
  12826. #endif /* OPENSSL_EXTRA */
  12827. }
  12828. else if (id == ASN_USER_ID) {
  12829. copy = WOLFSSL_USER_ID;
  12830. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12831. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12832. if (nameType == SUBJECT) {
  12833. cert->subjectUID = (char*)&input[srcIdx];
  12834. cert->subjectUIDLen = strLen;
  12835. cert->subjectUIDEnc = (char)b;
  12836. }
  12837. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12838. #if (defined(OPENSSL_EXTRA) || \
  12839. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12840. && !defined(WOLFCRYPT_ONLY)
  12841. nid = NID_userId;
  12842. #endif /* OPENSSL_EXTRA */
  12843. }
  12844. #ifdef WOLFSSL_CERT_EXT
  12845. else if (id == ASN_STREET_ADDR) {
  12846. copy = WOLFSSL_STREET_ADDR_NAME;
  12847. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  12848. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12849. if (nameType == SUBJECT) {
  12850. cert->subjectStreet = (char*)&input[srcIdx];
  12851. cert->subjectStreetLen = strLen;
  12852. cert->subjectStreetEnc = (char)b;
  12853. }
  12854. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12855. #if (defined(OPENSSL_EXTRA) || \
  12856. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12857. && !defined(WOLFCRYPT_ONLY)
  12858. nid = NID_streetAddress;
  12859. #endif /* OPENSSL_EXTRA */
  12860. }
  12861. else if (id == ASN_BUS_CAT) {
  12862. copy = WOLFSSL_BUS_CAT;
  12863. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  12864. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12865. if (nameType == SUBJECT) {
  12866. cert->subjectBC = (char*)&input[srcIdx];
  12867. cert->subjectBCLen = strLen;
  12868. cert->subjectBCEnc = (char)b;
  12869. }
  12870. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12871. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12872. && !defined(WOLFCRYPT_ONLY)
  12873. nid = NID_businessCategory;
  12874. #endif /* OPENSSL_EXTRA */
  12875. }
  12876. else if (id == ASN_POSTAL_CODE) {
  12877. copy = WOLFSSL_POSTAL_NAME;
  12878. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  12879. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12880. if (nameType == SUBJECT) {
  12881. cert->subjectPC = (char*)&input[srcIdx];
  12882. cert->subjectPCLen = strLen;
  12883. cert->subjectPCEnc = (char)b;
  12884. }
  12885. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12886. #if (defined(OPENSSL_EXTRA) || \
  12887. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12888. && !defined(WOLFCRYPT_ONLY)
  12889. nid = NID_postalCode;
  12890. #endif /* OPENSSL_EXTRA */
  12891. }
  12892. #endif /* WOLFSSL_CERT_EXT */
  12893. }
  12894. #ifdef WOLFSSL_CERT_EXT
  12895. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  12896. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  12897. ASN_JOI_PREFIX_SZ)) &&
  12898. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  12899. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  12900. {
  12901. srcIdx += ASN_JOI_PREFIX_SZ;
  12902. id = input[srcIdx++];
  12903. b = input[srcIdx++]; /* encoding */
  12904. if (GetLength(input, &srcIdx, &strLen,
  12905. maxIdx) < 0) {
  12906. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12907. !defined(WOLFCRYPT_ONLY)
  12908. wolfSSL_X509_NAME_free(dName);
  12909. #endif /* OPENSSL_EXTRA */
  12910. return ASN_PARSE_E;
  12911. }
  12912. /* Check for jurisdiction of incorporation country name */
  12913. if (id == ASN_JOI_C) {
  12914. copy = WOLFSSL_JOI_C;
  12915. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  12916. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12917. if (nameType == SUBJECT) {
  12918. cert->subjectJC = (char*)&input[srcIdx];
  12919. cert->subjectJCLen = strLen;
  12920. cert->subjectJCEnc = (char)b;
  12921. }
  12922. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12923. #if (defined(OPENSSL_EXTRA) || \
  12924. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12925. && !defined(WOLFCRYPT_ONLY)
  12926. nid = NID_jurisdictionCountryName;
  12927. #endif /* OPENSSL_EXTRA */
  12928. }
  12929. /* Check for jurisdiction of incorporation state name */
  12930. else if (id == ASN_JOI_ST) {
  12931. copy = WOLFSSL_JOI_ST;
  12932. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12933. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12934. if (nameType == SUBJECT) {
  12935. cert->subjectJS = (char*)&input[srcIdx];
  12936. cert->subjectJSLen = strLen;
  12937. cert->subjectJSEnc = (char)b;
  12938. }
  12939. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12940. #if (defined(OPENSSL_EXTRA) || \
  12941. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12942. && !defined(WOLFCRYPT_ONLY)
  12943. nid = NID_jurisdictionStateOrProvinceName;
  12944. #endif /* OPENSSL_EXTRA */
  12945. }
  12946. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12947. WOLFSSL_MSG("ASN Name too big, skipping");
  12948. tooBig = TRUE;
  12949. }
  12950. }
  12951. #endif /* WOLFSSL_CERT_EXT */
  12952. else {
  12953. /* skip */
  12954. byte email = FALSE;
  12955. byte pilot = FALSE;
  12956. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  12957. id = ASN_EMAIL_NAME;
  12958. email = TRUE;
  12959. }
  12960. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  12961. /* last value of OID is the type of pilot attribute */
  12962. id = input[srcIdx + (word32)oidSz - 1];
  12963. if (id == 0x01)
  12964. id = ASN_USER_ID;
  12965. pilot = TRUE;
  12966. }
  12967. srcIdx += (word32)oidSz + 1;
  12968. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  12969. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12970. !defined(WOLFCRYPT_ONLY)
  12971. wolfSSL_X509_NAME_free(dName);
  12972. #endif /* OPENSSL_EXTRA */
  12973. return ASN_PARSE_E;
  12974. }
  12975. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12976. WOLFSSL_MSG("ASN name too big, skipping");
  12977. tooBig = TRUE;
  12978. }
  12979. if (email) {
  12980. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12981. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12982. WOLFSSL_MSG("ASN name too big, skipping");
  12983. tooBig = TRUE;
  12984. }
  12985. else {
  12986. copy = WOLFSSL_EMAIL_ADDR;
  12987. }
  12988. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12989. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12990. if (nameType == SUBJECT) {
  12991. cert->subjectEmail = (char*)&input[srcIdx];
  12992. cert->subjectEmailLen = strLen;
  12993. }
  12994. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12995. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12996. else if (nameType == ISSUER) {
  12997. cert->issuerEmail = (char*)&input[srcIdx];
  12998. cert->issuerEmailLen = strLen;
  12999. }
  13000. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  13001. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  13002. #if (defined(OPENSSL_EXTRA) || \
  13003. defined(OPENSSL_EXTRA_X509_SMALL)) \
  13004. && !defined(WOLFCRYPT_ONLY)
  13005. nid = NID_emailAddress;
  13006. #endif /* OPENSSL_EXTRA */
  13007. }
  13008. if (pilot) {
  13009. switch (id) {
  13010. case ASN_USER_ID:
  13011. copy = WOLFSSL_USER_ID;
  13012. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  13013. #if (defined(OPENSSL_EXTRA) || \
  13014. defined(OPENSSL_EXTRA_X509_SMALL)) \
  13015. && !defined(WOLFCRYPT_ONLY)
  13016. nid = NID_userId;
  13017. #endif /* OPENSSL_EXTRA */
  13018. break;
  13019. case ASN_DOMAIN_COMPONENT:
  13020. copy = WOLFSSL_DOMAIN_COMPONENT;
  13021. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  13022. #if (defined(OPENSSL_EXTRA) || \
  13023. defined(OPENSSL_EXTRA_X509_SMALL)) \
  13024. && !defined(WOLFCRYPT_ONLY)
  13025. nid = NID_domainComponent;
  13026. #endif /* OPENSSL_EXTRA */
  13027. break;
  13028. case ASN_FAVOURITE_DRINK:
  13029. copy = WOLFSSL_FAVOURITE_DRINK;
  13030. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  13031. #if (defined(OPENSSL_EXTRA) || \
  13032. defined(OPENSSL_EXTRA_X509_SMALL)) \
  13033. && !defined(WOLFCRYPT_ONLY)
  13034. nid = NID_favouriteDrink;
  13035. #endif /* OPENSSL_EXTRA */
  13036. break;
  13037. case ASN_CONTENT_TYPE:
  13038. copy = WOLFSSL_CONTENT_TYPE;
  13039. copyLen = sizeof(WOLFSSL_CONTENT_TYPE) - 1;
  13040. #if (defined(OPENSSL_EXTRA) || \
  13041. defined(OPENSSL_EXTRA_X509_SMALL)) \
  13042. && !defined(WOLFCRYPT_ONLY)
  13043. nid = NID_pkcs9_contentType;
  13044. #endif /* OPENSSL_EXTRA */
  13045. break;
  13046. default:
  13047. WOLFSSL_MSG("Unknown pilot attribute type");
  13048. #if (defined(OPENSSL_EXTRA) || \
  13049. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  13050. !defined(WOLFCRYPT_ONLY)
  13051. wolfSSL_X509_NAME_free(dName);
  13052. #endif /* OPENSSL_EXTRA */
  13053. return ASN_PARSE_E;
  13054. }
  13055. }
  13056. }
  13057. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  13058. {
  13059. WOLFSSL_MSG("ASN Name too big, skipping");
  13060. tooBig = TRUE;
  13061. }
  13062. if ((copy != NULL) && !tooBig) {
  13063. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  13064. idx += (word32)copyLen;
  13065. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  13066. idx += (word32)strLen;
  13067. }
  13068. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  13069. !defined(WOLFCRYPT_ONLY)
  13070. switch (b) {
  13071. case CTC_UTF8:
  13072. enc = MBSTRING_UTF8;
  13073. break;
  13074. case CTC_PRINTABLE:
  13075. enc = V_ASN1_PRINTABLESTRING;
  13076. break;
  13077. default:
  13078. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  13079. enc = MBSTRING_UTF8;
  13080. }
  13081. if (nid != NID_undef) {
  13082. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  13083. &input[srcIdx], strLen, -1, -1) !=
  13084. WOLFSSL_SUCCESS) {
  13085. wolfSSL_X509_NAME_free(dName);
  13086. return ASN_PARSE_E;
  13087. }
  13088. }
  13089. #endif /* OPENSSL_EXTRA */
  13090. srcIdx += (word32)strLen;
  13091. }
  13092. full[idx++] = 0;
  13093. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  13094. !defined(WOLFCRYPT_ONLY)
  13095. if (nameType == ISSUER) {
  13096. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  13097. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  13098. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  13099. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  13100. #endif
  13101. cert->issuerName = dName;
  13102. }
  13103. else {
  13104. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  13105. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  13106. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  13107. #endif
  13108. cert->subjectName = dName;
  13109. }
  13110. #endif
  13111. *inOutIdx = srcIdx;
  13112. return 0;
  13113. #else
  13114. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  13115. int ret = 0;
  13116. word32 idx = 0;
  13117. int len;
  13118. word32 srcIdx = *inOutIdx;
  13119. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  13120. WOLFSSL_X509_NAME* dName = NULL;
  13121. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  13122. WOLFSSL_MSG("Getting Cert Name");
  13123. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  13124. * calculated over the entire DER encoding of the Name field, including
  13125. * the tag and length. */
  13126. if (CalcHashId_ex(input + srcIdx, maxIdx - srcIdx, hash,
  13127. HashIdAlg(cert->signatureOID)) != 0) {
  13128. ret = ASN_PARSE_E;
  13129. }
  13130. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  13131. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  13132. if (ret == 0) {
  13133. /* Create an X509_NAME to hold data for OpenSSL compatibility APIs. */
  13134. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  13135. if (dName == NULL) {
  13136. ret = MEMORY_E;
  13137. }
  13138. }
  13139. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  13140. if (ret == 0) {
  13141. /* Expecting a SEQUENCE using up all data. */
  13142. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  13143. }
  13144. if (ret == 0) {
  13145. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  13146. /* Store pointer and length to raw issuer. */
  13147. if (nameType == ISSUER) {
  13148. cert->issuerRaw = &input[srcIdx];
  13149. cert->issuerRawLen = len;
  13150. }
  13151. #endif
  13152. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  13153. /* Store pointer and length to raw subject. */
  13154. if (nameType == SUBJECT) {
  13155. cert->subjectRaw = &input[srcIdx];
  13156. cert->subjectRawLen = len;
  13157. }
  13158. #endif
  13159. /* Process all RDNs in name. */
  13160. while ((ret == 0) && (srcIdx < maxIdx)) {
  13161. int nid = 0;
  13162. /* Initialize for data and setup RDN choice. */
  13163. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  13164. /* Ignore type OID as too many to store in table. */
  13165. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  13166. /* Parse RDN. */
  13167. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  13168. &srcIdx, maxIdx);
  13169. if (ret == 0) {
  13170. /* Put RDN data into certificate. */
  13171. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  13172. dataASN);
  13173. }
  13174. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  13175. /* TODO: push this back up to ssl.c
  13176. * (do parsing for WOLFSSL_X509_NAME on demand) */
  13177. if (ret == 0) {
  13178. int enc;
  13179. byte* str;
  13180. word32 strLen;
  13181. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  13182. /* Get string reference. */
  13183. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  13184. /* Convert BER tag to a OpenSSL type. */
  13185. switch (tag) {
  13186. case CTC_UTF8:
  13187. enc = MBSTRING_UTF8;
  13188. break;
  13189. case CTC_PRINTABLE:
  13190. enc = V_ASN1_PRINTABLESTRING;
  13191. break;
  13192. default:
  13193. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  13194. enc = MBSTRING_UTF8;
  13195. }
  13196. if (nid != 0) {
  13197. /* Add an entry to the X509_NAME. */
  13198. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  13199. (int)strLen, -1, -1) != WOLFSSL_SUCCESS) {
  13200. ret = ASN_PARSE_E;
  13201. }
  13202. }
  13203. }
  13204. #endif
  13205. }
  13206. }
  13207. if (ret == 0) {
  13208. /* Terminate string. */
  13209. full[idx] = 0;
  13210. /* Return index into encoding after name. */
  13211. *inOutIdx = srcIdx;
  13212. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  13213. /* Store X509_NAME in certificate. */
  13214. if (nameType == ISSUER) {
  13215. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  13216. defined(HAVE_LIGHTY)) && \
  13217. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  13218. dName->rawLen = (int)min((word32)cert->issuerRawLen,
  13219. WC_ASN_NAME_MAX);
  13220. XMEMCPY(dName->raw, cert->issuerRaw, (size_t)dName->rawLen);
  13221. #endif
  13222. cert->issuerName = dName;
  13223. }
  13224. else {
  13225. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  13226. dName->rawLen = (int)min((word32)cert->subjectRawLen,
  13227. WC_ASN_NAME_MAX);
  13228. XMEMCPY(dName->raw, cert->subjectRaw, (size_t)dName->rawLen);
  13229. #endif
  13230. cert->subjectName = dName;
  13231. }
  13232. }
  13233. else {
  13234. /* Dispose of unused X509_NAME. */
  13235. wolfSSL_X509_NAME_free(dName);
  13236. #endif
  13237. }
  13238. FREE_ASNGETDATA(dataASN, cert->heap);
  13239. return ret;
  13240. #endif /* WOLFSSL_ASN_TEMPLATE */
  13241. }
  13242. #ifdef WOLFSSL_ASN_TEMPLATE
  13243. /* ASN.1 template for certificate name. */
  13244. static const ASNItem certNameASN[] = {
  13245. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  13246. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  13247. };
  13248. enum {
  13249. CERTNAMEASN_IDX_OID = 0,
  13250. CERTNAMEASN_IDX_NAME
  13251. };
  13252. /* Number of items in ASN.1 template for certificate name. */
  13253. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  13254. #endif
  13255. /* Get a certificate name into the certificate object.
  13256. *
  13257. * Either the issuer or subject name.
  13258. *
  13259. * @param [in, out] cert Decoded certificate object.
  13260. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  13261. * @param [in] maxIdx Index of next item after certificate name.
  13262. * @return 0 on success.
  13263. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13264. * is invalid.
  13265. * @return BUFFER_E when data in buffer is too small.
  13266. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13267. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  13268. * @return MEMORY_E when dynamic memory allocation fails.
  13269. */
  13270. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  13271. {
  13272. #ifndef WOLFSSL_ASN_TEMPLATE
  13273. char* full;
  13274. byte* hash;
  13275. int length;
  13276. word32 localIdx;
  13277. byte tag;
  13278. WOLFSSL_MSG("Getting Name");
  13279. if (nameType == ISSUER) {
  13280. full = cert->issuer;
  13281. hash = cert->issuerHash;
  13282. }
  13283. else {
  13284. full = cert->subject;
  13285. hash = cert->subjectHash;
  13286. }
  13287. if (cert->srcIdx >= (word32)maxIdx) {
  13288. return BUFFER_E;
  13289. }
  13290. localIdx = cert->srcIdx;
  13291. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  13292. return ASN_PARSE_E;
  13293. }
  13294. if (tag == ASN_OBJECT_ID) {
  13295. WOLFSSL_MSG("Trying optional prefix...");
  13296. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  13297. return ASN_PARSE_E;
  13298. WOLFSSL_MSG("Got optional prefix");
  13299. }
  13300. localIdx = cert->srcIdx;
  13301. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  13302. return ASN_PARSE_E;
  13303. }
  13304. localIdx = cert->srcIdx + 1;
  13305. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  13306. return ASN_PARSE_E;
  13307. }
  13308. length += (int)(localIdx - cert->srcIdx);
  13309. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  13310. cert->srcIdx + (word32)length);
  13311. #else
  13312. ASNGetData dataASN[certNameASN_Length];
  13313. word32 idx = cert->srcIdx;
  13314. int ret = 0;
  13315. WOLFSSL_MSG("Getting Name");
  13316. XMEMSET(dataASN, 0, sizeof(dataASN));
  13317. /* Initialize for data and don't check optional prefix OID. */
  13318. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  13319. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  13320. cert->source, &idx, (word32)maxIdx);
  13321. if (ret == 0) {
  13322. char* full;
  13323. byte* hash;
  13324. /* Store offset of SEQUENCE that is start of name. */
  13325. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  13326. /* Get fields to fill in based on name type. */
  13327. if (nameType == ISSUER) {
  13328. full = cert->issuer;
  13329. hash = cert->issuerHash;
  13330. }
  13331. else {
  13332. full = cert->subject;
  13333. hash = cert->subjectHash;
  13334. }
  13335. /* Parse certificate name. */
  13336. ret = GetCertName(cert, full, hash, nameType, cert->source,
  13337. &cert->srcIdx, idx);
  13338. }
  13339. return ret;
  13340. #endif
  13341. }
  13342. #ifndef NO_ASN_TIME
  13343. /* two byte date/time, add to value */
  13344. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  13345. {
  13346. int i = *idx;
  13347. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  13348. date[i+1] > 0x39) {
  13349. return ASN_PARSE_E;
  13350. }
  13351. *value += (int)btoi(date[i++]) * 10;
  13352. *value += (int)btoi(date[i++]);
  13353. *idx = i;
  13354. return 0;
  13355. }
  13356. #ifdef WOLFSSL_LINUXKM
  13357. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  13358. {
  13359. int i = *idx;
  13360. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  13361. date[i+1] > 0x39) {
  13362. return ASN_PARSE_E;
  13363. }
  13364. *value += (long)btoi(date[i++]) * 10;
  13365. *value += (long)btoi(date[i++]);
  13366. *idx = i;
  13367. return 0;
  13368. }
  13369. #endif
  13370. int ExtractDate(const unsigned char* date, unsigned char format,
  13371. struct tm* certTime, int* idx)
  13372. {
  13373. XMEMSET(certTime, 0, sizeof(struct tm));
  13374. if (format == ASN_UTC_TIME) {
  13375. if (btoi(date[*idx]) >= 5)
  13376. certTime->tm_year = 1900;
  13377. else
  13378. certTime->tm_year = 2000;
  13379. }
  13380. else { /* format == GENERALIZED_TIME */
  13381. #ifdef WOLFSSL_LINUXKM
  13382. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  13383. #else
  13384. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  13385. #endif
  13386. certTime->tm_year *= 100;
  13387. }
  13388. #ifdef AVR
  13389. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  13390. /* AVR libc stores these as uint8_t instead of int */
  13391. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  13392. int tm_year = certTime->tm_year - 2000;
  13393. int tm_mon = certTime->tm_mon - 1;
  13394. int tm_mday = certTime->tm_mday;
  13395. int tm_hour = certTime->tm_hour;
  13396. int tm_min = certTime->tm_min;
  13397. int tm_sec = certTime->tm_sec;
  13398. #ifdef WOLFSSL_LINUXKM
  13399. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  13400. #else
  13401. if (GetTime(&tm_year, date, idx) != 0) return 0;
  13402. #endif
  13403. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  13404. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  13405. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  13406. if (GetTime(&tm_min , date, idx) != 0) return 0;
  13407. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  13408. /* Re-populate certTime with computed values */
  13409. certTime->tm_year = tm_year;
  13410. certTime->tm_mon = tm_mon;
  13411. certTime->tm_mday = tm_mday;
  13412. certTime->tm_hour = tm_hour;
  13413. certTime->tm_min = tm_min;
  13414. certTime->tm_sec = tm_sec;
  13415. #else
  13416. /* adjust tm_year, tm_mon */
  13417. #ifdef WOLFSSL_LINUXKM
  13418. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  13419. #else
  13420. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  13421. #endif
  13422. certTime->tm_year -= 1900;
  13423. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  13424. certTime->tm_mon -= 1;
  13425. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  13426. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  13427. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  13428. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  13429. #endif
  13430. return 1;
  13431. }
  13432. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  13433. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  13434. int GetTimeString(byte* date, int format, char* buf, int len)
  13435. {
  13436. struct tm t;
  13437. int idx = 0;
  13438. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  13439. return 0;
  13440. }
  13441. if (date[idx] != 'Z') {
  13442. WOLFSSL_MSG("UTCtime, not Zulu") ;
  13443. return 0;
  13444. }
  13445. /* place month in buffer */
  13446. buf[0] = '\0';
  13447. switch(t.tm_mon) {
  13448. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  13449. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  13450. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  13451. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  13452. case 4: XSTRNCAT(buf, "May ", 5); break;
  13453. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  13454. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  13455. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  13456. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  13457. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  13458. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  13459. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  13460. default:
  13461. return 0;
  13462. }
  13463. idx = 4; /* use idx now for char buffer */
  13464. if (XSNPRINTF(buf + idx, (size_t)(len - idx), "%2d %02d:%02d:%02d %d GMT",
  13465. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  13466. >= len - idx)
  13467. {
  13468. WOLFSSL_MSG("buffer overrun in GetTimeString");
  13469. return 0;
  13470. }
  13471. return 1;
  13472. }
  13473. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  13474. /* Check time struct for valid values. Returns 0 for success */
  13475. static int ValidateGmtime(struct tm* inTime)
  13476. {
  13477. int ret = 1;
  13478. if ((inTime != NULL) &&
  13479. (inTime->tm_sec >= 0) && (inTime->tm_sec <= 61) &&
  13480. (inTime->tm_min >= 0) && (inTime->tm_min <= 59) &&
  13481. (inTime->tm_hour >= 0) && (inTime->tm_hour <= 23) &&
  13482. (inTime->tm_mday >= 1) && (inTime->tm_mday <= 31) &&
  13483. (inTime->tm_mon >= 0) && (inTime->tm_mon <= 11) &&
  13484. (inTime->tm_wday >= 0) && (inTime->tm_wday <= 6) &&
  13485. (inTime->tm_yday >= 0) && (inTime->tm_yday <= 365)) {
  13486. ret = 0;
  13487. }
  13488. return ret;
  13489. }
  13490. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  13491. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  13492. /* Set current time string, either UTC or GeneralizedTime.
  13493. * (void*) tm should be a pointer to time_t, output is placed in buf.
  13494. *
  13495. * Return time string length placed in buf on success, negative on error */
  13496. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  13497. {
  13498. byte* data_ptr = buf;
  13499. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  13500. int data_len = 0;
  13501. WOLFSSL_ENTER("GetAsnTimeString");
  13502. if (buf == NULL || len == 0)
  13503. return BAD_FUNC_ARG;
  13504. XMEMSET(uf_time, 0, sizeof(uf_time));
  13505. /* GetFormattedTime returns length with null terminator */
  13506. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  13507. if (data_len <= 0) {
  13508. return ASN_TIME_E;
  13509. }
  13510. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  13511. else if (len < (word32)data_len + 2) {
  13512. return BUFFER_E;
  13513. }
  13514. if (data_len == ASN_UTC_TIME_SIZE-1) {
  13515. /* increment data_len for ASN length byte after adding the data_ptr */
  13516. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  13517. /* -1 below excludes null terminator */
  13518. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  13519. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  13520. data_ptr += ASN_UTC_TIME_SIZE - 1;
  13521. }
  13522. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  13523. /* increment data_len for ASN length byte after adding the data_ptr */
  13524. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  13525. /* -1 below excludes null terminator */
  13526. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  13527. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  13528. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  13529. }
  13530. else {
  13531. WOLFSSL_MSG("Invalid time size returned");
  13532. return ASN_TIME_E;
  13533. }
  13534. /* append null terminator */
  13535. *data_ptr = 0;
  13536. /* return length without null terminator */
  13537. return data_len;
  13538. }
  13539. /* return just the time string as either UTC or Generalized Time*/
  13540. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  13541. {
  13542. struct tm* ts = NULL;
  13543. struct tm* tmpTime = NULL;
  13544. int year, mon, day, hour, mini, sec;
  13545. int ret;
  13546. #if defined(NEED_TMP_TIME)
  13547. struct tm tmpTimeStorage;
  13548. tmpTime = &tmpTimeStorage;
  13549. #endif
  13550. /* Needed in case XGMTIME does not use the tmpTime argument. */
  13551. (void)tmpTime;
  13552. WOLFSSL_ENTER("GetFormattedTime");
  13553. if (buf == NULL || len == 0)
  13554. return BAD_FUNC_ARG;
  13555. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  13556. if (ValidateGmtime(ts)) {
  13557. WOLFSSL_MSG("failed to get time data.");
  13558. return ASN_TIME_E;
  13559. }
  13560. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  13561. * the null terminator. ASN encoded values leave off the terminator. */
  13562. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  13563. /* UTC Time */
  13564. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  13565. year = ts->tm_year;
  13566. }
  13567. else {
  13568. year = ts->tm_year - 100;
  13569. }
  13570. mon = ts->tm_mon + 1;
  13571. day = ts->tm_mday;
  13572. hour = ts->tm_hour;
  13573. mini = ts->tm_min;
  13574. sec = ts->tm_sec;
  13575. #if defined(WOLF_C89)
  13576. if (len < ASN_UTC_TIME_SIZE) {
  13577. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13578. return BUFFER_E;
  13579. }
  13580. ret = XSPRINTF((char*)buf,
  13581. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13582. hour, mini, sec);
  13583. #else
  13584. ret = XSNPRINTF((char*)buf, len,
  13585. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13586. hour, mini, sec);
  13587. #endif
  13588. }
  13589. else {
  13590. /* GeneralizedTime */
  13591. year = ts->tm_year + 1900;
  13592. mon = ts->tm_mon + 1;
  13593. day = ts->tm_mday;
  13594. hour = ts->tm_hour;
  13595. mini = ts->tm_min;
  13596. sec = ts->tm_sec;
  13597. #if defined(WOLF_C89)
  13598. if (len < ASN_GENERALIZED_TIME_SIZE) {
  13599. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13600. return BUFFER_E;
  13601. }
  13602. ret = XSPRINTF((char*)buf,
  13603. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13604. hour, mini, sec);
  13605. #else
  13606. ret = XSNPRINTF((char*)buf, len,
  13607. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13608. hour, mini, sec);
  13609. #endif
  13610. }
  13611. return ret;
  13612. }
  13613. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  13614. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  13615. #if defined(USE_WOLF_VALIDDATE)
  13616. /* to the second */
  13617. int DateGreaterThan(const struct tm* a, const struct tm* b)
  13618. {
  13619. if (a->tm_year > b->tm_year)
  13620. return 1;
  13621. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  13622. return 1;
  13623. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13624. a->tm_mday > b->tm_mday)
  13625. return 1;
  13626. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13627. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  13628. return 1;
  13629. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13630. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13631. a->tm_min > b->tm_min)
  13632. return 1;
  13633. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13634. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13635. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  13636. return 1;
  13637. return 0; /* false */
  13638. }
  13639. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  13640. {
  13641. return DateGreaterThan(b,a);
  13642. }
  13643. /* like atoi but only use first byte */
  13644. /* Make sure before and after dates are valid */
  13645. /* date = ASN.1 raw */
  13646. /* format = ASN_UTC_TIME or ASN_GENERALIZED_TIME */
  13647. /* dateType = AFTER or BEFORE */
  13648. int wc_ValidateDate(const byte* date, byte format, int dateType)
  13649. {
  13650. time_t ltime;
  13651. struct tm certTime;
  13652. struct tm* localTime;
  13653. struct tm* tmpTime;
  13654. int i = 0;
  13655. int timeDiff = 0;
  13656. int diffHH = 0, diffMM = 0;
  13657. #if defined(NEED_TMP_TIME)
  13658. struct tm tmpTimeStorage;
  13659. tmpTime = &tmpTimeStorage;
  13660. #else
  13661. tmpTime = NULL;
  13662. #endif
  13663. (void)tmpTime;
  13664. ltime = wc_Time(0);
  13665. #ifndef NO_TIME_SIGNEDNESS_CHECK
  13666. if (sizeof(ltime) == sizeof(word32) && (sword32)ltime < 0){
  13667. /* A negative response here could be due to a 32-bit time_t
  13668. * where the year is 2038 or later. */
  13669. WOLFSSL_MSG("wc_Time failed to return a valid value");
  13670. return 0;
  13671. }
  13672. #endif
  13673. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  13674. if (dateType == BEFORE) {
  13675. WOLFSSL_MSG("Skewing local time for before date check");
  13676. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  13677. }
  13678. #endif
  13679. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  13680. if (dateType == AFTER) {
  13681. WOLFSSL_MSG("Skewing local time for after date check");
  13682. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  13683. }
  13684. #endif
  13685. if (!ExtractDate(date, format, &certTime, &i)) {
  13686. WOLFSSL_MSG("Error extracting the date");
  13687. return 0;
  13688. }
  13689. if ((date[i] == '+') || (date[i] == '-')) {
  13690. int diffSign;
  13691. WOLFSSL_MSG("Using time differential, not Zulu") ;
  13692. diffSign = date[i++] == '+' ? 1 : -1 ;
  13693. if (GetTime(&diffHH, date, &i) != 0)
  13694. return 0;
  13695. if (GetTime(&diffMM, date, &i) != 0)
  13696. return 0;
  13697. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  13698. } else if (date[i] != 'Z') {
  13699. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  13700. return 0;
  13701. }
  13702. ltime -= (time_t)timeDiff;
  13703. localTime = XGMTIME(&ltime, tmpTime);
  13704. if (ValidateGmtime(localTime)) {
  13705. WOLFSSL_MSG("XGMTIME failed");
  13706. return 0;
  13707. }
  13708. if (dateType == BEFORE) {
  13709. if (DateLessThan(localTime, &certTime)) {
  13710. WOLFSSL_MSG("Date BEFORE check failed");
  13711. return 0;
  13712. }
  13713. }
  13714. else { /* dateType == AFTER */
  13715. if (DateGreaterThan(localTime, &certTime)) {
  13716. WOLFSSL_MSG("Date AFTER check failed");
  13717. return 0;
  13718. }
  13719. }
  13720. return 1;
  13721. }
  13722. #endif /* USE_WOLF_VALIDDATE */
  13723. int wc_GetTime(void* timePtr, word32 timeSize)
  13724. {
  13725. time_t* ltime = (time_t*)timePtr;
  13726. if (timePtr == NULL) {
  13727. return BAD_FUNC_ARG;
  13728. }
  13729. if ((word32)sizeof(time_t) > timeSize) {
  13730. return BUFFER_E;
  13731. }
  13732. *ltime = wc_Time(0);
  13733. return 0;
  13734. }
  13735. #ifdef TIME_OVERRIDES
  13736. #ifndef HAVE_TIME_T_TYPE
  13737. typedef long time_t;
  13738. #endif
  13739. extern time_t XTIME(time_t* t);
  13740. #endif
  13741. static wc_time_cb timeFunc = NULL;
  13742. int wc_SetTimeCb(wc_time_cb f)
  13743. {
  13744. timeFunc = f;
  13745. return 0;
  13746. }
  13747. time_t wc_Time(time_t* t)
  13748. {
  13749. if (timeFunc != NULL) {
  13750. return timeFunc(t);
  13751. }
  13752. return XTIME(t);
  13753. }
  13754. #endif /* !NO_ASN_TIME */
  13755. #ifdef WOLFSSL_ASN_TEMPLATE
  13756. /* TODO: use a CHOICE instead of two items? */
  13757. /* ASN.1 template for a date - either UTC or Generalized Time. */
  13758. static const ASNItem dateASN[] = {
  13759. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  13760. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  13761. };
  13762. enum {
  13763. DATEASN_IDX_UTC = 0,
  13764. DATEASN_IDX_GT
  13765. };
  13766. /* Number of items in ASN.1 template for a date. */
  13767. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  13768. #endif /* WOLFSSL_ASN_TEMPLATE */
  13769. /* Get date buffer, format and length. Returns 0=success or error */
  13770. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  13771. *
  13772. * @param [in] source Buffer containing encoded date.
  13773. * @param [in, out] idx On in, the index of the date.
  13774. * On out, index after date.
  13775. * @param [out] pDate Pointer into buffer of data bytes.
  13776. * @param [out] pFormat Format of date - BER/DER tag.
  13777. * @param [out] pLength Length of date bytes.
  13778. * @param [in] maxIdx Index of next item after date.
  13779. * @return 0 on success.
  13780. * @return BAD_FUNC_ARG when source or idx is NULL.
  13781. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13782. * is invalid.
  13783. * @return BUFFER_E when data in buffer is too small.
  13784. */
  13785. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  13786. byte* pFormat, int* pLength, word32 maxIdx)
  13787. {
  13788. #ifndef WOLFSSL_ASN_TEMPLATE
  13789. int length;
  13790. byte format;
  13791. if (source == NULL || idx == NULL)
  13792. return BAD_FUNC_ARG;
  13793. /* get ASN format header */
  13794. if (*idx+1 > maxIdx)
  13795. return BUFFER_E;
  13796. format = source[*idx];
  13797. *idx += 1;
  13798. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  13799. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  13800. return ASN_TIME_E;
  13801. }
  13802. /* get length */
  13803. if (GetLength(source, idx, &length, maxIdx) < 0)
  13804. return ASN_PARSE_E;
  13805. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  13806. return ASN_DATE_SZ_E;
  13807. /* return format, date and length */
  13808. if (pFormat)
  13809. *pFormat = format;
  13810. if (pDate)
  13811. *pDate = &source[*idx];
  13812. if (pLength)
  13813. *pLength = length;
  13814. *idx += (word32)length;
  13815. return 0;
  13816. #else
  13817. ASNGetData dataASN[dateASN_Length];
  13818. int ret = 0;
  13819. if ((source == NULL) || (idx == NULL)) {
  13820. ret = BAD_FUNC_ARG;
  13821. }
  13822. if (ret == 0) {
  13823. /* Initialize data. */
  13824. XMEMSET(dataASN, 0, sizeof(dataASN));
  13825. /* Parse date. */
  13826. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  13827. maxIdx);
  13828. }
  13829. if (ret == 0) {
  13830. /* Determine which tag was seen. */
  13831. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  13832. : DATEASN_IDX_GT;
  13833. /* Return data from seen item. */
  13834. if (pFormat != NULL) {
  13835. *pFormat = dataASN[i].tag;
  13836. }
  13837. if (pDate != NULL) {
  13838. *pDate = dataASN[i].data.ref.data;
  13839. }
  13840. if (pLength != NULL) {
  13841. *pLength = (int)dataASN[i].data.ref.length;
  13842. }
  13843. }
  13844. return ret;
  13845. #endif
  13846. }
  13847. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13848. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  13849. {
  13850. int ret, length;
  13851. const byte *datePtr = NULL;
  13852. byte date[MAX_DATE_SIZE];
  13853. byte format;
  13854. word32 startIdx = 0;
  13855. if (dateType == BEFORE)
  13856. cert->beforeDate = &cert->source[cert->srcIdx];
  13857. else
  13858. cert->afterDate = &cert->source[cert->srcIdx];
  13859. startIdx = cert->srcIdx;
  13860. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  13861. &length, (word32)maxIdx);
  13862. if (ret < 0)
  13863. return ret;
  13864. XMEMSET(date, 0, MAX_DATE_SIZE);
  13865. XMEMCPY(date, datePtr, (size_t)length);
  13866. if (dateType == BEFORE)
  13867. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  13868. else
  13869. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  13870. #ifndef NO_ASN_TIME_CHECK
  13871. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  13872. !XVALIDATE_DATE(date, format, dateType)) {
  13873. if (dateType == BEFORE) {
  13874. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  13875. return ASN_BEFORE_DATE_E;
  13876. }
  13877. else {
  13878. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  13879. return ASN_AFTER_DATE_E;
  13880. }
  13881. }
  13882. #else
  13883. (void)verify;
  13884. #endif
  13885. return 0;
  13886. }
  13887. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  13888. {
  13889. int length;
  13890. int badDate = 0;
  13891. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  13892. return ASN_PARSE_E;
  13893. maxIdx = (int)cert->srcIdx + length;
  13894. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  13895. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  13896. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  13897. return ASN_AFTER_DATE_E;
  13898. if (badDate != 0)
  13899. return badDate;
  13900. return 0;
  13901. }
  13902. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13903. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  13904. byte* format, int* length)
  13905. {
  13906. int ret;
  13907. word32 idx = 0;
  13908. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  13909. return ret;
  13910. }
  13911. #ifndef NO_ASN_TIME
  13912. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  13913. struct tm* timearg)
  13914. {
  13915. int idx = 0;
  13916. (void)length;
  13917. if (!ExtractDate(date, format, timearg, &idx))
  13918. return ASN_TIME_E;
  13919. return 0;
  13920. }
  13921. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  13922. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  13923. {
  13924. int ret = 0;
  13925. const byte* date;
  13926. byte format;
  13927. int length;
  13928. if (cert == NULL)
  13929. return BAD_FUNC_ARG;
  13930. if (before && cert->beforeDateSz > 0) {
  13931. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  13932. &format, &length);
  13933. if (ret == 0)
  13934. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  13935. }
  13936. if (after && cert->afterDateSz > 0) {
  13937. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  13938. &format, &length);
  13939. if (ret == 0)
  13940. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  13941. }
  13942. return ret;
  13943. }
  13944. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  13945. #endif /* !NO_ASN_TIME */
  13946. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  13947. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  13948. {
  13949. int length;
  13950. word32 endSeqIdx;
  13951. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13952. return ASN_PARSE_E;
  13953. endSeqIdx = cert->srcIdx + (word32)length;
  13954. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  13955. maxIdx) < 0) {
  13956. return ASN_OBJECT_ID_E;
  13957. }
  13958. if (cert->srcIdx != endSeqIdx) {
  13959. #ifdef WC_RSA_PSS
  13960. if (*sigOid == CTC_RSASSAPSS) {
  13961. cert->sigParamsIndex = cert->srcIdx;
  13962. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  13963. }
  13964. else
  13965. #endif
  13966. /* Only allowed a ASN NULL header with zero length. */
  13967. if (endSeqIdx - cert->srcIdx != 2)
  13968. return ASN_PARSE_E;
  13969. else {
  13970. byte tag;
  13971. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  13972. return ASN_PARSE_E;
  13973. if (tag != ASN_TAG_NULL)
  13974. return ASN_PARSE_E;
  13975. }
  13976. }
  13977. cert->srcIdx = endSeqIdx;
  13978. return 0;
  13979. }
  13980. #endif
  13981. #ifndef NO_CERTS
  13982. #ifdef WOLFSSL_ASN_TEMPLATE
  13983. /* TODO: move code around to not require this. */
  13984. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  13985. int* badDateRet, int stopAtPubKey,
  13986. int stopAfterPubKey);
  13987. #endif
  13988. /* Assumes the target is a Raw-Public-Key certificate and parsed up to the
  13989. * public key. Returns CRYPTOCB_UNAVAILABLE if it determines that the cert is
  13990. * different from the Paw-Public-Key cert. In that case, cert->srcIdx is not
  13991. * consumed so as succeeding parse function can take over.
  13992. * In case that the target is Raw-Public-Key cert and contains a public key,
  13993. * returns 0 and consumes cert->srcIdx so as a public key retrieval function
  13994. * can follow.
  13995. */
  13996. #if defined(HAVE_RPK)
  13997. int TryDecodeRPKToKey(DecodedCert* cert)
  13998. {
  13999. int ret = 0, len;
  14000. word32 tmpIdx;
  14001. word32 oid;
  14002. WOLFSSL_ENTER("TryDecodeRPKToKey");
  14003. if (cert == NULL)
  14004. return BAD_FUNC_ARG;
  14005. tmpIdx = cert->srcIdx;
  14006. /* both X509 cert and RPK cert should start with a Sequence tag */
  14007. if (ret == 0) {
  14008. if (GetSequence(cert->source, &tmpIdx, &len, cert->maxIdx) < 0)
  14009. ret = ASN_PARSE_E;
  14010. }
  14011. /* TBSCertificate of X509 or AlgorithmIdentifier of RPK cert */
  14012. if (ret == 0) {
  14013. if (GetSequence(cert->source, &tmpIdx, &len, cert->maxIdx) < 0)
  14014. ret = ASN_PARSE_E;
  14015. }
  14016. /* OBJ ID should be next in RPK cert */
  14017. if (ret == 0) {
  14018. if (GetObjectId(cert->source, &tmpIdx, &oid, oidKeyType, cert->maxIdx)
  14019. < 0)
  14020. ret = CRYPTOCB_UNAVAILABLE;
  14021. }
  14022. /* consume cert->srcIdx */
  14023. if (ret == 0) {
  14024. WOLFSSL_MSG("Looks like RPK certificate");
  14025. cert->srcIdx = tmpIdx;
  14026. }
  14027. WOLFSSL_LEAVE("TryDecodeRPKToKey", ret);
  14028. return ret;
  14029. }
  14030. #endif /* HAVE_RPK */
  14031. /* Parse the certificate up to the X.509 public key.
  14032. *
  14033. * If cert data is invalid then badDate get set to error value.
  14034. *
  14035. * @param [in, out] cert Decoded certificate object.
  14036. * @param [in] verify Whether to verify dates.
  14037. * @param [out] badDate Error code when verify dates.
  14038. * @return 0 on success.
  14039. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  14040. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  14041. * @return ASN_DATE_SZ_E when time data is not supported.
  14042. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  14043. * is invalid.
  14044. * @return BUFFER_E when data in buffer is too small.
  14045. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  14046. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  14047. */
  14048. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  14049. {
  14050. #ifndef WOLFSSL_ASN_TEMPLATE
  14051. int ret;
  14052. if (cert == NULL || badDate == NULL)
  14053. return BAD_FUNC_ARG;
  14054. *badDate = 0;
  14055. if ( (ret = GetCertHeader(cert)) < 0)
  14056. return ret;
  14057. WOLFSSL_MSG("Got Cert Header");
  14058. #ifdef WOLFSSL_CERT_REQ
  14059. if (!cert->isCSR) {
  14060. #endif
  14061. /* Using the sigIndex as the upper bound because that's where the
  14062. * actual certificate data ends. */
  14063. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  14064. return ret;
  14065. WOLFSSL_MSG("Got Algo ID");
  14066. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  14067. return ret;
  14068. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  14069. *badDate = ret;
  14070. #ifdef WOLFSSL_CERT_REQ
  14071. }
  14072. #endif
  14073. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  14074. return ret;
  14075. WOLFSSL_MSG("Got Subject Name");
  14076. return ret;
  14077. #else
  14078. /* Use common decode routine and stop at public key. */
  14079. int ret;
  14080. *badDate = 0;
  14081. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  14082. if (ret >= 0) {
  14083. /* Store current index: public key. */
  14084. cert->srcIdx = (word32)ret;
  14085. }
  14086. return ret;
  14087. #endif /* WOLFSSL_ASN_TEMPLATE */
  14088. }
  14089. /* Parse the certificate up to and including X.509 public key.
  14090. *
  14091. * @param [in, out] cert Decoded certificate object.
  14092. * @param [in] verify Whether to verify dates.
  14093. * @return 0 on success.
  14094. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  14095. * @return ASN_DATE_SZ_E when time data is not supported.
  14096. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  14097. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  14098. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  14099. * is invalid.
  14100. * @return BUFFER_E when data in buffer is too small.
  14101. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  14102. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  14103. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  14104. */
  14105. int DecodeToKey(DecodedCert* cert, int verify)
  14106. {
  14107. #ifndef WOLFSSL_ASN_TEMPLATE
  14108. int badDate = 0;
  14109. int ret;
  14110. #if defined(HAVE_RPK)
  14111. /* Raw Public Key certificate has only a SubjectPublicKeyInfo structure
  14112. * as its contents. So try to call GetCertKey to get public key from it.
  14113. * If it fails, the cert should be a X509 cert and proceed to process as
  14114. * x509 cert. */
  14115. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  14116. if (ret == 0) {
  14117. WOLFSSL_MSG("Raw Public Key certificate found and parsed");
  14118. cert->isRPK = 1;
  14119. return ret;
  14120. }
  14121. #endif /* HAVE_RPK */
  14122. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  14123. return ret;
  14124. /* Determine if self signed */
  14125. #ifdef WOLFSSL_CERT_REQ
  14126. if (cert->isCSR)
  14127. cert->selfSigned = 1;
  14128. else
  14129. #endif
  14130. {
  14131. cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
  14132. KEYID_SIZE) == 0 ? 1 : 0;
  14133. }
  14134. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  14135. if (ret != 0)
  14136. return ret;
  14137. WOLFSSL_MSG("Got Key");
  14138. if (badDate != 0)
  14139. return badDate;
  14140. return ret;
  14141. #else
  14142. int ret;
  14143. int badDate = 0;
  14144. /* Call internal version and stop after public key. */
  14145. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  14146. /* Always return date errors. */
  14147. if (ret == 0) {
  14148. ret = badDate;
  14149. }
  14150. return ret;
  14151. #endif /* WOLFSSL_ASN_TEMPLATE */
  14152. }
  14153. #if !defined(WOLFSSL_ASN_TEMPLATE)
  14154. static int GetSignature(DecodedCert* cert)
  14155. {
  14156. int length;
  14157. int ret;
  14158. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  14159. NULL);
  14160. if (ret != 0)
  14161. return ret;
  14162. cert->sigLength = (word32)length;
  14163. cert->signature = &cert->source[cert->srcIdx];
  14164. cert->srcIdx += cert->sigLength;
  14165. if (cert->srcIdx != cert->maxIdx)
  14166. return ASN_PARSE_E;
  14167. return 0;
  14168. }
  14169. #endif /* !WOLFSSL_ASN_TEMPLATE */
  14170. #endif /* !NO_CERTS */
  14171. #ifndef WOLFSSL_ASN_TEMPLATE
  14172. static word32 SetOctetString8Bit(word32 len, byte* output)
  14173. {
  14174. output[0] = ASN_OCTET_STRING;
  14175. output[1] = (byte)len;
  14176. return 2;
  14177. }
  14178. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  14179. {
  14180. word32 idx = SetOctetString8Bit(digSz, output);
  14181. XMEMCPY(&output[idx], digest, digSz);
  14182. return idx + digSz;
  14183. }
  14184. #endif
  14185. /* Encode a length for DER.
  14186. *
  14187. * @param [in] length Value to encode.
  14188. * @param [out] output Buffer to encode into.
  14189. * @return Number of bytes encoded.
  14190. */
  14191. word32 SetLength(word32 length, byte* output)
  14192. {
  14193. /* Start encoding at start of buffer. */
  14194. word32 i = 0;
  14195. if (length < ASN_LONG_LENGTH) {
  14196. /* Only one byte needed to encode. */
  14197. if (output) {
  14198. /* Write out length value. */
  14199. output[i] = (byte)length;
  14200. }
  14201. /* Skip over length. */
  14202. i++;
  14203. }
  14204. else {
  14205. /* Calculate the number of bytes required to encode value. */
  14206. byte j = (byte)BytePrecision(length);
  14207. if (output) {
  14208. /* Encode count byte. */
  14209. output[i] = (byte)(j | ASN_LONG_LENGTH);
  14210. }
  14211. /* Skip over count byte. */
  14212. i++;
  14213. /* Encode value as a big-endian byte array. */
  14214. for (; j > 0; --j) {
  14215. if (output) {
  14216. /* Encode next most-significant byte. */
  14217. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  14218. }
  14219. /* Skip over byte. */
  14220. i++;
  14221. }
  14222. }
  14223. /* Return number of bytes in encoded length. */
  14224. return i;
  14225. }
  14226. word32 SetLengthEx(word32 length, byte* output, byte isIndef)
  14227. {
  14228. if (isIndef) {
  14229. if (output != NULL) {
  14230. output[0] = ASN_INDEF_LENGTH;
  14231. }
  14232. return 1;
  14233. }
  14234. else {
  14235. return SetLength(length, output);
  14236. }
  14237. }
  14238. /* Encode a DER header - type/tag and length.
  14239. *
  14240. * @param [in] tag DER tag of ASN.1 item.
  14241. * @param [in] len Length of data in ASN.1 item.
  14242. * @param [out] output Buffer to encode into.
  14243. * @return Number of bytes encoded.
  14244. */
  14245. static word32 SetHeader(byte tag, word32 len, byte* output, byte isIndef)
  14246. {
  14247. if (output) {
  14248. /* Encode tag first. */
  14249. output[0] = tag;
  14250. }
  14251. /* Encode the length. */
  14252. return SetLengthEx(len, output ? output + ASN_TAG_SZ : NULL, isIndef) +
  14253. ASN_TAG_SZ;
  14254. }
  14255. /* Encode a SEQUENCE header in DER.
  14256. *
  14257. * @param [in] len Length of data in SEQUENCE.
  14258. * @param [out] output Buffer to encode into.
  14259. * @return Number of bytes encoded.
  14260. */
  14261. word32 SetSequence(word32 len, byte* output)
  14262. {
  14263. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output, 0);
  14264. }
  14265. word32 SetSequenceEx(word32 len, byte* output, byte isIndef)
  14266. {
  14267. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output, isIndef);
  14268. }
  14269. /* Encode an OCTET STRING header in DER.
  14270. *
  14271. * @param [in] len Length of data in OCTET STRING.
  14272. * @param [out] output Buffer to encode into.
  14273. * @return Number of bytes encoded.
  14274. */
  14275. word32 SetOctetString(word32 len, byte* output)
  14276. {
  14277. return SetHeader(ASN_OCTET_STRING, len, output, 0);
  14278. }
  14279. word32 SetOctetStringEx(word32 len, byte* output, byte indef)
  14280. {
  14281. if (indef)
  14282. return SetHeader(ASN_OCTET_STRING | ASN_CONSTRUCTED, len, output, indef);
  14283. return SetOctetString(len, output);
  14284. }
  14285. /* Encode a SET header in DER.
  14286. *
  14287. * @param [in] len Length of data in SET.
  14288. * @param [out] output Buffer to encode into.
  14289. * @return Number of bytes encoded.
  14290. */
  14291. word32 SetSet(word32 len, byte* output)
  14292. {
  14293. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output, 0);
  14294. }
  14295. /* Encode an implicit context specific header in DER.
  14296. *
  14297. * Implicit means that it is constructed only if the included ASN.1 item is.
  14298. *
  14299. * @param [in] tag Tag for the implicit ASN.1 item.
  14300. * @param [in] number Context specific number.
  14301. * @param [in] len Length of data in SET.
  14302. * @param [out] output Buffer to encode into.
  14303. * @return Number of bytes encoded.
  14304. */
  14305. word32 SetImplicit(byte tag, byte number, word32 len, byte* output, byte isIndef)
  14306. {
  14307. byte useIndef = 0;
  14308. if ((tag == ASN_OCTET_STRING) && isIndef) {
  14309. tag = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number;
  14310. }
  14311. else {
  14312. tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ?
  14313. ASN_CONSTRUCTED : 0) | ASN_CONTEXT_SPECIFIC | number);
  14314. }
  14315. if (isIndef && (tag & ASN_CONSTRUCTED)) {
  14316. useIndef = 1;
  14317. }
  14318. return SetHeader(tag, len, output, useIndef);
  14319. }
  14320. /* Encode an explicit context specific header in DER.
  14321. *
  14322. * Explicit means that there will be an ASN.1 item underneath.
  14323. *
  14324. * @param [in] number Context specific number.
  14325. * @param [in] len Length of data in SET.
  14326. * @param [out] output Buffer to encode into.
  14327. * @return Number of bytes encoded.
  14328. */
  14329. word32 SetExplicit(byte number, word32 len, byte* output, byte isIndef)
  14330. {
  14331. return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
  14332. len, output, isIndef);
  14333. }
  14334. #if defined(OPENSSL_EXTRA)
  14335. /* Encode an Othername into DER.
  14336. *
  14337. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  14338. * @param [out] output Buffer to encode into. If NULL, don't encode.
  14339. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  14340. */
  14341. word32 SetOthername(void *name, byte *output)
  14342. {
  14343. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  14344. char *nameStr = NULL;
  14345. word32 nameSz = 0;
  14346. word32 len = 0;
  14347. if ((nm == NULL) || (nm->value == NULL)) {
  14348. WOLFSSL_MSG("otherName value is NULL");
  14349. return WOLFSSL_FAILURE;
  14350. }
  14351. nameStr = nm->value->value.utf8string->data;
  14352. nameSz = (word32)nm->value->value.utf8string->length;
  14353. len = nm->type_id->objSz +
  14354. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL, 0) +
  14355. SetHeader(CTC_UTF8, nameSz, NULL, 0) + nameSz;
  14356. if (output != NULL) {
  14357. /* otherName OID */
  14358. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  14359. output += nm->type_id->objSz;
  14360. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  14361. output, 0);
  14362. output += SetHeader(CTC_UTF8, nameSz, output, 0);
  14363. XMEMCPY(output, nameStr, nameSz);
  14364. }
  14365. return len;
  14366. }
  14367. #endif /* OPENSSL_EXTRA */
  14368. #ifdef HAVE_ECC
  14369. /* Determines whether the signature algorithm is using ECDSA.
  14370. *
  14371. * @param [in] algoOID Signature algorithm identifier.
  14372. * @return 1 when algorithm is using ECDSA.
  14373. * @return 0 otherwise.
  14374. */
  14375. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  14376. {
  14377. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  14378. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  14379. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  14380. return 1;
  14381. }
  14382. return 0;
  14383. }
  14384. #endif
  14385. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  14386. * and post-quantum algorithms.
  14387. *
  14388. * @param [in] algoOID Algorithm OID.
  14389. * @return 1 when is EC signing algorithm.
  14390. * @return 0 otherwise.
  14391. */
  14392. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  14393. {
  14394. (void)algoOID;
  14395. return (0
  14396. #ifdef HAVE_ECC
  14397. || IsSigAlgoECDSA(algoOID)
  14398. #endif
  14399. #ifdef WOLFSSL_SM2
  14400. || (algoOID == SM2k)
  14401. #endif
  14402. #ifdef HAVE_ED25519
  14403. || (algoOID == ED25519k)
  14404. #endif
  14405. #ifdef HAVE_CURVE25519
  14406. || (algoOID == X25519k)
  14407. #endif
  14408. #ifdef HAVE_ED448
  14409. || (algoOID == ED448k)
  14410. #endif
  14411. #ifdef HAVE_CURVE448
  14412. || (algoOID == X448k)
  14413. #endif
  14414. #ifdef HAVE_PQC
  14415. #ifdef HAVE_FACON
  14416. || (algoOID == FALCON_LEVEL1k)
  14417. || (algoOID == FALCON_LEVEL5k)
  14418. #endif
  14419. #ifdef HAVE_DILITHIUM
  14420. || (algoOID == DILITHIUM_LEVEL2k)
  14421. || (algoOID == DILITHIUM_LEVEL3k)
  14422. || (algoOID == DILITHIUM_LEVEL5k)
  14423. #endif
  14424. #ifdef HAVE_SPHINCS
  14425. || (algoOID == SPHINCS_FAST_LEVEL1k)
  14426. || (algoOID == SPHINCS_FAST_LEVEL3k)
  14427. || (algoOID == SPHINCS_FAST_LEVEL5k)
  14428. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  14429. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  14430. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  14431. #endif
  14432. #endif /* HAVE_PQC */
  14433. );
  14434. }
  14435. /* Encode an algorithm identifier.
  14436. *
  14437. * [algoOID, type] is unique.
  14438. *
  14439. * @param [in] algoOID Algorithm identifier.
  14440. * @param [out] output Buffer to hold encoding.
  14441. * @param [in] type Type of OID being encoded.
  14442. * @param [in] curveSz Add extra space for curve data.
  14443. * @return Encoded data size on success.
  14444. * @return 0 when dynamic memory allocation fails.
  14445. */
  14446. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  14447. {
  14448. #ifndef WOLFSSL_ASN_TEMPLATE
  14449. word32 tagSz, idSz, seqSz, algoSz = 0;
  14450. const byte* algoName = 0;
  14451. byte ID_Length[1 + MAX_LENGTH_SZ];
  14452. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  14453. word32 length = 0;
  14454. tagSz = (type == oidHashType ||
  14455. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  14456. (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
  14457. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  14458. if (algoName == NULL) {
  14459. WOLFSSL_MSG("Unknown Algorithm");
  14460. return 0;
  14461. }
  14462. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  14463. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  14464. /* Copy only algo to output for DSA keys */
  14465. if (algoOID == DSAk && output) {
  14466. XMEMCPY(output, ID_Length, idSz);
  14467. XMEMCPY(output + idSz, algoName, algoSz);
  14468. if (tagSz == 2)
  14469. SetASNNull(&output[seqSz + idSz + algoSz]);
  14470. }
  14471. else if (output) {
  14472. XMEMCPY(output, seqArray, seqSz);
  14473. XMEMCPY(output + seqSz, ID_Length, idSz);
  14474. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  14475. if (tagSz == 2)
  14476. SetASNNull(&output[seqSz + idSz + algoSz]);
  14477. }
  14478. if (algoOID == DSAk)
  14479. length = idSz + algoSz + tagSz;
  14480. else
  14481. length = seqSz + idSz + algoSz + tagSz;
  14482. return length;
  14483. #else
  14484. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  14485. int ret = 0;
  14486. const byte* algoName = 0;
  14487. word32 algoSz = 0;
  14488. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  14489. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  14490. if (algoName == NULL) {
  14491. WOLFSSL_MSG("Unknown Algorithm");
  14492. }
  14493. else {
  14494. int sz;
  14495. int o = 0;
  14496. /* Set the OID and OID type to encode. */
  14497. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  14498. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  14499. if (!(type == oidHashType ||
  14500. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  14501. (type == oidKeyType && algoOID == RSAk))) {
  14502. /* Don't put out NULL DER item. */
  14503. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  14504. }
  14505. if (algoOID == DSAk) {
  14506. /* Don't include SEQUENCE for DSA keys. */
  14507. o = 1;
  14508. }
  14509. else if (curveSz > 0) {
  14510. /* Don't put out NULL DER item. */
  14511. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  14512. /* Include space for extra data of length curveSz.
  14513. * Subtract 1 for sequence and 1 for length encoding. */
  14514. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  14515. (word32)curveSz - 2);
  14516. }
  14517. /* Calculate size of encoding. */
  14518. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  14519. (int)algoIdASN_Length - (int)o, &sz);
  14520. if (ret == 0 && output != NULL) {
  14521. /* Encode into buffer. */
  14522. SetASN_Items(algoIdASN + o, dataASN + o,
  14523. (int)algoIdASN_Length - (int)o, output);
  14524. if (curveSz > 0) {
  14525. /* Return size excluding curve data. */
  14526. sz = (int)(dataASN[o].offset -
  14527. dataASN[ALGOIDASN_IDX_NULL].offset);
  14528. }
  14529. }
  14530. if (ret == 0) {
  14531. /* Return encoded size. */
  14532. ret = sz;
  14533. }
  14534. else {
  14535. /* Unsigned return type so 0 indicates error. */
  14536. ret = 0;
  14537. }
  14538. }
  14539. FREE_ASNSETDATA(dataASN, NULL);
  14540. return (word32)ret;
  14541. #endif /* WOLFSSL_ASN_TEMPLATE */
  14542. }
  14543. #ifdef WOLFSSL_ASN_TEMPLATE
  14544. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  14545. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  14546. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  14547. */
  14548. static const ASNItem digestInfoASN[] = {
  14549. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14550. /* digestAlgorithm */
  14551. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14552. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  14553. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  14554. /* digest */
  14555. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  14556. };
  14557. enum {
  14558. DIGESTINFOASN_IDX_SEQ = 0,
  14559. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  14560. DIGESTINFOASN_IDX_DIGALGO_OID,
  14561. DIGESTINFOASN_IDX_DIGALGO_NULL,
  14562. DIGESTINFOASN_IDX_DIGEST
  14563. };
  14564. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  14565. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  14566. #endif
  14567. /* Encode signature.
  14568. *
  14569. * @param [out] out Buffer to hold encoding.
  14570. * @param [in] digest Buffer holding digest.
  14571. * @param [in] digSz Length of digest in bytes.
  14572. * @return Encoded data size on success.
  14573. * @return 0 when dynamic memory allocation fails.
  14574. */
  14575. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  14576. int hashOID)
  14577. {
  14578. #ifndef WOLFSSL_ASN_TEMPLATE
  14579. byte digArray[MAX_ENCODED_DIG_SZ];
  14580. byte algoArray[MAX_ALGO_SZ];
  14581. byte seqArray[MAX_SEQ_SZ];
  14582. word32 encDigSz, algoSz, seqSz;
  14583. encDigSz = SetDigest(digest, digSz, digArray);
  14584. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  14585. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  14586. XMEMCPY(out, seqArray, seqSz);
  14587. XMEMCPY(out + seqSz, algoArray, algoSz);
  14588. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  14589. return encDigSz + algoSz + seqSz;
  14590. #else
  14591. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  14592. int ret = 0;
  14593. int sz;
  14594. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  14595. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  14596. if (ret == 0) {
  14597. /* Set hash OID and type. */
  14598. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  14599. oidHashType);
  14600. /* Set digest. */
  14601. if (digest == out) {
  14602. XMEMCPY(dgst, digest, digSz);
  14603. digest = dgst;
  14604. }
  14605. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  14606. /* Calculate size of encoding. */
  14607. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  14608. }
  14609. if (ret == 0) {
  14610. /* Encode PKCS#1 v1.5 RSA signature. */
  14611. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  14612. ret = sz;
  14613. }
  14614. else {
  14615. /* Unsigned return type so 0 indicates error. */
  14616. ret = 0;
  14617. }
  14618. FREE_ASNSETDATA(dataASN, NULL);
  14619. return (word32)ret;
  14620. #endif
  14621. }
  14622. #ifndef NO_CERTS
  14623. int wc_GetCTC_HashOID(int type)
  14624. {
  14625. int ret;
  14626. enum wc_HashType hType;
  14627. hType = wc_HashTypeConvert(type);
  14628. ret = wc_HashGetOID(hType);
  14629. if (ret < 0) {
  14630. ret = 0; /* backwards compatibility */
  14631. }
  14632. return ret;
  14633. }
  14634. /* Initialize a signature context object.
  14635. *
  14636. * Object used for signing and verifying a certificate signature.
  14637. *
  14638. * @param [in, out] sigCtx Signature context object.
  14639. * @param [in] heap Dynamic memory hint.
  14640. * @param [in] devId Hardware device identifier.
  14641. */
  14642. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  14643. {
  14644. if (sigCtx) {
  14645. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  14646. sigCtx->devId = devId;
  14647. sigCtx->heap = heap;
  14648. }
  14649. }
  14650. /* Free dynamic data in a signature context object.
  14651. *
  14652. * @param [in, out] sigCtx Signature context object.
  14653. */
  14654. void FreeSignatureCtx(SignatureCtx* sigCtx)
  14655. {
  14656. if (sigCtx == NULL)
  14657. return;
  14658. if (sigCtx->digest) {
  14659. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  14660. sigCtx->digest = NULL;
  14661. }
  14662. #if !(defined(NO_RSA) && defined(NO_DSA))
  14663. if (sigCtx->sigCpy) {
  14664. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14665. sigCtx->sigCpy = NULL;
  14666. }
  14667. #endif
  14668. #ifndef NO_ASN_CRYPT
  14669. if (sigCtx->key.ptr) {
  14670. switch (sigCtx->keyOID) {
  14671. #ifndef NO_RSA
  14672. #ifdef WC_RSA_PSS
  14673. case RSAPSSk:
  14674. #endif
  14675. case RSAk:
  14676. wc_FreeRsaKey(sigCtx->key.rsa);
  14677. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  14678. sigCtx->key.rsa = NULL;
  14679. break;
  14680. #endif /* !NO_RSA */
  14681. #ifndef NO_DSA
  14682. case DSAk:
  14683. wc_FreeDsaKey(sigCtx->key.dsa);
  14684. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  14685. sigCtx->key.dsa = NULL;
  14686. break;
  14687. #endif
  14688. #ifdef HAVE_ECC
  14689. case ECDSAk:
  14690. #ifdef WOLFSSL_SM2
  14691. case SM2k:
  14692. #endif
  14693. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14694. defined(WC_ASYNC_ENABLE_ECC)
  14695. if (sigCtx->key.ecc->nb_ctx != NULL) {
  14696. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  14697. DYNAMIC_TYPE_TMP_BUFFER);
  14698. }
  14699. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14700. WC_ASYNC_ENABLE_ECC */
  14701. wc_ecc_free(sigCtx->key.ecc);
  14702. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  14703. sigCtx->key.ecc = NULL;
  14704. break;
  14705. #endif /* HAVE_ECC */
  14706. #ifdef HAVE_ED25519
  14707. case ED25519k:
  14708. wc_ed25519_free(sigCtx->key.ed25519);
  14709. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  14710. sigCtx->key.ed25519 = NULL;
  14711. break;
  14712. #endif /* HAVE_ED25519 */
  14713. #ifdef HAVE_ED448
  14714. case ED448k:
  14715. wc_ed448_free(sigCtx->key.ed448);
  14716. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  14717. sigCtx->key.ed448 = NULL;
  14718. break;
  14719. #endif /* HAVE_ED448 */
  14720. #if defined(HAVE_PQC)
  14721. #if defined(HAVE_FALCON)
  14722. case FALCON_LEVEL1k:
  14723. case FALCON_LEVEL5k:
  14724. wc_falcon_free(sigCtx->key.falcon);
  14725. XFREE(sigCtx->key.falcon, sigCtx->heap,
  14726. DYNAMIC_TYPE_FALCON);
  14727. sigCtx->key.falcon = NULL;
  14728. break;
  14729. #endif /* HAVE_FALCON */
  14730. #if defined(HAVE_DILITHIUM)
  14731. case DILITHIUM_LEVEL2k:
  14732. case DILITHIUM_LEVEL3k:
  14733. case DILITHIUM_LEVEL5k:
  14734. wc_dilithium_free(sigCtx->key.dilithium);
  14735. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  14736. DYNAMIC_TYPE_DILITHIUM);
  14737. sigCtx->key.dilithium = NULL;
  14738. break;
  14739. #endif /* HAVE_DILITHIUM */
  14740. #if defined(HAVE_SPHINCS)
  14741. case SPHINCS_FAST_LEVEL1k:
  14742. case SPHINCS_FAST_LEVEL3k:
  14743. case SPHINCS_FAST_LEVEL5k:
  14744. case SPHINCS_SMALL_LEVEL1k:
  14745. case SPHINCS_SMALL_LEVEL3k:
  14746. case SPHINCS_SMALL_LEVEL5k:
  14747. wc_sphincs_free(sigCtx->key.sphincs);
  14748. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  14749. DYNAMIC_TYPE_SPHINCS);
  14750. sigCtx->key.sphincs = NULL;
  14751. break;
  14752. #endif /* HAVE_SPHINCS */
  14753. #endif /* HAVE_PQC */
  14754. default:
  14755. break;
  14756. } /* switch (keyOID) */
  14757. sigCtx->key.ptr = NULL;
  14758. }
  14759. #endif
  14760. /* reset state, we are done */
  14761. sigCtx->state = SIG_STATE_BEGIN;
  14762. }
  14763. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  14764. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  14765. byte* digest, int* typeH, int* digestSz, int verify)
  14766. {
  14767. int ret = 0;
  14768. switch (sigOID) {
  14769. #if defined(WOLFSSL_MD2)
  14770. case CTC_MD2wRSA:
  14771. if (!verify) {
  14772. ret = HASH_TYPE_E;
  14773. WOLFSSL_MSG("MD2 not supported for signing");
  14774. }
  14775. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  14776. *typeH = MD2h;
  14777. *digestSz = MD2_DIGEST_SIZE;
  14778. }
  14779. break;
  14780. #endif
  14781. #ifndef NO_MD5
  14782. case CTC_MD5wRSA:
  14783. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  14784. *typeH = MD5h;
  14785. *digestSz = WC_MD5_DIGEST_SIZE;
  14786. }
  14787. break;
  14788. #endif
  14789. #ifndef NO_SHA
  14790. case CTC_SHAwRSA:
  14791. case CTC_SHAwDSA:
  14792. case CTC_SHAwECDSA:
  14793. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  14794. *typeH = SHAh;
  14795. *digestSz = WC_SHA_DIGEST_SIZE;
  14796. }
  14797. break;
  14798. #endif
  14799. #ifdef WOLFSSL_SHA224
  14800. case CTC_SHA224wRSA:
  14801. case CTC_SHA224wECDSA:
  14802. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  14803. *typeH = SHA224h;
  14804. *digestSz = WC_SHA224_DIGEST_SIZE;
  14805. }
  14806. break;
  14807. #endif
  14808. #ifndef NO_SHA256
  14809. case CTC_SHA256wRSA:
  14810. case CTC_SHA256wECDSA:
  14811. case CTC_SHA256wDSA:
  14812. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  14813. *typeH = SHA256h;
  14814. *digestSz = WC_SHA256_DIGEST_SIZE;
  14815. }
  14816. break;
  14817. #endif
  14818. #ifdef WOLFSSL_SHA384
  14819. case CTC_SHA384wRSA:
  14820. case CTC_SHA384wECDSA:
  14821. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  14822. *typeH = SHA384h;
  14823. *digestSz = WC_SHA384_DIGEST_SIZE;
  14824. }
  14825. break;
  14826. #endif
  14827. #ifdef WOLFSSL_SHA512
  14828. case CTC_SHA512wRSA:
  14829. case CTC_SHA512wECDSA:
  14830. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  14831. *typeH = SHA512h;
  14832. *digestSz = WC_SHA512_DIGEST_SIZE;
  14833. }
  14834. break;
  14835. #endif
  14836. #ifdef WOLFSSL_SHA3
  14837. #ifndef WOLFSSL_NOSHA3_224
  14838. case CTC_SHA3_224wRSA:
  14839. case CTC_SHA3_224wECDSA:
  14840. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  14841. *typeH = SHA3_224h;
  14842. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  14843. }
  14844. break;
  14845. #endif
  14846. #ifndef WOLFSSL_NOSHA3_256
  14847. case CTC_SHA3_256wRSA:
  14848. case CTC_SHA3_256wECDSA:
  14849. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  14850. *typeH = SHA3_256h;
  14851. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  14852. }
  14853. break;
  14854. #endif
  14855. #ifndef WOLFSSL_NOSHA3_384
  14856. case CTC_SHA3_384wRSA:
  14857. case CTC_SHA3_384wECDSA:
  14858. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  14859. *typeH = SHA3_384h;
  14860. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  14861. }
  14862. break;
  14863. #endif
  14864. #ifndef WOLFSSL_NOSHA3_512
  14865. case CTC_SHA3_512wRSA:
  14866. case CTC_SHA3_512wECDSA:
  14867. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  14868. *typeH = SHA3_512h;
  14869. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  14870. }
  14871. break;
  14872. #endif
  14873. #endif
  14874. #if defined(WOLFSSL_SM2) & defined(WOLFSSL_SM3)
  14875. case CTC_SM3wSM2:
  14876. if ((ret = wc_Sm3Hash(buf, bufSz, digest)) == 0) {
  14877. *typeH = SM3h;
  14878. *digestSz = WC_SM3_DIGEST_SIZE;
  14879. }
  14880. break;
  14881. #endif
  14882. #ifdef HAVE_ED25519
  14883. case CTC_ED25519:
  14884. /* Hashes done in signing operation.
  14885. * Two dependent hashes with prefixes performed.
  14886. */
  14887. break;
  14888. #endif
  14889. #ifdef HAVE_ED448
  14890. case CTC_ED448:
  14891. /* Hashes done in signing operation.
  14892. * Two dependent hashes with prefixes performed.
  14893. */
  14894. break;
  14895. #endif
  14896. #ifdef HAVE_PQC
  14897. #ifdef HAVE_FALCON
  14898. case CTC_FALCON_LEVEL1:
  14899. case CTC_FALCON_LEVEL5:
  14900. /* Hashes done in signing operation. */
  14901. break;
  14902. #endif
  14903. #ifdef HAVE_DILITHIUM
  14904. case CTC_DILITHIUM_LEVEL2:
  14905. case CTC_DILITHIUM_LEVEL3:
  14906. case CTC_DILITHIUM_LEVEL5:
  14907. /* Hashes done in signing operation. */
  14908. break;
  14909. #endif
  14910. #ifdef HAVE_SPHINCS
  14911. case CTC_SPHINCS_FAST_LEVEL1:
  14912. case CTC_SPHINCS_FAST_LEVEL3:
  14913. case CTC_SPHINCS_FAST_LEVEL5:
  14914. case CTC_SPHINCS_SMALL_LEVEL1:
  14915. case CTC_SPHINCS_SMALL_LEVEL3:
  14916. case CTC_SPHINCS_SMALL_LEVEL5:
  14917. /* Hashes done in signing operation. */
  14918. break;
  14919. #endif
  14920. #endif /* HAVE_PQC */
  14921. default:
  14922. ret = HASH_TYPE_E;
  14923. WOLFSSL_MSG("Hash for Signature has unsupported type");
  14924. }
  14925. (void)buf;
  14926. (void)bufSz;
  14927. (void)sigOID;
  14928. (void)digest;
  14929. (void)digestSz;
  14930. (void)typeH;
  14931. (void)verify;
  14932. return ret;
  14933. }
  14934. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  14935. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  14936. static int ConfirmSignature(SignatureCtx* sigCtx,
  14937. const byte* buf, word32 bufSz,
  14938. const byte* key, word32 keySz, word32 keyOID,
  14939. const byte* sig, word32 sigSz, word32 sigOID,
  14940. const byte* sigParams, word32 sigParamsSz,
  14941. byte* rsaKeyIdx)
  14942. {
  14943. int ret = 0;
  14944. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  14945. CertAttribute* certatt = NULL;
  14946. #endif
  14947. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  14948. keySz == 0 || sig == NULL || sigSz == 0) {
  14949. return BAD_FUNC_ARG;
  14950. }
  14951. (void)key;
  14952. (void)keySz;
  14953. (void)sig;
  14954. (void)sigSz;
  14955. (void)sigParams;
  14956. (void)sigParamsSz;
  14957. WOLFSSL_ENTER("ConfirmSignature");
  14958. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_FSPSM_TLS)
  14959. (void)rsaKeyIdx;
  14960. #else
  14961. #if !defined(NO_RSA) || defined(HAVE_ECC)
  14962. certatt = (CertAttribute*)&sigCtx->CertAtt;
  14963. #endif
  14964. if (certatt) {
  14965. certatt->keyIndex = rsaKeyIdx;
  14966. certatt->cert = buf;
  14967. certatt->certSz = bufSz;
  14968. }
  14969. #endif
  14970. #ifndef NO_ASN_CRYPT
  14971. switch (sigCtx->state) {
  14972. case SIG_STATE_BEGIN:
  14973. {
  14974. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  14975. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  14976. DYNAMIC_TYPE_DIGEST);
  14977. if (sigCtx->digest == NULL) {
  14978. ERROR_OUT(MEMORY_E, exit_cs);
  14979. }
  14980. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14981. /* RSA PSS Defaults */
  14982. sigCtx->hash = WC_HASH_TYPE_SHA;
  14983. sigCtx->mgf = WC_MGF1SHA1;
  14984. sigCtx->saltLen = 20;
  14985. #endif
  14986. sigCtx->state = SIG_STATE_HASH;
  14987. } /* SIG_STATE_BEGIN */
  14988. FALL_THROUGH;
  14989. case SIG_STATE_HASH:
  14990. {
  14991. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14992. if (sigOID == RSAPSSk) {
  14993. word32 fakeSigOID = 0;
  14994. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  14995. &sigCtx->mgf, &sigCtx->saltLen);
  14996. if (ret != 0) {
  14997. goto exit_cs;
  14998. }
  14999. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  15000. if (ret != 0) {
  15001. goto exit_cs;
  15002. }
  15003. /* Decode parameters. */
  15004. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  15005. &sigCtx->typeH, &sigCtx->digestSz, 1);
  15006. if (ret != 0) {
  15007. goto exit_cs;
  15008. }
  15009. }
  15010. else
  15011. #endif
  15012. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15013. if (sigOID == CTC_SM3wSM2) {
  15014. ; /* SM2 hash requires public key. Done later. */
  15015. }
  15016. else
  15017. #endif
  15018. {
  15019. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  15020. &sigCtx->typeH, &sigCtx->digestSz, 1);
  15021. if (ret != 0) {
  15022. goto exit_cs;
  15023. }
  15024. }
  15025. sigCtx->state = SIG_STATE_KEY;
  15026. } /* SIG_STATE_HASH */
  15027. FALL_THROUGH;
  15028. case SIG_STATE_KEY:
  15029. {
  15030. switch (keyOID) {
  15031. #ifndef NO_RSA
  15032. #ifdef WC_RSA_PSS
  15033. case RSAPSSk:
  15034. #endif
  15035. case RSAk:
  15036. {
  15037. word32 idx = 0;
  15038. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  15039. sigCtx->heap, DYNAMIC_TYPE_RSA);
  15040. if (sigCtx->key.rsa == NULL) {
  15041. ERROR_OUT(MEMORY_E, exit_cs);
  15042. }
  15043. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  15044. sigCtx->devId)) != 0) {
  15045. goto exit_cs;
  15046. }
  15047. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  15048. DYNAMIC_TYPE_SIGNATURE);
  15049. if (sigCtx->sigCpy == NULL) {
  15050. ERROR_OUT(MEMORY_E, exit_cs);
  15051. }
  15052. if (sigSz > MAX_ENCODED_SIG_SZ) {
  15053. WOLFSSL_MSG("Verify Signature is too big");
  15054. ERROR_OUT(BUFFER_E, exit_cs);
  15055. }
  15056. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  15057. keySz)) != 0) {
  15058. WOLFSSL_MSG("ASN Key decode error RSA");
  15059. WOLFSSL_ERROR_VERBOSE(ret);
  15060. goto exit_cs;
  15061. }
  15062. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  15063. sigCtx->out = NULL;
  15064. #ifdef WOLFSSL_ASYNC_CRYPT
  15065. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  15066. #endif
  15067. break;
  15068. }
  15069. #endif /* !NO_RSA */
  15070. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15071. case DSAk:
  15072. {
  15073. word32 idx = 0;
  15074. if (sigSz < DSA_MIN_SIG_SIZE) {
  15075. WOLFSSL_MSG("Verify Signature is too small");
  15076. ERROR_OUT(BUFFER_E, exit_cs);
  15077. }
  15078. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  15079. sigCtx->heap, DYNAMIC_TYPE_DSA);
  15080. if (sigCtx->key.dsa == NULL) {
  15081. ERROR_OUT(MEMORY_E, exit_cs);
  15082. }
  15083. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  15084. WOLFSSL_MSG("wc_InitDsaKey_h error");
  15085. goto exit_cs;
  15086. }
  15087. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  15088. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  15089. if (sigCtx->sigCpy == NULL) {
  15090. ERROR_OUT(MEMORY_E, exit_cs);
  15091. }
  15092. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  15093. keySz)) != 0) {
  15094. WOLFSSL_MSG("ASN Key decode error DSA");
  15095. WOLFSSL_ERROR_VERBOSE(ret);
  15096. goto exit_cs;
  15097. }
  15098. if (sigSz != DSA_160_SIG_SIZE &&
  15099. sigSz != DSA_256_SIG_SIZE) {
  15100. /* Try to parse it as the contents of a bitstring */
  15101. #ifdef WOLFSSL_SMALL_STACK
  15102. mp_int* r;
  15103. mp_int* s;
  15104. #else
  15105. mp_int r[1];
  15106. mp_int s[1];
  15107. #endif
  15108. int rSz;
  15109. int sSz;
  15110. #ifdef WOLFSSL_SMALL_STACK
  15111. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  15112. DYNAMIC_TYPE_TMP_BUFFER);
  15113. if (r == NULL) {
  15114. ERROR_OUT(MEMORY_E, exit_cs);
  15115. }
  15116. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  15117. DYNAMIC_TYPE_TMP_BUFFER);
  15118. if (s == NULL) {
  15119. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15120. ERROR_OUT(MEMORY_E, exit_cs);
  15121. }
  15122. #endif
  15123. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  15124. goto exit_cs;
  15125. }
  15126. idx = 0;
  15127. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  15128. != 0) {
  15129. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  15130. "incorrect format");
  15131. mp_free(r);
  15132. mp_free(s);
  15133. #ifdef WOLFSSL_SMALL_STACK
  15134. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15135. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15136. #endif
  15137. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  15138. }
  15139. rSz = mp_unsigned_bin_size(r);
  15140. sSz = mp_unsigned_bin_size(s);
  15141. if (rSz + sSz > (int)sigSz) {
  15142. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  15143. "incorrect format");
  15144. mp_free(r);
  15145. mp_free(s);
  15146. #ifdef WOLFSSL_SMALL_STACK
  15147. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15148. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15149. #endif
  15150. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  15151. }
  15152. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  15153. mp_to_unsigned_bin(s,
  15154. sigCtx->sigCpy + rSz) != MP_OKAY) {
  15155. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  15156. "incorrect format");
  15157. mp_free(r);
  15158. mp_free(s);
  15159. #ifdef WOLFSSL_SMALL_STACK
  15160. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15161. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15162. #endif
  15163. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  15164. }
  15165. mp_free(r);
  15166. mp_free(s);
  15167. #ifdef WOLFSSL_SMALL_STACK
  15168. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15169. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15170. #endif
  15171. }
  15172. else {
  15173. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  15174. }
  15175. break;
  15176. }
  15177. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15178. #ifdef HAVE_ECC
  15179. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15180. case SM2k:
  15181. #endif
  15182. case ECDSAk:
  15183. {
  15184. word32 idx = 0;
  15185. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  15186. defined(WC_ASYNC_ENABLE_ECC)
  15187. ecc_nb_ctx_t* nbCtx;
  15188. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  15189. WC_ASYNC_ENABLE_ECC */
  15190. sigCtx->verify = 0;
  15191. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  15192. sigCtx->heap, DYNAMIC_TYPE_ECC);
  15193. if (sigCtx->key.ecc == NULL) {
  15194. ERROR_OUT(MEMORY_E, exit_cs);
  15195. }
  15196. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  15197. sigCtx->devId)) < 0) {
  15198. goto exit_cs;
  15199. }
  15200. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  15201. defined(WC_ASYNC_ENABLE_ECC)
  15202. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  15203. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15204. if (nbCtx == NULL) {
  15205. ERROR_OUT(MEMORY_E, exit_cs);
  15206. }
  15207. else {
  15208. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  15209. if (ret != 0) {
  15210. goto exit_cs;
  15211. }
  15212. }
  15213. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  15214. WC_ASYNC_ENABLE_ECC */
  15215. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  15216. keySz);
  15217. if (ret < 0) {
  15218. WOLFSSL_MSG("ASN Key import error ECC");
  15219. WOLFSSL_ERROR_VERBOSE(ret);
  15220. goto exit_cs;
  15221. }
  15222. #ifdef WOLFSSL_ASYNC_CRYPT
  15223. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  15224. #endif
  15225. break;
  15226. }
  15227. #endif /* HAVE_ECC */
  15228. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  15229. case ED25519k:
  15230. {
  15231. sigCtx->verify = 0;
  15232. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  15233. sizeof(ed25519_key), sigCtx->heap,
  15234. DYNAMIC_TYPE_ED25519);
  15235. if (sigCtx->key.ed25519 == NULL) {
  15236. ERROR_OUT(MEMORY_E, exit_cs);
  15237. }
  15238. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  15239. sigCtx->heap, sigCtx->devId)) < 0) {
  15240. goto exit_cs;
  15241. }
  15242. if ((ret = wc_ed25519_import_public(key, keySz,
  15243. sigCtx->key.ed25519)) < 0) {
  15244. WOLFSSL_MSG("ASN Key import error ED25519");
  15245. WOLFSSL_ERROR_VERBOSE(ret);
  15246. goto exit_cs;
  15247. }
  15248. #ifdef WOLFSSL_ASYNC_CRYPT
  15249. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  15250. #endif
  15251. break;
  15252. }
  15253. #endif
  15254. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  15255. case ED448k:
  15256. {
  15257. sigCtx->verify = 0;
  15258. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  15259. sizeof(ed448_key), sigCtx->heap,
  15260. DYNAMIC_TYPE_ED448);
  15261. if (sigCtx->key.ed448 == NULL) {
  15262. ERROR_OUT(MEMORY_E, exit_cs);
  15263. }
  15264. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  15265. goto exit_cs;
  15266. }
  15267. if ((ret = wc_ed448_import_public(key, keySz,
  15268. sigCtx->key.ed448)) < 0) {
  15269. WOLFSSL_MSG("ASN Key import error ED448");
  15270. WOLFSSL_ERROR_VERBOSE(ret);
  15271. goto exit_cs;
  15272. }
  15273. #ifdef WOLFSSL_ASYNC_CRYPT
  15274. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  15275. #endif
  15276. break;
  15277. }
  15278. #endif
  15279. #if defined(HAVE_PQC)
  15280. #if defined(HAVE_FALCON)
  15281. case FALCON_LEVEL1k:
  15282. {
  15283. word32 idx = 0;
  15284. sigCtx->verify = 0;
  15285. sigCtx->key.falcon =
  15286. (falcon_key*)XMALLOC(sizeof(falcon_key),
  15287. sigCtx->heap,
  15288. DYNAMIC_TYPE_FALCON);
  15289. if (sigCtx->key.falcon == NULL) {
  15290. ERROR_OUT(MEMORY_E, exit_cs);
  15291. }
  15292. if ((ret = wc_falcon_init_ex(sigCtx->key.falcon,
  15293. sigCtx->heap, sigCtx->devId)) < 0) {
  15294. goto exit_cs;
  15295. }
  15296. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  15297. < 0) {
  15298. goto exit_cs;
  15299. }
  15300. if ((ret = wc_Falcon_PublicKeyDecode(key, &idx,
  15301. sigCtx->key.falcon, keySz)) < 0) {
  15302. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  15303. WOLFSSL_ERROR_VERBOSE(ret);
  15304. goto exit_cs;
  15305. }
  15306. break;
  15307. }
  15308. case FALCON_LEVEL5k:
  15309. {
  15310. word32 idx = 0;
  15311. sigCtx->verify = 0;
  15312. sigCtx->key.falcon =
  15313. (falcon_key*)XMALLOC(sizeof(falcon_key),
  15314. sigCtx->heap,
  15315. DYNAMIC_TYPE_FALCON);
  15316. if (sigCtx->key.falcon == NULL) {
  15317. ERROR_OUT(MEMORY_E, exit_cs);
  15318. }
  15319. if ((ret = wc_falcon_init_ex(sigCtx->key.falcon,
  15320. sigCtx->heap, sigCtx->devId)) < 0) {
  15321. goto exit_cs;
  15322. }
  15323. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  15324. < 0) {
  15325. goto exit_cs;
  15326. }
  15327. if ((ret = wc_Falcon_PublicKeyDecode(key, &idx,
  15328. sigCtx->key.falcon, keySz)) < 0) {
  15329. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  15330. WOLFSSL_ERROR_VERBOSE(ret);
  15331. goto exit_cs;
  15332. }
  15333. break;
  15334. }
  15335. #endif /* HAVE_FALCON */
  15336. #if defined(HAVE_DILITHIUM)
  15337. case DILITHIUM_LEVEL2k:
  15338. {
  15339. word32 idx = 0;
  15340. sigCtx->verify = 0;
  15341. sigCtx->key.dilithium =
  15342. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  15343. sigCtx->heap,
  15344. DYNAMIC_TYPE_DILITHIUM);
  15345. if (sigCtx->key.dilithium == NULL) {
  15346. ERROR_OUT(MEMORY_E, exit_cs);
  15347. }
  15348. if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium,
  15349. sigCtx->heap, sigCtx->devId)) < 0) {
  15350. goto exit_cs;
  15351. }
  15352. if ((ret = wc_dilithium_set_level(
  15353. sigCtx->key.dilithium, 2))
  15354. < 0) {
  15355. goto exit_cs;
  15356. }
  15357. if ((ret = wc_Dilithium_PublicKeyDecode(key, &idx,
  15358. sigCtx->key.dilithium, keySz)) < 0) {
  15359. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  15360. goto exit_cs;
  15361. }
  15362. break;
  15363. }
  15364. case DILITHIUM_LEVEL3k:
  15365. {
  15366. word32 idx = 0;
  15367. sigCtx->verify = 0;
  15368. sigCtx->key.dilithium =
  15369. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  15370. sigCtx->heap,
  15371. DYNAMIC_TYPE_DILITHIUM);
  15372. if (sigCtx->key.dilithium == NULL) {
  15373. ERROR_OUT(MEMORY_E, exit_cs);
  15374. }
  15375. if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium,
  15376. sigCtx->heap, sigCtx->devId)) < 0) {
  15377. goto exit_cs;
  15378. }
  15379. if ((ret = wc_dilithium_set_level(
  15380. sigCtx->key.dilithium, 3))
  15381. < 0) {
  15382. goto exit_cs;
  15383. }
  15384. if ((ret = wc_Dilithium_PublicKeyDecode(key, &idx,
  15385. sigCtx->key.dilithium, keySz)) < 0) {
  15386. WOLFSSL_MSG("ASN Key import error Dilithium Level 3");
  15387. goto exit_cs;
  15388. }
  15389. break;
  15390. }
  15391. case DILITHIUM_LEVEL5k:
  15392. {
  15393. word32 idx = 0;
  15394. sigCtx->verify = 0;
  15395. sigCtx->key.dilithium =
  15396. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  15397. sigCtx->heap,
  15398. DYNAMIC_TYPE_DILITHIUM);
  15399. if (sigCtx->key.dilithium == NULL) {
  15400. ERROR_OUT(MEMORY_E, exit_cs);
  15401. }
  15402. if ((ret = wc_dilithium_init_ex(sigCtx->key.dilithium,
  15403. sigCtx->heap, sigCtx->devId)) < 0) {
  15404. goto exit_cs;
  15405. }
  15406. if ((ret = wc_dilithium_set_level(
  15407. sigCtx->key.dilithium, 5))
  15408. < 0) {
  15409. goto exit_cs;
  15410. }
  15411. if ((ret = wc_Dilithium_PublicKeyDecode(key, &idx,
  15412. sigCtx->key.dilithium, keySz)) < 0) {
  15413. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  15414. goto exit_cs;
  15415. }
  15416. break;
  15417. }
  15418. #endif /* HAVE_DILITHIUM */
  15419. #if defined(HAVE_SPHINCS)
  15420. case SPHINCS_FAST_LEVEL1k:
  15421. {
  15422. word32 idx = 0;
  15423. sigCtx->verify = 0;
  15424. sigCtx->key.sphincs =
  15425. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15426. sigCtx->heap,
  15427. DYNAMIC_TYPE_SPHINCS);
  15428. if (sigCtx->key.sphincs == NULL) {
  15429. ERROR_OUT(MEMORY_E, exit_cs);
  15430. }
  15431. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15432. goto exit_cs;
  15433. }
  15434. if ((ret = wc_sphincs_set_level_and_optim(
  15435. sigCtx->key.sphincs, 1, FAST_VARIANT))
  15436. < 0) {
  15437. goto exit_cs;
  15438. }
  15439. if ((ret = wc_Sphincs_PublicKeyDecode(key, &idx,
  15440. sigCtx->key.sphincs, keySz)) < 0) {
  15441. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  15442. goto exit_cs;
  15443. }
  15444. break;
  15445. }
  15446. case SPHINCS_FAST_LEVEL3k:
  15447. {
  15448. word32 idx = 0;
  15449. sigCtx->verify = 0;
  15450. sigCtx->key.sphincs =
  15451. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15452. sigCtx->heap,
  15453. DYNAMIC_TYPE_SPHINCS);
  15454. if (sigCtx->key.sphincs == NULL) {
  15455. ERROR_OUT(MEMORY_E, exit_cs);
  15456. }
  15457. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15458. goto exit_cs;
  15459. }
  15460. if ((ret = wc_sphincs_set_level_and_optim(
  15461. sigCtx->key.sphincs, 3, FAST_VARIANT))
  15462. < 0) {
  15463. goto exit_cs;
  15464. }
  15465. if ((ret = wc_Sphincs_PublicKeyDecode(key, &idx,
  15466. sigCtx->key.sphincs, keySz)) < 0) {
  15467. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  15468. goto exit_cs;
  15469. }
  15470. break;
  15471. }
  15472. case SPHINCS_FAST_LEVEL5k:
  15473. {
  15474. word32 idx = 0;
  15475. sigCtx->verify = 0;
  15476. sigCtx->key.sphincs =
  15477. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15478. sigCtx->heap,
  15479. DYNAMIC_TYPE_SPHINCS);
  15480. if (sigCtx->key.sphincs == NULL) {
  15481. ERROR_OUT(MEMORY_E, exit_cs);
  15482. }
  15483. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15484. goto exit_cs;
  15485. }
  15486. if ((ret = wc_sphincs_set_level_and_optim(
  15487. sigCtx->key.sphincs, 5, FAST_VARIANT))
  15488. < 0) {
  15489. goto exit_cs;
  15490. }
  15491. if ((ret = wc_Sphincs_PublicKeyDecode(key, &idx,
  15492. sigCtx->key.sphincs, keySz)) < 0) {
  15493. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  15494. goto exit_cs;
  15495. }
  15496. break;
  15497. }
  15498. case SPHINCS_SMALL_LEVEL1k:
  15499. {
  15500. word32 idx = 0;
  15501. sigCtx->verify = 0;
  15502. sigCtx->key.sphincs =
  15503. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15504. sigCtx->heap,
  15505. DYNAMIC_TYPE_SPHINCS);
  15506. if (sigCtx->key.sphincs == NULL) {
  15507. ERROR_OUT(MEMORY_E, exit_cs);
  15508. }
  15509. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15510. goto exit_cs;
  15511. }
  15512. if ((ret = wc_sphincs_set_level_and_optim(
  15513. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  15514. < 0) {
  15515. goto exit_cs;
  15516. }
  15517. if ((ret = wc_Sphincs_PublicKeyDecode(key, &idx,
  15518. sigCtx->key.sphincs, keySz)) < 0) {
  15519. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  15520. goto exit_cs;
  15521. }
  15522. break;
  15523. }
  15524. case SPHINCS_SMALL_LEVEL3k:
  15525. {
  15526. word32 idx = 0;
  15527. sigCtx->verify = 0;
  15528. sigCtx->key.sphincs =
  15529. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15530. sigCtx->heap,
  15531. DYNAMIC_TYPE_SPHINCS);
  15532. if (sigCtx->key.sphincs == NULL) {
  15533. ERROR_OUT(MEMORY_E, exit_cs);
  15534. }
  15535. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15536. goto exit_cs;
  15537. }
  15538. if ((ret = wc_sphincs_set_level_and_optim(
  15539. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  15540. < 0) {
  15541. goto exit_cs;
  15542. }
  15543. if ((ret = wc_Sphincs_PublicKeyDecode(key, &idx,
  15544. sigCtx->key.sphincs, keySz)) < 0) {
  15545. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  15546. goto exit_cs;
  15547. }
  15548. break;
  15549. }
  15550. case SPHINCS_SMALL_LEVEL5k:
  15551. {
  15552. word32 idx = 0;
  15553. sigCtx->verify = 0;
  15554. sigCtx->key.sphincs =
  15555. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15556. sigCtx->heap,
  15557. DYNAMIC_TYPE_SPHINCS);
  15558. if (sigCtx->key.sphincs == NULL) {
  15559. ERROR_OUT(MEMORY_E, exit_cs);
  15560. }
  15561. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15562. goto exit_cs;
  15563. }
  15564. if ((ret = wc_sphincs_set_level_and_optim(
  15565. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  15566. < 0) {
  15567. goto exit_cs;
  15568. }
  15569. if ((ret = wc_Sphincs_PublicKeyDecode(key, &idx,
  15570. sigCtx->key.sphincs, keySz)) < 0) {
  15571. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  15572. goto exit_cs;
  15573. }
  15574. break;
  15575. }
  15576. #endif /* HAVE_SPHINCS */
  15577. #endif /* HAVE_PQC */
  15578. default:
  15579. WOLFSSL_MSG("Verify Key type unknown");
  15580. ret = ASN_UNKNOWN_OID_E;
  15581. WOLFSSL_ERROR_VERBOSE(ret);
  15582. break;
  15583. } /* switch (keyOID) */
  15584. if (ret != 0) {
  15585. goto exit_cs;
  15586. }
  15587. sigCtx->state = SIG_STATE_DO;
  15588. #ifdef WOLFSSL_ASYNC_CRYPT
  15589. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  15590. /* make sure event is initialized */
  15591. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  15592. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  15593. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  15594. }
  15595. #endif
  15596. } /* SIG_STATE_KEY */
  15597. FALL_THROUGH;
  15598. case SIG_STATE_DO:
  15599. {
  15600. switch (keyOID) {
  15601. #ifndef NO_RSA
  15602. case RSAk:
  15603. #ifdef WC_RSA_PSS
  15604. case RSAPSSk:
  15605. if (sigOID == RSAPSSk) {
  15606. /* TODO: pkCbRsaPss - RSA PSS callback. */
  15607. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  15608. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  15609. sigCtx->saltLen, sigCtx->key.rsa);
  15610. }
  15611. else
  15612. #endif
  15613. {
  15614. #if defined(HAVE_PK_CALLBACKS)
  15615. if (sigCtx->pkCbRsa) {
  15616. ret = sigCtx->pkCbRsa(
  15617. sigCtx->sigCpy, sigSz, &sigCtx->out,
  15618. key, keySz,
  15619. sigCtx->pkCtxRsa);
  15620. }
  15621. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  15622. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15623. else
  15624. #else
  15625. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  15626. #endif /* WOLFSSL_RENESAS_FSPSM_TLS */
  15627. #endif /* HAVE_PK_CALLBACKS */
  15628. {
  15629. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  15630. &sigCtx->out, sigCtx->key.rsa);
  15631. }
  15632. }
  15633. break;
  15634. #endif /* !NO_RSA */
  15635. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15636. case DSAk:
  15637. {
  15638. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  15639. sigCtx->key.dsa, &sigCtx->verify);
  15640. break;
  15641. }
  15642. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15643. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15644. case SM2k:
  15645. {
  15646. /* OpenSSL creates signature without CERT_SIG_ID. */
  15647. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID, 0, buf, bufSz,
  15648. WC_HASH_TYPE_SM3, sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15649. sigCtx->key.ecc);
  15650. if (ret == 0) {
  15651. sigCtx->typeH = SM3h;
  15652. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15653. }
  15654. else {
  15655. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15656. WOLFSSL_ERROR_VERBOSE(ret);
  15657. goto exit_cs;
  15658. }
  15659. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15660. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15661. break;
  15662. }
  15663. #endif
  15664. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  15665. case ECDSAk:
  15666. {
  15667. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15668. if (sigOID == CTC_SM3wSM2) {
  15669. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID,
  15670. CERT_SIG_ID_SZ, buf, bufSz, WC_HASH_TYPE_SM3,
  15671. sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15672. sigCtx->key.ecc);
  15673. if (ret == 0) {
  15674. sigCtx->typeH = SM3h;
  15675. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15676. }
  15677. else {
  15678. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15679. WOLFSSL_ERROR_VERBOSE(ret);
  15680. goto exit_cs;
  15681. }
  15682. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15683. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15684. }
  15685. else
  15686. #endif
  15687. #if defined(HAVE_PK_CALLBACKS)
  15688. if (sigCtx->pkCbEcc) {
  15689. ret = sigCtx->pkCbEcc(
  15690. sig, sigSz,
  15691. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  15692. key, keySz, &sigCtx->verify,
  15693. sigCtx->pkCtxEcc);
  15694. }
  15695. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  15696. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15697. else
  15698. #else
  15699. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  15700. #endif /* WOLFSSL_RENESAS_FSPSM_TLS */
  15701. #endif /* HAVE_PK_CALLBACKS */
  15702. {
  15703. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  15704. (word32)sigCtx->digestSz, &sigCtx->verify,
  15705. sigCtx->key.ecc);
  15706. }
  15707. break;
  15708. }
  15709. #endif /* HAVE_ECC */
  15710. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  15711. case ED25519k:
  15712. {
  15713. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  15714. &sigCtx->verify, sigCtx->key.ed25519);
  15715. break;
  15716. }
  15717. #endif
  15718. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  15719. case ED448k:
  15720. {
  15721. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  15722. &sigCtx->verify, sigCtx->key.ed448,
  15723. NULL, 0);
  15724. break;
  15725. }
  15726. #endif
  15727. #if defined(HAVE_PQC)
  15728. #if defined(HAVE_FALCON)
  15729. case FALCON_LEVEL1k:
  15730. case FALCON_LEVEL5k:
  15731. {
  15732. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  15733. &sigCtx->verify,
  15734. sigCtx->key.falcon);
  15735. break;
  15736. }
  15737. #endif /* HAVE_FALCON */
  15738. #if defined(HAVE_DILITHIUM)
  15739. case DILITHIUM_LEVEL2k:
  15740. case DILITHIUM_LEVEL3k:
  15741. case DILITHIUM_LEVEL5k:
  15742. {
  15743. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  15744. &sigCtx->verify,
  15745. sigCtx->key.dilithium);
  15746. break;
  15747. }
  15748. #endif /* HAVE_DILITHIUM */
  15749. #if defined(HAVE_SPHINCS)
  15750. case SPHINCS_FAST_LEVEL1k:
  15751. case SPHINCS_FAST_LEVEL3k:
  15752. case SPHINCS_FAST_LEVEL5k:
  15753. case SPHINCS_SMALL_LEVEL1k:
  15754. case SPHINCS_SMALL_LEVEL3k:
  15755. case SPHINCS_SMALL_LEVEL5k:
  15756. {
  15757. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  15758. &sigCtx->verify,
  15759. sigCtx->key.sphincs);
  15760. break;
  15761. }
  15762. #endif /* HAVE_SPHINCS */
  15763. #endif /* HAVE_PQC */
  15764. default:
  15765. break;
  15766. } /* switch (keyOID) */
  15767. #ifdef WOLFSSL_ASYNC_CRYPT
  15768. if (ret == WC_PENDING_E) {
  15769. goto exit_cs;
  15770. }
  15771. #endif
  15772. if (ret < 0) {
  15773. /* treat all errors as ASN_SIG_CONFIRM_E */
  15774. ret = ASN_SIG_CONFIRM_E;
  15775. WOLFSSL_ERROR_VERBOSE(ret);
  15776. goto exit_cs;
  15777. }
  15778. sigCtx->state = SIG_STATE_CHECK;
  15779. } /* SIG_STATE_DO */
  15780. FALL_THROUGH;
  15781. case SIG_STATE_CHECK:
  15782. {
  15783. switch (keyOID) {
  15784. #ifndef NO_RSA
  15785. case RSAk:
  15786. #ifdef WC_RSA_PSS
  15787. case RSAPSSk:
  15788. if (sigOID == RSAPSSk) {
  15789. #if (defined(HAVE_SELFTEST) && \
  15790. (!defined(HAVE_SELFTEST_VERSION) || \
  15791. (HAVE_SELFTEST_VERSION < 2))) || \
  15792. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15793. (HAVE_FIPS_VERSION < 2))
  15794. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15795. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15796. sigCtx->saltLen);
  15797. #elif (defined(HAVE_SELFTEST) && \
  15798. (HAVE_SELFTEST_VERSION == 2)) || \
  15799. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15800. (HAVE_FIPS_VERSION == 2))
  15801. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15802. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15803. sigCtx->saltLen, 0);
  15804. #else
  15805. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  15806. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  15807. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  15808. sigCtx->heap);
  15809. #endif
  15810. break;
  15811. }
  15812. else
  15813. #endif
  15814. {
  15815. int encodedSigSz, verifySz;
  15816. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  15817. defined(WOLFSSL_RENESAS_FSPSM_TLS)
  15818. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  15819. #endif
  15820. #ifdef WOLFSSL_SMALL_STACK
  15821. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  15822. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15823. if (encodedSig == NULL) {
  15824. ERROR_OUT(MEMORY_E, exit_cs);
  15825. }
  15826. #else
  15827. byte encodedSig[MAX_ENCODED_SIG_SZ];
  15828. #endif
  15829. verifySz = ret;
  15830. /* make sure we're right justified */
  15831. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  15832. sigCtx->digest, (word32)sigCtx->digestSz,
  15833. sigCtx->typeH);
  15834. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  15835. XMEMCMP(sigCtx->out, encodedSig,
  15836. (size_t)encodedSigSz) == 0) {
  15837. ret = 0;
  15838. }
  15839. else {
  15840. WOLFSSL_MSG("RSA SSL verify match encode error");
  15841. ret = ASN_SIG_CONFIRM_E;
  15842. WOLFSSL_ERROR_VERBOSE(ret);
  15843. }
  15844. #ifdef WOLFSSL_SMALL_STACK
  15845. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15846. #endif
  15847. break;
  15848. }
  15849. #endif /* NO_RSA */
  15850. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15851. case DSAk:
  15852. {
  15853. if (sigCtx->verify == 1) {
  15854. ret = 0;
  15855. }
  15856. else {
  15857. WOLFSSL_MSG("DSA Verify didn't match");
  15858. ret = ASN_SIG_CONFIRM_E;
  15859. WOLFSSL_ERROR_VERBOSE(ret);
  15860. }
  15861. break;
  15862. }
  15863. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15864. #ifdef HAVE_ECC
  15865. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15866. case SM2k:
  15867. #endif
  15868. case ECDSAk:
  15869. {
  15870. if (sigCtx->verify == 1) {
  15871. ret = 0;
  15872. }
  15873. else {
  15874. WOLFSSL_MSG("ECC Verify didn't match");
  15875. ret = ASN_SIG_CONFIRM_E;
  15876. WOLFSSL_ERROR_VERBOSE(ret);
  15877. }
  15878. break;
  15879. }
  15880. #endif /* HAVE_ECC */
  15881. #ifdef HAVE_ED25519
  15882. case ED25519k:
  15883. {
  15884. if (sigCtx->verify == 1) {
  15885. ret = 0;
  15886. }
  15887. else {
  15888. WOLFSSL_MSG("ED25519 Verify didn't match");
  15889. ret = ASN_SIG_CONFIRM_E;
  15890. WOLFSSL_ERROR_VERBOSE(ret);
  15891. }
  15892. break;
  15893. }
  15894. #endif /* HAVE_ED25519 */
  15895. #ifdef HAVE_ED448
  15896. case ED448k:
  15897. {
  15898. if (sigCtx->verify == 1) {
  15899. ret = 0;
  15900. }
  15901. else {
  15902. WOLFSSL_MSG("ED448 Verify didn't match");
  15903. ret = ASN_SIG_CONFIRM_E;
  15904. WOLFSSL_ERROR_VERBOSE(ret);
  15905. }
  15906. break;
  15907. }
  15908. #endif /* HAVE_ED448 */
  15909. #ifdef HAVE_PQC
  15910. #ifdef HAVE_FALCON
  15911. case FALCON_LEVEL1k:
  15912. {
  15913. if (sigCtx->verify == 1) {
  15914. ret = 0;
  15915. }
  15916. else {
  15917. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  15918. ret = ASN_SIG_CONFIRM_E;
  15919. WOLFSSL_ERROR_VERBOSE(ret);
  15920. }
  15921. break;
  15922. }
  15923. case FALCON_LEVEL5k:
  15924. {
  15925. if (sigCtx->verify == 1) {
  15926. ret = 0;
  15927. }
  15928. else {
  15929. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  15930. ret = ASN_SIG_CONFIRM_E;
  15931. WOLFSSL_ERROR_VERBOSE(ret);
  15932. }
  15933. break;
  15934. }
  15935. #endif /* HAVE_FALCON */
  15936. #ifdef HAVE_DILITHIUM
  15937. case DILITHIUM_LEVEL2k:
  15938. {
  15939. if (sigCtx->verify == 1) {
  15940. ret = 0;
  15941. }
  15942. else {
  15943. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  15944. ret = ASN_SIG_CONFIRM_E;
  15945. }
  15946. break;
  15947. }
  15948. case DILITHIUM_LEVEL3k:
  15949. {
  15950. if (sigCtx->verify == 1) {
  15951. ret = 0;
  15952. }
  15953. else {
  15954. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  15955. ret = ASN_SIG_CONFIRM_E;
  15956. }
  15957. break;
  15958. }
  15959. case DILITHIUM_LEVEL5k:
  15960. {
  15961. if (sigCtx->verify == 1) {
  15962. ret = 0;
  15963. }
  15964. else {
  15965. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  15966. ret = ASN_SIG_CONFIRM_E;
  15967. }
  15968. break;
  15969. }
  15970. #endif /* HAVE_DILITHIUM */
  15971. #ifdef HAVE_SPHINCS
  15972. case SPHINCS_FAST_LEVEL1k:
  15973. {
  15974. if (sigCtx->verify == 1) {
  15975. ret = 0;
  15976. }
  15977. else {
  15978. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  15979. ret = ASN_SIG_CONFIRM_E;
  15980. }
  15981. break;
  15982. }
  15983. case SPHINCS_FAST_LEVEL3k:
  15984. {
  15985. if (sigCtx->verify == 1) {
  15986. ret = 0;
  15987. }
  15988. else {
  15989. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  15990. ret = ASN_SIG_CONFIRM_E;
  15991. }
  15992. break;
  15993. }
  15994. case SPHINCS_FAST_LEVEL5k:
  15995. {
  15996. if (sigCtx->verify == 1) {
  15997. ret = 0;
  15998. }
  15999. else {
  16000. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  16001. ret = ASN_SIG_CONFIRM_E;
  16002. }
  16003. break;
  16004. }
  16005. case SPHINCS_SMALL_LEVEL1k:
  16006. {
  16007. if (sigCtx->verify == 1) {
  16008. ret = 0;
  16009. }
  16010. else {
  16011. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  16012. ret = ASN_SIG_CONFIRM_E;
  16013. }
  16014. break;
  16015. }
  16016. case SPHINCS_SMALL_LEVEL3k:
  16017. {
  16018. if (sigCtx->verify == 1) {
  16019. ret = 0;
  16020. }
  16021. else {
  16022. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  16023. ret = ASN_SIG_CONFIRM_E;
  16024. }
  16025. break;
  16026. }
  16027. case SPHINCS_SMALL_LEVEL5k:
  16028. {
  16029. if (sigCtx->verify == 1) {
  16030. ret = 0;
  16031. }
  16032. else {
  16033. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  16034. ret = ASN_SIG_CONFIRM_E;
  16035. }
  16036. break;
  16037. }
  16038. #endif /* HAVE_SPHINCS */
  16039. #endif /* HAVE_PQC */
  16040. default:
  16041. break;
  16042. } /* switch (keyOID) */
  16043. break;
  16044. } /* SIG_STATE_CHECK */
  16045. default:
  16046. break;
  16047. } /* switch (sigCtx->state) */
  16048. exit_cs:
  16049. #endif /* !NO_ASN_CRYPT */
  16050. (void)keyOID;
  16051. (void)sigOID;
  16052. WOLFSSL_LEAVE("ConfirmSignature", ret);
  16053. #ifdef WOLFSSL_ASYNC_CRYPT
  16054. if (ret == WC_PENDING_E)
  16055. return ret;
  16056. #endif
  16057. FreeSignatureCtx(sigCtx);
  16058. return ret;
  16059. }
  16060. #ifdef WOLFSSL_DUAL_ALG_CERTS
  16061. int wc_ConfirmAltSignature(
  16062. const byte* buf, word32 bufSz,
  16063. const byte* key, word32 keySz, word32 keyOID,
  16064. const byte* sig, word32 sigSz, word32 sigOID,
  16065. void *heap)
  16066. {
  16067. int ret = 0;
  16068. #ifdef WOLFSSL_SMALL_STACK
  16069. SignatureCtx* sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  16070. DYNAMIC_TYPE_SIGNATURE);
  16071. if (sigCtx == NULL) {
  16072. ret = MEMORY_E;
  16073. }
  16074. #else
  16075. SignatureCtx sigCtx[1];
  16076. (void)heap;
  16077. #endif
  16078. if (ret == 0) {
  16079. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  16080. ret = ConfirmSignature(sigCtx, buf, bufSz, key, keySz,
  16081. keyOID, sig, sigSz, sigOID, NULL, 0, NULL);
  16082. FreeSignatureCtx(sigCtx);
  16083. }
  16084. #ifdef WOLFSSL_SMALL_STACK
  16085. if (sigCtx != NULL)
  16086. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  16087. #endif
  16088. return ret;
  16089. }
  16090. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  16091. #ifndef IGNORE_NAME_CONSTRAINTS
  16092. static int MatchBaseName(int type, const char* name, int nameSz,
  16093. const char* base, int baseSz)
  16094. {
  16095. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  16096. name[0] == '.' || nameSz < baseSz ||
  16097. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  16098. type != ASN_DIR_TYPE)) {
  16099. return 0;
  16100. }
  16101. if (type == ASN_DIR_TYPE)
  16102. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  16103. /* If an email type, handle special cases where the base is only
  16104. * a domain, or is an email address itself. */
  16105. if (type == ASN_RFC822_TYPE) {
  16106. const char* p = NULL;
  16107. int count = 0;
  16108. if (base[0] != '.') {
  16109. p = base;
  16110. count = 0;
  16111. /* find the '@' in the base */
  16112. while (*p != '@' && count < baseSz) {
  16113. count++;
  16114. p++;
  16115. }
  16116. /* No '@' in base, reset p to NULL */
  16117. if (count >= baseSz)
  16118. p = NULL;
  16119. }
  16120. if (p == NULL) {
  16121. /* Base isn't an email address, it is a domain name,
  16122. * wind the name forward one character past its '@'. */
  16123. p = name;
  16124. count = 0;
  16125. while (*p != '@' && count < baseSz) {
  16126. count++;
  16127. p++;
  16128. }
  16129. if (count < baseSz && *p == '@') {
  16130. name = p + 1;
  16131. nameSz -= count + 1;
  16132. }
  16133. }
  16134. }
  16135. /* RFC 5280 section 4.2.1.10
  16136. * "...Any DNS name that can be constructed by simply adding zero or more
  16137. * labels to the left-hand side of the name satisfies the name constraint."
  16138. * i.e www.host.example.com works for host.example.com name constraint and
  16139. * host1.example.com does not. */
  16140. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  16141. int szAdjust = nameSz - baseSz;
  16142. name += szAdjust;
  16143. nameSz -= szAdjust;
  16144. }
  16145. while (nameSz > 0) {
  16146. if (XTOLOWER((unsigned char)*name) !=
  16147. XTOLOWER((unsigned char)*base))
  16148. return 0;
  16149. name++;
  16150. base++;
  16151. nameSz--;
  16152. }
  16153. return 1;
  16154. }
  16155. /* Search through the list to find if the name is permitted.
  16156. * name The DNS name to search for
  16157. * dnsList The list to search through
  16158. * nameType Type of DNS name to currently searching
  16159. * return 1 if found in list or if not needed
  16160. * return 0 if not found in the list but is needed
  16161. */
  16162. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  16163. {
  16164. Base_entry* current = dnsList;
  16165. int match = 0;
  16166. int need = 0;
  16167. int ret = 1; /* is ok unless needed and no match found */
  16168. while (current != NULL) {
  16169. if (current->type == nameType) {
  16170. need = 1; /* restriction on permitted names is set for this type */
  16171. if (name->len >= current->nameSz &&
  16172. MatchBaseName(nameType, name->name, name->len,
  16173. current->name, current->nameSz)) {
  16174. match = 1; /* found the current name in the permitted list*/
  16175. break;
  16176. }
  16177. }
  16178. current = current->next;
  16179. }
  16180. /* check if permitted name restriction was set and no matching name found */
  16181. if (need && !match)
  16182. ret = 0;
  16183. return ret;
  16184. }
  16185. /* Search through the list to find if the name is excluded.
  16186. * name The DNS name to search for
  16187. * dnsList The list to search through
  16188. * nameType Type of DNS name to currently searching
  16189. * return 1 if found in list and 0 if not found in the list
  16190. */
  16191. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  16192. {
  16193. int ret = 0; /* default of not found in the list */
  16194. Base_entry* current = dnsList;
  16195. while (current != NULL) {
  16196. if (current->type == nameType) {
  16197. if (name->len >= current->nameSz &&
  16198. MatchBaseName(nameType, name->name, name->len,
  16199. current->name, current->nameSz)) {
  16200. ret = 1;
  16201. break;
  16202. }
  16203. }
  16204. current = current->next;
  16205. }
  16206. return ret;
  16207. }
  16208. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  16209. {
  16210. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  16211. int i;
  16212. if (signer == NULL || cert == NULL)
  16213. return 0;
  16214. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  16215. return 1;
  16216. for (i=0; i < (int)sizeof(nameTypes); i++) {
  16217. byte nameType = nameTypes[i];
  16218. DNS_entry* name = NULL;
  16219. DNS_entry subjectDnsName; /* temporary node used for subject name */
  16220. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  16221. switch (nameType) {
  16222. case ASN_DNS_TYPE:
  16223. /* Should it also consider CN in subject? It could use
  16224. * subjectDnsName too */
  16225. name = cert->altNames;
  16226. break;
  16227. case ASN_RFC822_TYPE:
  16228. /* Shouldn't it validate E= in subject as well? */
  16229. name = cert->altEmailNames;
  16230. /* Add subject email for checking. */
  16231. if (cert->subjectEmail != NULL) {
  16232. /* RFC 5280 section 4.2.1.10
  16233. * "When constraints are imposed on the rfc822Name name
  16234. * form, but the certificate does not include a subject
  16235. * alternative name, the rfc822Name constraint MUST be
  16236. * applied to the attribute of type emailAddress in the
  16237. * subject distinguished name" */
  16238. subjectDnsName.next = NULL;
  16239. subjectDnsName.type = ASN_RFC822_TYPE;
  16240. subjectDnsName.len = cert->subjectEmailLen;
  16241. subjectDnsName.name = (char *)cert->subjectEmail;
  16242. }
  16243. break;
  16244. case ASN_DIR_TYPE:
  16245. #ifndef WOLFSSL_NO_ASN_STRICT
  16246. name = cert->altDirNames;
  16247. #endif
  16248. /* RFC 5280 section 4.2.1.10
  16249. "Restrictions of the form directoryName MUST be
  16250. applied to the subject field .... and to any names
  16251. of type directoryName in the subjectAltName
  16252. extension"
  16253. */
  16254. if (cert->subjectRaw != NULL) {
  16255. subjectDnsName.next = NULL;
  16256. subjectDnsName.type = ASN_DIR_TYPE;
  16257. subjectDnsName.len = cert->subjectRawLen;
  16258. subjectDnsName.name = (char *)cert->subjectRaw;
  16259. }
  16260. break;
  16261. default:
  16262. /* Other types of names are ignored for now.
  16263. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  16264. * and signer->extNameConstraintCrit is set? */
  16265. return 0;
  16266. }
  16267. while (name != NULL) {
  16268. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  16269. WOLFSSL_MSG("Excluded name was found!");
  16270. return 0;
  16271. }
  16272. /* Check against the permitted list */
  16273. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  16274. WOLFSSL_MSG("Permitted name was not found!");
  16275. return 0;
  16276. }
  16277. name = name->next;
  16278. }
  16279. /* handle comparing against subject name too */
  16280. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  16281. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  16282. nameType) == 1) {
  16283. WOLFSSL_MSG("Excluded name was found!");
  16284. return 0;
  16285. }
  16286. /* Check against the permitted list */
  16287. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  16288. nameType) != 1) {
  16289. WOLFSSL_MSG("Permitted name was not found!");
  16290. return 0;
  16291. }
  16292. }
  16293. }
  16294. return 1;
  16295. }
  16296. #endif /* IGNORE_NAME_CONSTRAINTS */
  16297. #ifndef WOLFSSL_ASN_TEMPLATE
  16298. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  16299. {
  16300. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  16301. dnsEntry->next = NULL;
  16302. if (cert->altNames == NULL) {
  16303. /* First on list */
  16304. cert->altNames = dnsEntry;
  16305. }
  16306. else {
  16307. DNS_entry* temp = cert->altNames;
  16308. /* Find end */
  16309. for (; (temp->next != NULL); temp = temp->next);
  16310. /* Add to end */
  16311. temp->next = dnsEntry;
  16312. }
  16313. #else
  16314. dnsEntry->next = cert->altNames;
  16315. cert->altNames = dnsEntry;
  16316. #endif
  16317. }
  16318. #endif
  16319. #ifdef WOLFSSL_ASN_TEMPLATE
  16320. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  16321. /* ASN.1 template for OtherName of an X.509 certificate.
  16322. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  16323. * HW Name: RFC 4108, 5 - Hardware Module Name
  16324. * Only support HW Name where the type is a HW serial number.
  16325. *
  16326. * Other Names handled for FPKI (Federal PKI) use:
  16327. * UPN (Universal Principal Name), a non-standard Other Name
  16328. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  16329. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  16330. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  16331. */
  16332. static const ASNItem otherNameASN[] = {
  16333. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  16334. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  16335. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  16336. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  16337. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  16338. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  16339. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  16340. };
  16341. enum {
  16342. OTHERNAMEASN_IDX_TYPEID = 0,
  16343. OTHERNAMEASN_IDX_VALUE,
  16344. OTHERNAMEASN_IDX_UPN,
  16345. OTHERNAMEASN_IDX_FASCN,
  16346. OTHERNAMEASN_IDX_HWN_SEQ,
  16347. OTHERNAMEASN_IDX_HWN_TYPE,
  16348. OTHERNAMEASN_IDX_HWN_NUM
  16349. };
  16350. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  16351. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  16352. #ifdef WOLFSSL_SEP
  16353. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  16354. {
  16355. int ret = 0;
  16356. word32 oidLen, serialLen;
  16357. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  16358. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  16359. /* Allocate space for HW type OID. */
  16360. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  16361. DYNAMIC_TYPE_X509_EXT);
  16362. if (cert->hwType == NULL)
  16363. ret = MEMORY_E;
  16364. if (ret == 0) {
  16365. /* Copy, into cert HW type OID */
  16366. XMEMCPY(cert->hwType,
  16367. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  16368. cert->hwTypeSz = (int)oidLen;
  16369. /* TODO: check this is the HW serial number OID - no test data. */
  16370. /* Allocate space for HW serial number, +1 for null terminator. */
  16371. cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
  16372. DYNAMIC_TYPE_X509_EXT);
  16373. if (cert->hwSerialNum == NULL) {
  16374. WOLFSSL_MSG("\tOut of Memory");
  16375. ret = MEMORY_E;
  16376. }
  16377. }
  16378. if (ret == 0) {
  16379. /* Copy into cert HW serial number. */
  16380. XMEMCPY(cert->hwSerialNum,
  16381. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  16382. cert->hwSerialNum[serialLen] = '\0';
  16383. cert->hwSerialNumSz = (int)serialLen;
  16384. }
  16385. return ret;
  16386. }
  16387. #endif /* WOLFSSL_SEP */
  16388. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  16389. {
  16390. DNS_entry* entry = NULL;
  16391. int ret = 0;
  16392. word32 bufLen = 0;
  16393. const char* buf = NULL;
  16394. switch (oid) {
  16395. #ifdef WOLFSSL_FPKI
  16396. case FASCN_OID:
  16397. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  16398. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  16399. break;
  16400. #endif /* WOLFSSL_FPKI */
  16401. case UPN_OID:
  16402. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  16403. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  16404. break;
  16405. default:
  16406. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  16407. ret = ASN_UNKNOWN_OID_E;
  16408. break;
  16409. }
  16410. if (ret == 0) {
  16411. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  16412. if (ret == 0) {
  16413. #ifdef WOLFSSL_FPKI
  16414. entry->oidSum = oid;
  16415. #endif
  16416. AddDNSEntryToList(&cert->altNames, entry);
  16417. }
  16418. }
  16419. return ret;
  16420. }
  16421. /* Decode data with OtherName format from after implicit SEQUENCE.
  16422. *
  16423. * @param [in, out] cert Certificate object.
  16424. * @param [in] input Buffer containing encoded OtherName.
  16425. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  16426. * On out, index after OtherName.
  16427. * @param [in] maxIdx Maximum index of data in buffer.
  16428. * @return 0 on success.
  16429. * @return MEMORY_E on dynamic memory allocation failure.
  16430. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16431. * is invalid.
  16432. * @return ASN_PARSE_E when OID does is not HW Name.
  16433. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16434. * @return BUFFER_E when data in buffer is too small.
  16435. */
  16436. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  16437. word32* inOutIdx, word32 maxIdx)
  16438. {
  16439. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  16440. int ret = 0;
  16441. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  16442. if (ret == 0) {
  16443. /* Check the first OID is a recognized Alt Cert Name type. */
  16444. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  16445. /* Parse OtherName. */
  16446. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  16447. inOutIdx, maxIdx);
  16448. }
  16449. if (ret == 0) {
  16450. /* Ensure expected OID. */
  16451. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  16452. #ifdef WOLFSSL_SEP
  16453. case HW_NAME_OID:
  16454. /* Only support HW serial number. */
  16455. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  16456. ret = DecodeSEP(dataASN, cert);
  16457. break;
  16458. #endif /* WOLFSSL_SEP */
  16459. #ifdef WOLFSSL_FPKI
  16460. case FASCN_OID:
  16461. #endif /* WOLFSSL_FPKI */
  16462. case UPN_OID:
  16463. ret = DecodeOtherHelper(dataASN, cert,
  16464. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  16465. break;
  16466. default:
  16467. WOLFSSL_MSG("\tunsupported OID skipping");
  16468. break;
  16469. }
  16470. }
  16471. FREE_ASNGETDATA(dataASN, cert->heap);
  16472. return ret;
  16473. }
  16474. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  16475. /* Decode a GeneralName.
  16476. *
  16477. * @param [in] input Buffer containing encoded OtherName.
  16478. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  16479. * On out, index after OtherName.
  16480. * @param [in] len Length of data in buffer.
  16481. * @param [in] cert Decoded certificate object.
  16482. * @return 0 on success.
  16483. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16484. * is invalid.
  16485. * @return BUFFER_E when data in buffer is too small.
  16486. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16487. * @return MEMORY_E when dynamic memory allocation fails.
  16488. */
  16489. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  16490. int len, DecodedCert* cert)
  16491. {
  16492. int ret = 0;
  16493. word32 idx = *inOutIdx;
  16494. /* GeneralName choice: dnsName */
  16495. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16496. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  16497. &cert->altNames);
  16498. if (ret == 0) {
  16499. idx += (word32)len;
  16500. }
  16501. }
  16502. #ifndef IGNORE_NAME_CONSTRAINTS
  16503. /* GeneralName choice: directoryName */
  16504. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16505. int strLen;
  16506. word32 idxDir = idx;
  16507. /* Expecting a SEQUENCE using up all data. */
  16508. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  16509. {
  16510. WOLFSSL_MSG("\tfail: seq length");
  16511. return ASN_PARSE_E;
  16512. }
  16513. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  16514. ASN_DIR_TYPE, &cert->altDirNames);
  16515. if (ret == 0) {
  16516. idx += (word32)len;
  16517. }
  16518. }
  16519. /* GeneralName choice: rfc822Name */
  16520. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16521. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  16522. ASN_RFC822_TYPE, &cert->altEmailNames);
  16523. if (ret == 0) {
  16524. idx += (word32)len;
  16525. }
  16526. }
  16527. /* GeneralName choice: uniformResourceIdentifier */
  16528. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16529. WOLFSSL_MSG("\tPutting URI into list but not using");
  16530. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16531. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16532. "The name MUST NOT be a relative URI"
  16533. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16534. a scheme and hier-part. So the only strict requirement is a ':'
  16535. being present after the scheme. If a '/' is present as part of the
  16536. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16537. {
  16538. int i;
  16539. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16540. for (i = 0; i < len; i++) {
  16541. if (input[idx + (word32)i] == ':') {
  16542. break;
  16543. }
  16544. if (input[idx + (word32)i] == '/') {
  16545. i = len; /* error, found relative path since '/' was
  16546. * encountered before ':'. Returning error
  16547. * value in next if statement. */
  16548. }
  16549. }
  16550. /* test hier-part is empty */
  16551. if (i == 0 || i == len) {
  16552. WOLFSSL_MSG("\tEmpty or malformed URI");
  16553. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16554. return ASN_ALT_NAME_E;
  16555. }
  16556. /* test if scheme is missing */
  16557. if (input[idx + (word32)i] != ':') {
  16558. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16559. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16560. return ASN_ALT_NAME_E;
  16561. }
  16562. }
  16563. #endif
  16564. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  16565. &cert->altNames);
  16566. if (ret == 0) {
  16567. idx += (word32)len;
  16568. }
  16569. }
  16570. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  16571. defined(WOLFSSL_IP_ALT_NAME)
  16572. /* GeneralName choice: iPAddress */
  16573. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16574. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  16575. &cert->altNames);
  16576. if (ret == 0) {
  16577. idx += (word32)len;
  16578. }
  16579. }
  16580. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16581. /* GeneralName choice: registeredID */
  16582. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) {
  16583. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  16584. ASN_RID_TYPE, &cert->altNames);
  16585. if (ret == 0) {
  16586. idx += (word32)len;
  16587. }
  16588. }
  16589. #endif /* IGNORE_NAME_CONSTRAINTS */
  16590. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  16591. /* GeneralName choice: otherName */
  16592. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16593. /* TODO: test data for code path */
  16594. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  16595. }
  16596. #endif
  16597. /* GeneralName choice: dNSName, x400Address, ediPartyName */
  16598. else {
  16599. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16600. idx += (word32)len;
  16601. }
  16602. if (ret == 0) {
  16603. /* Return index of next encoded byte. */
  16604. *inOutIdx = idx;
  16605. }
  16606. return ret;
  16607. }
  16608. /* ASN.1 choices for GeneralName.
  16609. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16610. */
  16611. static const byte generalNameChoice[] = {
  16612. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  16613. ASN_CONTEXT_SPECIFIC | 1,
  16614. ASN_CONTEXT_SPECIFIC | 2,
  16615. ASN_CONTEXT_SPECIFIC | 3,
  16616. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  16617. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  16618. ASN_CONTEXT_SPECIFIC | 6,
  16619. ASN_CONTEXT_SPECIFIC | 7,
  16620. ASN_CONTEXT_SPECIFIC | 8,
  16621. 0
  16622. };
  16623. /* ASN.1 template for GeneralName.
  16624. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16625. */
  16626. static const ASNItem altNameASN[] = {
  16627. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  16628. };
  16629. enum {
  16630. ALTNAMEASN_IDX_GN = 0
  16631. };
  16632. /* Number of items in ASN.1 template for GeneralName. */
  16633. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  16634. #endif /* WOLFSSL_ASN_TEMPLATE */
  16635. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  16636. /* return 0 on success */
  16637. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  16638. word32* idxIn, word32 sz)
  16639. {
  16640. word32 idx = *idxIn;
  16641. int strLen;
  16642. int ret;
  16643. byte tag;
  16644. /* Certificates issued with this OID in the subject alt name are for
  16645. * verifying signatures created on a module.
  16646. * RFC 4108 Section 5. */
  16647. if (cert->hwType != NULL) {
  16648. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  16649. return ASN_PARSE_E;
  16650. }
  16651. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16652. return ASN_PARSE_E;
  16653. }
  16654. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  16655. WOLFSSL_MSG("\twrong type");
  16656. return ASN_PARSE_E;
  16657. }
  16658. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16659. WOLFSSL_MSG("\tfail: str len");
  16660. return ASN_PARSE_E;
  16661. }
  16662. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16663. WOLFSSL_MSG("\tBad Sequence");
  16664. return ASN_PARSE_E;
  16665. }
  16666. ret = GetASNObjectId(input, &idx, &strLen, sz);
  16667. if (ret != 0) {
  16668. WOLFSSL_MSG("\tbad OID");
  16669. return ret;
  16670. }
  16671. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  16672. DYNAMIC_TYPE_X509_EXT);
  16673. if (cert->hwType == NULL) {
  16674. WOLFSSL_MSG("\tOut of Memory");
  16675. return MEMORY_E;
  16676. }
  16677. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  16678. cert->hwTypeSz = strLen;
  16679. idx += (word32)strLen;
  16680. ret = GetOctetString(input, &idx, &strLen, sz);
  16681. if (ret < 0) {
  16682. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16683. cert->hwType = NULL;
  16684. return ret;
  16685. }
  16686. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  16687. DYNAMIC_TYPE_X509_EXT);
  16688. if (cert->hwSerialNum == NULL) {
  16689. WOLFSSL_MSG("\tOut of Memory");
  16690. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16691. cert->hwType = NULL;
  16692. return MEMORY_E;
  16693. }
  16694. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  16695. cert->hwSerialNum[strLen] = '\0';
  16696. cert->hwSerialNumSz = strLen;
  16697. idx += (word32)strLen;
  16698. *idxIn = idx;
  16699. return 0;
  16700. }
  16701. #endif /* WOLFSSL_SEP */
  16702. #if !defined(WOLFSSL_ASN_TEMPLATE)
  16703. /* return 0 on success */
  16704. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  16705. word32* idx, word32 sz, int oid)
  16706. {
  16707. int ret = 0;
  16708. int strLen = 0;
  16709. byte tag;
  16710. DNS_entry* dnsEntry = NULL;
  16711. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16712. ret = ASN_PARSE_E;
  16713. }
  16714. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  16715. ret = ASN_PARSE_E;
  16716. }
  16717. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16718. ret = ASN_PARSE_E;
  16719. }
  16720. if (ret == 0) {
  16721. dnsEntry = AltNameNew(cert->heap);
  16722. if (dnsEntry == NULL) {
  16723. WOLFSSL_MSG("\tOut of Memory");
  16724. return MEMORY_E;
  16725. }
  16726. switch (oid) {
  16727. #ifdef WOLFSSL_FPKI
  16728. case FASCN_OID:
  16729. ret = GetOctetString(input, idx, &strLen, sz);
  16730. if (ret > 0) {
  16731. ret = 0;
  16732. }
  16733. break;
  16734. #endif /* WOLFSSL_FPKI */
  16735. case UPN_OID:
  16736. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16737. ret = ASN_PARSE_E;
  16738. }
  16739. if (ret == 0 &&
  16740. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16741. tag != ASN_IA5_STRING) {
  16742. WOLFSSL_MSG("Was expecting a string for UPN");
  16743. ret = ASN_PARSE_E;
  16744. }
  16745. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16746. WOLFSSL_MSG("Was expecting a string for UPN");
  16747. ret = ASN_PARSE_E;
  16748. }
  16749. break;
  16750. default:
  16751. WOLFSSL_MSG("Unknown constructed other name, skipping");
  16752. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16753. dnsEntry = NULL;
  16754. }
  16755. }
  16756. if (ret == 0 && dnsEntry != NULL) {
  16757. dnsEntry->type = ASN_OTHER_TYPE;
  16758. dnsEntry->len = strLen;
  16759. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16760. DYNAMIC_TYPE_ALTNAME);
  16761. #ifdef WOLFSSL_FPKI
  16762. dnsEntry->oidSum = oid;
  16763. #endif /* WOLFSSL_FPKI */
  16764. if (dnsEntry->name == NULL) {
  16765. WOLFSSL_MSG("\tOut of Memory");
  16766. ret = MEMORY_E;
  16767. }
  16768. else {
  16769. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  16770. dnsEntry->name[strLen] = '\0';
  16771. AddAltName(cert, dnsEntry);
  16772. }
  16773. }
  16774. if (ret == 0) {
  16775. *idx += (word32)strLen;
  16776. }
  16777. else {
  16778. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16779. }
  16780. return ret;
  16781. }
  16782. #endif
  16783. /* Decode subject alternative names extension.
  16784. *
  16785. * RFC 5280 4.2.1.6. Subject Alternative Name
  16786. *
  16787. * @param [in] input Buffer holding encoded data.
  16788. * @param [in] sz Size of encoded data in bytes.
  16789. * @param [in, out] cert Decoded certificate object.
  16790. * @return 0 on success.
  16791. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16792. * is invalid.
  16793. * @return BUFFER_E when data in buffer is too small.
  16794. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16795. * @return MEMORY_E when dynamic memory allocation fails.
  16796. */
  16797. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  16798. {
  16799. #ifndef WOLFSSL_ASN_TEMPLATE
  16800. word32 idx = 0;
  16801. int length = 0;
  16802. WOLFSSL_ENTER("DecodeAltNames");
  16803. if (GetSequence(input, &idx, &length, sz) < 0) {
  16804. WOLFSSL_MSG("\tBad Sequence");
  16805. return ASN_PARSE_E;
  16806. }
  16807. if (length == 0) {
  16808. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16809. If the subjectAltName extension is present, the sequence MUST
  16810. contain at least one entry. */
  16811. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16812. return ASN_PARSE_E;
  16813. }
  16814. #ifdef OPENSSL_ALL
  16815. cert->extSubjAltNameSrc = input;
  16816. cert->extSubjAltNameSz = sz;
  16817. #endif
  16818. cert->weOwnAltNames = 1;
  16819. while (length > 0) {
  16820. byte current_byte;
  16821. /* Verify idx can't overflow input buffer */
  16822. if (idx >= (word32)sz) {
  16823. WOLFSSL_MSG("\tBad Index");
  16824. return BUFFER_E;
  16825. }
  16826. current_byte = input[idx++];
  16827. length--;
  16828. /* Save DNS Type names in the altNames list. */
  16829. /* Save Other Type names in the cert's OidMap */
  16830. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16831. DNS_entry* dnsEntry;
  16832. int strLen;
  16833. word32 lenStartIdx = idx;
  16834. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16835. WOLFSSL_MSG("\tfail: str length");
  16836. return ASN_PARSE_E;
  16837. }
  16838. length -= (int)(idx - lenStartIdx);
  16839. dnsEntry = AltNameNew(cert->heap);
  16840. if (dnsEntry == NULL) {
  16841. WOLFSSL_MSG("\tOut of Memory");
  16842. return MEMORY_E;
  16843. }
  16844. dnsEntry->type = ASN_DNS_TYPE;
  16845. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16846. DYNAMIC_TYPE_ALTNAME);
  16847. if (dnsEntry->name == NULL) {
  16848. WOLFSSL_MSG("\tOut of Memory");
  16849. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16850. return MEMORY_E;
  16851. }
  16852. dnsEntry->len = strLen;
  16853. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  16854. dnsEntry->name[strLen] = '\0';
  16855. AddAltName(cert, dnsEntry);
  16856. length -= strLen;
  16857. idx += (word32)strLen;
  16858. }
  16859. #ifndef IGNORE_NAME_CONSTRAINTS
  16860. else if (current_byte ==
  16861. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16862. DNS_entry* dirEntry;
  16863. int strLen;
  16864. word32 lenStartIdx = idx;
  16865. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16866. WOLFSSL_MSG("\tfail: str length");
  16867. return ASN_PARSE_E;
  16868. }
  16869. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16870. WOLFSSL_MSG("\tfail: seq length");
  16871. return ASN_PARSE_E;
  16872. }
  16873. length -= (int)(idx - lenStartIdx);
  16874. dirEntry = AltNameNew(cert->heap);
  16875. if (dirEntry == NULL) {
  16876. WOLFSSL_MSG("\tOut of Memory");
  16877. return MEMORY_E;
  16878. }
  16879. dirEntry->type = ASN_DIR_TYPE;
  16880. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16881. DYNAMIC_TYPE_ALTNAME);
  16882. if (dirEntry->name == NULL) {
  16883. WOLFSSL_MSG("\tOut of Memory");
  16884. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16885. return MEMORY_E;
  16886. }
  16887. dirEntry->len = strLen;
  16888. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  16889. dirEntry->name[strLen] = '\0';
  16890. dirEntry->next = cert->altDirNames;
  16891. cert->altDirNames = dirEntry;
  16892. length -= strLen;
  16893. idx += (word32)strLen;
  16894. }
  16895. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16896. DNS_entry* emailEntry;
  16897. int strLen;
  16898. word32 lenStartIdx = idx;
  16899. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16900. WOLFSSL_MSG("\tfail: str length");
  16901. return ASN_PARSE_E;
  16902. }
  16903. length -= (int)(idx - lenStartIdx);
  16904. emailEntry = AltNameNew(cert->heap);
  16905. if (emailEntry == NULL) {
  16906. WOLFSSL_MSG("\tOut of Memory");
  16907. return MEMORY_E;
  16908. }
  16909. emailEntry->type = ASN_RFC822_TYPE;
  16910. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16911. DYNAMIC_TYPE_ALTNAME);
  16912. if (emailEntry->name == NULL) {
  16913. WOLFSSL_MSG("\tOut of Memory");
  16914. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16915. return MEMORY_E;
  16916. }
  16917. emailEntry->len = strLen;
  16918. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  16919. emailEntry->name[strLen] = '\0';
  16920. emailEntry->next = cert->altEmailNames;
  16921. cert->altEmailNames = emailEntry;
  16922. length -= strLen;
  16923. idx += (word32)strLen;
  16924. }
  16925. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16926. DNS_entry* uriEntry;
  16927. int strLen;
  16928. word32 lenStartIdx = idx;
  16929. WOLFSSL_MSG("\tPutting URI into list but not using");
  16930. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16931. WOLFSSL_MSG("\tfail: str length");
  16932. return ASN_PARSE_E;
  16933. }
  16934. length -= (int)(idx - lenStartIdx);
  16935. /* check that strLen at index is not past input buffer */
  16936. if ((word32)strLen + idx > sz) {
  16937. return BUFFER_E;
  16938. }
  16939. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16940. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16941. "The name MUST NOT be a relative URI"
  16942. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16943. a scheme and hier-part. So the only strict requirement is a ':'
  16944. being present after the scheme. If a '/' is present as part of the
  16945. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16946. {
  16947. word32 i;
  16948. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16949. for (i = 0; i < (word32)strLen; i++) {
  16950. if (input[idx + i] == ':') {
  16951. break;
  16952. }
  16953. if (input[idx + i] == '/') {
  16954. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16955. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16956. return ASN_ALT_NAME_E;
  16957. }
  16958. }
  16959. /* test hier-part is empty */
  16960. if (i == 0 || i == (word32)strLen) {
  16961. WOLFSSL_MSG("\tEmpty or malformed URI");
  16962. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16963. return ASN_ALT_NAME_E;
  16964. }
  16965. /* test if scheme is missing */
  16966. if (input[idx + i] != ':') {
  16967. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16968. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16969. return ASN_ALT_NAME_E;
  16970. }
  16971. }
  16972. #endif
  16973. uriEntry = AltNameNew(cert->heap);
  16974. if (uriEntry == NULL) {
  16975. WOLFSSL_MSG("\tOut of Memory");
  16976. return MEMORY_E;
  16977. }
  16978. uriEntry->type = ASN_URI_TYPE;
  16979. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16980. DYNAMIC_TYPE_ALTNAME);
  16981. if (uriEntry->name == NULL) {
  16982. WOLFSSL_MSG("\tOut of Memory");
  16983. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16984. return MEMORY_E;
  16985. }
  16986. uriEntry->len = strLen;
  16987. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  16988. uriEntry->name[strLen] = '\0';
  16989. AddAltName(cert, uriEntry);
  16990. length -= strLen;
  16991. idx += (word32)strLen;
  16992. }
  16993. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16994. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16995. DNS_entry* ipAddr;
  16996. int strLen;
  16997. word32 lenStartIdx = idx;
  16998. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  16999. if (GetLength(input, &idx, &strLen, sz) < 0) {
  17000. WOLFSSL_MSG("\tfail: str length");
  17001. return ASN_PARSE_E;
  17002. }
  17003. length -= (idx - lenStartIdx);
  17004. /* check that strLen at index is not past input buffer */
  17005. if (strLen + idx > sz) {
  17006. return BUFFER_E;
  17007. }
  17008. ipAddr = AltNameNew(cert->heap);
  17009. if (ipAddr == NULL) {
  17010. WOLFSSL_MSG("\tOut of Memory");
  17011. return MEMORY_E;
  17012. }
  17013. ipAddr->type = ASN_IP_TYPE;
  17014. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  17015. DYNAMIC_TYPE_ALTNAME);
  17016. if (ipAddr->name == NULL) {
  17017. WOLFSSL_MSG("\tOut of Memory");
  17018. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  17019. return MEMORY_E;
  17020. }
  17021. ipAddr->len = strLen;
  17022. XMEMCPY(ipAddr->name, &input[idx], strLen);
  17023. ipAddr->name[strLen] = '\0';
  17024. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  17025. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  17026. WOLFSSL_MSG("\tOut of Memory for IP string");
  17027. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  17028. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  17029. return MEMORY_E;
  17030. }
  17031. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  17032. AddAltName(cert, ipAddr);
  17033. length -= strLen;
  17034. idx += (word32)strLen;
  17035. }
  17036. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  17037. #if defined(OPENSSL_ALL)
  17038. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) {
  17039. DNS_entry* rid;
  17040. int strLen;
  17041. word32 lenStartIdx = idx;
  17042. WOLFSSL_MSG("Decoding Subject Alt. Name: Registered Id");
  17043. if (GetLength(input, &idx, &strLen, sz) < 0) {
  17044. WOLFSSL_MSG("\tfail: str length");
  17045. return ASN_PARSE_E;
  17046. }
  17047. length -= (idx - lenStartIdx);
  17048. /* check that strLen at index is not past input buffer */
  17049. if (strLen + idx > sz) {
  17050. return BUFFER_E;
  17051. }
  17052. rid = AltNameNew(cert->heap);
  17053. if (rid == NULL) {
  17054. WOLFSSL_MSG("\tOut of Memory");
  17055. return MEMORY_E;
  17056. }
  17057. rid->type = ASN_RID_TYPE;
  17058. rid->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  17059. DYNAMIC_TYPE_ALTNAME);
  17060. if (rid->name == NULL) {
  17061. WOLFSSL_MSG("\tOut of Memory");
  17062. XFREE(rid, cert->heap, DYNAMIC_TYPE_ALTNAME);
  17063. return MEMORY_E;
  17064. }
  17065. rid->len = strLen;
  17066. XMEMCPY(rid->name, &input[idx], strLen);
  17067. rid->name[strLen] = '\0';
  17068. if (GenerateDNSEntryRIDString(rid, cert->heap) != 0) {
  17069. WOLFSSL_MSG("\tOut of Memory for registered Id string");
  17070. XFREE(rid->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  17071. XFREE(rid, cert->heap, DYNAMIC_TYPE_ALTNAME);
  17072. return MEMORY_E;
  17073. }
  17074. AddAltName(cert, rid);
  17075. length -= strLen;
  17076. idx += (word32)strLen;
  17077. }
  17078. #endif /* OPENSSL_ALL */
  17079. #endif /* IGNORE_NAME_CONSTRAINTS */
  17080. else if (current_byte ==
  17081. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  17082. int strLen;
  17083. word32 lenStartIdx = idx;
  17084. word32 oid = 0;
  17085. int ret = 0;
  17086. if (GetLength(input, &idx, &strLen, sz) < 0) {
  17087. WOLFSSL_MSG("\tfail: other name length");
  17088. return ASN_PARSE_E;
  17089. }
  17090. /* Consume the rest of this sequence. */
  17091. length -= (int)(((word32)strLen + idx - lenStartIdx));
  17092. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  17093. WOLFSSL_MSG("\tbad OID");
  17094. return ASN_PARSE_E;
  17095. }
  17096. /* handle parsing other type alt names */
  17097. switch (oid) {
  17098. #ifdef WOLFSSL_SEP
  17099. case HW_NAME_OID:
  17100. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  17101. if (ret != 0)
  17102. return ret;
  17103. break;
  17104. #endif /* WOLFSSL_SEP */
  17105. #ifdef WOLFSSL_FPKI
  17106. case FASCN_OID:
  17107. case UPN_OID:
  17108. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  17109. oid);
  17110. if (ret != 0)
  17111. return ret;
  17112. break;
  17113. #endif /* WOLFSSL_FPKI */
  17114. default:
  17115. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  17116. if (GetLength(input, &idx, &strLen, sz) < 0) {
  17117. /* check to skip constructed other names too */
  17118. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  17119. (int)oid) != 0) {
  17120. WOLFSSL_MSG("\tfail: unsupported other name length");
  17121. return ASN_PARSE_E;
  17122. }
  17123. }
  17124. else {
  17125. idx += (word32)strLen;
  17126. }
  17127. }
  17128. (void)ret;
  17129. }
  17130. else {
  17131. int strLen;
  17132. word32 lenStartIdx = idx;
  17133. WOLFSSL_MSG("\tUnsupported name type, skipping");
  17134. if (GetLength(input, &idx, &strLen, sz) < 0) {
  17135. WOLFSSL_MSG("\tfail: unsupported name length");
  17136. return ASN_PARSE_E;
  17137. }
  17138. length -= (int)((word32)strLen + idx - lenStartIdx);
  17139. idx += (word32)strLen;
  17140. }
  17141. }
  17142. return 0;
  17143. #else
  17144. word32 idx = 0;
  17145. int length = 0;
  17146. int ret = 0;
  17147. WOLFSSL_ENTER("DecodeAltNames");
  17148. /* Get SEQUENCE and expect all data to be accounted for. */
  17149. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  17150. WOLFSSL_MSG("\tBad Sequence");
  17151. ret = ASN_PARSE_E;
  17152. }
  17153. if ((ret == 0) && (length == 0)) {
  17154. /* RFC 5280 4.2.1.6. Subject Alternative Name
  17155. If the subjectAltName extension is present, the sequence MUST
  17156. contain at least one entry. */
  17157. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17158. ret = ASN_PARSE_E;
  17159. }
  17160. if (ret == 0) {
  17161. #ifdef OPENSSL_ALL
  17162. cert->extSubjAltNameSrc = input;
  17163. cert->extSubjAltNameSz = sz;
  17164. #endif
  17165. cert->weOwnAltNames = 1;
  17166. if ((word32)length + idx != sz) {
  17167. ret = ASN_PARSE_E;
  17168. }
  17169. }
  17170. while ((ret == 0) && (idx < sz)) {
  17171. ASNGetData dataASN[altNameASN_Length];
  17172. /* Clear dynamic data items. */
  17173. XMEMSET(dataASN, 0, sizeof(dataASN));
  17174. /* Parse GeneralName with the choices supported. */
  17175. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  17176. /* Decode a GeneralName choice. */
  17177. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  17178. &idx, sz);
  17179. if (ret == 0) {
  17180. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  17181. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  17182. }
  17183. }
  17184. return ret;
  17185. #endif
  17186. }
  17187. #ifdef WOLFSSL_ASN_TEMPLATE
  17188. /* ASN.1 template for BasicConstraints.
  17189. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  17190. */
  17191. static const ASNItem basicConsASN[] = {
  17192. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17193. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  17194. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  17195. };
  17196. enum {
  17197. BASICCONSASN_IDX_SEQ = 0,
  17198. BASICCONSASN_IDX_CA,
  17199. BASICCONSASN_IDX_PLEN
  17200. };
  17201. /* Number of items in ASN.1 template for BasicContraints. */
  17202. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  17203. #endif
  17204. /* Decode basic constraints extension in a certificate.
  17205. *
  17206. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  17207. *
  17208. * @param [in] input Buffer holding data.
  17209. * @param [in] sz Size of data in buffer.
  17210. * @param [in, out] cert Certificate object.
  17211. * @return 0 on success.
  17212. * @return MEMORY_E on dynamic memory allocation failure.
  17213. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  17214. * @return ASN_PARSE_E when CA boolean is not present unless
  17215. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  17216. * @return ASN_PARSE_E when path length more than 7 bits.
  17217. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17218. * is invalid.
  17219. * @return BUFFER_E when data in buffer is too small.
  17220. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  17221. * non-zero length.
  17222. */
  17223. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  17224. {
  17225. #ifndef WOLFSSL_ASN_TEMPLATE
  17226. word32 idx = 0;
  17227. int length = 0;
  17228. int ret;
  17229. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  17230. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  17231. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  17232. return ASN_PARSE_E;
  17233. }
  17234. if (length == 0)
  17235. return 0;
  17236. /* If the basic ca constraint is false, this extension may be named, but
  17237. * left empty. So, if the length is 0, just return. */
  17238. ret = GetBoolean(input, &idx, (word32)sz);
  17239. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  17240. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  17241. * When CA Boolean not asserted use the default value "False" */
  17242. if (ret < 0) {
  17243. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  17244. ret = 0;
  17245. }
  17246. cert->isCA = ret ? 1 : 0;
  17247. /* If there isn't any more data, return. */
  17248. if (idx >= (word32)sz) {
  17249. return 0;
  17250. }
  17251. ret = GetInteger7Bit(input, &idx, (word32)sz);
  17252. if (ret < 0)
  17253. return ret;
  17254. cert->pathLength = (byte)ret;
  17255. cert->pathLengthSet = 1;
  17256. return 0;
  17257. #else
  17258. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  17259. int ret = 0;
  17260. word32 idx = 0;
  17261. byte isCA = 0;
  17262. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  17263. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  17264. if (ret == 0) {
  17265. /* Get the CA boolean and path length when present. */
  17266. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  17267. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  17268. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  17269. &idx, (word32)sz);
  17270. }
  17271. /* Empty SEQUENCE is OK - nothing to store. */
  17272. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  17273. /* Bad encoding when CA Boolean is false
  17274. * (default when not present). */
  17275. #if !defined(ASN_TEMPLATE_SKIP_ISCA_CHECK) && \
  17276. !defined(WOLFSSL_ALLOW_ENCODING_CA_FALSE)
  17277. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  17278. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17279. ret = ASN_PARSE_E;
  17280. }
  17281. #endif
  17282. /* Path length must be a 7-bit value. */
  17283. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  17284. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17285. ret = ASN_PARSE_E;
  17286. }
  17287. if ((ret == 0) && cert->pathLength > WOLFSSL_MAX_PATH_LEN) {
  17288. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_SIZE_E);
  17289. ret = ASN_PATHLEN_SIZE_E;
  17290. }
  17291. /* Store CA boolean and whether a path length was seen. */
  17292. if (ret == 0) {
  17293. /* isCA in certificate is a 1 bit of a byte. */
  17294. cert->isCA = isCA ? 1 : 0;
  17295. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  17296. }
  17297. }
  17298. FREE_ASNGETDATA(dataASN, cert->heap);
  17299. return ret;
  17300. #endif
  17301. }
  17302. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  17303. {
  17304. word32 idx = 0;
  17305. int length = 0;
  17306. int skipLength = 0;
  17307. int ret;
  17308. byte tag;
  17309. WOLFSSL_ENTER("DecodePolicyConstraints");
  17310. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  17311. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  17312. return ASN_PARSE_E;
  17313. }
  17314. if (length == 0)
  17315. return ASN_PARSE_E;
  17316. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  17317. WOLFSSL_MSG("\tfail: bad TAG");
  17318. return ASN_PARSE_E;
  17319. }
  17320. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  17321. /* requireExplicitPolicy */
  17322. cert->extPolicyConstRxpSet = 1;
  17323. }
  17324. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  17325. /* inhibitPolicyMapping */
  17326. cert->extPolicyConstIpmSet = 1;
  17327. }
  17328. else {
  17329. WOLFSSL_MSG("\tfail: invalid TAG");
  17330. return ASN_PARSE_E;
  17331. }
  17332. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  17333. if (ret < 0) {
  17334. WOLFSSL_MSG("\tfail: invalid length");
  17335. return ret;
  17336. }
  17337. if (skipLength > 1) {
  17338. WOLFSSL_MSG("\tfail: skip value too big");
  17339. return BUFFER_E;
  17340. }
  17341. if (idx >= (word32)sz) {
  17342. WOLFSSL_MSG("\tfail: no policy const skip to read");
  17343. return BUFFER_E;
  17344. }
  17345. cert->policyConstSkip = input[idx];
  17346. return 0;
  17347. }
  17348. /* Context-Specific value for: DistributionPoint.distributionPoint
  17349. * From RFC5280 SS4.2.1.13, Distribution Point */
  17350. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  17351. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  17352. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  17353. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  17354. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  17355. * From RFC3280 SS4.2.1.7, GeneralName */
  17356. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  17357. #ifdef WOLFSSL_ASN_TEMPLATE
  17358. /* ASN.1 template for CRL distribution points.
  17359. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  17360. */
  17361. static const ASNItem crlDistASN[] = {
  17362. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17363. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17364. /* Distribution point name */
  17365. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  17366. /* fullName */
  17367. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  17368. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  17369. /* nameRelativeToCRLIssuer */
  17370. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  17371. /* reasons: IMPLICIT BIT STRING */
  17372. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17373. /* cRLIssuer */
  17374. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  17375. };
  17376. enum {
  17377. CRLDISTASN_IDX_SEQ = 0,
  17378. CRLDISTASN_IDX_DP_SEQ,
  17379. CRLDISTASN_IDX_DP_DISTPOINT,
  17380. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  17381. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  17382. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  17383. CRLDISTASN_IDX_DP_REASONS,
  17384. CRLDISTASN_IDX_DP_CRLISSUER
  17385. };
  17386. /* Number of items in ASN.1 template for CRL distribution points. */
  17387. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  17388. #endif
  17389. /* Decode CRL distribution point extension in a certificate.
  17390. *
  17391. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  17392. *
  17393. * @param [in] input Buffer holding data.
  17394. * @param [in] sz Size of data in buffer.
  17395. * @param [in, out] cert Certificate object.
  17396. * @return 0 on success.
  17397. * @return MEMORY_E on dynamic memory allocation failure.
  17398. * @return ASN_PARSE_E when invalid bits of reason are set.
  17399. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  17400. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  17401. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17402. * is invalid.
  17403. * @return BUFFER_E when data in buffer is too small.
  17404. */
  17405. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  17406. {
  17407. #ifndef WOLFSSL_ASN_TEMPLATE
  17408. word32 idx = 0, localIdx;
  17409. int length = 0;
  17410. byte tag = 0;
  17411. WOLFSSL_ENTER("DecodeCrlDist");
  17412. cert->extCrlInfoRaw = input;
  17413. cert->extCrlInfoRawSz = (int)sz;
  17414. /* Unwrap the list of Distribution Points*/
  17415. if (GetSequence(input, &idx, &length, sz) < 0)
  17416. return ASN_PARSE_E;
  17417. /* Unwrap a single Distribution Point */
  17418. if (GetSequence(input, &idx, &length, sz) < 0)
  17419. return ASN_PARSE_E;
  17420. /* The Distribution Point has three explicit optional members
  17421. * First check for a DistributionPointName
  17422. */
  17423. localIdx = idx;
  17424. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17425. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  17426. {
  17427. idx++;
  17428. if (GetLength(input, &idx, &length, sz) < 0)
  17429. return ASN_PARSE_E;
  17430. localIdx = idx;
  17431. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17432. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  17433. {
  17434. idx++;
  17435. if (GetLength(input, &idx, &length, sz) < 0)
  17436. return ASN_PARSE_E;
  17437. localIdx = idx;
  17438. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17439. tag == GENERALNAME_URI)
  17440. {
  17441. idx++;
  17442. if (GetLength(input, &idx, &length, sz) < 0)
  17443. return ASN_PARSE_E;
  17444. cert->extCrlInfoSz = length;
  17445. cert->extCrlInfo = input + idx;
  17446. idx += (word32)length;
  17447. }
  17448. else
  17449. /* This isn't a URI, skip it. */
  17450. idx += (word32)length;
  17451. }
  17452. else {
  17453. /* This isn't a FULLNAME, skip it. */
  17454. idx += (word32)length;
  17455. }
  17456. }
  17457. /* Check for reasonFlags */
  17458. localIdx = idx;
  17459. if (idx < (word32)sz &&
  17460. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17461. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  17462. {
  17463. idx++;
  17464. if (GetLength(input, &idx, &length, sz) < 0)
  17465. return ASN_PARSE_E;
  17466. idx += (word32)length;
  17467. }
  17468. /* Check for cRLIssuer */
  17469. localIdx = idx;
  17470. if (idx < (word32)sz &&
  17471. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17472. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  17473. {
  17474. idx++;
  17475. if (GetLength(input, &idx, &length, sz) < 0)
  17476. return ASN_PARSE_E;
  17477. idx += (word32)length;
  17478. }
  17479. if (idx < (word32)sz)
  17480. {
  17481. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  17482. "but we only use the first one.");
  17483. }
  17484. return 0;
  17485. #else
  17486. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  17487. word32 idx = 0;
  17488. int ret = 0;
  17489. #ifdef CRLDP_VALIDATE_DATA
  17490. word16 reason;
  17491. #endif
  17492. WOLFSSL_ENTER("DecodeCrlDist");
  17493. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  17494. cert->extCrlInfoRaw = input;
  17495. cert->extCrlInfoRawSz = (int)sz;
  17496. if (ret == 0) {
  17497. /* Get the GeneralName choice */
  17498. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  17499. /* Parse CRL distribution point. */
  17500. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  17501. &idx, sz);
  17502. }
  17503. if (ret == 0) {
  17504. /* If the choice was a URI, store it in certificate. */
  17505. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  17506. word32 sz32;
  17507. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  17508. &cert->extCrlInfo, &sz32);
  17509. cert->extCrlInfoSz = (int)sz32;
  17510. }
  17511. #ifdef CRLDP_VALIDATE_DATA
  17512. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  17513. /* TODO: test case */
  17514. /* Validate ReasonFlags. */
  17515. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  17516. &reason);
  17517. /* First bit (LSB) unused and eight other bits defined. */
  17518. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  17519. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17520. ret = ASN_PARSE_E;
  17521. }
  17522. }
  17523. #endif
  17524. }
  17525. /* Only parsing the first one. */
  17526. if (ret == 0 && idx < (word32)sz) {
  17527. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  17528. "but we only use the first one.");
  17529. }
  17530. /* TODO: validate other points. */
  17531. FREE_ASNGETDATA(dataASN, cert->heap);
  17532. return ret;
  17533. #endif /* WOLFSSL_ASN_TEMPLATE */
  17534. }
  17535. #ifdef WOLFSSL_ASN_TEMPLATE
  17536. /* ASN.1 template for the access description.
  17537. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17538. */
  17539. static const ASNItem accessDescASN[] = {
  17540. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17541. /* accessMethod */
  17542. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17543. /* accessLocation: GeneralName */
  17544. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  17545. };
  17546. enum {
  17547. ACCESSDESCASN_IDX_SEQ = 0,
  17548. ACCESSDESCASN_IDX_METH,
  17549. ACCESSDESCASN_IDX_LOC
  17550. };
  17551. /* Number of items in ASN.1 template for the access description. */
  17552. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  17553. #endif
  17554. /* Decode authority information access extension in a certificate.
  17555. *
  17556. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17557. *
  17558. * @param [in] input Buffer holding data.
  17559. * @param [in] sz Size of data in buffer.
  17560. * @param [in, out] cert Certificate object.
  17561. * @return 0 on success.
  17562. * @return MEMORY_E on dynamic memory allocation failure.
  17563. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17564. * is invalid.
  17565. * @return BUFFER_E when data in buffer is too small.
  17566. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  17567. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  17568. */
  17569. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  17570. {
  17571. #ifndef WOLFSSL_ASN_TEMPLATE
  17572. word32 idx = 0;
  17573. int length = 0;
  17574. byte b = 0;
  17575. word32 oid;
  17576. WOLFSSL_ENTER("DecodeAuthInfo");
  17577. /* Unwrap the list of AIAs */
  17578. if (GetSequence(input, &idx, &length, sz) < 0)
  17579. return ASN_PARSE_E;
  17580. while ((idx < (word32)sz)) {
  17581. /* Unwrap a single AIA */
  17582. if (GetSequence(input, &idx, &length, sz) < 0)
  17583. return ASN_PARSE_E;
  17584. oid = 0;
  17585. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  17586. return ASN_PARSE_E;
  17587. }
  17588. /* Only supporting URIs right now. */
  17589. if (GetASNTag(input, &idx, &b, sz) < 0)
  17590. return ASN_PARSE_E;
  17591. if (GetLength(input, &idx, &length, sz) < 0)
  17592. return ASN_PARSE_E;
  17593. /* Set ocsp entry */
  17594. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID &&
  17595. cert->extAuthInfo == NULL)
  17596. {
  17597. cert->extAuthInfoSz = length;
  17598. cert->extAuthInfo = input + idx;
  17599. #if !defined(OPENSSL_ALL) && !defined(WOLFSSL_QT)
  17600. break;
  17601. #endif
  17602. }
  17603. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17604. /* Set CaIssuers entry */
  17605. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID &&
  17606. cert->extAuthInfoCaIssuer == NULL)
  17607. {
  17608. cert->extAuthInfoCaIssuerSz = length;
  17609. cert->extAuthInfoCaIssuer = input + idx;
  17610. }
  17611. #endif
  17612. idx += (word32)length;
  17613. }
  17614. return 0;
  17615. #else
  17616. word32 idx = 0;
  17617. int length = 0;
  17618. int ret = 0;
  17619. WOLFSSL_ENTER("DecodeAuthInfo");
  17620. /* Unwrap the list of AIAs */
  17621. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17622. ret = ASN_PARSE_E;
  17623. }
  17624. while ((ret == 0) && (idx < (word32)sz)) {
  17625. ASNGetData dataASN[accessDescASN_Length];
  17626. /* Clear dynamic data and retrieve OID and name. */
  17627. XMEMSET(dataASN, 0, sizeof(dataASN));
  17628. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  17629. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  17630. /* Parse AccessDescription. */
  17631. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  17632. input, &idx, sz);
  17633. if (ret == 0) {
  17634. word32 sz32;
  17635. /* Check we have OCSP and URI. */
  17636. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  17637. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI) &&
  17638. (cert->extAuthInfo == NULL)) {
  17639. /* Store URI for OCSP lookup. */
  17640. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17641. &cert->extAuthInfo, &sz32);
  17642. cert->extAuthInfoSz = (int)sz32;
  17643. #if !defined(OPENSSL_ALL) && !defined(WOLFSSL_QT)
  17644. break;
  17645. #endif
  17646. }
  17647. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17648. /* Check we have CA Issuer and URI. */
  17649. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  17650. AIA_CA_ISSUER_OID) &&
  17651. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI) &&
  17652. (cert->extAuthInfoCaIssuer == NULL)) {
  17653. /* Set CaIssuers entry */
  17654. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17655. &cert->extAuthInfoCaIssuer, &sz32);
  17656. cert->extAuthInfoCaIssuerSz = (int)sz32;
  17657. }
  17658. #endif
  17659. /* Otherwise skip. */
  17660. }
  17661. }
  17662. return ret;
  17663. #endif
  17664. }
  17665. #ifdef WOLFSSL_ASN_TEMPLATE
  17666. /* ASN.1 template for AuthorityKeyIdentifier.
  17667. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  17668. */
  17669. static const ASNItem authKeyIdASN[] = {
  17670. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17671. /* keyIdentifier */
  17672. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  17673. /* authorityCertIssuer */
  17674. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  17675. /* authorityCertSerialNumber */
  17676. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  17677. };
  17678. enum {
  17679. AUTHKEYIDASN_IDX_SEQ = 0,
  17680. AUTHKEYIDASN_IDX_KEYID,
  17681. AUTHKEYIDASN_IDX_ISSUER,
  17682. AUTHKEYIDASN_IDX_SERIAL
  17683. };
  17684. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  17685. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  17686. #endif
  17687. /* Decode authority key identifier extension in a certificate.
  17688. *
  17689. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  17690. *
  17691. * @param [in] input Buffer holding data.
  17692. * @param [in] sz Size of data in buffer.
  17693. * @param [in, out] cert Certificate object.
  17694. * @return 0 on success.
  17695. * @return MEMORY_E on dynamic memory allocation failure.
  17696. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17697. * is invalid.
  17698. * @return BUFFER_E when data in buffer is too small.
  17699. */
  17700. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17701. {
  17702. #ifndef WOLFSSL_ASN_TEMPLATE
  17703. word32 idx = 0;
  17704. int length = 0;
  17705. byte tag;
  17706. WOLFSSL_ENTER("DecodeAuthKeyId");
  17707. if (GetSequence(input, &idx, &length, sz) < 0) {
  17708. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17709. return ASN_PARSE_E;
  17710. }
  17711. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  17712. return ASN_PARSE_E;
  17713. }
  17714. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  17715. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  17716. cert->extAuthKeyIdSet = 0;
  17717. return 0;
  17718. }
  17719. if (GetLength(input, &idx, &length, sz) <= 0) {
  17720. WOLFSSL_MSG("\tfail: extension data length");
  17721. return ASN_PARSE_E;
  17722. }
  17723. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17724. #ifdef WOLFSSL_AKID_NAME
  17725. cert->extRawAuthKeyIdSrc = input;
  17726. cert->extRawAuthKeyIdSz = sz;
  17727. #endif
  17728. cert->extAuthKeyIdSrc = &input[idx];
  17729. cert->extAuthKeyIdSz = length;
  17730. #endif /* OPENSSL_EXTRA */
  17731. return GetHashId(input + idx, length, cert->extAuthKeyId,
  17732. HashIdAlg(cert->signatureOID));
  17733. #else
  17734. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  17735. int ret = 0;
  17736. WOLFSSL_ENTER("DecodeAuthKeyId");
  17737. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  17738. if (ret == 0) {
  17739. /* Parse an authority key identifier. */
  17740. word32 idx = 0;
  17741. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  17742. &idx, sz);
  17743. }
  17744. /* Each field is optional */
  17745. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data != NULL) {
  17746. #ifdef OPENSSL_EXTRA
  17747. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID],
  17748. &cert->extAuthKeyIdSrc, &cert->extAuthKeyIdSz);
  17749. #endif /* OPENSSL_EXTRA */
  17750. /* Get the hash or hash of the hash if wrong size. */
  17751. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  17752. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  17753. cert->extAuthKeyId, HashIdAlg(cert->signatureOID));
  17754. }
  17755. #ifdef WOLFSSL_AKID_NAME
  17756. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.data != NULL) {
  17757. /* We only support using one (first) name. Parse the name to perform
  17758. * a sanity check. */
  17759. word32 idx = 0;
  17760. ASNGetData nameASN[altNameASN_Length];
  17761. XMEMSET(nameASN, 0, sizeof(nameASN));
  17762. /* Parse GeneralName with the choices supported. */
  17763. GetASN_Choice(&nameASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  17764. /* Decode a GeneralName choice. */
  17765. ret = GetASN_Items(altNameASN, nameASN, altNameASN_Length, 0,
  17766. dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.data, &idx,
  17767. dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.length);
  17768. if (ret == 0) {
  17769. GetASN_GetConstRef(&nameASN[ALTNAMEASN_IDX_GN],
  17770. &cert->extAuthKeyIdIssuer, &cert->extAuthKeyIdIssuerSz);
  17771. }
  17772. }
  17773. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_SERIAL].data.ref.data != NULL) {
  17774. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_SERIAL],
  17775. &cert->extAuthKeyIdIssuerSN, &cert->extAuthKeyIdIssuerSNSz);
  17776. }
  17777. if (ret == 0) {
  17778. if ((cert->extAuthKeyIdIssuerSz > 0) ^
  17779. (cert->extAuthKeyIdIssuerSNSz > 0)) {
  17780. WOLFSSL_MSG("authorityCertIssuer and authorityCertSerialNumber MUST"
  17781. " both be present or both be absent");
  17782. }
  17783. }
  17784. #endif /* WOLFSSL_AKID_NAME */
  17785. if (ret == 0) {
  17786. #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_AKID_NAME)
  17787. /* Store the raw authority key id. */
  17788. cert->extRawAuthKeyIdSrc = input;
  17789. cert->extRawAuthKeyIdSz = sz;
  17790. #endif /* OPENSSL_EXTRA */
  17791. }
  17792. FREE_ASNGETDATA(dataASN, cert->heap);
  17793. return ret;
  17794. #endif /* WOLFSSL_ASN_TEMPLATE */
  17795. }
  17796. /* Decode subject key id extension in a certificate.
  17797. *
  17798. * X.509: RFC 5280, 4.2.1.2 - Subject Key Identifier.
  17799. *
  17800. * @param [in] input Buffer holding data.
  17801. * @param [in] sz Size of data in buffer.
  17802. * @param [in, out] cert Certificate object.
  17803. * @return 0 on success.
  17804. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  17805. * invalid.
  17806. * @return MEMORY_E on dynamic memory allocation failure.
  17807. */
  17808. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17809. {
  17810. word32 idx = 0;
  17811. int length = 0;
  17812. int ret = 0;
  17813. WOLFSSL_ENTER("DecodeSubjKeyId");
  17814. ret = GetOctetString(input, &idx, &length, sz);
  17815. if (ret > 0) {
  17816. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17817. cert->extSubjKeyIdSrc = &input[idx];
  17818. cert->extSubjKeyIdSz = (word32)length;
  17819. #endif /* OPENSSL_EXTRA */
  17820. /* Get the hash or hash of the hash if wrong size. */
  17821. ret = GetHashId(input + idx, length, cert->extSubjKeyId,
  17822. HashIdAlg(cert->signatureOID));
  17823. }
  17824. return ret;
  17825. }
  17826. #ifdef WOLFSSL_ASN_TEMPLATE
  17827. /* ASN.1 template for KeyUsage.
  17828. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17829. */
  17830. static const ASNItem keyUsageASN[] = {
  17831. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  17832. };
  17833. enum {
  17834. KEYUSAGEASN_IDX_STR = 0
  17835. };
  17836. /* Number of items in ASN.1 template for KeyUsage. */
  17837. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  17838. #endif
  17839. /* Decode key usage extension in a certificate.
  17840. *
  17841. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17842. *
  17843. * @param [in] input Buffer holding data.
  17844. * @param [in] sz Size of data in buffer.
  17845. * @param [in, out] cert Certificate object.
  17846. * @return 0 on success.
  17847. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17848. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17849. * is invalid.
  17850. * @return MEMORY_E on dynamic memory allocation failure.
  17851. */
  17852. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17853. {
  17854. #ifndef WOLFSSL_ASN_TEMPLATE
  17855. word32 idx = 0;
  17856. int length;
  17857. int ret;
  17858. WOLFSSL_ENTER("DecodeKeyUsage");
  17859. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  17860. if (ret != 0)
  17861. return ret;
  17862. if (length == 0 || length > 2)
  17863. return ASN_PARSE_E;
  17864. cert->extKeyUsage = (word16)(input[idx]);
  17865. if (length == 2)
  17866. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  17867. return 0;
  17868. #else
  17869. ASNGetData dataASN[keyUsageASN_Length];
  17870. word32 idx = 0;
  17871. byte keyUsage[2];
  17872. word32 keyUsageSz = sizeof(keyUsage);
  17873. int ret;
  17874. WOLFSSL_ENTER("DecodeKeyUsage");
  17875. /* Clear dynamic data and set where to store extended key usage. */
  17876. XMEMSET(dataASN, 0, sizeof(dataASN));
  17877. XMEMSET(keyUsage, 0, sizeof(keyUsage));
  17878. GetASN_Buffer(&dataASN[KEYUSAGEASN_IDX_STR], keyUsage, &keyUsageSz);
  17879. /* Parse key usage. */
  17880. ret = GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  17881. &idx, sz);
  17882. if (ret == 0) {
  17883. /* Decode the bit string number as LE */
  17884. cert->extKeyUsage = (word16)(keyUsage[0]);
  17885. if (keyUsageSz == 2)
  17886. cert->extKeyUsage |= (word16)(keyUsage[1] << 8);
  17887. }
  17888. return ret;
  17889. #endif /* WOLFSSL_ASN_TEMPLATE */
  17890. }
  17891. #ifdef WOLFSSL_ASN_TEMPLATE
  17892. /* ASN.1 template for KeyPurposeId.
  17893. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17894. */
  17895. static const ASNItem keyPurposeIdASN[] = {
  17896. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  17897. };
  17898. enum {
  17899. KEYPURPOSEIDASN_IDX_OID = 0
  17900. };
  17901. /* Number of items in ASN.1 template for KeyPurposeId. */
  17902. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  17903. #endif
  17904. /* Decode extended key usage extension in a certificate.
  17905. *
  17906. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17907. *
  17908. * @param [in] input Buffer holding data.
  17909. * @param [in] sz Size of data in buffer.
  17910. * @param [in, out] cert Certificate object.
  17911. * @return 0 on success.
  17912. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17913. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17914. * is invalid.
  17915. * @return MEMORY_E on dynamic memory allocation failure.
  17916. */
  17917. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17918. {
  17919. #ifndef WOLFSSL_ASN_TEMPLATE
  17920. word32 idx = 0, oid;
  17921. int length, ret;
  17922. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17923. if (GetSequence(input, &idx, &length, sz) < 0) {
  17924. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17925. return ASN_PARSE_E;
  17926. }
  17927. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17928. cert->extExtKeyUsageSrc = input + idx;
  17929. cert->extExtKeyUsageSz = length;
  17930. #endif
  17931. while (idx < (word32)sz) {
  17932. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  17933. if (ret == ASN_UNKNOWN_OID_E)
  17934. continue;
  17935. else if (ret < 0)
  17936. return ret;
  17937. switch (oid) {
  17938. case EKU_ANY_OID:
  17939. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17940. break;
  17941. case EKU_SERVER_AUTH_OID:
  17942. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17943. break;
  17944. case EKU_CLIENT_AUTH_OID:
  17945. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17946. break;
  17947. case EKU_CODESIGNING_OID:
  17948. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17949. break;
  17950. case EKU_EMAILPROTECT_OID:
  17951. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17952. break;
  17953. case EKU_TIMESTAMP_OID:
  17954. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17955. break;
  17956. case EKU_OCSP_SIGN_OID:
  17957. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17958. break;
  17959. #ifdef WOLFSSL_WOLFSSH
  17960. case EKU_SSH_CLIENT_AUTH_OID:
  17961. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  17962. break;
  17963. case EKU_SSH_MSCL_OID:
  17964. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  17965. break;
  17966. case EKU_SSH_KP_CLIENT_AUTH_OID:
  17967. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  17968. break;
  17969. #endif /* WOLFSSL_WOLFSSH */
  17970. default:
  17971. break;
  17972. }
  17973. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17974. cert->extExtKeyUsageCount++;
  17975. #endif
  17976. }
  17977. return 0;
  17978. #else
  17979. word32 idx = 0;
  17980. int length;
  17981. int ret = 0;
  17982. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17983. /* Strip SEQUENCE OF and expect to account for all the data. */
  17984. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17985. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17986. ret = ASN_PARSE_E;
  17987. }
  17988. if (ret == 0) {
  17989. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17990. /* Keep reference for WOLFSSL_X509. */
  17991. cert->extExtKeyUsageSrc = input + idx;
  17992. cert->extExtKeyUsageSz = (word32)length;
  17993. #endif
  17994. }
  17995. /* Check all OIDs. */
  17996. while ((ret == 0) && (idx < (word32)sz)) {
  17997. ASNGetData dataASN[keyPurposeIdASN_Length];
  17998. /* Clear dynamic data items and set OID type expected. */
  17999. XMEMSET(dataASN, 0, sizeof(dataASN));
  18000. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  18001. /* Decode KeyPurposeId. */
  18002. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  18003. input, &idx, sz);
  18004. /* Skip unknown OIDs. */
  18005. if (ret == ASN_UNKNOWN_OID_E) {
  18006. ret = 0;
  18007. }
  18008. else if (ret == 0) {
  18009. /* Store the bit for the OID. */
  18010. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  18011. case EKU_ANY_OID:
  18012. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  18013. break;
  18014. case EKU_SERVER_AUTH_OID:
  18015. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  18016. break;
  18017. case EKU_CLIENT_AUTH_OID:
  18018. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  18019. break;
  18020. case EKU_CODESIGNING_OID:
  18021. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  18022. break;
  18023. case EKU_EMAILPROTECT_OID:
  18024. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  18025. break;
  18026. case EKU_TIMESTAMP_OID:
  18027. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  18028. break;
  18029. case EKU_OCSP_SIGN_OID:
  18030. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  18031. break;
  18032. }
  18033. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  18034. /* Keep count for WOLFSSL_X509. */
  18035. cert->extExtKeyUsageCount++;
  18036. #endif
  18037. }
  18038. }
  18039. return ret;
  18040. #endif /* WOLFSSL_ASN_TEMPLATE */
  18041. }
  18042. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18043. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  18044. {
  18045. word32 idx = 0;
  18046. int len = 0;
  18047. WOLFSSL_ENTER("DecodeNsCertType");
  18048. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  18049. return ASN_PARSE_E;
  18050. /* Don't need to worry about unused bits as CheckBitString makes sure
  18051. * they're zero. */
  18052. if (idx < (word32)sz)
  18053. cert->nsCertType = input[idx];
  18054. else
  18055. return ASN_PARSE_E;
  18056. return 0;
  18057. }
  18058. #endif
  18059. #ifndef IGNORE_NAME_CONSTRAINTS
  18060. #ifdef WOLFSSL_ASN_TEMPLATE
  18061. /* ASN.1 template for GeneralSubtree.
  18062. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  18063. */
  18064. static const ASNItem subTreeASN[] = {
  18065. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18066. /* base GeneralName */
  18067. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  18068. /* minimum BaseDistance DEFAULT 0*/
  18069. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  18070. /* maximum BaseDistance OPTIONAL */
  18071. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  18072. };
  18073. enum {
  18074. SUBTREEASN_IDX_SEQ = 0,
  18075. SUBTREEASN_IDX_BASE,
  18076. SUBTREEASN_IDX_MIN,
  18077. SUBTREEASN_IDX_MAX
  18078. };
  18079. /* Number of items in ASN.1 template for GeneralSubtree. */
  18080. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  18081. #endif
  18082. #ifdef WOLFSSL_ASN_TEMPLATE
  18083. /* Decode the Subtree's GeneralName.
  18084. *
  18085. * @param [in] input Buffer holding data.
  18086. * @param [in] sz Size of data in buffer.
  18087. * @param [in] tag BER tag on GeneralName.
  18088. * @param [in, out] head Linked list of subtree names.
  18089. * @param [in] heap Dynamic memory hint.
  18090. * @return 0 on success.
  18091. * @return MEMORY_E when dynamic memory allocation fails.
  18092. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  18093. */
  18094. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  18095. Base_entry** head, void* heap)
  18096. {
  18097. Base_entry* entry = NULL;
  18098. word32 nameIdx = 0;
  18099. word32 len = sz;
  18100. int strLen;
  18101. int ret = 0;
  18102. (void)heap;
  18103. /* if constructed has leading sequence */
  18104. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  18105. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  18106. if (ret < 0) {
  18107. ret = ASN_PARSE_E;
  18108. }
  18109. else {
  18110. len = (word32)strLen;
  18111. ret = 0;
  18112. }
  18113. }
  18114. if (ret == 0) {
  18115. /* TODO: consider one malloc. */
  18116. /* Allocate Base Entry object. */
  18117. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  18118. DYNAMIC_TYPE_ALTNAME);
  18119. if (entry == NULL) {
  18120. ret = MEMORY_E;
  18121. }
  18122. }
  18123. if (ret == 0) {
  18124. /* Allocate name. */
  18125. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  18126. if (entry->name == NULL) {
  18127. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  18128. ret = MEMORY_E;
  18129. }
  18130. }
  18131. if (ret == 0) {
  18132. /* Store name, size and tag in object. */
  18133. XMEMCPY(entry->name, &input[nameIdx], len);
  18134. entry->name[len] = '\0';
  18135. entry->nameSz = (int)len;
  18136. entry->type = tag & ASN_TYPE_MASK;
  18137. /* Put entry at front of linked list. */
  18138. entry->next = *head;
  18139. *head = entry;
  18140. }
  18141. return ret;
  18142. }
  18143. #endif
  18144. /* Decode a subtree of a name constraints in a certificate.
  18145. *
  18146. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  18147. *
  18148. * @param [in] input Buffer holding data.
  18149. * @param [in] sz Size of data in buffer.
  18150. * @param [in, out] head Linked list of subtree names.
  18151. * @param [in] heap Dynamic memory hint.
  18152. * @return 0 on success.
  18153. * @return MEMORY_E when dynamic memory allocation fails.
  18154. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  18155. */
  18156. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  18157. void* heap)
  18158. {
  18159. #ifndef WOLFSSL_ASN_TEMPLATE
  18160. word32 idx = 0;
  18161. int ret = 0;
  18162. (void)heap;
  18163. while (idx < (word32)sz) {
  18164. int seqLength, strLength;
  18165. word32 nameIdx;
  18166. byte b, bType;
  18167. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  18168. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18169. return ASN_PARSE_E;
  18170. }
  18171. if (idx >= (word32)sz) {
  18172. WOLFSSL_MSG("\tfail: expecting tag");
  18173. return ASN_PARSE_E;
  18174. }
  18175. nameIdx = idx;
  18176. b = input[nameIdx++];
  18177. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  18178. WOLFSSL_MSG("\tinvalid length");
  18179. return ASN_PARSE_E;
  18180. }
  18181. /* Get type, LSB 4-bits */
  18182. bType = (byte)(b & ASN_TYPE_MASK);
  18183. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  18184. bType == ASN_DIR_TYPE) {
  18185. Base_entry* entry;
  18186. /* if constructed has leading sequence */
  18187. if (b & ASN_CONSTRUCTED) {
  18188. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  18189. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  18190. return ASN_PARSE_E;
  18191. }
  18192. }
  18193. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  18194. DYNAMIC_TYPE_ALTNAME);
  18195. if (entry == NULL) {
  18196. WOLFSSL_MSG("allocate error");
  18197. return MEMORY_E;
  18198. }
  18199. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  18200. DYNAMIC_TYPE_ALTNAME);
  18201. if (entry->name == NULL) {
  18202. WOLFSSL_MSG("allocate error");
  18203. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  18204. return MEMORY_E;
  18205. }
  18206. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  18207. entry->name[strLength] = '\0';
  18208. entry->nameSz = strLength;
  18209. entry->type = bType;
  18210. entry->next = *head;
  18211. *head = entry;
  18212. }
  18213. idx += (word32)seqLength;
  18214. }
  18215. return ret;
  18216. #else
  18217. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  18218. word32 idx = 0;
  18219. int ret = 0;
  18220. (void)heap;
  18221. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  18222. /* Process all subtrees. */
  18223. while ((ret == 0) && (idx < (word32)sz)) {
  18224. byte minVal = 0;
  18225. byte maxVal = 0;
  18226. /* Clear dynamic data and set choice for GeneralName and location to
  18227. * store minimum and maximum.
  18228. */
  18229. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  18230. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  18231. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  18232. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  18233. /* Parse GeneralSubtree. */
  18234. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  18235. &idx, sz);
  18236. if (ret == 0) {
  18237. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  18238. /* Check GeneralName tag is one of the types we can handle. */
  18239. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  18240. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  18241. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  18242. /* Parse the general name and store a new entry. */
  18243. ret = DecodeSubtreeGeneralName(input +
  18244. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  18245. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  18246. }
  18247. /* Skip entry. */
  18248. }
  18249. }
  18250. FREE_ASNGETDATA(dataASN, heap);
  18251. return ret;
  18252. #endif
  18253. }
  18254. #ifdef WOLFSSL_ASN_TEMPLATE
  18255. /* ASN.1 template for NameConstraints.
  18256. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  18257. */
  18258. static const ASNItem nameConstraintsASN[] = {
  18259. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18260. /* permittedSubtrees */
  18261. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  18262. /* excludededSubtrees */
  18263. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  18264. };
  18265. enum {
  18266. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  18267. NAMECONSTRAINTSASN_IDX_PERMIT,
  18268. NAMECONSTRAINTSASN_IDX_EXCLUDE
  18269. };
  18270. /* Number of items in ASN.1 template for NameConstraints. */
  18271. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  18272. #endif
  18273. /* Decode name constraints extension in a certificate.
  18274. *
  18275. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  18276. *
  18277. * @param [in] input Buffer holding data.
  18278. * @param [in] sz Size of data in buffer.
  18279. * @param [in, out] cert Certificate object.
  18280. * @return 0 on success.
  18281. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18282. * is invalid.
  18283. * @return MEMORY_E on dynamic memory allocation failure.
  18284. */
  18285. static int DecodeNameConstraints(const byte* input, word32 sz,
  18286. DecodedCert* cert)
  18287. {
  18288. #ifndef WOLFSSL_ASN_TEMPLATE
  18289. word32 idx = 0;
  18290. int length = 0;
  18291. WOLFSSL_ENTER("DecodeNameConstraints");
  18292. if (GetSequence(input, &idx, &length, sz) < 0) {
  18293. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18294. return ASN_PARSE_E;
  18295. }
  18296. while (idx < (word32)sz) {
  18297. byte b = input[idx++];
  18298. Base_entry** subtree = NULL;
  18299. if (GetLength(input, &idx, &length, sz) <= 0) {
  18300. WOLFSSL_MSG("\tinvalid length");
  18301. return ASN_PARSE_E;
  18302. }
  18303. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  18304. subtree = &cert->permittedNames;
  18305. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  18306. subtree = &cert->excludedNames;
  18307. else {
  18308. WOLFSSL_MSG("\tinvalid subtree");
  18309. return ASN_PARSE_E;
  18310. }
  18311. if (DecodeSubtree(input + idx, (word32)length, subtree,
  18312. cert->heap) < 0) {
  18313. WOLFSSL_MSG("\terror parsing subtree");
  18314. return ASN_PARSE_E;
  18315. }
  18316. idx += (word32)length;
  18317. }
  18318. return 0;
  18319. #else
  18320. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  18321. word32 idx = 0;
  18322. int ret = 0;
  18323. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  18324. if (ret == 0) {
  18325. /* Parse NameConstraints. */
  18326. ret = GetASN_Items(nameConstraintsASN, dataASN,
  18327. nameConstraintsASN_Length, 1, input, &idx, sz);
  18328. }
  18329. if (ret == 0) {
  18330. /* If there was a permittedSubtrees then parse it. */
  18331. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  18332. ret = DecodeSubtree(
  18333. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  18334. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  18335. &cert->permittedNames, cert->heap);
  18336. }
  18337. }
  18338. if (ret == 0) {
  18339. /* If there was a excludedSubtrees then parse it. */
  18340. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  18341. ret = DecodeSubtree(
  18342. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  18343. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  18344. &cert->excludedNames, cert->heap);
  18345. }
  18346. }
  18347. FREE_ASNGETDATA(dataASN, cert->heap);
  18348. return ret;
  18349. #endif /* WOLFSSL_ASN_TEMPLATE */
  18350. }
  18351. #endif /* IGNORE_NAME_CONSTRAINTS */
  18352. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  18353. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  18354. /* Decode ITU-T X.690 OID format to a string representation
  18355. * return string length */
  18356. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  18357. {
  18358. word32 val, inIdx = 0, outIdx = 0;
  18359. int w = 0;
  18360. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  18361. return BAD_FUNC_ARG;
  18362. /* The first byte expands into b/40 dot b%40. */
  18363. val = in[inIdx++];
  18364. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  18365. if (w < 0) {
  18366. w = BUFFER_E;
  18367. goto exit;
  18368. }
  18369. outIdx += (word32)w;
  18370. val = 0;
  18371. while (inIdx < inSz && outIdx < outSz) {
  18372. /* extract the next OID digit from in to val */
  18373. /* first bit is used to set if value is coded on 1 or multiple bytes */
  18374. if (in[inIdx] & 0x80) {
  18375. val += in[inIdx] & 0x7F;
  18376. val *= 128;
  18377. }
  18378. else {
  18379. /* write val as text into out */
  18380. val += in[inIdx];
  18381. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  18382. if (w < 0 || (word32)w > outSz - outIdx) {
  18383. w = BUFFER_E;
  18384. goto exit;
  18385. }
  18386. outIdx += (word32)w;
  18387. val = 0;
  18388. }
  18389. inIdx++;
  18390. }
  18391. if (outIdx == outSz)
  18392. outIdx--;
  18393. out[outIdx] = 0;
  18394. w = (int)outIdx;
  18395. exit:
  18396. return w;
  18397. }
  18398. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  18399. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  18400. #ifdef WOLFSSL_ASN_TEMPLATE
  18401. /* ASN.1 template for PolicyInformation.
  18402. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  18403. */
  18404. static const ASNItem policyInfoASN[] = {
  18405. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18406. /* policyIdentifier */
  18407. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18408. /* policyQualifiers */
  18409. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  18410. };
  18411. enum {
  18412. POLICYINFOASN_IDX_SEQ = 0,
  18413. POLICYINFOASN_IDX_ID,
  18414. POLICYINFOASN_IDX_QUALI
  18415. };
  18416. /* Number of items in ASN.1 template for PolicyInformation. */
  18417. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  18418. #endif
  18419. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  18420. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  18421. {
  18422. #ifndef WOLFSSL_ASN_TEMPLATE
  18423. word32 idx = 0;
  18424. word32 oldIdx;
  18425. int policy_length = 0;
  18426. int ret;
  18427. int total_length = 0;
  18428. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  18429. !defined(WOLFSSL_DUP_CERTPOL)
  18430. int i;
  18431. #endif
  18432. WOLFSSL_ENTER("DecodeCertPolicy");
  18433. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  18434. /* Check if cert is null before dereferencing below */
  18435. if (cert == NULL)
  18436. return BAD_FUNC_ARG;
  18437. #else
  18438. (void)cert;
  18439. #endif
  18440. #if defined(WOLFSSL_CERT_EXT)
  18441. cert->extCertPoliciesNb = 0;
  18442. #endif
  18443. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  18444. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  18445. return ASN_PARSE_E;
  18446. }
  18447. /* Validate total length */
  18448. if (total_length > (int)(sz - idx)) {
  18449. WOLFSSL_MSG("\tCertPolicy length mismatch");
  18450. return ASN_PARSE_E;
  18451. }
  18452. /* Unwrap certificatePolicies */
  18453. do {
  18454. int length = 0;
  18455. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  18456. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  18457. return ASN_PARSE_E;
  18458. }
  18459. oldIdx = idx;
  18460. ret = GetASNObjectId(input, &idx, &length, sz);
  18461. if (ret != 0)
  18462. return ret;
  18463. policy_length -= (int)(idx - oldIdx);
  18464. if (length > 0) {
  18465. /* Verify length won't overrun buffer */
  18466. if (length > (int)(sz - idx)) {
  18467. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  18468. return ASN_PARSE_E;
  18469. }
  18470. #if defined(WOLFSSL_SEP)
  18471. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  18472. DYNAMIC_TYPE_X509_EXT);
  18473. if (cert->deviceType == NULL) {
  18474. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  18475. return MEMORY_E;
  18476. }
  18477. cert->deviceTypeSz = length;
  18478. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  18479. break;
  18480. #elif defined(WOLFSSL_CERT_EXT)
  18481. /* decode cert policy */
  18482. if (DecodePolicyOID(cert->extCertPolicies[
  18483. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  18484. input + idx, length) <= 0) {
  18485. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  18486. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18487. return ASN_PARSE_E;
  18488. }
  18489. #ifndef WOLFSSL_DUP_CERTPOL
  18490. /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST
  18491. * NOT appear more than once in a certificate policies
  18492. * extension". This is a sanity check for duplicates.
  18493. * extCertPolicies should only have OID values, additional
  18494. * qualifiers need to be stored in a separate array. */
  18495. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  18496. if (XMEMCMP(cert->extCertPolicies[i],
  18497. cert->extCertPolicies[cert->extCertPoliciesNb],
  18498. MAX_CERTPOL_SZ) == 0) {
  18499. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  18500. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  18501. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  18502. return CERTPOLICIES_E;
  18503. }
  18504. }
  18505. #endif /* !WOLFSSL_DUP_CERTPOL */
  18506. cert->extCertPoliciesNb++;
  18507. #else
  18508. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  18509. return 0;
  18510. #endif
  18511. }
  18512. idx += (word32)policy_length;
  18513. } while((int)idx < total_length
  18514. #if defined(WOLFSSL_CERT_EXT)
  18515. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  18516. #endif
  18517. );
  18518. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  18519. return 0;
  18520. #else /* WOLFSSL_ASN_TEMPLATE */
  18521. word32 idx = 0;
  18522. int ret = 0;
  18523. int total_length = 0;
  18524. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  18525. !defined(WOLFSSL_DUP_CERTPOL)
  18526. int i;
  18527. #endif
  18528. WOLFSSL_ENTER("DecodeCertPolicy");
  18529. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  18530. /* Check if cert is null before dereferencing below */
  18531. if (cert == NULL)
  18532. ret = BAD_FUNC_ARG;
  18533. #endif
  18534. if (ret == 0) {
  18535. #if defined(WOLFSSL_CERT_EXT)
  18536. cert->extCertPoliciesNb = 0;
  18537. #endif
  18538. /* Strip SEQUENCE OF and check using all data. */
  18539. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  18540. {
  18541. ret = ASN_PARSE_E;
  18542. }
  18543. }
  18544. /* Unwrap certificatePolicies */
  18545. while ((ret == 0) && ((int)idx < total_length)
  18546. #if defined(WOLFSSL_CERT_EXT)
  18547. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  18548. #endif
  18549. ) {
  18550. ASNGetData dataASN[policyInfoASN_Length];
  18551. byte* data = NULL;
  18552. word32 length = 0;
  18553. /* Clear dynamic data and check OID is a cert policy type. */
  18554. XMEMSET(dataASN, 0, sizeof(dataASN));
  18555. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  18556. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  18557. input, &idx, (word32)sz);
  18558. if (ret == 0) {
  18559. /* Get the OID. */
  18560. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  18561. if (length == 0) {
  18562. ret = ASN_PARSE_E;
  18563. }
  18564. }
  18565. #if defined(WOLFSSL_SEP)
  18566. /* Store OID in device type. */
  18567. if (ret == 0) {
  18568. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  18569. DYNAMIC_TYPE_X509_EXT);
  18570. if (cert->deviceType == NULL) {
  18571. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  18572. ret = MEMORY_E;
  18573. }
  18574. }
  18575. if (ret == 0) {
  18576. /* Store device type data and length. */
  18577. cert->deviceTypeSz = (int)length;
  18578. XMEMCPY(cert->deviceType, data, length);
  18579. break;
  18580. }
  18581. #elif defined(WOLFSSL_CERT_EXT)
  18582. if (ret == 0) {
  18583. /* Decode cert policy. */
  18584. if (DecodePolicyOID(
  18585. cert->extCertPolicies[cert->extCertPoliciesNb],
  18586. MAX_CERTPOL_SZ, data, length) <= 0) {
  18587. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  18588. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18589. ret = ASN_PARSE_E;
  18590. }
  18591. }
  18592. #ifndef WOLFSSL_DUP_CERTPOL
  18593. /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST
  18594. * NOT appear more than once in a certificate policies
  18595. * extension". This is a sanity check for duplicates.
  18596. * extCertPolicies should only have OID values, additional
  18597. * qualifiers need to be stored in a separate array. */
  18598. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  18599. if (XMEMCMP(cert->extCertPolicies[i],
  18600. cert->extCertPolicies[cert->extCertPoliciesNb],
  18601. MAX_CERTPOL_SZ) == 0) {
  18602. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  18603. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  18604. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  18605. ret = CERTPOLICIES_E;
  18606. }
  18607. }
  18608. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  18609. if (ret == 0) {
  18610. /* Keep count of policies seen. */
  18611. cert->extCertPoliciesNb++;
  18612. }
  18613. #else
  18614. (void)data;
  18615. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  18616. break;
  18617. #endif
  18618. }
  18619. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  18620. return ret;
  18621. #endif /* WOLFSSL_ASN_TEMPLATE */
  18622. }
  18623. #endif /* WOLFSSL_SEP */
  18624. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18625. #ifdef WOLFSSL_ASN_TEMPLATE
  18626. /* ASN.1 template for subject dir attribute.
  18627. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  18628. */
  18629. static const ASNItem subjDirAttrASN[] = {
  18630. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18631. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18632. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  18633. };
  18634. enum {
  18635. SUBJDIRATTRASN_IDX_SEQ = 0,
  18636. SUBJDIRATTRASN_IDX_OID,
  18637. SUBJDIRATTRASN_IDX_SET,
  18638. };
  18639. /* Number of items in ASN.1 template for BasicConstraints. */
  18640. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  18641. #endif
  18642. /* Decode subject directory attributes extension in a certificate.
  18643. *
  18644. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  18645. *
  18646. * @param [in] input Buffer holding data.
  18647. * @param [in] sz Size of data in buffer.
  18648. * @param [in, out] cert Certificate object.
  18649. * @return 0 on success.
  18650. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18651. * is invalid.
  18652. */
  18653. static int DecodeSubjDirAttr(const byte* input, word32 sz, DecodedCert* cert)
  18654. {
  18655. #ifndef WOLFSSL_ASN_TEMPLATE
  18656. word32 idx = 0;
  18657. int length = 0;
  18658. int ret = 0;
  18659. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18660. #ifdef OPENSSL_ALL
  18661. cert->extSubjDirAttrSrc = input;
  18662. cert->extSubjDirAttrSz = sz;
  18663. #endif /* OPENSSL_ALL */
  18664. /* Unwrap the list of Attributes */
  18665. if (GetSequence(input, &idx, &length, sz) < 0)
  18666. return ASN_PARSE_E;
  18667. if (length == 0) {
  18668. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  18669. If the subjectDirectoryAttributes extension is present, the
  18670. sequence MUST contain at least one entry. */
  18671. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18672. return ASN_PARSE_E;
  18673. }
  18674. /* length is the length of the list contents */
  18675. while (idx < (word32)sz) {
  18676. word32 oid;
  18677. if (GetSequence(input, &idx, &length, sz) < 0)
  18678. return ASN_PARSE_E;
  18679. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  18680. return ASN_PARSE_E;
  18681. if (GetSet(input, &idx, &length, sz) < 0)
  18682. return ASN_PARSE_E;
  18683. /* There may be more than one countryOfCitizenship, but save the
  18684. * first one for now. */
  18685. if (oid == SDA_COC_OID) {
  18686. byte tag;
  18687. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  18688. return ASN_PARSE_E;
  18689. if (length != COUNTRY_CODE_LEN)
  18690. return ASN_PARSE_E;
  18691. if (tag == ASN_PRINTABLE_STRING) {
  18692. XMEMCPY(cert->countryOfCitizenship,
  18693. input + idx, COUNTRY_CODE_LEN);
  18694. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18695. }
  18696. }
  18697. idx += length;
  18698. }
  18699. return ret;
  18700. #else
  18701. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  18702. int ret = 0;
  18703. word32 idx = 0;
  18704. int length;
  18705. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18706. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  18707. /* Strip outer SEQUENCE. */
  18708. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  18709. ret = ASN_PARSE_E;
  18710. }
  18711. /* Handle each inner SEQUENCE. */
  18712. while ((ret == 0) && (idx < (word32)sz)) {
  18713. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  18714. input, &idx, sz);
  18715. /* There may be more than one countryOfCitizenship, but save the
  18716. * first one for now. */
  18717. if ((ret == 0) &&
  18718. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  18719. int cuLen;
  18720. word32 setIdx = 0;
  18721. byte* setData;
  18722. word32 setLen;
  18723. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  18724. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  18725. setLen) < 0) {
  18726. ret = ASN_PARSE_E;
  18727. }
  18728. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  18729. ret = ASN_PARSE_E;
  18730. }
  18731. if (ret == 0) {
  18732. XMEMCPY(cert->countryOfCitizenship, setData + setIdx,
  18733. (size_t)cuLen);
  18734. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18735. }
  18736. }
  18737. }
  18738. FREE_ASNGETDATA(dataASN, cert->heap);
  18739. return ret;
  18740. #endif /* WOLFSSL_ASN_TEMPLATE */
  18741. }
  18742. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  18743. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18744. /* Decode subject information access extension in a certificate.
  18745. *
  18746. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  18747. *
  18748. * @param [in] input Buffer holding data.
  18749. * @param [in] sz Size of data in buffer.
  18750. * @param [in, out] cert Certificate object.
  18751. * @return 0 on success.
  18752. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18753. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18754. * is invalid.
  18755. * @return MEMORY_E on dynamic memory allocation failure.
  18756. */
  18757. static int DecodeSubjInfoAcc(const byte* input, word32 sz, DecodedCert* cert)
  18758. {
  18759. word32 idx = 0;
  18760. int length = 0;
  18761. int ret = 0;
  18762. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  18763. #ifdef OPENSSL_ALL
  18764. cert->extSubjAltNameSrc = input;
  18765. cert->extSubjAltNameSz = sz;
  18766. #endif /* OPENSSL_ALL */
  18767. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  18768. if (GetSequence(input, &idx, &length, sz) < 0)
  18769. return ASN_PARSE_E;
  18770. if (length == 0) {
  18771. /* RFC 5280 4.2.2.2. Subject Information Access
  18772. If the subjectInformationAccess extension is present, the
  18773. sequence MUST contain at least one entry. */
  18774. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18775. return ASN_PARSE_E;
  18776. }
  18777. /* Per fpkx-x509-cert-profile-common... section 5.3.
  18778. * [The] subjectInfoAccess extension must contain at least one
  18779. * instance of the id-ad-caRepository access method containing a
  18780. * publicly accessible HTTP URI which returns as certs-only
  18781. * CMS.
  18782. */
  18783. while (idx < (word32)sz) {
  18784. word32 oid = 0;
  18785. byte b;
  18786. /* Unwrap an AccessDescription */
  18787. if (GetSequence(input, &idx, &length, sz) < 0)
  18788. return ASN_PARSE_E;
  18789. /* Get the accessMethod */
  18790. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  18791. return ASN_PARSE_E;
  18792. /* Only supporting URIs right now. */
  18793. if (GetASNTag(input, &idx, &b, sz) < 0)
  18794. return ASN_PARSE_E;
  18795. if (GetLength(input, &idx, &length, sz) < 0)
  18796. return ASN_PARSE_E;
  18797. /* Set caRepo entry */
  18798. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  18799. cert->extSubjInfoAccCaRepoSz = (word32)length;
  18800. cert->extSubjInfoAccCaRepo = input + idx;
  18801. break;
  18802. }
  18803. idx += (word32)length;
  18804. }
  18805. if (cert->extSubjInfoAccCaRepo == NULL ||
  18806. cert->extSubjInfoAccCaRepoSz == 0) {
  18807. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  18808. ret = ASN_PARSE_E;
  18809. }
  18810. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  18811. return ret;
  18812. }
  18813. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  18814. #ifdef WOLFSSL_DUAL_ALG_CERTS
  18815. /* The subject alternative public key is an extension that holds the same thing
  18816. * as a subject public key. */
  18817. static const ASNItem subjAltPubKeyInfoASN[] = {
  18818. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18819. /* ALT_SPUBKEYINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18820. /* algorithm AlgorithmIdentifier */
  18821. /* AlgorithmIdentifier ::= SEQUENCE */
  18822. /* ALT_SPUBKEYINFO_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18823. /* Algorithm OBJECT IDENTIFIER */
  18824. /* ALT_SPUBKEYINFO_ALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18825. /* parameters ANY defined by algorithm OPTIONAL */
  18826. /* ALT_SPUBKEYINFO_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  18827. /* ALT_SPUBKEYINFO_ALGO_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  18828. #ifdef WC_RSA_PSS
  18829. /* ALT_SPUBKEYINFO_ALGO_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  18830. #endif
  18831. /* subjectPublicKey BIT STRING */
  18832. /* ALT_SPUBKEYINFO_PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 }
  18833. };
  18834. #define subjAltPubKeyInfoASN_Length (sizeof(subjAltPubKeyInfoASN) / \
  18835. sizeof(ASNItem))
  18836. enum {
  18837. ALT_SPUBKEYINFO_SEQ = 0,
  18838. ALT_SPUBKEYINFO_ALGO_SEQ,
  18839. ALT_SPUBKEYINFO_ALGO_OID,
  18840. ALT_SPUBKEYINFO_ALGO_NULL,
  18841. ALT_SPUBKEYINFO_ALGO_CURVEID,
  18842. #ifdef WC_RSA_PSS
  18843. ALT_SPUBKEYINFO_ALGO_P_SEQ,
  18844. #endif
  18845. ALT_SPUBKEYINFO_PUBKEY
  18846. };
  18847. static int DecodeSubjAltPubKeyInfo(const byte* input, int sz, DecodedCert* cert)
  18848. {
  18849. int ret = 0;
  18850. word32 idx = 0;
  18851. DECL_ASNGETDATA(dataASN, subjAltPubKeyInfoASN_Length);
  18852. WOLFSSL_ENTER("DecodeSubjAltPubKeyInfo");
  18853. if (ret == 0) {
  18854. CALLOC_ASNGETDATA(dataASN, subjAltPubKeyInfoASN_Length, ret,
  18855. cert->heap);
  18856. (void)cert;
  18857. }
  18858. if (ret == 0) {
  18859. GetASN_OID(&dataASN[ALT_SPUBKEYINFO_ALGO_OID], oidKeyType);
  18860. GetASN_OID(&dataASN[ALT_SPUBKEYINFO_ALGO_CURVEID], oidCurveType);
  18861. ret = GetASN_Items(subjAltPubKeyInfoASN, dataASN,
  18862. subjAltPubKeyInfoASN_Length, 1, input, &idx,
  18863. (word32)sz);
  18864. }
  18865. if (ret == 0) {
  18866. /* dataASN[ALT_SPUBKEYINFO_SEQ].data.u8 */
  18867. cert->sapkiDer = (byte *)input;
  18868. /* dataASN[ALT_SPUBKEYINFO_SEQ].length */
  18869. cert->sapkiLen = sz;
  18870. cert->sapkiOID = dataASN[ALT_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18871. }
  18872. FREE_ASNGETDATA(dataASN, cert->heap);
  18873. WOLFSSL_LEAVE("DecodeSubjAltPubKeyInfo", ret);
  18874. return ret;
  18875. }
  18876. /* The alternative signature algorithm extension holds the same thing as a
  18877. * as a signature algorithm identifier. */
  18878. static const ASNItem altSigAlgASN[] = {
  18879. /* AltSigAlg AlgorithmIdentifier */
  18880. /* AlgorithmIdentifier ::= SEQUENCE */
  18881. /* ALTSIG_ALGOID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18882. /* Algorithm OBJECT IDENTIFIER */
  18883. /* ALTSIG_ALGOID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18884. /* parameters ANY defined by algorithm OPTIONAL */
  18885. /* ALTSIG_ALGOID_PARAMS_NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  18886. #ifdef WC_RSA_PSS
  18887. /* ALTSIG_ALGOID_PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  18888. #endif
  18889. };
  18890. #define altSigAlgASN_Length (sizeof(altSigAlgASN) / sizeof(ASNItem))
  18891. enum {
  18892. ALTSIG_ALGOID_SEQ = 0,
  18893. ALTSIG_ALGOID_OID,
  18894. ALTSIG_ALGOID_PARAMS_NULL,
  18895. #ifdef WC_RSA_PSS
  18896. ALTSIG_ALGOID_PARAMS,
  18897. #endif
  18898. };
  18899. static int DecodeAltSigAlg(const byte* input, int sz, DecodedCert* cert)
  18900. {
  18901. int ret = 0;
  18902. word32 idx = 0;
  18903. DECL_ASNGETDATA(dataASN, altSigAlgASN_Length);
  18904. WOLFSSL_ENTER("DecodeAltSigAlg");
  18905. if (ret == 0) {
  18906. CALLOC_ASNGETDATA(dataASN, altSigAlgASN_Length, ret, cert->heap);
  18907. (void)cert;
  18908. }
  18909. if (ret == 0) {
  18910. GetASN_OID(&dataASN[ALTSIG_ALGOID_OID], oidSigType);
  18911. ret = GetASN_Items(altSigAlgASN, dataASN,
  18912. altSigAlgASN_Length, 1, input, &idx,
  18913. (word32)sz);
  18914. }
  18915. if (ret == 0) {
  18916. cert->altSigAlgDer = dataASN[ALTSIG_ALGOID_SEQ].data.u8;
  18917. cert->altSigAlgLen = dataASN[ALTSIG_ALGOID_SEQ].length;
  18918. cert->altSigAlgOID = dataASN[ALTSIG_ALGOID_OID].data.oid.sum;
  18919. }
  18920. FREE_ASNGETDATA(dataASN, cert->heap);
  18921. WOLFSSL_LEAVE("DecodeAltSigAlg", ret);
  18922. return ret;
  18923. }
  18924. /* The alternative signature value extension holds an ASN.1 bitstring just
  18925. * like a traditional signature in the certificate. */
  18926. static int DecodeAltSigVal(const byte* input, int sz, DecodedCert* cert)
  18927. {
  18928. (void)cert;
  18929. int ret = 0;
  18930. word32 idx = 0;
  18931. int len = 0;
  18932. WOLFSSL_ENTER("DecodeAltSigVal");
  18933. if (ret == 0) {
  18934. ret = CheckBitString(input, &idx, &len, sz, 1, NULL);
  18935. }
  18936. if (ret == 0) {
  18937. cert->altSigValDer = (byte *)input + idx;
  18938. cert->altSigValLen = len;
  18939. }
  18940. WOLFSSL_LEAVE("DecodeAltSigVal", ret);
  18941. return ret;
  18942. }
  18943. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  18944. /* Macro to check if bit is set, if not sets and return success.
  18945. Otherwise returns failure */
  18946. /* Macro required here because bit-field operation */
  18947. #ifndef WOLFSSL_NO_ASN_STRICT
  18948. #define VERIFY_AND_SET_OID(bit) \
  18949. if ((bit) == 0) \
  18950. (bit) = 1; \
  18951. else \
  18952. return ASN_OBJECT_ID_E;
  18953. #else
  18954. /* With no strict defined, the verify is skipped */
  18955. #define VERIFY_AND_SET_OID(bit) bit = 1;
  18956. #endif
  18957. /* Parse extension type specific data based on OID sum.
  18958. *
  18959. * Supported extensions:
  18960. * Basic Constraints - BASIC_CA_OID
  18961. * CRL Distribution Points - CRL_DIST_OID
  18962. * Authority Information Access - AUTH_INFO_OID
  18963. * Subject Alternative Name - ALT_NAMES_OID
  18964. * Authority Key Identifier - AUTH_KEY_OID
  18965. * Subject Key Identifier - SUBJ_KEY_OID
  18966. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  18967. * Key Usage - KEY_USAGE_OID
  18968. * Extended Key Usage - EXT_KEY_USAGE_OID
  18969. * Name Constraints - NAME_CONS_OID
  18970. * Inhibit anyPolicy - INHIBIT_ANY_OID
  18971. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  18972. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  18973. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  18974. * Subject Information Access - SUBJ_INFO_ACC_OID
  18975. * Unsupported extensions from RFC 5280:
  18976. * 4.2.1.5 - Policy mappings
  18977. * 4.2.1.7 - Issuer Alternative Name
  18978. * 4.2.1.11 - Policy Constraints
  18979. * 4.2.1.15 - Freshest CRL
  18980. *
  18981. * @param [in] input Buffer containing extension type specific data.
  18982. * @param [in] length Length of data.
  18983. * @param [in] oid OID sum for extension.
  18984. * @param [in] critical Whether extension is critical.
  18985. * @param [in, out] cert Certificate object.
  18986. * @return 0 on success.
  18987. * @return ASN_PARSE_E when BER encoding is invalid.
  18988. * @return MEMORY_E on dynamic memory allocation failure.
  18989. * @return Other negative values on error.
  18990. */
  18991. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  18992. byte critical, DecodedCert* cert,
  18993. int *isUnknownExt)
  18994. {
  18995. int ret = 0;
  18996. word32 idx = 0;
  18997. if (isUnknownExt != NULL)
  18998. *isUnknownExt = 0;
  18999. switch (oid) {
  19000. /* Basic Constraints. */
  19001. case BASIC_CA_OID:
  19002. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  19003. cert->extBasicConstCrit = critical ? 1 : 0;
  19004. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  19005. ret = ASN_PARSE_E;
  19006. }
  19007. break;
  19008. /* CRL Distribution point. */
  19009. case CRL_DIST_OID:
  19010. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  19011. cert->extCRLdistCrit = critical ? 1 : 0;
  19012. if (DecodeCrlDist(input, length, cert) < 0) {
  19013. ret = ASN_PARSE_E;
  19014. }
  19015. break;
  19016. /* Authority information access. */
  19017. case AUTH_INFO_OID:
  19018. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  19019. cert->extAuthInfoCrit = critical ? 1 : 0;
  19020. #ifndef WOLFSSL_ALLOW_CRIT_AIA
  19021. /* This check is added due to RFC 5280 section 4.2.2.1
  19022. * stating that conforming CA's must mark this extension
  19023. * as non-critical. When parsing extensions check that
  19024. * certificate was made in compliance with this. */
  19025. if (critical) {
  19026. WOLFSSL_MSG("Critical Authority Information Access is not"
  19027. "allowed");
  19028. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_AIA if wanted");
  19029. ret = ASN_CRIT_EXT_E;
  19030. }
  19031. #endif
  19032. if ((ret == 0) && (DecodeAuthInfo(input, length, cert) < 0)) {
  19033. ret = ASN_PARSE_E;
  19034. }
  19035. break;
  19036. /* Subject alternative name. */
  19037. case ALT_NAMES_OID:
  19038. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  19039. cert->extSubjAltNameCrit = critical ? 1 : 0;
  19040. ret = DecodeAltNames(input, length, cert);
  19041. break;
  19042. /* Authority Key Identifier. */
  19043. case AUTH_KEY_OID:
  19044. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  19045. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  19046. #ifndef WOLFSSL_ALLOW_CRIT_AKID
  19047. /* This check is added due to RFC 5280 section 4.2.1.1
  19048. * stating that conforming CA's must mark this extension
  19049. * as non-critical. When parsing extensions check that
  19050. * certificate was made in compliance with this. */
  19051. if (critical) {
  19052. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  19053. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_AKID if wanted");
  19054. ret = ASN_CRIT_EXT_E;
  19055. }
  19056. #endif
  19057. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  19058. ret = ASN_PARSE_E;
  19059. }
  19060. break;
  19061. /* Subject Key Identifier. */
  19062. case SUBJ_KEY_OID:
  19063. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  19064. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  19065. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  19066. /* This check is added due to RFC 5280 section 4.2.1.2
  19067. * stating that conforming CA's must mark this extension
  19068. * as non-critical. When parsing extensions check that
  19069. * certificate was made in compliance with this. */
  19070. if (critical) {
  19071. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  19072. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  19073. ret = ASN_CRIT_EXT_E;
  19074. }
  19075. #endif
  19076. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  19077. ret = ASN_PARSE_E;
  19078. }
  19079. break;
  19080. /* Certificate policies. */
  19081. case CERT_POLICY_OID:
  19082. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  19083. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  19084. #if defined(OPENSSL_EXTRA) || \
  19085. defined(OPENSSL_EXTRA_X509_SMALL)
  19086. cert->extCertPolicyCrit = critical ? 1 : 0;
  19087. #endif
  19088. #endif
  19089. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  19090. defined(WOLFSSL_QT)
  19091. if (DecodeCertPolicy(input, length, cert) < 0) {
  19092. ret = ASN_PARSE_E;
  19093. }
  19094. #else
  19095. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  19096. #endif
  19097. break;
  19098. /* Key usage. */
  19099. case KEY_USAGE_OID:
  19100. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  19101. cert->extKeyUsageCrit = critical ? 1 : 0;
  19102. if (DecodeKeyUsage(input, length, cert) < 0) {
  19103. ret = ASN_PARSE_E;
  19104. }
  19105. break;
  19106. /* Extended key usage. */
  19107. case EXT_KEY_USAGE_OID:
  19108. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  19109. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  19110. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  19111. ret = ASN_PARSE_E;
  19112. }
  19113. break;
  19114. #ifndef IGNORE_NAME_CONSTRAINTS
  19115. /* Name constraints. */
  19116. case NAME_CONS_OID:
  19117. #ifndef WOLFSSL_NO_ASN_STRICT
  19118. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  19119. "The name constraints extension,
  19120. which MUST be used only in a CA certificate" */
  19121. if (!cert->isCA) {
  19122. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  19123. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  19124. ret = ASN_NAME_INVALID_E;
  19125. }
  19126. #endif
  19127. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  19128. cert->extNameConstraintCrit = critical ? 1 : 0;
  19129. if (DecodeNameConstraints(input, length, cert) < 0) {
  19130. ret = ASN_PARSE_E;
  19131. }
  19132. break;
  19133. #endif /* IGNORE_NAME_CONSTRAINTS */
  19134. /* Inhibit anyPolicy. */
  19135. case INHIBIT_ANY_OID:
  19136. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  19137. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  19138. break;
  19139. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  19140. /* Netscape's certificate type. */
  19141. case NETSCAPE_CT_OID:
  19142. if (DecodeNsCertType(input, (int)length, cert) < 0)
  19143. ret = ASN_PARSE_E;
  19144. break;
  19145. #endif
  19146. #ifdef HAVE_OCSP
  19147. /* OCSP no check. */
  19148. case OCSP_NOCHECK_OID:
  19149. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  19150. ret = GetASNNull(input, &idx, length);
  19151. if (ret != 0) {
  19152. ret = ASN_PARSE_E;
  19153. }
  19154. break;
  19155. #endif
  19156. case POLICY_CONST_OID:
  19157. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  19158. cert->extPolicyConstCrit = critical ? 1 : 0;
  19159. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  19160. return ASN_PARSE_E;
  19161. break;
  19162. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  19163. case SUBJ_DIR_ATTR_OID:
  19164. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  19165. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  19166. return ASN_PARSE_E;
  19167. break;
  19168. #endif
  19169. #ifdef WOLFSSL_SUBJ_INFO_ACC
  19170. case SUBJ_INFO_ACC_OID:
  19171. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  19172. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  19173. return ASN_PARSE_E;
  19174. break;
  19175. #endif
  19176. #ifdef WOLFSSL_DUAL_ALG_CERTS
  19177. case SUBJ_ALT_PUB_KEY_INFO_OID:
  19178. VERIFY_AND_SET_OID(cert->extSapkiSet);
  19179. if (DecodeSubjAltPubKeyInfo(&input[idx], length, cert) < 0)
  19180. return ASN_PARSE_E;
  19181. break;
  19182. case ALT_SIG_ALG_OID:
  19183. VERIFY_AND_SET_OID(cert->extAltSigAlgSet);
  19184. if (DecodeAltSigAlg(&input[idx], length, cert) < 0)
  19185. return ASN_PARSE_E;
  19186. break;
  19187. case ALT_SIG_VAL_OID:
  19188. VERIFY_AND_SET_OID(cert->extAltSigValSet);
  19189. if (DecodeAltSigVal(&input[idx], length, cert) < 0)
  19190. return ASN_PARSE_E;
  19191. break;
  19192. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  19193. default:
  19194. if (isUnknownExt != NULL)
  19195. *isUnknownExt = 1;
  19196. #ifndef WOLFSSL_NO_ASN_STRICT
  19197. /* While it is a failure to not support critical extensions,
  19198. * still parse the certificate ignoring the unsupported
  19199. * extension to allow caller to accept it with the verify
  19200. * callback. */
  19201. if (critical) {
  19202. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  19203. ret = ASN_CRIT_EXT_E;
  19204. }
  19205. #endif
  19206. break;
  19207. }
  19208. return ret;
  19209. }
  19210. #ifdef WOLFSSL_ASN_TEMPLATE
  19211. /* ASN.1 template for extensions.
  19212. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  19213. */
  19214. static const ASNItem certExtHdrASN[] = {
  19215. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  19216. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19217. };
  19218. enum {
  19219. CERTEXTHDRASN_IDX_EXTTAG = 0,
  19220. CERTEXTHDRASN_IDX_EXTSEQ
  19221. };
  19222. /* Number of items in ASN.1 template for extensions. */
  19223. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  19224. /* ASN.1 template for Extension.
  19225. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  19226. */
  19227. static const ASNItem certExtASN[] = {
  19228. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19229. /* Extension object id */
  19230. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  19231. /* critical - when true, must be parseable. */
  19232. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  19233. /* Data for extension - leave index at start of data. */
  19234. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  19235. };
  19236. enum {
  19237. CERTEXTASN_IDX_SEQ = 0,
  19238. CERTEXTASN_IDX_OID,
  19239. CERTEXTASN_IDX_CRIT,
  19240. CERTEXTASN_IDX_VAL
  19241. };
  19242. /* Number of items in ASN.1 template for Extension. */
  19243. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  19244. #endif
  19245. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  19246. && defined(HAVE_OID_DECODING)
  19247. int wc_SetUnknownExtCallback(DecodedCert* cert,
  19248. wc_UnknownExtCallback cb) {
  19249. if (cert == NULL) {
  19250. return BAD_FUNC_ARG;
  19251. }
  19252. cert->unknownExtCallback = cb;
  19253. return 0;
  19254. }
  19255. #endif
  19256. /*
  19257. * Processing the Certificate Extensions. This does not modify the current
  19258. * index. It is works starting with the recorded extensions pointer.
  19259. */
  19260. static int DecodeCertExtensions(DecodedCert* cert)
  19261. {
  19262. #ifndef WOLFSSL_ASN_TEMPLATE
  19263. int ret = 0;
  19264. word32 idx = 0;
  19265. word32 sz = (word32)cert->extensionsSz;
  19266. const byte* input = cert->extensions;
  19267. int length;
  19268. word32 oid;
  19269. byte critical = 0;
  19270. byte criticalFail = 0;
  19271. byte tag = 0;
  19272. WOLFSSL_ENTER("DecodeCertExtensions");
  19273. if (input == NULL || sz == 0)
  19274. return BAD_FUNC_ARG;
  19275. #ifdef WOLFSSL_CERT_REQ
  19276. if (!cert->isCSR)
  19277. #endif
  19278. { /* Not included in CSR */
  19279. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  19280. return ASN_PARSE_E;
  19281. }
  19282. if (tag != ASN_EXTENSIONS) {
  19283. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  19284. return ASN_PARSE_E;
  19285. }
  19286. if (GetLength(input, &idx, &length, sz) < 0) {
  19287. WOLFSSL_MSG("\tfail: invalid length");
  19288. return ASN_PARSE_E;
  19289. }
  19290. }
  19291. if (GetSequence(input, &idx, &length, sz) < 0) {
  19292. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  19293. return ASN_PARSE_E;
  19294. }
  19295. while (idx < (word32)sz) {
  19296. word32 localIdx;
  19297. if (GetSequence(input, &idx, &length, sz) < 0) {
  19298. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  19299. return ASN_PARSE_E;
  19300. }
  19301. oid = 0;
  19302. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  19303. WOLFSSL_MSG("\tfail: OBJECT ID");
  19304. return ret;
  19305. }
  19306. /* check for critical flag */
  19307. critical = 0;
  19308. if ((idx + 1) > (word32)sz) {
  19309. WOLFSSL_MSG("\tfail: malformed buffer");
  19310. return BUFFER_E;
  19311. }
  19312. localIdx = idx;
  19313. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  19314. if (tag == ASN_BOOLEAN) {
  19315. ret = GetBoolean(input, &idx, sz);
  19316. if (ret < 0) {
  19317. WOLFSSL_MSG("\tfail: critical boolean");
  19318. return ret;
  19319. }
  19320. critical = (byte)ret;
  19321. }
  19322. }
  19323. /* process the extension based on the OID */
  19324. ret = GetOctetString(input, &idx, &length, sz);
  19325. if (ret < 0) {
  19326. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  19327. return ret;
  19328. }
  19329. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  19330. cert, NULL);
  19331. if (ret == ASN_CRIT_EXT_E) {
  19332. ret = 0;
  19333. criticalFail = 1;
  19334. }
  19335. if (ret < 0)
  19336. goto end;
  19337. idx += (word32)length;
  19338. }
  19339. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  19340. end:
  19341. return ret;
  19342. #else
  19343. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  19344. ASNGetData dataExtsASN[certExtHdrASN_Length];
  19345. int ret = 0;
  19346. const byte* input = cert->extensions;
  19347. int sz = cert->extensionsSz;
  19348. word32 idx = 0;
  19349. int criticalRet = 0;
  19350. int offset = 0;
  19351. WOLFSSL_ENTER("DecodeCertExtensions");
  19352. if (input == NULL || sz == 0)
  19353. ret = BAD_FUNC_ARG;
  19354. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  19355. #ifdef WOLFSSL_CERT_REQ
  19356. if (cert->isCSR) {
  19357. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  19358. }
  19359. #endif
  19360. if (ret == 0) {
  19361. /* Clear dynamic data. */
  19362. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  19363. /* Parse extensions header. */
  19364. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  19365. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  19366. input, &idx, (word32)sz);
  19367. }
  19368. /* Parse each extension. */
  19369. while ((ret == 0) && (idx < (word32)sz)) {
  19370. byte critical = 0;
  19371. int isUnknownExt = 0;
  19372. /* Clear dynamic data. */
  19373. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  19374. /* Ensure OID is an extension type. */
  19375. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  19376. /* Set criticality variable. */
  19377. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  19378. /* Parse extension wrapper. */
  19379. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  19380. &idx, (word32)sz);
  19381. if (ret == 0) {
  19382. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  19383. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  19384. /* Decode the extension by type. */
  19385. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  19386. &isUnknownExt);
  19387. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  19388. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  19389. word16 decOid[MAX_OID_SZ];
  19390. word32 decOidSz = sizeof(decOid);
  19391. ret = DecodeObjectId(
  19392. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  19393. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  19394. decOid, &decOidSz);
  19395. if (ret != 0) {
  19396. /* Should never get here as the extension was successfully
  19397. * decoded earlier. Something might be corrupted. */
  19398. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  19399. WOLFSSL_ERROR(ret);
  19400. }
  19401. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  19402. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  19403. dataASN[CERTEXTASN_IDX_VAL].length);
  19404. }
  19405. #endif
  19406. (void)isUnknownExt;
  19407. /* Move index on to next extension. */
  19408. idx += length;
  19409. }
  19410. /* Don't fail criticality until all other extensions have been checked.
  19411. */
  19412. if (ret == ASN_CRIT_EXT_E) {
  19413. criticalRet = ASN_CRIT_EXT_E;
  19414. ret = 0;
  19415. }
  19416. }
  19417. if (ret == 0) {
  19418. /* Use criticality return. */
  19419. ret = criticalRet;
  19420. }
  19421. FREE_ASNGETDATA(dataASN, cert->heap);
  19422. return ret;
  19423. #endif
  19424. }
  19425. #ifdef WOLFSSL_ASN_TEMPLATE
  19426. #if defined(HAVE_RPK)
  19427. /* ASN template for a Raw Public Key certificate defined RFC7250. */
  19428. static const ASNItem RPKCertASN[] = {
  19429. /* SubjectPublicKeyInfo ::= SEQUENCE */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19430. /* algorithm AlgorithmIdentifier */
  19431. /* AlgorithmIdentifier ::= SEQUENCE */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19432. /* Algorithm OBJECT IDENTIFIER */
  19433. /* TBS_SPUBKEYINFO_ALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  19434. /* parameters ANY defined by algorithm OPTIONAL */
  19435. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  19436. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  19437. #ifdef WC_RSA_PSS
  19438. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  19439. #endif
  19440. /* subjectPublicKey BIT STRING */
  19441. /* TBS_SPUBKEYINFO_PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19442. };
  19443. /* Number of items in ASN template for a RawPublicKey certificate. */
  19444. #define RPKCertASN_Length (sizeof(RPKCertASN) / sizeof(ASNItem))
  19445. enum {
  19446. RPKCERTASN_IDX_SPUBKEYINFO_SEQ = 0,
  19447. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_SEQ,
  19448. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID,
  19449. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_NULL,
  19450. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_CURVEID,
  19451. #ifdef WC_RSA_PSS
  19452. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_P_SEQ,
  19453. #endif
  19454. RPKCERTASN_IDX_SPUBKEYINFO_PUBKEY,
  19455. };
  19456. #endif /* HAVE_RPK */
  19457. /* ASN template for an X509 certificate.
  19458. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  19459. */
  19460. static const ASNItem x509CertASN[] = {
  19461. /* Certificate ::= SEQUENCE */
  19462. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19463. /* tbsCertificate TBSCertificate */
  19464. /* TBSCertificate ::= SEQUENCE */
  19465. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19466. /* version [0] EXPLICIT Version DEFAULT v1 */
  19467. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  19468. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  19469. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  19470. /* serialNumber CertificateSerialNumber */
  19471. /* CertificateSerialNumber ::= INTEGER */
  19472. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  19473. /* signature AlgorithmIdentifier */
  19474. /* AlgorithmIdentifier ::= SEQUENCE */
  19475. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19476. /* Algorithm OBJECT IDENTIFIER */
  19477. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  19478. /* parameters ANY defined by algorithm OPTIONAL */
  19479. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  19480. #ifdef WC_RSA_PSS
  19481. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  19482. #endif
  19483. /* issuer Name */
  19484. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  19485. /* validity Validity */
  19486. /* Validity ::= SEQUENCE */
  19487. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19488. /* notBefore Time */
  19489. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  19490. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  19491. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  19492. /* notAfter Time */
  19493. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  19494. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  19495. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  19496. /* subject Name */
  19497. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  19498. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  19499. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19500. /* algorithm AlgorithmIdentifier */
  19501. /* AlgorithmIdentifier ::= SEQUENCE */
  19502. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  19503. /* Algorithm OBJECT IDENTIFIER */
  19504. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  19505. /* parameters ANY defined by algorithm OPTIONAL */
  19506. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  19507. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  19508. #ifdef WC_RSA_PSS
  19509. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  19510. #endif
  19511. /* subjectPublicKey BIT STRING */
  19512. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  19513. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  19514. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  19515. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  19516. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  19517. /* extensions Extensions OPTIONAL */
  19518. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  19519. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  19520. /* signatureAlgorithm AlgorithmIdentifier */
  19521. /* AlgorithmIdentifier ::= SEQUENCE */
  19522. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19523. /* Algorithm OBJECT IDENTIFIER */
  19524. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  19525. /* parameters ANY defined by algorithm OPTIONAL */
  19526. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  19527. #ifdef WC_RSA_PSS
  19528. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  19529. #endif
  19530. /* signature BIT STRING */
  19531. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19532. };
  19533. enum {
  19534. X509CERTASN_IDX_SEQ = 0,
  19535. X509CERTASN_IDX_TBS_SEQ,
  19536. X509CERTASN_IDX_TBS_VER,
  19537. X509CERTASN_IDX_TBS_VER_INT,
  19538. X509CERTASN_IDX_TBS_SERIAL,
  19539. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  19540. X509CERTASN_IDX_TBS_ALGOID_OID,
  19541. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  19542. #ifdef WC_RSA_PSS
  19543. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  19544. #endif
  19545. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  19546. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  19547. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  19548. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  19549. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  19550. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  19551. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  19552. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  19553. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  19554. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  19555. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  19556. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  19557. #ifdef WC_RSA_PSS
  19558. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  19559. #endif
  19560. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  19561. X509CERTASN_IDX_TBS_ISSUERUID,
  19562. X509CERTASN_IDX_TBS_SUBJECTUID,
  19563. X509CERTASN_IDX_TBS_EXT,
  19564. X509CERTASN_IDX_TBS_EXT_SEQ,
  19565. X509CERTASN_IDX_SIGALGO_SEQ,
  19566. X509CERTASN_IDX_SIGALGO_OID,
  19567. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  19568. #ifdef WC_RSA_PSS
  19569. X509CERTASN_IDX_SIGALGO_PARAMS,
  19570. #endif
  19571. X509CERTASN_IDX_SIGNATURE,
  19572. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  19573. };
  19574. /* Number of items in ASN template for an X509 certificate. */
  19575. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  19576. /* Check the data data.
  19577. *
  19578. * @param [in] dataASN ASN template dynamic data item.
  19579. * @param [in] dataType BEFORE or AFTER date.
  19580. * @return 0 on success.
  19581. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  19582. * @return ASN_DATE_SZ_E when time data is not supported.
  19583. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19584. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19585. */
  19586. static int CheckDate(ASNGetData *dataASN, int dateType)
  19587. {
  19588. int ret = 0;
  19589. /* Check BER tag is valid. */
  19590. if ((dataASN->tag != ASN_UTC_TIME) &&
  19591. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  19592. ret = ASN_TIME_E;
  19593. }
  19594. /* Check date length is valid. */
  19595. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  19596. (dataASN->length < MIN_DATE_SIZE))) {
  19597. ret = ASN_DATE_SZ_E;
  19598. }
  19599. #ifndef NO_ASN_TIME_CHECK
  19600. /* Check date is a valid string and BEFORE or AFTER now. */
  19601. if ((ret == 0) &&
  19602. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  19603. if (dateType == BEFORE) {
  19604. ret = ASN_BEFORE_DATE_E;
  19605. }
  19606. else {
  19607. ret = ASN_AFTER_DATE_E;
  19608. }
  19609. }
  19610. #endif
  19611. (void)dateType;
  19612. return ret;
  19613. }
  19614. /* Decode a certificate. Internal/non-public API.
  19615. *
  19616. * @param [in] cert Certificate object.
  19617. * @param [in] verify Whether to verify dates before and after now.
  19618. * @param [out] criticalExt Critical extension return code.
  19619. * @param [out] badDateRet Bad date return code.
  19620. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  19621. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  19622. * @return 0 on success.
  19623. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19624. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  19625. * @return ASN_DATE_SZ_E when time data is not supported.
  19626. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19627. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19628. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19629. * is invalid.
  19630. * @return BUFFER_E when data in buffer is too small.
  19631. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19632. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  19633. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19634. * non-zero length.
  19635. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19636. */
  19637. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  19638. int* badDateRet, int stopAtPubKey,
  19639. int stopAfterPubKey)
  19640. {
  19641. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19642. int ret = 0;
  19643. int badDate = 0;
  19644. byte version;
  19645. word32 idx;
  19646. word32 serialSz;
  19647. const unsigned char* issuer = NULL;
  19648. word32 issuerSz = 0;
  19649. const unsigned char* subject = NULL;
  19650. word32 subjectSz = 0;
  19651. word32 pubKeyOffset = 0;
  19652. word32 pubKeyEnd = 0;
  19653. int done = 0;
  19654. #if defined(HAVE_RPK)
  19655. /* try to parse the cert as Raw Public Key cert */
  19656. DECL_ASNGETDATA(RPKdataASN, RPKCertASN_Length);
  19657. CALLOC_ASNGETDATA(RPKdataASN, RPKCertASN_Length, ret, cert->heap);
  19658. GetASN_OID(&RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID],
  19659. oidKeyType);
  19660. GetASN_OID(&RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_CURVEID],
  19661. oidCurveType);
  19662. ret = GetASN_Items(RPKCertASN, RPKdataASN, RPKCertASN_Length, 1,
  19663. cert->source, &cert->srcIdx, cert->maxIdx);
  19664. if (ret == 0) {
  19665. cert->keyOID =
  19666. RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  19667. /* Parse the public key. */
  19668. pubKeyOffset = RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_SEQ].offset;
  19669. pubKeyEnd = cert->maxIdx;
  19670. ret = GetCertKey(cert, cert->source, &pubKeyOffset, pubKeyEnd);
  19671. if (ret == 0) {
  19672. WOLFSSL_MSG("Raw Public Key certificate found and parsed");
  19673. cert->isRPK = 1;
  19674. }
  19675. }
  19676. /* Dispose of memory before allocating for extension decoding. */
  19677. FREE_ASNGETDATA(RPKdataASN, cert->heap);
  19678. if (ret == 0) {
  19679. return ret;
  19680. }
  19681. else {
  19682. ret = 0; /* proceed to the original x509 parsing */
  19683. }
  19684. #endif /* HAVE_RPK */
  19685. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  19686. if (ret == 0) {
  19687. version = 0;
  19688. serialSz = EXTERNAL_SERIAL_SIZE;
  19689. /* Get the version and put the serial number into the buffer. */
  19690. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  19691. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  19692. &serialSz);
  19693. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  19694. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19695. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19696. oidKeyType);
  19697. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19698. oidCurveType);
  19699. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19700. /* Parse the X509 certificate. */
  19701. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  19702. cert->source, &cert->srcIdx, cert->maxIdx);
  19703. #ifdef WOLFSSL_CLANG_TIDY
  19704. /* work around clang-tidy false positive re cert->source. */
  19705. if ((ret == 0) && (cert->source == NULL)) {
  19706. ret = ASN_PARSE_E;
  19707. }
  19708. #endif
  19709. }
  19710. /* Check version is valid/supported - can't be negative. */
  19711. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  19712. WOLFSSL_MSG("Unexpected certificate version");
  19713. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19714. ret = ASN_PARSE_E;
  19715. }
  19716. if (ret == 0) {
  19717. int i;
  19718. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  19719. /* Set fields extracted from data. */
  19720. cert->version = version;
  19721. cert->serialSz = (int)serialSz;
  19722. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  19723. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  19724. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  19725. /* No bad date error - don't always care. */
  19726. badDate = 0;
  19727. /* Find the item with the BEFORE date and check it. */
  19728. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  19729. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  19730. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  19731. if ((CheckDate(&dataASN[i], BEFORE) < 0) && (verify != NO_VERIFY) &&
  19732. (verify != VERIFY_SKIP_DATE)) {
  19733. badDate = ASN_BEFORE_DATE_E;
  19734. }
  19735. /* Store reference to BEFOREdate. */
  19736. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  19737. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  19738. /* Find the item with the AFTER date and check it. */
  19739. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  19740. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  19741. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  19742. if ((CheckDate(&dataASN[i], AFTER) < 0) && (verify != NO_VERIFY) &&
  19743. (verify != VERIFY_SKIP_DATE)) {
  19744. badDate = ASN_AFTER_DATE_E;
  19745. }
  19746. /* Store reference to AFTER date. */
  19747. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  19748. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  19749. /* Get the issuer name. */
  19750. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  19751. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  19752. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  19753. /* Get the subject name. */
  19754. subject = cert->source +
  19755. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  19756. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  19757. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  19758. }
  19759. if ((ret == 0) && stopAtPubKey) {
  19760. /* Return any bad date error through badDateRet and return offset of
  19761. * subjectPublicKeyInfo.
  19762. */
  19763. if (badDateRet != NULL) {
  19764. *badDateRet = badDate;
  19765. }
  19766. done = 1;
  19767. }
  19768. if ((ret == 0) && (!done)) {
  19769. /* Store the signature information. */
  19770. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  19771. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  19772. &cert->signature, &cert->sigLength);
  19773. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  19774. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  19775. != cert->signatureOID) {
  19776. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  19777. ret = ASN_SIG_OID_E;
  19778. }
  19779. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  19780. else if (IsSigAlgoECC(cert->signatureOID)) {
  19781. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  19782. #ifdef WC_RSA_PSS
  19783. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  19784. #endif
  19785. ) {
  19786. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19787. ret = ASN_PARSE_E;
  19788. }
  19789. }
  19790. #ifdef WC_RSA_PSS
  19791. /* Check parameters starting with a SEQUENCE. */
  19792. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19793. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19794. word32 sigAlgParamsSz = 0;
  19795. /* Parameters only with RSA PSS. */
  19796. if (oid != CTC_RSASSAPSS) {
  19797. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19798. ret = ASN_PARSE_E;
  19799. }
  19800. if (ret == 0) {
  19801. const byte* tbsParams;
  19802. word32 tbsParamsSz;
  19803. const byte* sigAlgParams;
  19804. /* Check RSA PSS parameters are the same. */
  19805. tbsParams =
  19806. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19807. cert->source);
  19808. tbsParamsSz =
  19809. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19810. cert->source);
  19811. sigAlgParams =
  19812. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19813. cert->source);
  19814. sigAlgParamsSz =
  19815. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19816. cert->source);
  19817. if ((tbsParamsSz != sigAlgParamsSz) ||
  19818. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  19819. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19820. ret = ASN_PARSE_E;
  19821. }
  19822. }
  19823. if (ret == 0) {
  19824. /* Store parameters for use in signature verification. */
  19825. cert->sigParamsIndex =
  19826. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  19827. cert->sigParamsLength = sigAlgParamsSz;
  19828. }
  19829. }
  19830. #endif
  19831. }
  19832. if ((ret == 0) && (!done)) {
  19833. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  19834. if (stopAfterPubKey) {
  19835. /* Return any bad date error through badDateRed and return offset
  19836. * after subjectPublicKeyInfo.
  19837. */
  19838. if (badDateRet != NULL) {
  19839. *badDateRet = badDate;
  19840. }
  19841. done = 1;
  19842. }
  19843. }
  19844. if ((ret == 0) && (!done) &&
  19845. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  19846. #ifndef ALLOW_V1_EXTENSIONS
  19847. /* Certificate extensions were only defined in version 2. */
  19848. if (cert->version < 2) {
  19849. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  19850. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  19851. ret = ASN_VERSION_E;
  19852. }
  19853. #endif
  19854. if (ret == 0) {
  19855. /* Save references to extension data. */
  19856. cert->extensions = GetASNItem_Addr(
  19857. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  19858. cert->extensionsSz = (int)GetASNItem_Length(
  19859. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  19860. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  19861. /* Advance past extensions. */
  19862. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  19863. }
  19864. }
  19865. /* Dispose of memory before allocating for extension decoding. */
  19866. FREE_ASNGETDATA(dataASN, cert->heap);
  19867. if ((ret == 0) && (issuer != NULL)) {
  19868. idx = 0;
  19869. /* Put issuer into cert and calculate hash. */
  19870. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  19871. &idx, issuerSz);
  19872. }
  19873. if ((ret == 0) && (subject != NULL)) {
  19874. idx = 0;
  19875. /* Put subject into cert and calculate hash. */
  19876. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19877. subject, &idx, subjectSz);
  19878. }
  19879. if (ret == 0) {
  19880. /* Determine if self signed by comparing issuer and subject hashes. */
  19881. #ifdef WOLFSSL_CERT_REQ
  19882. if (cert->isCSR) {
  19883. cert->selfSigned = 1;
  19884. }
  19885. else
  19886. #endif
  19887. {
  19888. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  19889. KEYID_SIZE) == 0);
  19890. }
  19891. if (stopAtPubKey) {
  19892. ret = (int)pubKeyOffset;
  19893. }
  19894. }
  19895. if ((ret == 0) && (!stopAtPubKey)) {
  19896. /* Parse the public key. */
  19897. idx = pubKeyOffset;
  19898. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  19899. }
  19900. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  19901. (cert->extensions != NULL)) {
  19902. /* Decode the extension data starting at [3]. */
  19903. ret = DecodeCertExtensions(cert);
  19904. if (criticalExt != NULL) {
  19905. if (ret == ASN_CRIT_EXT_E) {
  19906. /* Return critical extension not recognized. */
  19907. *criticalExt = ret;
  19908. ret = 0;
  19909. }
  19910. else {
  19911. /* No critical extension error. */
  19912. *criticalExt = 0;
  19913. }
  19914. }
  19915. }
  19916. if ((ret == 0) && (!done) && (badDate != 0)) {
  19917. /* Parsed whole certificate fine but return any date errors. */
  19918. ret = badDate;
  19919. }
  19920. return ret;
  19921. }
  19922. /* Decode BER/DER data into certificate object.
  19923. *
  19924. * BER/DER data information held in source, srcIdx and maxIdx fields of
  19925. * certificate object.
  19926. *
  19927. * @param [in] cert Decoded certificate object.
  19928. * @param [in] verify Whether to find CA and verify certificate.
  19929. * @param [in] criticalExt Any error for critical extensions not recognized.
  19930. * @return 0 on success.
  19931. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19932. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  19933. * @return ASN_DATE_SZ_E when time data is not supported.
  19934. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19935. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19936. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19937. * is invalid.
  19938. * @return BUFFER_E when data in buffer is too small.
  19939. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19940. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  19941. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19942. * non-zero length.
  19943. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19944. */
  19945. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  19946. {
  19947. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  19948. }
  19949. #ifdef WOLFSSL_CERT_REQ
  19950. /* ASN.1 template for certificate request Attribute.
  19951. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  19952. */
  19953. static const ASNItem reqAttrASN[] = {
  19954. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19955. /* type */
  19956. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  19957. /* values */
  19958. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  19959. };
  19960. enum {
  19961. REQATTRASN_IDX_SEQ = 0,
  19962. REQATTRASN_IDX_TYPE,
  19963. REQATTRASN_IDX_VALS
  19964. };
  19965. /* Number of items in ASN.1 template for certificate request Attribute. */
  19966. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  19967. /* ASN.1 template for a string choice. */
  19968. static const ASNItem strAttrASN[] = {
  19969. { 0, 0, 0, 0, 0 },
  19970. };
  19971. enum {
  19972. STRATTRASN_IDX_STR = 0
  19973. };
  19974. /* Number of items in ASN.1 template for a string choice. */
  19975. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  19976. /* ASN.1 choices for types for a string in an attribute. */
  19977. static const byte strAttrChoice[] = {
  19978. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  19979. };
  19980. /* Decode a certificate request attribute's value.
  19981. *
  19982. * @param [in] cert Certificate request object.
  19983. * @param [out] criticalExt Critical extension return code.
  19984. * @param [in] oid OID describing which attribute was found.
  19985. * @param [in] aIdx Index into certificate source to start parsing.
  19986. * @param [in] input Attribute value data.
  19987. * @param [in] maxIdx Maximum index to parse to.
  19988. * @return 0 on success.
  19989. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19990. * is invalid.
  19991. */
  19992. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  19993. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  19994. {
  19995. int ret = 0;
  19996. word32 idx = 0;
  19997. ASNGetData strDataASN[strAttrASN_Length];
  19998. switch (oid) {
  19999. case PKCS9_CONTENT_TYPE_OID:
  20000. /* Clear dynamic data and specify choices acceptable. */
  20001. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  20002. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  20003. /* Parse a string. */
  20004. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  20005. 1, input, &idx, maxIdx);
  20006. if (ret == 0) {
  20007. /* Store references to password data. */
  20008. cert->contentType =
  20009. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  20010. cert->contentTypeLen =
  20011. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  20012. }
  20013. break;
  20014. /* A password by which the entity may request certificate revocation.
  20015. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  20016. */
  20017. case CHALLENGE_PASSWORD_OID:
  20018. /* Clear dynamic data and specify choices acceptable. */
  20019. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  20020. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  20021. /* Parse a string. */
  20022. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  20023. 1, input, &idx, maxIdx);
  20024. if (ret == 0) {
  20025. /* Store references to password data. */
  20026. cert->cPwd =
  20027. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  20028. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  20029. data.ref.length;
  20030. }
  20031. break;
  20032. /* Requested serial number to issue with.
  20033. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  20034. * (References: ISO/IEC 9594-6:1997)
  20035. */
  20036. case SERIAL_NUMBER_OID:
  20037. /* Clear dynamic data and specify choices acceptable. */
  20038. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  20039. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  20040. /* Parse a string. */
  20041. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  20042. 1, input, &idx, maxIdx);
  20043. if (ret == 0) {
  20044. /* Store references to serial number. */
  20045. cert->sNum =
  20046. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  20047. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  20048. data.ref.length;
  20049. /* Store serial number if small enough. */
  20050. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  20051. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  20052. cert->serialSz = cert->sNumLen;
  20053. }
  20054. }
  20055. break;
  20056. case UNSTRUCTURED_NAME_OID:
  20057. /* Clear dynamic data and specify choices acceptable. */
  20058. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  20059. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  20060. /* Parse a string. */
  20061. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  20062. 1, input, &idx, maxIdx);
  20063. if (ret == 0) {
  20064. /* Store references to unstructured name. */
  20065. cert->unstructuredName =
  20066. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  20067. cert->unstructuredNameLen = (int)strDataASN[STRATTRASN_IDX_STR].
  20068. data.ref.length;
  20069. }
  20070. break;
  20071. /* Certificate extensions to be included in generated certificate.
  20072. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  20073. */
  20074. case EXTENSION_REQUEST_OID:
  20075. /* Store references to all extensions. */
  20076. cert->extensions = input;
  20077. cert->extensionsSz = (int)maxIdx;
  20078. cert->extensionsIdx = aIdx;
  20079. /* Decode and validate extensions. */
  20080. ret = DecodeCertExtensions(cert);
  20081. if (ret == ASN_CRIT_EXT_E) {
  20082. /* Return critical extension not recognized. */
  20083. *criticalExt = ret;
  20084. ret = 0;
  20085. }
  20086. else {
  20087. /* No critical extension error. */
  20088. *criticalExt = 0;
  20089. }
  20090. break;
  20091. default:
  20092. ret = ASN_PARSE_E;
  20093. break;
  20094. }
  20095. return ret;
  20096. }
  20097. /* Decode attributes of a BER encoded certificate request.
  20098. *
  20099. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  20100. *
  20101. * Outer sequence has been removed.
  20102. *
  20103. * @param [in] cert Certificate request object.
  20104. * @param [out] criticalExt Critical extension return code.
  20105. * @param [in] idx Index into certificate source to start parsing.
  20106. * @param [in] maxIdx Maximum index to parse to.
  20107. * @return 0 on success.
  20108. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  20109. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  20110. * is invalid.
  20111. * @return BUFFER_E when data in buffer is too small.
  20112. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  20113. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  20114. * non-zero length.
  20115. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  20116. */
  20117. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  20118. word32 idx, word32 maxIdx)
  20119. {
  20120. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  20121. int ret = 0;
  20122. WOLFSSL_ENTER("DecodeCertReqAttributes");
  20123. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  20124. /* Parse each attribute until all data used up. */
  20125. while ((ret == 0) && (idx < maxIdx)) {
  20126. /* Clear dynamic data. */
  20127. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  20128. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  20129. /* Parse an attribute. */
  20130. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  20131. cert->source, &idx, maxIdx);
  20132. /* idx is now at end of attribute data. */
  20133. if (ret == 0) {
  20134. ret = DecodeCertReqAttrValue(cert, criticalExt,
  20135. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  20136. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  20137. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  20138. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  20139. }
  20140. }
  20141. FREE_ASNGETDATA(dataASN, cert->heap);
  20142. return ret;
  20143. }
  20144. /* ASN.1 template for a certificate request.
  20145. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  20146. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  20147. */
  20148. static const ASNItem certReqASN[] = {
  20149. /* CertificationRequest */
  20150. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  20151. /* CertificationRequestInfo */
  20152. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20153. /* version INTEGER { v1(0), v2(1), v3(2) */
  20154. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  20155. /* subject Name */
  20156. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  20157. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  20158. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  20159. /* algorithm AlgorithmIdentifier */
  20160. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  20161. /* Algorithm OBJECT IDENTIFIER */
  20162. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  20163. /* parameters ANY defined by algorithm OPTIONAL */
  20164. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  20165. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  20166. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  20167. /* subjectPublicKey BIT STRING */
  20168. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  20169. /* attributes [0] Attributes */
  20170. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  20171. /* signatureAlgorithm AlgorithmIdentifier */
  20172. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20173. /* Algorithm OBJECT IDENTIFIER */
  20174. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20175. /* parameters ANY defined by algorithm OPTIONAL */
  20176. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  20177. /* signature BIT STRING */
  20178. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  20179. };
  20180. enum {
  20181. CERTREQASN_IDX_SEQ = 0,
  20182. CERTREQASN_IDX_INFO_SEQ,
  20183. CERTREQASN_IDX_INFO_VER,
  20184. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  20185. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  20186. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  20187. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  20188. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  20189. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  20190. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  20191. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  20192. CERTREQASN_IDX_INFO_ATTRS,
  20193. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  20194. CERTREQASN_IDX_INFO_SIGALGO_OID,
  20195. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  20196. CERTREQASN_IDX_INFO_SIGNATURE
  20197. };
  20198. /* Number of items in ASN.1 template for a certificate request. */
  20199. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  20200. /* Parse BER encoded certificate request.
  20201. *
  20202. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  20203. *
  20204. * @param [in] cert Certificate request object.
  20205. * @param [out] criticalExt Critical extension return code.
  20206. * @return 0 on success.
  20207. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  20208. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  20209. * is invalid.
  20210. * @return BUFFER_E when data in buffer is too small.
  20211. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  20212. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  20213. * non-zero length.
  20214. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  20215. * @return MEMORY_E on dynamic memory allocation failure.
  20216. */
  20217. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  20218. {
  20219. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  20220. int ret = 0;
  20221. byte version;
  20222. word32 idx;
  20223. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  20224. if (ret == 0) {
  20225. /* Default version is 0. */
  20226. version = 0;
  20227. /* Set version var and OID types to expect. */
  20228. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  20229. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  20230. oidKeyType);
  20231. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  20232. oidCurveType);
  20233. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  20234. /* Parse a certificate request. */
  20235. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  20236. cert->source, &cert->srcIdx, cert->maxIdx);
  20237. }
  20238. /* Check version is valid/supported - can't be negative. */
  20239. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  20240. WOLFSSL_MSG("Unexpected certificate request version");
  20241. ret = ASN_PARSE_E;
  20242. }
  20243. if (ret == 0) {
  20244. /* Set fields of certificate request. */
  20245. cert->version = version;
  20246. cert->signatureOID =
  20247. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  20248. cert->keyOID =
  20249. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  20250. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  20251. /* Parse the subject name. */
  20252. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  20253. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  20254. cert->source, &idx,
  20255. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  20256. }
  20257. if (ret == 0) {
  20258. /* Parse the certificate request Attributes. */
  20259. ret = DecodeCertReqAttributes(cert, criticalExt,
  20260. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  20261. cert->source),
  20262. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  20263. }
  20264. if (ret == 0) {
  20265. /* Parse the certificate request's key. */
  20266. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  20267. ret = GetCertKey(cert, cert->source, &idx,
  20268. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  20269. }
  20270. if (ret == 0) {
  20271. /* Store references to signature. */
  20272. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  20273. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  20274. &cert->signature, &cert->sigLength);
  20275. }
  20276. FREE_ASNGETDATA(dataASN, cert->heap);
  20277. return ret;
  20278. }
  20279. #endif /* WOLFSSL_CERT_REQ */
  20280. #endif
  20281. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  20282. {
  20283. int ret;
  20284. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  20285. defined(WOLFSSL_DYN_CERT)
  20286. char* ptr;
  20287. #endif
  20288. ret = ParseCertRelative(cert, type, verify, cm);
  20289. if (ret < 0)
  20290. return ret;
  20291. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  20292. defined(WOLFSSL_DYN_CERT)
  20293. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defined */
  20294. if (cert->subjectCNLen > 0) {
  20295. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  20296. DYNAMIC_TYPE_SUBJECT_CN);
  20297. if (ptr == NULL)
  20298. return MEMORY_E;
  20299. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  20300. ptr[cert->subjectCNLen] = '\0';
  20301. cert->subjectCN = ptr;
  20302. cert->subjectCNStored = 1;
  20303. }
  20304. #endif
  20305. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  20306. defined(WOLFSSL_DYN_CERT)
  20307. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  20308. if ((cert->keyOID == RSAk
  20309. #ifdef WC_RSA_PSS
  20310. || cert->keyOID == RSAPSSk
  20311. #endif
  20312. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  20313. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  20314. DYNAMIC_TYPE_PUBLIC_KEY);
  20315. if (ptr == NULL)
  20316. return MEMORY_E;
  20317. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  20318. cert->publicKey = (byte *)ptr;
  20319. cert->pubKeyStored = 1;
  20320. }
  20321. #endif
  20322. return ret;
  20323. }
  20324. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  20325. {
  20326. return ParseCert(cert, type, verify, cm);
  20327. }
  20328. #ifdef WOLFCRYPT_ONLY
  20329. /* dummy functions, not using wolfSSL so don't need actual ones */
  20330. Signer* GetCA(void* signers, byte* hash);
  20331. Signer* GetCA(void* signers, byte* hash)
  20332. {
  20333. (void)hash;
  20334. return (Signer*)signers;
  20335. }
  20336. #ifndef NO_SKID
  20337. Signer* GetCAByName(void* signers, byte* hash);
  20338. Signer* GetCAByName(void* signers, byte* hash)
  20339. {
  20340. (void)hash;
  20341. return (Signer*)signers;
  20342. }
  20343. #endif /* NO_SKID */
  20344. #ifdef WOLFSSL_AKID_NAME
  20345. Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
  20346. const byte* serial, word32 serialSz);
  20347. Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
  20348. const byte* serial, word32 serialSz)
  20349. {
  20350. (void)issuer;
  20351. (void)issuerSz;
  20352. (void)serial;
  20353. (void)serialSz;
  20354. return (Signer*)vp;
  20355. }
  20356. #endif
  20357. #endif /* WOLFCRYPT_ONLY */
  20358. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20359. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  20360. {
  20361. Signer* ca = NULL;
  20362. if (cert->extSubjKeyIdSet)
  20363. ca = GetCA(cm, cert->extSubjKeyId);
  20364. if (ca == NULL)
  20365. ca = GetCAByName(cm, cert->subjectHash);
  20366. if (ca) {
  20367. if ((ca->pubKeySize == cert->pubKeySize) &&
  20368. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  20369. return ca;
  20370. }
  20371. }
  20372. return NULL;
  20373. }
  20374. #endif
  20375. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  20376. #ifdef WOLFSSL_ASN_TEMPLATE
  20377. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  20378. *
  20379. * @param [in] input Input data.
  20380. * @param [in] maxIdx Maximum index for data.
  20381. * @param [in] sigOID Signature OID for determining hash algorithm.
  20382. * @param [out] hash Hash of AKI.
  20383. * @param [out] set Whether the hash buffer was set.
  20384. * @param [in] heap Dynamic memory allocation hint.
  20385. * @return 0 on success.
  20386. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  20387. * is invalid.
  20388. * @return MEMORY_E on dynamic memory allocation failure.
  20389. */
  20390. static int GetAKIHash(const byte* input, word32 maxIdx, word32 sigOID,
  20391. byte* hash, int* set, void* heap)
  20392. {
  20393. /* AKI and Certificate Extension ASN.1 templates are the same length. */
  20394. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  20395. int ret = 0;
  20396. word32 idx = 0;
  20397. word32 extEndIdx;
  20398. byte* extData;
  20399. word32 extDataSz;
  20400. byte critical;
  20401. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  20402. (void)heap;
  20403. extEndIdx = idx + maxIdx;
  20404. /* Step through each extension looking for AKI. */
  20405. while ((ret == 0) && (idx < extEndIdx)) {
  20406. /* Clear dynamic data and check for certificate extension type OIDs. */
  20407. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  20408. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  20409. /* Set criticality variable. */
  20410. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  20411. /* Parse an extension. */
  20412. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  20413. &idx, extEndIdx);
  20414. if (ret == 0) {
  20415. /* Get reference to extension data and move index on past this
  20416. * extension. */
  20417. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  20418. idx += extDataSz;
  20419. /* Check whether we have the AKI extension. */
  20420. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  20421. /* Clear dynamic data. */
  20422. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  20423. /* Start parsing extension data from the start. */
  20424. idx = 0;
  20425. /* Parse AKI extension data. */
  20426. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  20427. 1, extData, &idx, extDataSz);
  20428. if ((ret == 0) &&
  20429. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  20430. != NULL)) {
  20431. /* We parsed successfully and have data. */
  20432. *set = 1;
  20433. /* Get the hash or hash of the hash if wrong size. */
  20434. ret = GetHashId(
  20435. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  20436. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  20437. hash, HashIdAlg(sigOID));
  20438. }
  20439. break;
  20440. }
  20441. }
  20442. }
  20443. FREE_ASNGETDATA(dataASN, heap);
  20444. return ret;
  20445. }
  20446. #endif
  20447. /* Only quick step through the certificate to find fields that are then used
  20448. * in certificate signature verification.
  20449. * Must use the signature OID from the signed part of the certificate.
  20450. * Works also on certificate signing requests.
  20451. *
  20452. * This is only for minimizing dynamic memory usage during TLS certificate
  20453. * chain processing.
  20454. * Doesn't support:
  20455. * OCSP Only: alt lookup using subject and pub key w/o sig check
  20456. */
  20457. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  20458. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  20459. {
  20460. #ifndef WOLFSSL_ASN_TEMPLATE
  20461. #ifndef WOLFSSL_SMALL_STACK
  20462. SignatureCtx sigCtx[1];
  20463. #else
  20464. SignatureCtx* sigCtx;
  20465. #endif
  20466. byte hash[KEYID_SIZE];
  20467. Signer* ca = NULL;
  20468. word32 idx = 0;
  20469. int len;
  20470. word32 tbsCertIdx = 0;
  20471. word32 sigIndex = 0;
  20472. word32 signatureOID = 0;
  20473. word32 oid = 0;
  20474. word32 issuerIdx = 0;
  20475. word32 issuerSz = 0;
  20476. #ifndef NO_SKID
  20477. int extLen = 0;
  20478. word32 extIdx = 0;
  20479. word32 extEndIdx = 0;
  20480. int extAuthKeyIdSet = 0;
  20481. #endif
  20482. int ret = 0;
  20483. word32 localIdx;
  20484. byte tag;
  20485. const byte* sigParams = NULL;
  20486. word32 sigParamsSz = 0;
  20487. if (cert == NULL) {
  20488. return BAD_FUNC_ARG;
  20489. }
  20490. #ifdef WOLFSSL_SMALL_STACK
  20491. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  20492. if (sigCtx == NULL)
  20493. return MEMORY_E;
  20494. #endif
  20495. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  20496. /* Certificate SEQUENCE */
  20497. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20498. ret = ASN_PARSE_E;
  20499. if (ret == 0) {
  20500. tbsCertIdx = idx;
  20501. /* TBSCertificate SEQUENCE */
  20502. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20503. ret = ASN_PARSE_E;
  20504. }
  20505. if (ret == 0) {
  20506. sigIndex = len + idx;
  20507. if ((idx + 1) > certSz)
  20508. ret = BUFFER_E;
  20509. }
  20510. if (ret == 0) {
  20511. /* version - optional */
  20512. localIdx = idx;
  20513. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  20514. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  20515. idx++;
  20516. if (GetLength(cert, &idx, &len, certSz) < 0)
  20517. ret = ASN_PARSE_E;
  20518. idx += len;
  20519. }
  20520. }
  20521. }
  20522. if (ret == 0) {
  20523. /* serialNumber */
  20524. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  20525. ret = ASN_PARSE_E;
  20526. }
  20527. if (ret == 0) {
  20528. idx += len;
  20529. /* signature */
  20530. if (!req) {
  20531. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  20532. ret = ASN_PARSE_E;
  20533. #ifdef WC_RSA_PSS
  20534. else if (signatureOID == CTC_RSASSAPSS) {
  20535. int start = idx;
  20536. sigParams = cert + idx;
  20537. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20538. ret = ASN_PARSE_E;
  20539. if (ret == 0) {
  20540. idx += len;
  20541. sigParamsSz = idx - start;
  20542. }
  20543. }
  20544. #endif
  20545. }
  20546. }
  20547. if (ret == 0) {
  20548. issuerIdx = idx;
  20549. /* issuer for cert or subject for csr */
  20550. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20551. ret = ASN_PARSE_E;
  20552. }
  20553. if (ret == 0) {
  20554. issuerSz = len + idx - issuerIdx;
  20555. }
  20556. #ifndef NO_SKID
  20557. if (!req && ret == 0) {
  20558. idx += len;
  20559. /* validity */
  20560. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20561. ret = ASN_PARSE_E;
  20562. }
  20563. if (!req && ret == 0) {
  20564. idx += len;
  20565. /* subject */
  20566. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20567. ret = ASN_PARSE_E;
  20568. }
  20569. if (ret == 0) {
  20570. idx += len;
  20571. /* subjectPublicKeyInfo */
  20572. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20573. ret = ASN_PARSE_E;
  20574. }
  20575. if (req && ret == 0) {
  20576. idx += len;
  20577. /* attributes */
  20578. if (GetASNHeader_ex(cert,
  20579. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  20580. &len, certSz, 1) < 0)
  20581. ret = ASN_PARSE_E;
  20582. }
  20583. if (!req) {
  20584. if (ret == 0) {
  20585. idx += len;
  20586. if ((idx + 1) > certSz)
  20587. ret = BUFFER_E;
  20588. }
  20589. if (ret == 0) {
  20590. /* issuerUniqueID - optional */
  20591. localIdx = idx;
  20592. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  20593. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  20594. idx++;
  20595. if (GetLength(cert, &idx, &len, certSz) < 0)
  20596. ret = ASN_PARSE_E;
  20597. idx += len;
  20598. }
  20599. }
  20600. }
  20601. if (ret == 0) {
  20602. if ((idx + 1) > certSz)
  20603. ret = BUFFER_E;
  20604. }
  20605. if (ret == 0) {
  20606. /* subjectUniqueID - optional */
  20607. localIdx = idx;
  20608. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  20609. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  20610. idx++;
  20611. if (GetLength(cert, &idx, &len, certSz) < 0)
  20612. ret = ASN_PARSE_E;
  20613. idx += len;
  20614. }
  20615. }
  20616. }
  20617. if (ret == 0) {
  20618. if ((idx + 1) > certSz)
  20619. ret = BUFFER_E;
  20620. }
  20621. /* extensions - optional */
  20622. localIdx = idx;
  20623. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  20624. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  20625. idx++;
  20626. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  20627. ret = ASN_PARSE_E;
  20628. if (ret == 0) {
  20629. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  20630. ret = ASN_PARSE_E;
  20631. }
  20632. if (ret == 0) {
  20633. extEndIdx = idx + extLen;
  20634. /* Check each extension for the ones we want. */
  20635. while (ret == 0 && idx < extEndIdx) {
  20636. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20637. ret = ASN_PARSE_E;
  20638. if (ret == 0) {
  20639. extIdx = idx;
  20640. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  20641. certSz) < 0) {
  20642. ret = ASN_PARSE_E;
  20643. }
  20644. if (ret == 0) {
  20645. if ((extIdx + 1) > certSz)
  20646. ret = BUFFER_E;
  20647. }
  20648. }
  20649. if (ret == 0) {
  20650. localIdx = extIdx;
  20651. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  20652. tag == ASN_BOOLEAN) {
  20653. if (GetBoolean(cert, &extIdx, certSz) < 0)
  20654. ret = ASN_PARSE_E;
  20655. }
  20656. }
  20657. if (ret == 0) {
  20658. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  20659. ret = ASN_PARSE_E;
  20660. }
  20661. if (ret == 0) {
  20662. switch (oid) {
  20663. case AUTH_KEY_OID:
  20664. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  20665. ret = ASN_PARSE_E;
  20666. if (ret == 0 && (extIdx + 1) >= certSz)
  20667. ret = BUFFER_E;
  20668. if (ret == 0 &&
  20669. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  20670. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  20671. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  20672. ret = ASN_PARSE_E;
  20673. if (ret == 0) {
  20674. extAuthKeyIdSet = 1;
  20675. /* Get the hash or hash of the hash if wrong
  20676. * size. */
  20677. ret = GetHashId(cert + extIdx, extLen,
  20678. hash, HashIdAlg(signatureOID));
  20679. }
  20680. }
  20681. break;
  20682. default:
  20683. break;
  20684. }
  20685. }
  20686. idx += len;
  20687. }
  20688. }
  20689. }
  20690. }
  20691. else if (ret == 0) {
  20692. idx += len;
  20693. }
  20694. if (ret == 0 && pubKey == NULL) {
  20695. if (extAuthKeyIdSet)
  20696. ca = GetCA(cm, hash);
  20697. if (ca == NULL) {
  20698. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  20699. HashIdAlg(signatureOID));
  20700. if (ret == 0)
  20701. ca = GetCAByName(cm, hash);
  20702. }
  20703. }
  20704. #else
  20705. if (ret == 0 && pubKey == NULL) {
  20706. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  20707. HashIdAlg(signatureOID));
  20708. if (ret == 0)
  20709. ca = GetCA(cm, hash);
  20710. }
  20711. #endif /* !NO_SKID */
  20712. if (ca == NULL && pubKey == NULL)
  20713. ret = ASN_NO_SIGNER_E;
  20714. if (ret == 0) {
  20715. idx = sigIndex;
  20716. /* signatureAlgorithm */
  20717. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  20718. ret = ASN_PARSE_E;
  20719. #ifdef WC_RSA_PSS
  20720. else if (signatureOID == CTC_RSASSAPSS) {
  20721. word32 sz = idx;
  20722. const byte* params = cert + idx;
  20723. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20724. ret = ASN_PARSE_E;
  20725. if (ret == 0) {
  20726. idx += len;
  20727. sz = idx - sz;
  20728. if (req) {
  20729. if ((sz != sigParamsSz) ||
  20730. (XMEMCMP(sigParams, params, sz) != 0)) {
  20731. ret = ASN_PARSE_E;
  20732. }
  20733. }
  20734. else {
  20735. sigParams = params;
  20736. sigParamsSz = sz;
  20737. }
  20738. }
  20739. }
  20740. #endif
  20741. /* In CSR signature data is not present in body */
  20742. if (req)
  20743. signatureOID = oid;
  20744. }
  20745. if (ret == 0) {
  20746. if (oid != signatureOID)
  20747. ret = ASN_SIG_OID_E;
  20748. }
  20749. if (ret == 0) {
  20750. /* signatureValue */
  20751. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  20752. ret = ASN_PARSE_E;
  20753. }
  20754. if (ret == 0) {
  20755. if (pubKey != NULL) {
  20756. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  20757. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  20758. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  20759. }
  20760. else {
  20761. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  20762. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  20763. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  20764. sigParamsSz, NULL);
  20765. }
  20766. if (ret != 0) {
  20767. WOLFSSL_ERROR_VERBOSE(ret);
  20768. WOLFSSL_MSG("Confirm signature failed");
  20769. }
  20770. }
  20771. FreeSignatureCtx(sigCtx);
  20772. #ifdef WOLFSSL_SMALL_STACK
  20773. if (sigCtx != NULL)
  20774. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  20775. #endif
  20776. return ret;
  20777. #else /* WOLFSSL_ASN_TEMPLATE */
  20778. /* X509 ASN.1 template longer than Certificate Request template. */
  20779. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  20780. #ifndef WOLFSSL_SMALL_STACK
  20781. SignatureCtx sigCtx[1];
  20782. #else
  20783. SignatureCtx* sigCtx = NULL;
  20784. #endif
  20785. byte hash[KEYID_SIZE];
  20786. Signer* ca = NULL;
  20787. int ret = 0;
  20788. word32 idx = 0;
  20789. #ifndef NO_SKID
  20790. int extAuthKeyIdSet = 0;
  20791. #endif
  20792. const byte* tbs = NULL;
  20793. word32 tbsSz = 0;
  20794. #ifdef WC_RSA_PSS
  20795. const byte* tbsParams = NULL;
  20796. word32 tbsParamsSz = 0;
  20797. #endif
  20798. const byte* sig = NULL;
  20799. word32 sigSz = 0;
  20800. word32 sigOID = 0;
  20801. const byte* sigParams = NULL;
  20802. word32 sigParamsSz = 0;
  20803. const byte* caName = NULL;
  20804. word32 caNameLen = 0;
  20805. #ifndef NO_SKID
  20806. const byte* akiData = NULL;
  20807. word32 akiLen = 0;
  20808. #endif
  20809. (void)req;
  20810. (void)heap;
  20811. if (cert == NULL) {
  20812. ret = BAD_FUNC_ARG;
  20813. }
  20814. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  20815. if ((ret == 0) && (!req)) {
  20816. /* Clear dynamic data for certificate items. */
  20817. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  20818. /* Set OID types expected for signature and public key. */
  20819. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  20820. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  20821. oidKeyType);
  20822. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  20823. oidCurveType);
  20824. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  20825. /* Parse certificate. */
  20826. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  20827. &idx, certSz);
  20828. /* Check signature OIDs match. */
  20829. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  20830. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  20831. ret = ASN_SIG_OID_E;
  20832. }
  20833. /* Store the data for verification in the certificate. */
  20834. if (ret == 0) {
  20835. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  20836. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  20837. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  20838. cert);
  20839. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  20840. cert);
  20841. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  20842. #ifdef WC_RSA_PSS
  20843. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  20844. tbsParams =
  20845. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  20846. cert);
  20847. tbsParamsSz =
  20848. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  20849. cert);
  20850. }
  20851. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  20852. sigParams =
  20853. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20854. cert);
  20855. sigParamsSz =
  20856. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20857. cert);
  20858. }
  20859. #endif
  20860. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  20861. #ifdef WC_RSA_PSS
  20862. if (tbsParamsSz != sigParamsSz) {
  20863. ret = ASN_PARSE_E;
  20864. }
  20865. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  20866. ret = ASN_PARSE_E;
  20867. }
  20868. else if ((tbsParamsSz > 0) &&
  20869. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  20870. ret = ASN_PARSE_E;
  20871. }
  20872. #endif
  20873. }
  20874. }
  20875. else if (ret == 0) {
  20876. #ifndef WOLFSSL_CERT_REQ
  20877. ret = NOT_COMPILED_IN;
  20878. #else
  20879. /* Clear dynamic data for certificate request items. */
  20880. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  20881. /* Set OID types expected for signature and public key. */
  20882. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  20883. oidKeyType);
  20884. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  20885. oidCurveType);
  20886. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  20887. /* Parse certificate request. */
  20888. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  20889. &idx, certSz);
  20890. if (ret == 0) {
  20891. /* Store the data for verification in the certificate. */
  20892. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  20893. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  20894. caName = GetASNItem_Addr(
  20895. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20896. caNameLen = GetASNItem_Length(
  20897. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20898. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  20899. #ifdef WC_RSA_PSS
  20900. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20901. cert);
  20902. sigParamsSz =
  20903. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20904. cert);
  20905. #endif
  20906. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  20907. &sigSz);
  20908. }
  20909. #endif
  20910. }
  20911. #ifndef NO_SKID
  20912. if ((ret == 0) && (pubKey == NULL) && !req) {
  20913. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  20914. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  20915. }
  20916. #endif
  20917. FREE_ASNGETDATA(dataASN, heap);
  20918. /* If no public passed, then find the CA. */
  20919. if ((ret == 0) && (pubKey == NULL)) {
  20920. #ifndef NO_SKID
  20921. /* Find the AKI extension in list of extensions and get hash. */
  20922. if ((!req) && (akiData != NULL)) {
  20923. /* TODO: test case */
  20924. ret = GetAKIHash(akiData, akiLen, sigOID, hash, &extAuthKeyIdSet,
  20925. heap);
  20926. }
  20927. /* Get the CA by hash one was found. */
  20928. if (extAuthKeyIdSet) {
  20929. ca = GetCA(cm, hash);
  20930. }
  20931. if (ca == NULL)
  20932. #endif
  20933. {
  20934. /* Try hash of issuer name. */
  20935. ret = CalcHashId_ex(caName, caNameLen, hash, HashIdAlg(sigOID));
  20936. if (ret == 0) {
  20937. ca = GetCAByName(cm, hash);
  20938. }
  20939. }
  20940. if (ca != NULL) {
  20941. /* Extract public key information. */
  20942. pubKey = ca->publicKey;
  20943. pubKeySz = ca->pubKeySize;
  20944. pubKeyOID = (int)ca->keyOID;
  20945. }
  20946. else {
  20947. /* No public key to verify with. */
  20948. ret = ASN_NO_SIGNER_E;
  20949. }
  20950. }
  20951. if (ret == 0) {
  20952. #ifdef WOLFSSL_SMALL_STACK
  20953. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  20954. DYNAMIC_TYPE_SIGNATURE);
  20955. if (sigCtx == NULL) {
  20956. ret = MEMORY_E;
  20957. }
  20958. if (ret == 0)
  20959. #endif
  20960. {
  20961. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  20962. /* Check signature. */
  20963. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  20964. (word32)pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz,
  20965. NULL);
  20966. if (ret != 0) {
  20967. WOLFSSL_MSG("Confirm signature failed");
  20968. }
  20969. FreeSignatureCtx(sigCtx);
  20970. #ifdef WOLFSSL_SMALL_STACK
  20971. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  20972. #endif
  20973. }
  20974. }
  20975. return ret;
  20976. #endif /* WOLFSSL_ASN_TEMPLATE */
  20977. }
  20978. #ifdef OPENSSL_EXTRA
  20979. /* Call CheckCertSignature_ex using a public key buffer for verification
  20980. */
  20981. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20982. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20983. {
  20984. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20985. pubKey, pubKeySz, pubKeyOID, 0);
  20986. }
  20987. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  20988. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20989. {
  20990. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  20991. pubKeyOID);
  20992. }
  20993. #ifdef WOLFSSL_CERT_REQ
  20994. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20995. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20996. {
  20997. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20998. pubKey, pubKeySz, pubKeyOID, 1);
  20999. }
  21000. #endif /* WOLFSSL_CERT_REQ */
  21001. #endif /* OPENSSL_EXTRA */
  21002. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  21003. /* Call CheckCertSignature_ex using a certificate manager (cm)
  21004. */
  21005. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  21006. {
  21007. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  21008. }
  21009. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  21010. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  21011. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  21012. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  21013. /* ASN.1 DER decode instruction. */
  21014. typedef struct DecodeInstr {
  21015. /* Tag expected. */
  21016. byte tag;
  21017. /* Operation to perform: step in or go over */
  21018. byte op:1;
  21019. /* ASN.1 item is optional. */
  21020. byte optional:1;
  21021. } DecodeInstr;
  21022. /* Step into ASN.1 item. */
  21023. #define DECODE_INSTR_IN 0
  21024. /* Step over ASN.1 item. */
  21025. #define DECODE_INSTR_OVER 1
  21026. /* Get the public key data from the DER encoded X.509 certificate.
  21027. *
  21028. * Assumes data has previously been parsed for complete validity.
  21029. *
  21030. * @param [in] cert DER encoded X.509 certificate data.
  21031. * @param [in] certSz Length of DER encoding.
  21032. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  21033. * @param [out] pubKeySz Length of public key data in bytes.
  21034. * @return 0 on success.
  21035. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  21036. * @return ASN_PARSE_E when certificate encoding is invalid.
  21037. */
  21038. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  21039. const unsigned char** pubKey, word32* pubKeySz)
  21040. {
  21041. int ret = 0;
  21042. int l;
  21043. word32 o = 0;
  21044. int i;
  21045. static DecodeInstr ops[] = {
  21046. /* Outer SEQ */
  21047. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  21048. /* TBSCertificate: SEQ */
  21049. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  21050. /* Version: [0] */
  21051. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  21052. DECODE_INSTR_OVER, 1 },
  21053. /* CertificateSerialNumber: INT */
  21054. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  21055. /* AlgorithmIdentifier: SEQ */
  21056. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  21057. /* issuer: SEQ */
  21058. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  21059. /* Validity: SEQ */
  21060. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  21061. /* subject: SEQ */
  21062. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  21063. /* subjectPublicKeyInfo SEQ */
  21064. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  21065. /* AlgorithmIdentifier: SEQ */
  21066. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  21067. /* PublicKey: BIT_STRING */
  21068. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  21069. };
  21070. /* Validate parameters. */
  21071. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  21072. ret = BAD_FUNC_ARG;
  21073. }
  21074. /* Process each instruction to take us to public key data. */
  21075. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  21076. DecodeInstr op = ops[i];
  21077. /* Check the current ASN.1 item has the expected tag. */
  21078. if (cert[o] != op.tag) {
  21079. /* If not optional then error, otherwise skip op. */
  21080. if (!op.optional) {
  21081. ret = ASN_PARSE_E;
  21082. }
  21083. }
  21084. else {
  21085. /* Move past tag. */
  21086. o++;
  21087. /* Get the length of ASN.1 item and move past length encoding. */
  21088. if (GetLength(cert, &o, &l, certSz) < 0) {
  21089. ret = ASN_PARSE_E;
  21090. }
  21091. /* Skip data if required. */
  21092. else if (op.op == DECODE_INSTR_OVER) {
  21093. o += (word32)l;
  21094. }
  21095. }
  21096. }
  21097. if (ret == 0) {
  21098. /* Return the public key data and length.
  21099. * Skip first byte of BIT_STRING data: unused bits. */
  21100. *pubKey = cert + o + 1;
  21101. *pubKeySz = (word32)(l - 1);
  21102. }
  21103. return ret;
  21104. }
  21105. #endif
  21106. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  21107. {
  21108. int ret = 0;
  21109. #ifndef WOLFSSL_ASN_TEMPLATE
  21110. word32 confirmOID = 0;
  21111. #ifdef WOLFSSL_CERT_REQ
  21112. int len = 0;
  21113. #endif
  21114. #endif
  21115. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  21116. int idx = 0;
  21117. #endif
  21118. byte* sce_tsip_encRsaKeyIdx;
  21119. if (cert == NULL) {
  21120. return BAD_FUNC_ARG;
  21121. }
  21122. #ifdef WOLFSSL_CERT_REQ
  21123. if (type == CERTREQ_TYPE)
  21124. cert->isCSR = 1;
  21125. #endif
  21126. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  21127. #ifndef WOLFSSL_ASN_TEMPLATE
  21128. cert->badDate = 0;
  21129. cert->criticalExt = 0;
  21130. if ((ret = DecodeToKey(cert, verify)) < 0) {
  21131. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  21132. cert->badDate = ret;
  21133. if (verify == VERIFY_SKIP_DATE)
  21134. ret = 0;
  21135. }
  21136. else
  21137. return ret;
  21138. }
  21139. WOLFSSL_MSG("Parsed Past Key");
  21140. #if defined(HAVE_RPK)
  21141. if (cert->isRPK) {
  21142. return ret;
  21143. }
  21144. #endif /* HAVE_RPK */
  21145. #ifdef WOLFSSL_CERT_REQ
  21146. /* Read attributes */
  21147. if (cert->isCSR) {
  21148. if (GetASNHeader_ex(cert->source,
  21149. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  21150. &len, cert->maxIdx, 1) < 0) {
  21151. WOLFSSL_MSG("GetASNHeader_ex error");
  21152. return ASN_PARSE_E;
  21153. }
  21154. if (len) {
  21155. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  21156. word32 oid;
  21157. byte tag;
  21158. if (attrMaxIdx > cert->maxIdx) {
  21159. WOLFSSL_MSG("Attribute length greater than CSR length");
  21160. return ASN_PARSE_E;
  21161. }
  21162. while (cert->srcIdx < attrMaxIdx) {
  21163. /* Attributes have the structure:
  21164. * SEQ -> OID -> SET -> ATTRIBUTE */
  21165. if (GetSequence(cert->source, &cert->srcIdx, &len,
  21166. attrMaxIdx) < 0) {
  21167. WOLFSSL_MSG("attr GetSequence error");
  21168. return ASN_PARSE_E;
  21169. }
  21170. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  21171. oidCsrAttrType, attrMaxIdx) < 0) {
  21172. WOLFSSL_MSG("attr GetObjectId error");
  21173. return ASN_PARSE_E;
  21174. }
  21175. if (GetSet(cert->source, &cert->srcIdx, &len,
  21176. attrMaxIdx) < 0) {
  21177. WOLFSSL_MSG("attr GetSet error");
  21178. return ASN_PARSE_E;
  21179. }
  21180. switch (oid) {
  21181. case PKCS9_CONTENT_TYPE_OID:
  21182. if (GetHeader(cert->source, &tag,
  21183. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21184. WOLFSSL_MSG("attr GetHeader error");
  21185. return ASN_PARSE_E;
  21186. }
  21187. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  21188. tag != ASN_IA5_STRING) {
  21189. WOLFSSL_MSG("Unsupported attribute value format");
  21190. return ASN_PARSE_E;
  21191. }
  21192. cert->contentType = (char*)cert->source + cert->srcIdx;
  21193. cert->contentTypeLen = len;
  21194. cert->srcIdx += (word32)len;
  21195. break;
  21196. case CHALLENGE_PASSWORD_OID:
  21197. if (GetHeader(cert->source, &tag,
  21198. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21199. WOLFSSL_MSG("attr GetHeader error");
  21200. return ASN_PARSE_E;
  21201. }
  21202. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  21203. tag != ASN_IA5_STRING) {
  21204. WOLFSSL_MSG("Unsupported attribute value format");
  21205. return ASN_PARSE_E;
  21206. }
  21207. cert->cPwd = (char*)cert->source + cert->srcIdx;
  21208. cert->cPwdLen = len;
  21209. cert->srcIdx += (word32)len;
  21210. break;
  21211. case SERIAL_NUMBER_OID:
  21212. if (GetHeader(cert->source, &tag,
  21213. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21214. WOLFSSL_MSG("attr GetHeader error");
  21215. return ASN_PARSE_E;
  21216. }
  21217. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  21218. tag != ASN_IA5_STRING) {
  21219. WOLFSSL_MSG("Unsupported attribute value format");
  21220. return ASN_PARSE_E;
  21221. }
  21222. cert->sNum = (char*)cert->source + cert->srcIdx;
  21223. cert->sNumLen = len;
  21224. cert->srcIdx += (word32)len;
  21225. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  21226. XMEMCPY(cert->serial, cert->sNum,
  21227. (size_t)cert->sNumLen);
  21228. cert->serialSz = cert->sNumLen;
  21229. }
  21230. break;
  21231. case DNQUALIFIER_OID:
  21232. if (GetHeader(cert->source, &tag,
  21233. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21234. WOLFSSL_MSG("attr GetHeader error");
  21235. return ASN_PARSE_E;
  21236. }
  21237. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  21238. cert->dnQualifierLen = len;
  21239. cert->srcIdx += (word32)len;
  21240. break;
  21241. case INITIALS_OID:
  21242. if (GetHeader(cert->source, &tag,
  21243. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21244. WOLFSSL_MSG("attr GetHeader error");
  21245. return ASN_PARSE_E;
  21246. }
  21247. cert->initials = (char*)cert->source + cert->srcIdx;
  21248. cert->initialsLen = len;
  21249. cert->srcIdx += (word32)len;
  21250. break;
  21251. case SURNAME_OID:
  21252. if (GetHeader(cert->source, &tag,
  21253. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21254. WOLFSSL_MSG("attr GetHeader error");
  21255. return ASN_PARSE_E;
  21256. }
  21257. cert->surname = (char*)cert->source + cert->srcIdx;
  21258. cert->surnameLen = len;
  21259. cert->srcIdx += (word32)len;
  21260. break;
  21261. case GIVEN_NAME_OID:
  21262. if (GetHeader(cert->source, &tag,
  21263. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21264. WOLFSSL_MSG("attr GetHeader error");
  21265. return ASN_PARSE_E;
  21266. }
  21267. cert->givenName = (char*)cert->source + cert->srcIdx;
  21268. cert->givenNameLen = len;
  21269. cert->srcIdx += (word32)len;
  21270. break;
  21271. case UNSTRUCTURED_NAME_OID:
  21272. if (GetHeader(cert->source, &tag,
  21273. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  21274. WOLFSSL_MSG("attr GetHeader error");
  21275. return ASN_PARSE_E;
  21276. }
  21277. cert->unstructuredName =
  21278. (char*)cert->source + cert->srcIdx;
  21279. cert->unstructuredNameLen = len;
  21280. cert->srcIdx += (word32)len;
  21281. break;
  21282. case EXTENSION_REQUEST_OID:
  21283. /* save extensions */
  21284. cert->extensions = &cert->source[cert->srcIdx];
  21285. cert->extensionsSz = len;
  21286. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  21287. if ((ret = DecodeCertExtensions(cert)) < 0) {
  21288. if (ret == ASN_CRIT_EXT_E) {
  21289. cert->criticalExt = ret;
  21290. }
  21291. else {
  21292. return ret;
  21293. }
  21294. }
  21295. cert->srcIdx += (word32)len;
  21296. break;
  21297. default:
  21298. WOLFSSL_MSG("Unsupported attribute type");
  21299. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  21300. return ASN_PARSE_E;
  21301. }
  21302. }
  21303. }
  21304. }
  21305. #endif
  21306. if (cert->srcIdx < cert->sigIndex) {
  21307. #ifndef ALLOW_V1_EXTENSIONS
  21308. if (cert->version < 2) {
  21309. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  21310. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  21311. return ASN_VERSION_E;
  21312. }
  21313. #endif
  21314. /* save extensions */
  21315. cert->extensions = &cert->source[cert->srcIdx];
  21316. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  21317. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  21318. if ((ret = DecodeCertExtensions(cert)) < 0) {
  21319. if (ret == ASN_CRIT_EXT_E)
  21320. cert->criticalExt = ret;
  21321. else
  21322. return ret;
  21323. }
  21324. #ifdef HAVE_OCSP
  21325. if (verify == VERIFY_OCSP_CERT) {
  21326. /* trust for the lifetime of the responder's cert*/
  21327. if (cert->ocspNoCheckSet)
  21328. verify = VERIFY;
  21329. else
  21330. verify = VERIFY_OCSP;
  21331. }
  21332. #endif
  21333. /* advance past extensions */
  21334. cert->srcIdx = cert->sigIndex;
  21335. }
  21336. if ((ret = GetSigAlg(cert,
  21337. #ifdef WOLFSSL_CERT_REQ
  21338. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  21339. #else
  21340. &confirmOID,
  21341. #endif
  21342. cert->maxIdx)) < 0) {
  21343. return ret;
  21344. }
  21345. if ((ret = GetSignature(cert)) < 0) {
  21346. return ret;
  21347. }
  21348. if (confirmOID != cert->signatureOID
  21349. #ifdef WOLFSSL_CERT_REQ
  21350. && !cert->isCSR
  21351. #endif
  21352. ) {
  21353. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  21354. return ASN_SIG_OID_E;
  21355. }
  21356. #else
  21357. #ifdef WOLFSSL_CERT_REQ
  21358. if (cert->isCSR) {
  21359. ret = DecodeCertReq(cert, &cert->criticalExt);
  21360. if (ret < 0) {
  21361. return ret;
  21362. }
  21363. }
  21364. else
  21365. #endif
  21366. {
  21367. ret = DecodeCert(cert, verify, &cert->criticalExt);
  21368. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  21369. cert->badDate = ret;
  21370. if (verify == VERIFY_SKIP_DATE)
  21371. ret = 0;
  21372. }
  21373. else if (ret < 0) {
  21374. WOLFSSL_ERROR_VERBOSE(ret);
  21375. return ret;
  21376. }
  21377. #if defined(HAVE_RPK)
  21378. if (cert->isRPK) {
  21379. return ret;
  21380. }
  21381. #endif /* HAVE_RPK */
  21382. }
  21383. #endif
  21384. #ifndef ALLOW_INVALID_CERTSIGN
  21385. /* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.9
  21386. * If the cA boolean is not asserted, then the keyCertSign bit in the
  21387. * key usage extension MUST NOT be asserted. */
  21388. if (!cert->isCA && cert->extKeyUsageSet &&
  21389. (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  21390. WOLFSSL_ERROR_VERBOSE(KEYUSAGE_E);
  21391. return KEYUSAGE_E;
  21392. }
  21393. #endif
  21394. #ifndef NO_SKID
  21395. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  21396. cert->pubKeySize > 0) {
  21397. if (cert->signatureOID == CTC_SM3wSM2) {
  21398. /* TODO: GmSSL creates IDs this way but whole public key info
  21399. * block should be hashed. */
  21400. ret = CalcHashId_ex(cert->publicKey + cert->pubKeySize - 65, 65,
  21401. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  21402. }
  21403. else {
  21404. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  21405. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  21406. }
  21407. if (ret != 0) {
  21408. WOLFSSL_ERROR_VERBOSE(ret);
  21409. return ret;
  21410. }
  21411. }
  21412. #endif /* !NO_SKID */
  21413. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  21414. type != TRUSTED_PEER_TYPE)) {
  21415. cert->ca = NULL;
  21416. #ifndef NO_SKID
  21417. if (cert->extAuthKeyIdSet) {
  21418. cert->ca = GetCA(cm, cert->extAuthKeyId);
  21419. #ifdef WOLFSSL_AKID_NAME
  21420. if (cert->ca == NULL) {
  21421. cert->ca = GetCAByAKID(cm, cert->extAuthKeyIdIssuer,
  21422. cert->extAuthKeyIdIssuerSz, cert->extAuthKeyIdIssuerSN,
  21423. cert->extAuthKeyIdIssuerSNSz);
  21424. }
  21425. #endif
  21426. }
  21427. if (cert->ca == NULL && cert->extSubjKeyIdSet
  21428. && verify != VERIFY_OCSP) {
  21429. cert->ca = GetCA(cm, cert->extSubjKeyId);
  21430. }
  21431. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  21432. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  21433. cert->ca = NULL;
  21434. }
  21435. if (cert->ca == NULL) {
  21436. cert->ca = GetCAByName(cm, cert->issuerHash);
  21437. /* If AKID is available then this CA doesn't have the public
  21438. * key required */
  21439. if (cert->ca && cert->extAuthKeyIdSet) {
  21440. WOLFSSL_MSG("CA SKID doesn't match AKID");
  21441. cert->ca = NULL;
  21442. }
  21443. }
  21444. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  21445. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  21446. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  21447. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  21448. if (cert->ca) {
  21449. ret = 0; /* success */
  21450. goto exit_pcr;
  21451. }
  21452. }
  21453. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  21454. #else
  21455. cert->ca = GetCA(cm, cert->issuerHash);
  21456. #endif /* !NO_SKID */
  21457. if (cert->ca) {
  21458. WOLFSSL_MSG("CA found");
  21459. }
  21460. }
  21461. /* Set to WOLFSSL_MAX_PATH_LEN by default in InitDecodedCert_ex */
  21462. if (cert->pathLengthSet)
  21463. cert->maxPathLen = cert->pathLength;
  21464. if (!cert->selfSigned) {
  21465. /* Need to perform a pathlen check on anything that will be used
  21466. * to sign certificates later on. Otherwise, pathLen doesn't
  21467. * mean anything.
  21468. * Nothing to check if we don't have the issuer of this cert. */
  21469. if (type != CERT_TYPE && cert->isCA && cert->extKeyUsageSet &&
  21470. (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0 && cert->ca) {
  21471. if (cert->ca->maxPathLen == 0) {
  21472. /* This cert CAN NOT be used as an intermediate cert. The
  21473. * issuer does not allow it. */
  21474. cert->maxPathLen = 0;
  21475. if (verify != NO_VERIFY) {
  21476. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  21477. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  21478. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  21479. return ASN_PATHLEN_INV_E;
  21480. }
  21481. }
  21482. else {
  21483. cert->maxPathLen = (byte)min(cert->ca->maxPathLen - 1,
  21484. cert->maxPathLen);
  21485. }
  21486. }
  21487. }
  21488. #ifdef HAVE_OCSP
  21489. if (verify != NO_VERIFY && type != CA_TYPE &&
  21490. type != TRUSTED_PEER_TYPE) {
  21491. if (cert->ca) {
  21492. /* Need the CA's public key hash for OCSP */
  21493. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  21494. KEYID_SIZE);
  21495. }
  21496. }
  21497. #endif /* HAVE_OCSP */
  21498. }
  21499. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  21500. /* prepare for TSIP TLS cert verification API use */
  21501. if (cert->keyOID == RSAk) {
  21502. /* to call TSIP API, it needs keys position info in bytes */
  21503. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  21504. cert->pubKeySize,
  21505. &cert->sigCtx.CertAtt.pubkey_n_start,
  21506. &cert->sigCtx.CertAtt.pubkey_n_len,
  21507. &cert->sigCtx.CertAtt.pubkey_e_start,
  21508. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  21509. WOLFSSL_MSG("Decoding index from cert failed.");
  21510. return ret;
  21511. }
  21512. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  21513. }
  21514. else if (cert->keyOID == ECDSAk) {
  21515. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  21516. }
  21517. /* check if we can use TSIP for cert verification */
  21518. /* if the ca is verified as tsip root ca. */
  21519. /* TSIP can only handle 2048 bits(256 byte) key. */
  21520. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  21521. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  21522. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  21523. /* assign memory to encrypted tsip Rsa key index */
  21524. if (!cert->sce_tsip_encRsaKeyIdx)
  21525. cert->sce_tsip_encRsaKeyIdx =
  21526. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  21527. cert->heap, DYNAMIC_TYPE_RSA);
  21528. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  21529. return MEMORY_E;
  21530. }
  21531. else {
  21532. if (cert->ca) {
  21533. /* TSIP isn't usable */
  21534. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  21535. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  21536. "by TSIP.");
  21537. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  21538. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  21539. "RSA 2048.");
  21540. else
  21541. WOLFSSL_MSG("SCE-TSIP isn't usable");
  21542. }
  21543. cert->sce_tsip_encRsaKeyIdx = NULL;
  21544. }
  21545. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  21546. #else
  21547. sce_tsip_encRsaKeyIdx = NULL;
  21548. #endif
  21549. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  21550. if (cert->ca) {
  21551. if (verify == VERIFY || verify == VERIFY_OCSP ||
  21552. verify == VERIFY_SKIP_DATE) {
  21553. /* try to confirm/verify signature */
  21554. if ((ret = ConfirmSignature(&cert->sigCtx,
  21555. cert->source + cert->certBegin,
  21556. cert->sigIndex - cert->certBegin,
  21557. cert->ca->publicKey, cert->ca->pubKeySize,
  21558. cert->ca->keyOID, cert->signature,
  21559. cert->sigLength, cert->signatureOID,
  21560. #ifdef WC_RSA_PSS
  21561. cert->source + cert->sigParamsIndex,
  21562. cert->sigParamsLength,
  21563. #else
  21564. NULL, 0,
  21565. #endif
  21566. sce_tsip_encRsaKeyIdx)) != 0) {
  21567. if (ret != WC_PENDING_E) {
  21568. WOLFSSL_MSG("Confirm signature failed");
  21569. }
  21570. WOLFSSL_ERROR_VERBOSE(ret);
  21571. return ret;
  21572. }
  21573. }
  21574. #ifndef IGNORE_NAME_CONSTRAINTS
  21575. if (verify == VERIFY || verify == VERIFY_OCSP ||
  21576. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  21577. /* check that this cert's name is permitted by the signer's
  21578. * name constraints */
  21579. if (!ConfirmNameConstraints(cert->ca, cert)) {
  21580. WOLFSSL_MSG("Confirm name constraint failed");
  21581. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  21582. return ASN_NAME_INVALID_E;
  21583. }
  21584. }
  21585. #endif /* IGNORE_NAME_CONSTRAINTS */
  21586. }
  21587. #ifdef WOLFSSL_CERT_REQ
  21588. else if (type == CERTREQ_TYPE) {
  21589. if ((ret = ConfirmSignature(&cert->sigCtx,
  21590. cert->source + cert->certBegin,
  21591. cert->sigIndex - cert->certBegin,
  21592. cert->publicKey, cert->pubKeySize,
  21593. cert->keyOID, cert->signature,
  21594. cert->sigLength, cert->signatureOID,
  21595. #ifdef WC_RSA_PSS
  21596. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  21597. #else
  21598. NULL, 0,
  21599. #endif
  21600. sce_tsip_encRsaKeyIdx)) != 0) {
  21601. if (ret != WC_PENDING_E) {
  21602. WOLFSSL_MSG("Confirm signature failed");
  21603. }
  21604. WOLFSSL_ERROR_VERBOSE(ret);
  21605. return ret;
  21606. }
  21607. }
  21608. #endif
  21609. else {
  21610. /* no signer */
  21611. WOLFSSL_MSG("No CA signer to verify with");
  21612. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  21613. /* ret needs to be self-signer error for Qt compat */
  21614. if (cert->selfSigned) {
  21615. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  21616. return ASN_SELF_SIGNED_E;
  21617. }
  21618. else
  21619. #endif
  21620. {
  21621. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  21622. return ASN_NO_SIGNER_E;
  21623. }
  21624. }
  21625. }
  21626. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  21627. exit_pcr:
  21628. #endif
  21629. if (cert->badDate != 0) {
  21630. if (verify != VERIFY_SKIP_DATE) {
  21631. return cert->badDate;
  21632. }
  21633. WOLFSSL_MSG("Date error: Verify option is skipping");
  21634. }
  21635. if (cert->criticalExt != 0)
  21636. return cert->criticalExt;
  21637. return ret;
  21638. }
  21639. /* Create and init an new signer */
  21640. Signer* MakeSigner(void* heap)
  21641. {
  21642. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  21643. DYNAMIC_TYPE_SIGNER);
  21644. if (signer) {
  21645. XMEMSET(signer, 0, sizeof(Signer));
  21646. }
  21647. (void)heap;
  21648. return signer;
  21649. }
  21650. /* Free an individual signer.
  21651. *
  21652. * Used by Certificate Manager.
  21653. *
  21654. * @param [in, out] signer On in, signer object.
  21655. * On out, pointer is no longer valid.
  21656. * @param [in] heap Dynamic memory hint.
  21657. */
  21658. void FreeSigner(Signer* signer, void* heap)
  21659. {
  21660. (void)signer;
  21661. (void)heap;
  21662. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  21663. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  21664. #ifndef IGNORE_NAME_CONSTRAINTS
  21665. if (signer->permittedNames)
  21666. FreeNameSubtrees(signer->permittedNames, heap);
  21667. if (signer->excludedNames)
  21668. FreeNameSubtrees(signer->excludedNames, heap);
  21669. #endif
  21670. #ifdef WOLFSSL_SIGNER_DER_CERT
  21671. FreeDer(&signer->derCert);
  21672. #endif
  21673. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  21674. }
  21675. /* Free the whole singer table with number of rows.
  21676. *
  21677. * Each table entry is a linked list of signers.
  21678. * Used by Certificate Manager.
  21679. *
  21680. * @param [in, out] table Array of signer objects.
  21681. * @param [in] rows Number of entries in table.
  21682. * @param [in] heap Dynamic memory hint.
  21683. */
  21684. void FreeSignerTable(Signer** table, int rows, void* heap)
  21685. {
  21686. int i;
  21687. for (i = 0; i < rows; i++) {
  21688. Signer* signer = table[i];
  21689. while (signer) {
  21690. Signer* next = signer->next;
  21691. FreeSigner(signer, heap);
  21692. signer = next;
  21693. }
  21694. table[i] = NULL;
  21695. }
  21696. }
  21697. void FreeSignerTableType(Signer** table, int rows, byte type, void* heap)
  21698. {
  21699. int i;
  21700. for (i = 0; i < rows; i++) {
  21701. Signer* signer = table[i];
  21702. Signer** next = &table[i];
  21703. while (signer) {
  21704. if (signer->type == type) {
  21705. *next = signer->next;
  21706. FreeSigner(signer, heap);
  21707. signer = *next;
  21708. }
  21709. else {
  21710. next = &signer->next;
  21711. signer = signer->next;
  21712. }
  21713. }
  21714. }
  21715. }
  21716. #ifdef WOLFSSL_TRUST_PEER_CERT
  21717. /* Free an individual trusted peer cert.
  21718. *
  21719. * @param [in, out] tp Trusted peer certificate object.
  21720. * @param [in] heap Dynamic memory hint.
  21721. */
  21722. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  21723. {
  21724. if (tp == NULL) {
  21725. return;
  21726. }
  21727. if (tp->name) {
  21728. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  21729. }
  21730. if (tp->sig) {
  21731. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  21732. }
  21733. #ifndef IGNORE_NAME_CONSTRAINTS
  21734. if (tp->permittedNames)
  21735. FreeNameSubtrees(tp->permittedNames, heap);
  21736. if (tp->excludedNames)
  21737. FreeNameSubtrees(tp->excludedNames, heap);
  21738. #endif
  21739. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  21740. (void)heap;
  21741. }
  21742. /* Free the whole Trusted Peer linked list.
  21743. *
  21744. * Each table entry is a linked list of trusted peer certificates.
  21745. * Used by Certificate Manager.
  21746. *
  21747. * @param [in, out] table Array of trusted peer certificate objects.
  21748. * @param [in] rows Number of entries in table.
  21749. * @param [in] heap Dynamic memory hint.
  21750. */
  21751. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  21752. {
  21753. int i;
  21754. for (i = 0; i < rows; i++) {
  21755. TrustedPeerCert* tp = table[i];
  21756. while (tp) {
  21757. TrustedPeerCert* next = tp->next;
  21758. FreeTrustedPeer(tp, heap);
  21759. tp = next;
  21760. }
  21761. table[i] = NULL;
  21762. }
  21763. }
  21764. #endif /* WOLFSSL_TRUST_PEER_CERT */
  21765. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  21766. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  21767. word32 outputSz, int maxSnSz)
  21768. {
  21769. int i;
  21770. int snSzInt = (int)snSz;
  21771. if (sn == NULL || output == NULL || snSzInt < 0)
  21772. return BAD_FUNC_ARG;
  21773. /* remove leading zeros */
  21774. while (snSzInt > 0 && sn[0] == 0) {
  21775. snSzInt--;
  21776. sn++;
  21777. }
  21778. /* RFC 5280 - 4.1.2.2:
  21779. * Serial numbers must be a positive value (and not zero) */
  21780. if (snSzInt == 0) {
  21781. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  21782. return BAD_FUNC_ARG;
  21783. }
  21784. if (sn[0] & 0x80)
  21785. maxSnSz--;
  21786. /* truncate if input is too long */
  21787. if (snSzInt > maxSnSz)
  21788. snSzInt = maxSnSz;
  21789. i = SetASNInt(snSzInt, sn[0], NULL);
  21790. /* truncate if input is too long */
  21791. if (snSzInt > (int)outputSz - i)
  21792. snSzInt = (int)outputSz - i;
  21793. /* sanity check number of bytes to copy */
  21794. if (snSzInt <= 0) {
  21795. return BUFFER_E;
  21796. }
  21797. /* write out ASN.1 Integer */
  21798. (void)SetASNInt(snSzInt, sn[0], output);
  21799. XMEMCPY(output + i, sn, (size_t)snSzInt);
  21800. /* compute final length */
  21801. i += snSzInt;
  21802. return i;
  21803. }
  21804. #endif /* !WOLFSSL_ASN_TEMPLATE */
  21805. #endif /* !NO_CERTS */
  21806. #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \
  21807. (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT))
  21808. int SetMyVersion(word32 version, byte* output, int header)
  21809. {
  21810. int i = 0;
  21811. if (output == NULL)
  21812. return BAD_FUNC_ARG;
  21813. if (header) {
  21814. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  21815. output[i++] = 3;
  21816. }
  21817. output[i++] = ASN_INTEGER;
  21818. output[i++] = 0x01;
  21819. output[i++] = (byte)version;
  21820. return i;
  21821. }
  21822. #endif
  21823. #ifndef WOLFSSL_ASN_TEMPLATE
  21824. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  21825. byte* serial, int* serialSz, word32 maxIdx)
  21826. {
  21827. int result = 0;
  21828. int ret;
  21829. WOLFSSL_ENTER("wc_GetSerialNumber");
  21830. if (serial == NULL || input == NULL || serialSz == NULL) {
  21831. return BAD_FUNC_ARG;
  21832. }
  21833. /* First byte is ASN type */
  21834. if ((*inOutIdx+1) > maxIdx) {
  21835. WOLFSSL_MSG("Bad idx first");
  21836. return BUFFER_E;
  21837. }
  21838. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  21839. if (ret != 0)
  21840. return ret;
  21841. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  21842. WOLFSSL_MSG("Serial size bad");
  21843. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  21844. return ASN_PARSE_E;
  21845. }
  21846. /* return serial */
  21847. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  21848. *inOutIdx += (word32)*serialSz;
  21849. return result;
  21850. }
  21851. #endif
  21852. #ifndef NO_CERTS
  21853. /* TODO: consider moving PEM code out to a different file. */
  21854. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  21855. {
  21856. int ret = BAD_FUNC_ARG;
  21857. if (pDer) {
  21858. int dynType = 0;
  21859. DerBuffer* der;
  21860. /* Determine dynamic type */
  21861. switch (type) {
  21862. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  21863. case CHAIN_CERT_TYPE:
  21864. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  21865. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  21866. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  21867. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  21868. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  21869. default: dynType = DYNAMIC_TYPE_KEY; break;
  21870. }
  21871. /* Setup new buffer */
  21872. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  21873. if (*pDer == NULL) {
  21874. return MEMORY_E;
  21875. }
  21876. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  21877. der = *pDer;
  21878. der->type = type;
  21879. der->dynType = dynType; /* Cache this for FreeDer */
  21880. der->heap = heap;
  21881. der->buffer = (byte*)der + sizeof(DerBuffer);
  21882. der->length = length;
  21883. ret = 0; /* Success */
  21884. }
  21885. return ret;
  21886. }
  21887. void FreeDer(DerBuffer** pDer)
  21888. {
  21889. if (pDer && *pDer)
  21890. {
  21891. DerBuffer* der = (DerBuffer*)*pDer;
  21892. /* ForceZero private keys */
  21893. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  21894. ForceZero(der->buffer, der->length);
  21895. }
  21896. der->buffer = NULL;
  21897. der->length = 0;
  21898. XFREE(der, der->heap, der->dynType);
  21899. *pDer = NULL;
  21900. }
  21901. }
  21902. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  21903. {
  21904. return AllocDer(pDer, length, type, heap);
  21905. }
  21906. void wc_FreeDer(DerBuffer** pDer)
  21907. {
  21908. FreeDer(pDer);
  21909. }
  21910. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  21911. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  21912. updated to reflect maximum length and pem_struct_min_sz
  21913. to reflect minimum size */
  21914. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  21915. wcchar END_CERT = "-----END CERTIFICATE-----";
  21916. #ifdef WOLFSSL_CERT_REQ
  21917. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  21918. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  21919. #endif
  21920. #ifndef NO_DH
  21921. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  21922. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  21923. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  21924. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  21925. #endif
  21926. #ifndef NO_DSA
  21927. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  21928. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  21929. #endif
  21930. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  21931. wcchar END_X509_CRL = "-----END X509 CRL-----";
  21932. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  21933. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  21934. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  21935. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  21936. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  21937. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  21938. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  21939. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  21940. #ifdef HAVE_ECC
  21941. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  21942. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  21943. #ifdef OPENSSL_EXTRA
  21944. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  21945. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  21946. #endif
  21947. #endif
  21948. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21949. !defined(NO_DSA)
  21950. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  21951. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  21952. #endif
  21953. #ifdef OPENSSL_EXTRA
  21954. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  21955. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  21956. const char END_PRIV_KEY_PREFIX[] = "-----END";
  21957. #endif
  21958. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  21959. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  21960. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21961. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  21962. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  21963. #endif
  21964. #if defined(HAVE_PQC)
  21965. #if defined(HAVE_FALCON)
  21966. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  21967. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  21968. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  21969. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  21970. #endif /* HAVE_FALCON */
  21971. #if defined(HAVE_DILITHIUM)
  21972. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21973. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21974. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21975. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21976. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21977. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21978. #endif /* HAVE_DILITHIUM */
  21979. #if defined(HAVE_SPHINCS)
  21980. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21981. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21982. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21983. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21984. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21985. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21986. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21987. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21988. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21989. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21990. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21991. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21992. #endif /* HAVE_SPHINCS */
  21993. #endif /* HAVE_PQC */
  21994. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  21995. "-----END X509 CRL-----");
  21996. #ifdef WOLFSSL_PEM_TO_DER
  21997. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  21998. const char* endOfLine)
  21999. {
  22000. /* eat end of line characters */
  22001. while (line < endOfLine &&
  22002. (line[0] == '\r' || line[0] == '\n')) {
  22003. line++;
  22004. }
  22005. return line;
  22006. }
  22007. #endif
  22008. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  22009. {
  22010. int ret = BAD_FUNC_ARG;
  22011. switch (type) {
  22012. case CA_TYPE: /* same as below */
  22013. case TRUSTED_PEER_TYPE:
  22014. case CHAIN_CERT_TYPE:
  22015. case CERT_TYPE:
  22016. if (header) *header = BEGIN_CERT;
  22017. if (footer) *footer = END_CERT;
  22018. ret = 0;
  22019. break;
  22020. case CRL_TYPE:
  22021. if (header) *header = BEGIN_X509_CRL;
  22022. if (footer) *footer = END_X509_CRL;
  22023. ret = 0;
  22024. break;
  22025. #ifndef NO_DH
  22026. case DH_PARAM_TYPE:
  22027. if (header) *header = BEGIN_DH_PARAM;
  22028. if (footer) *footer = END_DH_PARAM;
  22029. ret = 0;
  22030. break;
  22031. case X942_PARAM_TYPE:
  22032. if (header) *header = BEGIN_X942_PARAM;
  22033. if (footer) *footer = END_X942_PARAM;
  22034. ret = 0;
  22035. break;
  22036. #endif
  22037. #ifndef NO_DSA
  22038. case DSA_PARAM_TYPE:
  22039. if (header) *header = BEGIN_DSA_PARAM;
  22040. if (footer) *footer = END_DSA_PARAM;
  22041. ret = 0;
  22042. break;
  22043. #endif
  22044. #ifdef WOLFSSL_CERT_REQ
  22045. case CERTREQ_TYPE:
  22046. if (header) *header = BEGIN_CERT_REQ;
  22047. if (footer) *footer = END_CERT_REQ;
  22048. ret = 0;
  22049. break;
  22050. #endif
  22051. #ifndef NO_DSA
  22052. case DSA_TYPE:
  22053. case DSA_PRIVATEKEY_TYPE:
  22054. if (header) *header = BEGIN_DSA_PRIV;
  22055. if (footer) *footer = END_DSA_PRIV;
  22056. ret = 0;
  22057. break;
  22058. #endif
  22059. #ifdef HAVE_ECC
  22060. case ECC_TYPE:
  22061. case ECC_PRIVATEKEY_TYPE:
  22062. if (header) *header = BEGIN_EC_PRIV;
  22063. if (footer) *footer = END_EC_PRIV;
  22064. ret = 0;
  22065. break;
  22066. #ifdef OPENSSL_EXTRA
  22067. case ECC_PARAM_TYPE:
  22068. if (header) *header = BEGIN_EC_PARAM;
  22069. if (footer) *footer = END_EC_PARAM;
  22070. ret = 0;
  22071. break;
  22072. #endif
  22073. #endif
  22074. case RSA_TYPE:
  22075. case PRIVATEKEY_TYPE:
  22076. #ifdef WOLFSSL_DUAL_ALG_CERTS
  22077. case ALT_PRIVATEKEY_TYPE:
  22078. #endif
  22079. if (header) *header = BEGIN_RSA_PRIV;
  22080. if (footer) *footer = END_RSA_PRIV;
  22081. ret = 0;
  22082. break;
  22083. #ifdef HAVE_ED25519
  22084. case ED25519_TYPE:
  22085. #endif
  22086. #ifdef HAVE_ED448
  22087. case ED448_TYPE:
  22088. #endif
  22089. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  22090. case EDDSA_PRIVATEKEY_TYPE:
  22091. if (header) *header = BEGIN_EDDSA_PRIV;
  22092. if (footer) *footer = END_EDDSA_PRIV;
  22093. ret = 0;
  22094. break;
  22095. #endif
  22096. #ifdef HAVE_PQC
  22097. #ifdef HAVE_FALCON
  22098. case FALCON_LEVEL1_TYPE:
  22099. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  22100. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  22101. ret = 0;
  22102. break;
  22103. case FALCON_LEVEL5_TYPE:
  22104. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  22105. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  22106. ret = 0;
  22107. break;
  22108. #endif /* HAVE_FALCON */
  22109. #ifdef HAVE_DILITHIUM
  22110. case DILITHIUM_LEVEL2_TYPE:
  22111. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  22112. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  22113. ret = 0;
  22114. break;
  22115. case DILITHIUM_LEVEL3_TYPE:
  22116. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  22117. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  22118. ret = 0;
  22119. break;
  22120. case DILITHIUM_LEVEL5_TYPE:
  22121. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  22122. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  22123. ret = 0;
  22124. break;
  22125. #endif /* HAVE_DILITHIUM */
  22126. #ifdef HAVE_SPHINCS
  22127. case SPHINCS_FAST_LEVEL1_TYPE:
  22128. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  22129. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  22130. ret = 0;
  22131. break;
  22132. case SPHINCS_FAST_LEVEL3_TYPE:
  22133. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  22134. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  22135. ret = 0;
  22136. break;
  22137. case SPHINCS_FAST_LEVEL5_TYPE:
  22138. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  22139. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  22140. ret = 0;
  22141. break;
  22142. case SPHINCS_SMALL_LEVEL1_TYPE:
  22143. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  22144. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  22145. ret = 0;
  22146. break;
  22147. case SPHINCS_SMALL_LEVEL3_TYPE:
  22148. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  22149. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  22150. ret = 0;
  22151. break;
  22152. case SPHINCS_SMALL_LEVEL5_TYPE:
  22153. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  22154. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  22155. ret = 0;
  22156. break;
  22157. #endif /* HAVE_SPHINCS */
  22158. #endif /* HAVE_PQC */
  22159. case PUBLICKEY_TYPE:
  22160. case ECC_PUBLICKEY_TYPE:
  22161. if (header) *header = BEGIN_PUB_KEY;
  22162. if (footer) *footer = END_PUB_KEY;
  22163. ret = 0;
  22164. break;
  22165. case RSA_PUBLICKEY_TYPE:
  22166. if (header) *header = BEGIN_RSA_PUB;
  22167. if (footer) *footer = END_RSA_PUB;
  22168. ret = 0;
  22169. break;
  22170. #ifndef NO_DH
  22171. case DH_PRIVATEKEY_TYPE:
  22172. #endif
  22173. case PKCS8_PRIVATEKEY_TYPE:
  22174. if (header) *header = BEGIN_PRIV_KEY;
  22175. if (footer) *footer = END_PRIV_KEY;
  22176. ret = 0;
  22177. break;
  22178. case PKCS8_ENC_PRIVATEKEY_TYPE:
  22179. if (header) *header = BEGIN_ENC_PRIV_KEY;
  22180. if (footer) *footer = END_ENC_PRIV_KEY;
  22181. ret = 0;
  22182. break;
  22183. default:
  22184. break;
  22185. }
  22186. return ret;
  22187. }
  22188. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22189. static wcchar kProcTypeHeader = "Proc-Type";
  22190. static wcchar kDecInfoHeader = "DEK-Info";
  22191. #ifdef WOLFSSL_PEM_TO_DER
  22192. #ifndef NO_DES3
  22193. static wcchar kEncTypeDes = "DES-CBC";
  22194. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  22195. #endif
  22196. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  22197. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  22198. #endif
  22199. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  22200. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  22201. #endif
  22202. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  22203. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  22204. #endif
  22205. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  22206. {
  22207. int ret = 0;
  22208. if (info == NULL || cipherInfo == NULL)
  22209. return BAD_FUNC_ARG;
  22210. /* determine cipher information */
  22211. #ifndef NO_DES3
  22212. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  22213. info->cipherType = WC_CIPHER_DES;
  22214. info->keySz = DES_KEY_SIZE;
  22215. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  22216. * block size. */
  22217. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  22218. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  22219. #else
  22220. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  22221. #endif
  22222. }
  22223. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  22224. info->cipherType = WC_CIPHER_DES3;
  22225. info->keySz = DES3_KEY_SIZE;
  22226. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  22227. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  22228. #else
  22229. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  22230. #endif
  22231. }
  22232. else
  22233. #endif /* !NO_DES3 */
  22234. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  22235. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  22236. info->cipherType = WC_CIPHER_AES_CBC;
  22237. info->keySz = AES_128_KEY_SIZE;
  22238. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  22239. }
  22240. else
  22241. #endif
  22242. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  22243. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  22244. info->cipherType = WC_CIPHER_AES_CBC;
  22245. info->keySz = AES_192_KEY_SIZE;
  22246. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  22247. }
  22248. else
  22249. #endif
  22250. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  22251. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  22252. info->cipherType = WC_CIPHER_AES_CBC;
  22253. info->keySz = AES_256_KEY_SIZE;
  22254. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  22255. }
  22256. else
  22257. #endif
  22258. {
  22259. ret = NOT_COMPILED_IN;
  22260. }
  22261. return ret;
  22262. }
  22263. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  22264. size_t bufSz)
  22265. {
  22266. int err = 0;
  22267. const char* bufferStart;
  22268. const char* bufferEnd;
  22269. char* line;
  22270. if (info == NULL || pBuffer == NULL || bufSz == 0)
  22271. return BAD_FUNC_ARG;
  22272. bufferStart = *pBuffer;
  22273. bufferEnd = bufferStart + bufSz;
  22274. /* find encrypted info marker */
  22275. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  22276. min((word32)bufSz, PEM_LINE_LEN));
  22277. if (line != NULL) {
  22278. word32 lineSz;
  22279. char* finish;
  22280. char* start;
  22281. word32 startSz;
  22282. const char* newline = NULL;
  22283. if (line >= bufferEnd) {
  22284. return BUFFER_E;
  22285. }
  22286. lineSz = (word32)(bufferEnd - line);
  22287. /* find DEC-Info marker */
  22288. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  22289. if (start == NULL)
  22290. return BUFFER_E;
  22291. /* skip dec-info and ": " */
  22292. start += XSTRLEN(kDecInfoHeader);
  22293. if (start >= bufferEnd)
  22294. return BUFFER_E;
  22295. if (start[0] == ':') {
  22296. start++;
  22297. if (start >= bufferEnd)
  22298. return BUFFER_E;
  22299. }
  22300. if (start[0] == ' ')
  22301. start++;
  22302. startSz = (word32)(bufferEnd - start);
  22303. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  22304. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  22305. word32 finishSz;
  22306. if (finish >= bufferEnd) {
  22307. return BUFFER_E;
  22308. }
  22309. finishSz = (word32)(bufferEnd - finish);
  22310. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  22311. /* get cipher name */
  22312. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  22313. return BUFFER_E;
  22314. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  22315. return BUFFER_E;
  22316. info->name[finish - start] = '\0'; /* null term */
  22317. /* populate info */
  22318. err = wc_EncryptedInfoGet(info, info->name);
  22319. if (err != 0)
  22320. return err;
  22321. /* get IV */
  22322. if (finishSz < info->ivSz + 1)
  22323. return BUFFER_E;
  22324. if (newline == NULL) {
  22325. newline = XSTRNSTR(finish, "\n", min(finishSz,
  22326. PEM_LINE_LEN));
  22327. }
  22328. if ((newline != NULL) && (newline > finish)) {
  22329. finish++;
  22330. info->ivSz = (word32)(newline - finish);
  22331. if (info->ivSz > IV_SZ)
  22332. return BUFFER_E;
  22333. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  22334. return BUFFER_E;
  22335. info->set = 1;
  22336. }
  22337. else
  22338. return BUFFER_E;
  22339. }
  22340. else
  22341. return BUFFER_E;
  22342. /* eat end of line characters */
  22343. newline = SkipEndOfLineChars(newline, bufferEnd);
  22344. /* return new headerEnd */
  22345. *pBuffer = newline;
  22346. }
  22347. return err;
  22348. }
  22349. #endif /* WOLFSSL_PEM_TO_DER */
  22350. #ifdef WOLFSSL_DER_TO_PEM
  22351. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  22352. {
  22353. if (cipherInfo != NULL) {
  22354. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  22355. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  22356. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  22357. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  22358. /* strncat's src length needs to include the NULL */
  22359. XSTRNCAT(dest, kProcTypeHeader, 10);
  22360. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  22361. XSTRNCAT(dest, kDecInfoHeader, 9);
  22362. XSTRNCAT(dest, ": ", 3);
  22363. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  22364. XSTRNCAT(dest, "\n\n", 4);
  22365. }
  22366. }
  22367. return 0;
  22368. }
  22369. #endif /* WOLFSSL_DER_TO_PEM */
  22370. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  22371. #ifdef WOLFSSL_DER_TO_PEM
  22372. /* Used for compatibility API */
  22373. WOLFSSL_ABI
  22374. int wc_DerToPem(const byte* der, word32 derSz,
  22375. byte* output, word32 outSz, int type)
  22376. {
  22377. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  22378. }
  22379. /* convert der buffer to pem into output, can't do inplace, der and output
  22380. need to be different */
  22381. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  22382. byte *cipher_info, int type)
  22383. {
  22384. const char* headerStr = NULL;
  22385. const char* footerStr = NULL;
  22386. #ifdef WOLFSSL_SMALL_STACK
  22387. char* header = NULL;
  22388. char* footer = NULL;
  22389. #else
  22390. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  22391. char footer[MAX_X509_HEADER_SZ];
  22392. #endif
  22393. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  22394. int footerLen = MAX_X509_HEADER_SZ;
  22395. int i;
  22396. int err;
  22397. int outLen; /* return length or error */
  22398. (void)cipher_info;
  22399. if (der == output) /* no in place conversion */
  22400. return BAD_FUNC_ARG;
  22401. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  22402. if (err != 0)
  22403. return err;
  22404. #ifdef WOLFSSL_SMALL_STACK
  22405. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22406. if (header == NULL)
  22407. return MEMORY_E;
  22408. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22409. if (footer == NULL) {
  22410. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22411. return MEMORY_E;
  22412. }
  22413. #endif
  22414. /* build header and footer based on type */
  22415. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  22416. header[headerLen - 2] = 0;
  22417. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  22418. footer[footerLen - 2] = 0;
  22419. /* add new line to end */
  22420. XSTRNCAT(header, "\n", 2);
  22421. XSTRNCAT(footer, "\n", 2);
  22422. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22423. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  22424. if (err != 0) {
  22425. #ifdef WOLFSSL_SMALL_STACK
  22426. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22427. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22428. #endif
  22429. return err;
  22430. }
  22431. #endif
  22432. headerLen = (int)XSTRLEN(header);
  22433. footerLen = (int)XSTRLEN(footer);
  22434. /* if null output and 0 size passed in then return size needed */
  22435. if (!output && outSz == 0) {
  22436. #ifdef WOLFSSL_SMALL_STACK
  22437. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22438. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22439. #endif
  22440. outLen = 0;
  22441. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  22442. != LENGTH_ONLY_E) {
  22443. WOLFSSL_ERROR_VERBOSE(err);
  22444. return err;
  22445. }
  22446. return headerLen + footerLen + outLen;
  22447. }
  22448. if (!der || !output) {
  22449. #ifdef WOLFSSL_SMALL_STACK
  22450. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22451. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22452. #endif
  22453. return BAD_FUNC_ARG;
  22454. }
  22455. /* don't even try if outSz too short */
  22456. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  22457. #ifdef WOLFSSL_SMALL_STACK
  22458. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22459. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22460. #endif
  22461. return BAD_FUNC_ARG;
  22462. }
  22463. /* header */
  22464. XMEMCPY(output, header, (size_t)headerLen);
  22465. i = headerLen;
  22466. #ifdef WOLFSSL_SMALL_STACK
  22467. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22468. #endif
  22469. /* body */
  22470. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  22471. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  22472. #ifdef WOLFSSL_SMALL_STACK
  22473. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22474. #endif
  22475. WOLFSSL_ERROR_VERBOSE(err);
  22476. return err;
  22477. }
  22478. i += outLen;
  22479. /* footer */
  22480. if ( (i + footerLen) > (int)outSz) {
  22481. #ifdef WOLFSSL_SMALL_STACK
  22482. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22483. #endif
  22484. return BAD_FUNC_ARG;
  22485. }
  22486. XMEMCPY(output + i, footer, (size_t)footerLen);
  22487. #ifdef WOLFSSL_SMALL_STACK
  22488. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22489. #endif
  22490. return outLen + headerLen + footerLen;
  22491. }
  22492. #endif /* WOLFSSL_DER_TO_PEM */
  22493. #ifdef WOLFSSL_PEM_TO_DER
  22494. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  22495. info->consumed tracks of PEM bytes consumed in case multiple parts */
  22496. int PemToDer(const unsigned char* buff, long longSz, int type,
  22497. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  22498. {
  22499. const char* header = NULL;
  22500. const char* footer = NULL;
  22501. const char* headerEnd;
  22502. const char* footerEnd;
  22503. const char* consumedEnd;
  22504. const char* bufferEnd = (const char*)(buff + longSz);
  22505. long neededSz;
  22506. int ret = 0;
  22507. word32 sz = (word32)longSz;
  22508. int encrypted_key = 0;
  22509. DerBuffer* der;
  22510. word32 algId = 0;
  22511. word32 idx;
  22512. #ifdef OPENSSL_EXTRA
  22513. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  22514. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  22515. #endif
  22516. WOLFSSL_ENTER("PemToDer");
  22517. /* get PEM header and footer based on type */
  22518. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  22519. if (ret != 0)
  22520. return ret;
  22521. /* map header if not found for type */
  22522. for (;;) {
  22523. headerEnd = XSTRNSTR((char*)buff, header, sz);
  22524. if (headerEnd) {
  22525. break;
  22526. }
  22527. if (type == PRIVATEKEY_TYPE
  22528. #ifdef WOLFSSL_DUAL_ALG_CERTS
  22529. || type == ALT_PRIVATEKEY_TYPE
  22530. #endif
  22531. ) {
  22532. if (header == BEGIN_RSA_PRIV) {
  22533. header = BEGIN_PRIV_KEY;
  22534. footer = END_PRIV_KEY;
  22535. }
  22536. else if (header == BEGIN_PRIV_KEY) {
  22537. header = BEGIN_ENC_PRIV_KEY;
  22538. footer = END_ENC_PRIV_KEY;
  22539. }
  22540. #ifdef HAVE_ECC
  22541. else if (header == BEGIN_ENC_PRIV_KEY) {
  22542. header = BEGIN_EC_PRIV;
  22543. footer = END_EC_PRIV;
  22544. }
  22545. else if (header == BEGIN_EC_PRIV) {
  22546. header = BEGIN_DSA_PRIV;
  22547. footer = END_DSA_PRIV;
  22548. }
  22549. #endif
  22550. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  22551. #ifdef HAVE_ECC
  22552. else if (header == BEGIN_DSA_PRIV) {
  22553. #else
  22554. else if (header == BEGIN_ENC_PRIV_KEY) {
  22555. #endif
  22556. header = BEGIN_EDDSA_PRIV;
  22557. footer = END_EDDSA_PRIV;
  22558. }
  22559. #endif
  22560. else {
  22561. #ifdef WOLF_PRIVATE_KEY_ID
  22562. /* allow loading a public key for use with crypto or PK callbacks */
  22563. type = PUBLICKEY_TYPE;
  22564. header = BEGIN_PUB_KEY;
  22565. footer = END_PUB_KEY;
  22566. #else
  22567. break;
  22568. #endif
  22569. }
  22570. }
  22571. else if (type == PUBLICKEY_TYPE) {
  22572. if (header == BEGIN_PUB_KEY) {
  22573. header = BEGIN_RSA_PUB;
  22574. footer = END_RSA_PUB;
  22575. }
  22576. else {
  22577. break;
  22578. }
  22579. }
  22580. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  22581. else if (type == ECC_PARAM_TYPE) {
  22582. if (header == BEGIN_EC_PARAM) {
  22583. header = BEGIN_EC_PARAM;
  22584. footer = END_EC_PARAM;
  22585. }
  22586. else {
  22587. break;
  22588. }
  22589. }
  22590. #endif
  22591. #ifdef HAVE_CRL
  22592. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  22593. header = BEGIN_X509_CRL;
  22594. footer = END_X509_CRL;
  22595. }
  22596. #endif
  22597. else {
  22598. break;
  22599. }
  22600. }
  22601. if (!headerEnd) {
  22602. #ifdef OPENSSL_EXTRA
  22603. if (type == PRIVATEKEY_TYPE
  22604. #ifdef WOLFSSL_DUAL_ALG_CERTS
  22605. || type == ALT_PRIVATEKEY_TYPE
  22606. #endif
  22607. ) {
  22608. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  22609. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  22610. if (headerEnd) {
  22611. const char* beginEnd;
  22612. unsigned int endLen;
  22613. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  22614. if (beginEnd >= (char*)buff + sz) {
  22615. return BUFFER_E;
  22616. }
  22617. /* back up to BEGIN_PRIV_KEY_PREFIX */
  22618. while (headerEnd > (char*)buff &&
  22619. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  22620. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  22621. *headerEnd != '\n') {
  22622. headerEnd--;
  22623. }
  22624. if (headerEnd <= (char*)buff ||
  22625. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  22626. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  22627. beginEnd - headerEnd > PEM_LINE_LEN) {
  22628. WOLFSSL_MSG("Couldn't find PEM header");
  22629. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  22630. return ASN_NO_PEM_HEADER;
  22631. }
  22632. /* headerEnd now points to beginning of header */
  22633. XMEMCPY(beginBuf, headerEnd, (size_t)(beginEnd - headerEnd));
  22634. beginBuf[beginEnd - headerEnd] = '\0';
  22635. /* look for matching footer */
  22636. footer = XSTRNSTR(beginEnd,
  22637. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  22638. (unsigned int)((char*)buff + sz - beginEnd));
  22639. if (!footer) {
  22640. WOLFSSL_MSG("Couldn't find PEM footer");
  22641. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  22642. return ASN_NO_PEM_HEADER;
  22643. }
  22644. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  22645. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  22646. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  22647. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  22648. WOLFSSL_MSG("Unexpected footer for PEM");
  22649. return BUFFER_E;
  22650. }
  22651. endLen = (unsigned int)((size_t)(beginEnd - headerEnd) -
  22652. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  22653. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  22654. XMEMCPY(endBuf, footer, (size_t)endLen);
  22655. endBuf[endLen] = '\0';
  22656. header = beginBuf;
  22657. footer = endBuf;
  22658. headerEnd = beginEnd;
  22659. }
  22660. }
  22661. if (!headerEnd) {
  22662. WOLFSSL_MSG("Couldn't find PEM header");
  22663. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  22664. return ASN_NO_PEM_HEADER;
  22665. }
  22666. #else
  22667. WOLFSSL_MSG("Couldn't find PEM header");
  22668. return ASN_NO_PEM_HEADER;
  22669. #endif
  22670. } else {
  22671. headerEnd += XSTRLEN(header);
  22672. }
  22673. /* eat end of line characters */
  22674. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  22675. if (keyFormat) {
  22676. /* keyFormat is Key_Sum enum */
  22677. if (type == PRIVATEKEY_TYPE
  22678. #ifdef WOLFSSL_DUAL_ALG_CERTS
  22679. || type == ALT_PRIVATEKEY_TYPE
  22680. #endif
  22681. ) {
  22682. #ifndef NO_RSA
  22683. if (header == BEGIN_RSA_PRIV)
  22684. *keyFormat = RSAk;
  22685. #endif
  22686. #ifdef HAVE_ECC
  22687. if (header == BEGIN_EC_PRIV)
  22688. *keyFormat = ECDSAk;
  22689. #endif
  22690. #ifndef NO_DSA
  22691. if (header == BEGIN_DSA_PRIV)
  22692. *keyFormat = DSAk;
  22693. #endif
  22694. }
  22695. #ifdef WOLF_PRIVATE_KEY_ID
  22696. else if (type == PUBLICKEY_TYPE) {
  22697. #ifndef NO_RSA
  22698. if (header == BEGIN_RSA_PUB)
  22699. *keyFormat = RSAk;
  22700. #endif
  22701. }
  22702. #endif
  22703. }
  22704. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22705. if (info) {
  22706. ret = wc_EncryptedInfoParse(info, &headerEnd,
  22707. (size_t)(bufferEnd - headerEnd));
  22708. if (ret < 0)
  22709. return ret;
  22710. if (info->set)
  22711. encrypted_key = 1;
  22712. }
  22713. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  22714. /* find footer */
  22715. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  22716. sz - headerEnd));
  22717. if (!footerEnd) {
  22718. if (info)
  22719. info->consumed = longSz; /* No more certs if no footer */
  22720. return BUFFER_E;
  22721. }
  22722. consumedEnd = footerEnd + XSTRLEN(footer);
  22723. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  22724. /* eat end of line characters */
  22725. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  22726. /* skip possible null term */
  22727. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  22728. consumedEnd++;
  22729. }
  22730. if (info)
  22731. info->consumed = (long)(consumedEnd - (const char*)buff);
  22732. /* set up der buffer */
  22733. neededSz = (long)(footerEnd - headerEnd);
  22734. if (neededSz > (long)sz || neededSz <= 0)
  22735. return BUFFER_E;
  22736. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  22737. if (ret < 0) {
  22738. return ret;
  22739. }
  22740. der = *pDer;
  22741. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  22742. der->buffer, &der->length) < 0) {
  22743. WOLFSSL_ERROR(BUFFER_E);
  22744. return BUFFER_E;
  22745. }
  22746. if ((header == BEGIN_PRIV_KEY
  22747. #ifdef OPENSSL_EXTRA
  22748. || header == beginBuf
  22749. #endif
  22750. #ifdef HAVE_ECC
  22751. || header == BEGIN_EC_PRIV
  22752. #endif
  22753. ) && !encrypted_key)
  22754. {
  22755. /* detect pkcs8 key and get alg type */
  22756. /* keep PKCS8 header */
  22757. idx = 0;
  22758. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  22759. if (ret > 0) {
  22760. if (keyFormat)
  22761. *keyFormat = (int)algId;
  22762. }
  22763. else {
  22764. /* ignore failure here and assume key is not pkcs8 wrapped */
  22765. }
  22766. return 0;
  22767. }
  22768. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22769. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  22770. int passwordSz = NAME_SZ;
  22771. #ifdef WOLFSSL_SMALL_STACK
  22772. char* password = NULL;
  22773. #else
  22774. char password[NAME_SZ];
  22775. #endif
  22776. if (!info || !info->passwd_cb) {
  22777. WOLFSSL_MSG("No password callback set");
  22778. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  22779. return NO_PASSWORD;
  22780. }
  22781. #ifdef WOLFSSL_SMALL_STACK
  22782. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  22783. if (password == NULL) {
  22784. return MEMORY_E;
  22785. }
  22786. #endif
  22787. /* get password */
  22788. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  22789. info->passwd_userdata);
  22790. if (ret >= 0) {
  22791. passwordSz = ret;
  22792. #ifdef WOLFSSL_CHECK_MEM_ZERO
  22793. wc_MemZero_Add("PEM password", password, passwordSz);
  22794. #endif
  22795. /* convert and adjust length */
  22796. if (header == BEGIN_ENC_PRIV_KEY) {
  22797. #ifndef NO_PWDBASED
  22798. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  22799. password, passwordSz);
  22800. if (ret > 0) {
  22801. /* update length by decrypted content */
  22802. der->length = (word32)ret;
  22803. idx = 0;
  22804. /* detect pkcs8 key and get alg type */
  22805. /* keep PKCS8 header */
  22806. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  22807. &algId);
  22808. if (ret >= 0) {
  22809. if (keyFormat)
  22810. *keyFormat = (int)algId;
  22811. ret = 0;
  22812. }
  22813. }
  22814. #else
  22815. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  22816. ret = NOT_COMPILED_IN;
  22817. #endif
  22818. }
  22819. /* decrypt the key */
  22820. else {
  22821. if (passwordSz == 0) {
  22822. /* The key is encrypted but does not have a password */
  22823. WOLFSSL_MSG("No password for encrypted key");
  22824. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  22825. ret = NO_PASSWORD;
  22826. }
  22827. else {
  22828. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  22829. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  22830. defined(HAVE_AES_DECRYPT))) && \
  22831. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  22832. int padVal = 0;
  22833. #endif
  22834. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  22835. (byte*)password, passwordSz, WC_MD5);
  22836. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  22837. #ifndef NO_DES3
  22838. if (info->cipherType == WC_CIPHER_DES3) {
  22839. /* Assuming there is padding:
  22840. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  22841. * (der->length % DES_BLOCK_SIZE) != 0)
  22842. * and assuming the last value signifies the number of
  22843. * padded bytes IE if last value is 0x08 then there are
  22844. * 8 bytes of padding:
  22845. * padVal = der->buffer[der->length-1];
  22846. * then strip this padding before proceeding:
  22847. * der->length -= padVal;
  22848. */
  22849. if (der->length > DES_BLOCK_SIZE &&
  22850. (der->length % DES_BLOCK_SIZE) != 0) {
  22851. padVal = der->buffer[der->length-1];
  22852. if (padVal < DES_BLOCK_SIZE) {
  22853. der->length -= (word32)padVal;
  22854. }
  22855. }
  22856. }
  22857. #endif /* !NO_DES3 */
  22858. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  22859. defined(HAVE_AES_DECRYPT)
  22860. if (info->cipherType == WC_CIPHER_AES_CBC) {
  22861. if (der->length > AES_BLOCK_SIZE) {
  22862. padVal = der->buffer[der->length-1];
  22863. if (padVal <= AES_BLOCK_SIZE) {
  22864. der->length -= (word32)padVal;
  22865. }
  22866. }
  22867. }
  22868. #endif
  22869. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  22870. }
  22871. }
  22872. #ifdef OPENSSL_EXTRA
  22873. if (ret) {
  22874. PEMerr(0, PEM_R_BAD_DECRYPT);
  22875. }
  22876. #endif
  22877. ForceZero(password, (word32)passwordSz);
  22878. }
  22879. #ifdef OPENSSL_EXTRA
  22880. else {
  22881. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  22882. }
  22883. #endif
  22884. #ifdef WOLFSSL_SMALL_STACK
  22885. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  22886. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  22887. wc_MemZero_Check(password, NAME_SZ);
  22888. #endif
  22889. }
  22890. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  22891. return ret;
  22892. }
  22893. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  22894. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  22895. {
  22896. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  22897. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  22898. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  22899. DerBuffer* der = *pDer;
  22900. /* if a PKCS8 key header exists remove it */
  22901. ret = ToTraditional(der->buffer, der->length);
  22902. if (ret > 0) {
  22903. der->length = (word32)ret;
  22904. }
  22905. ret = 0; /* ignore error removing PKCS8 header */
  22906. }
  22907. #endif
  22908. return ret;
  22909. }
  22910. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22911. /* our KeyPemToDer password callback, password in userData */
  22912. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  22913. {
  22914. (void)rw;
  22915. if (userdata == NULL)
  22916. return 0;
  22917. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  22918. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  22919. }
  22920. #endif
  22921. /* Return bytes written to buff or < 0 for error */
  22922. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  22923. unsigned char* buff, int buffSz, const char* pass)
  22924. {
  22925. int ret;
  22926. DerBuffer* der = NULL;
  22927. #ifdef WOLFSSL_SMALL_STACK
  22928. EncryptedInfo* info = NULL;
  22929. #else
  22930. EncryptedInfo info[1];
  22931. #endif
  22932. WOLFSSL_ENTER("wc_KeyPemToDer");
  22933. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22934. WOLFSSL_MSG("Bad pem der args");
  22935. return BAD_FUNC_ARG;
  22936. }
  22937. #ifdef WOLFSSL_SMALL_STACK
  22938. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  22939. DYNAMIC_TYPE_ENCRYPTEDINFO);
  22940. if (info == NULL)
  22941. return MEMORY_E;
  22942. #endif
  22943. XMEMSET(info, 0, sizeof(EncryptedInfo));
  22944. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22945. info->passwd_cb = KeyPemToDerPassCb;
  22946. info->passwd_userdata = (void*)pass;
  22947. #else
  22948. (void)pass;
  22949. #endif
  22950. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  22951. #ifdef WOLFSSL_SMALL_STACK
  22952. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  22953. #endif
  22954. if (ret < 0 || der == NULL) {
  22955. WOLFSSL_MSG("Bad Pem To Der");
  22956. }
  22957. else if (buff == NULL) {
  22958. WOLFSSL_MSG("Return needed der buff length");
  22959. ret = (int)der->length;
  22960. }
  22961. else if (der->length <= (word32)buffSz) {
  22962. XMEMCPY(buff, der->buffer, der->length);
  22963. ret = (int)der->length;
  22964. }
  22965. else {
  22966. WOLFSSL_MSG("Bad der length");
  22967. ret = BAD_FUNC_ARG;
  22968. }
  22969. FreeDer(&der);
  22970. return ret;
  22971. }
  22972. /* Return bytes written to buff or < 0 for error */
  22973. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  22974. unsigned char* buff, int buffSz, int type)
  22975. {
  22976. int ret;
  22977. DerBuffer* der = NULL;
  22978. WOLFSSL_ENTER("wc_CertPemToDer");
  22979. if (pem == NULL || buff == NULL || buffSz <= 0) {
  22980. WOLFSSL_MSG("Bad pem der args");
  22981. return BAD_FUNC_ARG;
  22982. }
  22983. if (type != CERT_TYPE && type != CHAIN_CERT_TYPE && type != CA_TYPE &&
  22984. type != CERTREQ_TYPE) {
  22985. WOLFSSL_MSG("Bad cert type");
  22986. return BAD_FUNC_ARG;
  22987. }
  22988. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  22989. if (ret < 0 || der == NULL) {
  22990. WOLFSSL_MSG("Bad Pem To Der");
  22991. }
  22992. else {
  22993. if (der->length <= (word32)buffSz) {
  22994. XMEMCPY(buff, der->buffer, der->length);
  22995. ret = (int)der->length;
  22996. }
  22997. else {
  22998. WOLFSSL_MSG("Bad der length");
  22999. ret = BAD_FUNC_ARG;
  23000. }
  23001. }
  23002. FreeDer(&der);
  23003. return ret;
  23004. }
  23005. #endif /* WOLFSSL_PEM_TO_DER */
  23006. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  23007. #ifdef WOLFSSL_PEM_TO_DER
  23008. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  23009. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  23010. zero for error */
  23011. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  23012. unsigned char* buff, int buffSz)
  23013. {
  23014. int ret;
  23015. DerBuffer* der = NULL;
  23016. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  23017. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  23018. WOLFSSL_MSG("Bad pem der args");
  23019. return BAD_FUNC_ARG;
  23020. }
  23021. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  23022. if (ret < 0 || der == NULL) {
  23023. WOLFSSL_MSG("Bad Pem To Der");
  23024. }
  23025. else if (buff == NULL) {
  23026. WOLFSSL_MSG("Return needed der buff length");
  23027. ret = (int)der->length;
  23028. }
  23029. else if (der->length <= (word32)buffSz) {
  23030. XMEMCPY(buff, der->buffer, der->length);
  23031. ret = (int)der->length;
  23032. }
  23033. else {
  23034. WOLFSSL_MSG("Bad der length");
  23035. ret = BAD_FUNC_ARG;
  23036. }
  23037. FreeDer(&der);
  23038. return ret;
  23039. }
  23040. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  23041. #endif /* WOLFSSL_PEM_TO_DER */
  23042. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  23043. #ifdef WOLFSSL_CERT_GEN
  23044. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  23045. {
  23046. #ifndef WOLFSSL_SMALL_STACK
  23047. byte staticBuffer[FILE_BUFFER_SIZE];
  23048. #endif
  23049. byte* fileBuf = NULL;
  23050. int ret = 0;
  23051. XFILE file = XBADFILE;
  23052. int dynamic = 0;
  23053. long sz = 0;
  23054. WOLFSSL_ENTER("wc_PemCertToDer");
  23055. if (fileName == NULL) {
  23056. ret = BAD_FUNC_ARG;
  23057. }
  23058. else {
  23059. file = XFOPEN(fileName, "rb");
  23060. if (file == XBADFILE) {
  23061. ret = IO_FAILED_E;
  23062. }
  23063. }
  23064. if (ret == 0) {
  23065. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  23066. ret = IO_FAILED_E;
  23067. }
  23068. }
  23069. if (ret == 0) {
  23070. sz = XFTELL(file);
  23071. if (sz <= 0) {
  23072. ret = IO_FAILED_E;
  23073. }
  23074. }
  23075. if (ret == 0) {
  23076. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  23077. ret = IO_FAILED_E;
  23078. }
  23079. }
  23080. if (ret == 0) {
  23081. #ifndef WOLFSSL_SMALL_STACK
  23082. if (sz <= (long)sizeof(staticBuffer))
  23083. fileBuf = staticBuffer;
  23084. else
  23085. #endif
  23086. {
  23087. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  23088. if (fileBuf == NULL)
  23089. ret = MEMORY_E;
  23090. else
  23091. dynamic = 1;
  23092. }
  23093. }
  23094. if (ret == 0) {
  23095. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  23096. ret = IO_FAILED_E;
  23097. }
  23098. else {
  23099. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  23100. }
  23101. }
  23102. if (file != XBADFILE)
  23103. XFCLOSE(file);
  23104. if (dynamic)
  23105. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  23106. return ret;
  23107. }
  23108. /* load pem cert from file into der buffer, return der size or error */
  23109. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  23110. {
  23111. int ret;
  23112. DerBuffer* converted = NULL;
  23113. ret = wc_PemCertToDer_ex(fileName, &converted);
  23114. if (ret == 0) {
  23115. if (converted->length < (word32)derSz) {
  23116. XMEMCPY(derBuf, converted->buffer, converted->length);
  23117. ret = (int)converted->length;
  23118. }
  23119. else
  23120. ret = BUFFER_E;
  23121. FreeDer(&converted);
  23122. }
  23123. return ret;
  23124. }
  23125. #endif /* WOLFSSL_CERT_GEN */
  23126. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  23127. /* load pem public key from file into der buffer, return der size or error */
  23128. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  23129. {
  23130. #ifndef WOLFSSL_SMALL_STACK
  23131. byte staticBuffer[FILE_BUFFER_SIZE];
  23132. #endif
  23133. byte* fileBuf = NULL;
  23134. int dynamic = 0;
  23135. int ret = 0;
  23136. long sz = 0;
  23137. XFILE file = XBADFILE;
  23138. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  23139. if (fileName == NULL) {
  23140. ret = BAD_FUNC_ARG;
  23141. }
  23142. else {
  23143. file = XFOPEN(fileName, "rb");
  23144. if (file == XBADFILE) {
  23145. ret = IO_FAILED_E;
  23146. }
  23147. }
  23148. if (ret == 0) {
  23149. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  23150. ret = IO_FAILED_E;
  23151. }
  23152. }
  23153. if (ret == 0) {
  23154. sz = XFTELL(file);
  23155. if (sz <= 0) {
  23156. ret = IO_FAILED_E;
  23157. }
  23158. }
  23159. if (ret == 0) {
  23160. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  23161. ret = IO_FAILED_E;
  23162. }
  23163. }
  23164. if (ret == 0) {
  23165. #ifndef WOLFSSL_SMALL_STACK
  23166. if (sz <= (long)sizeof(staticBuffer))
  23167. fileBuf = staticBuffer;
  23168. else
  23169. #endif
  23170. {
  23171. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  23172. if (fileBuf == NULL)
  23173. ret = MEMORY_E;
  23174. else
  23175. dynamic = 1;
  23176. }
  23177. }
  23178. if (ret == 0) {
  23179. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  23180. ret = BUFFER_E;
  23181. }
  23182. else {
  23183. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  23184. 0, NULL, NULL);
  23185. }
  23186. }
  23187. if (file != XBADFILE)
  23188. XFCLOSE(file);
  23189. if (dynamic)
  23190. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  23191. return ret;
  23192. }
  23193. /* load pem public key from file into der buffer, return der size or error */
  23194. int wc_PemPubKeyToDer(const char* fileName,
  23195. unsigned char* derBuf, int derSz)
  23196. {
  23197. int ret;
  23198. DerBuffer* converted = NULL;
  23199. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  23200. if (ret == 0) {
  23201. if (converted->length < (word32)derSz) {
  23202. XMEMCPY(derBuf, converted->buffer, converted->length);
  23203. ret = (int)converted->length;
  23204. }
  23205. else
  23206. ret = BUFFER_E;
  23207. FreeDer(&converted);
  23208. }
  23209. return ret;
  23210. }
  23211. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  23212. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  23213. /* Get public key in DER format from a populated DecodedCert struct.
  23214. *
  23215. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  23216. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  23217. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  23218. * wc_InitDecodedCert().
  23219. *
  23220. * cert - populated DecodedCert struct holding X.509 certificate
  23221. * derKey - output buffer to place DER/ASN.1 encoded public key
  23222. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  23223. * on return. If derKey is passed in as NULL, derKeySz
  23224. * will be set to required buffer size for public key
  23225. * and LENGTH_ONLY_E will be returned from function.
  23226. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  23227. * if derKey is NULL and returning length only.
  23228. */
  23229. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  23230. byte* derKey, word32* derKeySz)
  23231. {
  23232. int ret = 0;
  23233. /* derKey may be NULL to return length only */
  23234. if (cert == NULL || derKeySz == NULL ||
  23235. (derKey != NULL && *derKeySz == 0)) {
  23236. return BAD_FUNC_ARG;
  23237. }
  23238. if (cert->publicKey == NULL) {
  23239. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  23240. return BAD_FUNC_ARG;
  23241. }
  23242. /* if derKey is NULL, return required output buffer size in derKeySz */
  23243. if (derKey == NULL) {
  23244. *derKeySz = cert->pubKeySize;
  23245. ret = LENGTH_ONLY_E;
  23246. }
  23247. if (ret == 0) {
  23248. if (cert->pubKeySize > *derKeySz) {
  23249. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  23250. ret = BAD_FUNC_ARG;
  23251. }
  23252. else {
  23253. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  23254. *derKeySz = cert->pubKeySize;
  23255. }
  23256. }
  23257. return ret;
  23258. }
  23259. #ifdef WOLFSSL_FPKI
  23260. /* Search through list for first matching alt name of the same type
  23261. * If 'current' is null then the search starts at the head of the list
  23262. * otherwise the search starts from the node after 'current' alt name.
  23263. * Returns 0 on success
  23264. */
  23265. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  23266. DNS_entry* current)
  23267. {
  23268. DNS_entry* entry;
  23269. if (current == NULL) {
  23270. entry = cert->altNames;
  23271. }
  23272. else {
  23273. entry = current->next;
  23274. }
  23275. /* cycle through alt names to check for needed types */
  23276. while (entry != NULL) {
  23277. if (entry->type == nameType) {
  23278. break;
  23279. }
  23280. entry = entry->next;
  23281. }
  23282. return entry;
  23283. }
  23284. /* returns 0 on success */
  23285. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  23286. {
  23287. int ret = ALT_NAME_E;
  23288. DNS_entry* id = NULL;
  23289. do {
  23290. id = FindAltName(cert, ASN_URI_TYPE, id);
  23291. if (id != NULL) {
  23292. /* check if URI string matches expected format for UUID */
  23293. if (id->len != DEFAULT_UUID_SZ) {
  23294. continue; /* size not right not a UUID URI */
  23295. }
  23296. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  23297. continue; /* beginning text not right for a UUID URI */
  23298. }
  23299. if (uuid == NULL) {
  23300. *uuidSz = (word32)id->len;
  23301. return LENGTH_ONLY_E;
  23302. }
  23303. if ((int)*uuidSz < id->len) {
  23304. return BUFFER_E;
  23305. }
  23306. XMEMCPY(uuid, id->name, (size_t)id->len);
  23307. ret = 0; /* success */
  23308. break;
  23309. }
  23310. } while (id != NULL);
  23311. return ret;
  23312. }
  23313. /* returns 0 on success */
  23314. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  23315. {
  23316. int ret = ALT_NAME_E;
  23317. DNS_entry* id = NULL;
  23318. do {
  23319. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  23320. if (id != NULL && id->oidSum == FASCN_OID) {
  23321. if (fascn == NULL) {
  23322. *fascnSz = (word32)id->len;
  23323. return LENGTH_ONLY_E;
  23324. }
  23325. if ((int)*fascnSz < id->len) {
  23326. return BUFFER_E;
  23327. }
  23328. XMEMCPY(fascn, id->name, (size_t)id->len);
  23329. ret = 0; /* success */
  23330. }
  23331. } while (id != NULL);
  23332. return ret;
  23333. }
  23334. #endif /* WOLFSSL_FPKI */
  23335. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  23336. defined(WOLFSSL_KCAPI_RSA) || \
  23337. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA))))
  23338. /* USER RSA ifdef portions used instead of refactor in consideration for
  23339. possible fips build */
  23340. /* Encode a public RSA key to output.
  23341. *
  23342. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  23343. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  23344. *
  23345. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  23346. * (RSAPublicKey).
  23347. *
  23348. * @param [out] output Buffer to put encoded data in.
  23349. * @param [in] key RSA key object.
  23350. * @param [in] outLen Size of the output buffer in bytes.
  23351. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  23352. * @return Size of encoded data in bytes on success.
  23353. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  23354. * minimum length (5 bytes).
  23355. * @return MEMORY_E when dynamic memory allocation failed.
  23356. */
  23357. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  23358. int with_header)
  23359. {
  23360. #ifndef WOLFSSL_ASN_TEMPLATE
  23361. int nSz, eSz;
  23362. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  23363. byte seq[MAX_SEQ_SZ];
  23364. byte headSeq[MAX_SEQ_SZ];
  23365. byte bitString[1 + MAX_LENGTH_SZ + 1];
  23366. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  23367. if (key == NULL) {
  23368. return BAD_FUNC_ARG;
  23369. }
  23370. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  23371. if (nSz < 0)
  23372. return nSz;
  23373. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  23374. if (eSz < 0)
  23375. return eSz;
  23376. seqSz = SetSequence((word32)(nSz + eSz), seq);
  23377. /* headers */
  23378. if (with_header) {
  23379. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  23380. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  23381. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  23382. headSeq);
  23383. }
  23384. /* if getting length only */
  23385. if (output == NULL) {
  23386. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  23387. }
  23388. /* check output size */
  23389. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  23390. return BUFFER_E;
  23391. }
  23392. /* write output */
  23393. idx = 0;
  23394. if (with_header) {
  23395. /* header size */
  23396. XMEMCPY(output + idx, headSeq, headSz);
  23397. idx += headSz;
  23398. /* algo */
  23399. XMEMCPY(output + idx, algo, algoSz);
  23400. idx += algoSz;
  23401. /* bit string */
  23402. XMEMCPY(output + idx, bitString, bitStringSz);
  23403. idx += bitStringSz;
  23404. }
  23405. /* seq */
  23406. XMEMCPY(output + idx, seq, seqSz);
  23407. idx += seqSz;
  23408. /* n */
  23409. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  23410. idx += (word32)nSz;
  23411. /* e */
  23412. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  23413. idx += (word32)eSz;
  23414. return (int)idx;
  23415. #else
  23416. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  23417. int sz = 0;
  23418. int ret = 0;
  23419. int o = 0;
  23420. /* Check parameter validity. */
  23421. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  23422. ret = BAD_FUNC_ARG;
  23423. }
  23424. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  23425. if (ret == 0) {
  23426. if (!with_header) {
  23427. /* Start encoding with items after header. */
  23428. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  23429. }
  23430. /* Set OID for RSA key. */
  23431. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  23432. #ifdef WC_RSA_PSS
  23433. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  23434. #endif
  23435. /* Set public key mp_ints. */
  23436. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  23437. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  23438. /* Calculate size of RSA public key. */
  23439. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  23440. (int)rsaPublicKeyASN_Length - o, &sz);
  23441. }
  23442. /* Check output buffer is big enough for encoding. */
  23443. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  23444. ret = BUFFER_E;
  23445. }
  23446. if ((ret == 0) && (output != NULL)) {
  23447. /* Encode RSA public key. */
  23448. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  23449. (int)rsaPublicKeyASN_Length - o, output);
  23450. }
  23451. if (ret == 0) {
  23452. /* Return size of encoding. */
  23453. ret = sz;
  23454. }
  23455. FREE_ASNSETDATA(dataASN, key->heap);
  23456. return ret;
  23457. #endif /* WOLFSSL_ASN_TEMPLATE */
  23458. }
  23459. /* Calculate size of encoded public RSA key in bytes.
  23460. *
  23461. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  23462. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  23463. *
  23464. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  23465. * (RSAPublicKey).
  23466. *
  23467. * @param [in] key RSA key object.
  23468. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  23469. * @return Size of encoded data in bytes on success.
  23470. * @return BAD_FUNC_ARG when key is NULL.
  23471. * @return MEMORY_E when dynamic memory allocation failed.
  23472. */
  23473. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  23474. {
  23475. return SetRsaPublicKey(NULL, key, 0, with_header);
  23476. }
  23477. /* Encode public RSA key in DER format.
  23478. *
  23479. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  23480. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  23481. *
  23482. * @param [in] key RSA key object.
  23483. * @param [out] output Buffer to put encoded data in.
  23484. * @param [in] inLen Size of buffer in bytes.
  23485. * @return Size of encoded data in bytes on success.
  23486. * @return BAD_FUNC_ARG when key or output is NULL.
  23487. * @return MEMORY_E when dynamic memory allocation failed.
  23488. */
  23489. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  23490. {
  23491. return SetRsaPublicKey(output, key, (int)inLen, 1);
  23492. }
  23493. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  23494. * seq + n + e is returned in ASN.1 DER format */
  23495. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  23496. int with_header)
  23497. {
  23498. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  23499. }
  23500. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  23501. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN))) */
  23502. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  23503. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  23504. !defined(NO_RSA)
  23505. /* Encode private RSA key in DER format.
  23506. *
  23507. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  23508. *
  23509. * @param [in] key RSA key object.
  23510. * @param [out] output Buffer to put encoded data in.
  23511. * @param [in] inLen Size of buffer in bytes.
  23512. * @return Size of encoded data in bytes on success.
  23513. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  23514. * @return MEMORY_E when dynamic memory allocation failed.
  23515. */
  23516. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  23517. {
  23518. #ifndef WOLFSSL_ASN_TEMPLATE
  23519. int ret = 0, i;
  23520. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
  23521. word32 sizes[RSA_INTS];
  23522. byte seq[MAX_SEQ_SZ];
  23523. byte ver[MAX_VERSION_SZ];
  23524. byte* tmps[RSA_INTS];
  23525. if (key == NULL)
  23526. return BAD_FUNC_ARG;
  23527. if (key->type != RSA_PRIVATE)
  23528. return BAD_FUNC_ARG;
  23529. for (i = 0; i < RSA_INTS; i++)
  23530. tmps[i] = NULL;
  23531. /* write all big ints from key to DER tmps */
  23532. for (i = 0; i < RSA_INTS; i++) {
  23533. mp_int* keyInt = GetRsaInt(key, i);
  23534. int mpSz;
  23535. word32 rawLen;
  23536. ret = mp_unsigned_bin_size(keyInt);
  23537. if (ret < 0)
  23538. return ret;
  23539. rawLen = (word32)ret + 1;
  23540. ret = 0;
  23541. if (output != NULL) {
  23542. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  23543. DYNAMIC_TYPE_RSA);
  23544. if (tmps[i] == NULL) {
  23545. ret = MEMORY_E;
  23546. break;
  23547. }
  23548. }
  23549. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  23550. if (mpSz < 0) {
  23551. ret = mpSz;
  23552. break;
  23553. }
  23554. sizes[i] = (word32)mpSz;
  23555. intTotalLen += (word32)mpSz;
  23556. }
  23557. if (ret == 0) {
  23558. /* make headers */
  23559. ret = SetMyVersion(0, ver, FALSE);
  23560. }
  23561. if (ret >= 0) {
  23562. verSz = (word32)ret;
  23563. ret = 0;
  23564. seqSz = SetSequence(verSz + intTotalLen, seq);
  23565. outLen = seqSz + verSz + intTotalLen;
  23566. if (output != NULL && outLen > inLen)
  23567. ret = BUFFER_E;
  23568. }
  23569. if (ret == 0 && output != NULL) {
  23570. word32 j;
  23571. /* write to output */
  23572. XMEMCPY(output, seq, seqSz);
  23573. j = seqSz;
  23574. XMEMCPY(output + j, ver, verSz);
  23575. j += verSz;
  23576. for (i = 0; i < RSA_INTS; i++) {
  23577. XMEMCPY(output + j, tmps[i], sizes[i]);
  23578. j += sizes[i];
  23579. }
  23580. }
  23581. for (i = 0; i < RSA_INTS; i++) {
  23582. if (tmps[i])
  23583. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  23584. }
  23585. if (ret == 0)
  23586. ret = (int)outLen;
  23587. return ret;
  23588. #else
  23589. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  23590. int i;
  23591. int sz = 0;
  23592. int ret = 0;
  23593. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  23594. ret = BAD_FUNC_ARG;
  23595. }
  23596. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  23597. if (ret == 0) {
  23598. /* Set the version. */
  23599. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  23600. /* Set all the mp_ints in private key. */
  23601. for (i = 0; i < RSA_INTS; i++) {
  23602. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  23603. }
  23604. /* Calculate size of RSA private key encoding. */
  23605. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  23606. }
  23607. /* Check output buffer has enough space for encoding. */
  23608. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  23609. ret = BAD_FUNC_ARG;
  23610. }
  23611. if ((ret == 0) && (output != NULL)) {
  23612. /* Encode RSA private key. */
  23613. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  23614. }
  23615. if (ret == 0) {
  23616. /* Return size of encoding. */
  23617. ret = sz;
  23618. }
  23619. FREE_ASNSETDATA(dataASN, key->heap);
  23620. return ret;
  23621. #endif
  23622. }
  23623. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA */
  23624. #ifdef WOLFSSL_CERT_GEN
  23625. /* Initialize and Set Certificate defaults:
  23626. version = 3 (0x2)
  23627. serial = 0
  23628. sigType = SHA_WITH_RSA
  23629. issuer = blank
  23630. daysValid = 500
  23631. selfSigned = 1 (true) use subject as issuer
  23632. subject = blank
  23633. */
  23634. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  23635. {
  23636. #ifdef WOLFSSL_MULTI_ATTRIB
  23637. int i = 0;
  23638. #endif
  23639. if (cert == NULL) {
  23640. return BAD_FUNC_ARG;
  23641. }
  23642. XMEMSET(cert, 0, sizeof(Cert));
  23643. cert->version = 2; /* version 3 is hex 2 */
  23644. #ifndef NO_SHA
  23645. cert->sigType = CTC_SHAwRSA;
  23646. #elif !defined(NO_SHA256)
  23647. cert->sigType = CTC_SHA256wRSA;
  23648. #else
  23649. cert->sigType = 0;
  23650. #endif
  23651. cert->daysValid = 500;
  23652. cert->selfSigned = 1;
  23653. cert->keyType = RSA_KEY;
  23654. cert->issuer.countryEnc = CTC_PRINTABLE;
  23655. cert->issuer.stateEnc = CTC_UTF8;
  23656. cert->issuer.streetEnc = CTC_UTF8;
  23657. cert->issuer.localityEnc = CTC_UTF8;
  23658. cert->issuer.surEnc = CTC_UTF8;
  23659. #ifdef WOLFSSL_CERT_NAME_ALL
  23660. cert->issuer.givenNameEnc = CTC_UTF8;
  23661. cert->issuer.initialsEnc = CTC_UTF8;
  23662. cert->issuer.dnQualifierEnc = CTC_UTF8;
  23663. cert->issuer.dnNameEnc = CTC_UTF8;
  23664. #endif
  23665. cert->issuer.orgEnc = CTC_UTF8;
  23666. cert->issuer.unitEnc = CTC_UTF8;
  23667. cert->issuer.commonNameEnc = CTC_UTF8;
  23668. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  23669. cert->issuer.userIdEnc = CTC_UTF8;
  23670. cert->issuer.postalCodeEnc = CTC_UTF8;
  23671. #ifdef WOLFSSL_CERT_EXT
  23672. cert->issuer.busCatEnc = CTC_UTF8;
  23673. cert->issuer.joiCEnc = CTC_UTF8;
  23674. cert->issuer.joiStEnc = CTC_UTF8;
  23675. #endif
  23676. cert->subject.countryEnc = CTC_PRINTABLE;
  23677. cert->subject.stateEnc = CTC_UTF8;
  23678. cert->subject.streetEnc = CTC_UTF8;
  23679. cert->subject.localityEnc = CTC_UTF8;
  23680. cert->subject.surEnc = CTC_UTF8;
  23681. #ifdef WOLFSSL_CERT_NAME_ALL
  23682. cert->subject.givenNameEnc = CTC_UTF8;
  23683. cert->subject.initialsEnc = CTC_UTF8;
  23684. cert->subject.dnQualifierEnc = CTC_UTF8;
  23685. cert->subject.dnNameEnc = CTC_UTF8;
  23686. #endif
  23687. cert->subject.orgEnc = CTC_UTF8;
  23688. cert->subject.unitEnc = CTC_UTF8;
  23689. cert->subject.commonNameEnc = CTC_UTF8;
  23690. cert->subject.serialDevEnc = CTC_PRINTABLE;
  23691. cert->subject.userIdEnc = CTC_UTF8;
  23692. cert->subject.postalCodeEnc = CTC_UTF8;
  23693. #ifdef WOLFSSL_CERT_EXT
  23694. cert->subject.busCatEnc = CTC_UTF8;
  23695. cert->subject.joiCEnc = CTC_UTF8;
  23696. cert->subject.joiStEnc = CTC_UTF8;
  23697. #endif
  23698. #ifdef WOLFSSL_MULTI_ATTRIB
  23699. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  23700. cert->issuer.name[i].type = CTC_UTF8;
  23701. cert->subject.name[i].type = CTC_UTF8;
  23702. }
  23703. #endif /* WOLFSSL_MULTI_ATTRIB */
  23704. cert->heap = heap;
  23705. (void)devId; /* future */
  23706. return 0;
  23707. }
  23708. WOLFSSL_ABI
  23709. int wc_InitCert(Cert* cert)
  23710. {
  23711. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  23712. }
  23713. WOLFSSL_ABI
  23714. Cert* wc_CertNew(void* heap)
  23715. {
  23716. Cert* certNew;
  23717. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  23718. if (certNew) {
  23719. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  23720. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  23721. certNew = NULL;
  23722. }
  23723. }
  23724. return certNew;
  23725. }
  23726. WOLFSSL_ABI
  23727. void wc_CertFree(Cert* cert)
  23728. {
  23729. if (cert) {
  23730. void* heap = cert->heap;
  23731. ForceZero(cert, sizeof(Cert));
  23732. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  23733. (void)heap;
  23734. }
  23735. }
  23736. /* DER encoded x509 Certificate */
  23737. typedef struct DerCert {
  23738. byte size[MAX_LENGTH_SZ]; /* length encoded */
  23739. byte version[MAX_VERSION_SZ]; /* version encoded */
  23740. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  23741. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  23742. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  23743. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  23744. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  23745. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  23746. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  23747. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  23748. #ifdef WOLFSSL_CERT_EXT
  23749. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  23750. byte akid[MAX_KID_SZ
  23751. #ifdef WOLFSSL_AKID_NAME
  23752. + sizeof(CertName) + CTC_SERIAL_SIZE
  23753. #endif
  23754. ]; /* Authority Key Identifier extension */
  23755. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  23756. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  23757. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23758. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  23759. #endif
  23760. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  23761. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  23762. #endif
  23763. #ifdef WOLFSSL_CERT_REQ
  23764. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  23765. #ifdef WOLFSSL_CUSTOM_OID
  23766. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  23767. #endif
  23768. #endif
  23769. #ifdef WOLFSSL_ALT_NAMES
  23770. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  23771. #endif
  23772. int sizeSz; /* encoded size length */
  23773. int versionSz; /* encoded version length */
  23774. int serialSz; /* encoded serial length */
  23775. int sigAlgoSz; /* encoded sig algo length */
  23776. int issuerSz; /* encoded issuer length */
  23777. int subjectSz; /* encoded subject length */
  23778. int validitySz; /* encoded validity length */
  23779. int publicKeySz; /* encoded public key length */
  23780. int caSz; /* encoded CA extension length */
  23781. #ifdef WOLFSSL_CERT_EXT
  23782. int skidSz; /* encoded SKID extension length */
  23783. int akidSz; /* encoded SKID extension length */
  23784. int keyUsageSz; /* encoded KeyUsage extension length */
  23785. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  23786. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23787. int nsCertTypeSz; /* encoded Netscape Certificate Type
  23788. * extension length */
  23789. #endif
  23790. int certPoliciesSz; /* encoded CertPolicies extension length*/
  23791. int crlInfoSz; /* encoded CRL Dist Points length */
  23792. #endif
  23793. #ifdef WOLFSSL_ALT_NAMES
  23794. int altNamesSz; /* encoded AltNames extension length */
  23795. #endif
  23796. int extensionsSz; /* encoded extensions total length */
  23797. int total; /* total encoded lengths */
  23798. #ifdef WOLFSSL_CERT_REQ
  23799. int attribSz;
  23800. #ifdef WOLFSSL_CUSTOM_OID
  23801. int extCustomSz;
  23802. #endif
  23803. #endif
  23804. } DerCert;
  23805. #ifdef WOLFSSL_CERT_REQ
  23806. #ifndef WOLFSSL_ASN_TEMPLATE
  23807. /* Write a set header to output */
  23808. static word32 SetPrintableString(word32 len, byte* output)
  23809. {
  23810. output[0] = ASN_PRINTABLE_STRING;
  23811. return SetLength(len, output + 1) + 1;
  23812. }
  23813. static word32 SetUTF8String(word32 len, byte* output)
  23814. {
  23815. output[0] = ASN_UTF8STRING;
  23816. return SetLength(len, output + 1) + 1;
  23817. }
  23818. #endif
  23819. #endif /* WOLFSSL_CERT_REQ */
  23820. #ifndef WOLFSSL_CERT_GEN_CACHE
  23821. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  23822. static
  23823. #endif
  23824. WOLFSSL_ABI
  23825. void wc_SetCert_Free(Cert* cert)
  23826. {
  23827. if (cert != NULL) {
  23828. cert->der = NULL;
  23829. if (cert->decodedCert) {
  23830. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  23831. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  23832. cert->decodedCert = NULL;
  23833. }
  23834. }
  23835. }
  23836. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  23837. int devId)
  23838. {
  23839. int ret;
  23840. if (cert == NULL) {
  23841. ret = BAD_FUNC_ARG;
  23842. }
  23843. else {
  23844. /* Allocate DecodedCert struct and Zero */
  23845. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  23846. DYNAMIC_TYPE_DCERT);
  23847. if (cert->decodedCert == NULL) {
  23848. ret = MEMORY_E;
  23849. }
  23850. else {
  23851. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  23852. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  23853. cert->heap, devId);
  23854. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  23855. CERT_TYPE, 0, NULL);
  23856. if (ret >= 0) {
  23857. cert->der = (byte*)der;
  23858. }
  23859. else {
  23860. wc_SetCert_Free(cert);
  23861. }
  23862. }
  23863. }
  23864. return ret;
  23865. }
  23866. #endif /* WOLFSSL_CERT_GEN */
  23867. #ifdef WOLFSSL_CERT_GEN
  23868. #ifndef NO_ASN_TIME
  23869. static WC_INLINE byte itob(int number)
  23870. {
  23871. return (byte)number + 0x30;
  23872. }
  23873. /* write time to output, format */
  23874. static void SetTime(struct tm* date, byte* output)
  23875. {
  23876. int i = 0;
  23877. output[i++] = itob((date->tm_year % 10000) / 1000);
  23878. output[i++] = itob((date->tm_year % 1000) / 100);
  23879. output[i++] = itob((date->tm_year % 100) / 10);
  23880. output[i++] = itob( date->tm_year % 10);
  23881. output[i++] = itob(date->tm_mon / 10);
  23882. output[i++] = itob(date->tm_mon % 10);
  23883. output[i++] = itob(date->tm_mday / 10);
  23884. output[i++] = itob(date->tm_mday % 10);
  23885. output[i++] = itob(date->tm_hour / 10);
  23886. output[i++] = itob(date->tm_hour % 10);
  23887. output[i++] = itob(date->tm_min / 10);
  23888. output[i++] = itob(date->tm_min % 10);
  23889. output[i++] = itob(date->tm_sec / 10);
  23890. output[i++] = itob(date->tm_sec % 10);
  23891. output[i] = 'Z'; /* Zulu profile */
  23892. }
  23893. #endif
  23894. #ifndef WOLFSSL_ASN_TEMPLATE
  23895. /* Copy Dates from cert, return bytes written */
  23896. static int CopyValidity(byte* output, Cert* cert)
  23897. {
  23898. word32 seqSz;
  23899. WOLFSSL_ENTER("CopyValidity");
  23900. /* headers and output */
  23901. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  23902. output);
  23903. if (output) {
  23904. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  23905. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  23906. (size_t)cert->afterDateSz);
  23907. }
  23908. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  23909. }
  23910. #endif /* !WOLFSSL_ASN_TEMPLATE */
  23911. /* Simple name OID size. */
  23912. #define NAME_OID_SZ 3
  23913. /* Domain name OIDs. */
  23914. static const byte nameOid[][NAME_OID_SZ] = {
  23915. { 0x55, 0x04, ASN_COUNTRY_NAME },
  23916. { 0x55, 0x04, ASN_STATE_NAME },
  23917. { 0x55, 0x04, ASN_STREET_ADDR },
  23918. { 0x55, 0x04, ASN_LOCALITY_NAME },
  23919. #ifdef WOLFSSL_CERT_NAME_ALL
  23920. { 0x55, 0x04, ASN_NAME },
  23921. { 0x55, 0x04, ASN_GIVEN_NAME },
  23922. { 0x55, 0x04, ASN_INITIALS },
  23923. { 0x55, 0x04, ASN_DNQUALIFIER },
  23924. #endif
  23925. { 0x55, 0x04, ASN_SUR_NAME },
  23926. { 0x55, 0x04, ASN_ORG_NAME },
  23927. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  23928. /* list all DC values before OUs */
  23929. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  23930. { 0x55, 0x04, ASN_COMMON_NAME },
  23931. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  23932. #ifdef WOLFSSL_CERT_EXT
  23933. { 0x55, 0x04, ASN_BUS_CAT },
  23934. #endif
  23935. { 0x55, 0x04, ASN_POSTAL_CODE },
  23936. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  23937. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  23938. #ifdef WOLFSSL_CUSTOM_OID
  23939. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  23940. #endif
  23941. };
  23942. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  23943. /* Get ASN Name from index */
  23944. byte GetCertNameId(int idx)
  23945. {
  23946. if (idx < NAME_ENTRIES)
  23947. return nameOid[idx][2];
  23948. return 0;
  23949. }
  23950. /* Get Which Name from index */
  23951. const char* GetOneCertName(CertName* name, int idx)
  23952. {
  23953. byte type = GetCertNameId(idx);
  23954. switch (type) {
  23955. case ASN_COUNTRY_NAME:
  23956. return name->country;
  23957. case ASN_STATE_NAME:
  23958. return name->state;
  23959. case ASN_STREET_ADDR:
  23960. return name->street;
  23961. case ASN_LOCALITY_NAME:
  23962. return name->locality;
  23963. #ifdef WOLFSSL_CERT_NAME_ALL
  23964. case ASN_NAME:
  23965. return name->dnName;
  23966. case ASN_GIVEN_NAME:
  23967. return name->givenName;
  23968. case ASN_INITIALS:
  23969. return name->initials;
  23970. case ASN_DNQUALIFIER:
  23971. return name->dnQualifier;
  23972. #endif /* WOLFSSL_CERT_NAME_ALL */
  23973. case ASN_SUR_NAME:
  23974. return name->sur;
  23975. case ASN_ORG_NAME:
  23976. return name->org;
  23977. case ASN_ORGUNIT_NAME:
  23978. return name->unit;
  23979. case ASN_COMMON_NAME:
  23980. return name->commonName;
  23981. case ASN_SERIAL_NUMBER:
  23982. return name->serialDev;
  23983. case ASN_USER_ID:
  23984. return name->userId;
  23985. case ASN_POSTAL_CODE:
  23986. return name->postalCode;
  23987. case ASN_EMAIL_NAME:
  23988. return name->email;
  23989. #ifdef WOLFSSL_CERT_EXT
  23990. case ASN_BUS_CAT:
  23991. return name->busCat;
  23992. #endif
  23993. #ifdef WOLFSSL_CUSTOM_OID
  23994. case ASN_CUSTOM_NAME:
  23995. return (const char*)name->custom.val;
  23996. #endif
  23997. default:
  23998. return NULL;
  23999. }
  24000. }
  24001. /* Get Which Name Encoding from index */
  24002. static char GetNameType(CertName* name, int idx)
  24003. {
  24004. byte type = GetCertNameId(idx);
  24005. switch (type) {
  24006. case ASN_COUNTRY_NAME:
  24007. return name->countryEnc;
  24008. case ASN_STATE_NAME:
  24009. return name->stateEnc;
  24010. case ASN_STREET_ADDR:
  24011. return name->streetEnc;
  24012. case ASN_LOCALITY_NAME:
  24013. return name->localityEnc;
  24014. #ifdef WOLFSSL_CERT_NAME_ALL
  24015. case ASN_NAME:
  24016. return name->dnNameEnc;
  24017. case ASN_GIVEN_NAME:
  24018. return name->givenNameEnc;
  24019. case ASN_INITIALS:
  24020. return name->initialsEnc;
  24021. case ASN_DNQUALIFIER:
  24022. return name->dnQualifierEnc;
  24023. #endif /* WOLFSSL_CERT_NAME_ALL */
  24024. case ASN_SUR_NAME:
  24025. return name->surEnc;
  24026. case ASN_ORG_NAME:
  24027. return name->orgEnc;
  24028. case ASN_ORGUNIT_NAME:
  24029. return name->unitEnc;
  24030. case ASN_COMMON_NAME:
  24031. return name->commonNameEnc;
  24032. case ASN_SERIAL_NUMBER:
  24033. return name->serialDevEnc;
  24034. case ASN_USER_ID:
  24035. return name->userIdEnc;
  24036. case ASN_POSTAL_CODE:
  24037. return name->postalCodeEnc;
  24038. case ASN_EMAIL_NAME:
  24039. return 0; /* special */
  24040. #ifdef WOLFSSL_CERT_EXT
  24041. case ASN_BUS_CAT:
  24042. return name->busCatEnc;
  24043. #endif
  24044. #ifdef WOLFSSL_CUSTOM_OID
  24045. case ASN_CUSTOM_NAME:
  24046. return name->custom.enc;
  24047. #endif
  24048. default:
  24049. return 0;
  24050. }
  24051. }
  24052. #ifndef WOLFSSL_ASN_TEMPLATE
  24053. /*
  24054. Extensions ::= SEQUENCE OF Extension
  24055. Extension ::= SEQUENCE {
  24056. extnId OBJECT IDENTIFIER,
  24057. critical BOOLEAN DEFAULT FALSE,
  24058. extnValue OCTET STRING }
  24059. */
  24060. /* encode all extensions, return total bytes written */
  24061. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  24062. const byte* ext, int extSz)
  24063. {
  24064. if (out == NULL || IdxInOut == NULL || ext == NULL)
  24065. return BAD_FUNC_ARG;
  24066. if (outSz < (word32)(*IdxInOut+extSz))
  24067. return BUFFER_E;
  24068. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  24069. *IdxInOut += extSz;
  24070. return *IdxInOut;
  24071. }
  24072. /* encode extensions header, return total bytes written */
  24073. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  24074. {
  24075. byte sequence[MAX_SEQ_SZ];
  24076. byte len[MAX_LENGTH_SZ];
  24077. word32 seqSz, lenSz, idx = 0;
  24078. if (out == NULL)
  24079. return BAD_FUNC_ARG;
  24080. if (outSz < 3)
  24081. return BUFFER_E;
  24082. seqSz = SetSequence(extSz, sequence);
  24083. /* encode extensions length provided */
  24084. lenSz = SetLength(extSz+seqSz, len);
  24085. if (outSz < (word32)(lenSz+seqSz+1))
  24086. return BUFFER_E;
  24087. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  24088. XMEMCPY(&out[idx], len, lenSz); /* length */
  24089. idx += lenSz;
  24090. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  24091. idx += seqSz;
  24092. return (int)idx;
  24093. }
  24094. /* encode CA basic constraints true with path length
  24095. * return total bytes written */
  24096. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  24097. {
  24098. /* ASN1->DER sequence for Basic Constraints True and path length */
  24099. const byte caPathLenBasicConstASN1[] = {
  24100. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  24101. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  24102. 0x00
  24103. };
  24104. if (out == NULL)
  24105. return BAD_FUNC_ARG;
  24106. if (outSz < sizeof(caPathLenBasicConstASN1))
  24107. return BUFFER_E;
  24108. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  24109. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  24110. return (int)sizeof(caPathLenBasicConstASN1);
  24111. }
  24112. /* encode CA basic constraints
  24113. * return total bytes written */
  24114. static int SetCaEx(byte* out, word32 outSz, byte isCa)
  24115. {
  24116. /* ASN1->DER sequence for Basic Constraints True */
  24117. const byte caBasicConstASN1[] = {
  24118. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  24119. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  24120. };
  24121. if (out == NULL)
  24122. return BAD_FUNC_ARG;
  24123. if (outSz < sizeof(caBasicConstASN1))
  24124. return BUFFER_E;
  24125. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  24126. if (!isCa) {
  24127. out[sizeof(caBasicConstASN1)-1] = isCa;
  24128. }
  24129. return (int)sizeof(caBasicConstASN1);
  24130. }
  24131. /* encode CA basic constraints true
  24132. * return total bytes written */
  24133. static int SetCa(byte* out, word32 outSz)
  24134. {
  24135. return SetCaEx(out, outSz, 1);
  24136. }
  24137. /* encode basic constraints without CA Boolean
  24138. * return total bytes written */
  24139. static int SetBC(byte* out, word32 outSz)
  24140. {
  24141. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  24142. const byte BasicConstASN1[] = {
  24143. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  24144. 0x02, 0x30, 0x00
  24145. };
  24146. if (out == NULL)
  24147. return BAD_FUNC_ARG;
  24148. if (outSz < sizeof(BasicConstASN1))
  24149. return BUFFER_E;
  24150. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  24151. return (int)sizeof(BasicConstASN1);
  24152. }
  24153. #endif
  24154. #ifdef WOLFSSL_CERT_EXT
  24155. #ifndef WOLFSSL_ASN_TEMPLATE
  24156. /* encode OID and associated value, return total bytes written */
  24157. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  24158. byte *in, word32 inSz)
  24159. {
  24160. word32 idx = 0;
  24161. if (out == NULL || oid == NULL || in == NULL)
  24162. return BAD_FUNC_ARG;
  24163. if (outSz < 3)
  24164. return BUFFER_E;
  24165. /* sequence, + 1 => byte to put value size */
  24166. idx = SetSequence(inSz + oidSz + 1, out);
  24167. if ((idx + inSz + oidSz + 1) > outSz)
  24168. return BUFFER_E;
  24169. XMEMCPY(out+idx, oid, oidSz);
  24170. idx += oidSz;
  24171. out[idx++] = (byte)inSz;
  24172. XMEMCPY(out+idx, in, inSz);
  24173. return (int)(idx+inSz);
  24174. }
  24175. /* encode Subject Key Identifier, return total bytes written
  24176. * RFC5280 : non-critical */
  24177. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  24178. {
  24179. byte skid_len[1 + MAX_LENGTH_SZ];
  24180. byte skid_enc_len[MAX_LENGTH_SZ];
  24181. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  24182. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  24183. if (output == NULL || input == NULL)
  24184. return BAD_FUNC_ARG;
  24185. /* Octet String header */
  24186. skid_lenSz = SetOctetString(length, skid_len);
  24187. /* length of encoded value */
  24188. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  24189. if (outSz < 3)
  24190. return BUFFER_E;
  24191. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  24192. skid_enc_lenSz, output);
  24193. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  24194. return BUFFER_E;
  24195. /* put oid */
  24196. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  24197. idx += sizeof(skid_oid);
  24198. /* put encoded len */
  24199. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  24200. idx += skid_enc_lenSz;
  24201. /* put octet header */
  24202. XMEMCPY(output+idx, skid_len, skid_lenSz);
  24203. idx += skid_lenSz;
  24204. /* put value */
  24205. XMEMCPY(output+idx, input, length);
  24206. idx += length;
  24207. return (int)idx;
  24208. }
  24209. /* encode Authority Key Identifier, return total bytes written
  24210. * RFC5280 : non-critical */
  24211. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  24212. byte rawAkid)
  24213. {
  24214. int enc_valSz;
  24215. byte enc_val_buf[MAX_KID_SZ];
  24216. byte* enc_val;
  24217. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  24218. const byte akid_cs[] = { 0x80 };
  24219. word32 inSeqSz, idx;
  24220. (void)rawAkid;
  24221. if (output == NULL || input == NULL)
  24222. return BAD_FUNC_ARG;
  24223. #ifdef WOLFSSL_AKID_NAME
  24224. if (rawAkid) {
  24225. enc_val = input;
  24226. enc_valSz = length;
  24227. }
  24228. else
  24229. #endif
  24230. {
  24231. enc_val = enc_val_buf;
  24232. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  24233. if (enc_valSz > (int)sizeof(enc_val_buf))
  24234. return BAD_FUNC_ARG;
  24235. /* sequence for ContentSpec & value */
  24236. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  24237. sizeof(akid_cs), input, length);
  24238. if (enc_valSz <= 0)
  24239. return enc_valSz;
  24240. }
  24241. /* The size of the extension sequence contents */
  24242. inSeqSz = (word32)sizeof(akid_oid) +
  24243. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  24244. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  24245. return BAD_FUNC_ARG;
  24246. /* Write out the sequence header */
  24247. idx = SetSequence(inSeqSz, output);
  24248. /* Write out OID */
  24249. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  24250. idx += sizeof(akid_oid);
  24251. /* Write out AKID */
  24252. idx += SetOctetString((word32)enc_valSz, output + idx);
  24253. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  24254. return (int)idx + enc_valSz;
  24255. }
  24256. /* encode Key Usage, return total bytes written
  24257. * RFC5280 : critical */
  24258. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  24259. {
  24260. byte ku[5];
  24261. word32 idx;
  24262. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  24263. 0x01, 0x01, 0xff, 0x04};
  24264. if (output == NULL)
  24265. return BAD_FUNC_ARG;
  24266. idx = SetBitString16Bit(input, ku);
  24267. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  24268. ku, idx);
  24269. }
  24270. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  24271. const byte* oid, word32 oidSz)
  24272. {
  24273. /* verify room */
  24274. if (*idx + 2 + oidSz >= outSz)
  24275. return ASN_PARSE_E;
  24276. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  24277. XMEMCPY(&output[*idx], oid, oidSz);
  24278. *idx += oidSz;
  24279. return 0;
  24280. }
  24281. #endif
  24282. #ifdef WOLFSSL_ASN_TEMPLATE
  24283. /* ASN.1 template for extended key usage.
  24284. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  24285. * Dynamic creation of template for encoding.
  24286. */
  24287. static const ASNItem ekuASN[] = {
  24288. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24289. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24290. };
  24291. enum {
  24292. EKUASN_IDX_SEQ = 0,
  24293. EKUASN_IDX_OID
  24294. };
  24295. /* OIDs corresponding to extended key usage. */
  24296. struct {
  24297. const byte* oid;
  24298. word32 oidSz;
  24299. } ekuOid[] = {
  24300. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  24301. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  24302. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  24303. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  24304. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  24305. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  24306. };
  24307. #define EKU_OID_LO 1
  24308. #define EKU_OID_HI 6
  24309. #endif /* WOLFSSL_ASN_TEMPLATE */
  24310. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  24311. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  24312. {
  24313. #ifndef WOLFSSL_ASN_TEMPLATE
  24314. word32 idx = 0, oidListSz = 0, totalSz;
  24315. int ret = 0;
  24316. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  24317. if (output == NULL)
  24318. return BAD_FUNC_ARG;
  24319. /* Skip to OID List */
  24320. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  24321. idx = totalSz;
  24322. /* Build OID List */
  24323. /* If any set, then just use it */
  24324. if (input & EXTKEYUSE_ANY) {
  24325. ret |= SetOjectIdValue(output, outSz, &idx,
  24326. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  24327. }
  24328. else {
  24329. if (input & EXTKEYUSE_SERVER_AUTH)
  24330. ret |= SetOjectIdValue(output, outSz, &idx,
  24331. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  24332. if (input & EXTKEYUSE_CLIENT_AUTH)
  24333. ret |= SetOjectIdValue(output, outSz, &idx,
  24334. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  24335. if (input & EXTKEYUSE_CODESIGN)
  24336. ret |= SetOjectIdValue(output, outSz, &idx,
  24337. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  24338. if (input & EXTKEYUSE_EMAILPROT)
  24339. ret |= SetOjectIdValue(output, outSz, &idx,
  24340. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  24341. if (input & EXTKEYUSE_TIMESTAMP)
  24342. ret |= SetOjectIdValue(output, outSz, &idx,
  24343. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  24344. if (input & EXTKEYUSE_OCSP_SIGN)
  24345. ret |= SetOjectIdValue(output, outSz, &idx,
  24346. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  24347. #ifdef WOLFSSL_EKU_OID
  24348. /* iterate through OID values */
  24349. if (input & EXTKEYUSE_USER) {
  24350. int i, sz;
  24351. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  24352. sz = cert->extKeyUsageOIDSz[i];
  24353. if (sz > 0) {
  24354. ret |= SetOjectIdValue(output, outSz, &idx,
  24355. cert->extKeyUsageOID[i], sz);
  24356. }
  24357. }
  24358. }
  24359. #endif /* WOLFSSL_EKU_OID */
  24360. }
  24361. if (ret != 0)
  24362. return ASN_PARSE_E;
  24363. /* Calculate Sizes */
  24364. oidListSz = idx - totalSz;
  24365. totalSz = idx - 2; /* exclude first seq/len (2) */
  24366. /* 1. Seq + Total Len (2) */
  24367. idx = SetSequence(totalSz, output);
  24368. /* 2. Object ID (2) */
  24369. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  24370. idx += sizeof(extkeyusage_oid);
  24371. /* 3. Octet String (2) */
  24372. idx += SetOctetString(totalSz - idx, &output[idx]);
  24373. /* 4. Seq + OidListLen (2) */
  24374. idx += SetSequence(oidListSz, &output[idx]);
  24375. /* 5. Oid List (already set in-place above) */
  24376. idx += oidListSz;
  24377. (void)cert;
  24378. return (int)idx;
  24379. #else
  24380. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  24381. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  24382. ASNSetData* dataASN;
  24383. ASNItem* extKuASN = NULL;
  24384. int asnIdx = 1;
  24385. size_t cnt = 1 + EKU_OID_HI;
  24386. int i;
  24387. int ret = 0;
  24388. int sz = 0;
  24389. #ifdef WOLFSSL_EKU_OID
  24390. cnt += CTC_MAX_EKU_NB;
  24391. #endif
  24392. /* Allocate memory for dynamic data items. */
  24393. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  24394. DYNAMIC_TYPE_TMP_BUFFER);
  24395. if (dataASN == NULL) {
  24396. ret = MEMORY_E;
  24397. }
  24398. if (ret == 0) {
  24399. /* Allocate memory for dynamic ASN.1 template. */
  24400. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  24401. DYNAMIC_TYPE_TMP_BUFFER);
  24402. if (extKuASN == NULL) {
  24403. ret = MEMORY_E;
  24404. }
  24405. }
  24406. if (ret == 0) {
  24407. /* Copy Sequence into dynamic ASN.1 template. */
  24408. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  24409. /* Clear dynamic data. */
  24410. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  24411. /* Build up the template and data. */
  24412. /* If 'any' set, then just use it. */
  24413. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  24414. /* Set template item. */
  24415. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  24416. sizeof(ASNItem));
  24417. /* Set data item. */
  24418. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  24419. sizeof(extExtKeyUsageAnyOid));
  24420. asnIdx++;
  24421. }
  24422. else {
  24423. /* Step through the flagged purposes. */
  24424. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  24425. if ((input & (1 << i)) != 0) {
  24426. /* Set template item. */
  24427. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  24428. sizeof(ASNItem));
  24429. /* Set data item. */
  24430. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  24431. ekuOid[i - 1].oidSz);
  24432. asnIdx++;
  24433. }
  24434. }
  24435. #ifdef WOLFSSL_EKU_OID
  24436. if (input & EXTKEYUSE_USER) {
  24437. /* Iterate through OID values */
  24438. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  24439. sz = cert->extKeyUsageOIDSz[i];
  24440. if (sz > 0) {
  24441. /* Set template item. */
  24442. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  24443. sizeof(ASNItem));
  24444. /* Set data item. */
  24445. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  24446. sz);
  24447. asnIdx++;
  24448. }
  24449. }
  24450. }
  24451. #endif /* WOLFSSL_EKU_OID */
  24452. (void)cert;
  24453. }
  24454. /* Calculate size of encoding. */
  24455. sz = 0;
  24456. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  24457. }
  24458. /* When buffer to write to, ensure it's big enough. */
  24459. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  24460. ret = BUFFER_E;
  24461. }
  24462. if ((ret == 0) && (output != NULL)) {
  24463. /* Encode extended key usage. */
  24464. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  24465. }
  24466. if (ret == 0) {
  24467. /* Return the encoding size. */
  24468. ret = sz;
  24469. }
  24470. /* Dispose of allocated data. */
  24471. if (extKuASN != NULL) {
  24472. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24473. }
  24474. if (dataASN != NULL) {
  24475. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24476. }
  24477. return ret;
  24478. #endif
  24479. }
  24480. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  24481. #ifndef WOLFSSL_ASN_TEMPLATE
  24482. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  24483. {
  24484. word32 idx;
  24485. byte unusedBits = 0;
  24486. byte nsCertType = input;
  24487. word32 totalSz;
  24488. word32 bitStrSz;
  24489. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  24490. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24491. if (cert == NULL || output == NULL ||
  24492. input == 0)
  24493. return BAD_FUNC_ARG;
  24494. totalSz = sizeof(nscerttype_oid);
  24495. /* Get amount of lsb zero's */
  24496. for (;(input & 1) == 0; input >>= 1)
  24497. unusedBits++;
  24498. /* 1 byte of NS Cert Type extension */
  24499. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  24500. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  24501. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  24502. return BAD_FUNC_ARG;
  24503. /* 1. Seq + Total Len */
  24504. idx = SetSequence(totalSz, output);
  24505. /* 2. Object ID */
  24506. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  24507. idx += sizeof(nscerttype_oid);
  24508. /* 3. Octet String */
  24509. idx += SetOctetString(bitStrSz, &output[idx]);
  24510. /* 4. Bit String */
  24511. idx += SetBitString(1, unusedBits, &output[idx]);
  24512. output[idx++] = nsCertType;
  24513. return (int)idx;
  24514. }
  24515. #endif
  24516. #endif
  24517. #ifndef WOLFSSL_ASN_TEMPLATE
  24518. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  24519. int inSz)
  24520. {
  24521. word32 idx;
  24522. word32 totalSz;
  24523. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  24524. if (cert == NULL || output == NULL ||
  24525. input == 0 || inSz <= 0)
  24526. return BAD_FUNC_ARG;
  24527. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  24528. (word32)inSz;
  24529. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  24530. return BAD_FUNC_ARG;
  24531. /* 1. Seq + Total Len */
  24532. idx = SetSequence(totalSz, output);
  24533. /* 2. Object ID */
  24534. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  24535. idx += sizeof(crlinfo_oid);
  24536. /* 3. Octet String */
  24537. idx += SetOctetString((word32)inSz, &output[idx]);
  24538. /* 4. CRL Info */
  24539. XMEMCPY(&output[idx], input, (size_t)inSz);
  24540. idx += (word32)inSz;
  24541. return (int)idx;
  24542. }
  24543. #endif
  24544. /* encode Certificate Policies, return total bytes written
  24545. * each input value must be ITU-T X.690 formatted : a.b.c...
  24546. * input must be an array of values with a NULL terminated for the latest
  24547. * RFC5280 : non-critical */
  24548. static int SetCertificatePolicies(byte *output,
  24549. word32 outputSz,
  24550. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  24551. word16 nb_certpol,
  24552. void* heap)
  24553. {
  24554. #ifndef WOLFSSL_ASN_TEMPLATE
  24555. byte oid[MAX_OID_SZ];
  24556. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  24557. byte out[MAX_CERTPOL_SZ];
  24558. word32 oidSz;
  24559. word32 outSz;
  24560. word32 i = 0;
  24561. word32 der_oidSz[MAX_CERTPOL_NB];
  24562. int ret;
  24563. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  24564. const byte oid_oid[] = { 0x06 };
  24565. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  24566. return BAD_FUNC_ARG;
  24567. for (i = 0; i < nb_certpol; i++) {
  24568. oidSz = sizeof(oid);
  24569. XMEMSET(oid, 0, oidSz);
  24570. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  24571. if (ret != 0)
  24572. return ret;
  24573. /* compute sequence value for the oid */
  24574. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  24575. sizeof(oid_oid), oid, oidSz);
  24576. if (ret <= 0)
  24577. return ret;
  24578. else
  24579. der_oidSz[i] = (word32)ret;
  24580. }
  24581. /* concatenate oid, keep two byte for sequence/size of the created value */
  24582. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  24583. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  24584. outSz += der_oidSz[i];
  24585. }
  24586. /* add sequence */
  24587. ret = (int)SetSequence(outSz-2, out);
  24588. if (ret <= 0)
  24589. return ret;
  24590. /* add Policy OID to compute final value */
  24591. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  24592. out, outSz);
  24593. #else
  24594. int i;
  24595. int ret = 0;
  24596. byte oid[MAX_OID_SZ];
  24597. word32 oidSz;
  24598. word32 sz = 0;
  24599. int piSz;
  24600. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  24601. ret = BAD_FUNC_ARG;
  24602. }
  24603. /* Put in policyIdentifier but not policyQualifiers. */
  24604. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  24605. ASNSetData dataASN[policyInfoASN_Length];
  24606. oidSz = sizeof(oid);
  24607. XMEMSET(oid, 0, oidSz);
  24608. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  24609. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  24610. if (ret == 0) {
  24611. XMEMSET(dataASN, 0, sizeof(dataASN));
  24612. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  24613. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  24614. &piSz);
  24615. }
  24616. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  24617. ret = BUFFER_E;
  24618. }
  24619. if (ret == 0) {
  24620. if (output != NULL) {
  24621. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  24622. output);
  24623. output += piSz;
  24624. }
  24625. sz += (word32)piSz;
  24626. }
  24627. }
  24628. if (ret == 0) {
  24629. ret = (int)sz;
  24630. }
  24631. return ret;
  24632. #endif
  24633. }
  24634. #endif /* WOLFSSL_CERT_EXT */
  24635. #ifdef WOLFSSL_ALT_NAMES
  24636. #ifndef WOLFSSL_ASN_TEMPLATE
  24637. /* encode Alternative Names, return total bytes written */
  24638. static int SetAltNames(byte *output, word32 outSz,
  24639. const byte *input, word32 length, int critical)
  24640. {
  24641. byte san_len[1 + MAX_LENGTH_SZ];
  24642. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  24643. const byte san_crit[] = { 0x01, 0x01, 0xff };
  24644. word32 seqSz, san_lenSz, idx = 0;
  24645. if (output == NULL || input == NULL)
  24646. return BAD_FUNC_ARG;
  24647. if (outSz < length)
  24648. return BUFFER_E;
  24649. /* Octet String header */
  24650. san_lenSz = SetOctetString(length, san_len);
  24651. if (outSz < MAX_SEQ_SZ)
  24652. return BUFFER_E;
  24653. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  24654. if (critical)
  24655. seqSz += sizeof(san_crit);
  24656. idx = SetSequence(seqSz, output);
  24657. if (seqSz > outSz)
  24658. return BUFFER_E;
  24659. /* put oid */
  24660. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  24661. idx += sizeof(san_oid);
  24662. if (critical) {
  24663. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  24664. idx += sizeof(san_crit);
  24665. }
  24666. /* put octet header */
  24667. XMEMCPY(output+idx, san_len, san_lenSz);
  24668. idx += san_lenSz;
  24669. /* put value */
  24670. XMEMCPY(output+idx, input, length);
  24671. idx += length;
  24672. return (int)idx;
  24673. }
  24674. #endif /* WOLFSSL_ASN_TEMPLATE */
  24675. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  24676. {
  24677. word32 idx;
  24678. const DNS_entry* curName;
  24679. word32 namesSz = 0;
  24680. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24681. word32 i;
  24682. #endif
  24683. if (output == NULL)
  24684. return BAD_FUNC_ARG;
  24685. if (names == NULL)
  24686. return 0;
  24687. curName = names;
  24688. do {
  24689. namesSz += (word32)curName->len + 2 +
  24690. ((curName->len < ASN_LONG_LENGTH) ? 0
  24691. : BytePrecision((word32)curName->len));
  24692. curName = curName->next;
  24693. } while (curName != NULL);
  24694. if (outputSz < MAX_SEQ_SZ + namesSz)
  24695. return BUFFER_E;
  24696. idx = SetSequence(namesSz, output);
  24697. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24698. namesSz += idx;
  24699. i = namesSz;
  24700. #endif
  24701. curName = names;
  24702. do {
  24703. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24704. word32 len = SetLength(curName->len, NULL);
  24705. idx = i - curName->len - len - 1;
  24706. i = idx;
  24707. #endif
  24708. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  24709. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  24710. output[idx] |= ASN_CONSTRUCTED;
  24711. }
  24712. idx++;
  24713. idx += SetLength((word32)curName->len, output + idx);
  24714. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  24715. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  24716. idx += (word32)curName->len;
  24717. #endif
  24718. curName = curName->next;
  24719. } while (curName != NULL);
  24720. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24721. idx = namesSz;
  24722. #endif
  24723. return (int)idx;
  24724. }
  24725. #endif /* WOLFSSL_ALT_NAMES */
  24726. #endif /* WOLFSSL_CERT_GEN */
  24727. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  24728. /* Simple domain name OID size. */
  24729. #define DN_OID_SZ 3
  24730. /* Encodes one attribute of the name (issuer/subject)
  24731. *
  24732. * name structure to hold result of encoding
  24733. * nameStr value to be encoded
  24734. * nameTag tag of encoding i.e CTC_UTF8
  24735. * type id of attribute i.e ASN_COMMON_NAME
  24736. * emailTag tag of email i.e CTC_UTF8
  24737. * returns length on success
  24738. */
  24739. static int EncodeName(EncodedName* name, const char* nameStr,
  24740. byte nameTag, byte type, byte emailTag, CertName* cname)
  24741. {
  24742. #if !defined(WOLFSSL_ASN_TEMPLATE)
  24743. word32 idx = 0;
  24744. /* bottom up */
  24745. byte firstLen[1 + MAX_LENGTH_SZ];
  24746. byte secondLen[MAX_LENGTH_SZ];
  24747. byte sequence[MAX_SEQ_SZ];
  24748. byte set[MAX_SET_SZ];
  24749. word32 strLen;
  24750. word32 thisLen;
  24751. word32 firstSz, secondSz, seqSz, setSz;
  24752. if (nameStr == NULL) {
  24753. name->used = 0;
  24754. return 0;
  24755. }
  24756. thisLen = strLen = (word32)XSTRLEN(nameStr);
  24757. #ifdef WOLFSSL_CUSTOM_OID
  24758. if (type == ASN_CUSTOM_NAME) {
  24759. if (cname == NULL || cname->custom.oidSz == 0) {
  24760. name->used = 0;
  24761. return 0;
  24762. }
  24763. thisLen = strLen = (word32)cname->custom.valSz;
  24764. }
  24765. #else
  24766. (void)cname;
  24767. #endif
  24768. if (strLen == 0) { /* no user data for this item */
  24769. name->used = 0;
  24770. return 0;
  24771. }
  24772. /* Restrict country code size */
  24773. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  24774. WOLFSSL_MSG("Country code size error");
  24775. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  24776. return ASN_COUNTRY_SIZE_E;
  24777. }
  24778. secondSz = SetLength(strLen, secondLen);
  24779. thisLen += secondSz;
  24780. switch (type) {
  24781. case ASN_EMAIL_NAME: /* email */
  24782. thisLen += (int)sizeof(attrEmailOid);
  24783. firstSz = (int)sizeof(attrEmailOid);
  24784. break;
  24785. case ASN_DOMAIN_COMPONENT:
  24786. thisLen += (int)sizeof(dcOid);
  24787. firstSz = (int)sizeof(dcOid);
  24788. break;
  24789. case ASN_USER_ID:
  24790. thisLen += (int)sizeof(uidOid);
  24791. firstSz = (int)sizeof(uidOid);
  24792. break;
  24793. case ASN_FAVOURITE_DRINK:
  24794. thisLen += (int)sizeof(fvrtDrk);
  24795. firstSz = (int)sizeof(fvrtDrk);
  24796. break;
  24797. #ifdef WOLFSSL_CUSTOM_OID
  24798. case ASN_CUSTOM_NAME:
  24799. thisLen += cname->custom.oidSz;
  24800. firstSz = cname->custom.oidSz;
  24801. break;
  24802. #endif
  24803. #ifdef WOLFSSL_CERT_REQ
  24804. case ASN_CONTENT_TYPE:
  24805. thisLen += (int)sizeof(attrPkcs9ContentTypeOid);
  24806. firstSz = (int)sizeof(attrPkcs9ContentTypeOid);
  24807. break;
  24808. #endif
  24809. default:
  24810. thisLen += DN_OID_SZ;
  24811. firstSz = DN_OID_SZ;
  24812. }
  24813. thisLen++; /* id type */
  24814. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  24815. thisLen += firstSz;
  24816. seqSz = SetSequence(thisLen, sequence);
  24817. thisLen += seqSz;
  24818. setSz = SetSet(thisLen, set);
  24819. thisLen += setSz;
  24820. if (thisLen > (int)sizeof(name->encoded)) {
  24821. return BUFFER_E;
  24822. }
  24823. /* store it */
  24824. idx = 0;
  24825. /* set */
  24826. XMEMCPY(name->encoded, set, setSz);
  24827. idx += setSz;
  24828. /* seq */
  24829. XMEMCPY(name->encoded + idx, sequence, seqSz);
  24830. idx += seqSz;
  24831. /* asn object id */
  24832. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  24833. idx += firstSz;
  24834. switch (type) {
  24835. case ASN_EMAIL_NAME:
  24836. /* email joint id */
  24837. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  24838. idx += (int)sizeof(attrEmailOid);
  24839. name->encoded[idx++] = emailTag;
  24840. break;
  24841. case ASN_DOMAIN_COMPONENT:
  24842. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  24843. idx += (int)sizeof(dcOid)-1;
  24844. /* id type */
  24845. name->encoded[idx++] = type;
  24846. /* str type */
  24847. name->encoded[idx++] = nameTag;
  24848. break;
  24849. case ASN_USER_ID:
  24850. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  24851. idx += (int)sizeof(uidOid);
  24852. /* str type */
  24853. name->encoded[idx++] = nameTag;
  24854. break;
  24855. case ASN_FAVOURITE_DRINK:
  24856. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  24857. idx += (int)sizeof(fvrtDrk);
  24858. /* str type */
  24859. name->encoded[idx++] = nameTag;
  24860. break;
  24861. #ifdef WOLFSSL_CUSTOM_OID
  24862. case ASN_CUSTOM_NAME:
  24863. XMEMCPY(name->encoded + idx, cname->custom.oid,
  24864. cname->custom.oidSz);
  24865. idx += cname->custom.oidSz;
  24866. /* str type */
  24867. name->encoded[idx++] = nameTag;
  24868. break;
  24869. #endif
  24870. #ifdef WOLFSSL_CERT_REQ
  24871. case ASN_CONTENT_TYPE:
  24872. XMEMCPY(name->encoded + idx, attrPkcs9ContentTypeOid,
  24873. sizeof(attrPkcs9ContentTypeOid));
  24874. idx += (int)sizeof(attrPkcs9ContentTypeOid);
  24875. /* str type */
  24876. name->encoded[idx++] = nameTag;
  24877. break;
  24878. #endif
  24879. default:
  24880. name->encoded[idx++] = 0x55;
  24881. name->encoded[idx++] = 0x04;
  24882. /* id type */
  24883. name->encoded[idx++] = type;
  24884. /* str type */
  24885. name->encoded[idx++] = nameTag;
  24886. }
  24887. /* second length */
  24888. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  24889. idx += secondSz;
  24890. /* str value */
  24891. XMEMCPY(name->encoded + idx, nameStr, strLen);
  24892. idx += strLen;
  24893. name->type = type;
  24894. name->totalLen = (int)idx;
  24895. name->used = 1;
  24896. return (int)idx;
  24897. #else
  24898. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  24899. ASNItem namesASN[rdnASN_Length];
  24900. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  24901. int ret = 0;
  24902. int sz = 0;
  24903. const byte* oid;
  24904. word32 oidSz = 0;
  24905. word32 nameSz = 0;
  24906. /* Validate input parameters. */
  24907. if ((name == NULL) || (nameStr == NULL)) {
  24908. ret = BAD_FUNC_ARG;
  24909. }
  24910. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  24911. if (ret == 0) {
  24912. nameSz = (word32)XSTRLEN(nameStr);
  24913. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  24914. * based on type. */
  24915. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  24916. /* Set OID and ASN.1 tag for name depending on type. */
  24917. switch (type) {
  24918. case ASN_EMAIL_NAME:
  24919. /* email OID different to standard types. */
  24920. oid = attrEmailOid;
  24921. oidSz = sizeof(attrEmailOid);
  24922. /* Use email specific type/tag. */
  24923. nameTag = emailTag;
  24924. break;
  24925. case ASN_DOMAIN_COMPONENT:
  24926. /* Domain component OID different to standard types. */
  24927. oid = dcOid;
  24928. oidSz = sizeof(dcOid);
  24929. break;
  24930. case ASN_USER_ID:
  24931. /* Domain component OID different to standard types. */
  24932. oid = uidOid;
  24933. oidSz = sizeof(uidOid);
  24934. break;
  24935. case ASN_FAVOURITE_DRINK:
  24936. oid = fvrtDrk;
  24937. oidSz = sizeof(fvrtDrk);
  24938. break;
  24939. #ifdef WOLFSSL_CUSTOM_OID
  24940. case ASN_CUSTOM_NAME:
  24941. nameSz = cname->custom.valSz;
  24942. oid = cname->custom.oid;
  24943. oidSz = cname->custom.oidSz;
  24944. break;
  24945. #endif
  24946. #ifdef WOLFSSL_CERT_REQ
  24947. case ASN_CONTENT_TYPE:
  24948. oid = attrPkcs9ContentTypeOid;
  24949. oidSz = sizeof(attrPkcs9ContentTypeOid);
  24950. break;
  24951. #endif
  24952. default:
  24953. /* Construct OID using type. */
  24954. dnOid[2] = type;
  24955. oid = dnOid;
  24956. oidSz = DN_OID_SZ;
  24957. break;
  24958. }
  24959. /* Set OID corresponding to the name type. */
  24960. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24961. /* Set name string. */
  24962. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  24963. /* Set the ASN.1 tag for the name string. */
  24964. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  24965. /* Calculate size of encoded name and indexes of components. */
  24966. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  24967. }
  24968. /* Check if name's buffer is big enough. */
  24969. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  24970. ret = BUFFER_E;
  24971. }
  24972. if (ret == 0) {
  24973. /* Encode name into the buffer. */
  24974. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  24975. /* Cache the type and size, and set that it is used. */
  24976. name->type = type;
  24977. name->totalLen = sz;
  24978. name->used = 1;
  24979. /* Return size of encoding. */
  24980. ret = sz;
  24981. }
  24982. (void)cname;
  24983. FREE_ASNSETDATA(dataASN, NULL);
  24984. return ret;
  24985. #endif /* WOLFSSL_ASN_TEMPLATE */
  24986. }
  24987. /* canonical encoding one attribute of the name (issuer/subject)
  24988. * call EncodeName with CTC_UTF8 for email type
  24989. *
  24990. * name structure to hold result of encoding
  24991. * nameStr value to be encoded
  24992. * nameType type of encoding i.e CTC_UTF8
  24993. * type id of attribute i.e ASN_COMMON_NAME
  24994. *
  24995. * returns length on success
  24996. */
  24997. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  24998. char nameType, byte type)
  24999. {
  25000. return EncodeName(name, nameStr, (byte)nameType, type,
  25001. ASN_UTF8STRING, NULL);
  25002. }
  25003. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  25004. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \
  25005. (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA))
  25006. /* Convert key usage string (comma delimited, null terminated) to word16
  25007. * Returns 0 on success, negative on error */
  25008. int ParseKeyUsageStr(const char* value, word16* keyUsage, void* heap)
  25009. {
  25010. int ret = 0;
  25011. char *token, *str, *ptr;
  25012. word32 len = 0;
  25013. word16 usage = 0;
  25014. if (value == NULL || keyUsage == NULL) {
  25015. return BAD_FUNC_ARG;
  25016. }
  25017. /* duplicate string (including terminator) */
  25018. len = (word32)XSTRLEN(value);
  25019. str = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25020. if (str == NULL) {
  25021. return MEMORY_E;
  25022. }
  25023. XMEMCPY(str, value, len + 1);
  25024. /* parse value, and set corresponding Key Usage value */
  25025. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  25026. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25027. return KEYUSAGE_E;
  25028. }
  25029. while (token != NULL) {
  25030. if (!XSTRCASECMP(token, "digitalSignature"))
  25031. usage |= KEYUSE_DIGITAL_SIG;
  25032. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  25033. !XSTRCASECMP(token, "contentCommitment"))
  25034. usage |= KEYUSE_CONTENT_COMMIT;
  25035. else if (!XSTRCASECMP(token, "keyEncipherment"))
  25036. usage |= KEYUSE_KEY_ENCIPHER;
  25037. else if (!XSTRCASECMP(token, "dataEncipherment"))
  25038. usage |= KEYUSE_DATA_ENCIPHER;
  25039. else if (!XSTRCASECMP(token, "keyAgreement"))
  25040. usage |= KEYUSE_KEY_AGREE;
  25041. else if (!XSTRCASECMP(token, "keyCertSign"))
  25042. usage |= KEYUSE_KEY_CERT_SIGN;
  25043. else if (!XSTRCASECMP(token, "cRLSign"))
  25044. usage |= KEYUSE_CRL_SIGN;
  25045. else if (!XSTRCASECMP(token, "encipherOnly"))
  25046. usage |= KEYUSE_ENCIPHER_ONLY;
  25047. else if (!XSTRCASECMP(token, "decipherOnly"))
  25048. usage |= KEYUSE_DECIPHER_ONLY;
  25049. else {
  25050. ret = KEYUSAGE_E;
  25051. break;
  25052. }
  25053. token = XSTRTOK(NULL, ",", &ptr);
  25054. }
  25055. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25056. if (ret == 0) {
  25057. *keyUsage = usage;
  25058. }
  25059. return ret;
  25060. }
  25061. /* Convert extended key usage string (comma delimited, null terminated) to byte
  25062. * Returns 0 on success, negative on error */
  25063. int ParseExtKeyUsageStr(const char* value, byte* extKeyUsage, void* heap)
  25064. {
  25065. int ret = 0;
  25066. char *token, *str, *ptr;
  25067. word32 len = 0;
  25068. byte usage = 0;
  25069. if (value == NULL || extKeyUsage == NULL) {
  25070. return BAD_FUNC_ARG;
  25071. }
  25072. /* duplicate string (including terminator) */
  25073. len = (word32)XSTRLEN(value);
  25074. str = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25075. if (str == NULL) {
  25076. return MEMORY_E;
  25077. }
  25078. XMEMCPY(str, value, len + 1);
  25079. /* parse value, and set corresponding Key Usage value */
  25080. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  25081. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25082. return EXTKEYUSAGE_E;
  25083. }
  25084. while (token != NULL) {
  25085. if (!XSTRCASECMP(token, "any"))
  25086. usage |= EXTKEYUSE_ANY;
  25087. else if (!XSTRCASECMP(token, "serverAuth"))
  25088. usage |= EXTKEYUSE_SERVER_AUTH;
  25089. else if (!XSTRCASECMP(token, "clientAuth"))
  25090. usage |= EXTKEYUSE_CLIENT_AUTH;
  25091. else if (!XSTRCASECMP(token, "codeSigning"))
  25092. usage |= EXTKEYUSE_CODESIGN;
  25093. else if (!XSTRCASECMP(token, "emailProtection"))
  25094. usage |= EXTKEYUSE_EMAILPROT;
  25095. else if (!XSTRCASECMP(token, "timeStamping"))
  25096. usage |= EXTKEYUSE_TIMESTAMP;
  25097. else if (!XSTRCASECMP(token, "OCSPSigning"))
  25098. usage |= EXTKEYUSE_OCSP_SIGN;
  25099. else {
  25100. ret = EXTKEYUSAGE_E;
  25101. break;
  25102. }
  25103. token = XSTRTOK(NULL, ",", &ptr);
  25104. }
  25105. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25106. if (ret == 0) {
  25107. *extKeyUsage = usage;
  25108. }
  25109. return ret;
  25110. }
  25111. #endif /* (CERT_GEN && CERT_EXT) || (OPENSSL_ALL || OPENSSL_EXTRA) */
  25112. #ifdef WOLFSSL_CERT_GEN
  25113. /* Encodes one attribute of the name (issuer/subject)
  25114. * call we_EncodeName_ex with 0x16, IA5String for email type
  25115. * name structure to hold result of encoding
  25116. * nameStr value to be encoded
  25117. * nameType type of encoding i.e CTC_UTF8
  25118. * type id of attribute i.e ASN_COMMON_NAME
  25119. *
  25120. * returns length on success
  25121. */
  25122. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  25123. byte type)
  25124. {
  25125. return EncodeName(name, nameStr, (byte)nameType, type,
  25126. ASN_IA5_STRING, NULL);
  25127. }
  25128. #ifdef WOLFSSL_ASN_TEMPLATE
  25129. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  25130. word32 oidSz, byte tag, const byte* data, word32 sz)
  25131. {
  25132. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  25133. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  25134. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  25135. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  25136. }
  25137. #ifdef WOLFSSL_MULTI_ATTRIB
  25138. static int FindMultiAttrib(CertName* name, int id, int* idx)
  25139. {
  25140. int i;
  25141. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  25142. if (name->name[i].sz > 0 && name->name[i].id == id) {
  25143. break;
  25144. }
  25145. }
  25146. if (i == CTC_MAX_ATTRIB) {
  25147. i = -1;
  25148. }
  25149. *idx = i;
  25150. return i >= 0;
  25151. }
  25152. #endif
  25153. /* ASN.1 template for the SEQUENCE around the RDNs.
  25154. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  25155. */
  25156. static const ASNItem nameASN[] = {
  25157. { 0, ASN_SEQUENCE, 1, 1, 0 },
  25158. };
  25159. enum {
  25160. NAMEASN_IDX_SEQ = 0
  25161. };
  25162. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  25163. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  25164. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  25165. int maxIdx, CertName* name)
  25166. {
  25167. int i;
  25168. int idx;
  25169. int ret = 0;
  25170. word32 nameLen[NAME_ENTRIES];
  25171. #ifdef WOLFSSL_MULTI_ATTRIB
  25172. int j;
  25173. #endif
  25174. for (i = 0; i < NAME_ENTRIES; i++) {
  25175. /* Keep name length to identify component is to be encoded. */
  25176. const char* nameStr = GetOneCertName(name, i);
  25177. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  25178. }
  25179. idx = nameASN_Length;
  25180. for (i = 0; i < NAME_ENTRIES; i++) {
  25181. int type = GetCertNameId(i);
  25182. #ifdef WOLFSSL_MULTI_ATTRIB
  25183. j = -1;
  25184. /* Put DomainComponents before OrgUnitName. */
  25185. while (FindMultiAttrib(name, type, &j)) {
  25186. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  25187. continue;
  25188. }
  25189. if (dataASN != NULL && namesASN != NULL) {
  25190. if (idx > maxIdx - (int)rdnASN_Length) {
  25191. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  25192. ret = BUFFER_E;
  25193. break;
  25194. }
  25195. /* Copy data into dynamic vars. */
  25196. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  25197. sizeof(dcOid), (byte)name->name[j].type,
  25198. (byte*)name->name[j].value,
  25199. (word32)name->name[j].sz);
  25200. }
  25201. idx += (int)rdnASN_Length;
  25202. }
  25203. if (ret != 0)
  25204. break;
  25205. #endif
  25206. if (nameLen[i] > 0) {
  25207. if (dataASN != NULL) {
  25208. if (idx > maxIdx - (int)rdnASN_Length) {
  25209. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  25210. ret = BUFFER_E;
  25211. break;
  25212. }
  25213. /* Write out first instance of attribute type. */
  25214. if (type == ASN_EMAIL_NAME) {
  25215. /* Copy email data into dynamic vars. */
  25216. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  25217. sizeof(attrEmailOid), ASN_IA5_STRING,
  25218. (const byte*)GetOneCertName(name, i), nameLen[i]);
  25219. }
  25220. else if (type == ASN_USER_ID) {
  25221. /* Copy userID data into dynamic vars. */
  25222. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  25223. sizeof(uidOid), (byte)GetNameType(name, i),
  25224. (const byte*)GetOneCertName(name, i), nameLen[i]);
  25225. }
  25226. else if (type == ASN_FAVOURITE_DRINK) {
  25227. /* Copy favourite drink data into dynamic vars. */
  25228. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  25229. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  25230. (const byte*)GetOneCertName(name, i), nameLen[i]);
  25231. }
  25232. else if (type == ASN_CUSTOM_NAME) {
  25233. #ifdef WOLFSSL_CUSTOM_OID
  25234. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  25235. name->custom.oidSz, name->custom.enc,
  25236. name->custom.val, name->custom.valSz);
  25237. #endif
  25238. }
  25239. else {
  25240. /* Copy name data into dynamic vars. */
  25241. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  25242. NAME_OID_SZ, (byte)GetNameType(name, i),
  25243. (const byte*)GetOneCertName(name, i), nameLen[i]);
  25244. }
  25245. }
  25246. idx += (int)rdnASN_Length;
  25247. }
  25248. #ifdef WOLFSSL_MULTI_ATTRIB
  25249. j = -1;
  25250. /* Write all other attributes of this type. */
  25251. while (FindMultiAttrib(name, type, &j)) {
  25252. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  25253. continue;
  25254. }
  25255. if (dataASN != NULL && namesASN != NULL) {
  25256. if (idx > maxIdx - (int)rdnASN_Length) {
  25257. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  25258. ret = BUFFER_E;
  25259. break;
  25260. }
  25261. /* Copy data into dynamic vars. */
  25262. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  25263. NAME_OID_SZ, (byte)name->name[j].type,
  25264. (byte*)name->name[j].value, (word32)name->name[j].sz);
  25265. }
  25266. idx += (int)rdnASN_Length;
  25267. }
  25268. if (ret != 0)
  25269. break;
  25270. #endif
  25271. }
  25272. if (ret == 0)
  25273. ret = idx;
  25274. return ret;
  25275. }
  25276. #endif
  25277. /* encode CertName into output, return total bytes written */
  25278. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  25279. {
  25280. #ifndef WOLFSSL_ASN_TEMPLATE
  25281. int ret;
  25282. int i;
  25283. word32 idx, totalBytes = 0;
  25284. #ifdef WOLFSSL_SMALL_STACK
  25285. EncodedName* names = NULL;
  25286. #else
  25287. EncodedName names[NAME_ENTRIES];
  25288. #endif
  25289. #ifdef WOLFSSL_MULTI_ATTRIB
  25290. EncodedName addNames[CTC_MAX_ATTRIB];
  25291. int j, type;
  25292. #endif
  25293. if (output == NULL || name == NULL)
  25294. return BAD_FUNC_ARG;
  25295. if (outputSz < 3)
  25296. return BUFFER_E;
  25297. #ifdef WOLFSSL_SMALL_STACK
  25298. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  25299. DYNAMIC_TYPE_TMP_BUFFER);
  25300. if (names == NULL)
  25301. return MEMORY_E;
  25302. #endif
  25303. for (i = 0; i < NAME_ENTRIES; i++) {
  25304. const char* nameStr = GetOneCertName(name, i);
  25305. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  25306. GetCertNameId(i), ASN_IA5_STRING, name);
  25307. if (ret < 0) {
  25308. #ifdef WOLFSSL_SMALL_STACK
  25309. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25310. #endif
  25311. WOLFSSL_MSG("EncodeName failed");
  25312. return BUFFER_E;
  25313. }
  25314. totalBytes += (word32)ret;
  25315. }
  25316. #ifdef WOLFSSL_MULTI_ATTRIB
  25317. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  25318. if (name->name[i].sz > 0) {
  25319. ret = EncodeName(&addNames[i], name->name[i].value,
  25320. (byte)name->name[i].type, (byte)name->name[i].id,
  25321. ASN_IA5_STRING, NULL);
  25322. if (ret < 0) {
  25323. #ifdef WOLFSSL_SMALL_STACK
  25324. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25325. #endif
  25326. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  25327. return BUFFER_E;
  25328. }
  25329. totalBytes += (word32)ret;
  25330. }
  25331. else {
  25332. addNames[i].used = 0;
  25333. }
  25334. }
  25335. #endif /* WOLFSSL_MULTI_ATTRIB */
  25336. /* header */
  25337. idx = SetSequence(totalBytes, output);
  25338. totalBytes += idx;
  25339. if (totalBytes > WC_ASN_NAME_MAX) {
  25340. #ifdef WOLFSSL_SMALL_STACK
  25341. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25342. #endif
  25343. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  25344. return BUFFER_E;
  25345. }
  25346. for (i = 0; i < NAME_ENTRIES; i++) {
  25347. #ifdef WOLFSSL_MULTI_ATTRIB
  25348. type = GetCertNameId(i);
  25349. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  25350. if (name->name[j].sz > 0 && type == name->name[j].id) {
  25351. if (outputSz < idx + (word32)addNames[j].totalLen) {
  25352. #ifdef WOLFSSL_SMALL_STACK
  25353. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25354. #endif
  25355. WOLFSSL_MSG("Not enough space left for DC value");
  25356. return BUFFER_E;
  25357. }
  25358. XMEMCPY(output + idx, addNames[j].encoded,
  25359. (size_t)addNames[j].totalLen);
  25360. idx += (word32)addNames[j].totalLen;
  25361. }
  25362. }
  25363. #endif /* WOLFSSL_MULTI_ATTRIB */
  25364. if (names[i].used) {
  25365. if (outputSz < idx + (word32)names[i].totalLen) {
  25366. #ifdef WOLFSSL_SMALL_STACK
  25367. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25368. #endif
  25369. return BUFFER_E;
  25370. }
  25371. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  25372. idx += (word32)names[i].totalLen;
  25373. }
  25374. }
  25375. #ifdef WOLFSSL_SMALL_STACK
  25376. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  25377. #endif
  25378. (void)heap;
  25379. return (int)totalBytes;
  25380. #else
  25381. /* TODO: consider calculating size of entries, putting length into
  25382. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  25383. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  25384. ASNItem* namesASN = NULL;
  25385. word32 items = 0;
  25386. int ret = 0;
  25387. int sz = 0;
  25388. /* Calculate length of name entries and size for allocating. */
  25389. ret = SetNameRdnItems(NULL, NULL, 0, name);
  25390. if (ret > 0) {
  25391. items = (word32)ret;
  25392. ret = 0;
  25393. }
  25394. /* Allocate dynamic data items. */
  25395. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  25396. DYNAMIC_TYPE_TMP_BUFFER);
  25397. if (dataASN == NULL) {
  25398. ret = MEMORY_E;
  25399. }
  25400. else {
  25401. /* Allocate dynamic ASN.1 template items. */
  25402. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  25403. DYNAMIC_TYPE_TMP_BUFFER);
  25404. if (namesASN == NULL) {
  25405. ret = MEMORY_E;
  25406. }
  25407. }
  25408. if (ret == 0) {
  25409. /* Clear the dynamic data. */
  25410. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  25411. /* Copy in the outer sequence. */
  25412. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  25413. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  25414. if (ret == (int)items)
  25415. ret = 0;
  25416. else if (ret > 0) {
  25417. WOLFSSL_MSG("SetNameRdnItems returned different length");
  25418. ret = BUFFER_E;
  25419. }
  25420. }
  25421. if (ret == 0) {
  25422. /* Calculate size of encoding. */
  25423. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  25424. }
  25425. /* Check buffer size if passed in. */
  25426. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  25427. ret = BUFFER_E;
  25428. }
  25429. if (ret == 0) {
  25430. if (output != NULL) {
  25431. /* Encode Name. */
  25432. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  25433. }
  25434. else {
  25435. /* Return the encoding size. */
  25436. ret = sz;
  25437. }
  25438. }
  25439. if (namesASN != NULL)
  25440. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25441. if (dataASN != NULL)
  25442. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25443. (void)heap;
  25444. return ret;
  25445. #endif
  25446. }
  25447. int SetName(byte* output, word32 outputSz, CertName* name)
  25448. {
  25449. return SetNameEx(output, outputSz, name, NULL);
  25450. }
  25451. #ifdef WOLFSSL_ASN_TEMPLATE
  25452. static int EncodePublicKey(int keyType, byte* output, int outLen,
  25453. RsaKey* rsaKey, ecc_key* eccKey,
  25454. ed25519_key* ed25519Key, ed448_key* ed448Key,
  25455. DsaKey* dsaKey)
  25456. {
  25457. int ret = 0;
  25458. (void)outLen;
  25459. (void)rsaKey;
  25460. (void)eccKey;
  25461. (void)ed25519Key;
  25462. (void)ed448Key;
  25463. (void)dsaKey;
  25464. switch (keyType) {
  25465. #ifndef NO_RSA
  25466. case RSA_KEY:
  25467. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  25468. if (ret <= 0) {
  25469. ret = PUBLIC_KEY_E;
  25470. }
  25471. break;
  25472. #endif
  25473. #ifdef HAVE_ECC
  25474. case ECC_KEY:
  25475. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  25476. if (ret <= 0) {
  25477. ret = PUBLIC_KEY_E;
  25478. }
  25479. break;
  25480. #endif /* HAVE_ECC */
  25481. #ifdef HAVE_ED25519
  25482. case ED25519_KEY:
  25483. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  25484. (word32)outLen, 1);
  25485. if (ret <= 0) {
  25486. ret = PUBLIC_KEY_E;
  25487. }
  25488. break;
  25489. #endif
  25490. #ifdef HAVE_ED448
  25491. case ED448_KEY:
  25492. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  25493. if (ret <= 0) {
  25494. ret = PUBLIC_KEY_E;
  25495. }
  25496. break;
  25497. #endif
  25498. default:
  25499. ret = PUBLIC_KEY_E;
  25500. break;
  25501. }
  25502. return ret;
  25503. }
  25504. /* ASN.1 template for certificate extensions.
  25505. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25506. * All extensions supported for encoding are described.
  25507. */
  25508. static const ASNItem static_certExtsASN[] = {
  25509. /* Basic Constraints Extension - 4.2.1.9 */
  25510. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25511. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25512. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  25513. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  25514. /* cA */
  25515. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  25516. /* pathLenConstraint */
  25517. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  25518. /* Subject Alternative Name - 4.2.1.6 */
  25519. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25520. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25521. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  25522. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25523. /* Subject Key Identifier - 4.2.1.2 */
  25524. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25525. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25526. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  25527. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  25528. /* Authority Key Identifier - 4.2.1.1 */
  25529. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25530. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25531. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  25532. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  25533. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  25534. /* Key Usage - 4.2.1.3 */
  25535. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25536. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25537. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  25538. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  25539. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  25540. /* Extended Key Usage - 4,2,1,12 */
  25541. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25542. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25543. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25544. /* Certificate Policies - 4.2.1.4 */
  25545. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25546. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25547. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  25548. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  25549. /* Netscape Certificate Type */
  25550. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25551. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25552. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  25553. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  25554. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25555. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25556. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25557. #ifdef WOLFSSL_DUAL_ALG_CERTS
  25558. /* SAPKI_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25559. /* SAPKI_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25560. /* SAPKI_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25561. /* ALTSIGALG_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25562. /* ALTSIGALG_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25563. /* ALTSIGALG_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25564. /* ALTSIGVAL_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25565. /* ALTSIGVAL_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25566. /* ALTSIGVAL_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25567. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  25568. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25569. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25570. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25571. };
  25572. enum {
  25573. CERTEXTSASN_IDX_BC_SEQ = 0,
  25574. CERTEXTSASN_IDX_BC_OID,
  25575. CERTEXTSASN_IDX_BC_STR,
  25576. CERTEXTSASN_IDX_BC_STR_SEQ,
  25577. CERTEXTSASN_IDX_BC_CA,
  25578. CERTEXTSASN_IDX_BC_PATHLEN,
  25579. CERTEXTSASN_IDX_SAN_SEQ,
  25580. CERTEXTSASN_IDX_SAN_OID,
  25581. CERTEXTSASN_IDX_SAN_CRIT,
  25582. CERTEXTSASN_IDX_SAN_STR,
  25583. CERTEXTSASN_IDX_SKID_SEQ,
  25584. CERTEXTSASN_IDX_SKID_OID,
  25585. CERTEXTSASN_IDX_SKID_STR,
  25586. CERTEXTSASN_IDX_SKID_KEYID,
  25587. CERTEXTSASN_IDX_AKID_SEQ,
  25588. CERTEXTSASN_IDX_AKID_OID,
  25589. CERTEXTSASN_IDX_AKID_STR,
  25590. CERTEXTSASN_IDX_AKID_STR_SEQ,
  25591. CERTEXTSASN_IDX_AKID_KEYID,
  25592. CERTEXTSASN_IDX_KU_SEQ,
  25593. CERTEXTSASN_IDX_KU_OID,
  25594. CERTEXTSASN_IDX_KU_CRIT,
  25595. CERTEXTSASN_IDX_KU_STR,
  25596. CERTEXTSASN_IDX_KU_USAGE,
  25597. CERTEXTSASN_IDX_EKU_SEQ,
  25598. CERTEXTSASN_IDX_EKU_OID,
  25599. CERTEXTSASN_IDX_EKU_STR,
  25600. CERTEXTSASN_IDX_POLICIES_SEQ,
  25601. CERTEXTSASN_IDX_POLICIES_OID,
  25602. CERTEXTSASN_IDX_POLICIES_STR,
  25603. CERTEXTSASN_IDX_POLICIES_INFO,
  25604. CERTEXTSASN_IDX_NSTYPE_SEQ,
  25605. CERTEXTSASN_IDX_NSTYPE_OID,
  25606. CERTEXTSASN_IDX_NSTYPE_STR,
  25607. CERTEXTSASN_IDX_NSTYPE_USAGE,
  25608. CERTEXTSASN_IDX_CRLINFO_SEQ,
  25609. CERTEXTSASN_IDX_CRLINFO_OID,
  25610. CERTEXTSASN_IDX_CRLINFO_STR,
  25611. #ifdef WOLFSSL_DUAL_ALG_CERTS
  25612. CERTEXTSASN_IDX_SAPKI_SEQ,
  25613. CERTEXTSASN_IDX_SAPKI_OID,
  25614. CERTEXTSASN_IDX_SAPKI_STR,
  25615. CERTEXTSASN_IDX_ALTSIGALG_SEQ,
  25616. CERTEXTSASN_IDX_ALTSIGALG_OID,
  25617. CERTEXTSASN_IDX_ALTSIGALG_STR,
  25618. CERTEXTSASN_IDX_ALTSIGVAL_SEQ,
  25619. CERTEXTSASN_IDX_ALTSIGVAL_OID,
  25620. CERTEXTSASN_IDX_ALTSIGVAL_STR,
  25621. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  25622. CERTEXTSASN_IDX_CUSTOM_SEQ,
  25623. CERTEXTSASN_IDX_CUSTOM_OID,
  25624. CERTEXTSASN_IDX_CUSTOM_STR,
  25625. CERTEXTSASN_IDX_START_CUSTOM
  25626. };
  25627. /* Number of items in ASN.1 template for certificate extensions. We multiply
  25628. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  25629. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  25630. + (NUM_CUSTOM_EXT * 4))
  25631. static const ASNItem customExtASN[] = {
  25632. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25633. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25634. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  25635. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25636. };
  25637. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  25638. int forRequest)
  25639. {
  25640. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  25641. int sz = 0;
  25642. int ret = 0;
  25643. int i = 0;
  25644. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  25645. #ifdef WOLFSSL_ALT_NAMES
  25646. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  25647. #endif
  25648. #ifdef WOLFSSL_CERT_EXT
  25649. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  25650. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  25651. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  25652. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  25653. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  25654. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  25655. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  25656. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  25657. #ifdef WOLFSSL_DUAL_ALG_CERTS
  25658. static const byte sapkiOID[] = { 0x55, 0x1d, 0x48 };
  25659. static const byte altSigAlgOID[] = { 0x55, 0x1d, 0x49 };
  25660. static const byte altSigValOID[] = { 0x55, 0x1d, 0x4a };
  25661. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  25662. #endif /* WOLFSSL_CERT_EXT */
  25663. #ifdef WOLFSSL_SMALL_STACK
  25664. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25665. byte *encodedOids;
  25666. #endif
  25667. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  25668. sizeof(ASNItem), cert->heap,
  25669. DYNAMIC_TYPE_TMP_BUFFER);
  25670. if (certExtsASN == NULL) {
  25671. return MEMORY_E;
  25672. }
  25673. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25674. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  25675. DYNAMIC_TYPE_TMP_BUFFER);
  25676. if (encodedOids == NULL) {
  25677. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25678. return MEMORY_E;
  25679. }
  25680. #endif
  25681. #else
  25682. ASNItem certExtsASN[certExtsASN_Length];
  25683. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25684. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  25685. #endif
  25686. #endif
  25687. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  25688. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  25689. * above definition of certExtsASN_Length. */
  25690. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  25691. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  25692. i < (int)certExtsASN_Length; i += 4) {
  25693. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  25694. }
  25695. (void)forRequest;
  25696. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  25697. if (ret == 0) {
  25698. if (cert->isCA) {
  25699. /* Set Basic Constraints to be a Certificate Authority. */
  25700. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  25701. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  25702. if (cert->pathLenSet
  25703. #ifdef WOLFSSL_CERT_EXT
  25704. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25705. #endif
  25706. ) {
  25707. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  25708. cert->pathLen);
  25709. }
  25710. else {
  25711. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  25712. }
  25713. }
  25714. #ifdef WOLFSSL_ALLOW_ENCODING_CA_FALSE
  25715. else if (cert->isCaSet) {
  25716. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 0);
  25717. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  25718. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  25719. }
  25720. #endif
  25721. else if (cert->basicConstSet) {
  25722. /* Set Basic Constraints to be a non Certificate Authority. */
  25723. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  25724. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  25725. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  25726. }
  25727. else {
  25728. /* Don't write out Basic Constraints extension items. */
  25729. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  25730. CERTEXTSASN_IDX_BC_PATHLEN);
  25731. }
  25732. #ifdef WOLFSSL_ALT_NAMES
  25733. if (cert->altNamesSz > 0) {
  25734. /* Set Subject Alternative Name OID and data. */
  25735. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  25736. sanOID, sizeof(sanOID));
  25737. if (cert->altNamesCrit) {
  25738. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  25739. }
  25740. else {
  25741. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  25742. }
  25743. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  25744. cert->altNames, (word32)cert->altNamesSz);
  25745. }
  25746. else
  25747. #endif
  25748. {
  25749. /* Don't write out Subject Alternative Name extension items. */
  25750. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  25751. CERTEXTSASN_IDX_SAN_STR);
  25752. }
  25753. #ifdef WOLFSSL_CERT_EXT
  25754. if (cert->skidSz > 0) {
  25755. /* Set Subject Key Identifier OID and data. */
  25756. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  25757. skidOID, sizeof(skidOID));
  25758. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  25759. cert->skid, (word32)cert->skidSz);
  25760. }
  25761. else
  25762. #endif
  25763. {
  25764. /* Don't write out Subject Key Identifier extension items. */
  25765. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  25766. CERTEXTSASN_IDX_SKID_KEYID);
  25767. }
  25768. #ifdef WOLFSSL_CERT_EXT
  25769. if (cert->akidSz > 0) {
  25770. /* Set Authority Key Identifier OID and data. */
  25771. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  25772. akidOID, sizeof(akidOID));
  25773. #ifdef WOLFSSL_AKID_NAME
  25774. if (cert->rawAkid) {
  25775. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  25776. cert->akid, (word32)cert->akidSz);
  25777. /* cert->akid contains the internal ext structure */
  25778. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  25779. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  25780. }
  25781. else
  25782. #endif
  25783. {
  25784. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  25785. cert->akid, (word32)cert->akidSz);
  25786. }
  25787. }
  25788. else
  25789. #endif
  25790. {
  25791. /* Don't write out Authority Key Identifier extension items. */
  25792. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  25793. CERTEXTSASN_IDX_AKID_KEYID);
  25794. }
  25795. #ifdef WOLFSSL_CERT_EXT
  25796. if (cert->keyUsage != 0) {
  25797. /* Set Key Usage OID, critical and value. */
  25798. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  25799. kuOID, sizeof(kuOID));
  25800. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  25801. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  25802. cert->keyUsage);
  25803. }
  25804. else
  25805. #endif
  25806. {
  25807. /* Don't write out Key Usage extension items. */
  25808. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  25809. CERTEXTSASN_IDX_KU_USAGE);
  25810. }
  25811. #ifdef WOLFSSL_CERT_EXT
  25812. if (cert->extKeyUsage != 0) {
  25813. /* Calculate size of Extended Key Usage data. */
  25814. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  25815. if (sz <= 0) {
  25816. ret = KEYUSAGE_E;
  25817. }
  25818. /* Set Extended Key Usage OID and data. */
  25819. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  25820. ekuOID, sizeof(ekuOID));
  25821. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  25822. NULL, (word32)sz);
  25823. }
  25824. else
  25825. #endif
  25826. {
  25827. /* Don't write out Extended Key Usage extension items. */
  25828. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  25829. CERTEXTSASN_IDX_EKU_STR);
  25830. }
  25831. #ifdef WOLFSSL_CERT_EXT
  25832. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  25833. /* Calculate size of certificate policies. */
  25834. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  25835. cert->certPoliciesNb, cert->heap);
  25836. if (sz > 0) {
  25837. /* Set Certificate Policies OID. */
  25838. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  25839. cpOID, sizeof(cpOID));
  25840. /* Make space for data. */
  25841. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  25842. NULL, (word32)sz);
  25843. }
  25844. else {
  25845. ret = CERTPOLICIES_E;
  25846. }
  25847. }
  25848. else
  25849. #endif
  25850. {
  25851. /* Don't write out Certificate Policies extension items. */
  25852. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  25853. CERTEXTSASN_IDX_POLICIES_INFO);
  25854. }
  25855. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  25856. /* Netscape Certificate Type */
  25857. if (cert->nsCertType != 0) {
  25858. /* Set Netscape Certificate Type OID and data. */
  25859. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  25860. nsCertOID, sizeof(nsCertOID));
  25861. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  25862. &cert->nsCertType, 1);
  25863. }
  25864. else
  25865. #endif
  25866. {
  25867. /* Don't write out Netscape Certificate Type. */
  25868. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  25869. CERTEXTSASN_IDX_NSTYPE_USAGE);
  25870. }
  25871. #ifdef WOLFSSL_CERT_EXT
  25872. if (cert->crlInfoSz > 0) {
  25873. /* Set CRL Distribution Points OID and data. */
  25874. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  25875. crlInfoOID, sizeof(crlInfoOID));
  25876. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  25877. cert->crlInfo, (word32)cert->crlInfoSz);
  25878. }
  25879. else
  25880. #endif
  25881. {
  25882. /* Don't write out CRL Distribution Points. */
  25883. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  25884. CERTEXTSASN_IDX_CRLINFO_STR);
  25885. }
  25886. #ifdef WOLFSSL_DUAL_ALG_CERTS
  25887. if (cert->sapkiDer != NULL) {
  25888. /* Set subject alternative public key info OID and data. */
  25889. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAPKI_OID], sapkiOID,
  25890. sizeof(sapkiOID));
  25891. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAPKI_STR], cert->sapkiDer,
  25892. cert->sapkiLen);
  25893. }
  25894. else {
  25895. /* Don't write out subject alternative public key info. */
  25896. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAPKI_SEQ,
  25897. CERTEXTSASN_IDX_SAPKI_STR);
  25898. }
  25899. if (cert->altSigAlgDer != NULL) {
  25900. /* Set alternative signature algorithm OID and data. */
  25901. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGALG_OID], altSigAlgOID,
  25902. sizeof(altSigAlgOID));
  25903. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGALG_STR],
  25904. cert->altSigAlgDer, cert->altSigAlgLen);
  25905. }
  25906. else {
  25907. /* Don't write out alternative signature algorithm. */
  25908. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_ALTSIGALG_SEQ,
  25909. CERTEXTSASN_IDX_ALTSIGALG_STR);
  25910. }
  25911. if (cert->altSigValDer != NULL) {
  25912. /* Set alternative signature value OID and data. */
  25913. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGVAL_OID], altSigValOID,
  25914. sizeof(altSigValOID));
  25915. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_ALTSIGVAL_STR],
  25916. cert->altSigValDer, cert->altSigValLen);
  25917. }
  25918. else {
  25919. /* Don't write out alternative signature value. */
  25920. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_ALTSIGVAL_SEQ,
  25921. CERTEXTSASN_IDX_ALTSIGVAL_STR);
  25922. }
  25923. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  25924. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  25925. /* encode a custom oid and value */
  25926. if (cert->extCustom.oidSz > 0) {
  25927. /* Set CRL Distribution Points OID and data. */
  25928. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  25929. cert->extCustom.oid, cert->extCustom.oidSz);
  25930. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  25931. cert->extCustom.val, cert->extCustom.valSz);
  25932. }
  25933. else
  25934. #endif
  25935. {
  25936. /* Don't write out custom OID. */
  25937. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  25938. CERTEXTSASN_IDX_CUSTOM_STR);
  25939. }
  25940. i = 0;
  25941. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  25942. for (; i < cert->customCertExtCount; i++) {
  25943. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  25944. word32 encodedOidSz = MAX_OID_SZ;
  25945. idx++; /* Skip one for for SEQ. */
  25946. /* EncodePolicyOID() will never return error since we parsed this
  25947. * OID when it was set. */
  25948. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  25949. cert->customCertExt[i].oid, NULL);
  25950. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  25951. encodedOidSz);
  25952. idx++;
  25953. if (cert->customCertExt[i].crit) {
  25954. SetASN_Boolean(&dataASN[idx], 1);
  25955. } else {
  25956. dataASN[idx].noOut = 1;
  25957. }
  25958. idx++;
  25959. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  25960. cert->customCertExt[i].valSz);
  25961. }
  25962. #endif
  25963. while (i < NUM_CUSTOM_EXT) {
  25964. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  25965. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  25966. i++;
  25967. }
  25968. }
  25969. if (ret == 0) {
  25970. /* Calculate size of encoded extensions. */
  25971. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  25972. }
  25973. if (ret == 0) {
  25974. /* Only SEQUENCE - don't encode extensions. */
  25975. if (sz == 2) {
  25976. sz = 0;
  25977. }
  25978. /* Check buffer is big enough. */
  25979. else if ((output != NULL) && (sz > (int)maxSz)) {
  25980. ret = BUFFER_E;
  25981. }
  25982. }
  25983. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  25984. /* Encode certificate extensions into buffer. */
  25985. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  25986. #ifdef WOLFSSL_CERT_EXT
  25987. if (cert->extKeyUsage != 0){
  25988. /* Encode Extended Key Usage into space provided. */
  25989. if (SetExtKeyUsage(cert,
  25990. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  25991. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  25992. cert->extKeyUsage) <= 0) {
  25993. ret = KEYUSAGE_E;
  25994. }
  25995. }
  25996. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  25997. /* Encode Certificate Policies into space provided. */
  25998. if (SetCertificatePolicies(
  25999. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  26000. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  26001. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  26002. ret = CERTPOLICIES_E;
  26003. }
  26004. }
  26005. #endif
  26006. }
  26007. if (ret == 0) {
  26008. /* Return the encoding size. */
  26009. ret = sz;
  26010. }
  26011. FREE_ASNSETDATA(dataASN, cert->heap);
  26012. #ifdef WOLFSSL_SMALL_STACK
  26013. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  26014. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26015. #endif
  26016. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26017. #endif
  26018. return ret;
  26019. }
  26020. #endif /* WOLFSSL_ASN_TEMPLATE */
  26021. #ifndef WOLFSSL_ASN_TEMPLATE
  26022. /* Set Date validity from now until now + daysValid
  26023. * return size in bytes written to output, 0 on error */
  26024. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  26025. * "MUST always encode certificate validity dates through the year 2049 as
  26026. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  26027. * GeneralizedTime." */
  26028. static int SetValidity(byte* output, int daysValid)
  26029. {
  26030. #ifndef NO_ASN_TIME
  26031. byte before[MAX_DATE_SIZE];
  26032. byte after[MAX_DATE_SIZE];
  26033. word32 beforeSz, afterSz, seqSz;
  26034. time_t now;
  26035. time_t then;
  26036. struct tm* tmpTime;
  26037. struct tm* expandedTime;
  26038. struct tm localTime;
  26039. #if defined(NEED_TMP_TIME)
  26040. /* for use with gmtime_r */
  26041. struct tm tmpTimeStorage;
  26042. tmpTime = &tmpTimeStorage;
  26043. #else
  26044. tmpTime = NULL;
  26045. #endif
  26046. (void)tmpTime;
  26047. now = wc_Time(0);
  26048. /* before now */
  26049. before[0] = ASN_GENERALIZED_TIME;
  26050. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  26051. /* subtract 1 day of seconds for more compliance */
  26052. then = now - 86400;
  26053. expandedTime = XGMTIME(&then, tmpTime);
  26054. if (ValidateGmtime(expandedTime)) {
  26055. WOLFSSL_MSG("XGMTIME failed");
  26056. return 0; /* error */
  26057. }
  26058. localTime = *expandedTime;
  26059. /* adjust */
  26060. localTime.tm_year += 1900;
  26061. localTime.tm_mon += 1;
  26062. SetTime(&localTime, before + beforeSz);
  26063. beforeSz += ASN_GEN_TIME_SZ;
  26064. after[0] = ASN_GENERALIZED_TIME;
  26065. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  26066. /* add daysValid of seconds */
  26067. then = now + (daysValid * (time_t)86400);
  26068. expandedTime = XGMTIME(&then, tmpTime);
  26069. if (ValidateGmtime(expandedTime)) {
  26070. WOLFSSL_MSG("XGMTIME failed");
  26071. return 0; /* error */
  26072. }
  26073. localTime = *expandedTime;
  26074. /* adjust */
  26075. localTime.tm_year += 1900;
  26076. localTime.tm_mon += 1;
  26077. SetTime(&localTime, after + afterSz);
  26078. afterSz += ASN_GEN_TIME_SZ;
  26079. /* headers and output */
  26080. seqSz = SetSequence(beforeSz + afterSz, output);
  26081. XMEMCPY(output + seqSz, before, beforeSz);
  26082. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  26083. return (int)(seqSz + beforeSz + afterSz);
  26084. #else
  26085. (void)output;
  26086. (void)daysValid;
  26087. return NOT_COMPILED_IN;
  26088. #endif
  26089. }
  26090. #else
  26091. static int SetValidity(byte* before, byte* after, int daysValid)
  26092. {
  26093. #ifndef NO_ASN_TIME
  26094. int ret = 0;
  26095. time_t now;
  26096. time_t then;
  26097. struct tm* tmpTime;
  26098. struct tm* expandedTime;
  26099. struct tm localTime;
  26100. #if defined(NEED_TMP_TIME)
  26101. /* for use with gmtime_r */
  26102. struct tm tmpTimeStorage;
  26103. tmpTime = &tmpTimeStorage;
  26104. #else
  26105. tmpTime = NULL;
  26106. #endif
  26107. (void)tmpTime;
  26108. now = wc_Time(0);
  26109. /* subtract 1 day of seconds for more compliance */
  26110. then = now - 86400;
  26111. expandedTime = XGMTIME(&then, tmpTime);
  26112. if (ValidateGmtime(expandedTime)) {
  26113. WOLFSSL_MSG("XGMTIME failed");
  26114. ret = DATE_E;
  26115. }
  26116. if (ret == 0) {
  26117. localTime = *expandedTime;
  26118. /* adjust */
  26119. localTime.tm_year += 1900;
  26120. localTime.tm_mon += 1;
  26121. SetTime(&localTime, before);
  26122. /* add daysValid of seconds */
  26123. then = now + (daysValid * (time_t)86400);
  26124. expandedTime = XGMTIME(&then, tmpTime);
  26125. if (ValidateGmtime(expandedTime)) {
  26126. WOLFSSL_MSG("XGMTIME failed");
  26127. ret = DATE_E;
  26128. }
  26129. }
  26130. if (ret == 0) {
  26131. localTime = *expandedTime;
  26132. /* adjust */
  26133. localTime.tm_year += 1900;
  26134. localTime.tm_mon += 1;
  26135. SetTime(&localTime, after);
  26136. }
  26137. return ret;
  26138. #else
  26139. (void)before;
  26140. (void)after;
  26141. (void)daysValid;
  26142. return NOT_COMPILED_IN;
  26143. #endif
  26144. }
  26145. #endif /* WOLFSSL_ASN_TEMPLATE */
  26146. #ifndef WOLFSSL_ASN_TEMPLATE
  26147. /* encode info from cert into DER encoded format */
  26148. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  26149. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  26150. ed448_key* ed448Key, falcon_key* falconKey,
  26151. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  26152. {
  26153. int ret;
  26154. if (cert == NULL || der == NULL || rng == NULL)
  26155. return BAD_FUNC_ARG;
  26156. /* make sure at least one key type is provided */
  26157. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26158. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26159. dilithiumKey == NULL && sphincsKey == NULL) {
  26160. return PUBLIC_KEY_E;
  26161. }
  26162. /* init */
  26163. XMEMSET(der, 0, sizeof(DerCert));
  26164. /* version */
  26165. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  26166. /* serial number (must be positive) */
  26167. if (cert->serialSz == 0) {
  26168. /* generate random serial */
  26169. cert->serialSz = CTC_GEN_SERIAL_SZ;
  26170. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  26171. if (ret != 0)
  26172. return ret;
  26173. /* Clear the top bit to avoid a negative value */
  26174. cert->serial[0] &= 0x7f;
  26175. }
  26176. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  26177. der->serial, sizeof(der->serial),
  26178. CTC_SERIAL_SIZE);
  26179. if (der->serialSz < 0)
  26180. return der->serialSz;
  26181. /* signature algo */
  26182. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  26183. if (der->sigAlgoSz <= 0)
  26184. return ALGO_ID_E;
  26185. /* public key */
  26186. #ifndef NO_RSA
  26187. if (cert->keyType == RSA_KEY) {
  26188. if (rsaKey == NULL)
  26189. return PUBLIC_KEY_E;
  26190. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26191. sizeof(der->publicKey), 1);
  26192. }
  26193. #endif
  26194. #ifdef HAVE_ECC
  26195. if (cert->keyType == ECC_KEY) {
  26196. if (eccKey == NULL)
  26197. return PUBLIC_KEY_E;
  26198. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26199. sizeof(der->publicKey), 1, 0);
  26200. }
  26201. #endif
  26202. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26203. if (cert->keyType == DSA_KEY) {
  26204. if (dsaKey == NULL)
  26205. return PUBLIC_KEY_E;
  26206. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26207. sizeof(der->publicKey), 1);
  26208. }
  26209. #endif
  26210. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26211. if (cert->keyType == ED25519_KEY) {
  26212. if (ed25519Key == NULL)
  26213. return PUBLIC_KEY_E;
  26214. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26215. (word32)sizeof(der->publicKey), 1);
  26216. }
  26217. #endif
  26218. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26219. if (cert->keyType == ED448_KEY) {
  26220. if (ed448Key == NULL)
  26221. return PUBLIC_KEY_E;
  26222. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26223. (word32)sizeof(der->publicKey), 1);
  26224. }
  26225. #endif
  26226. #if defined(HAVE_PQC)
  26227. #if defined(HAVE_FALCON)
  26228. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26229. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26230. if (falconKey == NULL)
  26231. return PUBLIC_KEY_E;
  26232. der->publicKeySz =
  26233. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  26234. (word32)sizeof(der->publicKey), 1);
  26235. }
  26236. #endif /* HAVE_FALCON */
  26237. #if defined(HAVE_DILITHIUM)
  26238. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26239. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26240. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26241. if (dilithiumKey == NULL)
  26242. return PUBLIC_KEY_E;
  26243. der->publicKeySz =
  26244. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  26245. (word32)sizeof(der->publicKey), 1);
  26246. }
  26247. #endif /* HAVE_DILITHIUM */
  26248. #if defined(HAVE_SPHINCS)
  26249. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26250. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26251. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26252. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26253. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26254. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26255. if (sphincsKey == NULL)
  26256. return PUBLIC_KEY_E;
  26257. der->publicKeySz =
  26258. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  26259. (word32)sizeof(der->publicKey), 1);
  26260. }
  26261. #endif /* HAVE_SPHINCS */
  26262. #endif /* HAVE_PQC */
  26263. if (der->publicKeySz <= 0)
  26264. return PUBLIC_KEY_E;
  26265. der->validitySz = 0;
  26266. /* copy date validity if already set in cert struct */
  26267. if (cert->beforeDateSz && cert->afterDateSz) {
  26268. der->validitySz = CopyValidity(der->validity, cert);
  26269. if (der->validitySz <= 0)
  26270. return DATE_E;
  26271. }
  26272. /* set date validity using daysValid if not set already */
  26273. if (der->validitySz == 0) {
  26274. der->validitySz = SetValidity(der->validity, cert->daysValid);
  26275. if (der->validitySz <= 0)
  26276. return DATE_E;
  26277. }
  26278. /* subject name */
  26279. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26280. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26281. /* Use the raw subject */
  26282. word32 idx;
  26283. der->subjectSz = (int)min((word32)sizeof(der->subject),
  26284. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26285. /* header */
  26286. idx = SetSequence((word32)der->subjectSz, der->subject);
  26287. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  26288. return SUBJECT_E;
  26289. }
  26290. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26291. (size_t)der->subjectSz);
  26292. der->subjectSz += (int)idx;
  26293. }
  26294. else
  26295. #endif
  26296. {
  26297. /* Use the name structure */
  26298. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26299. &cert->subject, cert->heap);
  26300. }
  26301. if (der->subjectSz <= 0)
  26302. return SUBJECT_E;
  26303. /* issuer name */
  26304. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26305. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  26306. /* Use the raw issuer */
  26307. word32 idx;
  26308. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  26309. (word32)XSTRLEN((const char*)cert->issRaw));
  26310. /* header */
  26311. idx = SetSequence((word32)der->issuerSz, der->issuer);
  26312. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  26313. return ISSUER_E;
  26314. }
  26315. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  26316. (size_t)der->issuerSz);
  26317. der->issuerSz += (int)idx;
  26318. }
  26319. else
  26320. #endif
  26321. {
  26322. /* Use the name structure */
  26323. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  26324. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  26325. }
  26326. if (der->issuerSz <= 0)
  26327. return ISSUER_E;
  26328. /* set the extensions */
  26329. der->extensionsSz = 0;
  26330. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26331. * The pathLenConstraint field is meaningful only if the CA boolean is
  26332. * asserted and the key usage extension, if present, asserts the
  26333. * keyCertSign bit */
  26334. /* Set CA and path length */
  26335. if ((cert->isCA) && (cert->pathLenSet)
  26336. #ifdef WOLFSSL_CERT_EXT
  26337. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26338. #endif
  26339. ) {
  26340. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26341. if (der->caSz <= 0)
  26342. return CA_TRUE_E;
  26343. der->extensionsSz += der->caSz;
  26344. }
  26345. #ifdef WOLFSSL_ALLOW_ENCODING_CA_FALSE
  26346. /* Set CA */
  26347. else if (cert->isCaSet) {
  26348. der->caSz = SetCaEx(der->ca, sizeof(der->ca), cert->isCA);
  26349. if (der->caSz <= 0)
  26350. return EXTENSIONS_E;
  26351. der->extensionsSz += der->caSz;
  26352. }
  26353. #endif
  26354. /* Set CA true */
  26355. else if (cert->isCA) {
  26356. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26357. if (der->caSz <= 0)
  26358. return CA_TRUE_E;
  26359. der->extensionsSz += der->caSz;
  26360. }
  26361. /* Set Basic Constraint */
  26362. else if (cert->basicConstSet) {
  26363. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26364. if (der->caSz <= 0)
  26365. return EXTENSIONS_E;
  26366. der->extensionsSz += der->caSz;
  26367. }
  26368. else
  26369. der->caSz = 0;
  26370. #ifdef WOLFSSL_ALT_NAMES
  26371. /* Alternative Name */
  26372. if (cert->altNamesSz) {
  26373. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26374. cert->altNames, (word32)cert->altNamesSz,
  26375. cert->altNamesCrit);
  26376. if (der->altNamesSz <= 0)
  26377. return ALT_NAME_E;
  26378. der->extensionsSz += der->altNamesSz;
  26379. }
  26380. else
  26381. der->altNamesSz = 0;
  26382. #endif
  26383. #ifdef WOLFSSL_CERT_EXT
  26384. /* SKID */
  26385. if (cert->skidSz) {
  26386. /* check the provided SKID size */
  26387. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26388. return SKID_E;
  26389. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  26390. cert (CTC_MAX_SKID_SIZE). */
  26391. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26392. cert->skid, (word32)cert->skidSz);
  26393. if (der->skidSz <= 0)
  26394. return SKID_E;
  26395. der->extensionsSz += der->skidSz;
  26396. }
  26397. else
  26398. der->skidSz = 0;
  26399. /* AKID */
  26400. if (cert->akidSz) {
  26401. /* check the provided AKID size */
  26402. if ((
  26403. #ifdef WOLFSSL_AKID_NAME
  26404. !cert->rawAkid &&
  26405. #endif
  26406. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  26407. #ifdef WOLFSSL_AKID_NAME
  26408. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  26409. #endif
  26410. )
  26411. return AKID_E;
  26412. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  26413. (word32)cert->akidSz,
  26414. #ifdef WOLFSSL_AKID_NAME
  26415. cert->rawAkid
  26416. #else
  26417. 0
  26418. #endif
  26419. );
  26420. if (der->akidSz <= 0)
  26421. return AKID_E;
  26422. der->extensionsSz += der->akidSz;
  26423. }
  26424. else
  26425. der->akidSz = 0;
  26426. /* Key Usage */
  26427. if (cert->keyUsage != 0){
  26428. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26429. cert->keyUsage);
  26430. if (der->keyUsageSz <= 0)
  26431. return KEYUSAGE_E;
  26432. der->extensionsSz += der->keyUsageSz;
  26433. }
  26434. else
  26435. der->keyUsageSz = 0;
  26436. /* Extended Key Usage */
  26437. if (cert->extKeyUsage != 0){
  26438. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26439. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26440. if (der->extKeyUsageSz <= 0)
  26441. return EXTKEYUSAGE_E;
  26442. der->extensionsSz += der->extKeyUsageSz;
  26443. }
  26444. else
  26445. der->extKeyUsageSz = 0;
  26446. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  26447. /* Netscape Certificate Type */
  26448. if (cert->nsCertType != 0) {
  26449. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  26450. sizeof(der->nsCertType), cert->nsCertType);
  26451. if (der->nsCertTypeSz <= 0)
  26452. return EXTENSIONS_E;
  26453. der->extensionsSz += der->nsCertTypeSz;
  26454. }
  26455. else
  26456. der->nsCertTypeSz = 0;
  26457. #endif
  26458. if (cert->crlInfoSz > 0) {
  26459. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  26460. cert->crlInfo, cert->crlInfoSz);
  26461. if (der->crlInfoSz <= 0)
  26462. return EXTENSIONS_E;
  26463. der->extensionsSz += der->crlInfoSz;
  26464. }
  26465. else
  26466. der->crlInfoSz = 0;
  26467. /* Certificate Policies */
  26468. if (cert->certPoliciesNb != 0) {
  26469. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  26470. sizeof(der->certPolicies),
  26471. cert->certPolicies,
  26472. cert->certPoliciesNb,
  26473. cert->heap);
  26474. if (der->certPoliciesSz <= 0)
  26475. return CERTPOLICIES_E;
  26476. der->extensionsSz += der->certPoliciesSz;
  26477. }
  26478. else
  26479. der->certPoliciesSz = 0;
  26480. #endif /* WOLFSSL_CERT_EXT */
  26481. /* put extensions */
  26482. if (der->extensionsSz > 0) {
  26483. /* put the start of extensions sequence (ID, Size) */
  26484. der->extensionsSz = SetExtensionsHeader(der->extensions,
  26485. sizeof(der->extensions),
  26486. (word32)der->extensionsSz);
  26487. if (der->extensionsSz <= 0)
  26488. return EXTENSIONS_E;
  26489. /* put CA */
  26490. if (der->caSz) {
  26491. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26492. &der->extensionsSz,
  26493. der->ca, der->caSz);
  26494. if (ret == 0)
  26495. return EXTENSIONS_E;
  26496. }
  26497. #ifdef WOLFSSL_ALT_NAMES
  26498. /* put Alternative Names */
  26499. if (der->altNamesSz) {
  26500. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26501. &der->extensionsSz,
  26502. der->altNames, der->altNamesSz);
  26503. if (ret <= 0)
  26504. return EXTENSIONS_E;
  26505. }
  26506. #endif
  26507. #ifdef WOLFSSL_CERT_EXT
  26508. /* put SKID */
  26509. if (der->skidSz) {
  26510. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26511. &der->extensionsSz,
  26512. der->skid, der->skidSz);
  26513. if (ret <= 0)
  26514. return EXTENSIONS_E;
  26515. }
  26516. /* put AKID */
  26517. if (der->akidSz) {
  26518. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26519. &der->extensionsSz,
  26520. der->akid, der->akidSz);
  26521. if (ret <= 0)
  26522. return EXTENSIONS_E;
  26523. }
  26524. /* put CRL Distribution Points */
  26525. if (der->crlInfoSz) {
  26526. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26527. &der->extensionsSz,
  26528. der->crlInfo, der->crlInfoSz);
  26529. if (ret <= 0)
  26530. return EXTENSIONS_E;
  26531. }
  26532. /* put KeyUsage */
  26533. if (der->keyUsageSz) {
  26534. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26535. &der->extensionsSz,
  26536. der->keyUsage, der->keyUsageSz);
  26537. if (ret <= 0)
  26538. return EXTENSIONS_E;
  26539. }
  26540. /* put ExtendedKeyUsage */
  26541. if (der->extKeyUsageSz) {
  26542. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26543. &der->extensionsSz,
  26544. der->extKeyUsage, der->extKeyUsageSz);
  26545. if (ret <= 0)
  26546. return EXTENSIONS_E;
  26547. }
  26548. /* put Netscape Cert Type */
  26549. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  26550. if (der->nsCertTypeSz) {
  26551. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26552. &der->extensionsSz,
  26553. der->nsCertType, der->nsCertTypeSz);
  26554. if (ret <= 0)
  26555. return EXTENSIONS_E;
  26556. }
  26557. #endif
  26558. /* put Certificate Policies */
  26559. if (der->certPoliciesSz) {
  26560. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26561. &der->extensionsSz,
  26562. der->certPolicies, der->certPoliciesSz);
  26563. if (ret <= 0)
  26564. return EXTENSIONS_E;
  26565. }
  26566. #endif /* WOLFSSL_CERT_EXT */
  26567. }
  26568. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  26569. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  26570. der->extensionsSz;
  26571. return 0;
  26572. }
  26573. /* write DER encoded cert to buffer, size already checked */
  26574. static int WriteCertBody(DerCert* der, byte* buf)
  26575. {
  26576. word32 idx;
  26577. /* signed part header */
  26578. idx = SetSequence((word32)der->total, buf);
  26579. /* version */
  26580. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  26581. idx += (word32)der->versionSz;
  26582. /* serial */
  26583. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  26584. idx += (word32)der->serialSz;
  26585. /* sig algo */
  26586. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  26587. idx += (word32)der->sigAlgoSz;
  26588. /* issuer */
  26589. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  26590. idx += (word32)der->issuerSz;
  26591. /* validity */
  26592. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  26593. idx += (word32)der->validitySz;
  26594. /* subject */
  26595. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  26596. idx += (word32)der->subjectSz;
  26597. /* public key */
  26598. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  26599. idx += (word32)der->publicKeySz;
  26600. if (der->extensionsSz) {
  26601. /* extensions */
  26602. XMEMCPY(buf + idx, der->extensions,
  26603. min((word32)der->extensionsSz,
  26604. (word32)sizeof(der->extensions)));
  26605. idx += (word32)der->extensionsSz;
  26606. }
  26607. return (int)idx;
  26608. }
  26609. #endif /* !WOLFSSL_ASN_TEMPLATE */
  26610. /* Make signature from buffer (sz), write to sig (sigSz) */
  26611. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  26612. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  26613. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  26614. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  26615. word32 sigAlgoType, void* heap)
  26616. {
  26617. int digestSz = 0, typeH = 0, ret = 0;
  26618. (void)digestSz;
  26619. (void)typeH;
  26620. (void)buf;
  26621. (void)sz;
  26622. (void)sig;
  26623. (void)sigSz;
  26624. (void)rsaKey;
  26625. (void)eccKey;
  26626. (void)ed25519Key;
  26627. (void)ed448Key;
  26628. (void)falconKey;
  26629. (void)dilithiumKey;
  26630. (void)sphincsKey;
  26631. (void)rng;
  26632. (void)heap;
  26633. switch (certSignCtx->state) {
  26634. case CERTSIGN_STATE_BEGIN:
  26635. case CERTSIGN_STATE_DIGEST:
  26636. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  26637. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  26638. DYNAMIC_TYPE_TMP_BUFFER);
  26639. if (certSignCtx->digest == NULL) {
  26640. ret = MEMORY_E; goto exit_ms;
  26641. }
  26642. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  26643. &typeH, &digestSz, 0);
  26644. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  26645. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  26646. if (ret != 0) {
  26647. goto exit_ms;
  26648. }
  26649. FALL_THROUGH;
  26650. case CERTSIGN_STATE_ENCODE:
  26651. #ifndef NO_RSA
  26652. if (rsaKey) {
  26653. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  26654. DYNAMIC_TYPE_TMP_BUFFER);
  26655. if (certSignCtx->encSig == NULL) {
  26656. ret = MEMORY_E; goto exit_ms;
  26657. }
  26658. /* signature */
  26659. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  26660. certSignCtx->digest, (word32)digestSz, typeH);
  26661. }
  26662. #endif /* !NO_RSA */
  26663. FALL_THROUGH;
  26664. case CERTSIGN_STATE_DO:
  26665. certSignCtx->state = CERTSIGN_STATE_DO;
  26666. ret = ALGO_ID_E; /* default to error */
  26667. #ifndef NO_RSA
  26668. if (rsaKey) {
  26669. /* signature */
  26670. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  26671. (word32)certSignCtx->encSigSz,
  26672. sig, sigSz, rsaKey, rng);
  26673. }
  26674. #endif /* !NO_RSA */
  26675. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  26676. if (!rsaKey && eccKey) {
  26677. word32 outSz = sigSz;
  26678. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  26679. sig, &outSz, rng, eccKey);
  26680. if (ret == 0)
  26681. ret = (int)outSz;
  26682. }
  26683. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  26684. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  26685. if (!rsaKey && !eccKey && ed25519Key) {
  26686. word32 outSz = sigSz;
  26687. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  26688. if (ret == 0)
  26689. ret = (int)outSz;
  26690. }
  26691. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  26692. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  26693. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  26694. word32 outSz = sigSz;
  26695. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  26696. if (ret == 0)
  26697. ret = (int)outSz;
  26698. }
  26699. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  26700. #if defined(HAVE_PQC)
  26701. #if defined(HAVE_FALCON)
  26702. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  26703. word32 outSz = sigSz;
  26704. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey, rng);
  26705. if (ret == 0)
  26706. ret = outSz;
  26707. }
  26708. #endif /* HAVE_FALCON */
  26709. #if defined(HAVE_DILITHIUM)
  26710. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  26711. dilithiumKey) {
  26712. word32 outSz = sigSz;
  26713. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey, rng);
  26714. if (ret == 0)
  26715. ret = outSz;
  26716. }
  26717. #endif /* HAVE_DILITHIUM */
  26718. #if defined(HAVE_SPHINCS)
  26719. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  26720. !dilithiumKey && sphincsKey) {
  26721. word32 outSz = sigSz;
  26722. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey, rng);
  26723. if (ret == 0)
  26724. ret = outSz;
  26725. }
  26726. #endif /* HAVE_SPHINCS */
  26727. #endif /* HAVE_PQC */
  26728. break;
  26729. }
  26730. exit_ms:
  26731. #ifdef WOLFSSL_ASYNC_CRYPT
  26732. if (ret == WC_PENDING_E) {
  26733. return ret;
  26734. }
  26735. #endif
  26736. #ifndef NO_RSA
  26737. if (rsaKey) {
  26738. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26739. }
  26740. #endif /* !NO_RSA */
  26741. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26742. certSignCtx->digest = NULL;
  26743. /* reset state */
  26744. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  26745. if (ret < 0) {
  26746. WOLFSSL_ERROR_VERBOSE(ret);
  26747. }
  26748. return ret;
  26749. }
  26750. #ifdef WOLFSSL_ASN_TEMPLATE
  26751. /* Generate a random integer value of at most len bytes.
  26752. *
  26753. * Most-significant bit will not be set when maximum size.
  26754. * Random value may be smaller than maximum size in bytes.
  26755. *
  26756. * @param [in] rng Random number generator.
  26757. * @param [out] out Buffer to hold integer value.
  26758. * @param [in] len Maximum number of bytes of integer.
  26759. * @return 0 on success.
  26760. * @return -ve when random number generation failed.
  26761. */
  26762. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  26763. {
  26764. int ret;
  26765. /* Generate random number. */
  26766. ret = wc_RNG_GenerateBlock(rng, out, len);
  26767. if (ret == 0) {
  26768. int i;
  26769. /* Clear the top bit to make positive. */
  26770. out[0] &= 0x7f;
  26771. /* Find first non-zero byte. One zero byte is valid though. */
  26772. for (i = 0; i < (int)len - 1; i++) {
  26773. if (out[i] != 0) {
  26774. break;
  26775. }
  26776. }
  26777. if (i != 0) {
  26778. /* Remove leading zeros. */
  26779. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  26780. }
  26781. }
  26782. return ret;
  26783. }
  26784. /* ASN.1 template for a Certificate.
  26785. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  26786. */
  26787. static const ASNItem sigASN[] = {
  26788. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26789. /* tbsCertificate */
  26790. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26791. /* signatureAlgorithm */
  26792. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  26793. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  26794. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  26795. /* signatureValue */
  26796. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  26797. };
  26798. enum {
  26799. SIGASN_IDX_SEQ = 0,
  26800. SIGASN_IDX_TBS_SEQ,
  26801. SIGASN_IDX_SIGALGO_SEQ,
  26802. SIGASN_IDX_SIGALGO_OID,
  26803. SIGASN_IDX_SIGALGO_NULL,
  26804. SIGASN_IDX_SIGNATURE
  26805. };
  26806. /* Number of items in ASN.1 template for a Certificate. */
  26807. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  26808. #endif
  26809. /* add signature to end of buffer, size of buffer assumed checked, return
  26810. new length */
  26811. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  26812. int sigAlgoType)
  26813. {
  26814. #ifndef WOLFSSL_ASN_TEMPLATE
  26815. byte seq[MAX_SEQ_SZ];
  26816. word32 idx, seqSz;
  26817. if ((bodySz < 0) || (sigSz < 0))
  26818. return BUFFER_E;
  26819. idx = (word32)bodySz;
  26820. /* algo */
  26821. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  26822. /* bit string */
  26823. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  26824. /* signature */
  26825. if (buf)
  26826. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  26827. idx += (word32)sigSz;
  26828. /* make room for overall header */
  26829. seqSz = SetSequence(idx, seq);
  26830. if (buf) {
  26831. XMEMMOVE(buf + seqSz, buf, idx);
  26832. XMEMCPY(buf, seq, seqSz);
  26833. }
  26834. return (int)(idx + seqSz);
  26835. #else
  26836. DECL_ASNSETDATA(dataASN, sigASN_Length);
  26837. word32 seqSz;
  26838. int sz;
  26839. int ret = 0;
  26840. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  26841. /* In place, put body between SEQUENCE and signature. */
  26842. if (ret == 0) {
  26843. /* Set signature OID and signature data. */
  26844. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  26845. oidSigType);
  26846. if (dataASN[SIGASN_IDX_SIGALGO_OID].data.buffer.data == NULL) {
  26847. /* The OID was not found or compiled in! */
  26848. ret = ASN_UNKNOWN_OID_E;
  26849. }
  26850. }
  26851. if (ret == 0) {
  26852. if (IsSigAlgoECC((word32)sigAlgoType)) {
  26853. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  26854. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  26855. }
  26856. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  26857. /* Calculate size of signature data. */
  26858. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  26859. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  26860. }
  26861. if (ret == 0) {
  26862. /* Calculate size of outer sequence by calculating size of the encoded
  26863. * length and adding 1 for tag. */
  26864. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  26865. if (buf != NULL) {
  26866. /* Move body to after sequence. */
  26867. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  26868. }
  26869. /* Leave space for body in encoding. */
  26870. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  26871. (word32)bodySz);
  26872. /* Calculate overall size and put in offsets and lengths. */
  26873. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  26874. }
  26875. if ((ret == 0) && (buf != NULL)) {
  26876. /* Write SEQUENCE and signature around body. */
  26877. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  26878. }
  26879. if (ret == 0) {
  26880. /* Return the encoding size. */
  26881. ret = sz;
  26882. }
  26883. FREE_ASNSETDATA(dataASN, NULL);
  26884. return ret;
  26885. #endif /* WOLFSSL_ASN_TEMPLATE */
  26886. }
  26887. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  26888. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  26889. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  26890. DsaKey* dsaKey, ed25519_key* ed25519Key,
  26891. ed448_key* ed448Key, falcon_key* falconKey,
  26892. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  26893. {
  26894. #ifndef WOLFSSL_ASN_TEMPLATE
  26895. int ret;
  26896. #ifdef WOLFSSL_SMALL_STACK
  26897. DerCert* der;
  26898. #else
  26899. DerCert der[1];
  26900. #endif
  26901. if (derBuffer == NULL)
  26902. return BAD_FUNC_ARG;
  26903. if (eccKey)
  26904. cert->keyType = ECC_KEY;
  26905. else if (rsaKey)
  26906. cert->keyType = RSA_KEY;
  26907. else if (dsaKey)
  26908. cert->keyType = DSA_KEY;
  26909. else if (ed25519Key)
  26910. cert->keyType = ED25519_KEY;
  26911. else if (ed448Key)
  26912. cert->keyType = ED448_KEY;
  26913. #ifdef HAVE_PQC
  26914. #ifdef HAVE_FALCON
  26915. else if ((falconKey != NULL) && (falconKey->level == 1))
  26916. cert->keyType = FALCON_LEVEL1_KEY;
  26917. else if ((falconKey != NULL) && (falconKey->level == 5))
  26918. cert->keyType = FALCON_LEVEL5_KEY;
  26919. #endif /* HAVE_FALCON */
  26920. #ifdef HAVE_DILITHIUM
  26921. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26922. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26923. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26924. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26925. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26926. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26927. #endif /* HAVE_DILITHIUM */
  26928. #ifdef HAVE_SPHINCS
  26929. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26930. && (sphincsKey->optim == FAST_VARIANT))
  26931. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26932. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26933. && (sphincsKey->optim == FAST_VARIANT))
  26934. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26935. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26936. && (sphincsKey->optim == FAST_VARIANT))
  26937. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26938. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26939. && (sphincsKey->optim == SMALL_VARIANT))
  26940. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26941. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26942. && (sphincsKey->optim == SMALL_VARIANT))
  26943. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26944. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26945. && (sphincsKey->optim == SMALL_VARIANT))
  26946. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26947. #endif /* HAVE_SPHINCS */
  26948. #endif /* HAVE_PQC */
  26949. else
  26950. return BAD_FUNC_ARG;
  26951. #ifdef WOLFSSL_SMALL_STACK
  26952. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26953. if (der == NULL)
  26954. return MEMORY_E;
  26955. #endif
  26956. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  26957. ed448Key, falconKey, dilithiumKey, sphincsKey);
  26958. if (ret == 0) {
  26959. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26960. ret = BUFFER_E;
  26961. else
  26962. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  26963. }
  26964. #ifdef WOLFSSL_SMALL_STACK
  26965. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26966. #endif
  26967. return ret;
  26968. #else
  26969. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  26970. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  26971. word32 publicKeySz = 0;
  26972. word32 issuerSz = 0;
  26973. word32 subjectSz = 0;
  26974. word32 extSz = 0;
  26975. int sz = 0;
  26976. int ret = 0;
  26977. word32 issRawLen = 0;
  26978. word32 sbjRawLen = 0;
  26979. /* Unused without OQS */
  26980. (void)falconKey;
  26981. (void)dilithiumKey;
  26982. (void)sphincsKey;
  26983. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  26984. if (ret == 0) {
  26985. /* Set key type into certificate object based on key passed in. */
  26986. if (rsaKey) {
  26987. cert->keyType = RSA_KEY;
  26988. }
  26989. else if (eccKey) {
  26990. cert->keyType = ECC_KEY;
  26991. }
  26992. else if (dsaKey) {
  26993. cert->keyType = DSA_KEY;
  26994. }
  26995. else if (ed25519Key) {
  26996. cert->keyType = ED25519_KEY;
  26997. }
  26998. else if (ed448Key) {
  26999. cert->keyType = ED448_KEY;
  27000. }
  27001. #ifdef HAVE_PQC
  27002. #ifdef HAVE_FALCON
  27003. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  27004. cert->keyType = FALCON_LEVEL1_KEY;
  27005. }
  27006. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  27007. cert->keyType = FALCON_LEVEL5_KEY;
  27008. }
  27009. #endif /* HAVE_FALCON */
  27010. #ifdef HAVE_DILITHIUM
  27011. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  27012. cert->keyType = DILITHIUM_LEVEL2_KEY;
  27013. }
  27014. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  27015. cert->keyType = DILITHIUM_LEVEL3_KEY;
  27016. }
  27017. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  27018. cert->keyType = DILITHIUM_LEVEL5_KEY;
  27019. }
  27020. #endif /* HAVE_DILITHIUM */
  27021. #ifdef HAVE_SPHINCS
  27022. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27023. && (sphincsKey->optim == FAST_VARIANT)) {
  27024. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  27025. }
  27026. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27027. && (sphincsKey->optim == FAST_VARIANT)) {
  27028. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  27029. }
  27030. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27031. && (sphincsKey->optim == FAST_VARIANT)) {
  27032. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  27033. }
  27034. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27035. && (sphincsKey->optim == SMALL_VARIANT)) {
  27036. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  27037. }
  27038. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27039. && (sphincsKey->optim == SMALL_VARIANT)) {
  27040. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  27041. }
  27042. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27043. && (sphincsKey->optim == SMALL_VARIANT)) {
  27044. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  27045. }
  27046. #endif /* HAVE_SPHINCS */
  27047. #endif /* HAVE_PQC */
  27048. else {
  27049. ret = BAD_FUNC_ARG;
  27050. }
  27051. }
  27052. if ((ret == 0) && (cert->serialSz == 0)) {
  27053. /* Generate random serial number. */
  27054. cert->serialSz = CTC_GEN_SERIAL_SZ;
  27055. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  27056. }
  27057. if (ret == 0) {
  27058. /* Determine issuer name size. */
  27059. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  27060. defined(WOLFSSL_CERT_REQ)
  27061. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  27062. if (issRawLen > 0) {
  27063. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  27064. }
  27065. else
  27066. #endif
  27067. {
  27068. /* Calculate issuer name encoding size. If the cert is self-signed
  27069. * use the subject instead of the issuer. */
  27070. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  27071. &cert->subject : &cert->issuer, cert->heap);
  27072. issuerSz = (word32)ret;
  27073. }
  27074. }
  27075. if (ret >= 0) {
  27076. /* Determine subject name size. */
  27077. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  27078. defined(WOLFSSL_CERT_REQ)
  27079. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  27080. if (sbjRawLen > 0) {
  27081. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  27082. }
  27083. else
  27084. #endif
  27085. {
  27086. /* Calculate subject name encoding size. */
  27087. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  27088. cert->heap);
  27089. subjectSz = (word32)ret;
  27090. }
  27091. }
  27092. if (ret >= 0) {
  27093. /* Calculate public key encoding size. */
  27094. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  27095. eccKey, ed25519Key, ed448Key, dsaKey);
  27096. publicKeySz = (word32)ret;
  27097. }
  27098. if (ret >= 0) {
  27099. /* Calculate extensions encoding size - may be 0. */
  27100. ret = EncodeExtensions(cert, NULL, 0, 0);
  27101. extSz = (word32)ret;
  27102. }
  27103. if (ret >= 0) {
  27104. /* Don't write out outer sequence - only doing body. */
  27105. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  27106. /* Set version, serial number and signature OID */
  27107. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  27108. (byte)cert->version);
  27109. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  27110. (word32)cert->serialSz);
  27111. #ifdef WOLFSSL_DUAL_ALG_CERTS
  27112. if (cert->sigType == 0) {
  27113. /* sigOID being 0 indicates preTBS. Do not encode signature. */
  27114. dataASN[X509CERTASN_IDX_TBS_ALGOID_SEQ].noOut = 1;
  27115. dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].noOut = 1;
  27116. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  27117. #ifdef WC_RSA_PSS
  27118. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  27119. #endif
  27120. }
  27121. else
  27122. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  27123. {
  27124. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  27125. (word32)cert->sigType, oidSigType);
  27126. }
  27127. if (IsSigAlgoECC((word32)cert->sigType)) {
  27128. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  27129. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  27130. }
  27131. #ifdef WC_RSA_PSS
  27132. /* TODO: Encode RSA PSS parameters. */
  27133. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  27134. #endif
  27135. if (issRawLen > 0) {
  27136. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  27137. defined(WOLFSSL_CERT_REQ)
  27138. /* Put in encoded issuer name. */
  27139. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  27140. cert->issRaw, issuerSz);
  27141. #endif
  27142. }
  27143. else {
  27144. /* Leave space for issuer name. */
  27145. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  27146. NULL, issuerSz);
  27147. }
  27148. if (cert->beforeDateSz && cert->afterDateSz) {
  27149. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  27150. /* Make space for before date data. */
  27151. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  27152. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  27153. /* Don't put out Generalized Time before data. */
  27154. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  27155. }
  27156. else {
  27157. /* Don't put out UTC before data. */
  27158. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  27159. /* Make space for before date data. */
  27160. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  27161. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  27162. }
  27163. if (cert->afterDate[0] == ASN_UTC_TIME) {
  27164. /* Make space for after date data. */
  27165. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  27166. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  27167. /* Don't put out UTC Generalized Time after data. */
  27168. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  27169. }
  27170. else {
  27171. /* Don't put out UTC after data. */
  27172. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  27173. /* Make space for after date data. */
  27174. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  27175. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  27176. }
  27177. }
  27178. else
  27179. {
  27180. /* Don't put out UTC before data. */
  27181. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  27182. /* Make space for before date data. */
  27183. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  27184. NULL, ASN_GEN_TIME_SZ);
  27185. /* Don't put out UTC after data. */
  27186. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  27187. /* Make space for after date data. */
  27188. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  27189. NULL, ASN_GEN_TIME_SZ);
  27190. }
  27191. if (sbjRawLen > 0) {
  27192. /* Put in encoded subject name. */
  27193. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  27194. defined(WOLFSSL_CERT_REQ)
  27195. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  27196. cert->sbjRaw, subjectSz);
  27197. #endif
  27198. }
  27199. else {
  27200. /* Leave space for subject name. */
  27201. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  27202. NULL, subjectSz);
  27203. }
  27204. /* Leave space for public key. */
  27205. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  27206. NULL, publicKeySz);
  27207. /* Replacement buffer instead of algorithm identifier items. */
  27208. SetASNItem_NoOut(dataASN,
  27209. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  27210. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  27211. /* issuerUniqueID and subjectUniqueID not supported. */
  27212. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  27213. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  27214. /* Leave space for extensions if any set into certificate object. */
  27215. if (extSz > 0) {
  27216. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  27217. }
  27218. else {
  27219. SetASNItem_NoOutNode(dataASN, x509CertASN,
  27220. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  27221. }
  27222. /* No signature - added later. */
  27223. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  27224. X509CERTASN_IDX_SIGNATURE);
  27225. /* Calculate encoded certificate body size. */
  27226. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  27227. }
  27228. /* Check buffer is big enough for encoded data. */
  27229. if ((ret == 0) && (sz > (int)derSz)) {
  27230. ret = BUFFER_E;
  27231. }
  27232. if (ret == 0) {
  27233. /* Encode certificate body into buffer. */
  27234. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  27235. if (issRawLen == 0) {
  27236. /* Encode issuer name into buffer. Use the subject as the issuer
  27237. * if it is self-signed. Size will be correct because we did the
  27238. * same for size. */
  27239. ret = SetNameEx(
  27240. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  27241. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  27242. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  27243. }
  27244. }
  27245. if ((ret >= 0) && (sbjRawLen == 0)) {
  27246. /* Encode subject name into buffer. */
  27247. ret = SetNameEx(
  27248. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  27249. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  27250. &cert->subject, cert->heap);
  27251. }
  27252. if (ret >= 0) {
  27253. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  27254. {
  27255. /* Encode validity into buffer. */
  27256. ret = SetValidity(
  27257. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  27258. .data.buffer.data,
  27259. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  27260. .data.buffer.data, cert->daysValid);
  27261. }
  27262. }
  27263. if (ret >= 0) {
  27264. /* Encode public key into buffer. */
  27265. ret = EncodePublicKey(cert->keyType,
  27266. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  27267. .data.buffer.data,
  27268. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  27269. .data.buffer.length,
  27270. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  27271. }
  27272. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  27273. /* Encode extensions into buffer. */
  27274. ret = EncodeExtensions(cert,
  27275. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  27276. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  27277. }
  27278. if (ret >= 0) {
  27279. /* Store encoded certificate body size. */
  27280. cert->bodySz = sz;
  27281. /* Return the encoding size. */
  27282. ret = sz;
  27283. }
  27284. FREE_ASNSETDATA(dataASN, cert->heap);
  27285. return ret;
  27286. #endif
  27287. }
  27288. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  27289. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  27290. void* key, WC_RNG* rng)
  27291. {
  27292. RsaKey* rsaKey = NULL;
  27293. DsaKey* dsaKey = NULL;
  27294. ecc_key* eccKey = NULL;
  27295. ed25519_key* ed25519Key = NULL;
  27296. ed448_key* ed448Key = NULL;
  27297. falcon_key* falconKey = NULL;
  27298. dilithium_key* dilithiumKey = NULL;
  27299. sphincs_key* sphincsKey = NULL;
  27300. if (keyType == RSA_TYPE)
  27301. rsaKey = (RsaKey*)key;
  27302. else if (keyType == DSA_TYPE)
  27303. dsaKey = (DsaKey*)key;
  27304. else if (keyType == ECC_TYPE)
  27305. eccKey = (ecc_key*)key;
  27306. else if (keyType == ED25519_TYPE)
  27307. ed25519Key = (ed25519_key*)key;
  27308. else if (keyType == ED448_TYPE)
  27309. ed448Key = (ed448_key*)key;
  27310. else if (keyType == FALCON_LEVEL1_TYPE)
  27311. falconKey = (falcon_key*)key;
  27312. else if (keyType == FALCON_LEVEL5_TYPE)
  27313. falconKey = (falcon_key*)key;
  27314. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27315. dilithiumKey = (dilithium_key*)key;
  27316. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27317. dilithiumKey = (dilithium_key*)key;
  27318. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27319. dilithiumKey = (dilithium_key*)key;
  27320. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27321. sphincsKey = (sphincs_key*)key;
  27322. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27323. sphincsKey = (sphincs_key*)key;
  27324. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27325. sphincsKey = (sphincs_key*)key;
  27326. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27327. sphincsKey = (sphincs_key*)key;
  27328. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27329. sphincsKey = (sphincs_key*)key;
  27330. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27331. sphincsKey = (sphincs_key*)key;
  27332. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  27333. ed25519Key, ed448Key, falconKey, dilithiumKey,
  27334. sphincsKey);
  27335. }
  27336. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  27337. WOLFSSL_ABI
  27338. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  27339. ecc_key* eccKey, WC_RNG* rng)
  27340. {
  27341. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  27342. NULL, NULL, NULL, NULL);
  27343. }
  27344. #ifdef WOLFSSL_CERT_REQ
  27345. #ifndef WOLFSSL_ASN_TEMPLATE
  27346. /* return size of data set on success
  27347. * if getting size only then attr and oid should be NULL
  27348. */
  27349. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  27350. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  27351. word32 extSz)
  27352. {
  27353. word32 totalSz = 0;
  27354. word32 seqSz = 0;
  27355. word32 setSz = 0;
  27356. word32 strSz = 0;
  27357. byte seq[MAX_SEQ_SZ];
  27358. byte set[MAX_SET_SZ];
  27359. byte str[MAX_PRSTR_SZ];
  27360. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  27361. totalSz += oidSz;
  27362. if (extSz > 0) {
  27363. totalSz += setSz = SetSet(extSz, set);
  27364. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  27365. totalSz += extSz;
  27366. }
  27367. else {
  27368. if (printable) {
  27369. strSz = SetPrintableString(attrSz, str);
  27370. totalSz += strSz;
  27371. }
  27372. else {
  27373. totalSz += strSz = SetUTF8String(attrSz, str);
  27374. }
  27375. totalSz += setSz = SetSet(strSz + attrSz, set);
  27376. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  27377. totalSz += attrSz;
  27378. }
  27379. if (oid) {
  27380. XMEMCPY(&output[*idx], seq, seqSz);
  27381. *idx += seqSz;
  27382. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  27383. XMEMCPY(&output[*idx], oid, oidSz);
  27384. *idx += oidSz;
  27385. XMEMCPY(&output[*idx], set, setSz);
  27386. *idx += setSz;
  27387. if (strSz > 0) {
  27388. XMEMCPY(&output[*idx], str, strSz);
  27389. *idx += strSz;
  27390. if (attrSz > 0) {
  27391. XMEMCPY(&output[*idx], attr, attrSz);
  27392. *idx += attrSz;
  27393. }
  27394. }
  27395. }
  27396. return totalSz;
  27397. }
  27398. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  27399. {
  27400. word32 sz = 0; /* overall size */
  27401. word32 setSz = 0;
  27402. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  27403. sz++;
  27404. if (cert->challengePw[0]) {
  27405. setSz += SetReqAttribSingle(output, &sz, NULL,
  27406. (word32)XSTRLEN(cert->challengePw), NULL,
  27407. sizeof(attrChallengePasswordOid),
  27408. (byte)cert->challengePwPrintableString, 0);
  27409. }
  27410. if (cert->unstructuredName[0]) {
  27411. setSz += SetReqAttribSingle(output, &sz, NULL,
  27412. (word32)XSTRLEN(cert->unstructuredName), NULL,
  27413. sizeof(attrUnstructuredNameOid), 1, 0);
  27414. }
  27415. if (extSz) {
  27416. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  27417. sizeof(attrExtensionRequestOid), 1, extSz);
  27418. }
  27419. /* Put the pieces together. */
  27420. sz += SetLength(setSz, &output[sz]);
  27421. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  27422. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  27423. return REQ_ATTRIBUTE_E;
  27424. }
  27425. if (cert->challengePw[0]) {
  27426. SetReqAttribSingle(output, &sz, cert->challengePw,
  27427. (word32)XSTRLEN(cert->challengePw),
  27428. &attrChallengePasswordOid[0],
  27429. sizeof(attrChallengePasswordOid),
  27430. (byte)cert->challengePwPrintableString, 0);
  27431. }
  27432. if (cert->unstructuredName[0]) {
  27433. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  27434. (word32)XSTRLEN(cert->unstructuredName),
  27435. &attrUnstructuredNameOid[0],
  27436. sizeof(attrUnstructuredNameOid), 1, 0);
  27437. }
  27438. if (extSz) {
  27439. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  27440. sizeof(attrExtensionRequestOid), 1, extSz);
  27441. /* The actual extension data will be tacked onto the output later. */
  27442. }
  27443. return (int)sz;
  27444. }
  27445. #ifdef WOLFSSL_CUSTOM_OID
  27446. /* encode a custom oid and value */
  27447. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  27448. CertOidField* custom)
  27449. {
  27450. int idx = 0, cust_lenSz, cust_oidSz;
  27451. if (cert == NULL || output == NULL || custom == NULL) {
  27452. return BAD_FUNC_ARG;
  27453. }
  27454. if (custom->oid == NULL || custom->oidSz <= 0) {
  27455. return 0; /* none set */
  27456. }
  27457. /* Octet String header */
  27458. cust_lenSz = SetOctetString(custom->valSz, NULL);
  27459. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  27460. /* check for output buffer room */
  27461. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  27462. outSz) {
  27463. return BUFFER_E;
  27464. }
  27465. /* put sequence with total */
  27466. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  27467. output);
  27468. /* put oid header */
  27469. idx += SetObjectId(custom->oidSz, output+idx);
  27470. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  27471. idx += custom->oidSz;
  27472. /* put value */
  27473. idx += SetOctetString(custom->valSz, output+idx);
  27474. XMEMCPY(output+idx, custom->val, custom->valSz);
  27475. idx += custom->valSz;
  27476. return idx;
  27477. }
  27478. #endif /* WOLFSSL_CUSTOM_OID */
  27479. /* encode info from cert into DER encoded format */
  27480. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  27481. DsaKey* dsaKey, ecc_key* eccKey,
  27482. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27483. falcon_key* falconKey, dilithium_key* dilithiumKey,
  27484. sphincs_key* sphincsKey)
  27485. {
  27486. int ret;
  27487. (void)eccKey;
  27488. (void)ed25519Key;
  27489. (void)ed448Key;
  27490. (void)falconKey;
  27491. (void)dilithiumKey;
  27492. (void)sphincsKey;
  27493. if (cert == NULL || der == NULL)
  27494. return BAD_FUNC_ARG;
  27495. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  27496. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  27497. falconKey == NULL) {
  27498. return PUBLIC_KEY_E;
  27499. }
  27500. /* init */
  27501. XMEMSET(der, 0, sizeof(DerCert));
  27502. /* version */
  27503. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  27504. /* subject name */
  27505. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27506. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  27507. /* Use the raw subject */
  27508. int idx;
  27509. der->subjectSz = (int)min(sizeof(der->subject),
  27510. (word32)XSTRLEN((const char*)cert->sbjRaw));
  27511. /* header */
  27512. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  27513. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  27514. return SUBJECT_E;
  27515. }
  27516. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  27517. (size_t)der->subjectSz);
  27518. der->subjectSz += idx;
  27519. }
  27520. else
  27521. #endif
  27522. {
  27523. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  27524. &cert->subject, cert->heap);
  27525. }
  27526. if (der->subjectSz <= 0)
  27527. return SUBJECT_E;
  27528. /* public key */
  27529. #ifndef NO_RSA
  27530. if (cert->keyType == RSA_KEY) {
  27531. if (rsaKey == NULL)
  27532. return PUBLIC_KEY_E;
  27533. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  27534. sizeof(der->publicKey), 1);
  27535. }
  27536. #endif
  27537. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  27538. if (cert->keyType == DSA_KEY) {
  27539. if (dsaKey == NULL)
  27540. return PUBLIC_KEY_E;
  27541. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  27542. sizeof(der->publicKey), 1);
  27543. }
  27544. #endif
  27545. #ifdef HAVE_ECC
  27546. if (cert->keyType == ECC_KEY) {
  27547. if (eccKey == NULL)
  27548. return PUBLIC_KEY_E;
  27549. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  27550. sizeof(der->publicKey), 1, 0);
  27551. }
  27552. #endif
  27553. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27554. if (cert->keyType == ED25519_KEY) {
  27555. if (ed25519Key == NULL)
  27556. return PUBLIC_KEY_E;
  27557. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  27558. (word32)sizeof(der->publicKey), 1);
  27559. }
  27560. #endif
  27561. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27562. if (cert->keyType == ED448_KEY) {
  27563. if (ed448Key == NULL)
  27564. return PUBLIC_KEY_E;
  27565. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  27566. (word32)sizeof(der->publicKey), 1);
  27567. }
  27568. #endif
  27569. #if defined(HAVE_PQC)
  27570. #if defined(HAVE_FALCON)
  27571. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  27572. (cert->keyType == FALCON_LEVEL5_KEY)) {
  27573. if (falconKey == NULL)
  27574. return PUBLIC_KEY_E;
  27575. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  27576. der->publicKey, (word32)sizeof(der->publicKey), 1);
  27577. }
  27578. #endif
  27579. #if defined(HAVE_DILITHIUM)
  27580. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  27581. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  27582. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  27583. if (dilithiumKey == NULL)
  27584. return PUBLIC_KEY_E;
  27585. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  27586. der->publicKey, (word32)sizeof(der->publicKey), 1);
  27587. }
  27588. #endif
  27589. #if defined(HAVE_SPHINCS)
  27590. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  27591. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  27592. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  27593. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  27594. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  27595. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  27596. if (sphincsKey == NULL)
  27597. return PUBLIC_KEY_E;
  27598. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  27599. der->publicKey, (word32)sizeof(der->publicKey), 1);
  27600. }
  27601. #endif
  27602. #endif /* HAVE_PQC */
  27603. if (der->publicKeySz <= 0)
  27604. return PUBLIC_KEY_E;
  27605. /* set the extensions */
  27606. der->extensionsSz = 0;
  27607. /* RFC 5280 : 4.2.1.9. Basic Constraints
  27608. * The pathLenConstraint field is meaningful only if the CA boolean is
  27609. * asserted and the key usage extension, if present, asserts the
  27610. * keyCertSign bit */
  27611. /* Set CA and path length */
  27612. if ((cert->isCA) && (cert->pathLenSet)
  27613. #ifdef WOLFSSL_CERT_EXT
  27614. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  27615. #endif
  27616. ) {
  27617. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  27618. if (der->caSz <= 0)
  27619. return CA_TRUE_E;
  27620. der->extensionsSz += der->caSz;
  27621. }
  27622. #ifdef WOLFSSL_ALLOW_ENCODING_CA_FALSE
  27623. /* Set CA */
  27624. else if (cert->isCaSet) {
  27625. der->caSz = SetCaEx(der->ca, sizeof(der->ca), cert->isCA);
  27626. if (der->caSz <= 0)
  27627. return EXTENSIONS_E;
  27628. der->extensionsSz += der->caSz;
  27629. }
  27630. #endif
  27631. /* Set CA true */
  27632. else if (cert->isCA) {
  27633. der->caSz = SetCa(der->ca, sizeof(der->ca));
  27634. if (der->caSz <= 0)
  27635. return CA_TRUE_E;
  27636. der->extensionsSz += der->caSz;
  27637. }
  27638. /* Set Basic Constraint */
  27639. else if (cert->basicConstSet) {
  27640. der->caSz = SetBC(der->ca, sizeof(der->ca));
  27641. if (der->caSz <= 0)
  27642. return EXTENSIONS_E;
  27643. der->extensionsSz += der->caSz;
  27644. }
  27645. else
  27646. der->caSz = 0;
  27647. #ifdef WOLFSSL_ALT_NAMES
  27648. /* Alternative Name */
  27649. if (cert->altNamesSz) {
  27650. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  27651. cert->altNames, (word32)cert->altNamesSz,
  27652. cert->altNamesCrit);
  27653. if (der->altNamesSz <= 0)
  27654. return ALT_NAME_E;
  27655. der->extensionsSz += der->altNamesSz;
  27656. }
  27657. else
  27658. der->altNamesSz = 0;
  27659. #endif
  27660. #ifdef WOLFSSL_CERT_EXT
  27661. /* SKID */
  27662. if (cert->skidSz) {
  27663. /* check the provided SKID size */
  27664. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  27665. return SKID_E;
  27666. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  27667. cert->skid, (word32)cert->skidSz);
  27668. if (der->skidSz <= 0)
  27669. return SKID_E;
  27670. der->extensionsSz += der->skidSz;
  27671. }
  27672. else
  27673. der->skidSz = 0;
  27674. /* Key Usage */
  27675. if (cert->keyUsage != 0) {
  27676. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  27677. cert->keyUsage);
  27678. if (der->keyUsageSz <= 0)
  27679. return KEYUSAGE_E;
  27680. der->extensionsSz += der->keyUsageSz;
  27681. }
  27682. else
  27683. der->keyUsageSz = 0;
  27684. /* Extended Key Usage */
  27685. if (cert->extKeyUsage != 0) {
  27686. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  27687. sizeof(der->extKeyUsage), cert->extKeyUsage);
  27688. if (der->extKeyUsageSz <= 0)
  27689. return EXTKEYUSAGE_E;
  27690. der->extensionsSz += der->extKeyUsageSz;
  27691. }
  27692. else
  27693. der->extKeyUsageSz = 0;
  27694. #endif /* WOLFSSL_CERT_EXT */
  27695. #ifdef WOLFSSL_CUSTOM_OID
  27696. /* encode a custom oid and value */
  27697. /* zero returns, means none set */
  27698. ret = SetCustomObjectId(cert, der->extCustom,
  27699. sizeof(der->extCustom), &cert->extCustom);
  27700. if (ret < 0)
  27701. return ret;
  27702. der->extCustomSz = ret;
  27703. der->extensionsSz += der->extCustomSz;
  27704. #endif
  27705. /* put extensions */
  27706. if (der->extensionsSz > 0) {
  27707. /* put the start of sequence (ID, Size) */
  27708. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  27709. der->extensions);
  27710. if (der->extensionsSz <= 0)
  27711. return EXTENSIONS_E;
  27712. /* put CA */
  27713. if (der->caSz) {
  27714. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27715. &der->extensionsSz,
  27716. der->ca, der->caSz);
  27717. if (ret <= 0)
  27718. return EXTENSIONS_E;
  27719. }
  27720. #ifdef WOLFSSL_ALT_NAMES
  27721. /* put Alternative Names */
  27722. if (der->altNamesSz) {
  27723. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27724. &der->extensionsSz,
  27725. der->altNames, der->altNamesSz);
  27726. if (ret <= 0)
  27727. return EXTENSIONS_E;
  27728. }
  27729. #endif
  27730. #ifdef WOLFSSL_CERT_EXT
  27731. /* put SKID */
  27732. if (der->skidSz) {
  27733. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27734. &der->extensionsSz,
  27735. der->skid, der->skidSz);
  27736. if (ret <= 0)
  27737. return EXTENSIONS_E;
  27738. }
  27739. /* put AKID */
  27740. if (der->akidSz) {
  27741. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27742. &der->extensionsSz,
  27743. der->akid, der->akidSz);
  27744. if (ret <= 0)
  27745. return EXTENSIONS_E;
  27746. }
  27747. /* put KeyUsage */
  27748. if (der->keyUsageSz) {
  27749. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27750. &der->extensionsSz,
  27751. der->keyUsage, der->keyUsageSz);
  27752. if (ret <= 0)
  27753. return EXTENSIONS_E;
  27754. }
  27755. /* put ExtendedKeyUsage */
  27756. if (der->extKeyUsageSz) {
  27757. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27758. &der->extensionsSz,
  27759. der->extKeyUsage, der->extKeyUsageSz);
  27760. if (ret <= 0)
  27761. return EXTENSIONS_E;
  27762. }
  27763. #ifdef WOLFSSL_CUSTOM_OID
  27764. if (der->extCustomSz) {
  27765. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27766. &der->extensionsSz,
  27767. der->extCustom, der->extCustomSz);
  27768. if (ret <= 0)
  27769. return EXTENSIONS_E;
  27770. }
  27771. #endif
  27772. #endif /* WOLFSSL_CERT_EXT */
  27773. }
  27774. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  27775. if (der->attribSz <= 0)
  27776. return REQ_ATTRIBUTE_E;
  27777. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  27778. der->extensionsSz + der->attribSz;
  27779. return 0;
  27780. }
  27781. /* write DER encoded cert req to buffer, size already checked */
  27782. static int WriteCertReqBody(DerCert* der, byte* buf)
  27783. {
  27784. int idx;
  27785. /* signed part header */
  27786. idx = (int)SetSequence((word32)der->total, buf);
  27787. /* version */
  27788. if (buf)
  27789. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  27790. idx += der->versionSz;
  27791. /* subject */
  27792. if (buf)
  27793. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  27794. idx += der->subjectSz;
  27795. /* public key */
  27796. if (buf)
  27797. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  27798. idx += der->publicKeySz;
  27799. /* attributes */
  27800. if (buf)
  27801. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  27802. idx += der->attribSz;
  27803. /* extensions */
  27804. if (der->extensionsSz) {
  27805. if (buf)
  27806. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  27807. sizeof(der->extensions)));
  27808. idx += der->extensionsSz;
  27809. }
  27810. return idx;
  27811. }
  27812. #endif
  27813. #ifdef WOLFSSL_ASN_TEMPLATE
  27814. /* ASN.1 template for Certificate Request body.
  27815. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  27816. */
  27817. static const ASNItem certReqBodyASN[] = {
  27818. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  27819. /* version */
  27820. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  27821. /* subject */
  27822. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  27823. /* subjectPKInfo */
  27824. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  27825. /* attributes*/
  27826. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  27827. /* Challenge Password Attribute */
  27828. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  27829. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27830. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  27831. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  27832. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  27833. /* ATTRS_USN_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  27834. /* ATTRS_USN_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27835. /* ATTRS_USN_SET */ { 3, ASN_SET, 1, 1, 0 },
  27836. /* ATTRS_USN_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  27837. /* ATTRS_USN_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  27838. /* Extensions Attribute */
  27839. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  27840. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27841. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  27842. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  27843. };
  27844. enum {
  27845. CERTREQBODYASN_IDX_SEQ = 0,
  27846. CERTREQBODYASN_IDX_VER,
  27847. CERTREQBODYASN_IDX_SUBJ_SEQ,
  27848. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  27849. CERTREQBODYASN_IDX_ATTRS,
  27850. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  27851. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  27852. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  27853. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  27854. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  27855. CERTREQBODYASN_IDX_ATTRS_USN_SEQ,
  27856. CERTREQBODYASN_IDX_ATTRS_USN_OID,
  27857. CERTREQBODYASN_IDX_ATTRS_USN_SET,
  27858. CERTREQBODYASN_IDX_ATTRS_USN_PS,
  27859. CERTREQBODYASN_IDX_ATTRS_USN_UTF,
  27860. CERTREQBODYASN_IDX_EXT_SEQ,
  27861. CERTREQBODYASN_IDX_EXT_OID,
  27862. CERTREQBODYASN_IDX_EXT_SET,
  27863. CERTREQBODYASN_IDX_EXT_BODY
  27864. };
  27865. /* Number of items in ASN.1 template for Certificate Request body. */
  27866. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  27867. #endif
  27868. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  27869. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  27870. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27871. falcon_key* falconKey, dilithium_key* dilithiumKey,
  27872. sphincs_key* sphincsKey)
  27873. {
  27874. #ifndef WOLFSSL_ASN_TEMPLATE
  27875. int ret;
  27876. #ifdef WOLFSSL_SMALL_STACK
  27877. DerCert* der;
  27878. #else
  27879. DerCert der[1];
  27880. #endif
  27881. if (eccKey)
  27882. cert->keyType = ECC_KEY;
  27883. else if (rsaKey)
  27884. cert->keyType = RSA_KEY;
  27885. else if (dsaKey)
  27886. cert->keyType = DSA_KEY;
  27887. else if (ed25519Key)
  27888. cert->keyType = ED25519_KEY;
  27889. else if (ed448Key)
  27890. cert->keyType = ED448_KEY;
  27891. #ifdef HAVE_PQC
  27892. #ifdef HAVE_FALCON
  27893. else if ((falconKey != NULL) && (falconKey->level == 1))
  27894. cert->keyType = FALCON_LEVEL1_KEY;
  27895. else if ((falconKey != NULL) && (falconKey->level == 5))
  27896. cert->keyType = FALCON_LEVEL5_KEY;
  27897. #endif /* HAVE_FALCON */
  27898. #ifdef HAVE_DILITHIUM
  27899. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  27900. cert->keyType = DILITHIUM_LEVEL2_KEY;
  27901. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  27902. cert->keyType = DILITHIUM_LEVEL3_KEY;
  27903. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  27904. cert->keyType = DILITHIUM_LEVEL5_KEY;
  27905. #endif /* HAVE_DILITHIUM */
  27906. #ifdef HAVE_SPHINCS
  27907. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27908. && (sphincsKey->optim == FAST_VARIANT))
  27909. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  27910. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27911. && (sphincsKey->optim == FAST_VARIANT))
  27912. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  27913. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27914. && (sphincsKey->optim == FAST_VARIANT))
  27915. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  27916. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27917. && (sphincsKey->optim == SMALL_VARIANT))
  27918. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  27919. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27920. && (sphincsKey->optim == SMALL_VARIANT))
  27921. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  27922. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27923. && (sphincsKey->optim == SMALL_VARIANT))
  27924. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  27925. #endif /* HAVE_SPHINCS */
  27926. #endif /* HAVE_PQC */
  27927. else
  27928. return BAD_FUNC_ARG;
  27929. #ifdef WOLFSSL_SMALL_STACK
  27930. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  27931. DYNAMIC_TYPE_TMP_BUFFER);
  27932. if (der == NULL)
  27933. return MEMORY_E;
  27934. #endif
  27935. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  27936. falconKey, dilithiumKey, sphincsKey);
  27937. if (ret == 0) {
  27938. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  27939. ret = BUFFER_E;
  27940. else
  27941. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  27942. }
  27943. #ifdef WOLFSSL_SMALL_STACK
  27944. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27945. #endif
  27946. return ret;
  27947. #else
  27948. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  27949. word32 publicKeySz = 0;
  27950. word32 subjectSz = 0;
  27951. word32 extSz = 0;
  27952. int sz = 0;
  27953. int ret = 0;
  27954. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27955. word32 sbjRawSz = 0;
  27956. #endif
  27957. /* Unused without OQS */
  27958. (void)falconKey;
  27959. (void)dilithiumKey;
  27960. (void)sphincsKey;
  27961. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  27962. if (ret == 0) {
  27963. /* Set key type into certificate object based on key passed in. */
  27964. if (rsaKey != NULL) {
  27965. cert->keyType = RSA_KEY;
  27966. }
  27967. else if (eccKey != NULL) {
  27968. cert->keyType = ECC_KEY;
  27969. }
  27970. else if (dsaKey != NULL) {
  27971. cert->keyType = DSA_KEY;
  27972. }
  27973. else if (ed25519Key != NULL) {
  27974. cert->keyType = ED25519_KEY;
  27975. }
  27976. else if (ed448Key != NULL) {
  27977. cert->keyType = ED448_KEY;
  27978. }
  27979. #ifdef HAVE_PQC
  27980. #ifdef HAVE_FALCON
  27981. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  27982. cert->keyType = FALCON_LEVEL1_KEY;
  27983. }
  27984. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  27985. cert->keyType = FALCON_LEVEL5_KEY;
  27986. }
  27987. #endif /* HAVE_FALCON */
  27988. #ifdef HAVE_DILITHIUM
  27989. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  27990. cert->keyType = DILITHIUM_LEVEL2_KEY;
  27991. }
  27992. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  27993. cert->keyType = DILITHIUM_LEVEL3_KEY;
  27994. }
  27995. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  27996. cert->keyType = DILITHIUM_LEVEL5_KEY;
  27997. }
  27998. #endif /* HAVE_DILITHIUM */
  27999. #ifdef HAVE_SPHINCS
  28000. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  28001. && (sphincsKey->optim == FAST_VARIANT)) {
  28002. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  28003. }
  28004. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  28005. && (sphincsKey->optim == FAST_VARIANT)) {
  28006. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  28007. }
  28008. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  28009. && (sphincsKey->optim == FAST_VARIANT)) {
  28010. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  28011. }
  28012. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  28013. && (sphincsKey->optim == SMALL_VARIANT)) {
  28014. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  28015. }
  28016. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  28017. && (sphincsKey->optim == SMALL_VARIANT)) {
  28018. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  28019. }
  28020. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  28021. && (sphincsKey->optim == SMALL_VARIANT)) {
  28022. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  28023. }
  28024. #endif /* HAVE_SPHINCS */
  28025. #endif /* HAVE_PQC */
  28026. else {
  28027. ret = BAD_FUNC_ARG;
  28028. }
  28029. }
  28030. if (ret == 0) {
  28031. /* Determine subject name size. */
  28032. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  28033. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  28034. if (sbjRawSz > 0) {
  28035. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  28036. }
  28037. else
  28038. #endif
  28039. {
  28040. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  28041. subjectSz = (word32)ret;
  28042. }
  28043. }
  28044. if (ret >= 0) {
  28045. /* Determine encode public key size. */
  28046. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  28047. eccKey, ed25519Key, ed448Key, dsaKey);
  28048. publicKeySz = (word32)ret;
  28049. }
  28050. if (ret >= 0) {
  28051. /* Determine encode extensions size. */
  28052. ret = EncodeExtensions(cert, NULL, 0, 1);
  28053. extSz = (word32)ret;
  28054. }
  28055. if (ret >= 0) {
  28056. /* Set version. */
  28057. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  28058. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  28059. if (sbjRawSz > 0) {
  28060. /* Put in encoded subject name. */
  28061. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  28062. subjectSz);
  28063. }
  28064. else
  28065. #endif
  28066. {
  28067. /* Leave space for subject name. */
  28068. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  28069. subjectSz);
  28070. }
  28071. /* Leave space for public key. */
  28072. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  28073. NULL, publicKeySz);
  28074. if (cert->challengePw[0] != '\0') {
  28075. /* Add challenge password attribute. */
  28076. /* Set challenge password OID. */
  28077. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  28078. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  28079. /* Enable the ASN template item with the appropriate tag. */
  28080. if (cert->challengePwPrintableString) {
  28081. /* PRINTABLE_STRING - set buffer */
  28082. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  28083. (byte*)cert->challengePw,
  28084. (word32)XSTRLEN(cert->challengePw));
  28085. /* UTF8STRING - don't encode */
  28086. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  28087. }
  28088. else {
  28089. /* PRINTABLE_STRING - don't encode */
  28090. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  28091. /* UTF8STRING - set buffer */
  28092. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  28093. (byte*)cert->challengePw,
  28094. (word32)XSTRLEN(cert->challengePw));
  28095. }
  28096. }
  28097. else {
  28098. /* Leave out challenge password attribute items. */
  28099. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  28100. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  28101. }
  28102. if (cert->unstructuredName[0] != '\0') {
  28103. /* Add unstructured name attribute. */
  28104. /* Set unstructured name OID. */
  28105. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_USN_OID],
  28106. attrUnstructuredNameOid, sizeof(attrUnstructuredNameOid));
  28107. /* PRINTABLE_STRING - set buffer */
  28108. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_USN_PS],
  28109. (byte*)cert->unstructuredName,
  28110. (word32)XSTRLEN(cert->unstructuredName));
  28111. /* UTF8STRING - don't encode */
  28112. dataASN[CERTREQBODYASN_IDX_ATTRS_USN_UTF].noOut = 1;
  28113. }
  28114. else {
  28115. /* Leave out unstructured name attribute item. */
  28116. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  28117. CERTREQBODYASN_IDX_ATTRS_USN_SEQ, certReqBodyASN_Length);
  28118. }
  28119. if (extSz > 0) {
  28120. /* Set extension attribute OID. */
  28121. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  28122. sizeof(attrExtensionRequestOid));
  28123. /* Leave space for data. */
  28124. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  28125. }
  28126. else {
  28127. /* Leave out extension attribute items. */
  28128. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  28129. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  28130. }
  28131. /* Calculate size of encoded certificate request body. */
  28132. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  28133. &sz);
  28134. }
  28135. /* Check buffer is big enough for encoded data. */
  28136. if ((ret == 0) && (sz > (int)derSz)) {
  28137. ret = BUFFER_E;
  28138. }
  28139. if (ret == 0 && derBuffer != NULL) {
  28140. /* Encode certificate request body into buffer. */
  28141. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  28142. /* Put in generated data */
  28143. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  28144. if (sbjRawSz == 0)
  28145. #endif
  28146. {
  28147. /* Encode subject name into space in buffer. */
  28148. ret = SetNameEx(
  28149. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  28150. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  28151. &cert->subject, cert->heap);
  28152. }
  28153. }
  28154. if (ret >= 0 && derBuffer != NULL) {
  28155. /* Encode public key into space in buffer. */
  28156. ret = EncodePublicKey(cert->keyType,
  28157. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  28158. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  28159. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  28160. }
  28161. if ((ret >= 0 && derBuffer != NULL) &&
  28162. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  28163. /* Encode extensions into space in buffer. */
  28164. ret = EncodeExtensions(cert,
  28165. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  28166. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  28167. }
  28168. if (ret >= 0) {
  28169. /* Store encoded certificate request body size. */
  28170. cert->bodySz = sz;
  28171. /* Return the encoding size. */
  28172. ret = sz;
  28173. }
  28174. FREE_ASNSETDATA(dataASN, cert->heap);
  28175. return ret;
  28176. #endif /* WOLFSSL_ASN_TEMPLATE */
  28177. }
  28178. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  28179. void* key)
  28180. {
  28181. RsaKey* rsaKey = NULL;
  28182. DsaKey* dsaKey = NULL;
  28183. ecc_key* eccKey = NULL;
  28184. ed25519_key* ed25519Key = NULL;
  28185. ed448_key* ed448Key = NULL;
  28186. falcon_key* falconKey = NULL;
  28187. dilithium_key* dilithiumKey = NULL;
  28188. sphincs_key* sphincsKey = NULL;
  28189. if (keyType == RSA_TYPE)
  28190. rsaKey = (RsaKey*)key;
  28191. else if (keyType == DSA_TYPE)
  28192. dsaKey = (DsaKey*)key;
  28193. else if (keyType == ECC_TYPE)
  28194. eccKey = (ecc_key*)key;
  28195. else if (keyType == ED25519_TYPE)
  28196. ed25519Key = (ed25519_key*)key;
  28197. else if (keyType == ED448_TYPE)
  28198. ed448Key = (ed448_key*)key;
  28199. else if (keyType == FALCON_LEVEL1_TYPE)
  28200. falconKey = (falcon_key*)key;
  28201. else if (keyType == FALCON_LEVEL5_TYPE)
  28202. falconKey = (falcon_key*)key;
  28203. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  28204. dilithiumKey = (dilithium_key*)key;
  28205. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  28206. dilithiumKey = (dilithium_key*)key;
  28207. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  28208. dilithiumKey = (dilithium_key*)key;
  28209. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  28210. sphincsKey = (sphincs_key*)key;
  28211. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  28212. sphincsKey = (sphincs_key*)key;
  28213. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  28214. sphincsKey = (sphincs_key*)key;
  28215. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  28216. sphincsKey = (sphincs_key*)key;
  28217. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  28218. sphincsKey = (sphincs_key*)key;
  28219. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  28220. sphincsKey = (sphincs_key*)key;
  28221. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  28222. ed25519Key, ed448Key, falconKey, dilithiumKey,
  28223. sphincsKey);
  28224. }
  28225. WOLFSSL_ABI
  28226. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  28227. RsaKey* rsaKey, ecc_key* eccKey)
  28228. {
  28229. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  28230. NULL, NULL, NULL, NULL);
  28231. }
  28232. #endif /* WOLFSSL_CERT_REQ */
  28233. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  28234. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  28235. ed448_key* ed448Key, falcon_key* falconKey,
  28236. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  28237. WC_RNG* rng)
  28238. {
  28239. int sigSz = 0;
  28240. void* heap = NULL;
  28241. CertSignCtx certSignCtx_lcl;
  28242. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  28243. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  28244. if (requestSz < 0)
  28245. return requestSz;
  28246. /* locate ctx */
  28247. if (rsaKey) {
  28248. #ifndef NO_RSA
  28249. #ifdef WOLFSSL_ASYNC_CRYPT
  28250. certSignCtx = &rsaKey->certSignCtx;
  28251. #endif
  28252. heap = rsaKey->heap;
  28253. #else
  28254. return NOT_COMPILED_IN;
  28255. #endif /* NO_RSA */
  28256. }
  28257. else if (eccKey) {
  28258. #ifdef HAVE_ECC
  28259. #ifdef WOLFSSL_ASYNC_CRYPT
  28260. certSignCtx = &eccKey->certSignCtx;
  28261. #endif
  28262. heap = eccKey->heap;
  28263. #else
  28264. return NOT_COMPILED_IN;
  28265. #endif /* HAVE_ECC */
  28266. }
  28267. if (certSignCtx->sig == NULL) {
  28268. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  28269. DYNAMIC_TYPE_TMP_BUFFER);
  28270. if (certSignCtx->sig == NULL)
  28271. return MEMORY_E;
  28272. }
  28273. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  28274. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  28275. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  28276. #ifdef WOLFSSL_ASYNC_CRYPT
  28277. if (sigSz == WC_PENDING_E) {
  28278. /* Not free'ing certSignCtx->sig here because it could still be in use
  28279. * with async operations. */
  28280. return sigSz;
  28281. }
  28282. #endif
  28283. if (sigSz >= 0) {
  28284. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  28285. sigSz = BUFFER_E;
  28286. else
  28287. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  28288. sType);
  28289. }
  28290. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28291. certSignCtx->sig = NULL;
  28292. return sigSz;
  28293. }
  28294. #ifdef WOLFSSL_DUAL_ALG_CERTS
  28295. int wc_MakeSigWithBitStr(byte *sig, int sigSz, int sType, byte* buf,
  28296. word32 bufSz, int keyType, void* key, WC_RNG* rng)
  28297. {
  28298. RsaKey* rsaKey = NULL;
  28299. ecc_key* eccKey = NULL;
  28300. ed25519_key* ed25519Key = NULL;
  28301. ed448_key* ed448Key = NULL;
  28302. falcon_key* falconKey = NULL;
  28303. dilithium_key* dilithiumKey = NULL;
  28304. sphincs_key* sphincsKey = NULL;
  28305. int ret = 0;
  28306. int headerSz;
  28307. void* heap = NULL;
  28308. CertSignCtx certSignCtx_lcl;
  28309. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  28310. if ((sig == NULL) || (sigSz <= 0)) {
  28311. return BAD_FUNC_ARG;
  28312. }
  28313. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  28314. switch (keyType)
  28315. {
  28316. case RSA_TYPE:
  28317. rsaKey = (RsaKey*)key;
  28318. break;
  28319. case ECC_TYPE:
  28320. eccKey = (ecc_key*)key;
  28321. break;
  28322. case ED25519_TYPE:
  28323. ed25519Key = (ed25519_key*)key;
  28324. break;
  28325. case ED448_TYPE:
  28326. ed448Key = (ed448_key*)key;
  28327. break;
  28328. case FALCON_LEVEL1_TYPE:
  28329. case FALCON_LEVEL5_TYPE:
  28330. falconKey = (falcon_key*)key;
  28331. break;
  28332. case DILITHIUM_LEVEL2_TYPE:
  28333. case DILITHIUM_LEVEL3_TYPE:
  28334. case DILITHIUM_LEVEL5_TYPE:
  28335. dilithiumKey = (dilithium_key*)key;
  28336. break;
  28337. case SPHINCS_FAST_LEVEL1_TYPE:
  28338. case SPHINCS_FAST_LEVEL3_TYPE:
  28339. case SPHINCS_FAST_LEVEL5_TYPE:
  28340. case SPHINCS_SMALL_LEVEL1_TYPE:
  28341. case SPHINCS_SMALL_LEVEL3_TYPE:
  28342. case SPHINCS_SMALL_LEVEL5_TYPE:
  28343. sphincsKey = (sphincs_key*)key;
  28344. break;
  28345. default:
  28346. return BAD_FUNC_ARG;
  28347. }
  28348. /* locate ctx */
  28349. if (rsaKey) {
  28350. #ifndef NO_RSA
  28351. #ifdef WOLFSSL_ASYNC_CRYPT
  28352. certSignCtx = &rsaKey->certSignCtx;
  28353. #endif
  28354. heap = rsaKey->heap;
  28355. #else
  28356. return NOT_COMPILED_IN;
  28357. #endif /* NO_RSA */
  28358. }
  28359. else if (eccKey) {
  28360. #ifdef HAVE_ECC
  28361. #ifdef WOLFSSL_ASYNC_CRYPT
  28362. certSignCtx = &eccKey->certSignCtx;
  28363. #endif
  28364. heap = eccKey->heap;
  28365. #else
  28366. return NOT_COMPILED_IN;
  28367. #endif /* HAVE_ECC */
  28368. }
  28369. if (certSignCtx->sig == NULL) {
  28370. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  28371. DYNAMIC_TYPE_TMP_BUFFER);
  28372. if (certSignCtx->sig == NULL)
  28373. return MEMORY_E;
  28374. }
  28375. ret = MakeSignature(certSignCtx, buf, (word32)bufSz, certSignCtx->sig,
  28376. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  28377. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  28378. #ifdef WOLFSSL_ASYNC_CRYPT
  28379. if (ret == WC_PENDING_E) {
  28380. /* Not free'ing certSignCtx->sig here because it could still be in use
  28381. * with async operations. */
  28382. return ret;
  28383. }
  28384. #endif
  28385. if (ret <= 0) {
  28386. return ret;
  28387. }
  28388. headerSz = SetBitString(ret, 0, NULL);
  28389. if (headerSz + ret > sigSz) {
  28390. ret = BUFFER_E;
  28391. }
  28392. if (ret > 0) {
  28393. sig += SetBitString(ret, 0, sig);
  28394. XMEMCPY(sig, certSignCtx->sig, ret);
  28395. ret += headerSz;
  28396. }
  28397. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28398. certSignCtx->sig = NULL;
  28399. return ret;
  28400. }
  28401. #endif /* WOLFSSL_DUAL_ALG_CERTS */
  28402. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  28403. int keyType, void* key, WC_RNG* rng)
  28404. {
  28405. RsaKey* rsaKey = NULL;
  28406. ecc_key* eccKey = NULL;
  28407. ed25519_key* ed25519Key = NULL;
  28408. ed448_key* ed448Key = NULL;
  28409. falcon_key* falconKey = NULL;
  28410. dilithium_key* dilithiumKey = NULL;
  28411. sphincs_key* sphincsKey = NULL;
  28412. if (keyType == RSA_TYPE)
  28413. rsaKey = (RsaKey*)key;
  28414. else if (keyType == ECC_TYPE)
  28415. eccKey = (ecc_key*)key;
  28416. else if (keyType == ED25519_TYPE)
  28417. ed25519Key = (ed25519_key*)key;
  28418. else if (keyType == ED448_TYPE)
  28419. ed448Key = (ed448_key*)key;
  28420. else if (keyType == FALCON_LEVEL1_TYPE)
  28421. falconKey = (falcon_key*)key;
  28422. else if (keyType == FALCON_LEVEL5_TYPE)
  28423. falconKey = (falcon_key*)key;
  28424. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  28425. dilithiumKey = (dilithium_key*)key;
  28426. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  28427. dilithiumKey = (dilithium_key*)key;
  28428. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  28429. dilithiumKey = (dilithium_key*)key;
  28430. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  28431. sphincsKey = (sphincs_key*)key;
  28432. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  28433. sphincsKey = (sphincs_key*)key;
  28434. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  28435. sphincsKey = (sphincs_key*)key;
  28436. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  28437. sphincsKey = (sphincs_key*)key;
  28438. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  28439. sphincsKey = (sphincs_key*)key;
  28440. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  28441. sphincsKey = (sphincs_key*)key;
  28442. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  28443. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  28444. }
  28445. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  28446. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  28447. {
  28448. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  28449. NULL, NULL, NULL, rng);
  28450. }
  28451. WOLFSSL_ABI
  28452. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  28453. RsaKey* key, WC_RNG* rng)
  28454. {
  28455. int ret;
  28456. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  28457. if (ret < 0)
  28458. return ret;
  28459. return wc_SignCert(cert->bodySz, cert->sigType,
  28460. buf, buffSz, key, NULL, rng);
  28461. }
  28462. #ifdef WOLFSSL_CERT_EXT
  28463. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  28464. The raw subject pointer will only be valid while "cert" is valid. */
  28465. WOLFSSL_ABI
  28466. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  28467. {
  28468. int rc = BAD_FUNC_ARG;
  28469. if ((subjectRaw != NULL) && (cert != NULL)) {
  28470. *subjectRaw = cert->sbjRaw;
  28471. rc = 0;
  28472. }
  28473. return rc;
  28474. }
  28475. /* Set KID from public key */
  28476. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  28477. ed25519_key* ed25519Key, ed448_key* ed448Key,
  28478. falcon_key* falconKey,
  28479. dilithium_key* dilithiumKey,
  28480. sphincs_key *sphincsKey, int kid_type)
  28481. {
  28482. byte *buf;
  28483. int bufferSz, ret;
  28484. if (cert == NULL ||
  28485. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  28486. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  28487. sphincsKey == NULL) ||
  28488. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  28489. return BAD_FUNC_ARG;
  28490. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  28491. DYNAMIC_TYPE_TMP_BUFFER);
  28492. if (buf == NULL)
  28493. return MEMORY_E;
  28494. /* Public Key */
  28495. bufferSz = -1;
  28496. #ifndef NO_RSA
  28497. /* RSA public key */
  28498. if (rsakey != NULL)
  28499. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  28500. #endif
  28501. #ifdef HAVE_ECC
  28502. /* ECC public key */
  28503. if (eckey != NULL)
  28504. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  28505. #endif
  28506. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  28507. /* ED25519 public key */
  28508. if (ed25519Key != NULL) {
  28509. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  28510. }
  28511. #endif
  28512. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  28513. /* ED448 public key */
  28514. if (ed448Key != NULL) {
  28515. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  28516. }
  28517. #endif
  28518. #if defined(HAVE_PQC)
  28519. #if defined(HAVE_FALCON)
  28520. if (falconKey != NULL) {
  28521. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  28522. 0);
  28523. }
  28524. #endif
  28525. #if defined(HAVE_DILITHIUM)
  28526. if (dilithiumKey != NULL) {
  28527. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  28528. MAX_PUBLIC_KEY_SZ, 0);
  28529. }
  28530. #endif
  28531. #if defined(HAVE_SPHINCS)
  28532. if (sphincsKey != NULL) {
  28533. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  28534. MAX_PUBLIC_KEY_SZ, 0);
  28535. }
  28536. #endif
  28537. #endif /* HAVE_PQC */
  28538. if (bufferSz <= 0) {
  28539. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28540. return PUBLIC_KEY_E;
  28541. }
  28542. /* Compute SKID by hashing public key */
  28543. if (kid_type == SKID_TYPE) {
  28544. int hashId = HashIdAlg((word32)cert->sigType);
  28545. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->skid, hashId);
  28546. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  28547. cert->skidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  28548. #else
  28549. cert->skidSz = KEYID_SIZE;
  28550. #endif
  28551. }
  28552. else if (kid_type == AKID_TYPE) {
  28553. int hashId = HashIdAlg((word32)cert->sigType);
  28554. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->akid, hashId);
  28555. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  28556. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  28557. #else
  28558. cert->akidSz = KEYID_SIZE;
  28559. #endif
  28560. }
  28561. else
  28562. ret = BAD_FUNC_ARG;
  28563. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28564. return ret;
  28565. }
  28566. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  28567. {
  28568. RsaKey* rsaKey = NULL;
  28569. ecc_key* eccKey = NULL;
  28570. ed25519_key* ed25519Key = NULL;
  28571. ed448_key* ed448Key = NULL;
  28572. falcon_key* falconKey = NULL;
  28573. dilithium_key* dilithiumKey = NULL;
  28574. sphincs_key* sphincsKey = NULL;
  28575. if (keyType == RSA_TYPE)
  28576. rsaKey = (RsaKey*)key;
  28577. else if (keyType == ECC_TYPE)
  28578. eccKey = (ecc_key*)key;
  28579. else if (keyType == ED25519_TYPE)
  28580. ed25519Key = (ed25519_key*)key;
  28581. else if (keyType == ED448_TYPE)
  28582. ed448Key = (ed448_key*)key;
  28583. else if (keyType == FALCON_LEVEL1_TYPE)
  28584. falconKey = (falcon_key*)key;
  28585. else if (keyType == FALCON_LEVEL5_TYPE)
  28586. falconKey = (falcon_key*)key;
  28587. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  28588. dilithiumKey = (dilithium_key*)key;
  28589. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  28590. dilithiumKey = (dilithium_key*)key;
  28591. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  28592. dilithiumKey = (dilithium_key*)key;
  28593. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  28594. sphincsKey = (sphincs_key*)key;
  28595. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  28596. sphincsKey = (sphincs_key*)key;
  28597. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  28598. sphincsKey = (sphincs_key*)key;
  28599. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  28600. sphincsKey = (sphincs_key*)key;
  28601. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  28602. sphincsKey = (sphincs_key*)key;
  28603. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  28604. sphincsKey = (sphincs_key*)key;
  28605. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  28606. falconKey, dilithiumKey, sphincsKey,
  28607. SKID_TYPE);
  28608. }
  28609. /* Set SKID from RSA or ECC public key */
  28610. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  28611. {
  28612. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  28613. NULL, SKID_TYPE);
  28614. }
  28615. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  28616. {
  28617. RsaKey* rsaKey = NULL;
  28618. ecc_key* eccKey = NULL;
  28619. ed25519_key* ed25519Key = NULL;
  28620. ed448_key* ed448Key = NULL;
  28621. falcon_key* falconKey = NULL;
  28622. dilithium_key* dilithiumKey = NULL;
  28623. sphincs_key* sphincsKey = NULL;
  28624. if (keyType == RSA_TYPE)
  28625. rsaKey = (RsaKey*)key;
  28626. else if (keyType == ECC_TYPE)
  28627. eccKey = (ecc_key*)key;
  28628. else if (keyType == ED25519_TYPE)
  28629. ed25519Key = (ed25519_key*)key;
  28630. else if (keyType == ED448_TYPE)
  28631. ed448Key = (ed448_key*)key;
  28632. else if (keyType == FALCON_LEVEL1_TYPE)
  28633. falconKey = (falcon_key*)key;
  28634. else if (keyType == FALCON_LEVEL5_TYPE)
  28635. falconKey = (falcon_key*)key;
  28636. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  28637. dilithiumKey = (dilithium_key*)key;
  28638. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  28639. dilithiumKey = (dilithium_key*)key;
  28640. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  28641. dilithiumKey = (dilithium_key*)key;
  28642. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  28643. sphincsKey = (sphincs_key*)key;
  28644. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  28645. sphincsKey = (sphincs_key*)key;
  28646. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  28647. sphincsKey = (sphincs_key*)key;
  28648. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  28649. sphincsKey = (sphincs_key*)key;
  28650. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  28651. sphincsKey = (sphincs_key*)key;
  28652. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  28653. sphincsKey = (sphincs_key*)key;
  28654. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  28655. falconKey, dilithiumKey, sphincsKey,
  28656. AKID_TYPE);
  28657. }
  28658. /* Set SKID from RSA or ECC public key */
  28659. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  28660. {
  28661. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  28662. NULL, AKID_TYPE);
  28663. }
  28664. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  28665. /* Set SKID from public key file in PEM */
  28666. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  28667. {
  28668. int ret, derSz;
  28669. byte* der;
  28670. word32 idx;
  28671. RsaKey *rsakey = NULL;
  28672. ecc_key *eckey = NULL;
  28673. if (cert == NULL || file == NULL)
  28674. return BAD_FUNC_ARG;
  28675. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  28676. if (der == NULL) {
  28677. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  28678. return MEMORY_E;
  28679. }
  28680. derSz = MAX_PUBLIC_KEY_SZ;
  28681. XMEMSET(der, 0, (size_t)derSz);
  28682. derSz = wc_PemPubKeyToDer(file, der, derSz);
  28683. if (derSz <= 0) {
  28684. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28685. return derSz;
  28686. }
  28687. /* Load PubKey in internal structure */
  28688. #ifndef NO_RSA
  28689. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  28690. if (rsakey == NULL) {
  28691. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28692. return MEMORY_E;
  28693. }
  28694. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  28695. WOLFSSL_MSG("wc_InitRsaKey failure");
  28696. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  28697. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28698. return MEMORY_E;
  28699. }
  28700. idx = 0;
  28701. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  28702. if (ret != 0)
  28703. #endif
  28704. {
  28705. #ifndef NO_RSA
  28706. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  28707. wc_FreeRsaKey(rsakey);
  28708. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  28709. rsakey = NULL;
  28710. #endif
  28711. #ifdef HAVE_ECC
  28712. /* Check to load ecc public key */
  28713. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  28714. DYNAMIC_TYPE_ECC);
  28715. if (eckey == NULL) {
  28716. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28717. return MEMORY_E;
  28718. }
  28719. if (wc_ecc_init(eckey) != 0) {
  28720. WOLFSSL_MSG("wc_ecc_init failure");
  28721. wc_ecc_free(eckey);
  28722. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  28723. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28724. return MEMORY_E;
  28725. }
  28726. idx = 0;
  28727. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  28728. if (ret != 0) {
  28729. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  28730. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28731. wc_ecc_free(eckey);
  28732. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  28733. return PUBLIC_KEY_E;
  28734. }
  28735. #else
  28736. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28737. return PUBLIC_KEY_E;
  28738. #endif /* HAVE_ECC */
  28739. }
  28740. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  28741. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  28742. #ifndef NO_RSA
  28743. wc_FreeRsaKey(rsakey);
  28744. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  28745. #endif
  28746. #ifdef HAVE_ECC
  28747. wc_ecc_free(eckey);
  28748. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  28749. #endif
  28750. #if defined(NO_RSA) && !defined(HAVE_ECC)
  28751. (void)idx;
  28752. #endif
  28753. return ret;
  28754. }
  28755. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  28756. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  28757. {
  28758. int ret = 0;
  28759. /* Subject Key Id not found !! */
  28760. if (decoded->extSubjKeyIdSet == 0) {
  28761. ret = ASN_NO_SKID;
  28762. }
  28763. /* SKID invalid size */
  28764. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  28765. ret = MEMORY_E;
  28766. }
  28767. else {
  28768. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  28769. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(HashIdAlg(
  28770. cert->sigType)));
  28771. #else
  28772. cert->akidSz = KEYID_SIZE;
  28773. #endif
  28774. /* Put the SKID of CA to AKID of certificate */
  28775. XMEMCPY(cert->akid, decoded->extSubjKeyId, (size_t)cert->akidSz);
  28776. }
  28777. return ret;
  28778. }
  28779. /* Set AKID from certificate contains in buffer (DER encoded) */
  28780. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  28781. {
  28782. int ret = 0;
  28783. if (cert == NULL) {
  28784. ret = BAD_FUNC_ARG;
  28785. }
  28786. else {
  28787. /* Check if decodedCert is cached */
  28788. if (cert->der != der) {
  28789. /* Allocate cache for the decoded cert */
  28790. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28791. }
  28792. if (ret >= 0) {
  28793. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28794. #ifndef WOLFSSL_CERT_GEN_CACHE
  28795. wc_SetCert_Free(cert);
  28796. #endif
  28797. }
  28798. }
  28799. return ret;
  28800. }
  28801. #ifndef NO_FILESYSTEM
  28802. /* Set AKID from certificate file in PEM */
  28803. int wc_SetAuthKeyId(Cert *cert, const char* file)
  28804. {
  28805. int ret;
  28806. DerBuffer* der = NULL;
  28807. if (cert == NULL || file == NULL)
  28808. return BAD_FUNC_ARG;
  28809. ret = wc_PemCertToDer_ex(file, &der);
  28810. if (ret == 0)
  28811. {
  28812. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  28813. FreeDer(&der);
  28814. }
  28815. return ret;
  28816. }
  28817. #endif /* !NO_FILESYSTEM */
  28818. /* Set KeyUsage from human readable string */
  28819. int wc_SetKeyUsage(Cert *cert, const char *value)
  28820. {
  28821. int ret = 0;
  28822. if (cert == NULL || value == NULL)
  28823. return BAD_FUNC_ARG;
  28824. cert->keyUsage = 0;
  28825. ret = ParseKeyUsageStr(value, &cert->keyUsage, cert->heap);
  28826. return ret;
  28827. }
  28828. /* Set ExtendedKeyUsage from human readable string */
  28829. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  28830. {
  28831. int ret = 0;
  28832. if (cert == NULL || value == NULL)
  28833. return BAD_FUNC_ARG;
  28834. cert->extKeyUsage = 0;
  28835. ret = ParseExtKeyUsageStr(value, &cert->extKeyUsage, cert->heap);
  28836. return ret;
  28837. }
  28838. #ifdef WOLFSSL_EKU_OID
  28839. /*
  28840. * cert structure to set EKU oid in
  28841. * oid the oid in byte representation
  28842. * sz size of oid buffer
  28843. * idx index of array to place oid
  28844. *
  28845. * returns 0 on success
  28846. */
  28847. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  28848. void* heap)
  28849. {
  28850. byte oid[CTC_MAX_EKU_OID_SZ];
  28851. word32 oidSz = CTC_MAX_EKU_OID_SZ;
  28852. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  28853. WOLFSSL_MSG("Either idx or sz was too large");
  28854. return BAD_FUNC_ARG;
  28855. }
  28856. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  28857. return BUFFER_E;
  28858. }
  28859. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  28860. cert->extKeyUsageOIDSz[idx] = oidSz;
  28861. cert->extKeyUsage |= EXTKEYUSE_USER;
  28862. return 0;
  28863. }
  28864. #endif /* WOLFSSL_EKU_OID */
  28865. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  28866. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  28867. defined(WOLFSSL_CERT_EXT)
  28868. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  28869. const byte *der, word32 derSz) {
  28870. CertExtension *ext;
  28871. byte encodedOid[MAX_OID_SZ];
  28872. word32 encodedOidSz = MAX_OID_SZ;
  28873. int ret;
  28874. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  28875. return BAD_FUNC_ARG;
  28876. }
  28877. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  28878. return MEMORY_E;
  28879. }
  28880. /* Make sure we can properly parse the OID. */
  28881. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  28882. if (ret != 0) {
  28883. return ret;
  28884. }
  28885. ext = &cert->customCertExt[cert->customCertExtCount];
  28886. ext->oid = (char*)oid;
  28887. ext->crit = (critical == 0) ? 0 : 1;
  28888. ext->val = (byte*)der;
  28889. ext->valSz = derSz;
  28890. cert->customCertExtCount++;
  28891. return 0;
  28892. }
  28893. #endif
  28894. #endif /* WOLFSSL_CERT_EXT */
  28895. #ifdef WOLFSSL_ALT_NAMES
  28896. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  28897. {
  28898. int ret = 0;
  28899. cert->altNamesSz = 0;
  28900. if (decoded->altNames) {
  28901. ret = FlattenAltNames(cert->altNames,
  28902. sizeof(cert->altNames), decoded->altNames);
  28903. if (ret >= 0) {
  28904. cert->altNamesSz = ret;
  28905. ret = 0;
  28906. }
  28907. }
  28908. return ret;
  28909. }
  28910. #ifndef NO_FILESYSTEM
  28911. /* Set Alt Names from der cert, return 0 on success */
  28912. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  28913. int devId)
  28914. {
  28915. int ret;
  28916. #ifdef WOLFSSL_SMALL_STACK
  28917. DecodedCert* decoded;
  28918. #else
  28919. DecodedCert decoded[1];
  28920. #endif
  28921. if (derSz < 0)
  28922. return derSz;
  28923. #ifdef WOLFSSL_SMALL_STACK
  28924. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  28925. DYNAMIC_TYPE_TMP_BUFFER);
  28926. if (decoded == NULL)
  28927. return MEMORY_E;
  28928. #endif
  28929. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  28930. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  28931. if (ret < 0) {
  28932. WOLFSSL_MSG("ParseCertRelative error");
  28933. }
  28934. else {
  28935. ret = SetAltNamesFromDcert(cert, decoded);
  28936. }
  28937. FreeDecodedCert(decoded);
  28938. #ifdef WOLFSSL_SMALL_STACK
  28939. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28940. #endif
  28941. return ret < 0 ? ret : 0;
  28942. }
  28943. #endif
  28944. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  28945. {
  28946. int ret = 0;
  28947. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  28948. WOLFSSL_MSG("Couldn't extract dates");
  28949. ret = -1;
  28950. }
  28951. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  28952. decoded->afterDateLen > MAX_DATE_SIZE) {
  28953. WOLFSSL_MSG("Bad date size");
  28954. ret = -1;
  28955. }
  28956. else {
  28957. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  28958. (size_t)decoded->beforeDateLen);
  28959. XMEMCPY(cert->afterDate, decoded->afterDate,
  28960. (size_t)decoded->afterDateLen);
  28961. cert->beforeDateSz = decoded->beforeDateLen;
  28962. cert->afterDateSz = decoded->afterDateLen;
  28963. }
  28964. return ret;
  28965. }
  28966. #endif /* WOLFSSL_ALT_NAMES */
  28967. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  28968. {
  28969. int sz;
  28970. if (decoded->subjectCN) {
  28971. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  28972. : CTC_NAME_SIZE - 1;
  28973. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  28974. cn->commonName[sz] = '\0';
  28975. cn->commonNameEnc = decoded->subjectCNEnc;
  28976. }
  28977. if (decoded->subjectC) {
  28978. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  28979. : CTC_NAME_SIZE - 1;
  28980. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  28981. cn->country[sz] = '\0';
  28982. cn->countryEnc = decoded->subjectCEnc;
  28983. }
  28984. if (decoded->subjectST) {
  28985. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  28986. : CTC_NAME_SIZE - 1;
  28987. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  28988. cn->state[sz] = '\0';
  28989. cn->stateEnc = decoded->subjectSTEnc;
  28990. }
  28991. if (decoded->subjectL) {
  28992. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  28993. : CTC_NAME_SIZE - 1;
  28994. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  28995. cn->locality[sz] = '\0';
  28996. cn->localityEnc = decoded->subjectLEnc;
  28997. }
  28998. if (decoded->subjectO) {
  28999. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  29000. : CTC_NAME_SIZE - 1;
  29001. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  29002. cn->org[sz] = '\0';
  29003. cn->orgEnc = decoded->subjectOEnc;
  29004. }
  29005. if (decoded->subjectOU) {
  29006. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  29007. : CTC_NAME_SIZE - 1;
  29008. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  29009. cn->unit[sz] = '\0';
  29010. cn->unitEnc = decoded->subjectOUEnc;
  29011. }
  29012. if (decoded->subjectSN) {
  29013. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  29014. : CTC_NAME_SIZE - 1;
  29015. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  29016. cn->sur[sz] = '\0';
  29017. cn->surEnc = decoded->subjectSNEnc;
  29018. }
  29019. if (decoded->subjectSND) {
  29020. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  29021. : CTC_NAME_SIZE - 1;
  29022. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  29023. cn->serialDev[sz] = '\0';
  29024. cn->serialDevEnc = decoded->subjectSNDEnc;
  29025. }
  29026. if (decoded->subjectUID) {
  29027. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  29028. : CTC_NAME_SIZE - 1;
  29029. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  29030. cn->userId[sz] = '\0';
  29031. cn->userIdEnc = decoded->subjectUIDEnc;
  29032. }
  29033. #ifdef WOLFSSL_CERT_EXT
  29034. if (decoded->subjectBC) {
  29035. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  29036. : CTC_NAME_SIZE - 1;
  29037. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  29038. cn->busCat[sz] = '\0';
  29039. cn->busCatEnc = decoded->subjectBCEnc;
  29040. }
  29041. if (decoded->subjectJC) {
  29042. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  29043. : CTC_NAME_SIZE - 1;
  29044. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  29045. cn->joiC[sz] = '\0';
  29046. cn->joiCEnc = decoded->subjectJCEnc;
  29047. }
  29048. if (decoded->subjectJS) {
  29049. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  29050. : CTC_NAME_SIZE - 1;
  29051. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  29052. cn->joiSt[sz] = '\0';
  29053. cn->joiStEnc = decoded->subjectJSEnc;
  29054. }
  29055. #endif
  29056. if (decoded->subjectEmail) {
  29057. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  29058. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  29059. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  29060. cn->email[sz] = '\0';
  29061. }
  29062. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  29063. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  29064. if (decoded->subjectN) {
  29065. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  29066. : CTC_NAME_SIZE - 1;
  29067. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  29068. cn->dnName[sz] = '\0';
  29069. cn->dnNameEnc = decoded->subjectNEnc;
  29070. }
  29071. if (decoded->subjectI) {
  29072. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  29073. : CTC_NAME_SIZE - 1;
  29074. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  29075. cn->initials[sz] = '\0';
  29076. cn->initialsEnc = decoded->subjectIEnc;
  29077. }
  29078. if (decoded->subjectGN) {
  29079. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  29080. : CTC_NAME_SIZE - 1;
  29081. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  29082. cn->givenName[sz] = '\0';
  29083. cn->givenNameEnc = decoded->subjectGNEnc;
  29084. }
  29085. if (decoded->subjectDNQ) {
  29086. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  29087. : CTC_NAME_SIZE - 1;
  29088. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  29089. cn->dnQualifier[sz] = '\0';
  29090. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  29091. }
  29092. #endif /* WOLFSSL_CERT_NAME_ALL */
  29093. }
  29094. #ifndef NO_FILESYSTEM
  29095. /* Set cn name from der buffer, return 0 on success */
  29096. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  29097. {
  29098. int ret;
  29099. #ifdef WOLFSSL_SMALL_STACK
  29100. DecodedCert* decoded;
  29101. #else
  29102. DecodedCert decoded[1];
  29103. #endif
  29104. if (derSz < 0)
  29105. return derSz;
  29106. #ifdef WOLFSSL_SMALL_STACK
  29107. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  29108. DYNAMIC_TYPE_TMP_BUFFER);
  29109. if (decoded == NULL)
  29110. return MEMORY_E;
  29111. #endif
  29112. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  29113. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  29114. if (ret < 0) {
  29115. WOLFSSL_MSG("ParseCertRelative error");
  29116. }
  29117. else {
  29118. SetNameFromDcert(cn, decoded);
  29119. }
  29120. FreeDecodedCert(decoded);
  29121. #ifdef WOLFSSL_SMALL_STACK
  29122. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  29123. #endif
  29124. return ret < 0 ? ret : 0;
  29125. }
  29126. /* Set cert issuer from issuerFile in PEM */
  29127. WOLFSSL_ABI
  29128. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  29129. {
  29130. int ret;
  29131. DerBuffer* der = NULL;
  29132. if (cert == NULL || issuerFile == NULL)
  29133. return BAD_FUNC_ARG;
  29134. ret = wc_PemCertToDer_ex(issuerFile, &der);
  29135. if (ret == 0) {
  29136. cert->selfSigned = 0;
  29137. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  29138. INVALID_DEVID);
  29139. FreeDer(&der);
  29140. }
  29141. return ret;
  29142. }
  29143. /* Set cert subject from subjectFile in PEM */
  29144. WOLFSSL_ABI
  29145. int wc_SetSubject(Cert* cert, const char* subjectFile)
  29146. {
  29147. int ret;
  29148. DerBuffer* der = NULL;
  29149. if (cert == NULL || subjectFile == NULL)
  29150. return BAD_FUNC_ARG;
  29151. ret = wc_PemCertToDer_ex(subjectFile, &der);
  29152. if (ret == 0) {
  29153. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  29154. INVALID_DEVID);
  29155. FreeDer(&der);
  29156. }
  29157. return ret;
  29158. }
  29159. #ifdef WOLFSSL_ALT_NAMES
  29160. /* Set alt names from file in PEM */
  29161. WOLFSSL_ABI
  29162. int wc_SetAltNames(Cert* cert, const char* file)
  29163. {
  29164. int ret;
  29165. DerBuffer* der = NULL;
  29166. if (cert == NULL) {
  29167. return BAD_FUNC_ARG;
  29168. }
  29169. ret = wc_PemCertToDer_ex(file, &der);
  29170. if (ret == 0) {
  29171. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  29172. INVALID_DEVID);
  29173. FreeDer(&der);
  29174. }
  29175. return ret;
  29176. }
  29177. #endif /* WOLFSSL_ALT_NAMES */
  29178. #endif /* !NO_FILESYSTEM */
  29179. /* Set cert issuer from DER buffer */
  29180. WOLFSSL_ABI
  29181. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  29182. {
  29183. int ret = 0;
  29184. if (cert == NULL) {
  29185. ret = BAD_FUNC_ARG;
  29186. }
  29187. else {
  29188. cert->selfSigned = 0;
  29189. /* Check if decodedCert is cached */
  29190. if (cert->der != der) {
  29191. /* Allocate cache for the decoded cert */
  29192. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  29193. }
  29194. if (ret >= 0) {
  29195. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  29196. #ifndef WOLFSSL_CERT_GEN_CACHE
  29197. wc_SetCert_Free(cert);
  29198. #endif
  29199. }
  29200. }
  29201. return ret;
  29202. }
  29203. /* Set cert subject from DER buffer */
  29204. WOLFSSL_ABI
  29205. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  29206. {
  29207. int ret = 0;
  29208. if (cert == NULL) {
  29209. ret = BAD_FUNC_ARG;
  29210. }
  29211. else {
  29212. /* Check if decodedCert is cached */
  29213. if (cert->der != der) {
  29214. /* Allocate cache for the decoded cert */
  29215. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  29216. }
  29217. if (ret >= 0) {
  29218. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  29219. #ifndef WOLFSSL_CERT_GEN_CACHE
  29220. wc_SetCert_Free(cert);
  29221. #endif
  29222. }
  29223. }
  29224. return ret;
  29225. }
  29226. #ifdef WOLFSSL_CERT_EXT
  29227. /* Set cert raw subject from DER buffer */
  29228. WOLFSSL_ABI
  29229. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  29230. {
  29231. int ret = 0;
  29232. if (cert == NULL) {
  29233. ret = BAD_FUNC_ARG;
  29234. }
  29235. else {
  29236. /* Check if decodedCert is cached */
  29237. if (cert->der != der) {
  29238. /* Allocate cache for the decoded cert */
  29239. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  29240. }
  29241. if (ret >= 0) {
  29242. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  29243. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  29244. (int)sizeof(CertName))) {
  29245. XMEMCPY(cert->sbjRaw,
  29246. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  29247. (size_t)((DecodedCert*)cert->decodedCert)->
  29248. subjectRawLen);
  29249. }
  29250. #ifndef WOLFSSL_CERT_GEN_CACHE
  29251. wc_SetCert_Free(cert);
  29252. #endif
  29253. }
  29254. }
  29255. return ret;
  29256. }
  29257. /* Set cert raw issuer from DER buffer */
  29258. WOLFSSL_ABI
  29259. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  29260. {
  29261. int ret = 0;
  29262. if (cert == NULL) {
  29263. ret = BAD_FUNC_ARG;
  29264. }
  29265. else {
  29266. /* Check if decodedCert is cached */
  29267. if (cert->der != der) {
  29268. /* Allocate cache for the decoded cert */
  29269. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  29270. }
  29271. if (ret >= 0) {
  29272. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  29273. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  29274. (int)sizeof(CertName))) {
  29275. /* Copy the subject to the issuer field */
  29276. XMEMCPY(cert->issRaw,
  29277. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  29278. (size_t)((DecodedCert*)cert->decodedCert)->
  29279. subjectRawLen);
  29280. }
  29281. #ifndef WOLFSSL_CERT_GEN_CACHE
  29282. wc_SetCert_Free(cert);
  29283. #endif
  29284. }
  29285. }
  29286. return ret;
  29287. }
  29288. #endif
  29289. #ifdef WOLFSSL_ALT_NAMES
  29290. /* Set cert alt names from DER buffer */
  29291. WOLFSSL_ABI
  29292. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  29293. {
  29294. int ret = 0;
  29295. if (cert == NULL) {
  29296. ret = BAD_FUNC_ARG;
  29297. }
  29298. else {
  29299. /* Check if decodedCert is cached */
  29300. if (cert->der != der) {
  29301. /* Allocate cache for the decoded cert */
  29302. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  29303. }
  29304. if (ret >= 0) {
  29305. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  29306. #ifndef WOLFSSL_CERT_GEN_CACHE
  29307. wc_SetCert_Free(cert);
  29308. #endif
  29309. }
  29310. }
  29311. return(ret);
  29312. }
  29313. /* Set cert dates from DER buffer */
  29314. WOLFSSL_ABI
  29315. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  29316. {
  29317. int ret = 0;
  29318. if (cert == NULL) {
  29319. ret = BAD_FUNC_ARG;
  29320. }
  29321. else {
  29322. /* Check if decodedCert is cached */
  29323. if (cert->der != der) {
  29324. /* Allocate cache for the decoded cert */
  29325. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  29326. }
  29327. if (ret >= 0) {
  29328. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  29329. #ifndef WOLFSSL_CERT_GEN_CACHE
  29330. wc_SetCert_Free(cert);
  29331. #endif
  29332. }
  29333. }
  29334. return(ret);
  29335. }
  29336. #endif /* WOLFSSL_ALT_NAMES */
  29337. #endif /* WOLFSSL_CERT_GEN */
  29338. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  29339. || defined(OPENSSL_EXTRA)
  29340. /* Encode OID string representation to ITU-T X.690 format */
  29341. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  29342. {
  29343. word32 idx = 0, nb_val;
  29344. char *token, *str, *ptr;
  29345. word32 len;
  29346. (void)heap;
  29347. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  29348. return BAD_FUNC_ARG;
  29349. /* duplicate string (including terminator) */
  29350. len = (word32)XSTRLEN(in);
  29351. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  29352. if (str == NULL)
  29353. return MEMORY_E;
  29354. XMEMCPY(str, in, len+1);
  29355. nb_val = 0;
  29356. /* parse value, and set corresponding Policy OID value */
  29357. token = XSTRTOK(str, ".", &ptr);
  29358. while (token != NULL)
  29359. {
  29360. word32 val = (word32)XATOI(token);
  29361. if (nb_val == 0) {
  29362. if (val > 2) {
  29363. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  29364. return ASN_OBJECT_ID_E;
  29365. }
  29366. out[idx] = (byte)(40 * val);
  29367. }
  29368. else if (nb_val == 1) {
  29369. if (val > 127) {
  29370. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  29371. return ASN_OBJECT_ID_E;
  29372. }
  29373. if (idx > *outSz) {
  29374. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  29375. return BUFFER_E;
  29376. }
  29377. out[idx++] += (byte)val;
  29378. }
  29379. else {
  29380. word32 tb = 0;
  29381. int i = 0;
  29382. byte oid[MAX_OID_SZ];
  29383. while (val >= 128) {
  29384. word32 x = val % 128;
  29385. val /= 128;
  29386. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  29387. }
  29388. if ((idx+(word32)i) >= *outSz) {
  29389. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  29390. return BUFFER_E;
  29391. }
  29392. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  29393. /* push value in the right order */
  29394. while (i >= 0)
  29395. out[idx++] = oid[i--];
  29396. }
  29397. token = XSTRTOK(NULL, ".", &ptr);
  29398. nb_val++;
  29399. }
  29400. *outSz = idx;
  29401. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  29402. return 0;
  29403. }
  29404. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  29405. #endif /* !NO_CERTS */
  29406. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  29407. /* Helper function for wolfSSL_i2d_DHparams */
  29408. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  29409. {
  29410. #ifndef WOLFSSL_ASN_TEMPLATE
  29411. word32 idx = 0;
  29412. word32 total;
  29413. WOLFSSL_ENTER("StoreDHparams");
  29414. if (out == NULL) {
  29415. WOLFSSL_MSG("Null buffer error");
  29416. return BUFFER_E;
  29417. }
  29418. /* determine size */
  29419. /* integer - g */
  29420. idx = SetASNIntMP(g, -1, NULL);
  29421. /* integer - p */
  29422. idx += SetASNIntMP(p, -1, NULL);
  29423. total = idx;
  29424. /* sequence */
  29425. idx += SetSequence(idx, NULL);
  29426. /* make sure output fits in buffer */
  29427. if (idx > *outLen) {
  29428. return BUFFER_E;
  29429. }
  29430. /* write DH parameters */
  29431. /* sequence - for P and G only */
  29432. idx = SetSequence(total, out);
  29433. /* integer - p */
  29434. idx += SetASNIntMP(p, -1, out + idx);
  29435. /* integer - g */
  29436. idx += SetASNIntMP(g, -1, out + idx);
  29437. *outLen = idx;
  29438. return 0;
  29439. #else
  29440. ASNSetData dataASN[dhParamASN_Length];
  29441. int ret = 0;
  29442. int sz = 0;
  29443. WOLFSSL_ENTER("StoreDHparams");
  29444. if (out == NULL) {
  29445. ret = BUFFER_E;
  29446. }
  29447. if (ret == 0) {
  29448. XMEMSET(dataASN, 0, sizeof(dataASN));
  29449. /* Set mp_int containing p and g. */
  29450. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  29451. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  29452. /* privateValueLength not encoded. */
  29453. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  29454. /* Calculate the size of the DH parameters. */
  29455. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  29456. }
  29457. /* Check buffer is big enough for encoding. */
  29458. if ((ret == 0) && ((int)*outLen < sz)) {
  29459. ret = BUFFER_E;
  29460. }
  29461. if (ret == 0) {
  29462. /* Encode the DH parameters into buffer. */
  29463. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  29464. /* Set the actual encoding size. */
  29465. *outLen = (word32)sz;
  29466. }
  29467. return ret;
  29468. #endif /* WOLFSSL_ASN_TEMPLATE */
  29469. }
  29470. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  29471. #if defined(HAVE_ECC) || !defined(NO_DSA)
  29472. #ifdef WOLFSSL_ASN_TEMPLATE
  29473. /* ASN.1 template for DSA signature.
  29474. * RFC 5912, 6 - DSA-Sig-Value
  29475. */
  29476. static const ASNItem dsaSigASN[] = {
  29477. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29478. /* r */
  29479. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  29480. /* s */
  29481. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  29482. };
  29483. enum {
  29484. DSASIGASN_IDX_SEQ = 0,
  29485. DSASIGASN_IDX_R,
  29486. DSASIGASN_IDX_S
  29487. };
  29488. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  29489. #endif
  29490. /* Der Encode r & s ints into out, outLen is (in/out) size */
  29491. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  29492. {
  29493. #ifndef WOLFSSL_ASN_TEMPLATE
  29494. word32 idx = 0;
  29495. int rSz; /* encoding size */
  29496. int sSz;
  29497. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  29498. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  29499. int rLeadingZero = mp_leading_bit(r);
  29500. int sLeadingZero = mp_leading_bit(s);
  29501. int rLen = mp_unsigned_bin_size(r); /* big int size */
  29502. int sLen = mp_unsigned_bin_size(s);
  29503. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  29504. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  29505. return BUFFER_E;
  29506. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  29507. headerSz), out);
  29508. /* store r */
  29509. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  29510. if (rSz < 0)
  29511. return rSz;
  29512. idx += (word32)rSz;
  29513. /* store s */
  29514. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  29515. if (sSz < 0)
  29516. return sSz;
  29517. idx += (word32)sSz;
  29518. *outLen = idx;
  29519. return 0;
  29520. #else
  29521. ASNSetData dataASN[dsaSigASN_Length];
  29522. int ret;
  29523. int sz;
  29524. /* Clear dynamic data and set mp_ints r and s */
  29525. XMEMSET(dataASN, 0, sizeof(dataASN));
  29526. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  29527. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  29528. /* Calculate size of encoding. */
  29529. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  29530. /* Check buffer is big enough for encoding. */
  29531. if ((ret == 0) && ((int)*outLen < sz)) {
  29532. ret = BUFFER_E;
  29533. }
  29534. if (ret == 0) {
  29535. /* Encode DSA signature into buffer. */
  29536. ret = SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  29537. if (ret >= 0) {
  29538. if (ret == sz) {
  29539. /* Set the actual encoding size. */
  29540. *outLen = (word32)sz;
  29541. ret = 0;
  29542. } else {
  29543. ret = BAD_STATE_E;
  29544. }
  29545. }
  29546. }
  29547. return ret;
  29548. #endif /* WOLFSSL_ASN_TEMPLATE */
  29549. }
  29550. #ifndef WOLFSSL_ASN_TEMPLATE
  29551. /* determine if leading bit is set */
  29552. static word32 is_leading_bit_set(const byte* input, word32 sz)
  29553. {
  29554. byte c = 0;
  29555. if (sz > 0)
  29556. c = input[0];
  29557. return (c & 0x80) != 0;
  29558. }
  29559. static word32 trim_leading_zeros(const byte** input, word32 sz)
  29560. {
  29561. int i;
  29562. word32 leadingZeroCount = 0;
  29563. const byte* tmp = *input;
  29564. for (i=0; i<(int)sz; i++) {
  29565. if (tmp[i] != 0)
  29566. break;
  29567. leadingZeroCount++;
  29568. }
  29569. /* catch all zero case */
  29570. if (sz > 0 && leadingZeroCount == sz) {
  29571. leadingZeroCount--;
  29572. }
  29573. *input += leadingZeroCount;
  29574. sz -= leadingZeroCount;
  29575. return sz;
  29576. }
  29577. #endif
  29578. /* Der Encode r & s ints into out, outLen is (in/out) size */
  29579. /* All input/outputs are assumed to be big-endian */
  29580. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  29581. const byte* s, word32 sLen)
  29582. {
  29583. #ifndef WOLFSSL_ASN_TEMPLATE
  29584. int ret;
  29585. word32 idx;
  29586. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  29587. word32 rAddLeadZero, sAddLeadZero;
  29588. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  29589. return BAD_FUNC_ARG;
  29590. /* Trim leading zeros */
  29591. rLen = trim_leading_zeros(&r, rLen);
  29592. sLen = trim_leading_zeros(&s, sLen);
  29593. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  29594. /* Add leading zero if MSB is set */
  29595. rAddLeadZero = is_leading_bit_set(r, rLen);
  29596. sAddLeadZero = is_leading_bit_set(s, sLen);
  29597. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  29598. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  29599. return BUFFER_E;
  29600. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  29601. /* store r */
  29602. ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  29603. if (ret < 0)
  29604. return ret;
  29605. idx += (word32)ret;
  29606. XMEMCPY(&out[idx], r, rLen);
  29607. idx += rLen;
  29608. /* store s */
  29609. ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  29610. if (ret < 0)
  29611. return ret;
  29612. idx += (word32)ret;
  29613. XMEMCPY(&out[idx], s, sLen);
  29614. idx += sLen;
  29615. *outLen = idx;
  29616. return 0;
  29617. #else
  29618. ASNSetData dataASN[dsaSigASN_Length];
  29619. int ret;
  29620. int sz;
  29621. /* Clear dynamic data and set buffers for r and s */
  29622. XMEMSET(dataASN, 0, sizeof(dataASN));
  29623. while ((rLen > 1) && (r[0] == 0)) {
  29624. rLen--;
  29625. r++;
  29626. }
  29627. while ((sLen > 1) && (s[0] == 0)) {
  29628. sLen--;
  29629. s++;
  29630. }
  29631. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  29632. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  29633. /* Calculate size of encoding. */
  29634. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  29635. /* Check buffer is big enough for encoding. */
  29636. if ((ret == 0) && ((int)*outLen < sz)) {
  29637. ret = BUFFER_E;
  29638. }
  29639. if (ret == 0) {
  29640. /* Encode DSA signature into buffer. */
  29641. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  29642. /* Set the actual encoding size. */
  29643. *outLen = (word32)sz;
  29644. }
  29645. return ret;
  29646. #endif /* WOLFSSL_ASN_TEMPLATE */
  29647. }
  29648. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  29649. /* All input/outputs are assumed to be big-endian */
  29650. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  29651. byte* s, word32* sLen)
  29652. {
  29653. #ifndef WOLFSSL_ASN_TEMPLATE
  29654. int ret;
  29655. word32 idx = 0;
  29656. int len = 0;
  29657. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  29658. return ASN_ECC_KEY_E;
  29659. }
  29660. #ifndef NO_STRICT_ECDSA_LEN
  29661. /* enable strict length checking for signature */
  29662. if (sigLen != idx + (word32)len) {
  29663. return ASN_ECC_KEY_E;
  29664. }
  29665. #else
  29666. /* allow extra signature bytes at end */
  29667. if ((word32)len > (sigLen - idx)) {
  29668. return ASN_ECC_KEY_E;
  29669. }
  29670. #endif
  29671. ret = GetASNInt(sig, &idx, &len, sigLen);
  29672. if (ret != 0)
  29673. return ret;
  29674. if (rLen)
  29675. *rLen = (word32)len;
  29676. if (r)
  29677. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  29678. idx += (word32)len;
  29679. ret = GetASNInt(sig, &idx, &len, sigLen);
  29680. if (ret != 0)
  29681. return ret;
  29682. if (sLen)
  29683. *sLen = (word32)len;
  29684. if (s)
  29685. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  29686. #ifndef NO_STRICT_ECDSA_LEN
  29687. /* sanity check that the index has been advanced all the way to the end of
  29688. * the buffer */
  29689. if (idx + (word32)len != sigLen) {
  29690. ret = ASN_ECC_KEY_E;
  29691. }
  29692. #endif
  29693. return ret;
  29694. #else
  29695. ASNGetData dataASN[dsaSigASN_Length];
  29696. word32 idx = 0;
  29697. /* Clear dynamic data and set buffers to put r and s into. */
  29698. XMEMSET(dataASN, 0, sizeof(dataASN));
  29699. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  29700. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  29701. /* Decode the DSA signature. */
  29702. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  29703. sigLen);
  29704. #endif /* WOLFSSL_ASN_TEMPLATE */
  29705. }
  29706. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  29707. {
  29708. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  29709. }
  29710. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  29711. int init)
  29712. {
  29713. #ifndef WOLFSSL_ASN_TEMPLATE
  29714. word32 idx = 0;
  29715. int len = 0;
  29716. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  29717. return ASN_ECC_KEY_E;
  29718. }
  29719. #ifndef NO_STRICT_ECDSA_LEN
  29720. /* enable strict length checking for signature */
  29721. if (sigLen != idx + (word32)len) {
  29722. return ASN_ECC_KEY_E;
  29723. }
  29724. #else
  29725. /* allow extra signature bytes at end */
  29726. if ((word32)len > (sigLen - idx)) {
  29727. return ASN_ECC_KEY_E;
  29728. }
  29729. #endif
  29730. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  29731. return ASN_ECC_KEY_E;
  29732. }
  29733. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  29734. mp_clear(r);
  29735. return ASN_ECC_KEY_E;
  29736. }
  29737. #ifndef NO_STRICT_ECDSA_LEN
  29738. /* sanity check that the index has been advanced all the way to the end of
  29739. * the buffer */
  29740. if (idx != sigLen) {
  29741. mp_clear(r);
  29742. mp_clear(s);
  29743. return ASN_ECC_KEY_E;
  29744. }
  29745. #endif
  29746. return 0;
  29747. #else
  29748. ASNGetData dataASN[dsaSigASN_Length];
  29749. word32 idx = 0;
  29750. int ret;
  29751. /* Clear dynamic data and set mp_ints to put r and s into. */
  29752. XMEMSET(dataASN, 0, sizeof(dataASN));
  29753. if (init) {
  29754. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  29755. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  29756. }
  29757. else {
  29758. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  29759. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  29760. }
  29761. /* Decode the DSA signature. */
  29762. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  29763. sigLen);
  29764. if (ret != 0) {
  29765. ret = ASN_ECC_KEY_E;
  29766. }
  29767. #ifndef NO_STRICT_ECDSA_LEN
  29768. /* sanity check that the index has been advanced all the way to the end of
  29769. * the buffer */
  29770. if ((ret == 0) && (idx != sigLen)) {
  29771. ret = ASN_ECC_KEY_E;
  29772. }
  29773. #endif
  29774. if (ret != 0) {
  29775. mp_clear(r);
  29776. mp_clear(s);
  29777. }
  29778. return ret;
  29779. #endif /* WOLFSSL_ASN_TEMPLATE */
  29780. }
  29781. #endif
  29782. #ifdef WOLFSSL_ASN_TEMPLATE
  29783. #if defined(HAVE_ECC) && defined(WOLFSSL_CUSTOM_CURVES)
  29784. /* Convert data to hex string.
  29785. *
  29786. * Big-endian byte array is converted to big-endian hexadecimal string.
  29787. *
  29788. * @param [in] input Buffer containing data.
  29789. * @param [in] inSz Size of data in buffer.
  29790. * @param [out] out Buffer to hold hex string.
  29791. */
  29792. static void DataToHexString(const byte* input, word32 inSz, char* out)
  29793. {
  29794. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  29795. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  29796. word32 i;
  29797. /* Converting a byte of data at a time to two hex characters. */
  29798. for (i = 0; i < inSz; i++) {
  29799. out[i*2 + 0] = hexChar[input[i] >> 4];
  29800. out[i*2 + 1] = hexChar[input[i] & 0xf];
  29801. }
  29802. /* NUL terminate string. */
  29803. out[i * 2] = '\0';
  29804. }
  29805. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29806. /* Convert data to hex string and place in allocated buffer.
  29807. *
  29808. * Big-endian byte array is converted to big-endian hexadecimal string.
  29809. *
  29810. * @param [in] input Buffer containing data.
  29811. * @param [in] inSz Size of data in buffer.
  29812. * @param [out] out Allocated buffer holding hex string.
  29813. * @param [in] heap Dynamic memory allocation hint.
  29814. * @param [in] heapType Type of heap to use.
  29815. * @return 0 on success.
  29816. * @return MEMORY_E when dynamic memory allocation fails.
  29817. */
  29818. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  29819. void* heap, int heapType)
  29820. {
  29821. int ret = 0;
  29822. char* str;
  29823. /* Allocate for 2 string characters ber byte plus NUL. */
  29824. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  29825. if (str == NULL) {
  29826. ret = MEMORY_E;
  29827. }
  29828. else {
  29829. /* Convert to hex string. */
  29830. DataToHexString(input, inSz, str);
  29831. *out = str;
  29832. }
  29833. (void)heap;
  29834. (void)heapType;
  29835. return ret;
  29836. }
  29837. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  29838. /* ASN.1 template for SpecifiedECDomain.
  29839. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  29840. * NOTE: characteristic-two-field not supported. */
  29841. static const ASNItem eccSpecifiedASN[] = {
  29842. /* version */
  29843. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  29844. /* fieldID */
  29845. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29846. /* prime-field or characteristic-two-field */
  29847. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  29848. /* Prime-p */
  29849. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  29850. /* fieldID */
  29851. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29852. /* a */
  29853. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  29854. /* b */
  29855. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  29856. /* seed */
  29857. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  29858. /* base */
  29859. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  29860. /* order */
  29861. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  29862. /* cofactor */
  29863. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  29864. /* hash */
  29865. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  29866. };
  29867. enum {
  29868. ECCSPECIFIEDASN_IDX_VER = 0,
  29869. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  29870. ECCSPECIFIEDASN_IDX_PRIME_OID,
  29871. ECCSPECIFIEDASN_IDX_PRIME_P,
  29872. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  29873. ECCSPECIFIEDASN_IDX_PARAM_A,
  29874. ECCSPECIFIEDASN_IDX_PARAM_B,
  29875. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  29876. ECCSPECIFIEDASN_IDX_BASE,
  29877. ECCSPECIFIEDASN_IDX_ORDER,
  29878. ECCSPECIFIEDASN_IDX_COFACTOR,
  29879. ECCSPECIFIEDASN_IDX_HASH_SEQ
  29880. };
  29881. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  29882. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  29883. /* OID indicating the prime field is explicitly defined. */
  29884. static const byte primeFieldOID[] = {
  29885. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  29886. };
  29887. static const char ecSetCustomName[] = "Custom";
  29888. /* Explicit EC parameter values. */
  29889. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  29890. ecc_key* key, void* heap, int* curveSz)
  29891. {
  29892. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  29893. int ret = 0;
  29894. ecc_set_type* curve = NULL;
  29895. word32 idx = 0;
  29896. byte version = 0;
  29897. byte cofactor = 0;
  29898. const byte *base = NULL;
  29899. word32 baseLen = 0;
  29900. /* Allocate a new parameter set. */
  29901. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), heap,
  29902. DYNAMIC_TYPE_ECC_BUFFER);
  29903. if (curve == NULL) {
  29904. ret = MEMORY_E;
  29905. }
  29906. else {
  29907. /* Clear out parameters and set fields to indicate it is custom. */
  29908. XMEMSET(curve, 0, sizeof(*curve));
  29909. }
  29910. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, heap);
  29911. if (ret == 0) {
  29912. /* Set name to be: "Custom" */
  29913. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29914. curve->name = ecSetCustomName;
  29915. #else
  29916. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  29917. #endif
  29918. curve->id = ECC_CURVE_CUSTOM;
  29919. /* Get version, must have prime field OID and get co-factor. */
  29920. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  29921. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  29922. primeFieldOID, sizeof(primeFieldOID));
  29923. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  29924. /* Decode the explicit parameters. */
  29925. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  29926. input, &idx, inSz);
  29927. }
  29928. /* Version must be 1 or 2 for supporting explicit parameters. */
  29929. if ((ret == 0) && (version < 1 || version > 3)) {
  29930. ret = ASN_PARSE_E;
  29931. }
  29932. #ifndef WOLFSSL_NO_ASN_STRICT
  29933. /* Only version 2 and above can have a seed. */
  29934. if (ret == 0) {
  29935. if ((dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  29936. (version < 2)) {
  29937. ret = ASN_PARSE_E;
  29938. }
  29939. }
  29940. #endif
  29941. /* Only version 2 and above can have a hash algorithm. */
  29942. if (ret == 0) {
  29943. if ((dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  29944. (version < 2)) {
  29945. ret = ASN_PARSE_E;
  29946. }
  29947. }
  29948. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  29949. /* Store optional co-factor. */
  29950. curve->cofactor = cofactor;
  29951. }
  29952. if (ret == 0) {
  29953. /* Length of the prime in bytes is the curve size. */
  29954. curve->size =
  29955. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  29956. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  29957. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  29958. &baseLen);
  29959. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  29960. ret = ASN_PARSE_E;
  29961. }
  29962. }
  29963. /* Put the curve parameters into the set.
  29964. * Convert the big-endian number byte array to a big-endian string.
  29965. */
  29966. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29967. /* Allocate buffer to put hex strings into. */
  29968. if (ret == 0) {
  29969. /* Base X-ordinate */
  29970. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  29971. (char**)&curve->Gx, heap,
  29972. DYNAMIC_TYPE_ECC_BUFFER);
  29973. }
  29974. if (ret == 0) {
  29975. /* Base Y-ordinate */
  29976. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  29977. (char**)&curve->Gy, heap,
  29978. DYNAMIC_TYPE_ECC_BUFFER);
  29979. }
  29980. if (ret == 0) {
  29981. /* Prime */
  29982. ret = DataToHexStringAlloc(
  29983. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  29984. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  29985. (char**)&curve->prime, heap, DYNAMIC_TYPE_ECC_BUFFER);
  29986. }
  29987. if (ret == 0) {
  29988. /* Parameter A */
  29989. ret = DataToHexStringAlloc(
  29990. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  29991. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  29992. (char**)&curve->Af, heap, DYNAMIC_TYPE_ECC_BUFFER);
  29993. }
  29994. if (ret == 0) {
  29995. /* Parameter B */
  29996. ret = DataToHexStringAlloc(
  29997. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  29998. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  29999. (char**)&curve->Bf, heap, DYNAMIC_TYPE_ECC_BUFFER);
  30000. }
  30001. if (ret == 0) {
  30002. /* Order of curve */
  30003. ret = DataToHexStringAlloc(
  30004. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  30005. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  30006. (char**)&curve->order, heap, DYNAMIC_TYPE_ECC_BUFFER);
  30007. }
  30008. #else
  30009. if (ret == 0) {
  30010. /* Base X-ordinate */
  30011. DataToHexString(base + 1, curve->size, curve->Gx);
  30012. /* Base Y-ordinate */
  30013. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  30014. /* Prime */
  30015. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  30016. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  30017. curve->prime);
  30018. /* Parameter A */
  30019. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  30020. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  30021. curve->Af);
  30022. /* Parameter B */
  30023. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  30024. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  30025. curve->Bf);
  30026. /* Order of curve */
  30027. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  30028. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  30029. curve->order);
  30030. }
  30031. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  30032. if (key) {
  30033. /* Store parameter set in key. */
  30034. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  30035. ret = ASN_PARSE_E;
  30036. }
  30037. if (ret == 0) {
  30038. /* The parameter set was allocated.. */
  30039. key->deallocSet = 1;
  30040. }
  30041. }
  30042. if ((ret == 0) && (curveSz)) {
  30043. *curveSz = curve->size;
  30044. }
  30045. if ((ret != 0) && (curve != NULL)) {
  30046. /* Failed to set parameters so free parameter set. */
  30047. wc_ecc_free_curve(curve, heap);
  30048. }
  30049. FREE_ASNGETDATA(dataASN, heap);
  30050. return ret;
  30051. }
  30052. #endif /* WOLFSSL_CUSTOM_CURVES */
  30053. #endif /* WOLFSSL_ASN_TEMPLATE */
  30054. #ifdef HAVE_ECC
  30055. #ifdef WOLFSSL_ASN_TEMPLATE
  30056. /* ASN.1 template for ECC private key.
  30057. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  30058. */
  30059. static const ASNItem eccKeyASN[] = {
  30060. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30061. /* version */
  30062. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  30063. /* privateKey */
  30064. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  30065. /* parameters */
  30066. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  30067. /* named */
  30068. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  30069. /* specified */
  30070. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  30071. /* publicKey */
  30072. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  30073. /* Uncompressed point - X9.62. */
  30074. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  30075. };
  30076. enum {
  30077. ECCKEYASN_IDX_SEQ = 0,
  30078. ECCKEYASN_IDX_VER,
  30079. ECCKEYASN_IDX_PKEY,
  30080. ECCKEYASN_IDX_PARAMS,
  30081. ECCKEYASN_IDX_CURVEID,
  30082. ECCKEYASN_IDX_CURVEPARAMS,
  30083. ECCKEYASN_IDX_PUBKEY,
  30084. ECCKEYASN_IDX_PUBKEY_VAL
  30085. };
  30086. /* Number of items in ASN.1 template for ECC private key. */
  30087. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  30088. #endif
  30089. WOLFSSL_ABI
  30090. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  30091. word32 inSz)
  30092. {
  30093. #ifndef WOLFSSL_ASN_TEMPLATE
  30094. word32 oidSum;
  30095. int version, length;
  30096. int privSz, pubSz = 0;
  30097. byte b;
  30098. int ret = 0;
  30099. int curve_id = ECC_CURVE_DEF;
  30100. #ifdef WOLFSSL_SMALL_STACK
  30101. byte* priv;
  30102. byte* pub = NULL;
  30103. #else
  30104. byte priv[ECC_MAXSIZE+1];
  30105. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  30106. #endif
  30107. word32 algId = 0;
  30108. byte* pubData = NULL;
  30109. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  30110. return BAD_FUNC_ARG;
  30111. /* if has pkcs8 header skip it */
  30112. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  30113. /* ignore error, did not have pkcs8 header */
  30114. }
  30115. else {
  30116. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  30117. }
  30118. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30119. return ASN_PARSE_E;
  30120. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  30121. return ASN_PARSE_E;
  30122. if (*inOutIdx >= inSz)
  30123. return ASN_PARSE_E;
  30124. b = input[*inOutIdx];
  30125. *inOutIdx += 1;
  30126. /* priv type */
  30127. if (b != 4 && b != 6 && b != 7)
  30128. return ASN_PARSE_E;
  30129. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  30130. return ASN_PARSE_E;
  30131. privSz = length;
  30132. if (privSz > ECC_MAXSIZE)
  30133. return BUFFER_E;
  30134. #ifdef WOLFSSL_SMALL_STACK
  30135. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30136. if (priv == NULL)
  30137. return MEMORY_E;
  30138. #endif
  30139. /* priv key */
  30140. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  30141. *inOutIdx += (word32)length;
  30142. if ((*inOutIdx + 1) < inSz) {
  30143. /* prefix 0, may have */
  30144. b = input[*inOutIdx];
  30145. if (b == ECC_PREFIX_0) {
  30146. *inOutIdx += 1;
  30147. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  30148. ret = ASN_PARSE_E;
  30149. else {
  30150. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  30151. inSz);
  30152. if (ret == 0) {
  30153. if ((ret = CheckCurve(oidSum)) < 0)
  30154. ret = ECC_CURVE_OID_E;
  30155. else {
  30156. curve_id = ret;
  30157. ret = 0;
  30158. }
  30159. }
  30160. }
  30161. }
  30162. }
  30163. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  30164. /* prefix 1 */
  30165. b = input[*inOutIdx];
  30166. *inOutIdx += 1;
  30167. if (b != ECC_PREFIX_1) {
  30168. ret = ASN_ECC_KEY_E;
  30169. }
  30170. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  30171. ret = ASN_PARSE_E;
  30172. }
  30173. else {
  30174. /* key header */
  30175. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  30176. if (ret == 0) {
  30177. /* pub key */
  30178. pubSz = length;
  30179. if (pubSz > 2*(ECC_MAXSIZE+1))
  30180. ret = BUFFER_E;
  30181. else {
  30182. #ifdef WOLFSSL_SMALL_STACK
  30183. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30184. if (pub == NULL)
  30185. ret = MEMORY_E;
  30186. else
  30187. #endif
  30188. {
  30189. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  30190. *inOutIdx += (word32)length;
  30191. pubData = pub;
  30192. }
  30193. }
  30194. }
  30195. }
  30196. }
  30197. if (ret == 0) {
  30198. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  30199. (word32)pubSz, key, curve_id);
  30200. }
  30201. #ifdef WOLFSSL_SMALL_STACK
  30202. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30203. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30204. #endif
  30205. return ret;
  30206. #else
  30207. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  30208. byte version = 0;
  30209. int ret = 0;
  30210. int curve_id = ECC_CURVE_DEF;
  30211. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  30212. word32 algId = 0;
  30213. #endif
  30214. /* Validate parameters. */
  30215. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  30216. ret = BAD_FUNC_ARG;
  30217. }
  30218. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  30219. /* if has pkcs8 header skip it */
  30220. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  30221. /* ignore error, did not have pkcs8 header */
  30222. }
  30223. else {
  30224. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  30225. }
  30226. #endif
  30227. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  30228. if (ret == 0) {
  30229. /* Get the version and set the expected OID type. */
  30230. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  30231. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  30232. /* Decode the private ECC key. */
  30233. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  30234. inOutIdx, inSz);
  30235. }
  30236. /* Only version 1 supported. */
  30237. if (ret == 0) {
  30238. if (version != 1) {
  30239. ret = ASN_PARSE_E;
  30240. }
  30241. }
  30242. /* Curve Parameters are optional. */
  30243. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  30244. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  30245. /* Named curve - check and get id. */
  30246. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  30247. if (curve_id < 0) {
  30248. ret = ECC_CURVE_OID_E;
  30249. }
  30250. }
  30251. else {
  30252. #ifdef WOLFSSL_CUSTOM_CURVES
  30253. /* Parse explicit parameters. */
  30254. ret = EccSpecifiedECDomainDecode(
  30255. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  30256. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key,
  30257. key->heap, NULL);
  30258. #else
  30259. /* Explicit parameters not supported in build configuration. */
  30260. ret = ASN_PARSE_E;
  30261. #endif
  30262. }
  30263. }
  30264. if (ret == 0) {
  30265. /* Import private key value and public point (may be NULL). */
  30266. ret = wc_ecc_import_private_key_ex(
  30267. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  30268. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  30269. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  30270. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  30271. key, curve_id);
  30272. }
  30273. FREE_ASNGETDATA(dataASN, key->heap);
  30274. return ret;
  30275. #endif
  30276. }
  30277. #ifdef WOLFSSL_CUSTOM_CURVES
  30278. #ifndef WOLFSSL_ASN_TEMPLATE
  30279. /* returns 0 on success */
  30280. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  30281. word32 inSz, void* heap, int heapType)
  30282. {
  30283. int len;
  30284. int i;
  30285. char* str;
  30286. word32 localIdx;
  30287. byte tag;
  30288. if (*inOutIdx >= inSz) {
  30289. return BUFFER_E;
  30290. }
  30291. localIdx = *inOutIdx;
  30292. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  30293. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  30294. return ASN_PARSE_E;
  30295. }
  30296. else {
  30297. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  30298. return ASN_PARSE_E;
  30299. }
  30300. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  30301. if (str == NULL) {
  30302. return MEMORY_E;
  30303. }
  30304. for (i=0; i<len; i++)
  30305. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  30306. str[len*2] = '\0';
  30307. *inOutIdx += (word32)len;
  30308. *out = str;
  30309. (void)heap;
  30310. (void)heapType;
  30311. return 0;
  30312. }
  30313. static int EccKeyParamCopy(char** dst, char* src, void* heap)
  30314. {
  30315. int ret = 0;
  30316. #ifdef WOLFSSL_ECC_CURVE_STATIC
  30317. word32 length;
  30318. #endif
  30319. if (dst == NULL || src == NULL)
  30320. return BAD_FUNC_ARG;
  30321. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30322. *dst = src;
  30323. #else
  30324. length = (int)XSTRLEN(src) + 1;
  30325. if (length > MAX_ECC_STRING) {
  30326. WOLFSSL_MSG("ECC Param too large for buffer");
  30327. ret = BUFFER_E;
  30328. }
  30329. else {
  30330. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  30331. }
  30332. XFREE(src, heap, DYNAMIC_TYPE_ECC_BUFFER);
  30333. #endif
  30334. (void)heap;
  30335. return ret;
  30336. }
  30337. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30338. #endif /* WOLFSSL_CUSTOM_CURVES */
  30339. WOLFSSL_ABI
  30340. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  30341. ecc_key* key, word32 inSz)
  30342. {
  30343. #ifndef WOLFSSL_ASN_TEMPLATE
  30344. int ret;
  30345. int version, length;
  30346. int curve_id = ECC_CURVE_DEF;
  30347. word32 oidSum, localIdx;
  30348. byte tag, isPrivFormat = 0;
  30349. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  30350. return BAD_FUNC_ARG;
  30351. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30352. return ASN_PARSE_E;
  30353. /* Check if ECC private key is being used and skip private portion */
  30354. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  30355. isPrivFormat = 1;
  30356. /* Type private key */
  30357. if (*inOutIdx >= inSz)
  30358. return ASN_PARSE_E;
  30359. tag = input[*inOutIdx];
  30360. *inOutIdx += 1;
  30361. if (tag != 4 && tag != 6 && tag != 7)
  30362. return ASN_PARSE_E;
  30363. /* Skip Private Key */
  30364. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  30365. return ASN_PARSE_E;
  30366. if (length > ECC_MAXSIZE)
  30367. return BUFFER_E;
  30368. *inOutIdx += (word32)length;
  30369. /* Private Curve Header */
  30370. if (*inOutIdx >= inSz)
  30371. return ASN_PARSE_E;
  30372. tag = input[*inOutIdx];
  30373. *inOutIdx += 1;
  30374. if (tag != ECC_PREFIX_0)
  30375. return ASN_ECC_KEY_E;
  30376. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  30377. return ASN_PARSE_E;
  30378. }
  30379. /* Standard ECC public key */
  30380. else {
  30381. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30382. return ASN_PARSE_E;
  30383. ret = SkipObjectId(input, inOutIdx, inSz);
  30384. if (ret != 0)
  30385. return ret;
  30386. }
  30387. if (*inOutIdx >= inSz) {
  30388. return BUFFER_E;
  30389. }
  30390. localIdx = *inOutIdx;
  30391. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  30392. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  30393. #ifdef WOLFSSL_CUSTOM_CURVES
  30394. ecc_set_type* curve;
  30395. int len;
  30396. char* point = NULL;
  30397. ret = 0;
  30398. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  30399. DYNAMIC_TYPE_ECC_BUFFER);
  30400. if (curve == NULL)
  30401. ret = MEMORY_E;
  30402. if (ret == 0) {
  30403. static const char customName[] = "Custom";
  30404. XMEMSET(curve, 0, sizeof(*curve));
  30405. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30406. curve->name = customName;
  30407. #else
  30408. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  30409. #endif
  30410. curve->id = ECC_CURVE_CUSTOM;
  30411. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30412. ret = ASN_PARSE_E;
  30413. }
  30414. if (ret == 0) {
  30415. GetInteger7Bit(input, inOutIdx, inSz);
  30416. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30417. ret = ASN_PARSE_E;
  30418. }
  30419. if (ret == 0) {
  30420. char* p = NULL;
  30421. SkipObjectId(input, inOutIdx, inSz);
  30422. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  30423. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30424. if (ret == 0) {
  30425. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30426. ret = EccKeyParamCopy((char**)&curve->prime, p, key->heap);
  30427. #else
  30428. const char *_tmp_ptr = &curve->prime[0];
  30429. ret = EccKeyParamCopy((char**)&_tmp_ptr, p, key->heap);
  30430. #endif
  30431. }
  30432. }
  30433. if (ret == 0) {
  30434. curve->size = (int)XSTRLEN(curve->prime) / 2;
  30435. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30436. ret = ASN_PARSE_E;
  30437. }
  30438. if (ret == 0) {
  30439. char* af = NULL;
  30440. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  30441. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30442. if (ret == 0) {
  30443. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30444. ret = EccKeyParamCopy((char**)&curve->Af, af, key->heap);
  30445. #else
  30446. const char *_tmp_ptr = &curve->Af[0];
  30447. ret = EccKeyParamCopy((char**)&_tmp_ptr, af, key->heap);
  30448. #endif
  30449. }
  30450. }
  30451. if (ret == 0) {
  30452. char* bf = NULL;
  30453. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  30454. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30455. if (ret == 0) {
  30456. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30457. ret = EccKeyParamCopy((char**)&curve->Bf, bf, key->heap);
  30458. #else
  30459. const char *_tmp_ptr = &curve->Bf[0];
  30460. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf, key->heap);
  30461. #endif
  30462. }
  30463. }
  30464. if (ret == 0) {
  30465. localIdx = *inOutIdx;
  30466. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  30467. == 0 && tag == ASN_BIT_STRING) {
  30468. len = 0;
  30469. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  30470. if (ret > 0)
  30471. ret = 0; /* reset on success */
  30472. *inOutIdx += (word32)len;
  30473. }
  30474. }
  30475. if (ret == 0) {
  30476. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  30477. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30478. /* sanity check that point buffer is not smaller than the expected
  30479. * size to hold ( 0 4 || Gx || Gy )
  30480. * where Gx and Gy are each the size of curve->size * 2 */
  30481. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  30482. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30483. ret = BUFFER_E;
  30484. }
  30485. }
  30486. if (ret == 0) {
  30487. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30488. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  30489. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30490. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  30491. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30492. if (curve->Gx == NULL || curve->Gy == NULL) {
  30493. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30494. ret = MEMORY_E;
  30495. }
  30496. #else
  30497. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  30498. WOLFSSL_MSG("curve size is too large to fit in buffer");
  30499. ret = BUFFER_E;
  30500. }
  30501. #endif
  30502. }
  30503. if (ret == 0) {
  30504. char* o = NULL;
  30505. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  30506. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  30507. (size_t)curve->size * 2);
  30508. ((char*)curve->Gx)[curve->size * 2] = '\0';
  30509. ((char*)curve->Gy)[curve->size * 2] = '\0';
  30510. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30511. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  30512. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  30513. if (ret == 0) {
  30514. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30515. ret = EccKeyParamCopy((char**)&curve->order, o, key->heap);
  30516. #else
  30517. const char *_tmp_ptr = &curve->order[0];
  30518. ret = EccKeyParamCopy((char**)&_tmp_ptr, o, key->heap);
  30519. #endif
  30520. }
  30521. }
  30522. if (ret == 0) {
  30523. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  30524. #ifndef WOLFSSL_ECC_CURVE_STATIC
  30525. curve->oid = NULL;
  30526. #else
  30527. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  30528. #endif
  30529. curve->oidSz = 0;
  30530. curve->oidSum = 0;
  30531. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  30532. ret = ASN_PARSE_E;
  30533. }
  30534. key->deallocSet = 1;
  30535. curve = NULL;
  30536. }
  30537. if (curve != NULL)
  30538. wc_ecc_free_curve(curve, key->heap);
  30539. if (ret < 0)
  30540. return ret;
  30541. #else
  30542. return ASN_PARSE_E;
  30543. #endif /* WOLFSSL_CUSTOM_CURVES */
  30544. }
  30545. else {
  30546. /* ecc params information */
  30547. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  30548. if (ret != 0)
  30549. return ret;
  30550. /* get curve id */
  30551. if ((ret = CheckCurve(oidSum)) < 0)
  30552. return ECC_CURVE_OID_E;
  30553. else {
  30554. curve_id = ret;
  30555. }
  30556. }
  30557. if (isPrivFormat) {
  30558. /* Public Curve Header - skip */
  30559. if (*inOutIdx >= inSz)
  30560. return ASN_PARSE_E;
  30561. tag = input[*inOutIdx];
  30562. *inOutIdx += 1;
  30563. if (tag != ECC_PREFIX_1)
  30564. return ASN_ECC_KEY_E;
  30565. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  30566. return ASN_PARSE_E;
  30567. }
  30568. /* key header */
  30569. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  30570. if (ret != 0)
  30571. return ret;
  30572. /* This is the raw point data compressed or uncompressed. */
  30573. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  30574. curve_id) != 0) {
  30575. return ASN_ECC_KEY_E;
  30576. }
  30577. *inOutIdx += (word32)length;
  30578. return 0;
  30579. #else
  30580. /* eccKeyASN is longer than eccPublicKeyASN. */
  30581. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  30582. int ret = 0;
  30583. int curve_id = ECC_CURVE_DEF;
  30584. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  30585. #ifdef WOLFSSL_CUSTOM_CURVES
  30586. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  30587. #endif
  30588. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  30589. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  30590. ret = BAD_FUNC_ARG;
  30591. }
  30592. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  30593. if (ret == 0) {
  30594. /* Clear dynamic data for ECC public key. */
  30595. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  30596. #if !defined(WOLFSSL_SM2) || !defined(WOLFSSL_SM3)
  30597. /* Set required ECDSA OID and ignore the curve OID type. */
  30598. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  30599. sizeof(keyEcdsaOid));
  30600. #else
  30601. GetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  30602. #endif
  30603. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  30604. /* Decode the public ECC key. */
  30605. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  30606. input, inOutIdx, inSz);
  30607. if (ret != 0) {
  30608. oidIdx = ECCKEYASN_IDX_CURVEID;
  30609. #ifdef WOLFSSL_CUSTOM_CURVES
  30610. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  30611. #endif
  30612. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  30613. /* Clear dynamic data for ECC private key. */
  30614. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  30615. /* Check named curve OID type. */
  30616. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  30617. /* Try private key format .*/
  30618. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  30619. inOutIdx, inSz);
  30620. if (ret != 0) {
  30621. ret = ASN_PARSE_E;
  30622. }
  30623. }
  30624. }
  30625. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  30626. if ((ret == 0) && (oidIdx == ECCPUBLICKEYASN_IDX_ALGOID_CURVEID)) {
  30627. int oidSum = dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  30628. if ((oidSum != ECDSAk) && (oidSum != SM2k)) {
  30629. ret = ASN_PARSE_E;
  30630. }
  30631. }
  30632. #endif
  30633. if (ret == 0) {
  30634. if (dataASN[oidIdx].tag != 0) {
  30635. /* Named curve - check and get id. */
  30636. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  30637. if (curve_id < 0) {
  30638. ret = ASN_OBJECT_ID_E;
  30639. }
  30640. }
  30641. else {
  30642. #ifdef WOLFSSL_CUSTOM_CURVES
  30643. /* Parse explicit parameters. */
  30644. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  30645. dataASN[specIdx].data.ref.length, key,
  30646. key->heap, NULL);
  30647. #else
  30648. /* Explicit parameters not supported in build configuration. */
  30649. ret = ASN_PARSE_E;
  30650. #endif
  30651. }
  30652. }
  30653. if (ret == 0) {
  30654. /* Import public point. */
  30655. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  30656. dataASN[pubIdx].data.ref.length, key, curve_id);
  30657. if (ret != 0) {
  30658. ret = ASN_ECC_KEY_E;
  30659. }
  30660. }
  30661. FREE_ASNGETDATA(dataASN, key->heap);
  30662. return ret;
  30663. #endif /* WOLFSSL_ASN_TEMPLATE */
  30664. }
  30665. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  30666. /* build DER formatted ECC key, include optional public key if requested,
  30667. * return length on success, negative on error */
  30668. int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  30669. int pubIn, int curveIn)
  30670. {
  30671. #ifndef WOLFSSL_ASN_TEMPLATE
  30672. byte curve[MAX_ALGO_SZ+2];
  30673. byte ver[MAX_VERSION_SZ];
  30674. byte seq[MAX_SEQ_SZ];
  30675. int ret, curveSz, verSz;
  30676. word32 totalSz;
  30677. int privHdrSz = ASN_ECC_HEADER_SZ;
  30678. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  30679. #ifdef WOLFSSL_NO_MALLOC
  30680. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  30681. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  30682. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  30683. #else
  30684. byte *prv = NULL, *pub = NULL;
  30685. #endif
  30686. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  30687. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  30688. if (key == NULL || (output == NULL && inLen == NULL))
  30689. return BAD_FUNC_ARG;
  30690. if (curveIn) {
  30691. /* curve */
  30692. curve[curveidx++] = ECC_PREFIX_0;
  30693. curveidx++ /* to put the size after computation */;
  30694. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  30695. if (curveSz < 0)
  30696. return curveSz;
  30697. /* set computed size */
  30698. curve[1] = (byte)curveSz;
  30699. curveidx += (word32)curveSz;
  30700. }
  30701. /* private */
  30702. privSz = (word32)key->dp->size;
  30703. #ifdef WOLFSSL_QNX_CAAM
  30704. /* check if is a black key, and add MAC size if needed */
  30705. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  30706. privSz = privSz + WC_CAAM_MAC_SZ;
  30707. }
  30708. #endif
  30709. #ifndef WOLFSSL_NO_MALLOC
  30710. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  30711. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30712. if (prv == NULL) {
  30713. return MEMORY_E;
  30714. }
  30715. #else
  30716. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  30717. return BUFFER_E;
  30718. }
  30719. #endif
  30720. if (privSz < ASN_LONG_LENGTH) {
  30721. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  30722. }
  30723. else {
  30724. prvidx += SetOctetString(privSz, &prv[prvidx]);
  30725. }
  30726. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  30727. if (ret < 0) {
  30728. #ifndef WOLFSSL_NO_MALLOC
  30729. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30730. #endif
  30731. return ret;
  30732. }
  30733. prvidx += privSz;
  30734. /* pubIn */
  30735. if (pubIn) {
  30736. PRIVATE_KEY_UNLOCK();
  30737. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  30738. PRIVATE_KEY_LOCK();
  30739. if (ret != LENGTH_ONLY_E) {
  30740. #ifndef WOLFSSL_NO_MALLOC
  30741. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30742. #endif
  30743. return ret;
  30744. }
  30745. #ifndef WOLFSSL_NO_MALLOC
  30746. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  30747. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30748. if (pub == NULL) {
  30749. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30750. return MEMORY_E;
  30751. }
  30752. #else
  30753. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  30754. return BUFFER_E;
  30755. }
  30756. #endif
  30757. pub[pubidx++] = ECC_PREFIX_1;
  30758. if (pubSz > 128) /* leading zero + extra size byte */
  30759. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  30760. else /* leading zero */
  30761. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  30762. /* SetBitString adds leading zero */
  30763. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  30764. PRIVATE_KEY_UNLOCK();
  30765. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  30766. PRIVATE_KEY_LOCK();
  30767. if (ret != 0) {
  30768. #ifndef WOLFSSL_NO_MALLOC
  30769. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30770. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30771. #endif
  30772. return ret;
  30773. }
  30774. pubidx += pubSz;
  30775. }
  30776. /* make headers */
  30777. verSz = SetMyVersion(1, ver, FALSE);
  30778. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  30779. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  30780. if (output == NULL) {
  30781. *inLen = totalSz;
  30782. #ifndef WOLFSSL_NO_MALLOC
  30783. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30784. if (pubIn) {
  30785. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30786. }
  30787. #endif
  30788. return LENGTH_ONLY_E;
  30789. }
  30790. if (inLen != NULL && totalSz > *inLen) {
  30791. #ifndef WOLFSSL_NO_MALLOC
  30792. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30793. if (pubIn) {
  30794. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30795. }
  30796. #endif
  30797. return BAD_FUNC_ARG;
  30798. }
  30799. /* write out */
  30800. /* seq */
  30801. XMEMCPY(output + idx, seq, seqSz);
  30802. idx = seqSz;
  30803. /* ver */
  30804. XMEMCPY(output + idx, ver, (size_t)verSz);
  30805. idx += (word32)verSz;
  30806. /* private */
  30807. XMEMCPY(output + idx, prv, prvidx);
  30808. idx += prvidx;
  30809. #ifndef WOLFSSL_NO_MALLOC
  30810. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30811. #endif
  30812. /* curve */
  30813. XMEMCPY(output + idx, curve, curveidx);
  30814. idx += curveidx;
  30815. /* pubIn */
  30816. if (pubIn) {
  30817. XMEMCPY(output + idx, pub, pubidx);
  30818. /* idx += pubidx; not used after write, if more data remove comment */
  30819. #ifndef WOLFSSL_NO_MALLOC
  30820. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30821. #endif
  30822. }
  30823. return (int)totalSz;
  30824. #else
  30825. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  30826. word32 privSz, pubSz;
  30827. int sz = 0;
  30828. int ret = 0;
  30829. int curveIdSz = 0;
  30830. /* Check validity of parameters. */
  30831. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  30832. ret = BAD_FUNC_ARG;
  30833. }
  30834. /* Check key has parameters when encoding curve. */
  30835. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  30836. ret = BAD_FUNC_ARG;
  30837. }
  30838. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  30839. if (ret == 0) {
  30840. /* Private key size is the curve size. */
  30841. privSz = (word32)key->dp->size;
  30842. if (pubIn) {
  30843. /* Get the length of the public key. */
  30844. PRIVATE_KEY_UNLOCK();
  30845. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  30846. PRIVATE_KEY_LOCK();
  30847. if (ret == LENGTH_ONLY_E)
  30848. ret = 0;
  30849. }
  30850. }
  30851. if (ret == 0) {
  30852. /* Version: 1 */
  30853. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  30854. /* Leave space for private key. */
  30855. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  30856. if (curveIn) {
  30857. /* Get length of the named curve OID to put into the encoding. */
  30858. curveIdSz = SetCurve(key, NULL, 0);
  30859. if (curveIdSz < 0) {
  30860. ret = curveIdSz;
  30861. }
  30862. /* Curve OID */
  30863. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  30864. (word32)curveIdSz);
  30865. /* TODO: add support for SpecifiedECDomain curve. */
  30866. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  30867. }
  30868. else {
  30869. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  30870. eccKeyASN_Length);
  30871. }
  30872. if (ret == 0) {
  30873. if (pubIn) {
  30874. /* Leave space for public key. */
  30875. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  30876. }
  30877. else {
  30878. /* Don't write out public key. */
  30879. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  30880. eccKeyASN_Length);
  30881. }
  30882. /* Calculate size of the private key encoding. */
  30883. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  30884. }
  30885. }
  30886. /* Return the size if no buffer. */
  30887. if ((ret == 0) && (output == NULL)) {
  30888. *inLen = (word32)sz;
  30889. ret = LENGTH_ONLY_E;
  30890. }
  30891. /* Check the buffer is big enough. */
  30892. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  30893. ret = BAD_FUNC_ARG;
  30894. }
  30895. if ((ret == 0) && (output != NULL)) {
  30896. /* Encode the private key. */
  30897. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  30898. if (curveIn) {
  30899. /* Put named curve OID data into encoding. */
  30900. curveIdSz = SetCurve(key,
  30901. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  30902. (size_t)curveIdSz);
  30903. if (curveIdSz < 0) {
  30904. ret = curveIdSz;
  30905. }
  30906. }
  30907. if (ret == 0) {
  30908. /* Export the private value into the buffer. */
  30909. ret = wc_ecc_export_private_only(key,
  30910. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  30911. }
  30912. if ((ret == 0) && pubIn) {
  30913. /* Export the public point into the buffer. */
  30914. PRIVATE_KEY_UNLOCK();
  30915. ret = wc_ecc_export_x963(key,
  30916. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  30917. &pubSz);
  30918. PRIVATE_KEY_LOCK();
  30919. }
  30920. }
  30921. if (ret == 0) {
  30922. /* Return the encoding size. */
  30923. ret = sz;
  30924. }
  30925. FREE_ASNSETDATA(dataASN, key->heap);
  30926. return ret;
  30927. #endif
  30928. }
  30929. /* Write a Private ecc key, including public to DER format,
  30930. * length on success else < 0 */
  30931. WOLFSSL_ABI
  30932. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  30933. {
  30934. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  30935. }
  30936. /* Write only private ecc key to DER format,
  30937. * length on success else < 0 */
  30938. int wc_EccKeyDerSize(ecc_key* key, int pub)
  30939. {
  30940. word32 sz = 0;
  30941. int ret;
  30942. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  30943. if (ret != LENGTH_ONLY_E) {
  30944. return ret;
  30945. }
  30946. return (int)sz;
  30947. }
  30948. /* Write only private ecc key to DER format,
  30949. * length on success else < 0 */
  30950. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  30951. {
  30952. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  30953. }
  30954. #ifdef HAVE_PKCS8
  30955. /* Write only private ecc key or both private and public parts to unencrypted
  30956. * PKCS#8 format.
  30957. *
  30958. * If output is NULL, places required PKCS#8 buffer size in outLen and
  30959. * returns LENGTH_ONLY_E.
  30960. *
  30961. * return length on success else < 0 */
  30962. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  30963. int includePublic)
  30964. {
  30965. int ret;
  30966. word32 tmpDerSz;
  30967. int algoID = 0;
  30968. word32 oidSz = 0;
  30969. word32 pkcs8Sz = 0;
  30970. const byte* curveOID = NULL;
  30971. #ifdef WOLFSSL_NO_MALLOC
  30972. byte tmpDer[ECC_BUFSIZE];
  30973. #else
  30974. byte* tmpDer = NULL;
  30975. #endif
  30976. word32 sz = ECC_BUFSIZE;
  30977. if (key == NULL || key->dp == NULL || outLen == NULL)
  30978. return BAD_FUNC_ARG;
  30979. /* set algoID, get curve OID */
  30980. algoID = ECDSAk;
  30981. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  30982. if (ret < 0)
  30983. return ret;
  30984. #ifndef WOLFSSL_NO_MALLOC
  30985. /* temp buffer for plain DER key */
  30986. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30987. if (tmpDer == NULL)
  30988. return MEMORY_E;
  30989. #endif
  30990. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  30991. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  30992. if (ret < 0) {
  30993. #ifndef WOLFSSL_NO_MALLOC
  30994. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30995. #endif
  30996. return ret;
  30997. }
  30998. tmpDerSz = (word32)ret;
  30999. /* get pkcs8 expected output size */
  31000. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  31001. curveOID, oidSz);
  31002. if (ret != LENGTH_ONLY_E) {
  31003. #ifndef WOLFSSL_NO_MALLOC
  31004. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  31005. #endif
  31006. return ret;
  31007. }
  31008. if (output == NULL) {
  31009. #ifndef WOLFSSL_NO_MALLOC
  31010. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  31011. #endif
  31012. *outLen = pkcs8Sz;
  31013. return LENGTH_ONLY_E;
  31014. }
  31015. else if (*outLen < pkcs8Sz) {
  31016. #ifndef WOLFSSL_NO_MALLOC
  31017. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  31018. #endif
  31019. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  31020. return BUFFER_E;
  31021. }
  31022. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  31023. algoID, curveOID, oidSz);
  31024. if (ret < 0) {
  31025. #ifndef WOLFSSL_NO_MALLOC
  31026. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  31027. #endif
  31028. return ret;
  31029. }
  31030. #ifndef WOLFSSL_NO_MALLOC
  31031. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  31032. #endif
  31033. *outLen = (word32)ret;
  31034. return ret;
  31035. }
  31036. /* Write only private ecc key to unencrypted PKCS#8 format.
  31037. *
  31038. * return length on success else < 0 */
  31039. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  31040. {
  31041. return eccToPKCS8(key, output, outLen, 0);
  31042. }
  31043. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  31044. *
  31045. * return length on success else < 0 */
  31046. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  31047. word32* outLen)
  31048. {
  31049. return eccToPKCS8(key, output, outLen, 1);
  31050. }
  31051. #endif /* HAVE_PKCS8 */
  31052. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  31053. #endif /* HAVE_ECC */
  31054. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  31055. #ifdef WOLFSSL_ASN_TEMPLATE
  31056. /* ASN.1 template for Ed25519 and Ed448 private key.
  31057. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  31058. */
  31059. static const ASNItem edKeyASN[] = {
  31060. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31061. /* Version */
  31062. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  31063. /* privateKeyAlgorithm */
  31064. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31065. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  31066. /* privateKey */
  31067. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  31068. /* CurvePrivateKey */
  31069. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  31070. /* attributes */
  31071. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  31072. /* publicKey */
  31073. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  31074. };
  31075. enum {
  31076. EDKEYASN_IDX_SEQ = 0,
  31077. EDKEYASN_IDX_VER,
  31078. EDKEYASN_IDX_PKEYALGO_SEQ,
  31079. EDKEYASN_IDX_PKEYALGO_OID,
  31080. EDKEYASN_IDX_PKEY,
  31081. EDKEYASN_IDX_PKEY_CURVEPKEY,
  31082. EDKEYASN_IDX_ATTRS,
  31083. EDKEYASN_IDX_PUBKEY
  31084. };
  31085. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  31086. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  31087. #endif
  31088. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  31089. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  31090. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  31091. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  31092. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  31093. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  31094. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  31095. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  31096. byte* privKey, word32* privKeyLen,
  31097. byte* pubKey, word32* pubKeyLen, int keyType)
  31098. {
  31099. #ifndef WOLFSSL_ASN_TEMPLATE
  31100. word32 oid;
  31101. int version, length, endKeyIdx, privSz, pubSz;
  31102. const byte* priv;
  31103. const byte* pub;
  31104. #else
  31105. int ret = 0;
  31106. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  31107. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  31108. #endif
  31109. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  31110. privKey == NULL || privKeyLen == NULL) {
  31111. #ifdef WOLFSSL_ASN_TEMPLATE
  31112. FREE_ASNGETDATA(dataASN, NULL);
  31113. #endif
  31114. return BAD_FUNC_ARG;
  31115. }
  31116. #ifndef WOLFSSL_ASN_TEMPLATE
  31117. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  31118. endKeyIdx = (int)*inOutIdx + length;
  31119. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  31120. return ASN_PARSE_E;
  31121. if (version != 0) {
  31122. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  31123. return ASN_PARSE_E;
  31124. }
  31125. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  31126. return ASN_PARSE_E;
  31127. if (oid != (word32)keyType)
  31128. return ASN_PARSE_E;
  31129. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  31130. return ASN_PARSE_E;
  31131. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  31132. return ASN_PARSE_E;
  31133. priv = input + *inOutIdx;
  31134. *inOutIdx += (word32)privSz;
  31135. }
  31136. else {
  31137. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  31138. return ASN_PARSE_E;
  31139. priv = input + *inOutIdx;
  31140. *inOutIdx += (word32)privSz;
  31141. endKeyIdx = (int)*inOutIdx;
  31142. }
  31143. if ((word32)privSz > *privKeyLen)
  31144. return BUFFER_E;
  31145. if (endKeyIdx == (int)*inOutIdx) {
  31146. *privKeyLen = (word32)privSz;
  31147. XMEMCPY(privKey, priv, *privKeyLen);
  31148. if (pubKeyLen != NULL)
  31149. *pubKeyLen = 0;
  31150. }
  31151. else {
  31152. if (pubKeyLen == NULL) {
  31153. return BAD_FUNC_ARG;
  31154. }
  31155. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  31156. inOutIdx, &pubSz, inSz) < 0) {
  31157. return ASN_PARSE_E;
  31158. }
  31159. if ((word32)pubSz > *pubKeyLen)
  31160. return BUFFER_E;
  31161. pub = input + *inOutIdx;
  31162. *inOutIdx += (word32)pubSz;
  31163. *privKeyLen = (word32)privSz;
  31164. XMEMCPY(privKey, priv, *privKeyLen);
  31165. *pubKeyLen = (word32)pubSz;
  31166. if (pubKey != NULL)
  31167. XMEMCPY(pubKey, pub, *pubKeyLen);
  31168. }
  31169. if (endKeyIdx != (int)*inOutIdx)
  31170. return ASN_PARSE_E;
  31171. return 0;
  31172. #else
  31173. if (ret == 0) {
  31174. /* Require OID. */
  31175. word32 oidSz;
  31176. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  31177. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  31178. /* Parse full private key. */
  31179. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  31180. inOutIdx, inSz);
  31181. if (ret != 0) {
  31182. /* Parse just the OCTET_STRING. */
  31183. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  31184. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  31185. inOutIdx, inSz);
  31186. if (ret != 0) {
  31187. ret = ASN_PARSE_E;
  31188. }
  31189. }
  31190. }
  31191. /* Check the private value length is correct. */
  31192. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  31193. > *privKeyLen) {
  31194. ret = ASN_PARSE_E;
  31195. }
  31196. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  31197. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  31198. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  31199. *privKeyLen);
  31200. if (pubKeyLen != NULL)
  31201. *pubKeyLen = 0;
  31202. }
  31203. else if ((ret == 0) &&
  31204. (pubKeyLen != NULL) &&
  31205. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  31206. ret = ASN_PARSE_E;
  31207. }
  31208. else if (ret == 0) {
  31209. /* Import private and public value. */
  31210. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  31211. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  31212. *privKeyLen);
  31213. if (pubKeyLen != NULL)
  31214. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  31215. if (pubKey != NULL && pubKeyLen != NULL)
  31216. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  31217. *pubKeyLen);
  31218. }
  31219. FREE_ASNGETDATA(dataASN, NULL);
  31220. return ret;
  31221. #endif /* WOLFSSL_ASN_TEMPLATE */
  31222. }
  31223. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  31224. byte* pubKey, word32* pubKeyLen, int keyType)
  31225. {
  31226. int ret = 0;
  31227. #ifndef WOLFSSL_ASN_TEMPLATE
  31228. int length;
  31229. word32 oid;
  31230. #else
  31231. word32 len;
  31232. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  31233. #endif
  31234. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  31235. pubKey == NULL || pubKeyLen == NULL) {
  31236. return BAD_FUNC_ARG;
  31237. }
  31238. #ifndef WOLFSSL_ASN_TEMPLATE
  31239. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  31240. return ASN_PARSE_E;
  31241. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  31242. return ASN_PARSE_E;
  31243. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  31244. return ASN_PARSE_E;
  31245. if (oid != (word32)keyType)
  31246. return ASN_PARSE_E;
  31247. /* key header */
  31248. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  31249. if (ret != 0)
  31250. return ret;
  31251. /* check that the value found is not too large for pubKey buffer */
  31252. if ((word32)length > *pubKeyLen)
  31253. return ASN_PARSE_E;
  31254. /* check that input buffer is exhausted */
  31255. if (*inOutIdx + (word32)length != inSz)
  31256. return ASN_PARSE_E;
  31257. /* This is the raw point data compressed or uncompressed. */
  31258. *pubKeyLen = (word32)length;
  31259. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  31260. #else
  31261. len = inSz - *inOutIdx;
  31262. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  31263. if (ret == 0) {
  31264. /* Require OID. */
  31265. word32 oidSz;
  31266. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  31267. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  31268. /* Decode Ed25519 private key. */
  31269. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  31270. inOutIdx, inSz);
  31271. if (ret != 0)
  31272. ret = ASN_PARSE_E;
  31273. /* check that input buffer is exhausted */
  31274. if (*inOutIdx != inSz)
  31275. ret = ASN_PARSE_E;
  31276. }
  31277. /* Check the public value length is correct. */
  31278. if ((ret == 0) &&
  31279. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  31280. ret = ASN_PARSE_E;
  31281. }
  31282. /* Check that the all the buffer was used. */
  31283. if ((ret == 0) &&
  31284. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  31285. ret = ASN_PARSE_E;
  31286. }
  31287. if (ret == 0) {
  31288. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  31289. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  31290. *pubKeyLen);
  31291. }
  31292. FREE_ASNGETDATA(dataASN, NULL);
  31293. #endif /* WOLFSSL_ASN_TEMPLATE */
  31294. return ret;
  31295. }
  31296. #endif
  31297. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  31298. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  31299. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  31300. ed25519_key* key, word32 inSz)
  31301. {
  31302. int ret;
  31303. byte privKey[ED25519_KEY_SIZE], pubKey[2*ED25519_PUB_KEY_SIZE+1];
  31304. word32 privKeyLen = (word32)sizeof(privKey);
  31305. word32 pubKeyLen = (word32)sizeof(pubKey);
  31306. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31307. return BAD_FUNC_ARG;
  31308. }
  31309. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  31310. pubKey, &pubKeyLen, ED25519k);
  31311. if (ret == 0) {
  31312. if (pubKeyLen == 0) {
  31313. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  31314. }
  31315. else {
  31316. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  31317. pubKey, pubKeyLen, key);
  31318. }
  31319. }
  31320. return ret;
  31321. }
  31322. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  31323. ed25519_key* key, word32 inSz)
  31324. {
  31325. int ret;
  31326. byte pubKey[2*ED25519_PUB_KEY_SIZE+1];
  31327. word32 pubKeyLen = (word32)sizeof(pubKey);
  31328. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31329. return BAD_FUNC_ARG;
  31330. }
  31331. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  31332. pubKey, &pubKeyLen, ED25519k);
  31333. if (ret == 0) {
  31334. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  31335. }
  31336. return ret;
  31337. }
  31338. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  31339. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  31340. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  31341. curve25519_key* key, word32 inSz)
  31342. {
  31343. int ret;
  31344. byte privKey[CURVE25519_KEYSIZE];
  31345. word32 privKeyLen = CURVE25519_KEYSIZE;
  31346. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31347. return BAD_FUNC_ARG;
  31348. }
  31349. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  31350. NULL, NULL, X25519k);
  31351. if (ret == 0) {
  31352. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  31353. }
  31354. return ret;
  31355. }
  31356. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  31357. curve25519_key* key, word32 inSz)
  31358. {
  31359. int ret;
  31360. byte pubKey[CURVE25519_KEYSIZE];
  31361. word32 pubKeyLen = (word32)sizeof(pubKey);
  31362. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31363. return BAD_FUNC_ARG;
  31364. }
  31365. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  31366. pubKey, &pubKeyLen, X25519k);
  31367. if (ret == 0) {
  31368. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  31369. }
  31370. return ret;
  31371. }
  31372. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  31373. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  31374. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  31375. *
  31376. * Pass NULL for output to get the size of the encoding.
  31377. *
  31378. * @param [in] privKey private key buffer
  31379. * @param [in] privKeyLen private key buffer length
  31380. * @param [in] pubKey public key buffer (optional)
  31381. * @param [in] pubKeyLen public key buffer length
  31382. * @param [out] output Buffer to put encoded data in (optional)
  31383. * @param [in] outLen Size of buffer in bytes
  31384. * @param [in] keyType is "enum Key_Sum" like ED25519k
  31385. * @return Size of encoded data in bytes on success
  31386. * @return BAD_FUNC_ARG when key is NULL.
  31387. * @return MEMORY_E when dynamic memory allocation failed.
  31388. */
  31389. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  31390. const byte* pubKey, word32 pubKeyLen,
  31391. byte* output, word32 outLen, int keyType)
  31392. {
  31393. int ret = 0;
  31394. #ifndef WOLFSSL_ASN_TEMPLATE
  31395. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  31396. #else
  31397. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  31398. int sz;
  31399. #endif
  31400. /* Validate parameters. */
  31401. if (privKey == NULL || outLen == 0) {
  31402. return BAD_FUNC_ARG;
  31403. }
  31404. #ifndef WOLFSSL_ASN_TEMPLATE
  31405. /* calculate size */
  31406. if (pubKey) {
  31407. pubSz = 2 + pubKeyLen;
  31408. }
  31409. privSz = 2 + 2 + privKeyLen;
  31410. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  31411. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  31412. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  31413. sz = seqSz + verSz + algoSz + privSz + pubSz;
  31414. /* checkout output size */
  31415. if (output != NULL && sz > outLen) {
  31416. ret = BAD_FUNC_ARG;
  31417. }
  31418. if (ret == 0 && output != NULL) {
  31419. /* write out */
  31420. /* seq */
  31421. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  31422. idx = seqSz;
  31423. /* ver */
  31424. SetMyVersion(0, output + idx, FALSE);
  31425. idx += verSz;
  31426. /* algo */
  31427. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  31428. idx += algoSz;
  31429. /* privKey */
  31430. idx += SetOctetString(2 + privKeyLen, output + idx);
  31431. idx += SetOctetString(privKeyLen, output + idx);
  31432. XMEMCPY(output + idx, privKey, privKeyLen);
  31433. idx += privKeyLen;
  31434. /* pubKey */
  31435. if (pubKey) {
  31436. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  31437. 1, pubKeyLen, output + idx, 0);
  31438. XMEMCPY(output + idx, pubKey, pubKeyLen);
  31439. idx += pubKeyLen;
  31440. }
  31441. sz = idx;
  31442. }
  31443. if (ret == 0) {
  31444. /* Return size of encoding. */
  31445. ret = (int)sz;
  31446. }
  31447. #else
  31448. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  31449. if (ret == 0) {
  31450. /* Set version = 0 */
  31451. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  31452. /* Set OID. */
  31453. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
  31454. oidKeyType);
  31455. /* Leave space for private key. */
  31456. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  31457. /* Don't write out attributes. */
  31458. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  31459. if (pubKey) {
  31460. /* Leave space for public key. */
  31461. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  31462. }
  31463. else {
  31464. /* Don't put out public part. */
  31465. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  31466. edKeyASN_Length);
  31467. }
  31468. /* Calculate the size of encoding. */
  31469. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  31470. }
  31471. /* Check buffer is big enough. */
  31472. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  31473. ret = BAD_FUNC_ARG;
  31474. }
  31475. if ((ret == 0) && (output != NULL)) {
  31476. /* Encode private key. */
  31477. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  31478. /* Put private value into space provided. */
  31479. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  31480. privKey, privKeyLen);
  31481. if (pubKey != NULL) {
  31482. /* Put public value into space provided. */
  31483. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  31484. pubKey, pubKeyLen);
  31485. }
  31486. }
  31487. if (ret == 0) {
  31488. /* Return size of encoding. */
  31489. ret = sz;
  31490. }
  31491. FREE_ASNSETDATA(dataASN, NULL);
  31492. #endif
  31493. return ret;
  31494. }
  31495. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  31496. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  31497. /* Write a Private ED25519 key, including public to DER format,
  31498. * length on success else < 0 */
  31499. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  31500. {
  31501. if (key == NULL) {
  31502. return BAD_FUNC_ARG;
  31503. }
  31504. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  31505. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  31506. }
  31507. /* Write only private ED25519 key to DER format,
  31508. * length on success else < 0 */
  31509. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  31510. {
  31511. if (key == NULL) {
  31512. return BAD_FUNC_ARG;
  31513. }
  31514. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  31515. NULL, 0, output, inLen, ED25519k);
  31516. }
  31517. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  31518. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  31519. /* Write only private Curve25519 key to DER format,
  31520. * length on success else < 0 */
  31521. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  31522. {
  31523. int ret;
  31524. byte privKey[CURVE25519_KEYSIZE];
  31525. word32 privKeyLen = CURVE25519_KEYSIZE;
  31526. if (key == NULL) {
  31527. return BAD_FUNC_ARG;
  31528. }
  31529. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  31530. if (ret == 0) {
  31531. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  31532. X25519k);
  31533. }
  31534. return ret;
  31535. }
  31536. /* Write a public Curve25519 key to DER format,
  31537. * length on success else < 0 */
  31538. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  31539. int withAlg)
  31540. {
  31541. int ret;
  31542. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  31543. word32 pubKeyLen = (word32)sizeof(pubKey);
  31544. if (key == NULL || output == NULL) {
  31545. return BAD_FUNC_ARG;
  31546. }
  31547. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  31548. if (ret == 0) {
  31549. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  31550. X25519k, withAlg);
  31551. }
  31552. return ret;
  31553. }
  31554. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  31555. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  31556. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  31557. ed448_key* key, word32 inSz)
  31558. {
  31559. int ret;
  31560. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  31561. word32 privKeyLen = (word32)sizeof(privKey);
  31562. word32 pubKeyLen = (word32)sizeof(pubKey);
  31563. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31564. return BAD_FUNC_ARG;
  31565. }
  31566. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  31567. pubKey, &pubKeyLen, ED448k);
  31568. if (ret == 0) {
  31569. if (pubKeyLen == 0) {
  31570. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  31571. }
  31572. else {
  31573. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  31574. pubKey, pubKeyLen, key);
  31575. }
  31576. }
  31577. return ret;
  31578. }
  31579. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  31580. ed448_key* key, word32 inSz)
  31581. {
  31582. int ret;
  31583. byte pubKey[2 * ED448_PUB_KEY_SIZE + 1];
  31584. word32 pubKeyLen = (word32)sizeof(pubKey);
  31585. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31586. return BAD_FUNC_ARG;
  31587. }
  31588. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  31589. pubKey, &pubKeyLen, ED448k);
  31590. if (ret == 0) {
  31591. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  31592. }
  31593. return ret;
  31594. }
  31595. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  31596. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  31597. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  31598. curve448_key* key, word32 inSz)
  31599. {
  31600. int ret;
  31601. byte privKey[CURVE448_KEY_SIZE];
  31602. word32 privKeyLen = CURVE448_KEY_SIZE;
  31603. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31604. return BAD_FUNC_ARG;
  31605. }
  31606. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  31607. NULL, NULL, X448k);
  31608. if (ret == 0) {
  31609. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  31610. }
  31611. return ret;
  31612. }
  31613. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  31614. curve448_key* key, word32 inSz)
  31615. {
  31616. int ret;
  31617. byte pubKey[CURVE448_PUB_KEY_SIZE];
  31618. word32 pubKeyLen = (word32)sizeof(pubKey);
  31619. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  31620. return BAD_FUNC_ARG;
  31621. }
  31622. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  31623. pubKey, &pubKeyLen, X448k);
  31624. if (ret == 0) {
  31625. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  31626. }
  31627. return ret;
  31628. }
  31629. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  31630. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  31631. /* Write a Private ecc key, including public to DER format,
  31632. * length on success else < 0 */
  31633. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  31634. {
  31635. if (key == NULL) {
  31636. return BAD_FUNC_ARG;
  31637. }
  31638. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  31639. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  31640. }
  31641. /* Write only private ecc key to DER format,
  31642. * length on success else < 0 */
  31643. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  31644. {
  31645. if (key == NULL) {
  31646. return BAD_FUNC_ARG;
  31647. }
  31648. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  31649. NULL, 0, output, inLen, ED448k);
  31650. }
  31651. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  31652. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  31653. /* Write private Curve448 key to DER format,
  31654. * length on success else < 0 */
  31655. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  31656. {
  31657. int ret;
  31658. byte privKey[CURVE448_KEY_SIZE];
  31659. word32 privKeyLen = CURVE448_KEY_SIZE;
  31660. if (key == NULL) {
  31661. return BAD_FUNC_ARG;
  31662. }
  31663. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  31664. if (ret == 0) {
  31665. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  31666. X448k);
  31667. }
  31668. return ret;
  31669. }
  31670. /* Write a public Curve448 key to DER format,
  31671. * length on success else < 0 */
  31672. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  31673. int withAlg)
  31674. {
  31675. int ret;
  31676. byte pubKey[CURVE448_PUB_KEY_SIZE];
  31677. word32 pubKeyLen = (word32)sizeof(pubKey);
  31678. if (key == NULL || output == NULL) {
  31679. return BAD_FUNC_ARG;
  31680. }
  31681. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  31682. if (ret == 0) {
  31683. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  31684. X448k, withAlg);
  31685. }
  31686. return ret;
  31687. }
  31688. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  31689. #ifndef WOLFSSL_ASN_TEMPLATE
  31690. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  31691. /* Get raw Date only, no processing, 0 on success */
  31692. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  31693. byte* format, int maxIdx)
  31694. {
  31695. int ret, length;
  31696. const byte *datePtr = NULL;
  31697. WOLFSSL_ENTER("GetBasicDate");
  31698. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  31699. if (ret < 0)
  31700. return ret;
  31701. XMEMCPY(date, datePtr, length);
  31702. return 0;
  31703. }
  31704. #endif /* HAVE_OCSP || HAVE_CRL */
  31705. #endif /* WOLFSSL_ASN_TEMPLATE */
  31706. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  31707. #ifndef WOLFSSL_ASN_TEMPLATE
  31708. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  31709. int sz)
  31710. {
  31711. word32 idx = *inOutIdx;
  31712. word32 len;
  31713. byte tag;
  31714. WOLFSSL_ENTER("GetEnumerated");
  31715. *value = 0;
  31716. if (GetASNTag(input, &idx, &tag, sz) < 0)
  31717. return ASN_PARSE_E;
  31718. if (tag != ASN_ENUMERATED)
  31719. return ASN_PARSE_E;
  31720. if ((int)idx >= sz)
  31721. return BUFFER_E;
  31722. len = input[idx++];
  31723. if (len > 4 || (int)(len + idx) > sz)
  31724. return ASN_PARSE_E;
  31725. while (len--) {
  31726. *value = *value << 8 | input[idx++];
  31727. }
  31728. *inOutIdx = idx;
  31729. return *value;
  31730. }
  31731. #endif /* !WOLFSSL_ASN_TEMPLATE */
  31732. #ifdef WOLFSSL_ASN_TEMPLATE
  31733. /* ASN.1 template for OCSP single response.
  31734. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31735. */
  31736. static const ASNItem singleResponseASN[] = {
  31737. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31738. /* certId */
  31739. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31740. /* hashAlgorithm */
  31741. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31742. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31743. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  31744. /* issuerNameHash */
  31745. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  31746. /* issuerKeyHash */
  31747. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  31748. /* serialNumber */
  31749. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  31750. /* certStatus - CHOICE */
  31751. /* good [0] IMPLICIT NULL */
  31752. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  31753. /* revoked [1] IMPLICIT RevokedInfo */
  31754. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  31755. /* revocationTime */
  31756. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  31757. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  31758. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31759. /* crlReason */
  31760. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  31761. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  31762. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  31763. /* thisUpdate */
  31764. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  31765. /* nextUpdate */
  31766. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31767. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  31768. /* singleExtensions */
  31769. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  31770. };
  31771. enum {
  31772. SINGLERESPONSEASN_IDX_SEQ = 0,
  31773. SINGLERESPONSEASN_IDX_CID_SEQ,
  31774. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  31775. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  31776. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  31777. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  31778. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  31779. SINGLERESPONSEASN_IDX_CID_SERIAL,
  31780. SINGLERESPONSEASN_IDX_CS_GOOD,
  31781. SINGLERESPONSEASN_IDX_CS_REVOKED,
  31782. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  31783. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  31784. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  31785. SINGLERESPONSEASN_IDX_UNKNOWN,
  31786. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  31787. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  31788. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  31789. SINGLERESPONSEASN_IDX_EXT,
  31790. };
  31791. /* Number of items in ASN.1 template for OCSP single response. */
  31792. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  31793. #endif
  31794. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  31795. int wrapperSz, OcspEntry* single)
  31796. {
  31797. #ifndef WOLFSSL_ASN_TEMPLATE
  31798. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  31799. int length;
  31800. int ret;
  31801. byte tag;
  31802. WOLFSSL_ENTER("DecodeSingleResponse");
  31803. prevIndex = idx;
  31804. /* Wrapper around the Single Response */
  31805. if (GetSequence(source, &idx, &length, size) < 0)
  31806. return ASN_PARSE_E;
  31807. /* Wrapper around the CertID */
  31808. certIdIdx = idx;
  31809. if (GetSequence(source, &idx, &length, size) < 0)
  31810. return ASN_PARSE_E;
  31811. single->rawCertId = source + certIdIdx;
  31812. /* Hash algorithm */
  31813. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  31814. if (ret < 0)
  31815. return ret;
  31816. single->hashAlgoOID = oid;
  31817. /* Save reference to the hash of CN */
  31818. ret = GetOctetString(source, &idx, &length, size);
  31819. if (ret < 0)
  31820. return ret;
  31821. if (length > (int)sizeof(single->issuerHash))
  31822. return BUFFER_E;
  31823. XMEMCPY(single->issuerHash, source + idx, length);
  31824. idx += length;
  31825. /* Save reference to the hash of the issuer public key */
  31826. ret = GetOctetString(source, &idx, &length, size);
  31827. if (ret < 0)
  31828. return ret;
  31829. if (length > (int)sizeof(single->issuerKeyHash))
  31830. return BUFFER_E;
  31831. XMEMCPY(single->issuerKeyHash, source + idx, length);
  31832. idx += length;
  31833. /* Get serial number */
  31834. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  31835. &single->status->serialSz, size) < 0)
  31836. return ASN_PARSE_E;
  31837. single->rawCertIdSize = idx - certIdIdx;
  31838. if (idx >= size)
  31839. return BUFFER_E;
  31840. /* CertStatus */
  31841. switch (source[idx++])
  31842. {
  31843. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  31844. single->status->status = CERT_GOOD;
  31845. idx++;
  31846. break;
  31847. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  31848. single->status->status = CERT_REVOKED;
  31849. if (GetLength(source, &idx, &length, size) < 0)
  31850. return ASN_PARSE_E;
  31851. idx += length;
  31852. break;
  31853. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  31854. single->status->status = CERT_UNKNOWN;
  31855. idx++;
  31856. break;
  31857. default:
  31858. return ASN_PARSE_E;
  31859. }
  31860. if (idx >= size)
  31861. return BUFFER_E;
  31862. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  31863. single->status->thisDateAsn = source + idx;
  31864. localIdx = 0;
  31865. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  31866. (byte*)&single->status->thisDateParsed.type,
  31867. &single->status->thisDateParsed.length, size - idx) < 0)
  31868. return ASN_PARSE_E;
  31869. if (idx + localIdx >= size)
  31870. return BUFFER_E;
  31871. XMEMCPY(single->status->thisDateParsed.data,
  31872. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  31873. single->status->thisDateParsed.length);
  31874. #endif
  31875. if (GetBasicDate(source, &idx, single->status->thisDate,
  31876. &single->status->thisDateFormat, size) < 0)
  31877. return ASN_PARSE_E;
  31878. #ifndef NO_ASN_TIME_CHECK
  31879. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  31880. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  31881. return ASN_BEFORE_DATE_E;
  31882. #endif
  31883. #endif
  31884. /* The following items are optional. Only check for them if there is more
  31885. * unprocessed data in the singleResponse wrapper. */
  31886. localIdx = idx;
  31887. if (((int)(idx - prevIndex) < wrapperSz) &&
  31888. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31889. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  31890. {
  31891. idx++;
  31892. if (GetLength(source, &idx, &length, size) < 0)
  31893. return ASN_PARSE_E;
  31894. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  31895. single->status->nextDateAsn = source + idx;
  31896. localIdx = 0;
  31897. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  31898. (byte*)&single->status->nextDateParsed.type,
  31899. &single->status->nextDateParsed.length, size - idx) < 0)
  31900. return ASN_PARSE_E;
  31901. if (idx + localIdx >= size)
  31902. return BUFFER_E;
  31903. XMEMCPY(single->status->nextDateParsed.data,
  31904. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  31905. single->status->nextDateParsed.length);
  31906. #endif
  31907. if (GetBasicDate(source, &idx, single->status->nextDate,
  31908. &single->status->nextDateFormat, size) < 0)
  31909. return ASN_PARSE_E;
  31910. #ifndef NO_ASN_TIME_CHECK
  31911. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  31912. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  31913. return ASN_AFTER_DATE_E;
  31914. #endif
  31915. #endif
  31916. }
  31917. /* Skip the optional extensions in singleResponse. */
  31918. localIdx = idx;
  31919. if (((int)(idx - prevIndex) < wrapperSz) &&
  31920. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31921. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  31922. {
  31923. idx++;
  31924. if (GetLength(source, &idx, &length, size) < 0)
  31925. return ASN_PARSE_E;
  31926. idx += length;
  31927. }
  31928. *ioIndex = idx;
  31929. return 0;
  31930. #else
  31931. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  31932. int ret = 0;
  31933. word32 ocspDigestSize = OCSP_DIGEST_SIZE;
  31934. CertStatus* cs = NULL;
  31935. word32 serialSz;
  31936. word32 issuerHashLen;
  31937. word32 issuerKeyHashLen;
  31938. word32 thisDateLen;
  31939. word32 nextDateLen;
  31940. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  31941. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  31942. WOLFSSL_ASN1_TIME *at;
  31943. #endif
  31944. (void)wrapperSz;
  31945. WOLFSSL_ENTER("DecodeSingleResponse");
  31946. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  31947. if (ret == 0) {
  31948. /* Certificate Status field. */
  31949. cs = single->status;
  31950. /* Set maximum lengths for data. */
  31951. issuerHashLen = OCSP_DIGEST_SIZE;
  31952. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  31953. serialSz = EXTERNAL_SERIAL_SIZE;
  31954. thisDateLen = MAX_DATE_SIZE;
  31955. nextDateLen = MAX_DATE_SIZE;
  31956. /* Set OID type, buffers to hold data and variables to hold size. */
  31957. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  31958. oidHashType);
  31959. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  31960. single->issuerHash, &issuerHashLen);
  31961. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  31962. single->issuerKeyHash, &issuerKeyHashLen);
  31963. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  31964. &serialSz);
  31965. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  31966. cs->thisDate, &thisDateLen);
  31967. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  31968. cs->nextDate, &nextDateLen);
  31969. /* TODO: decode revoked time and reason. */
  31970. /* Decode OCSP single response. */
  31971. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  31972. 1, source, ioIndex, size);
  31973. }
  31974. if (ret == 0) {
  31975. single->hashAlgoOID =
  31976. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  31977. ocspDigestSize = (word32)wc_HashGetDigestSize(
  31978. wc_OidGetHash((int)single->hashAlgoOID));
  31979. }
  31980. /* Validate the issuer hash length is the size required. */
  31981. if ((ret == 0) && (issuerHashLen != ocspDigestSize)) {
  31982. ret = ASN_PARSE_E;
  31983. }
  31984. /* Validate the issuer key hash length is the size required. */
  31985. if (ret == 0) {
  31986. if (issuerKeyHashLen != ocspDigestSize) {
  31987. ret = ASN_PARSE_E;
  31988. }
  31989. }
  31990. if (ret == 0) {
  31991. /* Store serial size. */
  31992. cs->serialSz = (int)serialSz;
  31993. /* Set the hash algorithm OID */
  31994. single->hashAlgoOID =
  31995. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  31996. /* Determine status by which item was found. */
  31997. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  31998. cs->status = CERT_GOOD;
  31999. }
  32000. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  32001. cs->status = CERT_REVOKED;
  32002. }
  32003. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  32004. cs->status = CERT_UNKNOWN;
  32005. }
  32006. /* Store the thisDate format - only one possible. */
  32007. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  32008. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  32009. /* Check date is a valid string and BEFORE now. */
  32010. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  32011. ret = ASN_BEFORE_DATE_E;
  32012. }
  32013. }
  32014. if (ret == 0) {
  32015. #endif
  32016. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  32017. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  32018. /* Store ASN.1 version of thisDate. */
  32019. cs->thisDateAsn = GetASNItem_Addr(
  32020. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  32021. at = &cs->thisDateParsed;
  32022. at->type = ASN_GENERALIZED_TIME;
  32023. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  32024. at->length = (int)thisDateLen;
  32025. #endif
  32026. }
  32027. if ((ret == 0) &&
  32028. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  32029. /* Store the nextDate format - only one possible. */
  32030. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  32031. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  32032. /* Check date is a valid string and AFTER now. */
  32033. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  32034. ret = ASN_AFTER_DATE_E;
  32035. }
  32036. }
  32037. if ((ret == 0) &&
  32038. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  32039. #endif
  32040. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  32041. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  32042. /* Store ASN.1 version of thisDate. */
  32043. cs->nextDateAsn = GetASNItem_Addr(
  32044. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  32045. at = &cs->nextDateParsed;
  32046. at->type = ASN_GENERALIZED_TIME;
  32047. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  32048. at->length = (int)nextDateLen;
  32049. #endif
  32050. }
  32051. if (ret == 0) {
  32052. /* OcspEntry now used. */
  32053. single->used = 1;
  32054. }
  32055. FREE_ASNGETDATA(dataASN, NULL);
  32056. return ret;
  32057. #endif
  32058. }
  32059. #ifdef WOLFSSL_ASN_TEMPLATE
  32060. /* ASN.1 template for OCSP response extension header.
  32061. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  32062. */
  32063. static const ASNItem respExtHdrASN[] = {
  32064. /* responseExtensions */
  32065. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  32066. /* extensions */
  32067. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32068. };
  32069. enum {
  32070. RESPEXTHDRASN_IDX_EXT = 0,
  32071. RESPEXTHDRASN_IDX_EXT_SEQ,
  32072. };
  32073. /* Number of items in ASN.1 template for OCSP response extension header. */
  32074. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  32075. #endif
  32076. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  32077. OcspResponse* resp, word32 sz)
  32078. {
  32079. #ifndef WOLFSSL_ASN_TEMPLATE
  32080. word32 idx = *ioIndex;
  32081. int length;
  32082. int ext_bound; /* boundary index for the sequence of extensions */
  32083. word32 oid;
  32084. int ret;
  32085. byte tag;
  32086. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  32087. if ((idx + 1) > sz)
  32088. return BUFFER_E;
  32089. if (GetASNTag(source, &idx, &tag, sz) < 0)
  32090. return ASN_PARSE_E;
  32091. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  32092. return ASN_PARSE_E;
  32093. if (GetLength(source, &idx, &length, sz) < 0)
  32094. return ASN_PARSE_E;
  32095. if (GetSequence(source, &idx, &length, sz) < 0)
  32096. return ASN_PARSE_E;
  32097. ext_bound = idx + length;
  32098. while (idx < (word32)ext_bound) {
  32099. word32 localIdx;
  32100. if (GetSequence(source, &idx, &length, sz) < 0) {
  32101. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32102. return ASN_PARSE_E;
  32103. }
  32104. oid = 0;
  32105. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  32106. WOLFSSL_MSG("\tfail: OBJECT ID");
  32107. return ASN_PARSE_E;
  32108. }
  32109. /* check for critical flag */
  32110. if ((idx + 1) > (word32)sz) {
  32111. WOLFSSL_MSG("\tfail: malformed buffer");
  32112. return BUFFER_E;
  32113. }
  32114. localIdx = idx;
  32115. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32116. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32117. ret = GetBoolean(source, &idx, sz);
  32118. if (ret < 0)
  32119. return ret;
  32120. }
  32121. ret = GetOctetString(source, &idx, &length, sz);
  32122. if (ret < 0)
  32123. return ret;
  32124. if (oid == OCSP_NONCE_OID) {
  32125. /* get data inside extra OCTET_STRING */
  32126. ret = GetOctetString(source, &idx, &length, sz);
  32127. if (ret < 0)
  32128. return ret;
  32129. resp->nonce = source + idx;
  32130. resp->nonceSz = length;
  32131. }
  32132. idx += length;
  32133. }
  32134. *ioIndex = idx;
  32135. return 0;
  32136. #else
  32137. /* certExtASN_Length is greater than respExtHdrASN_Length */
  32138. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32139. int ret = 0;
  32140. word32 idx = *ioIndex;
  32141. word32 maxIdx = 0;
  32142. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  32143. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  32144. if (ret == 0) {
  32145. /* Check for header and move past. */
  32146. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  32147. source, &idx, sz);
  32148. }
  32149. if (ret == 0) {
  32150. /* Keep end extensions index for total length check. */
  32151. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  32152. }
  32153. /* Step through all extensions. */
  32154. while ((ret == 0) && (idx < maxIdx)) {
  32155. /* Clear dynamic data, set OID type to expect. */
  32156. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32157. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  32158. /* TODO: check criticality. */
  32159. /* Decode OCSP response extension. */
  32160. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  32161. source, &idx, sz);
  32162. if (ret == 0) {
  32163. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32164. int length = (int)dataASN[CERTEXTASN_IDX_VAL].length;
  32165. if (oid == OCSP_NONCE_OID) {
  32166. /* Extract nonce data. */
  32167. ret = GetOctetString(source, &idx, &length, sz);
  32168. if (ret >= 0) {
  32169. ret = 0;
  32170. /* get data inside extra OCTET_STRING */
  32171. resp->nonce = source + idx;
  32172. resp->nonceSz = length;
  32173. }
  32174. }
  32175. /* Ignore all other extension types. */
  32176. /* Skip over rest of extension. */
  32177. idx += (word32)length;
  32178. }
  32179. }
  32180. /* Return index after extensions. */
  32181. *ioIndex = idx;
  32182. FREE_ASNGETDATA(dataASN, resp->heap);
  32183. return ret;
  32184. #endif
  32185. }
  32186. #ifdef WOLFSSL_ASN_TEMPLATE
  32187. /* ASN.1 template for OCSP ResponseData.
  32188. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  32189. */
  32190. static const ASNItem ocspRespDataASN[] = {
  32191. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32192. /* version DEFAULT v1 */
  32193. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32194. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  32195. /* byName */
  32196. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  32197. /* byKey */
  32198. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  32199. /* producedAt */
  32200. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  32201. /* responses */
  32202. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  32203. /* responseExtensions */
  32204. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  32205. };
  32206. enum {
  32207. OCSPRESPDATAASN_IDX_SEQ = 0,
  32208. OCSPRESPDATAASN_IDX_VER_PRESENT,
  32209. OCSPRESPDATAASN_IDX_VER,
  32210. OCSPRESPDATAASN_IDX_BYNAME,
  32211. OCSPRESPDATAASN_IDX_BYKEY,
  32212. OCSPRESPDATAASN_IDX_PA,
  32213. OCSPRESPDATAASN_IDX_RESP,
  32214. OCSPRESPDATAASN_IDX_RESPEXT,
  32215. };
  32216. /* Number of items in ASN.1 template for OCSP ResponseData. */
  32217. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  32218. #endif
  32219. static int DecodeResponseData(byte* source, word32* ioIndex,
  32220. OcspResponse* resp, word32 size)
  32221. {
  32222. #ifndef WOLFSSL_ASN_TEMPLATE
  32223. word32 idx = *ioIndex, prev_idx, localIdx;
  32224. int length;
  32225. int version;
  32226. int ret;
  32227. byte tag;
  32228. int wrapperSz;
  32229. OcspEntry* single;
  32230. WOLFSSL_ENTER("DecodeResponseData");
  32231. resp->response = source + idx;
  32232. prev_idx = idx;
  32233. if (GetSequence(source, &idx, &length, size) < 0)
  32234. return ASN_PARSE_E;
  32235. resp->responseSz = length + idx - prev_idx;
  32236. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  32237. * item isn't an EXPLICIT[0], then set version to zero and move
  32238. * onto the next item.
  32239. */
  32240. localIdx = idx;
  32241. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  32242. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  32243. {
  32244. idx += 2; /* Eat the value and length */
  32245. if (GetMyVersion(source, &idx, &version, size) < 0)
  32246. return ASN_PARSE_E;
  32247. } else
  32248. version = 0;
  32249. localIdx = idx;
  32250. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  32251. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  32252. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  32253. {
  32254. idx++; /* advance past ASN tag */
  32255. if (GetLength(source, &idx, &length, size) < 0)
  32256. return ASN_PARSE_E;
  32257. idx += length;
  32258. }
  32259. else
  32260. return ASN_PARSE_E;
  32261. /* save pointer to the producedAt time */
  32262. if (GetBasicDate(source, &idx, resp->producedDate,
  32263. &resp->producedDateFormat, size) < 0)
  32264. return ASN_PARSE_E;
  32265. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  32266. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  32267. return ASN_PARSE_E;
  32268. localIdx = idx;
  32269. single = resp->single;
  32270. while (idx - localIdx < (word32)wrapperSz) {
  32271. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  32272. if (ret < 0)
  32273. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  32274. if (idx - localIdx < (word32)wrapperSz) {
  32275. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  32276. DYNAMIC_TYPE_OCSP_ENTRY);
  32277. if (single->next == NULL) {
  32278. return MEMORY_E;
  32279. }
  32280. XMEMSET(single->next, 0, sizeof(OcspEntry));
  32281. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  32282. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  32283. if (single->next->status == NULL) {
  32284. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  32285. single->next = NULL;
  32286. return MEMORY_E;
  32287. }
  32288. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  32289. single->next->isDynamic = 1;
  32290. single = single->next;
  32291. }
  32292. }
  32293. /*
  32294. * Check the length of the ResponseData against the current index to
  32295. * see if there are extensions, they are optional.
  32296. */
  32297. if (idx - prev_idx < resp->responseSz)
  32298. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  32299. return ASN_PARSE_E;
  32300. *ioIndex = idx;
  32301. return 0;
  32302. #else
  32303. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  32304. int ret = 0;
  32305. byte version;
  32306. word32 dateSz = 0;
  32307. word32 idx = *ioIndex;
  32308. OcspEntry* single = NULL;
  32309. WOLFSSL_ENTER("DecodeResponseData");
  32310. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  32311. if (ret == 0) {
  32312. resp->response = source + idx;
  32313. /* Default, not present, is v1 = 0. */
  32314. version = 0;
  32315. /* Max size of date supported. */
  32316. dateSz = MAX_DATE_SIZE;
  32317. /* Set the where to put version an produced date. */
  32318. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  32319. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  32320. &dateSz);
  32321. /* Decode the ResponseData. */
  32322. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  32323. 1, source, ioIndex, size);
  32324. }
  32325. /* Only support v1 == 0 */
  32326. if (ret == 0) {
  32327. if (version != 0) {
  32328. ret = ASN_PARSE_E;
  32329. }
  32330. }
  32331. /* Ensure date is a minimal size. */
  32332. if (ret == 0) {
  32333. if (dateSz < MIN_DATE_SIZE) {
  32334. ret = ASN_PARSE_E;
  32335. }
  32336. }
  32337. if (ret == 0) {
  32338. /* TODO: use byName/byKey fields. */
  32339. /* Store size of response. */
  32340. resp->responseSz = *ioIndex - idx;
  32341. /* Store date format/tag. */
  32342. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  32343. /* Get the index of the responses SEQUENCE. */
  32344. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  32345. /* Start with the pre-existing OcspEntry. */
  32346. single = resp->single;
  32347. }
  32348. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  32349. /* Allocate and use a new OCSP entry if this is used. */
  32350. if (single->used) {
  32351. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  32352. DYNAMIC_TYPE_OCSP_ENTRY);
  32353. if (single->next == NULL) {
  32354. ret = MEMORY_E;
  32355. }
  32356. else {
  32357. XMEMSET(single->next, 0, sizeof(OcspEntry));
  32358. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  32359. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  32360. if (single->next->status == NULL) {
  32361. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  32362. single->next = NULL;
  32363. ret = MEMORY_E;
  32364. }
  32365. else {
  32366. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  32367. /* Entry to be freed. */
  32368. single->next->isDynamic = 1;
  32369. /* used will be 0 (false) */
  32370. single = single->next;
  32371. }
  32372. }
  32373. }
  32374. if (ret == 0) {
  32375. /* Decode SingleResponse into OcspEntry. */
  32376. ret = DecodeSingleResponse(source, &idx,
  32377. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  32378. (int)dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  32379. /* single->used set on successful decode. */
  32380. }
  32381. }
  32382. /* Check if there were extensions. */
  32383. if ((ret == 0) &&
  32384. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  32385. /* Get index of [1] */
  32386. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  32387. /* Decode the response extensions. */
  32388. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  32389. ret = ASN_PARSE_E;
  32390. }
  32391. }
  32392. FREE_ASNGETDATA(dataASN, resp->heap);
  32393. return ret;
  32394. #endif
  32395. }
  32396. #ifndef WOLFSSL_ASN_TEMPLATE
  32397. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32398. static int DecodeCerts(byte* source,
  32399. word32* ioIndex, OcspResponse* resp, word32 size)
  32400. {
  32401. word32 idx = *ioIndex;
  32402. byte tag;
  32403. WOLFSSL_ENTER("DecodeCerts");
  32404. if (GetASNTag(source, &idx, &tag, size) < 0)
  32405. return ASN_PARSE_E;
  32406. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  32407. {
  32408. int length;
  32409. if (GetLength(source, &idx, &length, size) < 0)
  32410. return ASN_PARSE_E;
  32411. if (GetSequence(source, &idx, &length, size) < 0)
  32412. return ASN_PARSE_E;
  32413. resp->cert = source + idx;
  32414. resp->certSz = length;
  32415. idx += length;
  32416. }
  32417. *ioIndex = idx;
  32418. return 0;
  32419. }
  32420. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  32421. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32422. #ifdef WOLFSSL_ASN_TEMPLATE
  32423. /* ASN.1 template for BasicOCSPResponse.
  32424. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  32425. */
  32426. static const ASNItem ocspBasicRespASN[] = {
  32427. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32428. /* tbsResponseData */
  32429. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  32430. /* signatureAlgorithm */
  32431. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  32432. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32433. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32434. /* parameters */
  32435. #ifdef WC_RSA_PSS
  32436. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32437. #endif
  32438. /* signature */
  32439. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32440. /* certs */
  32441. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32442. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  32443. };
  32444. enum {
  32445. OCSPBASICRESPASN_IDX_SEQ = 0,
  32446. OCSPBASICRESPASN_IDX_TBS_SEQ,
  32447. OCSPBASICRESPASN_IDX_SIGALGO,
  32448. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  32449. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  32450. #ifdef WC_RSA_PSS
  32451. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  32452. #endif
  32453. OCSPBASICRESPASN_IDX_SIGNATURE,
  32454. OCSPBASICRESPASN_IDX_CERTS,
  32455. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  32456. };
  32457. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  32458. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  32459. #endif /* WOLFSSL_ASN_TEMPLATE */
  32460. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  32461. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  32462. {
  32463. #ifndef WOLFSSL_ASN_TEMPLATE
  32464. int length;
  32465. word32 idx = *ioIndex;
  32466. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32467. word32 end_index;
  32468. #endif
  32469. int ret;
  32470. int sigLength;
  32471. const byte* sigParams = NULL;
  32472. word32 sigParamsSz = 0;
  32473. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  32474. (void)heap;
  32475. if (GetSequence(source, &idx, &length, size) < 0)
  32476. return ASN_PARSE_E;
  32477. if (idx + length > size)
  32478. return ASN_INPUT_E;
  32479. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32480. end_index = idx + length;
  32481. #endif
  32482. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  32483. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  32484. /* Get the signature algorithm */
  32485. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  32486. return ASN_PARSE_E;
  32487. }
  32488. #ifdef WC_RSA_PSS
  32489. else if (resp->sigOID == CTC_RSASSAPSS) {
  32490. word32 sz;
  32491. int len;
  32492. const byte* params;
  32493. sz = idx;
  32494. params = source + idx;
  32495. if (GetSequence(source, &idx, &len, size) < 0)
  32496. ret = ASN_PARSE_E;
  32497. if (ret == 0) {
  32498. idx += len;
  32499. sigParams = params;
  32500. sigParamsSz = idx - sz;
  32501. }
  32502. }
  32503. #endif
  32504. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  32505. if (ret != 0)
  32506. return ret;
  32507. resp->sigSz = sigLength;
  32508. resp->sig = source + idx;
  32509. idx += sigLength;
  32510. /*
  32511. * Check the length of the BasicOcspResponse against the current index to
  32512. * see if there are certificates, they are optional.
  32513. */
  32514. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32515. if (idx < end_index)
  32516. {
  32517. int cert_inited = 0;
  32518. #ifdef WOLFSSL_SMALL_STACK
  32519. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  32520. DYNAMIC_TYPE_TMP_BUFFER);
  32521. if (cert == NULL)
  32522. return MEMORY_E;
  32523. #else
  32524. DecodedCert cert[1];
  32525. #endif
  32526. do {
  32527. if (DecodeCerts(source, &idx, resp, size) < 0) {
  32528. ret = ASN_PARSE_E;
  32529. break;
  32530. }
  32531. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  32532. cert_inited = 1;
  32533. /* Don't verify if we don't have access to Cert Manager. */
  32534. ret = ParseCertRelative(cert, CERT_TYPE,
  32535. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  32536. cm);
  32537. if (ret < 0) {
  32538. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  32539. break;
  32540. }
  32541. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  32542. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  32543. if (XMEMCMP(cert->subjectHash,
  32544. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  32545. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  32546. }
  32547. else {
  32548. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  32549. #ifdef OPENSSL_EXTRA
  32550. resp->verifyError = OCSP_BAD_ISSUER;
  32551. #else
  32552. ret = BAD_OCSP_RESPONDER;
  32553. break;
  32554. #endif
  32555. }
  32556. }
  32557. #endif
  32558. /* ConfirmSignature is blocking here */
  32559. ret = ConfirmSignature(
  32560. &cert->sigCtx,
  32561. resp->response, resp->responseSz,
  32562. cert->publicKey, cert->pubKeySize, cert->keyOID,
  32563. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  32564. NULL);
  32565. if (ret != 0) {
  32566. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  32567. ret = ASN_OCSP_CONFIRM_E;
  32568. break;
  32569. }
  32570. } while(0);
  32571. if (cert_inited)
  32572. FreeDecodedCert(cert);
  32573. #ifdef WOLFSSL_SMALL_STACK
  32574. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  32575. #endif
  32576. if (ret != 0)
  32577. return ret;
  32578. }
  32579. else
  32580. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  32581. {
  32582. Signer* ca;
  32583. int sigValid = -1;
  32584. #ifndef NO_SKID
  32585. ca = GetCA(cm, resp->single->issuerKeyHash);
  32586. #else
  32587. ca = GetCA(cm, resp->single->issuerHash);
  32588. #endif
  32589. if (ca) {
  32590. SignatureCtx sigCtx;
  32591. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  32592. /* ConfirmSignature is blocking here */
  32593. sigValid = ConfirmSignature(&sigCtx, resp->response,
  32594. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  32595. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  32596. NULL);
  32597. }
  32598. if (ca == NULL || sigValid != 0) {
  32599. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  32600. return ASN_OCSP_CONFIRM_E;
  32601. }
  32602. (void)noVerify;
  32603. }
  32604. *ioIndex = idx;
  32605. return 0;
  32606. #else
  32607. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  32608. int ret = 0;
  32609. word32 idx = *ioIndex;
  32610. const byte* sigParams = NULL;
  32611. word32 sigParamsSz = 0;
  32612. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32613. #ifdef WOLFSSL_SMALL_STACK
  32614. DecodedCert* cert = NULL;
  32615. #else
  32616. DecodedCert cert[1];
  32617. #endif
  32618. int certInit = 0;
  32619. #endif
  32620. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  32621. (void)heap;
  32622. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  32623. if (ret == 0) {
  32624. /* Set expecting signature OID. */
  32625. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  32626. /* Decode BasicOCSPResponse. */
  32627. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  32628. 1, source, &idx, size);
  32629. }
  32630. if (ret == 0) {
  32631. word32 dataIdx = 0;
  32632. /* Decode the response data. */
  32633. ret = DecodeResponseData(
  32634. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  32635. &dataIdx, resp,
  32636. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  32637. );
  32638. }
  32639. #ifdef WC_RSA_PSS
  32640. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  32641. sigParams = GetASNItem_Addr(
  32642. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  32643. source);
  32644. sigParamsSz =
  32645. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  32646. source);
  32647. }
  32648. #endif
  32649. if (ret == 0) {
  32650. /* Get the signature OID and signature. */
  32651. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  32652. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  32653. &resp->sigSz);
  32654. }
  32655. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32656. if ((ret == 0) &&
  32657. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  32658. /* TODO: support more than one certificate. */
  32659. /* Store reference to certificate BER data. */
  32660. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  32661. &resp->certSz);
  32662. /* Allocate a certificate object to decode cert into. */
  32663. #ifdef WOLFSSL_SMALL_STACK
  32664. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  32665. DYNAMIC_TYPE_TMP_BUFFER);
  32666. if (cert == NULL) {
  32667. ret = MEMORY_E;
  32668. }
  32669. }
  32670. if ((ret == 0) &&
  32671. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  32672. #endif
  32673. /* Initialize the certificate object. */
  32674. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  32675. certInit = 1;
  32676. /* Parse the certificate and don't verify if we don't have access to
  32677. * Cert Manager. */
  32678. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  32679. cm);
  32680. if (ret < 0) {
  32681. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  32682. }
  32683. }
  32684. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  32685. if ((ret == 0) &&
  32686. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL) &&
  32687. !noVerify) {
  32688. ret = CheckOcspResponder(resp, cert, cm);
  32689. }
  32690. #endif /* WOLFSSL_NO_OCSP_ISSUER_CHECK */
  32691. if ((ret == 0) &&
  32692. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  32693. /* TODO: ConfirmSignature is blocking here */
  32694. /* Check the signature of the response. */
  32695. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  32696. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  32697. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  32698. if (ret != 0) {
  32699. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  32700. ret = ASN_OCSP_CONFIRM_E;
  32701. }
  32702. }
  32703. if ((ret == 0) &&
  32704. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  32705. #else
  32706. if (ret == 0)
  32707. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  32708. {
  32709. Signer* ca;
  32710. int sigValid = -1;
  32711. /* Response didn't have a certificate - lookup CA. */
  32712. #ifndef NO_SKID
  32713. ca = GetCA(cm, resp->single->issuerKeyHash);
  32714. #else
  32715. ca = GetCA(cm, resp->single->issuerHash);
  32716. #endif
  32717. if (ca) {
  32718. SignatureCtx sigCtx;
  32719. /* Initialize he signature context. */
  32720. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  32721. /* TODO: ConfirmSignature is blocking here */
  32722. /* Check the signature of the response CA public key. */
  32723. sigValid = ConfirmSignature(&sigCtx, resp->response,
  32724. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  32725. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  32726. NULL);
  32727. }
  32728. if ((ca == NULL) || (sigValid != 0)) {
  32729. /* Didn't find certificate or signature verificate failed. */
  32730. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  32731. ret = ASN_OCSP_CONFIRM_E;
  32732. }
  32733. }
  32734. if (ret == 0) {
  32735. /* Update the position to after response data. */
  32736. *ioIndex = idx;
  32737. }
  32738. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  32739. if (certInit) {
  32740. FreeDecodedCert(cert);
  32741. }
  32742. #ifdef WOLFSSL_SMALL_STACK
  32743. if (cert != NULL) {
  32744. /* Dispose of certificate object. */
  32745. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  32746. }
  32747. #endif
  32748. #endif
  32749. FREE_ASNGETDATA(dataASN, heap);
  32750. return ret;
  32751. #endif /* WOLFSSL_ASN_TEMPLATE */
  32752. }
  32753. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  32754. byte* source, word32 inSz, void* heap)
  32755. {
  32756. WOLFSSL_ENTER("InitOcspResponse");
  32757. XMEMSET(status, 0, sizeof(CertStatus));
  32758. XMEMSET(single, 0, sizeof(OcspEntry));
  32759. XMEMSET(resp, 0, sizeof(OcspResponse));
  32760. single->status = status;
  32761. resp->responseStatus = -1;
  32762. resp->single = single;
  32763. resp->source = source;
  32764. resp->maxIdx = inSz;
  32765. resp->heap = heap;
  32766. }
  32767. void FreeOcspResponse(OcspResponse* resp)
  32768. {
  32769. OcspEntry *single, *next;
  32770. if (resp != NULL) {
  32771. for (single = resp->single; single; single = next) {
  32772. next = single->next;
  32773. if (single->isDynamic) {
  32774. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  32775. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  32776. }
  32777. }
  32778. }
  32779. }
  32780. #ifdef WOLFSSL_ASN_TEMPLATE
  32781. /* ASN.1 template for OCSPResponse.
  32782. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  32783. */
  32784. static const ASNItem ocspResponseASN[] = {
  32785. /* OCSPResponse ::= SEQUENCE */
  32786. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32787. /* responseStatus OCSPResponseStatus */
  32788. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  32789. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  32790. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32791. /* ResponseBytes ::= SEQUENCE */
  32792. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32793. /* responseType OBJECT IDENTIFIER */
  32794. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32795. /* response OCTET STRING */
  32796. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  32797. };
  32798. enum {
  32799. OCSPRESPONSEASN_IDX_SEQ = 0,
  32800. OCSPRESPONSEASN_IDX_STATUS,
  32801. OCSPRESPONSEASN_IDX_BYTES,
  32802. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  32803. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  32804. OCSPRESPONSEASN_IDX_BYTES_VAL,
  32805. };
  32806. /* Number of items in ASN.1 template for OCSPResponse. */
  32807. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  32808. #endif /* WOLFSSL_ASN_TEMPLATE */
  32809. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  32810. {
  32811. #ifndef WOLFSSL_ASN_TEMPLATE
  32812. int ret;
  32813. int length = 0;
  32814. word32 idx = 0;
  32815. byte* source = resp->source;
  32816. word32 size = resp->maxIdx;
  32817. word32 oid;
  32818. byte tag;
  32819. WOLFSSL_ENTER("OcspResponseDecode");
  32820. /* peel the outer SEQUENCE wrapper */
  32821. if (GetSequence(source, &idx, &length, size) < 0) {
  32822. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32823. return ASN_PARSE_E;
  32824. }
  32825. /* First get the responseStatus, an ENUMERATED */
  32826. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  32827. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32828. return ASN_PARSE_E;
  32829. }
  32830. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  32831. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  32832. return 0;
  32833. }
  32834. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  32835. if (idx >= size) {
  32836. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32837. return ASN_PARSE_E;
  32838. }
  32839. if (GetASNTag(source, &idx, &tag, size) < 0) {
  32840. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32841. return ASN_PARSE_E;
  32842. }
  32843. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  32844. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32845. return ASN_PARSE_E;
  32846. }
  32847. if (GetLength(source, &idx, &length, size) < 0) {
  32848. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32849. return ASN_PARSE_E;
  32850. }
  32851. /* Get the responseBytes SEQUENCE */
  32852. if (GetSequence(source, &idx, &length, size) < 0) {
  32853. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32854. return ASN_PARSE_E;
  32855. }
  32856. /* Check ObjectID for the resposeBytes */
  32857. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  32858. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32859. return ASN_PARSE_E;
  32860. }
  32861. if (oid != OCSP_BASIC_OID) {
  32862. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32863. return ASN_PARSE_E;
  32864. }
  32865. ret = GetOctetString(source, &idx, &length, size);
  32866. if (ret < 0) {
  32867. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  32868. return ret;
  32869. }
  32870. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  32871. if (ret < 0) {
  32872. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  32873. return ret;
  32874. }
  32875. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  32876. return 0;
  32877. #else
  32878. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  32879. int ret = 0;
  32880. word32 idx = 0, size = resp->maxIdx;
  32881. byte* source = resp->source;
  32882. byte status = 0;
  32883. byte* basic;
  32884. word32 basicSz;
  32885. WOLFSSL_ENTER("OcspResponseDecode");
  32886. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  32887. if (ret == 0) {
  32888. /* Set variable to put status in and expect OCSP OID. */
  32889. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  32890. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  32891. /* Decode OCSPResponse (and ResponseBytes). */
  32892. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  32893. source, &idx, size);
  32894. }
  32895. if (ret == 0) {
  32896. /* Get response. */
  32897. resp->responseStatus = status;
  32898. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  32899. == OCSP_BASIC_OID) {
  32900. /* Get reference to BasicOCSPResponse. */
  32901. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  32902. &basicSz);
  32903. idx = 0;
  32904. /* Decode BasicOCSPResponse. */
  32905. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  32906. noVerify);
  32907. }
  32908. /* Only support BasicOCSPResponse. */
  32909. else {
  32910. ret = ASN_PARSE_E;
  32911. }
  32912. }
  32913. FREE_ASNGETDATA(dataASN, resp->heap);
  32914. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  32915. return ret;
  32916. #endif /* WOLFSSL_ASN_TEMPLATE */
  32917. }
  32918. #ifdef WOLFSSL_ASN_TEMPLATE
  32919. /* ASN.1 template for OCSP nonce extension.
  32920. * RFC 6960, 4.4.1 - Nonce
  32921. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  32922. */
  32923. static const ASNItem ocspNonceExtASN[] = {
  32924. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32925. /* Extension */
  32926. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32927. /* extnId */
  32928. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  32929. /* critical not encoded. */
  32930. /* extnValue */
  32931. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  32932. /* nonce */
  32933. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  32934. };
  32935. enum {
  32936. OCSPNONCEEXTASN_IDX_SEQ = 0,
  32937. OCSPNONCEEXTASN_IDX_EXT,
  32938. OCSPNONCEEXTASN_IDX_EXT_OID,
  32939. OCSPNONCEEXTASN_IDX_EXT_VAL,
  32940. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  32941. };
  32942. /* Number of items in ASN.1 template for OCSP nonce extension. */
  32943. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  32944. #endif /* WOLFSSL_ASN_TEMPLATE */
  32945. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  32946. {
  32947. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  32948. 0x30, 0x01, 0x02 };
  32949. #ifndef WOLFSSL_ASN_TEMPLATE
  32950. byte seqArray[5][MAX_SEQ_SZ];
  32951. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  32952. WOLFSSL_ENTER("SetOcspReqExtensions");
  32953. if (!req || !output || !req->nonceSz)
  32954. return 0;
  32955. totalSz += req->nonceSz;
  32956. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  32957. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  32958. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  32959. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  32960. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  32961. if (totalSz > size)
  32962. return 0;
  32963. totalSz = 0;
  32964. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  32965. totalSz += seqSz[4];
  32966. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  32967. totalSz += seqSz[3];
  32968. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  32969. totalSz += seqSz[2];
  32970. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  32971. totalSz += (word32)sizeof(NonceObjId);
  32972. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  32973. totalSz += seqSz[1];
  32974. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  32975. totalSz += seqSz[0];
  32976. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  32977. totalSz += req->nonceSz;
  32978. return totalSz;
  32979. #else
  32980. int ret = 0;
  32981. WOLFSSL_ENTER("SetOcspReqExtensions");
  32982. /* Check request has nonce to write in extension. */
  32983. if (req != NULL && req->nonceSz != 0) {
  32984. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  32985. int sz = 0;
  32986. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  32987. if (ret == 0) {
  32988. /* Set nonce extension OID and nonce. */
  32989. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  32990. sizeof(NonceObjId));
  32991. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  32992. (word32)req->nonceSz);
  32993. /* Calculate size of nonce extension. */
  32994. ret = SizeASN_Items(ocspNonceExtASN, dataASN,
  32995. ocspNonceExtASN_Length, &sz);
  32996. }
  32997. /* Check buffer big enough for encoding if supplied. */
  32998. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  32999. ret = BUFFER_E;
  33000. }
  33001. if ((ret == 0) && (output != NULL)) {
  33002. /* Encode nonce extension. */
  33003. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  33004. output);
  33005. }
  33006. if (ret == 0) {
  33007. /* Return size of encoding. */
  33008. ret = sz;
  33009. }
  33010. FREE_ASNSETDATA(dataASN, req->heap);
  33011. }
  33012. return (word32)ret;
  33013. #endif /* WOLFSSL_ASN_TEMPLATE */
  33014. }
  33015. #ifdef WOLFSSL_ASN_TEMPLATE
  33016. /* ASN.1 template for OCSPRequest.
  33017. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  33018. */
  33019. static const ASNItem ocspRequestASN[] = {
  33020. /* OCSPRequest */
  33021. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  33022. /* tbsRequest */
  33023. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  33024. /* version not written - v1 */
  33025. /* requestorName not written */
  33026. /* requestList */
  33027. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  33028. /* Request */
  33029. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  33030. /* reqCert */
  33031. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  33032. /* hashAlgorithm */
  33033. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  33034. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  33035. /* issuerNameHash */
  33036. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  33037. /* issuerKeyHash */
  33038. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  33039. /* serialNumber */
  33040. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  33041. /* requestExtensions */
  33042. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  33043. /* optionalSignature not written. */
  33044. };
  33045. enum {
  33046. OCSPREQUESTASN_IDX_SEQ = 0,
  33047. OCSPREQUESTASN_IDX_TBS,
  33048. OCSPREQUESTASN_IDX_TBS_SEQ,
  33049. OCSPREQUESTASN_IDX_TBS_LIST,
  33050. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  33051. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  33052. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  33053. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  33054. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  33055. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  33056. OCSPREQUESTASN_IDX_TBS_REQEXT,
  33057. };
  33058. /* Number of items in ASN.1 template for OCSPRequest. */
  33059. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  33060. #endif
  33061. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  33062. {
  33063. #ifndef WOLFSSL_ASN_TEMPLATE
  33064. byte seqArray[5][MAX_SEQ_SZ];
  33065. /* The ASN.1 of the OCSP Request is an onion of sequences */
  33066. byte algoArray[MAX_ALGO_SZ];
  33067. byte issuerArray[MAX_ENCODED_DIG_SZ];
  33068. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  33069. byte snArray[MAX_SN_SZ];
  33070. byte extArray[MAX_OCSP_EXT_SZ];
  33071. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  33072. int i, snSz;
  33073. int keyIdSz;
  33074. WOLFSSL_ENTER("EncodeOcspRequest");
  33075. #ifdef NO_SHA
  33076. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  33077. keyIdSz = WC_SHA256_DIGEST_SIZE;
  33078. #else
  33079. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  33080. keyIdSz = WC_SHA_DIGEST_SIZE;
  33081. #endif
  33082. issuerSz = SetDigest(req->issuerHash, keyIdSz, issuerArray);
  33083. issuerKeySz = SetDigest(req->issuerKeyHash, keyIdSz, issuerKeyArray);
  33084. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  33085. MAX_SN_SZ, MAX_SN_SZ);
  33086. extSz = 0;
  33087. if (snSz < 0)
  33088. return snSz;
  33089. if (req->nonceSz) {
  33090. /* TLS Extensions use this function too - put extensions after
  33091. * ASN.1: Context Specific [2].
  33092. */
  33093. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  33094. OCSP_NONCE_EXT_SZ);
  33095. extSz += SetExplicit(2, extSz, extArray, 0);
  33096. }
  33097. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  33098. for (i = 4; i >= 0; i--) {
  33099. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  33100. totalSz += seqSz[i];
  33101. if (i == 2) totalSz += extSz;
  33102. }
  33103. if (output == NULL)
  33104. return totalSz;
  33105. if (totalSz > size)
  33106. return BUFFER_E;
  33107. totalSz = 0;
  33108. for (i = 0; i < 5; i++) {
  33109. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  33110. totalSz += seqSz[i];
  33111. }
  33112. XMEMCPY(output + totalSz, algoArray, algoSz);
  33113. totalSz += algoSz;
  33114. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  33115. totalSz += issuerSz;
  33116. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  33117. totalSz += issuerKeySz;
  33118. XMEMCPY(output + totalSz, snArray, snSz);
  33119. totalSz += snSz;
  33120. if (extSz != 0) {
  33121. XMEMCPY(output + totalSz, extArray, extSz);
  33122. totalSz += extSz;
  33123. }
  33124. return totalSz;
  33125. #else
  33126. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  33127. word32 extSz = 0;
  33128. int sz = 0;
  33129. int ret = 0;
  33130. word32 keyIdSz;
  33131. WOLFSSL_ENTER("EncodeOcspRequest");
  33132. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  33133. if (ret == 0) {
  33134. /* Set OID of hash algorithm use on issuer and key. */
  33135. #ifdef NO_SHA
  33136. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  33137. oidHashType);
  33138. keyIdSz = WC_SHA256_DIGEST_SIZE;
  33139. #else
  33140. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  33141. oidHashType);
  33142. keyIdSz = WC_SHA_DIGEST_SIZE;
  33143. #endif
  33144. /* Set issuer, issuer key hash and serial number of certificate being
  33145. * checked. */
  33146. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  33147. req->issuerHash, keyIdSz);
  33148. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  33149. req->issuerKeyHash, keyIdSz);
  33150. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  33151. req->serial, (word32)req->serialSz);
  33152. /* Only extension to write is nonce - check if one to encode. */
  33153. if (req->nonceSz) {
  33154. /* Get size of extensions and leave space for them in encoding. */
  33155. ret = (int)(extSz = EncodeOcspRequestExtensions(req, NULL, 0));
  33156. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  33157. if (ret > 0) {
  33158. ret = 0;
  33159. }
  33160. }
  33161. else {
  33162. /* Don't write out extensions. */
  33163. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  33164. }
  33165. }
  33166. if (ret == 0) {
  33167. /* Calculate size of encoding. */
  33168. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  33169. &sz);
  33170. }
  33171. /* Check buffer big enough for encoding if supplied. */
  33172. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  33173. ret = BUFFER_E;
  33174. }
  33175. if ((ret == 0) && (output != NULL)) {
  33176. /* Encode OCSPRequest. */
  33177. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  33178. if (req->nonceSz) {
  33179. /* Encode extensions into space provided. */
  33180. ret = (int)EncodeOcspRequestExtensions(req,
  33181. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  33182. extSz);
  33183. if (ret > 0) {
  33184. ret = 0;
  33185. }
  33186. }
  33187. }
  33188. if (ret == 0) {
  33189. /* Return size of encoding. */
  33190. ret = sz;
  33191. }
  33192. FREE_ASNSETDATA(dataASN, req->heap);
  33193. return ret;
  33194. #endif /* WOLFSSL_ASN_TEMPLATE */
  33195. }
  33196. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  33197. void* heap)
  33198. {
  33199. int ret;
  33200. WOLFSSL_ENTER("InitOcspRequest");
  33201. if (req == NULL)
  33202. return BAD_FUNC_ARG;
  33203. XMEMSET(req, 0, sizeof(OcspRequest));
  33204. req->heap = heap;
  33205. if (cert) {
  33206. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  33207. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  33208. req->serial = (byte*)XMALLOC((size_t)cert->serialSz, req->heap,
  33209. DYNAMIC_TYPE_OCSP_REQUEST);
  33210. if (req->serial == NULL)
  33211. return MEMORY_E;
  33212. XMEMCPY(req->serial, cert->serial, (size_t)cert->serialSz);
  33213. req->serialSz = cert->serialSz;
  33214. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  33215. req->url = (byte*)XMALLOC((size_t)cert->extAuthInfoSz + 1,
  33216. req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  33217. if (req->url == NULL) {
  33218. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  33219. req->serial = NULL;
  33220. return MEMORY_E;
  33221. }
  33222. XMEMCPY(req->url, cert->extAuthInfo, (size_t)cert->extAuthInfoSz);
  33223. req->urlSz = cert->extAuthInfoSz;
  33224. req->url[req->urlSz] = 0;
  33225. }
  33226. }
  33227. if (useNonce) {
  33228. WC_RNG rng;
  33229. #ifndef HAVE_FIPS
  33230. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  33231. #else
  33232. ret = wc_InitRng(&rng);
  33233. #endif
  33234. if (ret != 0) {
  33235. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  33236. } else {
  33237. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  33238. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  33239. else
  33240. req->nonceSz = MAX_OCSP_NONCE_SZ;
  33241. wc_FreeRng(&rng);
  33242. }
  33243. }
  33244. return 0;
  33245. }
  33246. void FreeOcspRequest(OcspRequest* req)
  33247. {
  33248. WOLFSSL_ENTER("FreeOcspRequest");
  33249. if (req) {
  33250. if (req->serial)
  33251. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  33252. req->serial = NULL;
  33253. #ifdef OPENSSL_EXTRA
  33254. if (req->serialInt) {
  33255. if (req->serialInt->isDynamic) {
  33256. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  33257. }
  33258. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  33259. }
  33260. req->serialInt = NULL;
  33261. #endif
  33262. if (req->url)
  33263. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  33264. req->url = NULL;
  33265. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  33266. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_APACHE_HTTPD) || \
  33267. defined(HAVE_LIGHTY)
  33268. if (req->cid != NULL)
  33269. wolfSSL_OCSP_CERTID_free((WOLFSSL_OCSP_CERTID*)req->cid);
  33270. req->cid = NULL;
  33271. #endif
  33272. }
  33273. }
  33274. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  33275. {
  33276. int cmp = -1; /* default as not matching, cmp gets set on each check */
  33277. int ocspDigestSize;
  33278. OcspEntry *single, *next, *prev = NULL, *top;
  33279. WOLFSSL_ENTER("CompareOcspReqResp");
  33280. if (req == NULL) {
  33281. WOLFSSL_MSG("\tReq missing");
  33282. return -1;
  33283. }
  33284. if (resp == NULL || resp->single == NULL) {
  33285. WOLFSSL_MSG("\tResp missing");
  33286. return 1;
  33287. }
  33288. /* Nonces are not critical. The responder may not necessarily add
  33289. * the nonce to the response. */
  33290. if (req->nonceSz && resp->nonce != NULL
  33291. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  33292. && resp->nonceSz != 0
  33293. #endif
  33294. ) {
  33295. cmp = req->nonceSz - resp->nonceSz;
  33296. if (cmp != 0) {
  33297. WOLFSSL_MSG("\tnonceSz mismatch");
  33298. return cmp;
  33299. }
  33300. cmp = XMEMCMP(req->nonce, resp->nonce, (size_t)req->nonceSz);
  33301. if (cmp != 0) {
  33302. WOLFSSL_MSG("\tnonce mismatch");
  33303. return cmp;
  33304. }
  33305. }
  33306. /* match based on found status and return */
  33307. for (single = resp->single; single; single = next) {
  33308. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  33309. ocspDigestSize = wc_HashGetDigestSize(
  33310. wc_OidGetHash(single->hashAlgoOID));
  33311. #else
  33312. ocspDigestSize = OCSP_DIGEST_SIZE;
  33313. #endif
  33314. cmp = req->serialSz - single->status->serialSz;
  33315. if (cmp == 0) {
  33316. cmp = XMEMCMP(req->serial, single->status->serial,
  33317. (size_t)req->serialSz)
  33318. || XMEMCMP(req->issuerHash, single->issuerHash,
  33319. (size_t)ocspDigestSize)
  33320. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash,
  33321. (size_t)ocspDigestSize);
  33322. if (cmp == 0) {
  33323. /* match found */
  33324. if (resp->single != single && prev) {
  33325. /* move to top of list */
  33326. top = resp->single;
  33327. resp->single = single;
  33328. prev->next = single->next;
  33329. single->next = top;
  33330. }
  33331. break;
  33332. }
  33333. }
  33334. next = single->next;
  33335. prev = single;
  33336. }
  33337. if (cmp != 0) {
  33338. WOLFSSL_MSG("\trequest and response mismatch");
  33339. return cmp;
  33340. }
  33341. return 0;
  33342. }
  33343. #endif /* HAVE_OCSP */
  33344. #ifdef WOLFSSL_ASN_TEMPLATE
  33345. /* ASN.1 template for certificate name hash. */
  33346. static const ASNItem nameHashASN[] = {
  33347. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  33348. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  33349. };
  33350. enum {
  33351. NAMEHASHASN_IDX_OID = 0,
  33352. NAMEHASHASN_IDX_NAME
  33353. };
  33354. /* Number of items in ASN.1 template for certificate name hash. */
  33355. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  33356. #endif /* WOLFSSL_ASN_TEMPLATE */
  33357. /* store WC_SHA hash of NAME */
  33358. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  33359. {
  33360. /* Use summy signature OID. */
  33361. return GetNameHash_ex(source, idx, hash, maxIdx, 0);
  33362. }
  33363. /* store WC_SHA hash of NAME */
  33364. int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx,
  33365. word32 sigOID)
  33366. {
  33367. #ifndef WOLFSSL_ASN_TEMPLATE
  33368. int length; /* length of all distinguished names */
  33369. int ret;
  33370. word32 dummy;
  33371. byte tag;
  33372. WOLFSSL_ENTER("GetNameHash");
  33373. dummy = *idx;
  33374. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  33375. tag == ASN_OBJECT_ID) {
  33376. WOLFSSL_MSG("Trying optional prefix...");
  33377. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  33378. return ASN_PARSE_E;
  33379. *idx += (word32)length;
  33380. WOLFSSL_MSG("Got optional prefix");
  33381. }
  33382. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  33383. * calculated over the entire DER encoding of the Name field, including
  33384. * the tag and length. */
  33385. dummy = *idx;
  33386. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  33387. return ASN_PARSE_E;
  33388. ret = CalcHashId_ex(source + dummy, (word32)length + *idx - dummy, hash,
  33389. HashIdAlg(sigOID));
  33390. *idx += (word32)length;
  33391. return ret;
  33392. #else
  33393. ASNGetData dataASN[nameHashASN_Length];
  33394. int ret;
  33395. XMEMSET(dataASN, 0, sizeof(dataASN));
  33396. /* Ignore the OID even when present. */
  33397. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  33398. /* Decode certificate name. */
  33399. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  33400. (word32)maxIdx);
  33401. if (ret == 0) {
  33402. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  33403. * calculated over the entire DER encoding of the Name field, including
  33404. * the tag and length. */
  33405. /* Calculate hash of complete name including SEQUENCE. */
  33406. ret = CalcHashId_ex(
  33407. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  33408. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  33409. hash, HashIdAlg(sigOID));
  33410. }
  33411. return ret;
  33412. #endif /* WOLFSSL_ASN_TEMPLATE */
  33413. }
  33414. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  33415. #ifdef OPENSSL_EXTRA
  33416. static char* GetNameFromDer(const byte* source, int sz)
  33417. {
  33418. char* out;
  33419. out = (char*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_OPENSSL);
  33420. if (out == NULL) {
  33421. WOLFSSL_MSG("Name malloc failed");
  33422. return NULL;
  33423. }
  33424. XMEMCPY(out, source, (size_t)sz);
  33425. return out;
  33426. }
  33427. #endif
  33428. /* initialize decoded CRL */
  33429. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  33430. {
  33431. WOLFSSL_MSG("InitDecodedCRL");
  33432. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  33433. dcrl->heap = heap;
  33434. #ifdef WOLFSSL_HEAP_TEST
  33435. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  33436. #endif
  33437. }
  33438. /* free decoded CRL resources */
  33439. void FreeDecodedCRL(DecodedCRL* dcrl)
  33440. {
  33441. RevokedCert* tmp = dcrl->certs;
  33442. WOLFSSL_MSG("FreeDecodedCRL");
  33443. while(tmp) {
  33444. RevokedCert* next = tmp->next;
  33445. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  33446. tmp = next;
  33447. }
  33448. #ifdef OPENSSL_EXTRA
  33449. if (dcrl->issuer != NULL)
  33450. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  33451. #endif
  33452. }
  33453. #ifdef WOLFSSL_ASN_TEMPLATE
  33454. /* ASN.1 template for revoked certificates.
  33455. * X.509: RFC 5280, 5.1 - CRL Fields
  33456. */
  33457. static const ASNItem revokedASN[] = {
  33458. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  33459. /* userCertificate CertificateSerialNumber */
  33460. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  33461. /* revocationDate Time */
  33462. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  33463. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  33464. /* crlEntryExensions Extensions */
  33465. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  33466. };
  33467. enum {
  33468. REVOKEDASN_IDX_SEQ = 0,
  33469. REVOKEDASN_IDX_CERT,
  33470. REVOKEDASN_IDX_TIME_UTC,
  33471. REVOKEDASN_IDX_TIME_GT,
  33472. REVOKEDASN_IDX_TIME_EXT,
  33473. };
  33474. /* Number of items in ASN.1 template for revoked certificates. */
  33475. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  33476. #endif
  33477. /* Get Revoked Cert list, 0 on success */
  33478. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  33479. DecodedCRL* dcrl, word32 maxIdx)
  33480. {
  33481. #ifndef WOLFSSL_ASN_TEMPLATE
  33482. int ret;
  33483. int len;
  33484. word32 end;
  33485. RevokedCert* rc;
  33486. #ifdef CRL_STATIC_REVOKED_LIST
  33487. int totalCerts = 0;
  33488. #endif
  33489. WOLFSSL_ENTER("GetRevoked");
  33490. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  33491. return ASN_PARSE_E;
  33492. end = *idx + len;
  33493. #ifdef CRL_STATIC_REVOKED_LIST
  33494. totalCerts = dcrl->totalCerts;
  33495. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  33496. return MEMORY_E;
  33497. }
  33498. rc = &rcert[totalCerts];
  33499. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  33500. if (ret < 0) {
  33501. WOLFSSL_MSG("wc_GetSerialNumber error");
  33502. return ret;
  33503. }
  33504. #else
  33505. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  33506. DYNAMIC_TYPE_REVOKED);
  33507. if (rc == NULL) {
  33508. WOLFSSL_MSG("Alloc Revoked Cert failed");
  33509. return MEMORY_E;
  33510. }
  33511. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  33512. if (ret < 0) {
  33513. WOLFSSL_MSG("wc_GetSerialNumber error");
  33514. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  33515. return ret;
  33516. }
  33517. /* add to list */
  33518. rc->next = dcrl->certs;
  33519. dcrl->certs = rc;
  33520. (void)rcert;
  33521. #endif /* CRL_STATIC_REVOKED_LIST */
  33522. dcrl->totalCerts++;
  33523. /* get date */
  33524. #ifndef NO_ASN_TIME
  33525. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  33526. if (ret < 0) {
  33527. WOLFSSL_MSG("Expecting Date");
  33528. return ret;
  33529. }
  33530. #endif
  33531. /* skip extensions */
  33532. *idx = end;
  33533. return 0;
  33534. #else
  33535. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  33536. int ret = 0;
  33537. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  33538. word32 revDateSz = MAX_DATE_SIZE;
  33539. RevokedCert* rc;
  33540. #ifdef CRL_STATIC_REVOKED_LIST
  33541. int totalCerts = dcrl->totalCerts;
  33542. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  33543. return MEMORY_E;
  33544. }
  33545. rc = &rcert[totalCerts];
  33546. #else
  33547. /* Allocate a new revoked certificate object. */
  33548. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  33549. DYNAMIC_TYPE_CRL);
  33550. if (rc == NULL) {
  33551. ret = MEMORY_E;
  33552. }
  33553. #endif /* CRL_STATIC_REVOKED_LIST */
  33554. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  33555. if (ret == 0) {
  33556. /* Set buffer to place serial number into. */
  33557. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  33558. &serialSz);
  33559. /* Set buffer to store revocation date. */
  33560. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  33561. &revDateSz);
  33562. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  33563. &revDateSz);
  33564. /* Decode the Revoked */
  33565. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  33566. maxIdx);
  33567. }
  33568. if (ret == 0) {
  33569. /* Store size of serial number. */
  33570. rc->serialSz = (int)serialSz;
  33571. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  33572. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  33573. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  33574. /* TODO: use extensions, only v2 */
  33575. /* Add revoked certificate to chain. */
  33576. #ifndef CRL_STATIC_REVOKED_LIST
  33577. rc->next = dcrl->certs;
  33578. dcrl->certs = rc;
  33579. #endif
  33580. dcrl->totalCerts++;
  33581. }
  33582. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33583. #ifndef CRL_STATIC_REVOKED_LIST
  33584. if ((ret != 0) && (rc != NULL)) {
  33585. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  33586. }
  33587. (void)rcert;
  33588. #endif
  33589. return ret;
  33590. #endif /* WOLFSSL_ASN_TEMPLATE */
  33591. }
  33592. #ifdef WOLFSSL_ASN_TEMPLATE
  33593. /* Parse the revoked certificates of a CRL.
  33594. *
  33595. * @param [in] dcrl Decoded CRL object.
  33596. * @param [in] buff Buffer holding CRL.
  33597. * @param [in] idx Index into buffer of revoked certificates.
  33598. * @param [in] maxIdx Maximum index of revoked cartificates data.
  33599. * @return 0 on success.
  33600. * @return ASN_PARSE_E on failure.
  33601. */
  33602. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  33603. const byte* buff, word32 idx, word32 maxIdx)
  33604. {
  33605. int ret = 0;
  33606. /* Parse each revoked certificate. */
  33607. while ((ret == 0) && (idx < maxIdx)) {
  33608. /* Parse a revoked certificate. */
  33609. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  33610. ret = ASN_PARSE_E;
  33611. }
  33612. }
  33613. return ret;
  33614. }
  33615. #endif /* WOLFSSL_ASN_TEMPLATE */
  33616. #ifndef WOLFSSL_ASN_TEMPLATE
  33617. /* Get CRL Signature, 0 on success */
  33618. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  33619. int maxIdx)
  33620. {
  33621. int length;
  33622. int ret;
  33623. WOLFSSL_ENTER("GetCRL_Signature");
  33624. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  33625. if (ret != 0)
  33626. return ret;
  33627. dcrl->sigLength = length;
  33628. dcrl->signature = (byte*)&source[*idx];
  33629. *idx += dcrl->sigLength;
  33630. return 0;
  33631. }
  33632. #endif /* !WOLFSSL_ASN_TEMPLATE */
  33633. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  33634. word32 tbsSz, const byte* signature, word32 sigSz,
  33635. word32 signatureOID, const byte* sigParams,
  33636. int sigParamsSz, Signer *ca, void* heap)
  33637. {
  33638. /* try to confirm/verify signature */
  33639. #ifndef IGNORE_KEY_EXTENSIONS
  33640. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  33641. WOLFSSL_MSG("CA cannot sign CRLs");
  33642. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  33643. return ASN_CRL_NO_SIGNER_E;
  33644. }
  33645. #endif /* IGNORE_KEY_EXTENSIONS */
  33646. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  33647. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  33648. ca->pubKeySize, ca->keyOID, signature, sigSz,
  33649. signatureOID, sigParams, sigParamsSz, NULL) != 0) {
  33650. WOLFSSL_MSG("CRL Confirm signature failed");
  33651. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  33652. return ASN_CRL_CONFIRM_E;
  33653. }
  33654. return 0;
  33655. }
  33656. #ifdef WOLFSSL_ASN_TEMPLATE
  33657. /* Find the signer for the CRL and verify the signature.
  33658. *
  33659. * @param [in] dcrl Decoded CRL object.
  33660. * @param [in] buff Buffer holding CRL.
  33661. * @param [in] cm Certificate manager object.
  33662. * @return 0 on success.
  33663. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  33664. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  33665. */
  33666. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* sigParams,
  33667. int sigParamsSz, const byte* buff, void* cm)
  33668. {
  33669. int ret = 0;
  33670. Signer* ca = NULL;
  33671. SignatureCtx sigCtx;
  33672. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  33673. * If experiencing issues uncomment NO_SKID define in CRL section of
  33674. * wolfssl/wolfcrypt/settings.h */
  33675. #ifndef NO_SKID
  33676. if (dcrl->extAuthKeyIdSet) {
  33677. /* more unique than issuerHash */
  33678. ca = GetCA(cm, dcrl->extAuthKeyId);
  33679. }
  33680. /* Check issuerHash matched CA's subjectNameHash. */
  33681. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  33682. KEYID_SIZE) != 0)) {
  33683. ca = NULL;
  33684. }
  33685. if (ca == NULL) {
  33686. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  33687. /* If AKID is available then this CA doesn't have the public
  33688. * key required */
  33689. if (ca && dcrl->extAuthKeyIdSet) {
  33690. WOLFSSL_MSG("CA SKID doesn't match AKID");
  33691. ca = NULL;
  33692. }
  33693. }
  33694. #else
  33695. ca = GetCA(cm, dcrl->issuerHash);
  33696. #endif /* !NO_SKID */
  33697. WOLFSSL_MSG("About to verify CRL signature");
  33698. if (ca == NULL) {
  33699. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  33700. ret = ASN_CRL_NO_SIGNER_E;
  33701. WOLFSSL_ERROR_VERBOSE(ret);
  33702. }
  33703. if (ret == 0) {
  33704. WOLFSSL_MSG("Found CRL issuer CA");
  33705. /* Verify CRL signature with CA. */
  33706. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  33707. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  33708. dcrl->signatureOID, sigParams, sigParamsSz, ca, dcrl->heap);
  33709. }
  33710. return ret;
  33711. }
  33712. #endif
  33713. #ifndef WOLFSSL_ASN_TEMPLATE
  33714. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  33715. const byte* buf,word32* inOutIdx, int sz, int verify)
  33716. {
  33717. word32 oid, dateIdx, idx, checkIdx;
  33718. int length;
  33719. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  33720. int doNextDate = 1;
  33721. #endif
  33722. byte tag;
  33723. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  33724. return BAD_FUNC_ARG;
  33725. }
  33726. /* may have version */
  33727. idx = *inOutIdx;
  33728. checkIdx = idx;
  33729. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  33730. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  33731. return ASN_PARSE_E;
  33732. dcrl->version++;
  33733. }
  33734. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0) {
  33735. return ASN_PARSE_E;
  33736. }
  33737. #ifdef WC_RSA_PSS
  33738. else if (oid == CTC_RSASSAPSS) {
  33739. word32 tmpSz;
  33740. int len;
  33741. tmpSz = idx;
  33742. dcrl->sigParamsIndex = idx;
  33743. if (GetSequence(buf, &idx, &len, sz) < 0) {
  33744. dcrl->sigParamsIndex = 0;
  33745. return ASN_PARSE_E;
  33746. }
  33747. idx += len;
  33748. dcrl->sigParamsLength = idx - tmpSz;
  33749. }
  33750. #endif
  33751. checkIdx = idx;
  33752. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  33753. return ASN_PARSE_E;
  33754. }
  33755. #ifdef OPENSSL_EXTRA
  33756. dcrl->issuerSz = length + (checkIdx - idx);
  33757. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  33758. #endif
  33759. if (GetNameHash_ex(buf, &idx, dcrl->issuerHash, sz, oid) < 0)
  33760. return ASN_PARSE_E;
  33761. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  33762. return ASN_PARSE_E;
  33763. dateIdx = idx;
  33764. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  33765. {
  33766. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  33767. (void)dateIdx;
  33768. return ASN_PARSE_E;
  33769. #else
  33770. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  33771. doNextDate = 0;
  33772. idx = dateIdx;
  33773. #endif
  33774. }
  33775. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  33776. if (doNextDate)
  33777. #endif
  33778. {
  33779. #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK)
  33780. if (verify != NO_VERIFY &&
  33781. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  33782. WOLFSSL_MSG("CRL after date is no longer valid");
  33783. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  33784. return CRL_CERT_DATE_ERR;
  33785. }
  33786. #else
  33787. (void)verify;
  33788. #endif
  33789. }
  33790. checkIdx = idx;
  33791. if (idx != dcrl->sigIndex &&
  33792. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  33793. int len;
  33794. if (GetSequence(buf, &idx, &len, sz) < 0)
  33795. return ASN_PARSE_E;
  33796. len += idx;
  33797. while (idx < (word32)len) {
  33798. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  33799. return ASN_PARSE_E;
  33800. }
  33801. }
  33802. *inOutIdx = idx;
  33803. return 0;
  33804. }
  33805. #endif /* !WOLFSSL_ASN_TEMPLATE */
  33806. #ifndef NO_SKID
  33807. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  33808. {
  33809. #ifndef WOLFSSL_ASN_TEMPLATE
  33810. word32 idx = 0;
  33811. int length = 0, ret = 0;
  33812. byte tag;
  33813. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  33814. if (GetSequence(input, &idx, &length, sz) < 0) {
  33815. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  33816. return ASN_PARSE_E;
  33817. }
  33818. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  33819. return ASN_PARSE_E;
  33820. }
  33821. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  33822. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  33823. return 0;
  33824. }
  33825. if (GetLength(input, &idx, &length, sz) <= 0) {
  33826. WOLFSSL_MSG("\tfail: extension data length");
  33827. return ASN_PARSE_E;
  33828. }
  33829. dcrl->extAuthKeyIdSet = 1;
  33830. /* Get the hash or hash of the hash if wrong size. */
  33831. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId,
  33832. HashIdAlg(dcrl->signatureOID));
  33833. return ret;
  33834. #else
  33835. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  33836. int ret = 0;
  33837. word32 idx = 0;
  33838. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  33839. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  33840. if (ret == 0) {
  33841. /* Parse an authority key identifier. */
  33842. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  33843. &idx, (word32)sz);
  33844. }
  33845. if (ret == 0) {
  33846. /* Key id is optional. */
  33847. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  33848. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  33849. }
  33850. else {
  33851. /* Get the hash or hash of the hash if wrong size. */
  33852. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  33853. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  33854. dcrl->extAuthKeyId, HashIdAlg(dcrl->signatureOID));
  33855. }
  33856. }
  33857. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33858. return ret;
  33859. #endif /* WOLFSSL_ASN_TEMPLATE */
  33860. }
  33861. #endif
  33862. #ifndef WOLFSSL_ASN_TEMPLATE
  33863. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  33864. word32* inOutIdx, word32 sz)
  33865. {
  33866. int length;
  33867. word32 idx;
  33868. word32 ext_bound; /* boundary index for the sequence of extensions */
  33869. word32 oid;
  33870. byte tag;
  33871. WOLFSSL_ENTER("ParseCRL_Extensions");
  33872. (void)dcrl;
  33873. if (inOutIdx == NULL)
  33874. return BAD_FUNC_ARG;
  33875. idx = *inOutIdx;
  33876. /* CRL Extensions are optional */
  33877. if ((idx + 1) > sz)
  33878. return 0;
  33879. /* CRL Extensions are optional */
  33880. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  33881. return 0;
  33882. /* CRL Extensions are optional */
  33883. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  33884. return 0;
  33885. if (GetLength(buf, &idx, &length, sz) < 0)
  33886. return ASN_PARSE_E;
  33887. if (GetSequence(buf, &idx, &length, sz) < 0)
  33888. return ASN_PARSE_E;
  33889. ext_bound = idx + length;
  33890. while (idx < (word32)ext_bound) {
  33891. word32 localIdx;
  33892. int ret;
  33893. if (GetSequence(buf, &idx, &length, sz) < 0) {
  33894. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  33895. return ASN_PARSE_E;
  33896. }
  33897. oid = 0;
  33898. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  33899. WOLFSSL_MSG("\tfail: OBJECT ID");
  33900. return ASN_PARSE_E;
  33901. }
  33902. /* check for critical flag */
  33903. if ((idx + 1) > (word32)sz) {
  33904. WOLFSSL_MSG("\tfail: malformed buffer");
  33905. return BUFFER_E;
  33906. }
  33907. localIdx = idx;
  33908. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  33909. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  33910. ret = GetBoolean(buf, &idx, sz);
  33911. if (ret < 0)
  33912. return ret;
  33913. }
  33914. ret = GetOctetString(buf, &idx, &length, sz);
  33915. if (ret < 0)
  33916. return ret;
  33917. if (oid == AUTH_KEY_OID) {
  33918. #ifndef NO_SKID
  33919. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  33920. if (ret < 0) {
  33921. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  33922. return ret;
  33923. }
  33924. #endif
  33925. }
  33926. else if (oid == CRL_NUMBER_OID) {
  33927. localIdx = idx;
  33928. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  33929. tag == ASN_INTEGER) {
  33930. ret = GetASNInt(buf, &idx, &length, sz);
  33931. if (ret < 0) {
  33932. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  33933. return ret;
  33934. }
  33935. else {
  33936. if (length > 1) {
  33937. int i;
  33938. #ifdef WOLFSSL_SMALL_STACK
  33939. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  33940. DYNAMIC_TYPE_BIGINT);
  33941. if (m == NULL) {
  33942. return MEMORY_E;
  33943. }
  33944. #else
  33945. mp_int m[1];
  33946. #endif
  33947. if (mp_init(m) != MP_OKAY) {
  33948. ret = MP_INIT_E;
  33949. }
  33950. if (ret == 0)
  33951. ret = mp_read_unsigned_bin(m, buf + idx, length);
  33952. if (ret != MP_OKAY)
  33953. ret = BUFFER_E;
  33954. if (ret == 0) {
  33955. dcrl->crlNumber = 0;
  33956. for (i = 0; i < (int)(*m).used; ++i) {
  33957. if (i > (CHAR_BIT *
  33958. (int)sizeof(word32) / DIGIT_BIT)) {
  33959. break;
  33960. }
  33961. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  33962. (DIGIT_BIT * i);
  33963. }
  33964. }
  33965. mp_free(m);
  33966. #ifdef WOLFSSL_SMALL_STACK
  33967. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  33968. #endif
  33969. if (ret != 0)
  33970. return ret;
  33971. }
  33972. else if (length == 1) {
  33973. dcrl->crlNumber = buf[idx];
  33974. }
  33975. }
  33976. }
  33977. }
  33978. idx += length;
  33979. }
  33980. *inOutIdx = idx;
  33981. return 0;
  33982. }
  33983. #else
  33984. /* Parse the extensions of a CRL.
  33985. *
  33986. * @param [in] dcrl Decoded CRL object.
  33987. * @param [in] buff Buffer holding CRL.
  33988. * @param [in] idx Index into buffer of extensions.
  33989. * @param [in] maxIdx Maximum index of extension data.
  33990. * @return 0 on success.
  33991. * @return ASN_PARSE_E on failure.
  33992. */
  33993. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  33994. word32 maxIdx)
  33995. {
  33996. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  33997. int ret = 0;
  33998. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  33999. while ((ret == 0) && (idx < maxIdx)) {
  34000. byte critical = 0;
  34001. /* Clear dynamic data. */
  34002. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  34003. /* Ensure OID is an extension type. */
  34004. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  34005. /* Set criticality variable. */
  34006. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  34007. /* Parse extension wrapper. */
  34008. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  34009. maxIdx);
  34010. if (ret == 0) {
  34011. /* OID in extension. */
  34012. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  34013. /* Length of extension data. */
  34014. int length = (int)dataASN[CERTEXTASN_IDX_VAL].length;
  34015. if (oid == AUTH_KEY_OID) {
  34016. #ifndef NO_SKID
  34017. /* Parse Authority Key Id extension.
  34018. * idx is at start of OCTET_STRING data. */
  34019. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  34020. if (ret != 0) {
  34021. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  34022. }
  34023. #endif
  34024. }
  34025. /* TODO: Parse CRL Number extension */
  34026. /* TODO: check criticality */
  34027. /* Move index on to next extension. */
  34028. idx += (word32)length;
  34029. }
  34030. }
  34031. if (ret < 0) {
  34032. ret = ASN_PARSE_E;
  34033. }
  34034. FREE_ASNGETDATA(dataASN, dcrl->heap);
  34035. return ret;
  34036. }
  34037. #endif /* !WOLFSSL_ASN_TEMPLATE */
  34038. #ifdef WOLFSSL_ASN_TEMPLATE
  34039. /* ASN.1 template for a CRL- CertificateList.
  34040. * X.509: RFC 5280, 5.1 - CRL Fields
  34041. */
  34042. static const ASNItem crlASN[] = {
  34043. /* CertificateList */
  34044. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  34045. /* tbsCertList */
  34046. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  34047. /* version Version OPTIONAL if present must be v2 */
  34048. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  34049. /* signature */
  34050. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  34051. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  34052. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  34053. /* issuer */
  34054. #ifdef WC_RSA_PSS
  34055. /* TBS_SIGALGO_P_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  34056. #endif
  34057. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  34058. /* thisUpdate */
  34059. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  34060. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  34061. /* nextUpdate */
  34062. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  34063. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  34064. /* revokedCertificates */
  34065. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  34066. /* crlExtensions */
  34067. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  34068. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  34069. /* signatureAlgorithm */
  34070. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  34071. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  34072. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  34073. #ifdef WC_RSA_PSS
  34074. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  34075. #endif
  34076. /* signatureValue */
  34077. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  34078. };
  34079. enum {
  34080. CRLASN_IDX_SEQ = 0,
  34081. CRLASN_IDX_TBS,
  34082. CRLASN_IDX_TBS_VER,
  34083. CRLASN_IDX_TBS_SIGALGO,
  34084. CRLASN_IDX_TBS_SIGALGO_OID,
  34085. CRLASN_IDX_TBS_SIGALGO_NULL,
  34086. #ifdef WC_RSA_PSS
  34087. CRLASN_IDX_TBS_SIGALGO_PARAMS,
  34088. #endif
  34089. CRLASN_IDX_TBS_ISSUER,
  34090. CRLASN_IDX_TBS_THISUPDATE_UTC,
  34091. CRLASN_IDX_TBS_THISUPDATE_GT,
  34092. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  34093. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  34094. CRLASN_IDX_TBS_REVOKEDCERTS,
  34095. CRLASN_IDX_TBS_EXT,
  34096. CRLASN_IDX_TBS_EXT_SEQ,
  34097. CRLASN_IDX_SIGALGO,
  34098. CRLASN_IDX_SIGALGO_OID,
  34099. CRLASN_IDX_SIGALGO_NULL,
  34100. #ifdef WC_RSA_PSS
  34101. CRLASN_IDX_SIGALGO_PARAMS,
  34102. #endif
  34103. CRLASN_IDX_SIGNATURE,
  34104. };
  34105. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  34106. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  34107. #endif
  34108. /* parse crl buffer into decoded state, 0 on success */
  34109. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  34110. int verify, void* cm)
  34111. {
  34112. #ifndef WOLFSSL_ASN_TEMPLATE
  34113. Signer* ca = NULL;
  34114. SignatureCtx sigCtx;
  34115. int ret = 0;
  34116. int len;
  34117. word32 idx = 0;
  34118. #ifdef WC_RSA_PSS
  34119. const byte* sigParams = NULL;
  34120. int sigParamsSz = 0;
  34121. #endif
  34122. WOLFSSL_MSG("ParseCRL");
  34123. /* raw crl hash */
  34124. /* hash here if needed for optimized comparisons
  34125. * wc_Sha sha;
  34126. * wc_InitSha(&sha);
  34127. * wc_ShaUpdate(&sha, buff, sz);
  34128. * wc_ShaFinal(&sha, dcrl->crlHash); */
  34129. if (GetSequence(buff, &idx, &len, sz) < 0)
  34130. return ASN_PARSE_E;
  34131. dcrl->certBegin = idx;
  34132. /* Normalize sz for the length inside the outer sequence. */
  34133. sz = len + idx;
  34134. if (GetSequence(buff, &idx, &len, sz) < 0)
  34135. return ASN_PARSE_E;
  34136. dcrl->sigIndex = len + idx;
  34137. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  34138. return ASN_PARSE_E;
  34139. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  34140. return ASN_PARSE_E;
  34141. idx = dcrl->sigIndex;
  34142. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0) {
  34143. return ASN_PARSE_E;
  34144. }
  34145. #ifdef WC_RSA_PSS
  34146. else if (dcrl->signatureOID == CTC_RSASSAPSS) {
  34147. word32 tmpSz;
  34148. const byte* params;
  34149. tmpSz = idx;
  34150. params = buff + idx;
  34151. if (GetSequence(buff, &idx, &len, sz) < 0) {
  34152. return ASN_PARSE_E;
  34153. }
  34154. idx += len;
  34155. sigParams = params;
  34156. sigParamsSz = idx - tmpSz;
  34157. }
  34158. #endif
  34159. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  34160. return ASN_PARSE_E;
  34161. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  34162. if experiencing issues uncomment NO_SKID define in CRL section of
  34163. wolfssl/wolfcrypt/settings.h */
  34164. #ifndef NO_SKID
  34165. if (dcrl->extAuthKeyIdSet) {
  34166. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  34167. }
  34168. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  34169. KEYID_SIZE) != 0) {
  34170. ca = NULL;
  34171. }
  34172. if (ca == NULL) {
  34173. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  34174. /* If AKID is available then this CA doesn't have the public
  34175. * key required */
  34176. if (ca && dcrl->extAuthKeyIdSet) {
  34177. WOLFSSL_MSG("CA SKID doesn't match AKID");
  34178. ca = NULL;
  34179. }
  34180. }
  34181. #else
  34182. ca = GetCA(cm, dcrl->issuerHash);
  34183. #endif /* !NO_SKID */
  34184. WOLFSSL_MSG("About to verify CRL signature");
  34185. if (ca == NULL) {
  34186. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  34187. ret = ASN_CRL_NO_SIGNER_E;
  34188. WOLFSSL_ERROR_VERBOSE(ret);
  34189. goto end;
  34190. }
  34191. WOLFSSL_MSG("Found CRL issuer CA");
  34192. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  34193. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  34194. dcrl->signatureOID, sigParams, sigParamsSz, ca, dcrl->heap);
  34195. end:
  34196. return ret;
  34197. #else
  34198. DECL_ASNGETDATA(dataASN, crlASN_Length);
  34199. int ret = 0;
  34200. /* Default version - v1 = 0 */
  34201. byte version = 0;
  34202. word32 idx = 0;
  34203. /* Size of buffer for date. */
  34204. word32 lastDateSz = MAX_DATE_SIZE;
  34205. word32 nextDateSz = MAX_DATE_SIZE;
  34206. const byte* sigParams = NULL;
  34207. int sigParamsSz = 0;
  34208. #ifdef WC_RSA_PSS
  34209. const byte* tbsParams = NULL;
  34210. int tbsParamsSz = 0;
  34211. #endif
  34212. /* When NO_ASN_TIME is defined, verify not used. */
  34213. (void)verify;
  34214. WOLFSSL_MSG("ParseCRL");
  34215. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  34216. if (ret == 0) {
  34217. /* Set variable to store version. */
  34218. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  34219. /* Set expecting signature OID. */
  34220. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  34221. /* Set buffer to put last and next date into. */
  34222. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  34223. &lastDateSz);
  34224. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  34225. &lastDateSz);
  34226. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  34227. &nextDateSz);
  34228. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  34229. &nextDateSz);
  34230. /* Set expecting signature OID. */
  34231. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  34232. /* Decode the CRL. */
  34233. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  34234. }
  34235. /* Version must be v2 = 1 if present. */
  34236. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  34237. (version != 1)) {
  34238. ret = ASN_PARSE_E;
  34239. }
  34240. /* Check minimum size of last date. */
  34241. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  34242. ret = ASN_PARSE_E;
  34243. }
  34244. /* Check minimum size of next date. */
  34245. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  34246. ret = ASN_PARSE_E;
  34247. }
  34248. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  34249. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  34250. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  34251. ret = ASN_PARSE_E;
  34252. }
  34253. if (ret == 0) {
  34254. /* Store version */
  34255. dcrl->version = ++version;
  34256. /* Store offset of to be signed part. */
  34257. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  34258. /* Store index of signature. */
  34259. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  34260. #ifdef WC_RSA_PSS
  34261. /* get TBS and Signature parameters for PSS */
  34262. if (dataASN[CRLASN_IDX_TBS_SIGALGO_PARAMS].tag != 0) {
  34263. tbsParams =
  34264. GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_SIGALGO_PARAMS],
  34265. buff);
  34266. tbsParamsSz =
  34267. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_SIGALGO_PARAMS],
  34268. buff);
  34269. }
  34270. if (dataASN[CRLASN_IDX_SIGALGO_PARAMS].tag != 0) {
  34271. sigParams =
  34272. GetASNItem_Addr(dataASN[CRLASN_IDX_SIGALGO_PARAMS],
  34273. buff);
  34274. sigParamsSz =
  34275. GetASNItem_Length(dataASN[CRLASN_IDX_SIGALGO_PARAMS],
  34276. buff);
  34277. dcrl->sigParamsIndex =
  34278. dataASN[CRLASN_IDX_SIGALGO_PARAMS].offset;
  34279. dcrl->sigParamsLength = sigParamsSz;
  34280. }
  34281. #endif
  34282. /* Store address and length of signature data. */
  34283. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  34284. &dcrl->sigLength);
  34285. /* Get the signature OID. */
  34286. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  34287. #ifdef WC_RSA_PSS
  34288. /* Sanity check on parameters found */
  34289. if (tbsParamsSz != sigParamsSz) {
  34290. WOLFSSL_MSG("CRL TBS and signature parameter sizes mismatch");
  34291. ret = ASN_PARSE_E;
  34292. }
  34293. else if ((tbsParamsSz > 0) &&
  34294. (dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum != CTC_RSASSAPSS)) {
  34295. WOLFSSL_MSG("CRL unexpected signature parameters found");
  34296. ret = ASN_PARSE_E;
  34297. }
  34298. else if ((tbsParamsSz > 0) &&
  34299. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  34300. WOLFSSL_MSG("CRL TBS and signature parameter mismatch");
  34301. ret = ASN_PARSE_E;
  34302. }
  34303. #endif
  34304. /* Get the format/tag of the last and next date. */
  34305. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  34306. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  34307. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  34308. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  34309. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  34310. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  34311. #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_CRL_DATE_CHECK)
  34312. if (dcrl->nextDateFormat != 0) {
  34313. /* Next date was set, so validate it. */
  34314. if (verify != NO_VERIFY &&
  34315. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  34316. WOLFSSL_MSG("CRL after date is no longer valid");
  34317. ret = CRL_CERT_DATE_ERR;
  34318. WOLFSSL_ERROR_VERBOSE(ret);
  34319. }
  34320. }
  34321. }
  34322. if (ret == 0) { /* in "no time" cases above "ret" is not set */
  34323. #endif /* !NO_ASN_TIME && !WOLFSSL_NO_CRL_DATE_CHECK */
  34324. #ifdef OPENSSL_EXTRA
  34325. /* Parse and store the issuer name. */
  34326. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  34327. buff);
  34328. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  34329. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  34330. (int)dcrl->issuerSz);
  34331. #endif
  34332. /* Calculate the Hash id from the issuer name. */
  34333. ret = CalcHashId_ex(
  34334. GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  34335. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  34336. dcrl->issuerHash, HashIdAlg(dcrl->signatureOID));
  34337. if (ret < 0) {
  34338. ret = ASN_PARSE_E;
  34339. }
  34340. }
  34341. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  34342. /* Parse revoked certificates - starting after SEQUENCE OF. */
  34343. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  34344. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  34345. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  34346. }
  34347. if (ret == 0) {
  34348. /* Parse the extensions - starting after SEQUENCE OF. */
  34349. ret = ParseCRL_Extensions(dcrl, buff,
  34350. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  34351. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  34352. }
  34353. if (ret == 0) {
  34354. /* Find signer and verify signature. */
  34355. ret = PaseCRL_CheckSignature(dcrl, sigParams, sigParamsSz, buff, cm);
  34356. }
  34357. FREE_ASNGETDATA(dataASN, dcrl->heap);
  34358. return ret;
  34359. #endif /* WOLFSSL_ASN_TEMPLATE */
  34360. }
  34361. #endif /* HAVE_CRL */
  34362. #ifdef WOLFSSL_CERT_PIV
  34363. #ifdef WOLFSSL_ASN_TEMPLATE
  34364. /* Template for PIV. */
  34365. static const ASNItem pivASN[] = {
  34366. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  34367. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  34368. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  34369. };
  34370. enum {
  34371. PIVASN_IDX_CERT = 0,
  34372. PIVASN_IDX_NONCE,
  34373. PIVASN_IDX_SIGNEDNONCE,
  34374. };
  34375. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  34376. static const ASNItem pivCertASN[] = {
  34377. /* 0x53 = 0x40 | 0x13 */
  34378. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  34379. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  34380. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  34381. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  34382. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  34383. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  34384. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  34385. };
  34386. enum {
  34387. PIVCERTASN_IDX_CERT,
  34388. PIVCERTASN_IDX_X509,
  34389. PIVCERTASN_IDX_INFO,
  34390. PIVCERTASN_IDX_ERR,
  34391. };
  34392. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  34393. #endif
  34394. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  34395. {
  34396. #ifndef WOLFSSL_ASN_TEMPLATE
  34397. int length = 0;
  34398. word32 idx = 0;
  34399. WOLFSSL_ENTER("wc_ParseCertPIV");
  34400. if (piv == NULL || buf == NULL || totalSz == 0)
  34401. return BAD_FUNC_ARG;
  34402. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  34403. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  34404. /* Certificate (0A 82 05FA) */
  34405. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  34406. /* Identiv Type PIV card */
  34407. piv->isIdentiv = 1;
  34408. piv->cert = &buf[idx];
  34409. piv->certSz = length;
  34410. idx += length;
  34411. /* Nonce (0B 14) */
  34412. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  34413. piv->nonce = &buf[idx];
  34414. piv->nonceSz = length;
  34415. idx += length;
  34416. }
  34417. /* Signed Nonce (0C 82 0100) */
  34418. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  34419. piv->signedNonce = &buf[idx];
  34420. piv->signedNonceSz = length;
  34421. }
  34422. idx = 0;
  34423. buf = piv->cert;
  34424. totalSz = piv->certSz;
  34425. }
  34426. /* Certificate Buffer Total Size (53 82 05F6) */
  34427. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  34428. &length, totalSz) < 0) {
  34429. return ASN_PARSE_E;
  34430. }
  34431. /* PIV Certificate (70 82 05ED) */
  34432. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  34433. totalSz) < 0) {
  34434. return ASN_PARSE_E;
  34435. }
  34436. /* Capture certificate buffer pointer and length */
  34437. piv->cert = &buf[idx];
  34438. piv->certSz = length;
  34439. idx += length;
  34440. /* PIV Certificate Info (71 01 00) */
  34441. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  34442. totalSz) >= 0) {
  34443. if (length >= 1) {
  34444. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  34445. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  34446. }
  34447. idx += length;
  34448. }
  34449. /* PIV Error Detection (FE 00) */
  34450. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  34451. totalSz) >= 0) {
  34452. piv->certErrDet = &buf[idx];
  34453. piv->certErrDetSz = length;
  34454. idx += length;
  34455. }
  34456. return 0;
  34457. #else
  34458. /* pivCertASN_Length is longer than pivASN_Length */
  34459. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  34460. int ret = 0;
  34461. word32 idx;
  34462. byte info;
  34463. WOLFSSL_ENTER("wc_ParseCertPIV");
  34464. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  34465. if (ret == 0) {
  34466. /* Clear dynamic data. */
  34467. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  34468. /* Start parsing from start of buffer. */
  34469. idx = 0;
  34470. /* Parse Identiv wrapper. */
  34471. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  34472. totalSz);
  34473. if (ret == 0) {
  34474. /* Identiv wrapper found. */
  34475. piv->isIdentiv = 1;
  34476. /* Get nonce reference. */
  34477. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  34478. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  34479. &piv->nonceSz);
  34480. }
  34481. /* Get signedNonce reference. */
  34482. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  34483. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  34484. &piv->signedNonce, &piv->signedNonceSz);
  34485. }
  34486. /* Get the certificate data for parsing. */
  34487. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  34488. }
  34489. ret = 0;
  34490. }
  34491. if (ret == 0) {
  34492. /* Clear dynamic data and set variable to put cert info into. */
  34493. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  34494. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  34495. /* Start parsing from start of buffer. */
  34496. idx = 0;
  34497. /* Parse PIV certificate data. */
  34498. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  34499. totalSz);
  34500. if (ret == 0) {
  34501. /* Get X.509 certificate reference. */
  34502. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  34503. &piv->certSz);
  34504. /* Set the certificate info if available. */
  34505. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  34506. /* Bits 1 and 2 are compression. */
  34507. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  34508. /* Bits 3 is X509 flag. */
  34509. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  34510. }
  34511. /* Get X.509 certificate error detection reference. */
  34512. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  34513. &piv->certErrDetSz);
  34514. }
  34515. ret = 0;
  34516. }
  34517. FREE_ASNGETDATA(dataASN, NULL);
  34518. return ret;
  34519. #endif /* WOLFSSL_ASN_TEMPLATE */
  34520. }
  34521. #endif /* WOLFSSL_CERT_PIV */
  34522. #ifdef HAVE_SMIME
  34523. /*****************************************************************************
  34524. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  34525. * and parameters into headers. Will continue until in has no more content.
  34526. *
  34527. * RETURNS:
  34528. * returns zero on success, non-zero on error.
  34529. */
  34530. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  34531. {
  34532. MimeHdr* nextHdr = NULL;
  34533. MimeHdr* curHdr = NULL;
  34534. MimeParam* nextParam = NULL;
  34535. size_t start = 0;
  34536. size_t end = 0;
  34537. char* nameAttr = NULL;
  34538. char* bodyVal = NULL;
  34539. MimeTypes mimeType = MIME_HDR;
  34540. MimeStatus mimeStatus = MIME_NAMEATTR;
  34541. int ret = -1;
  34542. size_t pos = 0;
  34543. size_t lineLen = 0;
  34544. char* curLine = NULL;
  34545. char* ptr = NULL;
  34546. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  34547. ret = BAD_FUNC_ARG;
  34548. goto error;
  34549. }
  34550. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  34551. if (nextHdr == NULL) {
  34552. ret = MEMORY_E;
  34553. goto error;
  34554. }
  34555. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  34556. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  34557. DYNAMIC_TYPE_PKCS7);
  34558. if (nextParam == NULL) {
  34559. ret = MEMORY_E;
  34560. goto error;
  34561. }
  34562. XMEMSET(nextParam, 0, sizeof(MimeParam));
  34563. curLine = XSTRTOK(in, "\r\n", &ptr);
  34564. if (curLine == NULL) {
  34565. ret = ASN_PARSE_E;
  34566. goto error;
  34567. }
  34568. while (curLine != NULL) {
  34569. /* Leftover from previous line, add params to previous header. */
  34570. if (curLine[0] == ' ' && curHdr) {
  34571. mimeType = MIME_PARAM;
  34572. }
  34573. else {
  34574. mimeType = MIME_HDR;
  34575. }
  34576. start = 0;
  34577. lineLen = XSTRLEN(curLine);
  34578. if (lineLen == 0) {
  34579. ret = BAD_FUNC_ARG;
  34580. goto error;
  34581. }
  34582. for (pos = 0; pos < lineLen; pos++) {
  34583. char cur = curLine[pos];
  34584. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  34585. mimeType == MIME_HDR) || (cur == '=' &&
  34586. mimeType == MIME_PARAM)) && pos >= 1) {
  34587. mimeStatus = MIME_BODYVAL;
  34588. end = pos-1;
  34589. if (nameAttr != NULL) {
  34590. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  34591. nameAttr = NULL;
  34592. }
  34593. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  34594. if (ret) {
  34595. goto error;
  34596. }
  34597. start = pos+1;
  34598. }
  34599. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  34600. end = pos-1;
  34601. if (bodyVal != NULL) {
  34602. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  34603. bodyVal = NULL;
  34604. }
  34605. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  34606. if (ret) {
  34607. goto error;
  34608. }
  34609. if (mimeType == MIME_HDR) {
  34610. nextHdr->name = nameAttr;
  34611. nameAttr = NULL;
  34612. nextHdr->body = bodyVal;
  34613. bodyVal = NULL;
  34614. nextHdr->next = curHdr;
  34615. curHdr = nextHdr;
  34616. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  34617. DYNAMIC_TYPE_PKCS7);
  34618. if (nextHdr == NULL) {
  34619. ret = MEMORY_E;
  34620. goto error;
  34621. }
  34622. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  34623. }
  34624. else {
  34625. nextParam->attribute = nameAttr;
  34626. nameAttr = NULL;
  34627. nextParam->value = bodyVal;
  34628. bodyVal = NULL;
  34629. nextParam->next = curHdr->params;
  34630. curHdr->params = nextParam;
  34631. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  34632. DYNAMIC_TYPE_PKCS7);
  34633. if (nextParam == NULL) {
  34634. ret = MEMORY_E;
  34635. goto error;
  34636. }
  34637. XMEMSET(nextParam, 0, sizeof(MimeParam));
  34638. }
  34639. mimeType = MIME_PARAM;
  34640. mimeStatus = MIME_NAMEATTR;
  34641. start = pos+1;
  34642. }
  34643. }
  34644. end = lineLen-1;
  34645. /* Omit newline characters. */
  34646. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  34647. end--;
  34648. }
  34649. if (end >= start && mimeStatus == MIME_BODYVAL) {
  34650. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  34651. if (ret) {
  34652. goto error;
  34653. }
  34654. if (mimeType == MIME_HDR) {
  34655. nextHdr->name = nameAttr;
  34656. nameAttr = NULL;
  34657. nextHdr->body = bodyVal;
  34658. bodyVal = NULL;
  34659. nextHdr->next = curHdr;
  34660. curHdr = nextHdr;
  34661. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  34662. DYNAMIC_TYPE_PKCS7);
  34663. if (nextHdr == NULL) {
  34664. ret = MEMORY_E;
  34665. goto error;
  34666. }
  34667. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  34668. } else {
  34669. nextParam->attribute = nameAttr;
  34670. nameAttr = NULL;
  34671. nextParam->value = bodyVal;
  34672. bodyVal = NULL;
  34673. nextParam->next = curHdr->params;
  34674. curHdr->params = nextParam;
  34675. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  34676. DYNAMIC_TYPE_PKCS7);
  34677. if (nextParam == NULL) {
  34678. ret = MEMORY_E;
  34679. goto error;
  34680. }
  34681. XMEMSET(nextParam, 0, sizeof(MimeParam));
  34682. }
  34683. }
  34684. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  34685. mimeStatus = MIME_NAMEATTR;
  34686. }
  34687. *headers = curHdr;
  34688. ret = 0; /* success if at this point */
  34689. error:
  34690. if (ret != 0)
  34691. wc_MIME_free_hdrs(curHdr);
  34692. wc_MIME_free_hdrs(nextHdr);
  34693. if (nameAttr != NULL)
  34694. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  34695. if (bodyVal != NULL)
  34696. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  34697. if (nextParam != NULL)
  34698. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  34699. return ret;
  34700. }
  34701. /*****************************************************************************
  34702. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  34703. * out disallowed/separator characters and places the rest into *out.
  34704. *
  34705. * RETURNS:
  34706. * returns zero on success, non-zero on error.
  34707. */
  34708. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  34709. {
  34710. size_t inPos = start;
  34711. size_t outPos = 0;
  34712. size_t inLen = 0;
  34713. if (end < start || in == NULL || out == NULL) {
  34714. return BAD_FUNC_ARG;
  34715. }
  34716. inLen = XSTRLEN(in);
  34717. if (start > inLen || end > inLen) {
  34718. return BAD_FUNC_ARG;
  34719. }
  34720. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  34721. DYNAMIC_TYPE_PKCS7);
  34722. if (*out == NULL) {
  34723. return MEMORY_E;
  34724. }
  34725. while (inPos <= end) {
  34726. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  34727. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  34728. (*out)[outPos] = in[inPos];
  34729. outPos++;
  34730. }
  34731. inPos++;
  34732. }
  34733. (*out)[outPos] = '\0';
  34734. return 0;
  34735. }
  34736. /*****************************************************************************
  34737. * wc_MIME_find_header_name - Searches through all given headers until a header with
  34738. * a name matching the provided name is found.
  34739. *
  34740. * RETURNS:
  34741. * returns a pointer to the found header, if no match was found, returns NULL.
  34742. */
  34743. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  34744. {
  34745. while (header) {
  34746. if (!XSTRCMP(name, header->name)) {
  34747. return header;
  34748. }
  34749. header = header->next;
  34750. }
  34751. return header;
  34752. }
  34753. /*****************************************************************************
  34754. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  34755. * with a attribute matching the provided attribute is found.
  34756. *
  34757. * RETURNS:
  34758. * returns a pointer to the found parameter, if no match was found,
  34759. * returns NULL.
  34760. */
  34761. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  34762. MimeParam* param)
  34763. {
  34764. while (param) {
  34765. if (!XSTRCMP(attribute, param->attribute)) {
  34766. return param;
  34767. }
  34768. param = param->next;
  34769. }
  34770. return param;
  34771. }
  34772. /*****************************************************************************
  34773. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  34774. * line ending to CRLF.
  34775. *
  34776. * line - input line to canonicalize
  34777. * len - length of line in chars on input, length of output array on return
  34778. *
  34779. * RETURNS:
  34780. * returns a pointer to a canonicalized line on success, NULL on error.
  34781. */
  34782. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  34783. {
  34784. size_t end = 0;
  34785. char* canonLine = NULL;
  34786. if (line == NULL || len == NULL || *len == 0) {
  34787. return NULL;
  34788. }
  34789. end = *len;
  34790. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  34791. end--;
  34792. }
  34793. /* Need 2 chars for \r\n and 1 for EOL */
  34794. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  34795. if (canonLine == NULL) {
  34796. return NULL;
  34797. }
  34798. XMEMCPY(canonLine, line, end);
  34799. canonLine[end] = '\r';
  34800. canonLine[end+1] = '\n';
  34801. canonLine[end+2] = '\0';
  34802. *len = (word32)(end + 3);
  34803. return canonLine;
  34804. }
  34805. /*****************************************************************************
  34806. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  34807. * the provided header pointer.
  34808. *
  34809. * RETURNS:
  34810. * returns zero on success, non-zero on error.
  34811. */
  34812. int wc_MIME_free_hdrs(MimeHdr* head)
  34813. {
  34814. MimeHdr* curHdr = NULL;
  34815. MimeParam* curParam = NULL;
  34816. while (head) {
  34817. while (head->params) {
  34818. curParam = head->params;
  34819. head->params = head->params->next;
  34820. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  34821. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  34822. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  34823. }
  34824. curHdr = head;
  34825. head = head->next;
  34826. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  34827. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  34828. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  34829. }
  34830. return 0;
  34831. }
  34832. #endif /* HAVE_SMIME */
  34833. #undef ERROR_OUT
  34834. #ifdef WOLFSSL_ASN_PRINT
  34835. /*******************************************************************************
  34836. * ASN.1 Parsing and Printing Implementation
  34837. ******************************************************************************/
  34838. /* Initialize ASN.1 print options.
  34839. *
  34840. * @param [in, out] opts ASN.1 options for printing.
  34841. * @return 0 on success.
  34842. * @return BAD_FUNC_ARG when asn1 is NULL.
  34843. */
  34844. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  34845. {
  34846. int ret = 0;
  34847. if (opts == NULL) {
  34848. ret = BAD_FUNC_ARG;
  34849. }
  34850. else {
  34851. XMEMSET(opts, 0, sizeof(*opts));
  34852. }
  34853. return ret;
  34854. }
  34855. /* Set a print option into Asn1PrintOptions object.
  34856. *
  34857. * @param [in, out] opts ASN.1 options for printing.
  34858. * @param [in] opt Option to set value of.
  34859. * @param [in] val Value to set for option.
  34860. * @return 0 on success.
  34861. * @return BAD_FUNC_ARG when asn1 is NULL.
  34862. * @return BAD_FUNC_ARG when val is out of range for option.
  34863. */
  34864. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  34865. word32 val)
  34866. {
  34867. int ret = 0;
  34868. /* Validate parameters. */
  34869. if (opts == NULL) {
  34870. ret = BAD_FUNC_ARG;
  34871. }
  34872. if (ret == 0) {
  34873. switch (opt) {
  34874. /* Offset into DER/BER data to start decoding from. */
  34875. case ASN1_PRINT_OPT_OFFSET:
  34876. opts->offset = val;
  34877. break;
  34878. /* Length of DER/BER encoding to parse. */
  34879. case ASN1_PRINT_OPT_LENGTH:
  34880. opts->length = val;
  34881. break;
  34882. /* Number of spaces to indent for each change in depth. */
  34883. case ASN1_PRINT_OPT_INDENT:
  34884. /* Only 4 bits allowed for value. */
  34885. if (val >= (1 << 4)) {
  34886. ret = BAD_FUNC_ARG;
  34887. }
  34888. else {
  34889. opts->indent = (word8)val;
  34890. }
  34891. break;
  34892. /* Draw branches instead of indenting. */
  34893. case ASN1_PRINT_OPT_DRAW_BRANCH:
  34894. /* Boolean value. */
  34895. opts->draw_branch = (val > 0);
  34896. break;
  34897. /* Show raw data of primitive types as octets. */
  34898. case ASN1_PRINT_OPT_SHOW_DATA:
  34899. /* Boolean value. */
  34900. opts->show_data = (val > 0);
  34901. break;
  34902. /* Show header data as octets. */
  34903. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  34904. /* Boolean value. */
  34905. opts->show_header_data = (val > 0);
  34906. break;
  34907. /* Show the wolfSSL OID value for OBJECT_ID. */
  34908. case ASN1_PRINT_OPT_SHOW_OID:
  34909. /* Boolean value. */
  34910. opts->show_oid = (val > 0);
  34911. break;
  34912. /* Don't show text representations of primitive types. */
  34913. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  34914. /* Boolean value. */
  34915. opts->show_no_text = (val > 0);
  34916. break;
  34917. /* Don't show dump text representations of primitive types. */
  34918. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  34919. /* Boolean value. */
  34920. opts->show_no_dump_text = (val > 0);
  34921. break;
  34922. }
  34923. }
  34924. return ret;
  34925. }
  34926. /* Initialize an ASN.1 parse object.
  34927. *
  34928. * @param [in, out] asn1 ASN.1 parse object.
  34929. * @return 0 on success.
  34930. * @return BAD_FUNC_ARG when asn1 is NULL.
  34931. */
  34932. int wc_Asn1_Init(Asn1* asn1)
  34933. {
  34934. int ret = 0;
  34935. if (asn1 == NULL) {
  34936. ret = BAD_FUNC_ARG;
  34937. }
  34938. else {
  34939. XMEMSET(asn1, 0, sizeof(*asn1));
  34940. asn1->file = XBADFILE;
  34941. }
  34942. return ret;
  34943. }
  34944. /* Set the file to use when printing.
  34945. *
  34946. * @param [in, out] asn1 ASN.1 parse object.
  34947. * @param [in] file File to print to.
  34948. * @return 0 on success.
  34949. * @return BAD_FUNC_ARG when asn1 is NULL.
  34950. * @return BAD_FUNC_ARG when file is XBADFILE.
  34951. */
  34952. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  34953. {
  34954. int ret = 0;
  34955. if ((asn1 == NULL) || (file == XBADFILE)) {
  34956. ret = BAD_FUNC_ARG;
  34957. }
  34958. else {
  34959. asn1->file = file;
  34960. }
  34961. return ret;
  34962. }
  34963. /* Print OID in dotted form or as hex bytes.
  34964. *
  34965. * @param [in] file File pointer to write to.
  34966. * @param [in] oid OBJECT_ID data.
  34967. * @param [in] oid_len Length of OBJECT_ID data.
  34968. */
  34969. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  34970. {
  34971. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  34972. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  34973. word32 i;
  34974. /* Decode OBJECT_ID into dotted form array. */
  34975. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  34976. /* Print out each number of dotted form. */
  34977. for (i = 0; i < num; i++) {
  34978. XFPRINTF(file, "%d", dotted_nums[i]);
  34979. /* Add separator. */
  34980. if (i < num - 1) {
  34981. XFPRINTF(file, ".");
  34982. }
  34983. }
  34984. }
  34985. else {
  34986. /* Print out bytes as we couldn't decode. */
  34987. for (i = 0; i < len; i++) {
  34988. XFPRINTF(file, "%02x", oid[i]);
  34989. /* Add separator. */
  34990. if (i < len - 1) {
  34991. XFPRINTF(file, ":");
  34992. }
  34993. }
  34994. }
  34995. }
  34996. /* OID value to name mapping. */
  34997. typedef struct OidName {
  34998. /* wolfSSL OID value. */
  34999. word32 oid;
  35000. /* Long name to print when OID seen. */
  35001. const char* name;
  35002. } OidName;
  35003. /* Extra OID to name mappings. */
  35004. static const OidName extraOids[] = {
  35005. { 0x005c, "commonName" },
  35006. { 0x005d, "surname" },
  35007. { 0x005e, "serialNumber" },
  35008. { 0x005f, "countryName" },
  35009. { 0x0060, "localityName" },
  35010. { 0x0061, "stateOrProvinceName" },
  35011. { 0x0062, "streetAddress" },
  35012. { 0x0063, "organizationName" },
  35013. { 0x0064, "organizationUnitName" },
  35014. { 0x0065, "title" },
  35015. { 0x0086, "certificateExtension" },
  35016. { 0x028d, "emailAddress" },
  35017. { 0x0293, "challengePassword" },
  35018. { 0x029a, "extensionReq" },
  35019. };
  35020. /* Length of table of extra OID to name mappings. */
  35021. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  35022. /* Convert OID value to long name.
  35023. *
  35024. * @param [in] oid OID value.
  35025. * @param [out] name Long name for OID when known.
  35026. * @return 1 when OID known.
  35027. * @return 0 when OID not known.
  35028. */
  35029. static int Oid2LongName(word32 oid, const char** name)
  35030. {
  35031. int ret = 0;
  35032. int i;
  35033. /* Step through each entry in table. */
  35034. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  35035. if (extraOids[i].oid == oid) {
  35036. /* Return the name associated with the OID value. */
  35037. *name = extraOids[i].name;
  35038. ret = 1;
  35039. break;
  35040. }
  35041. }
  35042. return ret;
  35043. }
  35044. /* Print the text version of the OBJECT_ID.
  35045. *
  35046. * @param [in] asn1 ASN.1 parse object.
  35047. * @param [in] opts ASN.1 options for printing.
  35048. */
  35049. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  35050. {
  35051. word32 oid = (word32)-1;
  35052. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  35053. int nid;
  35054. #endif
  35055. const char* ln = NULL;
  35056. word32 i = 0;
  35057. int known = 1;
  35058. /* Get the OID value for the OBJECT_ID. */
  35059. if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  35060. asn1->item.len + 2) == ASN_PARSE_E) {
  35061. known = 0;
  35062. }
  35063. else
  35064. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  35065. /* Lookup NID for OID value. */
  35066. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  35067. /* Lookup long name for NID. */
  35068. ln = wolfSSL_OBJ_nid2ln(nid);
  35069. }
  35070. else
  35071. #endif
  35072. /* Lookup long name for extra known OID values. */
  35073. if (!Oid2LongName(oid, &ln)) {
  35074. /* Unknown OID value. */
  35075. ln = NULL;
  35076. known = 0;
  35077. }
  35078. XFPRINTF(asn1->file, ":");
  35079. /* Show OID value if not known or asked to. */
  35080. if ((!known) || opts->show_oid) {
  35081. XFPRINTF(asn1->file, "(0x%x) ", oid);
  35082. }
  35083. if (ln != NULL) {
  35084. /* Print long name. */
  35085. XFPRINTF(asn1->file, "%s", ln);
  35086. }
  35087. else {
  35088. /* Print out as numbers - either dotted or hex values. */
  35089. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  35090. asn1->item.len);
  35091. }
  35092. }
  35093. /* Print ASN.1 data as a character string.
  35094. *
  35095. * @param [in] asn1 ASN.1 parse object.
  35096. */
  35097. static void PrintText(Asn1* asn1)
  35098. {
  35099. word32 i;
  35100. XFPRINTF(asn1->file, ":");
  35101. /* Print all data bytes as characters. */
  35102. for (i = 0; i < asn1->item.len; i++) {
  35103. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  35104. }
  35105. }
  35106. /* Print data as a hex bytes.
  35107. *
  35108. * @param [in] file File pointer to write to.
  35109. * @param [in] data Data to print.
  35110. * @param [in] len Number of bytes to print.
  35111. */
  35112. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  35113. {
  35114. word32 i;
  35115. /* Print data bytes as hex numbers. */
  35116. for (i = 0; i < len; i++) {
  35117. XFPRINTF(file, "%02x", data[i]);
  35118. }
  35119. }
  35120. /* Print ASN.1 data as a hex bytes.
  35121. *
  35122. * @param [in] asn1 ASN.1 parse object.
  35123. */
  35124. static void PrintHexText(Asn1* asn1)
  35125. {
  35126. XFPRINTF(asn1->file, ":");
  35127. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  35128. }
  35129. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  35130. *
  35131. * @param [in] asn1 ASN.1 parse object.
  35132. */
  35133. static void PrintBitStringText(Asn1* asn1)
  35134. {
  35135. if (asn1->item.len > 0) {
  35136. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  35137. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  35138. asn1->item.len - 1);
  35139. }
  35140. }
  35141. /* Print ASN.1 BOOLEAN data as text with value.
  35142. *
  35143. * @param [in] asn1 ASN.1 parse object.
  35144. */
  35145. static void PrintBooleanText(Asn1* asn1)
  35146. {
  35147. /* Booleans should be 1 byte of data. */
  35148. if (asn1->item.len == 1) {
  35149. XFPRINTF(asn1->file, ":%s (%d)",
  35150. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  35151. asn1->data[asn1->item.data_idx]);
  35152. }
  35153. }
  35154. /* Print ASN.1 data as single byte +/- number.
  35155. *
  35156. * @param [in] asn1 ASN.1 parse object.
  35157. */
  35158. static void PrintNumberText(Asn1* asn1)
  35159. {
  35160. /* Only supporting 1 byte of data for now. */
  35161. if (asn1->item.len == 1) {
  35162. int num = asn1->data[asn1->item.data_idx];
  35163. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  35164. }
  35165. }
  35166. /* Print ASN.1 data as a text based on the tag.
  35167. *
  35168. * TODO: handle more tags.
  35169. *
  35170. * @param [in] asn1 ASN.1 parse object.
  35171. * @param [in] opts ASN.1 options for printing.
  35172. */
  35173. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  35174. {
  35175. /* Get the long name for OBJECT_ID where possible. */
  35176. if (asn1->item.tag == ASN_OBJECT_ID) {
  35177. PrintObjectIdText(asn1, opts);
  35178. }
  35179. /* Data is an array of printable characters. */
  35180. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  35181. (asn1->item.tag == ASN_IA5_STRING) ||
  35182. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  35183. (asn1->item.tag == ASN_T61STRING) ||
  35184. (asn1->item.tag == ASN_BMPSTRING) ||
  35185. (asn1->item.tag == ASN_UTC_TIME) ||
  35186. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  35187. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  35188. (asn1->item.tag == ASN_OBJECT_DESC) ||
  35189. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  35190. PrintText(asn1);
  35191. }
  35192. /* Show TRUE and FALSE with number. */
  35193. else if (asn1->item.tag == ASN_BOOLEAN) {
  35194. PrintBooleanText(asn1);
  35195. }
  35196. /* Show number. */
  35197. else if (asn1->item.tag == ASN_ENUMERATED) {
  35198. PrintNumberText(asn1);
  35199. }
  35200. /* Dumping potentially long string of hex digites. */
  35201. else if (!opts->show_no_dump_text) {
  35202. /* Dump all bytes. */
  35203. if ((asn1->item.tag == ASN_INTEGER) ||
  35204. (asn1->item.tag == ASN_OCTET_STRING) ||
  35205. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  35206. PrintHexText(asn1);
  35207. }
  35208. /* First byte is number of unused bits in last byte.
  35209. * Print first specially and dump rest of the bytes. */
  35210. else if (asn1->item.tag == ASN_BIT_STRING) {
  35211. PrintBitStringText(asn1);
  35212. }
  35213. }
  35214. }
  35215. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  35216. /* Dump data as hex bytes.
  35217. *
  35218. * @param [in] file File pointer to write to.
  35219. * @param [in] data Data to print.
  35220. * @param [in] len Number of bytes to print.
  35221. */
  35222. static void DumpData(XFILE file, unsigned char* data, word32 len)
  35223. {
  35224. word32 i;
  35225. word32 j;
  35226. for (i = 0; i < len; i += j) {
  35227. /* Print offset. */
  35228. XFPRINTF(file, " %04x:", i);
  35229. for (j = 0; (j < 16) && (i + j < len); j++) {
  35230. /* Print byte as hex number. */
  35231. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  35232. }
  35233. /* Print spaces between hex and characters. */
  35234. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  35235. for (j = 0; (j < 16) && (i + j < len); j++) {
  35236. /* Print byte as hex number. */
  35237. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  35238. }
  35239. XFPRINTF(file, "\n");
  35240. }
  35241. }
  35242. /* Update current depth based on the current position.
  35243. *
  35244. * @param [in, out] asn1 ASN.1 parse object.
  35245. */
  35246. static void UpdateDepth(Asn1* asn1)
  35247. {
  35248. /* If current index is greater than or equal end index then it is done. */
  35249. while ((asn1->depth > 0) &&
  35250. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  35251. /* Move up a depth. */
  35252. asn1->depth--;
  35253. }
  35254. }
  35255. /* Check validity of end index of constructed ASN.1 items.
  35256. *
  35257. * @param [in, out] asn1 ASN.1 parse object.
  35258. * @return 0 on success.
  35259. * @return ASN_DEPTH_E when end offset invalid.
  35260. */
  35261. static int CheckDepth(Asn1* asn1)
  35262. {
  35263. int ret = 0;
  35264. int i;
  35265. word32 curr_end = asn1->curr + asn1->item.len;
  35266. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  35267. /* Each end index must be at least as large as the current one. */
  35268. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  35269. ret = ASN_DEPTH_E;
  35270. }
  35271. /* Each end index must be at least as large as current index. */
  35272. if (asn1->end_idx[i] < curr_end) {
  35273. ret = ASN_DEPTH_E;
  35274. }
  35275. }
  35276. return ret;
  35277. }
  35278. /* Draw branching based on depth for an ASN.1 item.
  35279. *
  35280. * @param [in] asn1 ASN.1 parse object.
  35281. */
  35282. static void DrawBranch(Asn1* asn1)
  35283. {
  35284. int i;
  35285. word32 end = asn1->curr + asn1->item.len;
  35286. /* Write out the character for all depths but current. */
  35287. for (i = 0; i < asn1->depth; i++) {
  35288. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  35289. if (i < asn1->depth - 1) {
  35290. /* Constructed or not end index and not current depth: | */
  35291. XFPRINTF(asn1->file, "\xe2\x94\x82");
  35292. }
  35293. else {
  35294. /* Constructed or not end index and current depth: |- */
  35295. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  35296. }
  35297. }
  35298. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  35299. /* End index for previous: _|_ (in top half) */
  35300. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  35301. }
  35302. else {
  35303. /* End index but not for previous: L (in top half) */
  35304. XFPRINTF(asn1->file, "\xe2\x94\x94");
  35305. }
  35306. }
  35307. /* Prefix to tag name. */
  35308. if (asn1->item.cons) {
  35309. if (asn1->depth > 0) {
  35310. /* Have other line to connect to: T (in bottom half) */
  35311. XFPRINTF(asn1->file, "\xe2\x94\xac");
  35312. }
  35313. else {
  35314. /* Have no other line to connect to: r */
  35315. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  35316. }
  35317. }
  35318. else {
  35319. /* In a sequence: - */
  35320. XFPRINTF(asn1->file, "\xe2\x94\x80");
  35321. }
  35322. }
  35323. /* Print data as hex bytes separated by space.
  35324. *
  35325. * @param [in] file File pointer to write to.
  35326. * @param [in] data Data to print.
  35327. * @param [in] len Number of bytes to print.
  35328. */
  35329. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  35330. {
  35331. word32 i;
  35332. for (i = 0; i < len; i++) {
  35333. XFPRINTF(file, " %02x", data[i]);
  35334. }
  35335. }
  35336. /* Dump header data.
  35337. *
  35338. * @param [in] asn1 ASN.1 parse object.
  35339. * @param [in] opts ASN.1 options for printing.
  35340. */
  35341. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  35342. {
  35343. /* Put on same line when not showing data too and not showing text data. */
  35344. if ((!opts->show_data) && opts->show_no_text) {
  35345. XFPRINTF(asn1->file, "%10s", "");
  35346. }
  35347. else {
  35348. /* Align with start of data. */
  35349. XFPRINTF(asn1->file, "\n%12s", "");
  35350. }
  35351. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  35352. if (asn1->curr >= asn1->offset + 1) {
  35353. /* Print the header bytes as hex bytes separated by a space. */
  35354. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  35355. asn1->curr - (asn1->offset + 1));
  35356. }
  35357. }
  35358. /* Print ASN.1 item info based on header and indices.
  35359. *
  35360. * @param [in] asn1 ASN.1 parse object.
  35361. * @param [in] opts ASN.1 options for printing.
  35362. */
  35363. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  35364. {
  35365. /* Print offset of this ASN.1 item. */
  35366. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  35367. /* Print length of header. */
  35368. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  35369. /* Print data length. */
  35370. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  35371. asn1->item.cons ? ']' : ' ');
  35372. /* Print depth. */
  35373. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  35374. if (!opts->draw_branch) {
  35375. /* Indent to depth as required. */
  35376. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  35377. if (!opts->indent) {
  35378. /* Indicate constructed if no indent. */
  35379. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  35380. }
  35381. }
  35382. else {
  35383. /* Draw branch structure for ASN.1 item. */
  35384. XFPRINTF(asn1->file, " ");
  35385. DrawBranch(asn1);
  35386. }
  35387. /* Print tag name. */
  35388. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  35389. }
  35390. /* Expecting tag part of ASN.1 item. */
  35391. #define ASN_PART_TAG 0
  35392. /* Expecting length part of ASN.1 item. */
  35393. #define ASN_PART_LENGTH 1
  35394. /* Expecting data part of ASN.1 item. */
  35395. #define ASN_PART_DATA 2
  35396. /* Print next ASN.1 item.
  35397. *
  35398. * @param [in, out] asn1 ASN.1 parse object.
  35399. * @param [in] opts ASN.1 print options.
  35400. * @return 0 on success.
  35401. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  35402. * @return ASN_LEN_E when ASN.1 item's length too long.
  35403. * @return ASN_DEPTH_E when end offset invalid.
  35404. */
  35405. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  35406. {
  35407. int ret = 0;
  35408. /* Process tag. */
  35409. if (asn1->part == ASN_PART_TAG) {
  35410. /* Recalculate which depth we are at. */
  35411. UpdateDepth(asn1);
  35412. /* Get tag. */
  35413. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  35414. /* Store whether tag indicates constructed. */
  35415. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  35416. ASN_CONSTRUCTED;
  35417. /* Start of ASN.1 item is current index. */
  35418. asn1->offset = asn1->curr;
  35419. /* Step over tag. */
  35420. asn1->curr++;
  35421. /* Next part is length. */
  35422. asn1->part = ASN_PART_LENGTH;
  35423. }
  35424. /* Process length. */
  35425. if (asn1->part == ASN_PART_LENGTH) {
  35426. int len;
  35427. /* Decode length and step over it. */
  35428. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  35429. ret = ASN_LEN_E;
  35430. }
  35431. else {
  35432. /* Store ASN.1 item data offset. */
  35433. asn1->item.data_idx = asn1->curr;
  35434. /* Store ASN.1 item data length. */
  35435. asn1->item.len = (word32)len;
  35436. /* Print info about ASN.1 item. */
  35437. PrintInfo(asn1, opts);
  35438. if (!asn1->item.cons) {
  35439. /* Move on to print data. */
  35440. asn1->part = ASN_PART_DATA;
  35441. }
  35442. else {
  35443. /* Print header now if not printing data. */
  35444. if (opts->show_header_data) {
  35445. DumpHeader(asn1, opts);
  35446. }
  35447. XFPRINTF(asn1->file, "\n");
  35448. /* Record end offset for this depth. */
  35449. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  35450. /* Done with this ASN.1 item. */
  35451. asn1->part = ASN_PART_TAG;
  35452. }
  35453. /* Check end indices are valid. */
  35454. ret = CheckDepth(asn1);
  35455. }
  35456. }
  35457. /* Process data. */
  35458. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  35459. if (!opts->show_no_text) {
  35460. /* Print text representation of data. */
  35461. PrintAsn1Text(asn1, opts);
  35462. }
  35463. if (opts->show_header_data) {
  35464. /* Dump header bytes. */
  35465. DumpHeader(asn1, opts);
  35466. }
  35467. XFPRINTF(asn1->file, "\n");
  35468. if (opts->show_data) {
  35469. /* Dump data bytes. */
  35470. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  35471. asn1->item.len);
  35472. }
  35473. /* Step past data to next ASN.1 item. */
  35474. asn1->curr += asn1->item.len;
  35475. /* Update the depth based on end indices. */
  35476. UpdateDepth(asn1);
  35477. /* Done with this ASN.1 item. */
  35478. asn1->part = ASN_PART_TAG;
  35479. }
  35480. /* Make ASN.1 item printing go out. */
  35481. fflush(asn1->file);
  35482. return ret;
  35483. }
  35484. /* Print all ASN.1 items.
  35485. *
  35486. * @param [in, out] asn1 ASN.1 parse object.
  35487. * @param [in] opts ASN.1 print options.
  35488. * @param [in] data BER/DER data to print.
  35489. * @param [in] len Length of data to print in bytes.
  35490. * @return 0 on success.
  35491. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  35492. * @return ASN_LEN_E when ASN.1 item's length too long.
  35493. * @return ASN_DEPTH_E when end offset invalid.
  35494. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  35495. */
  35496. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  35497. word32 len)
  35498. {
  35499. int ret = 0;
  35500. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  35501. ret = BAD_FUNC_ARG;
  35502. }
  35503. if (ret == 0) {
  35504. /* Initialize start position. */
  35505. asn1->curr = 0;
  35506. /* Start parsing at tag. */
  35507. asn1->part = ASN_PART_TAG;
  35508. /* Start depth at 0. */
  35509. asn1->depth = 0;
  35510. /* Store the starting point of the data to parse. */
  35511. asn1->data = data + opts->offset;
  35512. if (opts->length > 0) {
  35513. /* Use user specified maximum length. */
  35514. asn1->max = opts->length;
  35515. }
  35516. else {
  35517. /* Maximum length is up to end from offset. */
  35518. asn1->max = len - opts->offset;
  35519. }
  35520. /* Keep going while no error and have data to parse. */
  35521. while ((ret == 0) && (asn1->curr < asn1->max)) {
  35522. /* Print an ASN.1 item. */
  35523. ret = wc_Asn1_Print(asn1, opts);
  35524. }
  35525. }
  35526. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  35527. /* Stopped before finishing ASN.1 item. */
  35528. ret = ASN_PARSE_E;
  35529. }
  35530. if ((ret == 0) && (asn1->depth != 0)) {
  35531. /* Stopped without seeing all items in a constructed item. */
  35532. ret = ASN_DEPTH_E;
  35533. }
  35534. return ret;
  35535. }
  35536. #endif /* WOLFSSL_ASN_PRINT */
  35537. #endif /* !NO_ASN */
  35538. /* Functions that parse, but are not using ASN.1 */
  35539. #if !defined(NO_RSA) && (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  35540. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  35541. /* this function does not use any ASN.1 parsing */
  35542. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  35543. word32 eSz, RsaKey* key)
  35544. {
  35545. if (n == NULL || e == NULL || key == NULL)
  35546. return BAD_FUNC_ARG;
  35547. key->type = RSA_PUBLIC;
  35548. if (mp_init(&key->n) != MP_OKAY)
  35549. return MP_INIT_E;
  35550. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  35551. mp_clear(&key->n);
  35552. return ASN_GETINT_E;
  35553. }
  35554. #ifdef HAVE_WOLF_BIGINT
  35555. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  35556. mp_clear(&key->n);
  35557. return ASN_GETINT_E;
  35558. }
  35559. #endif /* HAVE_WOLF_BIGINT */
  35560. if (mp_init(&key->e) != MP_OKAY) {
  35561. mp_clear(&key->n);
  35562. return MP_INIT_E;
  35563. }
  35564. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  35565. mp_clear(&key->n);
  35566. mp_clear(&key->e);
  35567. return ASN_GETINT_E;
  35568. }
  35569. #ifdef HAVE_WOLF_BIGINT
  35570. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  35571. mp_clear(&key->n);
  35572. mp_clear(&key->e);
  35573. return ASN_GETINT_E;
  35574. }
  35575. #endif /* HAVE_WOLF_BIGINT */
  35576. #ifdef WOLFSSL_XILINX_CRYPT
  35577. if (wc_InitRsaHw(key) != 0) {
  35578. return BAD_STATE_E;
  35579. }
  35580. #endif
  35581. return 0;
  35582. }
  35583. #endif /* !NO_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  35584. #ifdef WOLFSSL_SEP
  35585. #endif /* WOLFSSL_SEP */