asn.c 1.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603
  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_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  71. responses. The nonces are optional and may not be supported by all
  72. responders. If it can be ensured that the used responder sends nonces this
  73. option may improve security.
  74. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  75. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  76. templates.
  77. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  78. type issues for testing
  79. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  80. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  81. Only supports copying full AKID from an existing certificate.
  82. * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
  83. extensions
  84. * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
  85. lengths and encodings.
  86. * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
  87. extension.
  88. * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
  89. * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
  90. * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
  91. cost of taking up more memory. Adds initials, givenname, dnQualifer for
  92. example.
  93. * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
  94. */
  95. #include <wolfssl/wolfcrypt/error-crypt.h>
  96. #ifndef NO_RSA
  97. #include <wolfssl/wolfcrypt/rsa.h>
  98. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  99. extern int wc_InitRsaHw(RsaKey* key);
  100. #endif
  101. #endif
  102. #ifndef NO_ASN
  103. #include <wolfssl/wolfcrypt/asn.h>
  104. #include <wolfssl/wolfcrypt/coding.h>
  105. #include <wolfssl/wolfcrypt/md2.h>
  106. #include <wolfssl/wolfcrypt/hmac.h>
  107. #include <wolfssl/wolfcrypt/pwdbased.h>
  108. #include <wolfssl/wolfcrypt/des3.h>
  109. #include <wolfssl/wolfcrypt/aes.h>
  110. #include <wolfssl/wolfcrypt/rc2.h>
  111. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  112. #include <wolfssl/wolfcrypt/logging.h>
  113. #include <wolfssl/wolfcrypt/random.h>
  114. #include <wolfssl/wolfcrypt/hash.h>
  115. #ifdef NO_INLINE
  116. #include <wolfssl/wolfcrypt/misc.h>
  117. #else
  118. #define WOLFSSL_MISC_INCLUDED
  119. #include <wolfcrypt/src/misc.c>
  120. #endif
  121. #ifndef NO_RC4
  122. #include <wolfssl/wolfcrypt/arc4.h>
  123. #endif
  124. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  125. #include <wolfssl/wolfcrypt/sha512.h>
  126. #endif
  127. #ifndef NO_SHA256
  128. #include <wolfssl/wolfcrypt/sha256.h>
  129. #endif
  130. #ifdef HAVE_ECC
  131. #include <wolfssl/wolfcrypt/ecc.h>
  132. #endif
  133. #ifdef WOLFSSL_SM2
  134. #include <wolfssl/wolfcrypt/sm2.h>
  135. #endif
  136. #ifdef HAVE_ED25519
  137. #include <wolfssl/wolfcrypt/ed25519.h>
  138. #endif
  139. #ifdef HAVE_CURVE25519
  140. #include <wolfssl/wolfcrypt/curve25519.h>
  141. #endif
  142. #ifdef HAVE_ED448
  143. #include <wolfssl/wolfcrypt/ed448.h>
  144. #endif
  145. #ifdef HAVE_CURVE448
  146. #include <wolfssl/wolfcrypt/curve448.h>
  147. #endif
  148. #ifdef HAVE_PQC
  149. #if defined(HAVE_FALCON)
  150. #include <wolfssl/wolfcrypt/falcon.h>
  151. #endif
  152. #if defined(HAVE_DILITHIUM)
  153. #include <wolfssl/wolfcrypt/dilithium.h>
  154. #endif
  155. #if defined(HAVE_SPHINCS)
  156. #include <wolfssl/wolfcrypt/sphincs.h>
  157. #endif
  158. #endif
  159. #ifdef WOLFSSL_QNX_CAAM
  160. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  161. #endif
  162. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  163. #include <wolfssl/wolfcrypt/port/Renesas/renesas_cmn.h>
  164. #endif
  165. #ifndef NO_DSA
  166. #include <wolfssl/wolfcrypt/dsa.h>
  167. #else
  168. typedef void* DsaKey;
  169. #endif
  170. #ifdef WOLF_CRYPTO_CB
  171. #include <wolfssl/wolfcrypt/cryptocb.h>
  172. #endif
  173. #ifndef WOLFCRYPT_ONLY
  174. #include <wolfssl/internal.h>
  175. #endif
  176. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  177. #include <wolfssl/openssl/objects.h>
  178. #endif
  179. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  180. !defined(WOLFCRYPT_ONLY)
  181. #define WOLFSSL_X509_NAME_AVAILABLE
  182. #endif
  183. #ifdef _MSC_VER
  184. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  185. #pragma warning(disable: 4996)
  186. #endif
  187. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  188. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  189. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  190. (!defined(HAVE_SELFTEST_VERSION) || \
  191. HAVE_SELFTEST_VERSION < 2))
  192. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  193. #define WOLFSSL_AES_KEY_SIZE_ENUM
  194. enum Asn_Misc {
  195. AES_IV_SIZE = 16,
  196. AES_128_KEY_SIZE = 16,
  197. AES_192_KEY_SIZE = 24,
  198. AES_256_KEY_SIZE = 32
  199. };
  200. #endif
  201. #endif /* HAVE_SELFTEST */
  202. #endif
  203. #if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)
  204. /* String representations of tags. */
  205. static const char* tagString[4][32] = {
  206. /* Universal */
  207. {
  208. "EOC",
  209. "BOOLEAN",
  210. "INTEGER",
  211. "BIT STRING",
  212. "OCTET STRING",
  213. "NULL",
  214. "OBJECT ID",
  215. "ObjectDescriptor",
  216. "INSTANCE OF",
  217. "REAL",
  218. "ENUMERATED",
  219. "EMBEDDED PDV",
  220. "UT8String",
  221. "RELATIVE-OID",
  222. "(0x0e) 14",
  223. "(0x0f) 15",
  224. "SEQUENCE",
  225. "SET",
  226. "NumericString",
  227. "PrintableString",
  228. "T61String",
  229. "VideotexString",
  230. "IA5String",
  231. "UTCTime",
  232. "GeneralizedTime",
  233. "GraphicString",
  234. "ISO646String",
  235. "GeneralString",
  236. "UniversalString",
  237. "CHARACTER STRING",
  238. "BMPString",
  239. "(0x1f) 31",
  240. },
  241. /* Application */
  242. {
  243. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  244. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  245. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  246. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  247. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  248. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  249. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  250. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  251. },
  252. /* Context-Specific */
  253. {
  254. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  255. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  256. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  257. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  258. },
  259. /* Private */
  260. {
  261. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  262. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  263. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  264. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  265. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  266. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  267. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  268. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  269. }
  270. };
  271. /* Converts a tag byte to string.
  272. *
  273. * @param [in] tag BER tag value to interpret.
  274. * @return String corresponding to tag.
  275. */
  276. static const char* TagString(byte tag)
  277. {
  278. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  279. }
  280. #endif
  281. /* Calculates the minimum number of bytes required to encode the value.
  282. *
  283. * Only support up to 2^24-1.
  284. *
  285. * @param [in] value Value to be encoded.
  286. * @return Number of bytes to encode value.
  287. */
  288. static word32 BytePrecision(word32 value)
  289. {
  290. word32 i;
  291. for (i = (word32)sizeof(value) - 1; i; --i)
  292. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  293. break;
  294. return i;
  295. }
  296. /* DER encodes the length value in output buffer.
  297. *
  298. * 0 -> 2^7-1: <len byte>.
  299. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  300. *
  301. * @param [in] length Value to encode.
  302. * @param [in, out] output Buffer to encode into.
  303. * @return Number of bytes used in encoding.
  304. */
  305. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  306. {
  307. word32 i = 0;
  308. if (length < ASN_LONG_LENGTH)
  309. output[i++] = (byte)length;
  310. else {
  311. word32 j;
  312. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  313. for (j = BytePrecision(length); j; --j) {
  314. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  315. i++;
  316. }
  317. }
  318. return i;
  319. }
  320. #ifdef WOLFSSL_ASN_TEMPLATE
  321. /* Calculate the size of a DER encoded length value.
  322. *
  323. * 0 -> 2^7-1: <length byte>.
  324. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  325. *
  326. * @param [in] length Value to encode.
  327. * @return Number of bytes required to encode.
  328. */
  329. static word32 SizeASNLength(word32 length)
  330. {
  331. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  332. }
  333. /* Calculate the size of a DER encoded header.
  334. *
  335. * Header = Tag | Encoded length
  336. *
  337. * @param [in] length Length value to encode.
  338. * @return Number of bytes required to encode a DER header.
  339. */
  340. #define SizeASNHeader(length) \
  341. (1 + SizeASNLength(length))
  342. #endif
  343. #ifdef WOLFSSL_ASN_TEMPLATE
  344. #ifdef WOLFSSL_SMALL_STACK
  345. /* Declare the variable that is the dynamic data for decoding BER data.
  346. *
  347. * @param [in] name Variable name to declare.
  348. * @param [in] cnt Number of elements required.
  349. */
  350. #define DECL_ASNGETDATA(name, cnt) \
  351. ASNGetData* name = NULL
  352. /* Allocates the dynamic BER decoding data.
  353. *
  354. * @param [in] name Variable name to declare.
  355. * @param [in] cnt Number of elements required.
  356. * @param [in, out] err Error variable.
  357. * @param [in] heap Dynamic memory allocation hint.
  358. */
  359. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  360. do { \
  361. if ((err) == 0) { \
  362. (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  363. DYNAMIC_TYPE_TMP_BUFFER); \
  364. if ((name) == NULL) { \
  365. (err) = MEMORY_E; \
  366. } \
  367. } \
  368. } \
  369. while (0)
  370. /* Allocates the dynamic BER decoding data and clears the memory.
  371. *
  372. * @param [in] name Variable name to declare.
  373. * @param [in] cnt Number of elements required.
  374. * @param [in, out] err Error variable.
  375. * @param [in] heap Dynamic memory allocation hint.
  376. */
  377. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  378. do { \
  379. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  380. if ((err) == 0) { \
  381. XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
  382. } \
  383. } \
  384. while (0)
  385. /* Disposes of the dynamic BER decoding data.
  386. *
  387. * @param [in] name Variable name to declare.
  388. * @param [in] heap Dynamic memory allocation hint.
  389. */
  390. #define FREE_ASNGETDATA(name, heap) \
  391. do { \
  392. if ((name) != NULL) { \
  393. XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
  394. } \
  395. } \
  396. while (0)
  397. /* Declare the variable that is the dynamic data for encoding DER data.
  398. *
  399. * @param [in] name Variable name to declare.
  400. * @param [in] cnt Number of elements required.
  401. */
  402. #define DECL_ASNSETDATA(name, cnt) \
  403. ASNSetData* name = NULL
  404. /* Allocates the dynamic DER encoding data.
  405. *
  406. * @param [in] name Variable name to declare.
  407. * @param [in] cnt Number of elements required.
  408. * @param [in, out] err Error variable.
  409. * @param [in] heap Dynamic memory allocation hint.
  410. */
  411. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  412. do { \
  413. if ((err) == 0) { \
  414. (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  415. DYNAMIC_TYPE_TMP_BUFFER); \
  416. if ((name) == NULL) { \
  417. (err) = MEMORY_E; \
  418. } \
  419. } \
  420. } \
  421. while (0)
  422. /* Allocates the dynamic DER encoding data and clears the memory.
  423. *
  424. * @param [in] name Variable name to declare.
  425. * @param [in] cnt Number of elements required.
  426. * @param [in, out] err Error variable.
  427. * @param [in] heap Dynamic memory allocation hint.
  428. */
  429. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  430. do { \
  431. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  432. if ((err) == 0) { \
  433. XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
  434. } \
  435. } \
  436. while (0)
  437. /* Disposes of the dynamic DER encoding data.
  438. *
  439. * @param [in] name Variable name to declare.
  440. * @param [in] heap Dynamic memory allocation hint.
  441. */
  442. #define FREE_ASNSETDATA(name, heap) \
  443. do { \
  444. if ((name) != NULL) { \
  445. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  446. } \
  447. } \
  448. while (0)
  449. #else
  450. /* Declare the variable that is the dynamic data for decoding BER data.
  451. *
  452. * @param [in] name Variable name to declare.
  453. * @param [in] cnt Number of elements required.
  454. */
  455. #define DECL_ASNGETDATA(name, cnt) \
  456. ASNGetData name[cnt]
  457. /* No implementation as declaration is static.
  458. *
  459. * @param [in] name Variable name to declare.
  460. * @param [in] cnt Number of elements required.
  461. * @param [in, out] err Error variable.
  462. * @param [in] heap Dynamic memory allocation hint.
  463. */
  464. #define ALLOC_ASNGETDATA(name, cnt, err, heap) WC_DO_NOTHING
  465. /* Clears the memory of the dynamic BER encoding data.
  466. *
  467. * @param [in] name Variable name to declare.
  468. * @param [in] cnt Number of elements required.
  469. * @param [in, out] err Error variable.
  470. * @param [in] heap Dynamic memory allocation hint.
  471. */
  472. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  473. XMEMSET(name, 0, sizeof(name))
  474. /* No implementation as declaration is static.
  475. *
  476. * @param [in] name Variable name to declare.
  477. * @param [in] heap Dynamic memory allocation hint.
  478. */
  479. #define FREE_ASNGETDATA(name, heap) WC_DO_NOTHING
  480. /* Declare the variable that is the dynamic data for encoding DER data.
  481. *
  482. * @param [in] name Variable name to declare.
  483. * @param [in] cnt Number of elements required.
  484. */
  485. #define DECL_ASNSETDATA(name, cnt) \
  486. ASNSetData name[cnt]
  487. /* No implementation as declaration is static.
  488. *
  489. * @param [in] name Variable name to declare.
  490. * @param [in] cnt Number of elements required.
  491. * @param [in, out] err Error variable.
  492. * @param [in] heap Dynamic memory allocation hint.
  493. */
  494. #define ALLOC_ASNSETDATA(name, cnt, err, heap) WC_DO_NOTHING
  495. /* Clears the memory of the dynamic BER encoding data.
  496. *
  497. * @param [in] name Variable name to declare.
  498. * @param [in] cnt Number of elements required.
  499. * @param [in, out] err Error variable.
  500. * @param [in] heap Dynamic memory allocation hint.
  501. */
  502. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  503. XMEMSET(name, 0, sizeof(name))
  504. /* No implementation as declaration is static.
  505. *
  506. * @param [in] name Variable name to declare.
  507. * @param [in] heap Dynamic memory allocation hint.
  508. */
  509. #define FREE_ASNSETDATA(name, heap) WC_DO_NOTHING
  510. #endif
  511. #ifdef DEBUG_WOLFSSL
  512. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  513. #if 0
  514. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  515. #endif
  516. #endif
  517. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  518. #include <stdarg.h>
  519. /* Log a message that has the printf format string.
  520. *
  521. * @param [in] <va_args> printf style arguments.
  522. */
  523. #define WOLFSSL_MSG_VSNPRINTF(...) \
  524. do { \
  525. char line[81]; \
  526. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  527. line[sizeof(line) - 1] = '\0'; \
  528. WOLFSSL_MSG(line); \
  529. } \
  530. while (0)
  531. #endif
  532. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  533. *
  534. * @param [in] asn ASN.1 items to encode.
  535. * @param [in] data_a Data to place in each item. Lengths set were not known.
  536. * @param [in] i Index of item to check.
  537. * @return 1 when ASN.1 item is an integer and MSB is 1.
  538. * @return 0 otherwise.
  539. */
  540. #define ASNIntMSBSet(asn, data_a, i) \
  541. (((asn)[i].tag == ASN_INTEGER) && \
  542. ((data_a)[i].data.buffer.data != NULL && \
  543. ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
  544. /* Calculate the size of a DER encoded number.
  545. *
  546. * @param [in] n Number to be encoded.
  547. * @param [in] bits Maximum number of bits to encode.
  548. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  549. * @return Number of bytes to the ASN.1 item.
  550. */
  551. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  552. {
  553. int j;
  554. word32 len;
  555. len = 1 + 1 + (word32)bits / 8;
  556. /* Discover actual size by checking for high zeros. */
  557. for (j = bits - 8; j > 0; j -= 8) {
  558. if (n >> j)
  559. break;
  560. len--;
  561. }
  562. if (tag == ASN_BIT_STRING)
  563. len++;
  564. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  565. len++;
  566. return len;
  567. }
  568. /* Calculate the size of the data in the constructed item based on the
  569. * length of the ASN.1 items below.
  570. *
  571. * @param [in] asn ASN.1 items to encode.
  572. * @param [in, out] data Data to place in each item. Lengths set were not
  573. * known.
  574. * @param [in] idx Index of item working on.
  575. */
  576. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  577. int idx, int maxIdx)
  578. {
  579. int j;
  580. data[idx].data.buffer.length = 0;
  581. /* Sum the item length of all items underneath. */
  582. for (j = idx + 1; j < maxIdx; j++) {
  583. /* Stop looking if the next ASN.1 is same level or higher. */
  584. if (asn[j].depth <= asn[idx].depth)
  585. break;
  586. /* Only add in length if it is one level below. */
  587. if (asn[j].depth - 1 == asn[idx].depth) {
  588. data[idx].data.buffer.length += data[j].length;
  589. /* The length of a header only item doesn't include the data unless
  590. * a replacement buffer is supplied.
  591. */
  592. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  593. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  594. data[idx].data.buffer.length += data[j].data.buffer.length;
  595. }
  596. }
  597. }
  598. }
  599. /* Calculate the size of the DER encoding.
  600. *
  601. * Call SetASN_Items() to write encoding to a buffer.
  602. *
  603. * @param [in] asn ASN.1 items to encode.
  604. * @param [in, out] data Data to place in each item. Lengths set where not
  605. * known.
  606. * @param [in] count Count of items to encode.
  607. * @param [out] encSz Length of the DER encoding.
  608. * @return 0 on success.
  609. * @return BAD_STATE_E when the data type is not supported.
  610. */
  611. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  612. {
  613. int i;
  614. word32 sz = 0;
  615. word32 len;
  616. word32 dataLen;
  617. int length;
  618. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  619. WOLFSSL_ENTER("SizeASN_Items");
  620. #endif
  621. for (i = count - 1; i >= 0; i--) {
  622. /* Skip this ASN.1 item when encoding. */
  623. if (data[i].noOut) {
  624. /* Set the offset to the current size - used in writing DER. */
  625. data[i].offset = sz;
  626. continue;
  627. }
  628. len = 0;
  629. switch (data[i].dataType) {
  630. /* Calculate the size of the number of different sizes. */
  631. case ASN_DATA_TYPE_WORD8:
  632. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  633. break;
  634. case ASN_DATA_TYPE_WORD16:
  635. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  636. break;
  637. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  638. /* Not used yet! */
  639. case ASN_DATA_TYPE_WORD32:
  640. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  641. break;
  642. #endif
  643. case ASN_DATA_TYPE_MP:
  644. /* Calculate the size of the MP integer data. */
  645. length = mp_unsigned_bin_size(data[i].data.mp);
  646. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  647. len = (word32)SizeASNHeader((word32)length) + (word32)length;
  648. break;
  649. case ASN_DATA_TYPE_REPLACE_BUFFER:
  650. /* Buffer is put in directly - use the length. */
  651. len = data[i].data.buffer.length;
  652. break;
  653. case ASN_DATA_TYPE_NONE:
  654. /* Calculate the size based on the data to be included.
  655. * Mostly used for constructed items.
  656. */
  657. if (asn[i].headerOnly) {
  658. if (data[i].data.buffer.data != NULL) {
  659. /* Force all child nodes to be ignored. Buffer
  660. * overwrites children. */
  661. {
  662. int ii;
  663. for (ii = i + 1; ii < count; ii++) {
  664. if (asn[ii].depth <= asn[i].depth)
  665. break;
  666. sz -= data[ii].length;
  667. data[ii].noOut = 1;
  668. }
  669. }
  670. }
  671. else {
  672. /* Calculate data length from items below if no buffer
  673. * supplied. */
  674. SizeASN_CalcDataLength(asn, data, i, count);
  675. }
  676. }
  677. if (asn[i].tag == ASN_BOOLEAN) {
  678. dataLen = 1;
  679. }
  680. else {
  681. dataLen = data[i].data.buffer.length;
  682. }
  683. /* BIT_STRING and INTEGER have one byte prepended. */
  684. if ((asn[i].tag == ASN_BIT_STRING) ||
  685. ASNIntMSBSet(asn, data, i)) {
  686. dataLen++;
  687. /* ASN.1 items are below and cannot include extra byte. */
  688. if (asn[i].headerOnly) {
  689. len++;
  690. }
  691. }
  692. /* Add in the size of tag and length. */
  693. len += SizeASNHeader(dataLen);
  694. /* Include data in length if not header only or if
  695. * buffer supplied. */
  696. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  697. len += dataLen;
  698. }
  699. break;
  700. #ifdef DEBUG_WOLFSSL
  701. default:
  702. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  703. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  704. WOLFSSL_MSG("Bad data type");
  705. #endif
  706. return BAD_STATE_E;
  707. #endif
  708. }
  709. /* Set the total length of the item. */
  710. data[i].length = len;
  711. /* Add length to total size. */
  712. sz += len;
  713. /* Set the offset to the current size - used in writing DER. */
  714. data[i].offset = sz;
  715. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  716. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  717. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  718. asn[i].depth, "", TagString(asn[i].tag));
  719. #endif
  720. }
  721. *encSz = (int)sz;
  722. return 0;
  723. }
  724. /* Create the DER encoding of a number.
  725. *
  726. * Assumes that the out buffer is large enough for encoding.
  727. *
  728. * @param [in] n Number to be encoded.
  729. * @param [in] bits Maximum number of bits to encode.
  730. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  731. */
  732. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  733. {
  734. int j;
  735. word32 idx;
  736. byte len;
  737. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  738. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  739. idx = 2;
  740. /* Set the length of the number based on maximum bit length. */
  741. len = (byte)(bits / 8);
  742. /* Discover actual size by checking for leading zero bytes. */
  743. for (j = bits - 8; j > 0; j -= 8) {
  744. if ((n >> j) != 0) {
  745. break;
  746. }
  747. len--;
  748. }
  749. /* Keep j, index of first non-zero byte, for writing out. */
  750. /* A BIT_STRING has the number of unused bits in last byte prepended to
  751. * data.
  752. */
  753. if (tag == ASN_BIT_STRING) {
  754. byte unusedBits = 0;
  755. byte lastByte = (byte)(n >> j);
  756. /* Quick check last bit. */
  757. if ((lastByte & 0x01) == 0x00) {
  758. unusedBits++;
  759. /* Check each bit for first least significant bit set. */
  760. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  761. unusedBits++;
  762. }
  763. /* Add unused bits byte. */
  764. len++;
  765. out[idx++] = unusedBits;
  766. }
  767. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  768. * value positive. */
  769. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  770. len++;
  771. out[idx++] = 0;
  772. }
  773. /* Go back and put in length. */
  774. out[1] = len;
  775. /* Place in the required bytes of the number. */
  776. for (; j >= 0; j -= 8)
  777. out[idx++] = (byte)(n >> j);
  778. }
  779. /* Creates the DER encoding of the ASN.1 items.
  780. *
  781. * Assumes the output buffer is large enough to hold encoding.
  782. * Must call SizeASN_Items() to determine size of encoding and offsets.
  783. *
  784. * @param [in] asn ASN.1 items to encode.
  785. * @param [in] data Data to place in each item.
  786. * @param [in] count Count of items to encode.
  787. * @param [in, out] output Buffer to write encoding into.
  788. * @return Size of the DER encoding in bytes.
  789. */
  790. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  791. {
  792. int i;
  793. int length;
  794. int err;
  795. word32 sz;
  796. word32 idx;
  797. byte* out;
  798. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  799. WOLFSSL_ENTER("SetASN_Items");
  800. #endif
  801. /* Offset of first item is the total length.
  802. * SizeASN_Items() calculated this. */
  803. sz = data[0].offset;
  804. /* Write out each item. */
  805. for (i = 0; i < count; i++) {
  806. /* Skip items not writing out. */
  807. if (data[i].noOut)
  808. continue;
  809. /* Start position to write item based on reverse offsets. */
  810. out = output + sz - data[i].offset;
  811. /* Index from start of item out. */
  812. idx = 0;
  813. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  814. /* Put in the tag - not dumping in DER from buffer. */
  815. out[idx++] = asn[i].tag |
  816. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  817. }
  818. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  819. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  820. sz - data[i].offset,
  821. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  822. "", TagString(asn[i].tag));
  823. #endif
  824. switch (data[i].dataType) {
  825. /* Write out the length and data of a number. */
  826. case ASN_DATA_TYPE_WORD8:
  827. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  828. break;
  829. case ASN_DATA_TYPE_WORD16:
  830. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  831. break;
  832. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  833. /* Not used yet! */
  834. case ASN_DATA_TYPE_WORD32:
  835. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  836. break;
  837. #endif
  838. /* Write out the length and data of a multi-precision number. */
  839. case ASN_DATA_TYPE_MP:
  840. /* Get length in bytes. */
  841. length = mp_unsigned_bin_size(data[i].data.mp);
  842. /* Add one for leading zero to make encoding a positive num. */
  843. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  844. /* Write out length. */
  845. idx += SetASNLength((word32)length, out + idx);
  846. /* Write out leading zero to make positive. */
  847. if (mp_leading_bit(data[i].data.mp)) {
  848. out[idx++] = 0;
  849. }
  850. /* Encode number in big-endian byte array. */
  851. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  852. if (err != MP_OKAY) {
  853. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  854. return MP_TO_E;
  855. }
  856. break;
  857. case ASN_DATA_TYPE_REPLACE_BUFFER:
  858. if (data[i].data.buffer.data == NULL) {
  859. /* Return pointer for caller to use. */
  860. data[i].data.buffer.data = out + idx;
  861. }
  862. else {
  863. /* Dump in the DER encoded data. */
  864. XMEMCPY(out + idx, data[i].data.buffer.data,
  865. data[i].data.buffer.length);
  866. }
  867. break;
  868. case ASN_DATA_TYPE_NONE:
  869. if (asn[i].tag == ASN_BOOLEAN) {
  870. /* Always one byte of data. */
  871. out[idx++] = 1;
  872. /* TRUE = 0xff, FALSE = 0x00 */
  873. out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
  874. }
  875. else if (asn[i].tag == ASN_TAG_NULL) {
  876. /* NULL tag is always a zero length item. */
  877. out[idx] = 0;
  878. }
  879. else {
  880. word32 dataLen = data[i].data.buffer.length;
  881. /* Add one to data length for BIT_STRING unused bits and
  882. * INTEGER leading zero to make positive.
  883. */
  884. if ((asn[i].tag == ASN_BIT_STRING) ||
  885. ASNIntMSBSet(asn, data, i)) {
  886. dataLen++;
  887. }
  888. /* Write out length. */
  889. idx += SetASNLength(dataLen, out + idx);
  890. if ((asn[i].tag == ASN_BIT_STRING) ||
  891. ASNIntMSBSet(asn, data, i)) {
  892. /* Write out leading byte. BIT_STRING has no unused bits
  893. * - use number data types if needed. */
  894. out[idx++] = 0x00;
  895. }
  896. /* Record pointer for caller if data not supplied. */
  897. if (data[i].data.buffer.data == NULL) {
  898. data[i].data.buffer.data = out + idx;
  899. }
  900. /* Copy supplied data if not putting out header only or
  901. * if buffer supplied. */
  902. else if (!asn[i].headerOnly ||
  903. data[i].data.buffer.data != NULL) {
  904. /* Allow data to come from output buffer. */
  905. XMEMMOVE(out + idx, data[i].data.buffer.data,
  906. data[i].data.buffer.length);
  907. }
  908. }
  909. break;
  910. #ifdef DEBUG_WOLFSSL
  911. default:
  912. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  913. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  914. #endif
  915. return BAD_STATE_E;
  916. #endif
  917. }
  918. }
  919. return (int)sz;
  920. }
  921. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  922. word32 oidType, int length);
  923. /* Maximum supported depth in ASN.1 description. */
  924. #define GET_ASN_MAX_DEPTH 7
  925. /* Maximum number of checked numbered choices. Only one of the items with the
  926. * number is allowed.
  927. */
  928. #define GET_ASN_MAX_CHOICES 2
  929. /* Use existing function to decode BER length encoding. */
  930. #define GetASN_Length GetLength_ex
  931. /* Check an INTEGER's first byte - must be a positive number.
  932. *
  933. * @param [in] input BER encoded data.
  934. * @param [in] idx Index of BIT_STRING data.
  935. * @param [in] length Length of input data.
  936. * @param [in] positive Indicates number must be positive.
  937. * @return 0 on success.
  938. * @return ASN_PARSE_E when 0 is not required but seen.
  939. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  940. */
  941. static int GetASN_Integer(const byte* input, word32 idx, int length,
  942. int positive)
  943. {
  944. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  945. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  946. /* Check contents consist of one or more octets. */
  947. if (length == 0) {
  948. WOLFSSL_MSG("Zero length INTEGER not allowed");
  949. return ASN_PARSE_E;
  950. }
  951. #endif
  952. if (input[idx] == 0) {
  953. /* Check leading zero byte required. */
  954. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  955. WOLFSSL_MSG("Zero not required on INTEGER");
  956. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  957. return ASN_PARSE_E;
  958. #endif
  959. }
  960. }
  961. /* Check whether a leading zero byte was required. */
  962. else if (positive && (input[idx] & 0x80)) {
  963. WOLFSSL_MSG("INTEGER is negative");
  964. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  965. return ASN_EXPECT_0_E;
  966. #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
  967. }
  968. return 0;
  969. }
  970. /* Check a BIT_STRING's first byte - unused bits.
  971. *
  972. * @param [in] input BER encoded data.
  973. * @param [in] idx Index of BIT_STRING data.
  974. * @param [in] length Length of input data.
  975. * @return 0 on success.
  976. * @return ASN_PARSE_E when unused bits is invalid.
  977. */
  978. static int GetASN_BitString(const byte* input, word32 idx, int length)
  979. {
  980. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  981. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  982. /* Check contents consist of one or more octets. */
  983. if (length == 0) {
  984. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  985. WOLFSSL_MSG("Zero length BIT STRING not allowed");
  986. #endif
  987. return ASN_PARSE_E;
  988. }
  989. #endif
  990. /* Ensure unused bits value is valid range. */
  991. if (input[idx] > 7) {
  992. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  993. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  994. input[idx]);
  995. #endif
  996. return ASN_PARSE_E;
  997. }
  998. /* Ensure unused bits are zero. */
  999. if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
  1000. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1001. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  1002. input[idx], input[idx + length - 1]);
  1003. #endif
  1004. return ASN_PARSE_E;
  1005. }
  1006. return 0;
  1007. }
  1008. /* Get the ASN.1 items from the BER encoding.
  1009. *
  1010. * @param [in] asn ASN.1 item expected.
  1011. * @param [in] data Data array to place found item into.
  1012. * @param [in] input BER encoded data.
  1013. * @param [in] idx Starting index of item data.
  1014. * @param [in] len Length of input buffer upto end of this item's data.
  1015. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  1016. * @return 0 on success.
  1017. * @return ASN_PARSE_E when BER encoded data is invalid.
  1018. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  1019. * @return MP_INIT_E when the unable to initialize an mp_int.
  1020. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1021. * @return BAD_STATE_E when the data type is not supported.
  1022. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1023. */
  1024. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  1025. const byte* input, word32 idx, int len,
  1026. int zeroPadded)
  1027. {
  1028. int i;
  1029. int err;
  1030. /* Parse data based on data type to extract. */
  1031. switch (data->dataType) {
  1032. /* Parse a data into a number of specified bits. */
  1033. case ASN_DATA_TYPE_WORD8:
  1034. /* Check data is small enough to fit. */
  1035. if (len != 1) {
  1036. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1037. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  1038. #endif
  1039. return ASN_PARSE_E;
  1040. }
  1041. /* Fill number with all of data. */
  1042. *data->data.u8 = input[idx];
  1043. break;
  1044. case ASN_DATA_TYPE_WORD16:
  1045. /* Check data is small enough to fit. */
  1046. if (len == 0 || len > 2) {
  1047. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1048. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  1049. #endif
  1050. return ASN_PARSE_E;
  1051. }
  1052. /* Fill number with all of data. */
  1053. *data->data.u16 = 0;
  1054. for (i = 0; i < len; i++) {
  1055. *data->data.u16 <<= 8;
  1056. *data->data.u16 |= input[idx + (word32)i] ;
  1057. }
  1058. break;
  1059. case ASN_DATA_TYPE_WORD32:
  1060. /* Check data is small enough to fit. */
  1061. if (len == 0 || len > 4) {
  1062. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1063. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1064. #endif
  1065. return ASN_PARSE_E;
  1066. }
  1067. /* Fill number with all of data. */
  1068. *data->data.u32 = 0;
  1069. for (i = 0; i < len; i++) {
  1070. *data->data.u32 <<= 8;
  1071. *data->data.u32 |= input[idx + (word32)i] ;
  1072. }
  1073. break;
  1074. case ASN_DATA_TYPE_BUFFER:
  1075. /* Check buffer is big enough to hold data. */
  1076. if (len > (int)*data->data.buffer.length) {
  1077. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1078. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1079. *data->data.buffer.length);
  1080. #endif
  1081. return ASN_PARSE_E;
  1082. }
  1083. /* Copy in data and record actual length seen. */
  1084. XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
  1085. *data->data.buffer.length = (word32)len;
  1086. break;
  1087. case ASN_DATA_TYPE_EXP_BUFFER:
  1088. /* Check data is same size expected. */
  1089. if (len != (int)data->data.ref.length) {
  1090. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1091. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1092. data->data.ref.length);
  1093. #endif
  1094. return ASN_PARSE_E;
  1095. }
  1096. /* Check data is same as expected. */
  1097. if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
  1098. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1099. WOLFSSL_MSG("Data not as expected");
  1100. #endif
  1101. return ASN_PARSE_E;
  1102. }
  1103. break;
  1104. case ASN_DATA_TYPE_MP:
  1105. case ASN_DATA_TYPE_MP_POS_NEG:
  1106. /* Initialize mp_int and read in big-endian byte array. */
  1107. if (mp_init(data->data.mp) != MP_OKAY) {
  1108. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1109. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1110. #endif
  1111. return MP_INIT_E;
  1112. }
  1113. FALL_THROUGH;
  1114. case ASN_DATA_TYPE_MP_INITED:
  1115. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
  1116. (word32)len);
  1117. if (err != 0) {
  1118. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1119. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1120. #endif
  1121. mp_clear(data->data.mp);
  1122. return ASN_GETINT_E;
  1123. }
  1124. #ifdef HAVE_WOLF_BIGINT
  1125. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1126. len);
  1127. if (err != 0) {
  1128. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1129. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1130. #endif
  1131. mp_clear(data->data.mp);
  1132. return ASN_GETINT_E;
  1133. }
  1134. #endif /* HAVE_WOLF_BIGINT */
  1135. #ifdef WOLFSSL_SP_INT_NEGATIVE
  1136. /* Don't always read as positive. */
  1137. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1138. (input[idx] & 0x80)) {
  1139. #ifdef MP_NEG
  1140. data->data.mp->sign = MP_NEG;
  1141. #else
  1142. #ifdef OPENSSL_EXTRA
  1143. /* public API wolfSSL_ASN1_INTEGER_get() depends
  1144. * indirectly on negative bignum handling here.
  1145. */
  1146. #error OPENSSL_EXTRA requires negative bignum support.
  1147. #endif
  1148. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1149. WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
  1150. #endif
  1151. mp_clear(data->data.mp);
  1152. return ASN_GETINT_E;
  1153. #endif
  1154. }
  1155. #else
  1156. (void)zeroPadded;
  1157. #endif
  1158. break;
  1159. case ASN_DATA_TYPE_CHOICE:
  1160. /* Check if tag matched any of the choices specified. */
  1161. for (i = 0; data->data.choice[i] != 0; i++)
  1162. if (data->data.choice[i] == data->tag)
  1163. break;
  1164. if (data->data.choice[i] == 0) {
  1165. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1166. WOLFSSL_MSG("Tag didn't match a choice");
  1167. #endif
  1168. return ASN_PARSE_E;
  1169. }
  1170. /* Store data pointer and length for caller. */
  1171. data->data.ref.data = input + idx;
  1172. data->data.ref.length = (word32)len;
  1173. break;
  1174. case ASN_DATA_TYPE_NONE:
  1175. /* Default behaviour based on tag. */
  1176. if (asn->tag == ASN_BOOLEAN) {
  1177. /* BOOLEAN has only one byte of data in BER. */
  1178. if (len != 1) {
  1179. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1180. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1181. #endif
  1182. return ASN_PARSE_E;
  1183. }
  1184. if (data->data.u8 == NULL)
  1185. return BAD_STATE_E;
  1186. /* Store C boolean value. */
  1187. *data->data.u8 = (input[idx] != 0);
  1188. break;
  1189. }
  1190. if (asn->tag == ASN_TAG_NULL) {
  1191. /* NULL has no data in BER. */
  1192. if (len != 0) {
  1193. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1194. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1195. #endif
  1196. return ASN_EXPECT_0_E;
  1197. }
  1198. data->data.ref.data = input + idx;
  1199. break;
  1200. }
  1201. if (asn->tag == ASN_OBJECT_ID) {
  1202. word32 oidIdx = 0;
  1203. /* Store OID data pointer and length */
  1204. data->data.oid.data = input + idx;
  1205. data->data.oid.length = (word32)len;
  1206. /* Get the OID sum. */
  1207. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1208. data->data.oid.type, len);
  1209. if (err < 0) {
  1210. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1211. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1212. #endif
  1213. return err;
  1214. }
  1215. break;
  1216. }
  1217. /* Otherwise store data pointer and length. */
  1218. data->data.ref.data = input + idx;
  1219. data->data.ref.length = (word32)len;
  1220. break;
  1221. #ifdef DEBUG_WOLFSSL
  1222. default:
  1223. /* Bad ASN data type. */
  1224. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1225. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1226. #endif
  1227. return BAD_STATE_E;
  1228. #endif
  1229. }
  1230. return 0;
  1231. }
  1232. /* Get the ASN.1 items from the BER encoding.
  1233. *
  1234. * @param [in] asn ASN.1 items expected.
  1235. * @param [in] data Data array to place found items into.
  1236. * @param [in] count Count of items to parse.
  1237. * @param [in] complete Whether the whole buffer is to be used up.
  1238. * @param [in] input BER encoded data.
  1239. * @param [in, out] inOutIdx On in, starting index of data.
  1240. * On out, end of parsed data.
  1241. * @param [in] length Length of input buffer.
  1242. * @return 0 on success.
  1243. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1244. * is invalid.
  1245. * @return BUFFER_E when data in buffer is too small.
  1246. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1247. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1248. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1249. * non-zero length.
  1250. * @return MP_INIT_E when the unable to initialize an mp_int.
  1251. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1252. * @return BAD_STATE_E when the data type is not supported.
  1253. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1254. */
  1255. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1256. const byte* input, word32* inOutIdx, word32 length)
  1257. {
  1258. int i;
  1259. int j;
  1260. int err;
  1261. int len;
  1262. /* Current index into buffer. */
  1263. word32 idx = *inOutIdx;
  1264. /* Initialize the end index at each depth to be the length. */
  1265. word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
  1266. length, length };
  1267. /* Set choices to -1 to indicate they haven't been seen or found. */
  1268. signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1269. /* Not matching a choice right now. */
  1270. int choice = 0;
  1271. /* Current depth of ASN.1 item. */
  1272. int depth;
  1273. /* Minimum depth value seen. */
  1274. int minDepth;
  1275. /* Integer had a zero prepended. */
  1276. int zeroPadded;
  1277. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1278. WOLFSSL_ENTER("GetASN_Items");
  1279. #endif
  1280. /* Start depth at first items depth. */
  1281. minDepth = depth = asn[0].depth;
  1282. /* Check every ASN.1 item. */
  1283. for (i = 0; i < count; i++) {
  1284. /* Store offset of ASN.1 item. */
  1285. data[i].offset = idx;
  1286. /* Length of data in ASN.1 item starts empty. */
  1287. data[i].length = 0;
  1288. /* Get current item depth. */
  1289. depth = asn[i].depth;
  1290. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1291. if (depth > GET_ASN_MAX_DEPTH) {
  1292. WOLFSSL_MSG("Depth in template too large");
  1293. return ASN_PARSE_E;
  1294. }
  1295. #endif
  1296. /* Keep track of minimum depth. */
  1297. if (depth < minDepth) {
  1298. minDepth = depth;
  1299. }
  1300. /* Reset choice if different from previous. */
  1301. if (choice > 0 && asn[i].optional != choice) {
  1302. choice = 0;
  1303. }
  1304. /* Check if first of numbered choice. */
  1305. if (choice == 0 && asn[i].optional > 1) {
  1306. choice = asn[i].optional;
  1307. if (choiceMet[choice - 2] == -1) {
  1308. /* Choice seen but not found a match yet. */
  1309. choiceMet[choice - 2] = 0;
  1310. }
  1311. }
  1312. /* Check for end of data or not a choice and tag not matching. */
  1313. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1314. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1315. if (asn[i].optional) {
  1316. /* Skip over ASN.1 items underneath this optional item. */
  1317. for (j = i + 1; j < count; j++) {
  1318. if (asn[i].depth >= asn[j].depth)
  1319. break;
  1320. data[j].offset = idx;
  1321. data[j].length = 0;
  1322. }
  1323. i = j - 1;
  1324. continue;
  1325. }
  1326. /* Check for end of data. */
  1327. if (idx == length) {
  1328. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1329. WOLFSSL_MSG_VSNPRINTF(
  1330. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1331. i, data[i].offset, data[i].length,
  1332. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1333. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1334. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1335. length);
  1336. #endif
  1337. return BUFFER_E;
  1338. }
  1339. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1340. /* Show expected versus found. */
  1341. WOLFSSL_MSG_VSNPRINTF(
  1342. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1343. i, data[i].offset, data[i].length,
  1344. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1345. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1346. input[idx], TagString(input[idx]));
  1347. #endif
  1348. /* Check for end of data at this depth. */
  1349. if (idx == endIdx[depth]) {
  1350. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1351. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1352. endIdx[depth]);
  1353. #endif
  1354. return ASN_PARSE_E;
  1355. }
  1356. /* Expecting an OBJECT_ID */
  1357. if (asn[i].tag == ASN_OBJECT_ID) {
  1358. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1359. WOLFSSL_MSG("Expecting OBJECT ID");
  1360. #endif
  1361. return ASN_OBJECT_ID_E;
  1362. }
  1363. /* Expecting a BIT_STRING */
  1364. if (asn[i].tag == ASN_BIT_STRING) {
  1365. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1366. WOLFSSL_MSG("Expecting BIT STRING");
  1367. #endif
  1368. return ASN_BITSTR_E;
  1369. }
  1370. /* Not the expected tag. */
  1371. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1372. WOLFSSL_MSG("Bad tag");
  1373. #endif
  1374. return ASN_PARSE_E;
  1375. }
  1376. /* Store found tag in data. */
  1377. data[i].tag = input[idx];
  1378. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1379. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1380. /* Check constructed match expected for non-choice ASN.1 item. */
  1381. if (asn[i].constructed != constructed) {
  1382. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1383. WOLFSSL_MSG_VSNPRINTF(
  1384. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1385. i, data[i].offset, data[i].length,
  1386. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1387. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1388. input[idx], TagString(input[idx]));
  1389. if (!constructed) {
  1390. WOLFSSL_MSG("Not constructed");
  1391. }
  1392. else {
  1393. WOLFSSL_MSG("Not expected to be constructed");
  1394. }
  1395. #endif
  1396. return ASN_PARSE_E;
  1397. }
  1398. }
  1399. /* Move index to start of length. */
  1400. idx++;
  1401. /* Get the encoded length. */
  1402. if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
  1403. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1404. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1405. endIdx[depth]);
  1406. #endif
  1407. return ASN_PARSE_E;
  1408. }
  1409. /* Store length of data. */
  1410. data[i].length = (word32)len;
  1411. /* Note the max length of items under this one. */
  1412. endIdx[depth + 1] = idx + (word32)len;
  1413. if (choice > 1) {
  1414. /* Note we found a number choice. */
  1415. choiceMet[choice - 2] = 1;
  1416. }
  1417. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1418. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1419. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1420. asn[i].depth, "", TagString(data[i].tag));
  1421. #endif
  1422. /* Assume no zero padding on INTEGER. */
  1423. zeroPadded = 0;
  1424. /* Check data types that prepended a byte. */
  1425. if (asn[i].tag == ASN_INTEGER) {
  1426. /* Check validity of first byte. */
  1427. err = GetASN_Integer(input, idx, len,
  1428. data[i].dataType == ASN_DATA_TYPE_MP ||
  1429. data[i].dataType == ASN_DATA_TYPE_MP_INITED);
  1430. if (err != 0)
  1431. return err;
  1432. if (len > 1 && input[idx] == 0) {
  1433. zeroPadded = 1;
  1434. /* Move over prepended byte. */
  1435. idx++;
  1436. len--;
  1437. }
  1438. }
  1439. else if (asn[i].tag == ASN_BIT_STRING) {
  1440. /* Check prepended byte is correct. */
  1441. err = GetASN_BitString(input, idx, len);
  1442. if (err != 0)
  1443. return err;
  1444. /* Move over prepended byte. */
  1445. idx++;
  1446. len--;
  1447. }
  1448. else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
  1449. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1450. WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
  1451. #endif
  1452. return ASN_PARSE_E;
  1453. }
  1454. /* Don't parse data if only header required. */
  1455. if (asn[i].headerOnly) {
  1456. /* Store reference to data and length. */
  1457. data[i].data.ref.data = input + idx;
  1458. data[i].data.ref.length = (word32)len;
  1459. continue;
  1460. }
  1461. /* Store the data at idx in the ASN data item. */
  1462. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1463. if (err != 0) {
  1464. return err;
  1465. }
  1466. /* Move index to next item. */
  1467. idx += (word32)len;
  1468. /* When matched numbered choice ... */
  1469. if (asn[i].optional > 1) {
  1470. /* Skip over other ASN.1 items of the same number. */
  1471. for (j = i + 1; j < count; j++) {
  1472. if (asn[j].depth <= asn[i].depth &&
  1473. asn[j].optional != asn[i].optional) {
  1474. break;
  1475. }
  1476. }
  1477. i = j - 1;
  1478. }
  1479. }
  1480. if (complete) {
  1481. /* When expecting ASN.1 items to completely use data, check we did. */
  1482. for (j = depth; j > minDepth; j--) {
  1483. if (idx < endIdx[j]) {
  1484. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1485. WOLFSSL_MSG_VSNPRINTF(
  1486. "More data in constructed item at depth: %d", j - 1);
  1487. #endif
  1488. return ASN_PARSE_E;
  1489. }
  1490. }
  1491. }
  1492. /* Check all choices where met - found an item for them. */
  1493. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1494. if (choiceMet[j] == 0) {
  1495. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1496. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1497. #endif
  1498. return ASN_PARSE_E;
  1499. }
  1500. }
  1501. /* Return index after ASN.1 data has been parsed. */
  1502. *inOutIdx = idx;
  1503. return 0;
  1504. }
  1505. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1506. /* Calculate the size of the DER encoding.
  1507. *
  1508. * Call SetASN_Items() to write encoding to a buffer.
  1509. *
  1510. * @param [in] asn ASN.1 items to encode.
  1511. * @param [in, out] data Data to place in each item. Lengths set were not
  1512. * known.
  1513. * @param [in] count Count of items to encode.
  1514. * @param [out] len Length of the DER encoding.
  1515. * @return Size of the DER encoding in bytes.
  1516. */
  1517. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1518. ASNSetData *data, int count, int* encSz)
  1519. {
  1520. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1521. return SizeASN_Items(asn, data, count, encSz);
  1522. }
  1523. /* Creates the DER encoding of the ASN.1 items.
  1524. *
  1525. * Assumes the output buffer is large enough to hold encoding.
  1526. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1527. *
  1528. * Displays the template name first.
  1529. *
  1530. * @param [in] name Name of ASN.1 template.
  1531. * @param [in] asn ASN.1 items to encode.
  1532. * @param [in] data Data to place in each item.
  1533. * @param [in] count Count of items to encode.
  1534. * @param [in, out] output Buffer to write encoding into.
  1535. * @return Size of the DER encoding in bytes.
  1536. */
  1537. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1538. ASNSetData *data, int count, byte* output)
  1539. {
  1540. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1541. return SetASN_Items(asn, data, count, output);
  1542. }
  1543. /* Get the ASN.1 items from the BER encoding.
  1544. *
  1545. * Displays the template name first.
  1546. *
  1547. * @param [in] name Name of ASN.1 template.
  1548. * @param [in] asn ASN.1 items expected.
  1549. * @param [in] data Data array to place found items into.
  1550. * @param [in] count Count of items to parse.
  1551. * @param [in] complete Whether the whole buffer is to be used up.
  1552. * @param [in] input BER encoded data.
  1553. * @param [in, out] inOutIdx On in, starting index of data.
  1554. * On out, end of parsed data.
  1555. * @param [in] maxIdx Maximum index of input data.
  1556. * @return 0 on success.
  1557. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1558. * is invalid.
  1559. * @return BUFFER_E when data in buffer is too small.
  1560. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1561. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1562. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1563. * non-zero length.
  1564. * @return MP_INIT_E when the unable to initialize an mp_int.
  1565. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1566. * @return BAD_STATE_E when the data type is not supported.
  1567. */
  1568. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1569. ASNGetData *data, int count, int complete, const byte* input,
  1570. word32* inOutIdx, word32 maxIdx)
  1571. {
  1572. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1573. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1574. }
  1575. /* Calculate the size of the DER encoding.
  1576. *
  1577. * Call SetASN_Items() to write encoding to a buffer.
  1578. *
  1579. * @param [in] asn ASN.1 items to encode.
  1580. * @param [in, out] data Data to place in each item. Lengths set were not
  1581. * known.
  1582. * @param [in] count Count of items to encode.
  1583. * @param [out] len Length of the DER encoding.
  1584. * @return Size of the DER encoding in bytes.
  1585. */
  1586. #define SizeASN_Items(asn, data, count, encSz) \
  1587. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1588. /* Creates the DER encoding of the ASN.1 items.
  1589. *
  1590. * Assumes the output buffer is large enough to hold encoding.
  1591. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1592. *
  1593. * Displays the template name first.
  1594. *
  1595. * @param [in] name Name of ASN.1 template.
  1596. * @param [in] asn ASN.1 items to encode.
  1597. * @param [in] data Data to place in each item.
  1598. * @param [in] count Count of items to encode.
  1599. * @param [in, out] output Buffer to write encoding into.
  1600. * @return Size of the DER encoding in bytes.
  1601. */
  1602. #define SetASN_Items(asn, data, count, output) \
  1603. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1604. /* Get the ASN.1 items from the BER encoding.
  1605. *
  1606. * Displays the template name first.
  1607. *
  1608. * @param [in] name Name of ASN.1 template.
  1609. * @param [in] asn ASN.1 items expected.
  1610. * @param [in] data Data array to place found items into.
  1611. * @param [in] count Count of items to parse.
  1612. * @param [in] complete Whether the whole buffer is to be used up.
  1613. * @param [in] input BER encoded data.
  1614. * @param [in, out] inOutIdx On in, starting index of data.
  1615. * On out, end of parsed data.
  1616. * @param [in] maxIdx Maximum index of input data.
  1617. * @return 0 on success.
  1618. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1619. * is invalid.
  1620. * @return BUFFER_E when data in buffer is too small.
  1621. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1622. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1623. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1624. * non-zero length.
  1625. * @return MP_INIT_E when the unable to initialize an mp_int.
  1626. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1627. * @return BAD_STATE_E when the data type is not supported.
  1628. */
  1629. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1630. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1631. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1632. /* Decode a BER encoded constructed sequence.
  1633. *
  1634. * @param [in] input Buffer of BER encoded data.
  1635. * @param [in, out] inOutIdx On in, index to start decoding from.
  1636. * On out, index of next encoded byte.
  1637. * @param [out] len Length of data under SEQUENCE.
  1638. * @param [in] maxIdx Maximum index of data. Index of byte after SEQ.
  1639. * @param [in] complete All data used with SEQUENCE and data under.
  1640. * @return 0 on success.
  1641. * @return BUFFER_E when not enough data to complete decode.
  1642. * @return ASN_PARSE when decoding failed.
  1643. */
  1644. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1645. word32 maxIdx, int complete)
  1646. {
  1647. int ret = 0;
  1648. word32 idx = *inOutIdx;
  1649. /* Check buffer big enough for tag. */
  1650. if (idx + 1 > maxIdx) {
  1651. ret = BUFFER_E;
  1652. }
  1653. /* Check it is a constructed SEQUENCE. */
  1654. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1655. ret = ASN_PARSE_E;
  1656. }
  1657. /* Get the length. */
  1658. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1659. ret = ASN_PARSE_E;
  1660. }
  1661. /* Check all data used if complete set. */
  1662. if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
  1663. ret = ASN_PARSE_E;
  1664. }
  1665. if (ret == 0) {
  1666. /* Return index of next byte of encoded data. */
  1667. *inOutIdx = idx;
  1668. }
  1669. return ret;
  1670. }
  1671. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1672. /* Setup ASN data item to get an 8-bit number.
  1673. *
  1674. * @param [in] dataASN Dynamic ASN data item.
  1675. * @param [in] num Pointer to an 8-bit variable.
  1676. */
  1677. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1678. {
  1679. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1680. dataASN->data.u8 = num;
  1681. }
  1682. /* Setup ASN data item to get a 16-bit number.
  1683. *
  1684. * @param [in] dataASN Dynamic ASN data item.
  1685. * @param [in] num Pointer to a 16-bit variable.
  1686. */
  1687. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1688. {
  1689. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1690. dataASN->data.u16 = num;
  1691. }
  1692. /* Setup ASN data item to get a 32-bit number.
  1693. *
  1694. * @param [in] dataASN Dynamic ASN data item.
  1695. * @param [in] num Pointer to a 32-bit variable.
  1696. */
  1697. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1698. {
  1699. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1700. dataASN->data.u32 = num;
  1701. }
  1702. /* Setup ASN data item to get data into a buffer of a specific length.
  1703. *
  1704. * @param [in] dataASN Dynamic ASN data item.
  1705. * @param [in] data Buffer to hold data.
  1706. * @param [in] length Length of buffer in bytes.
  1707. */
  1708. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1709. {
  1710. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1711. dataASN->data.buffer.data = data;
  1712. dataASN->data.buffer.length = length;
  1713. }
  1714. /* Setup ASN data item to check parsed data against expected buffer.
  1715. *
  1716. * @param [in] dataASN Dynamic ASN data item.
  1717. * @param [in] data Buffer containing expected data.
  1718. * @param [in] length Length of buffer in bytes.
  1719. */
  1720. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1721. {
  1722. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1723. dataASN->data.ref.data = data;
  1724. dataASN->data.ref.length = length;
  1725. }
  1726. /* Setup ASN data item to get a number into an mp_int.
  1727. *
  1728. * @param [in] dataASN Dynamic ASN data item.
  1729. * @param [in] num Multi-precision number object.
  1730. */
  1731. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1732. {
  1733. dataASN->dataType = ASN_DATA_TYPE_MP;
  1734. dataASN->data.mp = num;
  1735. }
  1736. /* Setup ASN data item to get a number into an mp_int that is initialized.
  1737. *
  1738. * @param [in] dataASN Dynamic ASN data item.
  1739. * @param [in] num Multi-precision number object.
  1740. */
  1741. void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
  1742. {
  1743. dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
  1744. dataASN->data.mp = num;
  1745. }
  1746. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1747. *
  1748. * @param [in] dataASN Dynamic ASN data item.
  1749. * @param [in] num Multi-precision number object.
  1750. */
  1751. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1752. {
  1753. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1754. dataASN->data.mp = num;
  1755. }
  1756. /* Setup ASN data item to be a choice of tags.
  1757. *
  1758. * @param [in] dataASN Dynamic ASN data item.
  1759. * @param [in] options 0 terminated list of tags that are valid.
  1760. */
  1761. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1762. {
  1763. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1764. dataASN->data.choice = options;
  1765. }
  1766. /* Setup ASN data item to get a boolean value.
  1767. *
  1768. * @param [in] dataASN Dynamic ASN data item.
  1769. * @param [in] num Pointer to an 8-bit variable.
  1770. */
  1771. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1772. {
  1773. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1774. dataASN->data.choice = num;
  1775. }
  1776. /* Setup ASN data item to be a an OID of a specific type.
  1777. *
  1778. * @param [in] dataASN Dynamic ASN data item.
  1779. * @param [in] oidType Type of OID to expect.
  1780. */
  1781. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1782. {
  1783. dataASN->data.oid.type = oidType;
  1784. }
  1785. /* Get the data and length from an ASN data item.
  1786. *
  1787. * @param [in] dataASN Dynamic ASN data item.
  1788. * @param [out] data Pointer to data of item.
  1789. * @param [out] length Length of buffer in bytes.
  1790. */
  1791. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1792. {
  1793. *data = dataASN->data.ref.data;
  1794. *length = dataASN->data.ref.length;
  1795. }
  1796. /* Get the data and length from an ASN data item.
  1797. *
  1798. * @param [in] dataASN Dynamic ASN data item.
  1799. * @param [out] data Pointer to data of item.
  1800. * @param [out] length Length of buffer in bytes.
  1801. */
  1802. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1803. {
  1804. *data = (byte*)dataASN->data.ref.data;
  1805. *length = dataASN->data.ref.length;
  1806. }
  1807. /* Get the data and length from an ASN data item that is an OID.
  1808. *
  1809. * @param [in] dataASN Dynamic ASN data item.
  1810. * @param [out] data Pointer to .
  1811. * @param [out] length Length of buffer in bytes.
  1812. */
  1813. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1814. {
  1815. *data = (byte*)dataASN->data.oid.data;
  1816. *length = dataASN->data.oid.length;
  1817. }
  1818. /* Setup an ASN data item to set a boolean.
  1819. *
  1820. * @param [in] dataASN Dynamic ASN data item.
  1821. * @param [in] val Boolean value.
  1822. */
  1823. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1824. {
  1825. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1826. dataASN->data.u8 = val;
  1827. }
  1828. /* Setup an ASN data item to set an 8-bit number.
  1829. *
  1830. * @param [in] dataASN Dynamic ASN data item.
  1831. * @param [in] num 8-bit number to set.
  1832. */
  1833. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1834. {
  1835. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1836. dataASN->data.u8 = num;
  1837. }
  1838. /* Setup an ASN data item to set a 16-bit number.
  1839. *
  1840. * @param [in] dataASN Dynamic ASN data item.
  1841. * @param [in] num 16-bit number to set.
  1842. */
  1843. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1844. {
  1845. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1846. dataASN->data.u16 = num;
  1847. }
  1848. /* Setup an ASN data item to set the data in a buffer.
  1849. *
  1850. * @param [in] dataASN Dynamic ASN data item.
  1851. * @param [in] data Buffer containing data to set.
  1852. * @param [in] length Length of data in buffer in bytes.
  1853. */
  1854. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1855. {
  1856. dataASN->data.buffer.data = data;
  1857. dataASN->data.buffer.length = length;
  1858. }
  1859. /* Setup an ASN data item to set the DER encode data in a buffer.
  1860. *
  1861. * @param [in] dataASN Dynamic ASN data item.
  1862. * @param [in] data Buffer containing BER encoded data to set.
  1863. * @param [in] length Length of data in buffer in bytes.
  1864. */
  1865. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1866. {
  1867. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1868. dataASN->data.buffer.data = data;
  1869. dataASN->data.buffer.length = length;
  1870. }
  1871. /* Setup an ASN data item to set an multi-precision number.
  1872. *
  1873. * @param [in] dataASN Dynamic ASN data item.
  1874. * @param [in] num Multi-precision number.
  1875. */
  1876. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1877. {
  1878. dataASN->dataType = ASN_DATA_TYPE_MP;
  1879. dataASN->data.mp = num;
  1880. }
  1881. /* Setup an ASN data item to set an OID based on id and type.
  1882. *
  1883. * oid and oidType pair are unique.
  1884. *
  1885. * @param [in] dataASN Dynamic ASN data item.
  1886. * @param [in] oid OID identifier.
  1887. * @param [in] oidType Type of OID.
  1888. */
  1889. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  1890. {
  1891. dataASN->data.buffer.data = OidFromId(oid, oidType,
  1892. &dataASN->data.buffer.length);
  1893. }
  1894. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  1895. #ifdef CRLDP_VALIDATE_DATA
  1896. /* Get the data of the BIT_STRING as a 16-bit number.
  1897. *
  1898. * @param [in] dataASN Dynamic ASN data item.
  1899. * @param [out] val ASN.1 item's data as a 16-bit number.
  1900. * @return 0 on success.
  1901. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  1902. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  1903. */
  1904. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  1905. {
  1906. int ret;
  1907. int i;
  1908. const byte* input = dataASN->data.ref.data;
  1909. int length = dataASN->data.ref.length;
  1910. /* Validate the BIT_STRING data. */
  1911. ret = GetASN_BitString(input, 0, length);
  1912. if (ret == 0) {
  1913. /* Skip unused bits byte. */
  1914. input++;
  1915. length--;
  1916. /* Check the data is usable. */
  1917. if (length == 0 || length > 2) {
  1918. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1919. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  1920. #endif
  1921. ret = ASN_PARSE_E;
  1922. }
  1923. }
  1924. if (ret == 0) {
  1925. /* Fill 16-bit var with all the data. */
  1926. *val = 0;
  1927. for (i = 0; i < length; i++) {
  1928. *val <<= 8;
  1929. *val |= input[i];
  1930. }
  1931. }
  1932. return ret;
  1933. }
  1934. #endif /* CRLDP_VALIDATE_DATA */
  1935. #endif /* WOLFSSL_ASN_TEMPLATE */
  1936. /* Decode the BER/DER length field.
  1937. *
  1938. * @param [in] input BER encoded data.
  1939. * @param [in, out] inOutIdx On in, starting index of length.
  1940. * On out, end of parsed length.
  1941. * @param [out] len Length value decoded.
  1942. * @param [in] maxIdx Maximum index of input data.
  1943. * @return Length on success.
  1944. * @return ASN_PARSE_E if the encoding is invalid.
  1945. * @return BUFFER_E when not enough data to complete decode.
  1946. */
  1947. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  1948. {
  1949. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  1950. }
  1951. /* Decode the BER/DER length field and check the length is valid on request.
  1952. *
  1953. * BER/DER has Type-Length-Value triplets.
  1954. * When requested will check that the Length decoded, indicating the number
  1955. * of bytes in the Value, is available in the buffer after the Length bytes.
  1956. *
  1957. * Only supporting a length upto INT_MAX.
  1958. *
  1959. * @param [in] input BER encoded data.
  1960. * @param [in, out] inOutIdx On in, starting index of length.
  1961. * On out, end of parsed length.
  1962. * @param [out] len Length value decoded.
  1963. * @param [in] maxIdx Maximum index of input data.
  1964. * @param [in] check Whether to check the buffer has at least the
  1965. * decoded length of bytes remaining.
  1966. * @return Length on success.
  1967. * @return ASN_PARSE_E if the encoding is invalid.
  1968. * @return BUFFER_E when not enough data to complete decode.
  1969. */
  1970. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  1971. int check)
  1972. {
  1973. int length = 0;
  1974. word32 idx = (word32)*inOutIdx;
  1975. byte b;
  1976. /* Ensure zero return length on error. */
  1977. *len = 0;
  1978. /* Check there is at least one byte available containing length information.
  1979. */
  1980. if ((idx + 1) > maxIdx) {
  1981. WOLFSSL_MSG("GetLength - bad index on input");
  1982. return BUFFER_E;
  1983. }
  1984. /* Get the first length byte. */
  1985. b = input[idx++];
  1986. /* Check if the first byte indicates the count of bytes. */
  1987. if (b >= ASN_LONG_LENGTH) {
  1988. /* Bottom 7 bits are the number of bytes to calculate length with.
  1989. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
  1990. */
  1991. word32 bytes = (word32)b & 0x7FU;
  1992. int minLen;
  1993. /* Calculate minimum length to be encoded with bytes. */
  1994. if (b == ASN_INDEF_LENGTH) {
  1995. /* Indefinite length encoding - no length bytes. */
  1996. minLen = 0;
  1997. }
  1998. else if (bytes == 1) {
  1999. minLen = 0x80;
  2000. }
  2001. /* Only support up to the number of bytes that fit into return var. */
  2002. else if (bytes > sizeof(length)) {
  2003. WOLFSSL_MSG("GetLength - overlong data length spec");
  2004. return ASN_PARSE_E;
  2005. } else {
  2006. minLen = 1 << ((bytes - 1) * 8);
  2007. }
  2008. /* Check the number of bytes required are available. */
  2009. if ((idx + bytes) > maxIdx) {
  2010. WOLFSSL_MSG("GetLength - bad long length");
  2011. return BUFFER_E;
  2012. }
  2013. /* Big-endian encoding of number. */
  2014. while (bytes--) {
  2015. b = input[idx++];
  2016. length = (length << 8) | b;
  2017. }
  2018. /* Negative value indicates we overflowed the signed int. */
  2019. if (length < 0) {
  2020. return ASN_PARSE_E;
  2021. }
  2022. /* Don't allow lengths that are longer than strictly required. */
  2023. if (length < minLen) {
  2024. return ASN_PARSE_E;
  2025. }
  2026. }
  2027. else {
  2028. /* Length in first byte. */
  2029. length = b;
  2030. }
  2031. /* When requested, check the buffer has at least length bytes left. */
  2032. if (check && ((idx + (word32)length) > maxIdx)) {
  2033. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  2034. return BUFFER_E;
  2035. }
  2036. /* Return index after length encoding. */
  2037. *inOutIdx = idx;
  2038. /* Return length if valid. */
  2039. if (length > 0) {
  2040. *len = length;
  2041. }
  2042. /* Return length calculated or error code. */
  2043. return length;
  2044. }
  2045. /* Gets the tag of next BER/DER encoded item.
  2046. *
  2047. * Checks there is enough data in the buffer for the tag byte.
  2048. *
  2049. * @param [in] input BER encoded data.
  2050. * @param [in, out] inOutIdx On in, starting index of tag.
  2051. * On out, end of parsed tag.
  2052. * @param [out] tag Tag value found.
  2053. * @param [in] maxIdx Maximum index of input data.
  2054. *
  2055. * return 0 on success
  2056. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2057. * return BUFFER_E when not enough space in buffer for tag.
  2058. */
  2059. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2060. {
  2061. int ret = 0;
  2062. word32 idx = 0;
  2063. /* Check validity of parameters. */
  2064. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2065. ret = BAD_FUNC_ARG;
  2066. }
  2067. if (ret == 0) {
  2068. /* Get index and ensure space for tag. */
  2069. idx = *inOutIdx;
  2070. if (idx + ASN_TAG_SZ > maxIdx) {
  2071. WOLFSSL_MSG("Buffer too small for ASN tag");
  2072. ret = BUFFER_E;
  2073. }
  2074. }
  2075. if (ret == 0) {
  2076. /* Return the tag and the index after tag. */
  2077. *tag = input[idx];
  2078. *inOutIdx = idx + ASN_TAG_SZ;
  2079. }
  2080. /* Return error code. */
  2081. return ret;
  2082. }
  2083. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2084. *
  2085. * BER/DER has Type-Length-Value triplets.
  2086. * Check that the tag/type is the required value.
  2087. * When requested will check that the Length decoded, indicating the number
  2088. * of bytes in the Value, is available in the buffer after the Length bytes.
  2089. *
  2090. * Only supporting a length upto INT_MAX.
  2091. *
  2092. * @param [in] input Buffer holding DER/BER encoded data.
  2093. * @param [in] tag ASN.1 tag value expected in header.
  2094. * @param [in, out] inOutIdx On in, starting index of header.
  2095. * On out, end of parsed header.
  2096. * @param [out] len Number of bytes in the ASN.1 data.
  2097. * @param [in] maxIdx Length of data in buffer.
  2098. * @param [in] check Whether to check the buffer has at least the
  2099. * decoded length of bytes remaining.
  2100. * @return Number of bytes in the ASN.1 data on success.
  2101. * @return BUFFER_E when there is not enough data to parse.
  2102. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2103. */
  2104. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2105. int* len, word32 maxIdx, int check)
  2106. {
  2107. int ret = 0;
  2108. word32 idx = *inOutIdx;
  2109. byte tagFound;
  2110. int length = 0;
  2111. /* Get tag/type. */
  2112. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2113. ret = ASN_PARSE_E;
  2114. }
  2115. /* Ensure tag is the expected value. */
  2116. if ((ret == 0) && (tagFound != tag)) {
  2117. ret = ASN_PARSE_E;
  2118. }
  2119. /* Get the encoded length. */
  2120. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2121. ret = ASN_PARSE_E;
  2122. }
  2123. if (ret == 0) {
  2124. /* Return the length of data and index after header. */
  2125. *len = length;
  2126. *inOutIdx = idx;
  2127. ret = length;
  2128. }
  2129. /* Return number of data bytes or error code. */
  2130. return ret;
  2131. }
  2132. /* Decode the DER/BER header (Type-Length) and check the length.
  2133. *
  2134. * BER/DER has Type-Length-Value triplets.
  2135. * Check that the tag/type is the required value.
  2136. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2137. * is available in the buffer after the Length bytes.
  2138. *
  2139. * @param [in] input Buffer holding DER/BER encoded data.
  2140. * @param [in] tag ASN.1 tag value expected in header.
  2141. * @param [in, out] inOutIdx On in, starting index of header.
  2142. * On out, end of parsed header.
  2143. * @param [out] len Number of bytes in the ASN.1 data.
  2144. * @param [in] maxIdx Length of data in buffer.
  2145. * @return Number of bytes in the ASN.1 data on success.
  2146. * @return BUFFER_E when there is not enough data to parse.
  2147. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2148. */
  2149. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2150. word32 maxIdx)
  2151. {
  2152. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2153. }
  2154. #ifndef WOLFSSL_ASN_TEMPLATE
  2155. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2156. word32 maxIdx, int check)
  2157. {
  2158. word32 idx = *inOutIdx;
  2159. int length;
  2160. if ((idx + 1) > maxIdx)
  2161. return BUFFER_E;
  2162. *tag = input[idx++];
  2163. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2164. return ASN_PARSE_E;
  2165. *len = length;
  2166. *inOutIdx = idx;
  2167. return length;
  2168. }
  2169. #endif
  2170. /* Decode the header of a BER/DER encoded SEQUENCE.
  2171. *
  2172. * @param [in] input Buffer holding DER/BER encoded data.
  2173. * @param [in, out] inOutIdx On in, starting index of header.
  2174. * On out, end of parsed header.
  2175. * @param [out] len Number of bytes in the ASN.1 data.
  2176. * @param [in] maxIdx Length of data in buffer.
  2177. * @return Number of bytes in the ASN.1 data on success.
  2178. * @return BUFFER_E when there is not enough data to parse.
  2179. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2180. */
  2181. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2182. word32 maxIdx)
  2183. {
  2184. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2185. maxIdx);
  2186. }
  2187. /* Decode the header of a BER/DER encoded SEQUENCE.
  2188. *
  2189. * @param [in] input Buffer holding DER/BER encoded data.
  2190. * @param [in, out] inOutIdx On in, starting index of header.
  2191. * On out, end of parsed header.
  2192. * @param [out] len Number of bytes in the ASN.1 data.
  2193. * @param [in] maxIdx Length of data in buffer.
  2194. * @param [in] check Whether to check the buffer has at least the
  2195. * decoded length of bytes remaining.
  2196. * @return Number of bytes in the ASN.1 data on success.
  2197. * @return BUFFER_E when there is not enough data to parse.
  2198. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2199. */
  2200. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2201. word32 maxIdx, int check)
  2202. {
  2203. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2204. maxIdx, check);
  2205. }
  2206. /* Decode the header of a BER/DER encoded SET.
  2207. *
  2208. * @param [in] input Buffer holding DER/BER encoded data.
  2209. * @param [in, out] inOutIdx On in, starting index of header.
  2210. * On out, end of parsed header.
  2211. * @param [out] len Number of bytes in the ASN.1 data.
  2212. * @param [in] maxIdx Length of data in buffer.
  2213. * @return Number of bytes in the ASN.1 data on success.
  2214. * @return BUFFER_E when there is not enough data to parse.
  2215. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2216. */
  2217. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2218. word32 maxIdx)
  2219. {
  2220. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2221. maxIdx);
  2222. }
  2223. /* Decode the header of a BER/DER encoded SET.
  2224. *
  2225. * @param [in] input Buffer holding DER/BER encoded data.
  2226. * @param [in, out] inOutIdx On in, starting index of header.
  2227. * On out, end of parsed header.
  2228. * @param [out] len Number of bytes in the ASN.1 data.
  2229. * @param [in] maxIdx Length of data in buffer.
  2230. * @param [in] check Whether to check the buffer has at least the
  2231. * decoded length of bytes remaining.
  2232. * @return Number of bytes in the ASN.1 data on success.
  2233. * @return BUFFER_E when there is not enough data to parse.
  2234. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2235. */
  2236. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2237. word32 maxIdx, int check)
  2238. {
  2239. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2240. maxIdx, check);
  2241. }
  2242. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2243. /* Decode the BER/DER encoded NULL.
  2244. *
  2245. * No data in a NULL ASN.1 item.
  2246. * Ensure that the all fields are as expected and move index past the element.
  2247. *
  2248. * @param [in] input Buffer holding DER/BER encoded data.
  2249. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2250. * On out, end of parsed NULL item.
  2251. * @param [in] maxIdx Length of data in buffer.
  2252. * @return 0 on success.
  2253. * @return BUFFER_E when there is not enough data to parse.
  2254. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2255. * @return ASN_EXPECT_0_E when the length is not zero.
  2256. */
  2257. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2258. {
  2259. int ret = 0;
  2260. word32 idx = *inOutIdx;
  2261. /* Check buffer has enough data for a NULL item. */
  2262. if ((idx + 2) > maxIdx) {
  2263. ret = BUFFER_E;
  2264. }
  2265. /* Check the tag is NULL. */
  2266. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2267. ret = ASN_TAG_NULL_E;
  2268. }
  2269. /* Check the length is zero. */
  2270. if ((ret == 0) && (input[idx++] != 0)) {
  2271. ret = ASN_EXPECT_0_E;
  2272. }
  2273. if (ret == 0) {
  2274. /* Return the index after NULL tag. */
  2275. *inOutIdx = idx;
  2276. }
  2277. /* Return error code. */
  2278. return ret;
  2279. }
  2280. #endif
  2281. #ifndef WOLFSSL_ASN_TEMPLATE
  2282. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2283. *
  2284. * output Buffer to write into.
  2285. * returns the number of bytes added to the buffer.
  2286. */
  2287. static int SetASNNull(byte* output)
  2288. {
  2289. output[0] = ASN_TAG_NULL;
  2290. output[1] = 0;
  2291. return 2;
  2292. }
  2293. #endif
  2294. #ifndef NO_CERTS
  2295. #ifndef WOLFSSL_ASN_TEMPLATE
  2296. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2297. *
  2298. * input Buffer holding DER/BER encoded data.
  2299. * inOutIdx Current index into buffer to parse.
  2300. * maxIdx Length of data in buffer.
  2301. * returns BUFFER_E when there is not enough data to parse.
  2302. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2303. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2304. */
  2305. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2306. {
  2307. word32 idx = *inOutIdx;
  2308. byte b;
  2309. if ((idx + 3) > maxIdx)
  2310. return BUFFER_E;
  2311. b = input[idx++];
  2312. if (b != ASN_BOOLEAN)
  2313. return ASN_PARSE_E;
  2314. if (input[idx++] != 1)
  2315. return ASN_PARSE_E;
  2316. b = input[idx++] != 0;
  2317. *inOutIdx = idx;
  2318. return b;
  2319. }
  2320. #endif
  2321. #endif /* !NO_CERTS*/
  2322. /* Decode the header of a BER/DER encoded OCTET STRING.
  2323. *
  2324. * @param [in] input Buffer holding DER/BER encoded data.
  2325. * @param [in, out] inOutIdx On in, starting index of header.
  2326. * On out, end of parsed header.
  2327. * @param [out] len Number of bytes in the ASN.1 data.
  2328. * @param [in] maxIdx Length of data in buffer.
  2329. * @return Number of bytes in the ASN.1 data on success.
  2330. * @return BUFFER_E when there is not enough data to parse.
  2331. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2332. */
  2333. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2334. {
  2335. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2336. }
  2337. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2338. *
  2339. * Removes the leading zero byte when found.
  2340. *
  2341. * input Buffer holding DER/BER encoded data.
  2342. * inOutIdx Current index into buffer to parse.
  2343. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2344. * maxIdx Length of data in buffer.
  2345. * returns BUFFER_E when there is not enough data to parse.
  2346. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2347. * or invalid use of or missing leading zero.
  2348. * Otherwise, 0 to indicate success.
  2349. */
  2350. int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2351. word32 maxIdx)
  2352. {
  2353. int ret;
  2354. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2355. if (ret < 0)
  2356. return ret;
  2357. if (*len > 0) {
  2358. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2359. /* check for invalid padding on negative integer.
  2360. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2361. */
  2362. if (*len > 1) {
  2363. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2364. return ASN_PARSE_E;
  2365. }
  2366. #endif
  2367. /* remove leading zero, unless there is only one 0x00 byte */
  2368. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2369. (*inOutIdx)++;
  2370. (*len)--;
  2371. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2372. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2373. return ASN_PARSE_E;
  2374. #endif
  2375. }
  2376. }
  2377. return 0;
  2378. }
  2379. #ifndef WOLFSSL_ASN_TEMPLATE
  2380. #ifndef NO_CERTS
  2381. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2382. * 7 bits.
  2383. *
  2384. * input Buffer holding DER/BER encoded data.
  2385. * inOutIdx Current index into buffer to parse.
  2386. * maxIdx Length of data in buffer.
  2387. * returns BUFFER_E when there is not enough data to parse.
  2388. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2389. * Otherwise, the 7-bit value.
  2390. */
  2391. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2392. {
  2393. word32 idx = *inOutIdx;
  2394. byte b;
  2395. if ((idx + 3) > maxIdx)
  2396. return BUFFER_E;
  2397. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2398. return ASN_PARSE_E;
  2399. if (b != ASN_INTEGER)
  2400. return ASN_PARSE_E;
  2401. if (input[idx++] != 1)
  2402. return ASN_PARSE_E;
  2403. b = input[idx++];
  2404. *inOutIdx = idx;
  2405. return b;
  2406. }
  2407. #endif /* !NO_CERTS */
  2408. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  2409. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2410. * 16 bits.
  2411. *
  2412. * input Buffer holding DER/BER encoded data.
  2413. * inOutIdx Current index into buffer to parse.
  2414. * maxIdx Length of data in buffer.
  2415. * returns BUFFER_E when there is not enough data to parse.
  2416. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2417. * Otherwise, the 16-bit value.
  2418. */
  2419. static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2420. {
  2421. word32 idx = *inOutIdx;
  2422. byte tag;
  2423. word16 n;
  2424. if ((idx + 2) > maxIdx)
  2425. return BUFFER_E;
  2426. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2427. return ASN_PARSE_E;
  2428. if (tag != ASN_INTEGER)
  2429. return ASN_PARSE_E;
  2430. if (input[idx] == 1) {
  2431. idx++;
  2432. if ((idx + 1) > maxIdx) {
  2433. return ASN_PARSE_E;
  2434. }
  2435. n = input[idx++];
  2436. }
  2437. else if (input[idx] == 2) {
  2438. idx++;
  2439. if ((idx + 2) > maxIdx) {
  2440. return ASN_PARSE_E;
  2441. }
  2442. n = input[idx++];
  2443. n = (n << 8) | input[idx++];
  2444. }
  2445. else
  2446. return ASN_PARSE_E;
  2447. *inOutIdx = idx;
  2448. return n;
  2449. }
  2450. #endif /* WC_RSA_PSS && !NO_RSA */
  2451. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2452. #if !defined(NO_DSA) && !defined(NO_SHA)
  2453. static const char sigSha1wDsaName[] = "SHAwDSA";
  2454. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2455. #endif /* NO_DSA */
  2456. #ifndef NO_RSA
  2457. #ifdef WOLFSSL_MD2
  2458. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2459. #endif
  2460. #ifndef NO_MD5
  2461. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2462. #endif
  2463. #ifndef NO_SHA
  2464. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2465. #endif
  2466. #ifdef WOLFSSL_SHA224
  2467. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2468. #endif
  2469. #ifndef NO_SHA256
  2470. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2471. #endif
  2472. #ifdef WOLFSSL_SHA384
  2473. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2474. #endif
  2475. #ifdef WOLFSSL_SHA512
  2476. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2477. #endif
  2478. #ifdef WOLFSSL_SHA3
  2479. #ifndef WOLFSSL_NOSHA3_224
  2480. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2481. #endif
  2482. #ifndef WOLFSSL_NOSHA3_256
  2483. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2484. #endif
  2485. #ifndef WOLFSSL_NOSHA3_384
  2486. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2487. #endif
  2488. #ifndef WOLFSSL_NOSHA3_512
  2489. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2490. #endif
  2491. #endif
  2492. #ifdef WC_RSA_PSS
  2493. static const char sigRsaSsaPssName[] = "rsassaPss";
  2494. #endif
  2495. #endif /* NO_RSA */
  2496. #ifdef HAVE_ECC
  2497. #ifndef NO_SHA
  2498. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2499. #endif
  2500. #ifdef WOLFSSL_SHA224
  2501. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2502. #endif
  2503. #ifndef NO_SHA256
  2504. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2505. #endif
  2506. #ifdef WOLFSSL_SHA384
  2507. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2508. #endif
  2509. #ifdef WOLFSSL_SHA512
  2510. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2511. #endif
  2512. #ifdef WOLFSSL_SHA3
  2513. #ifndef WOLFSSL_NOSHA3_224
  2514. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2515. #endif
  2516. #ifndef WOLFSSL_NOSHA3_256
  2517. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2518. #endif
  2519. #ifndef WOLFSSL_NOSHA3_384
  2520. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2521. #endif
  2522. #ifndef WOLFSSL_NOSHA3_512
  2523. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2524. #endif
  2525. #endif
  2526. #endif /* HAVE_ECC */
  2527. static const char sigUnknownName[] = "Unknown";
  2528. /* Get the human readable string for a signature type
  2529. *
  2530. * oid Oid value for signature
  2531. */
  2532. const char* GetSigName(int oid) {
  2533. switch (oid) {
  2534. #if !defined(NO_DSA) && !defined(NO_SHA)
  2535. case CTC_SHAwDSA:
  2536. return sigSha1wDsaName;
  2537. case CTC_SHA256wDSA:
  2538. return sigSha256wDsaName;
  2539. #endif /* NO_DSA && NO_SHA */
  2540. #ifndef NO_RSA
  2541. #ifdef WOLFSSL_MD2
  2542. case CTC_MD2wRSA:
  2543. return sigMd2wRsaName;
  2544. #endif
  2545. #ifndef NO_MD5
  2546. case CTC_MD5wRSA:
  2547. return sigMd5wRsaName;
  2548. #endif
  2549. #ifndef NO_SHA
  2550. case CTC_SHAwRSA:
  2551. return sigSha1wRsaName;
  2552. #endif
  2553. #ifdef WOLFSSL_SHA224
  2554. case CTC_SHA224wRSA:
  2555. return sigSha224wRsaName;
  2556. #endif
  2557. #ifndef NO_SHA256
  2558. case CTC_SHA256wRSA:
  2559. return sigSha256wRsaName;
  2560. #endif
  2561. #ifdef WOLFSSL_SHA384
  2562. case CTC_SHA384wRSA:
  2563. return sigSha384wRsaName;
  2564. #endif
  2565. #ifdef WOLFSSL_SHA512
  2566. case CTC_SHA512wRSA:
  2567. return sigSha512wRsaName;
  2568. #endif
  2569. #ifdef WOLFSSL_SHA3
  2570. #ifndef WOLFSSL_NOSHA3_224
  2571. case CTC_SHA3_224wRSA:
  2572. return sigSha3_224wRsaName;
  2573. #endif
  2574. #ifndef WOLFSSL_NOSHA3_256
  2575. case CTC_SHA3_256wRSA:
  2576. return sigSha3_256wRsaName;
  2577. #endif
  2578. #ifndef WOLFSSL_NOSHA3_384
  2579. case CTC_SHA3_384wRSA:
  2580. return sigSha3_384wRsaName;
  2581. #endif
  2582. #ifndef WOLFSSL_NOSHA3_512
  2583. case CTC_SHA3_512wRSA:
  2584. return sigSha3_512wRsaName;
  2585. #endif
  2586. #endif
  2587. #ifdef WC_RSA_PSS
  2588. case CTC_RSASSAPSS:
  2589. return sigRsaSsaPssName;
  2590. #endif
  2591. #endif /* NO_RSA */
  2592. #ifdef HAVE_ECC
  2593. #ifndef NO_SHA
  2594. case CTC_SHAwECDSA:
  2595. return sigSha1wEcdsaName;
  2596. #endif
  2597. #ifdef WOLFSSL_SHA224
  2598. case CTC_SHA224wECDSA:
  2599. return sigSha224wEcdsaName;
  2600. #endif
  2601. #ifndef NO_SHA256
  2602. case CTC_SHA256wECDSA:
  2603. return sigSha256wEcdsaName;
  2604. #endif
  2605. #ifdef WOLFSSL_SHA384
  2606. case CTC_SHA384wECDSA:
  2607. return sigSha384wEcdsaName;
  2608. #endif
  2609. #ifdef WOLFSSL_SHA512
  2610. case CTC_SHA512wECDSA:
  2611. return sigSha512wEcdsaName;
  2612. #endif
  2613. #ifdef WOLFSSL_SHA3
  2614. #ifndef WOLFSSL_NOSHA3_224
  2615. case CTC_SHA3_224wECDSA:
  2616. return sigSha3_224wEcdsaName;
  2617. #endif
  2618. #ifndef WOLFSSL_NOSHA3_256
  2619. case CTC_SHA3_256wECDSA:
  2620. return sigSha3_256wEcdsaName;
  2621. #endif
  2622. #ifndef WOLFSSL_NOSHA3_384
  2623. case CTC_SHA3_384wECDSA:
  2624. return sigSha3_384wEcdsaName;
  2625. #endif
  2626. #ifndef WOLFSSL_NOSHA3_512
  2627. case CTC_SHA3_512wECDSA:
  2628. return sigSha3_512wEcdsaName;
  2629. #endif
  2630. #endif
  2631. #endif /* HAVE_ECC */
  2632. default:
  2633. return sigUnknownName;
  2634. }
  2635. }
  2636. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2637. defined(OPENSSL_EXTRA)
  2638. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2639. (!defined(NO_RSA) && \
  2640. (defined(WOLFSSL_CERT_GEN) || \
  2641. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  2642. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2643. *
  2644. * When output is NULL, calculate the header length only.
  2645. *
  2646. * @param [in] len Length of INTEGER data in bytes.
  2647. * @param [in] firstByte First byte of data, most significant byte of integer,
  2648. * to encode.
  2649. * @param [out] output Buffer to write into.
  2650. * @return Number of bytes added to the buffer.
  2651. */
  2652. int SetASNInt(int len, byte firstByte, byte* output)
  2653. {
  2654. int idx = 0;
  2655. if (output) {
  2656. /* Write out tag. */
  2657. output[idx] = ASN_INTEGER;
  2658. }
  2659. /* Step over tag. */
  2660. idx += ASN_TAG_SZ;
  2661. /* Check if first byte has top bit set in which case a 0 is needed to
  2662. * maintain positive value. */
  2663. if (firstByte & 0x80) {
  2664. /* Add pre-prepended byte to length of data in INTEGER. */
  2665. len++;
  2666. }
  2667. /* Encode length - passing NULL for output will not encode. */
  2668. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  2669. /* Put out prepended 0 as well. */
  2670. if (firstByte & 0x80) {
  2671. if (output) {
  2672. /* Write out 0 byte. */
  2673. output[idx] = 0x00;
  2674. }
  2675. /* Update index. */
  2676. idx++;
  2677. }
  2678. /* Return index after header. */
  2679. return idx;
  2680. }
  2681. #endif
  2682. #endif
  2683. #ifndef WOLFSSL_ASN_TEMPLATE
  2684. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2685. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2686. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2687. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  2688. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2689. * The number is assumed to be positive.
  2690. *
  2691. * n Multi-precision integer to encode.
  2692. * maxSz Maximum size of the encoded integer.
  2693. * A negative value indicates no check of length requested.
  2694. * output Buffer to write into.
  2695. * returns BUFFER_E when the data is too long for the buffer.
  2696. * MP_TO_E when encoding the integer fails.
  2697. * Otherwise, the number of bytes added to the buffer.
  2698. */
  2699. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2700. {
  2701. int idx = 0;
  2702. int leadingBit;
  2703. int length;
  2704. leadingBit = mp_leading_bit(n);
  2705. length = mp_unsigned_bin_size(n);
  2706. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2707. return BUFFER_E;
  2708. idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output);
  2709. if (maxSz >= 0 && (idx + length) > maxSz)
  2710. return BUFFER_E;
  2711. if (output) {
  2712. int err = mp_to_unsigned_bin(n, output + idx);
  2713. if (err != MP_OKAY)
  2714. return MP_TO_E;
  2715. }
  2716. idx += length;
  2717. return idx;
  2718. }
  2719. #endif
  2720. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2721. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2722. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2723. * an RSA key.
  2724. * The number is assumed to be positive.
  2725. *
  2726. * n Multi-precision integer to encode.
  2727. * output Buffer to write into.
  2728. * returns BUFFER_E when the data is too long for the buffer.
  2729. * MP_TO_E when encoding the integer fails.
  2730. * Otherwise, the number of bytes added to the buffer.
  2731. */
  2732. static int SetASNIntRSA(void* n, byte* output)
  2733. {
  2734. int idx = 0;
  2735. int leadingBit;
  2736. int length;
  2737. leadingBit = wc_Rsa_leading_bit(n);
  2738. length = wc_Rsa_unsigned_bin_size(n);
  2739. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2740. if ((idx + length) > MAX_RSA_INT_SZ)
  2741. return BUFFER_E;
  2742. if (output) {
  2743. int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2744. if (err != MP_OKAY)
  2745. return MP_TO_E;
  2746. }
  2747. idx += length;
  2748. return idx;
  2749. }
  2750. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2751. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2752. #ifdef WOLFSSL_ASN_TEMPLATE
  2753. /* ASN.1 template for an INTEGER. */
  2754. static const ASNItem intASN[] = {
  2755. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2756. };
  2757. enum {
  2758. INTASN_IDX_INT = 0
  2759. };
  2760. /* Number of items in ASN.1 template for an INTEGER. */
  2761. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2762. #endif /* WOLFSSL_ASN_TEMPLATE */
  2763. /* Windows header clash for WinCE using GetVersion */
  2764. /* Decode Version - one byte INTEGER.
  2765. *
  2766. * @param [in] input Buffer of BER data.
  2767. * @param [in, out] inOutIdx On in, start of encoded Version.
  2768. * On out, start of next encode ASN.1 item.
  2769. * @param [out] version Number encoded in INTEGER.
  2770. * @param [in] maxIdx Maximum index of data in buffer.
  2771. * @return 0 on success.
  2772. * @return ASN_PARSE_E when encoding is invalid.
  2773. * @return BUFFER_E when data in buffer is too small.
  2774. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2775. */
  2776. int GetMyVersion(const byte* input, word32* inOutIdx,
  2777. int* version, word32 maxIdx)
  2778. {
  2779. #ifndef WOLFSSL_ASN_TEMPLATE
  2780. word32 idx = *inOutIdx;
  2781. byte tag;
  2782. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2783. return ASN_PARSE_E;
  2784. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2785. return ASN_PARSE_E;
  2786. if (tag != ASN_INTEGER)
  2787. return ASN_PARSE_E;
  2788. if (input[idx++] != 0x01)
  2789. return ASN_VERSION_E;
  2790. *version = input[idx++];
  2791. *inOutIdx = idx;
  2792. return *version;
  2793. #else
  2794. ASNGetData dataASN[intASN_Length];
  2795. int ret;
  2796. byte num;
  2797. /* Clear dynamic data and set the version number variable. */
  2798. XMEMSET(dataASN, 0, sizeof(dataASN));
  2799. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2800. /* Decode the version (INTEGER). */
  2801. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2802. maxIdx);
  2803. if (ret == 0) {
  2804. /* Return version through variable and return value. */
  2805. *version = num;
  2806. ret = num;
  2807. }
  2808. return ret;
  2809. #endif /* WOLFSSL_ASN_TEMPLATE */
  2810. }
  2811. #ifndef NO_PWDBASED
  2812. /* Decode small integer, 32 bits or less.
  2813. *
  2814. * @param [in] input Buffer of BER data.
  2815. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2816. * On out, start of next encode ASN.1 item.
  2817. * @param [out] number Number encoded in INTEGER.
  2818. * @param [in] maxIdx Maximum index of data in buffer.
  2819. * @return 0 on success.
  2820. * @return ASN_PARSE_E when encoding is invalid.
  2821. * @return BUFFER_E when data in buffer is too small.
  2822. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2823. */
  2824. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2825. {
  2826. #ifndef WOLFSSL_ASN_TEMPLATE
  2827. word32 idx = *inOutIdx;
  2828. word32 len;
  2829. byte tag;
  2830. *number = 0;
  2831. /* check for type and length bytes */
  2832. if ((idx + 2) > maxIdx)
  2833. return BUFFER_E;
  2834. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2835. return ASN_PARSE_E;
  2836. if (tag != ASN_INTEGER)
  2837. return ASN_PARSE_E;
  2838. len = input[idx++];
  2839. if (len > 4)
  2840. return ASN_PARSE_E;
  2841. if (len + idx > maxIdx)
  2842. return ASN_PARSE_E;
  2843. while (len--) {
  2844. *number = *number << 8 | input[idx++];
  2845. }
  2846. *inOutIdx = idx;
  2847. return *number;
  2848. #else
  2849. ASNGetData dataASN[intASN_Length];
  2850. int ret;
  2851. word32 num;
  2852. /* Clear dynamic data and set the 32-bit number variable. */
  2853. XMEMSET(dataASN, 0, sizeof(dataASN));
  2854. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2855. /* Decode the short int (INTEGER). */
  2856. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2857. maxIdx);
  2858. if (ret == 0) {
  2859. /* Return number through variable and return value. */
  2860. *number = (int)num;
  2861. ret = (int)num;
  2862. }
  2863. return ret;
  2864. #endif
  2865. }
  2866. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
  2867. defined(HAVE_PKCS12)
  2868. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2869. * returns total amount written including ASN tag and length byte on success */
  2870. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2871. {
  2872. word32 idx = *inOutIdx;
  2873. int len = 0;
  2874. int i;
  2875. byte ar[MAX_LENGTH_SZ];
  2876. /* check for room for type and length bytes */
  2877. if ((idx + 2) > maxIdx)
  2878. return BUFFER_E;
  2879. input[idx++] = ASN_INTEGER;
  2880. idx++; /* place holder for length byte */
  2881. if (MAX_LENGTH_SZ + idx > maxIdx)
  2882. return ASN_PARSE_E;
  2883. /* find first non zero byte */
  2884. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2885. c32toa(number, ar);
  2886. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2887. if (ar[i] != 0) {
  2888. break;
  2889. }
  2890. }
  2891. /* handle case of 0 */
  2892. if (i == MAX_LENGTH_SZ) {
  2893. input[idx++] = 0; len++;
  2894. }
  2895. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2896. input[idx++] = ar[i]; len++;
  2897. }
  2898. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2899. * and set number of bytes for integer, then update the index value */
  2900. input[*inOutIdx + 1] = (byte)len;
  2901. *inOutIdx = idx;
  2902. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2903. }
  2904. #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
  2905. #endif /* !NO_PWDBASED */
  2906. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  2907. /* May not have one, not an error */
  2908. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2909. word32 maxIdx)
  2910. {
  2911. word32 idx = *inOutIdx;
  2912. byte tag;
  2913. WOLFSSL_ENTER("GetExplicitVersion");
  2914. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2915. return ASN_PARSE_E;
  2916. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2917. int ret;
  2918. *inOutIdx = ++idx; /* skip header */
  2919. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2920. if (ret >= 0) {
  2921. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2922. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2923. WOLFSSL_MSG("Unexpected certificate version");
  2924. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  2925. ret = ASN_VERSION_E;
  2926. }
  2927. }
  2928. return ret;
  2929. }
  2930. /* go back as is */
  2931. *version = 0;
  2932. return 0;
  2933. }
  2934. #endif
  2935. /* Decode small integer, 32 bits or less.
  2936. *
  2937. * mp_int is initialized.
  2938. *
  2939. * @param [out] mpi mp_int to hold number.
  2940. * @param [in] input Buffer of BER data.
  2941. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2942. * On out, start of next encode ASN.1 item.
  2943. * @param [in] maxIdx Maximum index of data in buffer.
  2944. * @return 0 on success.
  2945. * @return ASN_PARSE_E when encoding is invalid.
  2946. * @return BUFFER_E when data in buffer is too small.
  2947. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2948. * @return MP_INIT_E when the unable to initialize an mp_int.
  2949. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  2950. */
  2951. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  2952. {
  2953. #ifndef WOLFSSL_ASN_TEMPLATE
  2954. word32 idx = *inOutIdx;
  2955. int ret;
  2956. int length;
  2957. ret = GetASNInt(input, &idx, &length, maxIdx);
  2958. if (ret != 0)
  2959. return ret;
  2960. if (mp_init(mpi) != MP_OKAY)
  2961. return MP_INIT_E;
  2962. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2963. mp_clear(mpi);
  2964. return ASN_GETINT_E;
  2965. }
  2966. #ifdef HAVE_WOLF_BIGINT
  2967. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2968. mp_clear(mpi);
  2969. return ASN_GETINT_E;
  2970. }
  2971. #endif /* HAVE_WOLF_BIGINT */
  2972. *inOutIdx = idx + (word32)length;
  2973. return 0;
  2974. #else
  2975. ASNGetData dataASN[intASN_Length];
  2976. /* Clear dynamic data and set the mp_int to fill with value. */
  2977. XMEMSET(dataASN, 0, sizeof(dataASN));
  2978. GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
  2979. /* Decode the big number (INTEGER). */
  2980. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2981. maxIdx);
  2982. #endif
  2983. }
  2984. #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
  2985. static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
  2986. word32 maxIdx, int initNum)
  2987. {
  2988. word32 idx = *inOutIdx;
  2989. int ret;
  2990. int length;
  2991. ret = GetASNInt(input, &idx, &length, maxIdx);
  2992. if (ret != 0)
  2993. return ret;
  2994. /* should not be hit but adding in an additional sanity check */
  2995. if (idx + length > maxIdx) {
  2996. return MP_INIT_E;
  2997. }
  2998. if ((input[idx] & 0x80) == 0x80) {
  2999. if (idx < 1) {
  3000. /* needs at least one byte for length value */
  3001. return MP_INIT_E;
  3002. }
  3003. if (input[idx - 1] != 0x00) {
  3004. return MP_INIT_E;
  3005. }
  3006. }
  3007. if (initNum) {
  3008. if (mp_init(mpi) != MP_OKAY)
  3009. return MP_INIT_E;
  3010. }
  3011. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  3012. mp_clear(mpi);
  3013. return ASN_GETINT_E;
  3014. }
  3015. #ifdef HAVE_WOLF_BIGINT
  3016. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3017. mp_clear(mpi);
  3018. return ASN_GETINT_E;
  3019. }
  3020. #endif /* HAVE_WOLF_BIGINT */
  3021. *inOutIdx = idx + (word32)length;
  3022. return 0;
  3023. }
  3024. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  3025. #ifndef WOLFSSL_ASN_TEMPLATE
  3026. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  3027. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  3028. {
  3029. word32 idx = *inOutIdx;
  3030. int ret;
  3031. int length;
  3032. ret = GetASNInt(input, &idx, &length, maxIdx);
  3033. if (ret != 0)
  3034. return ret;
  3035. *inOutIdx = idx + (word32)length;
  3036. return 0;
  3037. }
  3038. #endif
  3039. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3040. #ifdef WOLFSSL_ASN_TEMPLATE
  3041. /* ASN.1 template for a BIT_STRING. */
  3042. static const ASNItem bitStringASN[] = {
  3043. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  3044. };
  3045. enum {
  3046. BITSTRINGASN_IDX_BIT_STR = 0
  3047. };
  3048. /* Number of items in ASN.1 template for a BIT_STRING. */
  3049. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  3050. #endif
  3051. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  3052. *
  3053. * @param [in] input Buffer holding BER encoding.
  3054. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3055. * On out, start of ASN.1 item after BIT_STRING.
  3056. * @param [out] len Length of BIT_STRING data.
  3057. * @param [in] maxIdx Maximum index of data in buffer.
  3058. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3059. * @param [in] unusedBits Number of unused bits in last byte.
  3060. * @return 0 on success.
  3061. * @return ASN_PARSE_E when encoding is invalid.
  3062. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3063. * @return BUFFER_E when data in buffer is too small.
  3064. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3065. */
  3066. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3067. word32 maxIdx, int zeroBits, byte* unusedBits)
  3068. {
  3069. #ifndef WOLFSSL_ASN_TEMPLATE
  3070. word32 idx = *inOutIdx;
  3071. int length;
  3072. byte b;
  3073. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3074. return ASN_BITSTR_E;
  3075. }
  3076. if (b != ASN_BIT_STRING) {
  3077. return ASN_BITSTR_E;
  3078. }
  3079. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3080. return ASN_PARSE_E;
  3081. /* extra sanity check that length is greater than 0 */
  3082. if (length <= 0) {
  3083. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3084. return BUFFER_E;
  3085. }
  3086. if (idx + 1 > maxIdx) {
  3087. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3088. return BUFFER_E;
  3089. }
  3090. b = input[idx];
  3091. if (zeroBits && b != 0x00)
  3092. return ASN_EXPECT_0_E;
  3093. if (b >= 0x08)
  3094. return ASN_PARSE_E;
  3095. if (b != 0) {
  3096. if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
  3097. return ASN_PARSE_E;
  3098. }
  3099. idx++;
  3100. length--; /* length has been checked for greater than 0 */
  3101. *inOutIdx = idx;
  3102. if (len != NULL)
  3103. *len = length;
  3104. if (unusedBits != NULL)
  3105. *unusedBits = b;
  3106. return 0;
  3107. #else
  3108. ASNGetData dataASN[bitStringASN_Length];
  3109. int ret;
  3110. int bits;
  3111. /* Parse BIT_STRING and check validity of unused bits. */
  3112. XMEMSET(dataASN, 0, sizeof(dataASN));
  3113. /* Decode BIT_STRING. */
  3114. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3115. inOutIdx, maxIdx);
  3116. if (ret == 0) {
  3117. /* Get unused bits from dynamic ASN.1 data. */
  3118. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3119. /* Check unused bits is 0 when expected. */
  3120. if (zeroBits && (bits != 0)) {
  3121. ret = ASN_EXPECT_0_E;
  3122. }
  3123. }
  3124. if (ret == 0) {
  3125. /* Return length of data and unused bits if required. */
  3126. if (len != NULL) {
  3127. *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3128. }
  3129. if (unusedBits != NULL) {
  3130. *unusedBits = (byte)bits;
  3131. }
  3132. }
  3133. return ret;
  3134. #endif
  3135. }
  3136. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3137. * KeyGen) */
  3138. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  3139. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3140. defined(OPENSSL_EXTRA))) || \
  3141. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3142. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3143. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3144. defined(OPENSSL_EXTRA))) || \
  3145. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3146. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3147. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3148. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3149. *
  3150. * When output is NULL, calculate the header length only.
  3151. *
  3152. * @param [in] len Length of BIT STRING data.
  3153. * That is, the number of least significant zero bits
  3154. * before a one.
  3155. * The last byte is the most-significant non-zero byte
  3156. * of a number.
  3157. * @param [out] output Buffer to write into.
  3158. * @return Number of bytes added to the buffer.
  3159. */
  3160. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3161. {
  3162. word32 idx = 0;
  3163. if (output) {
  3164. /* Write out tag. */
  3165. output[idx] = ASN_BIT_STRING;
  3166. }
  3167. /* Step over tag. */
  3168. idx += ASN_TAG_SZ;
  3169. /* Encode length - passing NULL for output will not encode.
  3170. * Add one to length for unused bits. */
  3171. idx += SetLength(len + 1, output ? output + idx : NULL);
  3172. if (output) {
  3173. /* Write out unused bits. */
  3174. output[idx] = unusedBits;
  3175. }
  3176. /* Skip over unused bits. */
  3177. idx++;
  3178. /* Return index after header. */
  3179. return idx;
  3180. }
  3181. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3182. #ifdef ASN_BER_TO_DER
  3183. /* Convert BER to DER */
  3184. /* Pull informtation from the ASN.1 BER encoded item header */
  3185. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3186. byte* pTag, word32* pLen, int* indef)
  3187. {
  3188. int len = 0;
  3189. byte tag;
  3190. word32 i = *idx;
  3191. *indef = 0;
  3192. /* Check there is enough data for a minimal header */
  3193. if (i + 2 > maxIdx) {
  3194. return ASN_PARSE_E;
  3195. }
  3196. /* Retrieve tag */
  3197. tag = data[i++];
  3198. /* Indefinite length handled specially */
  3199. if (data[i] == ASN_INDEF_LENGTH) {
  3200. /* Check valid tag for indefinite */
  3201. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3202. return ASN_PARSE_E;
  3203. }
  3204. i++;
  3205. *indef = 1;
  3206. }
  3207. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3208. return ASN_PARSE_E;
  3209. }
  3210. /* Return tag, length and index after BER item header */
  3211. *pTag = tag;
  3212. *pLen = (word32)len;
  3213. *idx = i;
  3214. return 0;
  3215. }
  3216. #ifndef INDEF_ITEMS_MAX
  3217. #define INDEF_ITEMS_MAX 20
  3218. #endif
  3219. /* Indef length item data */
  3220. typedef struct Indef {
  3221. word32 start;
  3222. int depth;
  3223. int headerLen;
  3224. word32 len;
  3225. } Indef;
  3226. /* Indef length items */
  3227. typedef struct IndefItems
  3228. {
  3229. Indef len[INDEF_ITEMS_MAX];
  3230. int cnt;
  3231. int idx;
  3232. int depth;
  3233. } IndefItems;
  3234. /* Get header length of current item */
  3235. static int IndefItems_HeaderLen(IndefItems* items)
  3236. {
  3237. return items->len[items->idx].headerLen;
  3238. }
  3239. /* Get data length of current item */
  3240. static word32 IndefItems_Len(IndefItems* items)
  3241. {
  3242. return items->len[items->idx].len;
  3243. }
  3244. /* Add a indefinite length item */
  3245. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3246. {
  3247. int ret = 0;
  3248. int i;
  3249. if (items->cnt == INDEF_ITEMS_MAX) {
  3250. ret = MEMORY_E;
  3251. }
  3252. else {
  3253. i = items->cnt++;
  3254. items->len[i].start = start;
  3255. items->len[i].depth = items->depth++;
  3256. items->len[i].headerLen = 1;
  3257. items->len[i].len = 0;
  3258. items->idx = i;
  3259. }
  3260. return ret;
  3261. }
  3262. /* Increase data length of current item */
  3263. static void IndefItems_AddData(IndefItems* items, word32 length)
  3264. {
  3265. items->len[items->idx].len += length;
  3266. }
  3267. /* Update header length of current item to reflect data length */
  3268. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3269. {
  3270. items->len[items->idx].headerLen +=
  3271. (int)SetLength(items->len[items->idx].len, NULL);
  3272. }
  3273. /* Go to indefinite parent of current item */
  3274. static void IndefItems_Up(IndefItems* items)
  3275. {
  3276. int i;
  3277. int depth = items->len[items->idx].depth - 1;
  3278. for (i = items->cnt - 1; i >= 0; i--) {
  3279. if (items->len[i].depth == depth) {
  3280. break;
  3281. }
  3282. }
  3283. items->idx = i;
  3284. items->depth = depth + 1;
  3285. }
  3286. /* Calculate final length by adding length of indefinite child items */
  3287. static void IndefItems_CalcLength(IndefItems* items)
  3288. {
  3289. int i;
  3290. int idx = items->idx;
  3291. for (i = idx + 1; i < items->cnt; i++) {
  3292. if (items->len[i].depth == items->depth) {
  3293. items->len[idx].len += (word32)items->len[i].headerLen;
  3294. items->len[idx].len += items->len[i].len;
  3295. }
  3296. }
  3297. items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
  3298. }
  3299. /* Add more data to indefinite length item */
  3300. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3301. {
  3302. if (items->cnt > 0 && items->idx >= 0) {
  3303. items->len[items->idx].len += length;
  3304. }
  3305. }
  3306. /* Convert a BER encoding with indefinite length items to DER.
  3307. *
  3308. * ber BER encoded data.
  3309. * berSz Length of BER encoded data.
  3310. * der Buffer to hold DER encoded version of data.
  3311. * NULL indicates only the length is required.
  3312. * derSz The size of the buffer to hold the DER encoded data.
  3313. * Will be set if der is NULL, otherwise the value is checked as der is
  3314. * filled.
  3315. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3316. * derSz are NULL.
  3317. */
  3318. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3319. {
  3320. int ret = 0;
  3321. word32 i, j;
  3322. #ifdef WOLFSSL_SMALL_STACK
  3323. IndefItems* indefItems = NULL;
  3324. #else
  3325. IndefItems indefItems[1];
  3326. #endif
  3327. byte tag, basic;
  3328. word32 length;
  3329. int indef;
  3330. if (ber == NULL || derSz == NULL)
  3331. return BAD_FUNC_ARG;
  3332. #ifdef WOLFSSL_SMALL_STACK
  3333. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3334. DYNAMIC_TYPE_TMP_BUFFER);
  3335. if (indefItems == NULL) {
  3336. ret = MEMORY_E;
  3337. goto end;
  3338. }
  3339. #endif
  3340. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3341. /* Calculate indefinite item lengths */
  3342. for (i = 0; i < berSz; ) {
  3343. word32 start = i;
  3344. /* Get next BER item */
  3345. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3346. if (ret != 0) {
  3347. goto end;
  3348. }
  3349. if (indef) {
  3350. /* Indefinite item - add to list */
  3351. ret = IndefItems_AddItem(indefItems, i);
  3352. if (ret != 0) {
  3353. goto end;
  3354. }
  3355. if ((tag & 0xC0) == 0 &&
  3356. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3357. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3358. /* Constructed basic type - get repeating tag */
  3359. basic = (byte)(tag & (~ASN_CONSTRUCTED));
  3360. /* Add up lengths of each item below */
  3361. for (; i < berSz; ) {
  3362. /* Get next BER_item */
  3363. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3364. if (ret != 0) {
  3365. goto end;
  3366. }
  3367. /* End of content closes item */
  3368. if (tag == ASN_EOC) {
  3369. /* Must be zero length */
  3370. if (length != 0) {
  3371. ret = ASN_PARSE_E;
  3372. goto end;
  3373. }
  3374. break;
  3375. }
  3376. /* Must not be indefinite and tag must match parent */
  3377. if (indef || tag != basic) {
  3378. ret = ASN_PARSE_E;
  3379. goto end;
  3380. }
  3381. /* Add to length */
  3382. IndefItems_AddData(indefItems, length);
  3383. /* Skip data */
  3384. i += length;
  3385. }
  3386. /* Ensure we got an EOC and not end of data */
  3387. if (tag != ASN_EOC) {
  3388. ret = ASN_PARSE_E;
  3389. goto end;
  3390. }
  3391. /* Set the header length to include the length field */
  3392. IndefItems_UpdateHeaderLen(indefItems);
  3393. /* Go to indefinite parent item */
  3394. IndefItems_Up(indefItems);
  3395. }
  3396. }
  3397. else if (tag == ASN_EOC) {
  3398. /* End-of-content must be 0 length */
  3399. if (length != 0) {
  3400. ret = ASN_PARSE_E;
  3401. goto end;
  3402. }
  3403. /* Check there is an item to close - missing EOC */
  3404. if (indefItems->depth == 0) {
  3405. ret = ASN_PARSE_E;
  3406. goto end;
  3407. }
  3408. /* Finish calculation of data length for indefinite item */
  3409. IndefItems_CalcLength(indefItems);
  3410. /* Go to indefinite parent item */
  3411. IndefItems_Up(indefItems);
  3412. }
  3413. else {
  3414. /* Known length item to add in - make sure enough data for it */
  3415. if (i + length > berSz) {
  3416. ret = ASN_PARSE_E;
  3417. goto end;
  3418. }
  3419. /* Include all data - can't have indefinite inside definite */
  3420. i += length;
  3421. /* Add entire item to current indefinite item */
  3422. IndefItems_MoreData(indefItems, i - start);
  3423. }
  3424. }
  3425. /* Check we had a EOC for each indefinite item */
  3426. if (indefItems->depth != 0) {
  3427. ret = ASN_PARSE_E;
  3428. goto end;
  3429. }
  3430. /* Write out DER */
  3431. j = 0;
  3432. /* Reset index */
  3433. indefItems->idx = 0;
  3434. for (i = 0; i < berSz; ) {
  3435. word32 start = i;
  3436. /* Get item - checked above */
  3437. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3438. if (indef) {
  3439. if (der != NULL) {
  3440. /* Check enough space for header */
  3441. if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
  3442. ret = BUFFER_E;
  3443. goto end;
  3444. }
  3445. if ((tag & 0xC0) == 0 &&
  3446. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3447. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3448. /* Remove constructed tag for basic types */
  3449. tag &= (byte)~ASN_CONSTRUCTED;
  3450. }
  3451. /* Add tag and length */
  3452. der[j] = tag;
  3453. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3454. }
  3455. /* Add header length of indefinite item */
  3456. j += (word32)IndefItems_HeaderLen(indefItems);
  3457. if ((tag & 0xC0) == 0 &&
  3458. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3459. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3460. /* For basic type - get each child item and add data */
  3461. for (; i < berSz; ) {
  3462. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3463. if (tag == ASN_EOC) {
  3464. break;
  3465. }
  3466. if (der != NULL) {
  3467. if (j + length > *derSz) {
  3468. ret = BUFFER_E;
  3469. goto end;
  3470. }
  3471. XMEMCPY(der + j, ber + i, length);
  3472. }
  3473. j += length;
  3474. i += length;
  3475. }
  3476. }
  3477. /* Move to next indef item in list */
  3478. indefItems->idx++;
  3479. }
  3480. else if (tag == ASN_EOC) {
  3481. /* End-Of-Content is not written out in DER */
  3482. }
  3483. else {
  3484. /* Write out definite length item as is. */
  3485. i += length;
  3486. if (der != NULL) {
  3487. /* Ensure space for item */
  3488. if (j + i - start > *derSz) {
  3489. ret = BUFFER_E;
  3490. goto end;
  3491. }
  3492. /* Copy item as is */
  3493. XMEMCPY(der + j, ber + start, i - start);
  3494. }
  3495. j += i - start;
  3496. }
  3497. }
  3498. /* Return the length of the DER encoded ASN.1 */
  3499. *derSz = j;
  3500. if (der == NULL) {
  3501. ret = LENGTH_ONLY_E;
  3502. }
  3503. end:
  3504. #ifdef WOLFSSL_SMALL_STACK
  3505. if (indefItems != NULL) {
  3506. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3507. }
  3508. #endif
  3509. return ret;
  3510. }
  3511. #endif
  3512. #ifndef WOLFSSL_ASN_TEMPLATE
  3513. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3514. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3515. *
  3516. * val 16-bit value to encode.
  3517. * output Buffer to write into.
  3518. * returns the number of bytes added to the buffer.
  3519. */
  3520. static word32 SetBitString16Bit(word16 val, byte* output)
  3521. {
  3522. word32 idx;
  3523. int len;
  3524. byte lastByte;
  3525. byte unusedBits = 0;
  3526. if ((val >> 8) != 0) {
  3527. len = 2;
  3528. lastByte = (byte)(val >> 8);
  3529. }
  3530. else {
  3531. len = 1;
  3532. lastByte = (byte)val;
  3533. }
  3534. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3535. unusedBits++;
  3536. idx = SetBitString((word32)len, unusedBits, output);
  3537. output[idx++] = (byte)val;
  3538. if (len > 1)
  3539. output[idx++] = (byte)(val >> 8);
  3540. return idx;
  3541. }
  3542. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3543. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3544. /* hashType */
  3545. #ifdef WOLFSSL_MD2
  3546. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3547. #endif
  3548. #ifndef NO_MD5
  3549. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3550. #endif
  3551. #ifndef NO_SHA
  3552. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3553. #endif
  3554. #ifdef WOLFSSL_SHA224
  3555. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3556. #endif
  3557. #ifndef NO_SHA256
  3558. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3559. #endif
  3560. #ifdef WOLFSSL_SHA384
  3561. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3562. #endif
  3563. #ifdef WOLFSSL_SHA512
  3564. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3565. #ifndef WOLFSSL_NOSHA512_224
  3566. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3567. #endif
  3568. #ifndef WOLFSSL_NOSHA512_256
  3569. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3570. #endif
  3571. #endif
  3572. #ifdef WOLFSSL_SHA3
  3573. #ifndef WOLFSSL_NOSHA3_224
  3574. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3575. #endif /* WOLFSSL_NOSHA3_224 */
  3576. #ifndef WOLFSSL_NOSHA3_256
  3577. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3578. #endif /* WOLFSSL_NOSHA3_256 */
  3579. #ifndef WOLFSSL_NOSHA3_384
  3580. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3581. #endif /* WOLFSSL_NOSHA3_384 */
  3582. #ifndef WOLFSSL_NOSHA3_512
  3583. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3584. #endif /* WOLFSSL_NOSHA3_512 */
  3585. #endif /* WOLFSSL_SHA3 */
  3586. /* hmacType */
  3587. #ifndef NO_HMAC
  3588. #ifdef WOLFSSL_SHA224
  3589. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3590. #endif
  3591. #ifndef NO_SHA256
  3592. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3593. #endif
  3594. #ifdef WOLFSSL_SHA384
  3595. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3596. #endif
  3597. #ifdef WOLFSSL_SHA512
  3598. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3599. #endif
  3600. #endif
  3601. /* sigType */
  3602. #if !defined(NO_DSA) && !defined(NO_SHA)
  3603. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3604. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3605. #endif /* NO_DSA */
  3606. #ifndef NO_RSA
  3607. #ifdef WOLFSSL_MD2
  3608. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3609. #endif
  3610. #ifndef NO_MD5
  3611. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3612. #endif
  3613. #ifndef NO_SHA
  3614. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3615. #endif
  3616. #ifdef WOLFSSL_SHA224
  3617. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3618. #endif
  3619. #ifndef NO_SHA256
  3620. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3621. #endif
  3622. #ifdef WOLFSSL_SHA384
  3623. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3624. #endif
  3625. #ifdef WOLFSSL_SHA512
  3626. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3627. #endif
  3628. #ifdef WOLFSSL_SHA3
  3629. #ifndef WOLFSSL_NOSHA3_224
  3630. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3631. #endif
  3632. #ifndef WOLFSSL_NOSHA3_256
  3633. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3634. #endif
  3635. #ifndef WOLFSSL_NOSHA3_384
  3636. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3637. #endif
  3638. #ifndef WOLFSSL_NOSHA3_512
  3639. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3640. #endif
  3641. #endif
  3642. #ifdef WC_RSA_PSS
  3643. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3644. #endif
  3645. #endif /* NO_RSA */
  3646. #ifdef HAVE_ECC
  3647. #ifndef NO_SHA
  3648. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3649. #endif
  3650. #ifdef WOLFSSL_SHA224
  3651. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3652. #endif
  3653. #ifndef NO_SHA256
  3654. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3655. #endif
  3656. #ifdef WOLFSSL_SHA384
  3657. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3658. #endif
  3659. #ifdef WOLFSSL_SHA512
  3660. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3661. #endif
  3662. #ifdef WOLFSSL_SHA3
  3663. #ifndef WOLFSSL_NOSHA3_224
  3664. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3665. #endif
  3666. #ifndef WOLFSSL_NOSHA3_256
  3667. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3668. #endif
  3669. #ifndef WOLFSSL_NOSHA3_384
  3670. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3671. #endif
  3672. #ifndef WOLFSSL_NOSHA3_512
  3673. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3674. #endif
  3675. #endif
  3676. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  3677. /* 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x75 */
  3678. static const byte sigSm3wSm2Oid[] = {42, 129, 28, 207, 85, 1, 131, 117};
  3679. #endif
  3680. #endif /* HAVE_ECC */
  3681. #ifdef HAVE_ED25519
  3682. static const byte sigEd25519Oid[] = {43, 101, 112};
  3683. #endif /* HAVE_ED25519 */
  3684. #ifdef HAVE_ED448
  3685. static const byte sigEd448Oid[] = {43, 101, 113};
  3686. #endif /* HAVE_ED448 */
  3687. #ifdef HAVE_PQC
  3688. #ifdef HAVE_FALCON
  3689. /* Falcon Level 1: 1 3 9999 3 1 */
  3690. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3691. /* Falcon Level 5: 1 3 9999 3 4 */
  3692. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3693. #endif /* HAVE_FACON */
  3694. #ifdef HAVE_DILITHIUM
  3695. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3696. static const byte sigDilithium_Level2Oid[] =
  3697. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3698. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3699. static const byte sigDilithium_Level3Oid[] =
  3700. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3701. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3702. static const byte sigDilithium_Level5Oid[] =
  3703. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3704. #endif /* HAVE_DILITHIUM */
  3705. #ifdef HAVE_SPHINCS
  3706. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3707. static const byte sigSphincsFast_Level1Oid[] =
  3708. {43, 206, 15, 6, 7, 4};
  3709. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3710. static const byte sigSphincsFast_Level3Oid[] =
  3711. {43, 206, 15, 6, 8, 3};
  3712. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3713. static const byte sigSphincsFast_Level5Oid[] =
  3714. {43, 206, 15, 6, 9, 3};
  3715. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3716. static const byte sigSphincsSmall_Level1Oid[] =
  3717. {43, 206, 15, 6, 7, 10};
  3718. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3719. static const byte sigSphincsSmall_Level3Oid[] =
  3720. {43, 206, 15, 6, 8, 7};
  3721. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3722. static const byte sigSphincsSmall_Level5Oid[] =
  3723. {43, 206, 15, 6, 9, 7};
  3724. #endif /* HAVE_SPHINCS */
  3725. #endif /* HAVE_PQC */
  3726. /* keyType */
  3727. #ifndef NO_DSA
  3728. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3729. #endif /* NO_DSA */
  3730. #ifndef NO_RSA
  3731. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3732. #ifdef WC_RSA_PSS
  3733. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3734. #endif
  3735. #endif /* NO_RSA */
  3736. #ifdef HAVE_ECC
  3737. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3738. #endif /* HAVE_ECC */
  3739. #ifdef HAVE_ED25519
  3740. static const byte keyEd25519Oid[] = {43, 101, 112};
  3741. #endif /* HAVE_ED25519 */
  3742. #ifdef HAVE_CURVE25519
  3743. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3744. #endif
  3745. #ifdef HAVE_ED448
  3746. static const byte keyEd448Oid[] = {43, 101, 113};
  3747. #endif /* HAVE_ED448 */
  3748. #ifdef HAVE_CURVE448
  3749. static const byte keyCurve448Oid[] = {43, 101, 111};
  3750. #endif /* HAVE_CURVE448 */
  3751. #ifndef NO_DH
  3752. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3753. #endif /* !NO_DH */
  3754. #ifdef HAVE_PQC
  3755. #ifdef HAVE_FALCON
  3756. /* Falcon Level 1: 1 3 9999 3 1 */
  3757. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3758. /* Falcon Level 5: 1 3 9999 3 4 */
  3759. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3760. #endif /* HAVE_FALCON */
  3761. #ifdef HAVE_DILITHIUM
  3762. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3763. static const byte keyDilithium_Level2Oid[] =
  3764. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3765. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3766. static const byte keyDilithium_Level3Oid[] =
  3767. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3768. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3769. static const byte keyDilithium_Level5Oid[] =
  3770. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3771. #endif /* HAVE_DILITHIUM */
  3772. #ifdef HAVE_SPHINCS
  3773. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3774. static const byte keySphincsFast_Level1Oid[] =
  3775. {43, 206, 15, 6, 7, 4};
  3776. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3777. static const byte keySphincsFast_Level3Oid[] =
  3778. {43, 206, 15, 6, 8, 3};
  3779. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3780. static const byte keySphincsFast_Level5Oid[] =
  3781. {43, 206, 15, 6, 9, 3};
  3782. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3783. static const byte keySphincsSmall_Level1Oid[] =
  3784. {43, 206, 15, 6, 7, 10};
  3785. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3786. static const byte keySphincsSmall_Level3Oid[] =
  3787. {43, 206, 15, 6, 8, 7};
  3788. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3789. static const byte keySphincsSmall_Level5Oid[] =
  3790. {43, 206, 15, 6, 9, 7};
  3791. #endif /* HAVE_SPHINCS */
  3792. #endif /* HAVE_PQC */
  3793. /* curveType */
  3794. #ifdef HAVE_ECC
  3795. /* See "ecc_sets" table in ecc.c */
  3796. #endif /* HAVE_ECC */
  3797. #ifdef HAVE_AES_CBC
  3798. /* blkType */
  3799. #ifdef WOLFSSL_AES_128
  3800. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3801. #endif
  3802. #ifdef WOLFSSL_AES_192
  3803. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3804. #endif
  3805. #ifdef WOLFSSL_AES_256
  3806. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3807. #endif
  3808. #endif /* HAVE_AES_CBC */
  3809. #ifdef HAVE_AESGCM
  3810. #ifdef WOLFSSL_AES_128
  3811. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3812. #endif
  3813. #ifdef WOLFSSL_AES_192
  3814. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3815. #endif
  3816. #ifdef WOLFSSL_AES_256
  3817. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3818. #endif
  3819. #endif /* HAVE_AESGCM */
  3820. #ifdef HAVE_AESCCM
  3821. #ifdef WOLFSSL_AES_128
  3822. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3823. #endif
  3824. #ifdef WOLFSSL_AES_192
  3825. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3826. #endif
  3827. #ifdef WOLFSSL_AES_256
  3828. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3829. #endif
  3830. #endif /* HAVE_AESCCM */
  3831. #ifndef NO_DES3
  3832. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3833. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3834. #endif
  3835. /* keyWrapType */
  3836. #ifdef WOLFSSL_AES_128
  3837. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3838. #endif
  3839. #ifdef WOLFSSL_AES_192
  3840. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3841. #endif
  3842. #ifdef WOLFSSL_AES_256
  3843. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3844. #endif
  3845. #ifdef HAVE_PKCS7
  3846. /* From RFC 3211 */
  3847. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3848. #endif
  3849. /* cmsKeyAgreeType */
  3850. #ifndef NO_SHA
  3851. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3852. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3853. #endif
  3854. #ifdef WOLFSSL_SHA224
  3855. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3856. #endif
  3857. #ifndef NO_SHA256
  3858. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3859. #endif
  3860. #ifdef WOLFSSL_SHA384
  3861. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3862. #endif
  3863. #ifdef WOLFSSL_SHA512
  3864. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3865. #endif
  3866. /* ocspType */
  3867. #ifdef HAVE_OCSP
  3868. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3869. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3870. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3871. #endif /* HAVE_OCSP */
  3872. /* certExtType */
  3873. static const byte extBasicCaOid[] = {85, 29, 19};
  3874. static const byte extAltNamesOid[] = {85, 29, 17};
  3875. static const byte extCrlDistOid[] = {85, 29, 31};
  3876. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3877. static const byte extAuthKeyOid[] = {85, 29, 35};
  3878. static const byte extSubjKeyOid[] = {85, 29, 14};
  3879. static const byte extCertPolicyOid[] = {85, 29, 32};
  3880. static const byte extKeyUsageOid[] = {85, 29, 15};
  3881. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3882. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3883. #ifndef IGNORE_NAME_CONSTRAINTS
  3884. static const byte extNameConsOid[] = {85, 29, 30};
  3885. #endif
  3886. #ifdef HAVE_CRL
  3887. static const byte extCrlNumberOid[] = {85, 29, 20};
  3888. #endif
  3889. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3890. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  3891. #endif
  3892. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3893. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  3894. #endif
  3895. /* certAuthInfoType */
  3896. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3897. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3898. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3899. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  3900. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  3901. /* certPolicyType */
  3902. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3903. #ifdef WOLFSSL_FPKI
  3904. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  3905. static const byte extCertPolicyFpkiCommonAuthOid[] =
  3906. CERT_POLICY_TYPE_OID_BASE(13);
  3907. static const byte extCertPolicyFpkiPivAuthOid[] =
  3908. CERT_POLICY_TYPE_OID_BASE(40);
  3909. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  3910. CERT_POLICY_TYPE_OID_BASE(41);
  3911. static const byte extCertPolicyFpkiPiviAuthOid[] =
  3912. CERT_POLICY_TYPE_OID_BASE(45);
  3913. #endif /* WOLFSSL_FPKI */
  3914. /* certAltNameType */
  3915. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3916. /* certKeyUseType */
  3917. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3918. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3919. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3920. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3921. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3922. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3923. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3924. #ifdef WOLFSSL_WOLFSSH
  3925. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  3926. static const byte extExtKeyUsageSshClientAuthOid[] =
  3927. EXT_KEY_USAGE_OID_BASE(21);
  3928. static const byte extExtKeyUsageSshMSCLOid[] =
  3929. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  3930. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  3931. {43, 6, 1, 5, 2, 3, 4};
  3932. #endif /* WOLFSSL_WOLFSSH */
  3933. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3934. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  3935. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  3936. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  3937. static const byte extSubjDirAttrGenderOid[] =
  3938. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  3939. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  3940. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  3941. #endif
  3942. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3943. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  3944. defined(OPENSSL_EXTRA_X509_SMALL)
  3945. /* csrAttrType */
  3946. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  3947. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3948. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3949. defined(WOLFSSL_ASN_TEMPLATE)
  3950. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  3951. #endif
  3952. #ifdef WOLFSSL_CERT_REQ
  3953. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  3954. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  3955. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  3956. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  3957. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3958. static const byte attrDnQualifier[] = {85, 4, 46};
  3959. static const byte attrInitals[] = {85, 4, 43};
  3960. static const byte attrSurname[] = {85, 4, 4};
  3961. static const byte attrGivenName[] = {85, 4, 42};
  3962. #endif
  3963. #endif
  3964. /* kdfType */
  3965. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3966. /* PKCS5 */
  3967. #if !defined(NO_DES3) && !defined(NO_MD5)
  3968. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3969. #endif
  3970. #if !defined(NO_DES3) && !defined(NO_SHA)
  3971. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3972. #endif
  3973. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3974. /* PKCS12 */
  3975. #if !defined(NO_RC4) && !defined(NO_SHA)
  3976. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3977. #endif
  3978. #if !defined(NO_DES3) && !defined(NO_SHA)
  3979. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3980. #endif
  3981. #if defined(WC_RC2) && !defined(NO_SHA)
  3982. static const byte pbe40Rc2Cbc[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 6};
  3983. #endif
  3984. #ifdef HAVE_LIBZ
  3985. /* zlib compression */
  3986. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3987. #endif
  3988. #ifdef WOLFSSL_APACHE_HTTPD
  3989. /* tlsExtType */
  3990. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3991. /* certNameType */
  3992. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3993. #endif
  3994. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3995. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3996. defined(WOLFSSL_ASN_TEMPLATE)
  3997. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  3998. #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
  3999. static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
  4000. static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
  4001. #endif
  4002. #if defined(WOLFSSL_CERT_GEN) || \
  4003. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  4004. defined(WOLFSSL_ASN_TEMPLATE)
  4005. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  4006. #endif
  4007. /* Looks up the ID/type of an OID.
  4008. *
  4009. * When known returns the OID as a byte array and its length.
  4010. * ID-type are unique.
  4011. *
  4012. * Use oidIgnoreType to autofail.
  4013. *
  4014. * @param [in] id OID id.
  4015. * @param [in] type Type of OID (enum Oid_Types).
  4016. * @param [out] oidSz Length of OID byte array returned.
  4017. * @return Array of bytes for the OID.
  4018. * @return NULL when ID/type not recognized.
  4019. */
  4020. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  4021. {
  4022. const byte* oid = NULL;
  4023. *oidSz = 0;
  4024. switch (type) {
  4025. case oidHashType:
  4026. switch (id) {
  4027. #ifdef WOLFSSL_MD2
  4028. case MD2h:
  4029. oid = hashMd2hOid;
  4030. *oidSz = sizeof(hashMd2hOid);
  4031. break;
  4032. #endif
  4033. #ifndef NO_MD5
  4034. case MD5h:
  4035. oid = hashMd5hOid;
  4036. *oidSz = sizeof(hashMd5hOid);
  4037. break;
  4038. #endif
  4039. #ifndef NO_SHA
  4040. case SHAh:
  4041. oid = hashSha1hOid;
  4042. *oidSz = sizeof(hashSha1hOid);
  4043. break;
  4044. #endif
  4045. #ifdef WOLFSSL_SHA224
  4046. case SHA224h:
  4047. oid = hashSha224hOid;
  4048. *oidSz = sizeof(hashSha224hOid);
  4049. break;
  4050. #endif
  4051. #ifndef NO_SHA256
  4052. case SHA256h:
  4053. oid = hashSha256hOid;
  4054. *oidSz = sizeof(hashSha256hOid);
  4055. break;
  4056. #endif
  4057. #ifdef WOLFSSL_SHA384
  4058. case SHA384h:
  4059. oid = hashSha384hOid;
  4060. *oidSz = sizeof(hashSha384hOid);
  4061. break;
  4062. #endif
  4063. #ifdef WOLFSSL_SHA512
  4064. #ifndef WOLFSSL_NOSHA512_224
  4065. case SHA512_224h:
  4066. oid = hashSha512_224hOid;
  4067. *oidSz = sizeof(hashSha512_224hOid);
  4068. break;
  4069. #endif
  4070. #ifndef WOLFSSL_NOSHA512_256
  4071. case SHA512_256h:
  4072. oid = hashSha512_256hOid;
  4073. *oidSz = sizeof(hashSha512_256hOid);
  4074. break;
  4075. #endif
  4076. case SHA512h:
  4077. oid = hashSha512hOid;
  4078. *oidSz = sizeof(hashSha512hOid);
  4079. break;
  4080. #endif
  4081. #ifdef WOLFSSL_SHA3
  4082. #ifndef WOLFSSL_NOSHA3_224
  4083. case SHA3_224h:
  4084. oid = hashSha3_224hOid;
  4085. *oidSz = sizeof(hashSha3_224hOid);
  4086. break;
  4087. #endif /* WOLFSSL_NOSHA3_224 */
  4088. #ifndef WOLFSSL_NOSHA3_256
  4089. case SHA3_256h:
  4090. oid = hashSha3_256hOid;
  4091. *oidSz = sizeof(hashSha3_256hOid);
  4092. break;
  4093. #endif /* WOLFSSL_NOSHA3_256 */
  4094. #ifndef WOLFSSL_NOSHA3_384
  4095. case SHA3_384h:
  4096. oid = hashSha3_384hOid;
  4097. *oidSz = sizeof(hashSha3_384hOid);
  4098. break;
  4099. #endif /* WOLFSSL_NOSHA3_384 */
  4100. #ifndef WOLFSSL_NOSHA3_512
  4101. case SHA3_512h:
  4102. oid = hashSha3_512hOid;
  4103. *oidSz = sizeof(hashSha3_512hOid);
  4104. break;
  4105. #endif /* WOLFSSL_NOSHA3_512 */
  4106. #endif /* WOLFSSL_SHA3 */
  4107. default:
  4108. break;
  4109. }
  4110. break;
  4111. case oidSigType:
  4112. switch (id) {
  4113. #if !defined(NO_DSA) && !defined(NO_SHA)
  4114. case CTC_SHAwDSA:
  4115. oid = sigSha1wDsaOid;
  4116. *oidSz = sizeof(sigSha1wDsaOid);
  4117. break;
  4118. case CTC_SHA256wDSA:
  4119. oid = sigSha256wDsaOid;
  4120. *oidSz = sizeof(sigSha256wDsaOid);
  4121. break;
  4122. #endif /* NO_DSA */
  4123. #ifndef NO_RSA
  4124. #ifdef WOLFSSL_MD2
  4125. case CTC_MD2wRSA:
  4126. oid = sigMd2wRsaOid;
  4127. *oidSz = sizeof(sigMd2wRsaOid);
  4128. break;
  4129. #endif
  4130. #ifndef NO_MD5
  4131. case CTC_MD5wRSA:
  4132. oid = sigMd5wRsaOid;
  4133. *oidSz = sizeof(sigMd5wRsaOid);
  4134. break;
  4135. #endif
  4136. #ifndef NO_SHA
  4137. case CTC_SHAwRSA:
  4138. oid = sigSha1wRsaOid;
  4139. *oidSz = sizeof(sigSha1wRsaOid);
  4140. break;
  4141. #endif
  4142. #ifdef WOLFSSL_SHA224
  4143. case CTC_SHA224wRSA:
  4144. oid = sigSha224wRsaOid;
  4145. *oidSz = sizeof(sigSha224wRsaOid);
  4146. break;
  4147. #endif
  4148. #ifndef NO_SHA256
  4149. case CTC_SHA256wRSA:
  4150. oid = sigSha256wRsaOid;
  4151. *oidSz = sizeof(sigSha256wRsaOid);
  4152. break;
  4153. #endif
  4154. #ifdef WOLFSSL_SHA384
  4155. case CTC_SHA384wRSA:
  4156. oid = sigSha384wRsaOid;
  4157. *oidSz = sizeof(sigSha384wRsaOid);
  4158. break;
  4159. #endif
  4160. #ifdef WOLFSSL_SHA512
  4161. case CTC_SHA512wRSA:
  4162. oid = sigSha512wRsaOid;
  4163. *oidSz = sizeof(sigSha512wRsaOid);
  4164. break;
  4165. #endif /* WOLFSSL_SHA512 */
  4166. #ifdef WOLFSSL_SHA3
  4167. #ifndef WOLFSSL_NOSHA3_224
  4168. case CTC_SHA3_224wRSA:
  4169. oid = sigSha3_224wRsaOid;
  4170. *oidSz = sizeof(sigSha3_224wRsaOid);
  4171. break;
  4172. #endif
  4173. #ifndef WOLFSSL_NOSHA3_256
  4174. case CTC_SHA3_256wRSA:
  4175. oid = sigSha3_256wRsaOid;
  4176. *oidSz = sizeof(sigSha3_256wRsaOid);
  4177. break;
  4178. #endif
  4179. #ifndef WOLFSSL_NOSHA3_384
  4180. case CTC_SHA3_384wRSA:
  4181. oid = sigSha3_384wRsaOid;
  4182. *oidSz = sizeof(sigSha3_384wRsaOid);
  4183. break;
  4184. #endif
  4185. #ifndef WOLFSSL_NOSHA3_512
  4186. case CTC_SHA3_512wRSA:
  4187. oid = sigSha3_512wRsaOid;
  4188. *oidSz = sizeof(sigSha3_512wRsaOid);
  4189. break;
  4190. #endif
  4191. #endif
  4192. #ifdef WC_RSA_PSS
  4193. case CTC_RSASSAPSS:
  4194. oid = sigRsaSsaPssOid;
  4195. *oidSz = sizeof(sigRsaSsaPssOid);
  4196. break;
  4197. #endif
  4198. #endif /* NO_RSA */
  4199. #ifdef HAVE_ECC
  4200. #ifndef NO_SHA
  4201. case CTC_SHAwECDSA:
  4202. oid = sigSha1wEcdsaOid;
  4203. *oidSz = sizeof(sigSha1wEcdsaOid);
  4204. break;
  4205. #endif
  4206. #ifdef WOLFSSL_SHA224
  4207. case CTC_SHA224wECDSA:
  4208. oid = sigSha224wEcdsaOid;
  4209. *oidSz = sizeof(sigSha224wEcdsaOid);
  4210. break;
  4211. #endif
  4212. #ifndef NO_SHA256
  4213. case CTC_SHA256wECDSA:
  4214. oid = sigSha256wEcdsaOid;
  4215. *oidSz = sizeof(sigSha256wEcdsaOid);
  4216. break;
  4217. #endif
  4218. #ifdef WOLFSSL_SHA384
  4219. case CTC_SHA384wECDSA:
  4220. oid = sigSha384wEcdsaOid;
  4221. *oidSz = sizeof(sigSha384wEcdsaOid);
  4222. break;
  4223. #endif
  4224. #ifdef WOLFSSL_SHA512
  4225. case CTC_SHA512wECDSA:
  4226. oid = sigSha512wEcdsaOid;
  4227. *oidSz = sizeof(sigSha512wEcdsaOid);
  4228. break;
  4229. #endif
  4230. #ifdef WOLFSSL_SHA3
  4231. #ifndef WOLFSSL_NOSHA3_224
  4232. case CTC_SHA3_224wECDSA:
  4233. oid = sigSha3_224wEcdsaOid;
  4234. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4235. break;
  4236. #endif
  4237. #ifndef WOLFSSL_NOSHA3_256
  4238. case CTC_SHA3_256wECDSA:
  4239. oid = sigSha3_256wEcdsaOid;
  4240. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4241. break;
  4242. #endif
  4243. #ifndef WOLFSSL_NOSHA3_384
  4244. case CTC_SHA3_384wECDSA:
  4245. oid = sigSha3_384wEcdsaOid;
  4246. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4247. break;
  4248. #endif
  4249. #ifndef WOLFSSL_NOSHA3_512
  4250. case CTC_SHA3_512wECDSA:
  4251. oid = sigSha3_512wEcdsaOid;
  4252. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4253. break;
  4254. #endif
  4255. #endif
  4256. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  4257. case CTC_SM3wSM2:
  4258. oid = sigSm3wSm2Oid;
  4259. *oidSz = sizeof(sigSm3wSm2Oid);
  4260. break;
  4261. #endif
  4262. #endif /* HAVE_ECC */
  4263. #ifdef HAVE_ED25519
  4264. case CTC_ED25519:
  4265. oid = sigEd25519Oid;
  4266. *oidSz = sizeof(sigEd25519Oid);
  4267. break;
  4268. #endif
  4269. #ifdef HAVE_ED448
  4270. case CTC_ED448:
  4271. oid = sigEd448Oid;
  4272. *oidSz = sizeof(sigEd448Oid);
  4273. break;
  4274. #endif
  4275. #ifdef HAVE_PQC
  4276. #ifdef HAVE_FALCON
  4277. case CTC_FALCON_LEVEL1:
  4278. oid = sigFalcon_Level1Oid;
  4279. *oidSz = sizeof(sigFalcon_Level1Oid);
  4280. break;
  4281. case CTC_FALCON_LEVEL5:
  4282. oid = sigFalcon_Level5Oid;
  4283. *oidSz = sizeof(sigFalcon_Level5Oid);
  4284. break;
  4285. #endif /* HAVE_FALCON */
  4286. #ifdef HAVE_DILITHIUM
  4287. case CTC_DILITHIUM_LEVEL2:
  4288. oid = sigDilithium_Level2Oid;
  4289. *oidSz = sizeof(sigDilithium_Level2Oid);
  4290. break;
  4291. case CTC_DILITHIUM_LEVEL3:
  4292. oid = sigDilithium_Level3Oid;
  4293. *oidSz = sizeof(sigDilithium_Level3Oid);
  4294. break;
  4295. case CTC_DILITHIUM_LEVEL5:
  4296. oid = sigDilithium_Level5Oid;
  4297. *oidSz = sizeof(sigDilithium_Level5Oid);
  4298. break;
  4299. #endif /* HAVE_DILITHIUM */
  4300. #ifdef HAVE_SPHINCS
  4301. case CTC_SPHINCS_FAST_LEVEL1:
  4302. oid = sigSphincsFast_Level1Oid;
  4303. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4304. break;
  4305. case CTC_SPHINCS_FAST_LEVEL3:
  4306. oid = sigSphincsFast_Level3Oid;
  4307. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4308. break;
  4309. case CTC_SPHINCS_FAST_LEVEL5:
  4310. oid = sigSphincsFast_Level5Oid;
  4311. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4312. break;
  4313. case CTC_SPHINCS_SMALL_LEVEL1:
  4314. oid = sigSphincsSmall_Level1Oid;
  4315. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4316. break;
  4317. case CTC_SPHINCS_SMALL_LEVEL3:
  4318. oid = sigSphincsSmall_Level3Oid;
  4319. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4320. break;
  4321. case CTC_SPHINCS_SMALL_LEVEL5:
  4322. oid = sigSphincsSmall_Level5Oid;
  4323. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4324. break;
  4325. #endif /* HAVE_SPHINCS */
  4326. #endif /* HAVE_PQC */
  4327. default:
  4328. break;
  4329. }
  4330. break;
  4331. case oidKeyType:
  4332. switch (id) {
  4333. #ifndef NO_DSA
  4334. case DSAk:
  4335. oid = keyDsaOid;
  4336. *oidSz = sizeof(keyDsaOid);
  4337. break;
  4338. #endif /* NO_DSA */
  4339. #ifndef NO_RSA
  4340. case RSAk:
  4341. oid = keyRsaOid;
  4342. *oidSz = sizeof(keyRsaOid);
  4343. break;
  4344. #ifdef WC_RSA_PSS
  4345. case RSAPSSk:
  4346. oid = keyRsaPssOid;
  4347. *oidSz = sizeof(keyRsaPssOid);
  4348. break;
  4349. #endif
  4350. #endif /* NO_RSA */
  4351. #ifdef HAVE_ECC
  4352. case ECDSAk:
  4353. oid = keyEcdsaOid;
  4354. *oidSz = sizeof(keyEcdsaOid);
  4355. break;
  4356. #endif /* HAVE_ECC */
  4357. #ifdef HAVE_ED25519
  4358. case ED25519k:
  4359. oid = keyEd25519Oid;
  4360. *oidSz = sizeof(keyEd25519Oid);
  4361. break;
  4362. #endif /* HAVE_ED25519 */
  4363. #ifdef HAVE_CURVE25519
  4364. case X25519k:
  4365. oid = keyCurve25519Oid;
  4366. *oidSz = sizeof(keyCurve25519Oid);
  4367. break;
  4368. #endif /* HAVE_CURVE25519 */
  4369. #ifdef HAVE_ED448
  4370. case ED448k:
  4371. oid = keyEd448Oid;
  4372. *oidSz = sizeof(keyEd448Oid);
  4373. break;
  4374. #endif /* HAVE_ED448 */
  4375. #ifdef HAVE_CURVE448
  4376. case X448k:
  4377. oid = keyCurve448Oid;
  4378. *oidSz = sizeof(keyCurve448Oid);
  4379. break;
  4380. #endif /* HAVE_CURVE448 */
  4381. #ifndef NO_DH
  4382. case DHk:
  4383. oid = keyDhOid;
  4384. *oidSz = sizeof(keyDhOid);
  4385. break;
  4386. #endif /* !NO_DH */
  4387. #ifdef HAVE_PQC
  4388. #ifdef HAVE_FALCON
  4389. case FALCON_LEVEL1k:
  4390. oid = keyFalcon_Level1Oid;
  4391. *oidSz = sizeof(keyFalcon_Level1Oid);
  4392. break;
  4393. case FALCON_LEVEL5k:
  4394. oid = keyFalcon_Level5Oid;
  4395. *oidSz = sizeof(keyFalcon_Level5Oid);
  4396. break;
  4397. #endif /* HAVE_FALCON */
  4398. #ifdef HAVE_DILITHIUM
  4399. case DILITHIUM_LEVEL2k:
  4400. oid = keyDilithium_Level2Oid;
  4401. *oidSz = sizeof(keyDilithium_Level2Oid);
  4402. break;
  4403. case DILITHIUM_LEVEL3k:
  4404. oid = keyDilithium_Level3Oid;
  4405. *oidSz = sizeof(keyDilithium_Level3Oid);
  4406. break;
  4407. case DILITHIUM_LEVEL5k:
  4408. oid = keyDilithium_Level5Oid;
  4409. *oidSz = sizeof(keyDilithium_Level5Oid);
  4410. break;
  4411. #endif /* HAVE_DILITHIUM */
  4412. #ifdef HAVE_SPHINCS
  4413. case SPHINCS_FAST_LEVEL1k:
  4414. oid = keySphincsFast_Level1Oid;
  4415. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4416. break;
  4417. case SPHINCS_FAST_LEVEL3k:
  4418. oid = keySphincsFast_Level3Oid;
  4419. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4420. break;
  4421. case SPHINCS_FAST_LEVEL5k:
  4422. oid = keySphincsFast_Level5Oid;
  4423. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4424. break;
  4425. case SPHINCS_SMALL_LEVEL1k:
  4426. oid = keySphincsSmall_Level1Oid;
  4427. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4428. break;
  4429. case SPHINCS_SMALL_LEVEL3k:
  4430. oid = keySphincsSmall_Level3Oid;
  4431. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4432. break;
  4433. case SPHINCS_SMALL_LEVEL5k:
  4434. oid = keySphincsSmall_Level5Oid;
  4435. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4436. break;
  4437. #endif /* HAVE_SPHINCS */
  4438. #endif /* HAVE_PQC */
  4439. default:
  4440. break;
  4441. }
  4442. break;
  4443. #ifdef HAVE_ECC
  4444. case oidCurveType:
  4445. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4446. WOLFSSL_MSG("ECC OID not found");
  4447. }
  4448. break;
  4449. #endif /* HAVE_ECC */
  4450. case oidBlkType:
  4451. switch (id) {
  4452. #ifdef HAVE_AES_CBC
  4453. #ifdef WOLFSSL_AES_128
  4454. case AES128CBCb:
  4455. oid = blkAes128CbcOid;
  4456. *oidSz = sizeof(blkAes128CbcOid);
  4457. break;
  4458. #endif
  4459. #ifdef WOLFSSL_AES_192
  4460. case AES192CBCb:
  4461. oid = blkAes192CbcOid;
  4462. *oidSz = sizeof(blkAes192CbcOid);
  4463. break;
  4464. #endif
  4465. #ifdef WOLFSSL_AES_256
  4466. case AES256CBCb:
  4467. oid = blkAes256CbcOid;
  4468. *oidSz = sizeof(blkAes256CbcOid);
  4469. break;
  4470. #endif
  4471. #endif /* HAVE_AES_CBC */
  4472. #ifdef HAVE_AESGCM
  4473. #ifdef WOLFSSL_AES_128
  4474. case AES128GCMb:
  4475. oid = blkAes128GcmOid;
  4476. *oidSz = sizeof(blkAes128GcmOid);
  4477. break;
  4478. #endif
  4479. #ifdef WOLFSSL_AES_192
  4480. case AES192GCMb:
  4481. oid = blkAes192GcmOid;
  4482. *oidSz = sizeof(blkAes192GcmOid);
  4483. break;
  4484. #endif
  4485. #ifdef WOLFSSL_AES_256
  4486. case AES256GCMb:
  4487. oid = blkAes256GcmOid;
  4488. *oidSz = sizeof(blkAes256GcmOid);
  4489. break;
  4490. #endif
  4491. #endif /* HAVE_AESGCM */
  4492. #ifdef HAVE_AESCCM
  4493. #ifdef WOLFSSL_AES_128
  4494. case AES128CCMb:
  4495. oid = blkAes128CcmOid;
  4496. *oidSz = sizeof(blkAes128CcmOid);
  4497. break;
  4498. #endif
  4499. #ifdef WOLFSSL_AES_192
  4500. case AES192CCMb:
  4501. oid = blkAes192CcmOid;
  4502. *oidSz = sizeof(blkAes192CcmOid);
  4503. break;
  4504. #endif
  4505. #ifdef WOLFSSL_AES_256
  4506. case AES256CCMb:
  4507. oid = blkAes256CcmOid;
  4508. *oidSz = sizeof(blkAes256CcmOid);
  4509. break;
  4510. #endif
  4511. #endif /* HAVE_AESCCM */
  4512. #ifndef NO_DES3
  4513. case DESb:
  4514. oid = blkDesCbcOid;
  4515. *oidSz = sizeof(blkDesCbcOid);
  4516. break;
  4517. case DES3b:
  4518. oid = blkDes3CbcOid;
  4519. *oidSz = sizeof(blkDes3CbcOid);
  4520. break;
  4521. #endif /* !NO_DES3 */
  4522. default:
  4523. break;
  4524. }
  4525. break;
  4526. #ifdef HAVE_OCSP
  4527. case oidOcspType:
  4528. switch (id) {
  4529. case OCSP_BASIC_OID:
  4530. oid = ocspBasicOid;
  4531. *oidSz = sizeof(ocspBasicOid);
  4532. break;
  4533. case OCSP_NONCE_OID:
  4534. oid = ocspNonceOid;
  4535. *oidSz = sizeof(ocspNonceOid);
  4536. break;
  4537. default:
  4538. break;
  4539. }
  4540. break;
  4541. #endif /* HAVE_OCSP */
  4542. case oidCertExtType:
  4543. switch (id) {
  4544. case BASIC_CA_OID:
  4545. oid = extBasicCaOid;
  4546. *oidSz = sizeof(extBasicCaOid);
  4547. break;
  4548. case ALT_NAMES_OID:
  4549. oid = extAltNamesOid;
  4550. *oidSz = sizeof(extAltNamesOid);
  4551. break;
  4552. case CRL_DIST_OID:
  4553. oid = extCrlDistOid;
  4554. *oidSz = sizeof(extCrlDistOid);
  4555. break;
  4556. case AUTH_INFO_OID:
  4557. oid = extAuthInfoOid;
  4558. *oidSz = sizeof(extAuthInfoOid);
  4559. break;
  4560. case AUTH_KEY_OID:
  4561. oid = extAuthKeyOid;
  4562. *oidSz = sizeof(extAuthKeyOid);
  4563. break;
  4564. case SUBJ_KEY_OID:
  4565. oid = extSubjKeyOid;
  4566. *oidSz = sizeof(extSubjKeyOid);
  4567. break;
  4568. case CERT_POLICY_OID:
  4569. oid = extCertPolicyOid;
  4570. *oidSz = sizeof(extCertPolicyOid);
  4571. break;
  4572. case KEY_USAGE_OID:
  4573. oid = extKeyUsageOid;
  4574. *oidSz = sizeof(extKeyUsageOid);
  4575. break;
  4576. case INHIBIT_ANY_OID:
  4577. oid = extInhibitAnyOid;
  4578. *oidSz = sizeof(extInhibitAnyOid);
  4579. break;
  4580. case EXT_KEY_USAGE_OID:
  4581. oid = extExtKeyUsageOid;
  4582. *oidSz = sizeof(extExtKeyUsageOid);
  4583. break;
  4584. #ifndef IGNORE_NAME_CONSTRAINTS
  4585. case NAME_CONS_OID:
  4586. oid = extNameConsOid;
  4587. *oidSz = sizeof(extNameConsOid);
  4588. break;
  4589. #endif
  4590. #ifdef HAVE_OCSP
  4591. case OCSP_NOCHECK_OID:
  4592. oid = ocspNoCheckOid;
  4593. *oidSz = sizeof(ocspNoCheckOid);
  4594. break;
  4595. #endif
  4596. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4597. case SUBJ_DIR_ATTR_OID:
  4598. oid = extSubjDirAttrOid;
  4599. *oidSz = sizeof(extSubjDirAttrOid);
  4600. break;
  4601. #endif
  4602. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4603. case SUBJ_INFO_ACC_OID:
  4604. oid = extSubjInfoAccessOid;
  4605. *oidSz = sizeof(extSubjInfoAccessOid);
  4606. break;
  4607. #endif
  4608. default:
  4609. break;
  4610. }
  4611. break;
  4612. case oidCrlExtType:
  4613. #ifdef HAVE_CRL
  4614. switch (id) {
  4615. case AUTH_KEY_OID:
  4616. oid = extAuthKeyOid;
  4617. *oidSz = sizeof(extAuthKeyOid);
  4618. break;
  4619. case CRL_NUMBER_OID:
  4620. oid = extCrlNumberOid;
  4621. *oidSz = sizeof(extCrlNumberOid);
  4622. break;
  4623. default:
  4624. break;
  4625. }
  4626. #endif
  4627. break;
  4628. case oidCertAuthInfoType:
  4629. switch (id) {
  4630. case AIA_OCSP_OID:
  4631. oid = extAuthInfoOcspOid;
  4632. *oidSz = sizeof(extAuthInfoOcspOid);
  4633. break;
  4634. case AIA_CA_ISSUER_OID:
  4635. oid = extAuthInfoCaIssuerOid;
  4636. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4637. break;
  4638. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4639. case AIA_CA_REPO_OID:
  4640. oid = extAuthInfoCaRespOid;
  4641. *oidSz = sizeof(extAuthInfoCaRespOid);
  4642. break;
  4643. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4644. default:
  4645. break;
  4646. }
  4647. break;
  4648. case oidCertPolicyType:
  4649. switch (id) {
  4650. case CP_ANY_OID:
  4651. oid = extCertPolicyAnyOid;
  4652. *oidSz = sizeof(extCertPolicyAnyOid);
  4653. break;
  4654. #if defined(WOLFSSL_FPKI)
  4655. case CP_FPKI_COMMON_AUTH_OID:
  4656. oid = extCertPolicyFpkiCommonAuthOid;
  4657. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4658. break;
  4659. case CP_FPKI_PIV_AUTH_OID:
  4660. oid = extCertPolicyFpkiPivAuthOid;
  4661. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4662. break;
  4663. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4664. oid = extCertPolicyFpkiPivAuthHwOid;
  4665. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4666. break;
  4667. case CP_FPKI_PIVI_AUTH_OID:
  4668. oid = extCertPolicyFpkiPiviAuthOid;
  4669. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4670. break;
  4671. #endif /* WOLFSSL_FPKI */
  4672. default:
  4673. break;
  4674. }
  4675. break;
  4676. case oidCertAltNameType:
  4677. switch (id) {
  4678. case HW_NAME_OID:
  4679. oid = extAltNamesHwNameOid;
  4680. *oidSz = sizeof(extAltNamesHwNameOid);
  4681. break;
  4682. default:
  4683. break;
  4684. }
  4685. break;
  4686. case oidCertKeyUseType:
  4687. switch (id) {
  4688. case EKU_ANY_OID:
  4689. oid = extExtKeyUsageAnyOid;
  4690. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4691. break;
  4692. case EKU_SERVER_AUTH_OID:
  4693. oid = extExtKeyUsageServerAuthOid;
  4694. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4695. break;
  4696. case EKU_CLIENT_AUTH_OID:
  4697. oid = extExtKeyUsageClientAuthOid;
  4698. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4699. break;
  4700. case EKU_CODESIGNING_OID:
  4701. oid = extExtKeyUsageCodeSigningOid;
  4702. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4703. break;
  4704. case EKU_EMAILPROTECT_OID:
  4705. oid = extExtKeyUsageEmailProtectOid;
  4706. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4707. break;
  4708. case EKU_TIMESTAMP_OID:
  4709. oid = extExtKeyUsageTimestampOid;
  4710. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4711. break;
  4712. case EKU_OCSP_SIGN_OID:
  4713. oid = extExtKeyUsageOcspSignOid;
  4714. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4715. break;
  4716. #ifdef WOLFSSL_WOLFSSH
  4717. case EKU_SSH_CLIENT_AUTH_OID:
  4718. oid = extExtKeyUsageSshClientAuthOid;
  4719. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4720. break;
  4721. case EKU_SSH_MSCL_OID:
  4722. oid = extExtKeyUsageSshMSCLOid;
  4723. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4724. break;
  4725. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4726. oid = extExtKeyUsageSshKpClientAuthOid;
  4727. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4728. break;
  4729. #endif /* WOLFSSL_WOLFSSH */
  4730. default:
  4731. break;
  4732. }
  4733. break;
  4734. case oidKdfType:
  4735. switch (id) {
  4736. case PBKDF2_OID:
  4737. oid = pbkdf2Oid;
  4738. *oidSz = sizeof(pbkdf2Oid);
  4739. break;
  4740. default:
  4741. break;
  4742. }
  4743. break;
  4744. case oidPBEType:
  4745. switch (id) {
  4746. #if !defined(NO_SHA) && !defined(NO_RC4)
  4747. case PBE_SHA1_RC4_128_SUM:
  4748. case PBE_SHA1_RC4_128:
  4749. oid = pbeSha1RC4128;
  4750. *oidSz = sizeof(pbeSha1RC4128);
  4751. break;
  4752. #endif
  4753. #if !defined(NO_MD5) && !defined(NO_DES3)
  4754. case PBE_MD5_DES_SUM:
  4755. case PBE_MD5_DES:
  4756. oid = pbeMd5Des;
  4757. *oidSz = sizeof(pbeMd5Des);
  4758. break;
  4759. #endif
  4760. #if !defined(NO_SHA) && !defined(NO_DES3)
  4761. case PBE_SHA1_DES_SUM:
  4762. case PBE_SHA1_DES:
  4763. oid = pbeSha1Des;
  4764. *oidSz = sizeof(pbeSha1Des);
  4765. break;
  4766. #endif
  4767. #if !defined(NO_SHA) && !defined(NO_DES3)
  4768. case PBE_SHA1_DES3_SUM:
  4769. case PBE_SHA1_DES3:
  4770. oid = pbeSha1Des3;
  4771. *oidSz = sizeof(pbeSha1Des3);
  4772. break;
  4773. #endif
  4774. #if !defined(NO_SHA) && defined(WC_RC2)
  4775. case PBE_SHA1_40RC2_CBC_SUM:
  4776. case PBE_SHA1_40RC2_CBC:
  4777. oid = pbe40Rc2Cbc;
  4778. *oidSz = sizeof(pbe40Rc2Cbc);
  4779. break;
  4780. #endif
  4781. case PBES2_SUM:
  4782. case PBES2:
  4783. oid = pbes2;
  4784. *oidSz = sizeof(pbes2);
  4785. break;
  4786. default:
  4787. break;
  4788. }
  4789. break;
  4790. case oidKeyWrapType:
  4791. switch (id) {
  4792. #ifdef WOLFSSL_AES_128
  4793. case AES128_WRAP:
  4794. oid = wrapAes128Oid;
  4795. *oidSz = sizeof(wrapAes128Oid);
  4796. break;
  4797. #endif
  4798. #ifdef WOLFSSL_AES_192
  4799. case AES192_WRAP:
  4800. oid = wrapAes192Oid;
  4801. *oidSz = sizeof(wrapAes192Oid);
  4802. break;
  4803. #endif
  4804. #ifdef WOLFSSL_AES_256
  4805. case AES256_WRAP:
  4806. oid = wrapAes256Oid;
  4807. *oidSz = sizeof(wrapAes256Oid);
  4808. break;
  4809. #endif
  4810. #ifdef HAVE_PKCS7
  4811. case PWRI_KEK_WRAP:
  4812. oid = wrapPwriKekOid;
  4813. *oidSz = sizeof(wrapPwriKekOid);
  4814. break;
  4815. #endif
  4816. default:
  4817. break;
  4818. }
  4819. break;
  4820. case oidCmsKeyAgreeType:
  4821. switch (id) {
  4822. #ifndef NO_SHA
  4823. case dhSinglePass_stdDH_sha1kdf_scheme:
  4824. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4825. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4826. break;
  4827. #endif
  4828. #ifdef WOLFSSL_SHA224
  4829. case dhSinglePass_stdDH_sha224kdf_scheme:
  4830. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4831. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4832. break;
  4833. #endif
  4834. #ifndef NO_SHA256
  4835. case dhSinglePass_stdDH_sha256kdf_scheme:
  4836. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4837. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4838. break;
  4839. #endif
  4840. #ifdef WOLFSSL_SHA384
  4841. case dhSinglePass_stdDH_sha384kdf_scheme:
  4842. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4843. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4844. break;
  4845. #endif
  4846. #ifdef WOLFSSL_SHA512
  4847. case dhSinglePass_stdDH_sha512kdf_scheme:
  4848. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4849. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4850. break;
  4851. #endif
  4852. default:
  4853. break;
  4854. }
  4855. break;
  4856. #ifndef NO_HMAC
  4857. case oidHmacType:
  4858. switch (id) {
  4859. #ifdef WOLFSSL_SHA224
  4860. case HMAC_SHA224_OID:
  4861. oid = hmacSha224Oid;
  4862. *oidSz = sizeof(hmacSha224Oid);
  4863. break;
  4864. #endif
  4865. #ifndef NO_SHA256
  4866. case HMAC_SHA256_OID:
  4867. oid = hmacSha256Oid;
  4868. *oidSz = sizeof(hmacSha256Oid);
  4869. break;
  4870. #endif
  4871. #ifdef WOLFSSL_SHA384
  4872. case HMAC_SHA384_OID:
  4873. oid = hmacSha384Oid;
  4874. *oidSz = sizeof(hmacSha384Oid);
  4875. break;
  4876. #endif
  4877. #ifdef WOLFSSL_SHA512
  4878. case HMAC_SHA512_OID:
  4879. oid = hmacSha512Oid;
  4880. *oidSz = sizeof(hmacSha512Oid);
  4881. break;
  4882. #endif
  4883. default:
  4884. break;
  4885. }
  4886. break;
  4887. #endif /* !NO_HMAC */
  4888. #ifdef HAVE_LIBZ
  4889. case oidCompressType:
  4890. switch (id) {
  4891. case ZLIBc:
  4892. oid = zlibCompress;
  4893. *oidSz = sizeof(zlibCompress);
  4894. break;
  4895. default:
  4896. break;
  4897. }
  4898. break;
  4899. #endif /* HAVE_LIBZ */
  4900. #ifdef WOLFSSL_APACHE_HTTPD
  4901. case oidCertNameType:
  4902. switch (id) {
  4903. case NID_id_on_dnsSRV:
  4904. oid = dnsSRVOid;
  4905. *oidSz = sizeof(dnsSRVOid);
  4906. break;
  4907. default:
  4908. break;
  4909. }
  4910. break;
  4911. case oidTlsExtType:
  4912. switch (id) {
  4913. case TLS_FEATURE_OID:
  4914. oid = tlsFeatureOid;
  4915. *oidSz = sizeof(tlsFeatureOid);
  4916. break;
  4917. default:
  4918. break;
  4919. }
  4920. break;
  4921. #endif /* WOLFSSL_APACHE_HTTPD */
  4922. #ifdef WOLFSSL_CERT_REQ
  4923. case oidCsrAttrType:
  4924. switch (id) {
  4925. case GIVEN_NAME_OID:
  4926. oid = attrGivenName;
  4927. *oidSz = sizeof(attrGivenName);
  4928. break;
  4929. case SURNAME_OID:
  4930. oid = attrSurname;
  4931. *oidSz = sizeof(attrSurname);
  4932. break;
  4933. case INITIALS_OID:
  4934. oid = attrInitals;
  4935. *oidSz = sizeof(attrInitals);
  4936. break;
  4937. case DNQUALIFIER_OID:
  4938. oid = attrDnQualifier;
  4939. *oidSz = sizeof(attrDnQualifier);
  4940. break;
  4941. case UNSTRUCTURED_NAME_OID:
  4942. oid = attrUnstructuredNameOid;
  4943. *oidSz = sizeof(attrUnstructuredNameOid);
  4944. break;
  4945. case PKCS9_CONTENT_TYPE_OID:
  4946. oid = attrPkcs9ContentTypeOid;
  4947. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4948. break;
  4949. case CHALLENGE_PASSWORD_OID:
  4950. oid = attrChallengePasswordOid;
  4951. *oidSz = sizeof(attrChallengePasswordOid);
  4952. break;
  4953. case SERIAL_NUMBER_OID:
  4954. oid = attrSerialNumberOid;
  4955. *oidSz = sizeof(attrSerialNumberOid);
  4956. break;
  4957. case USER_ID_OID:
  4958. oid = uidOid;
  4959. *oidSz = sizeof(uidOid);
  4960. break;
  4961. case EXTENSION_REQUEST_OID:
  4962. oid = attrExtensionRequestOid;
  4963. *oidSz = sizeof(attrExtensionRequestOid);
  4964. break;
  4965. default:
  4966. break;
  4967. }
  4968. break;
  4969. #endif
  4970. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4971. case oidSubjDirAttrType:
  4972. switch (id) {
  4973. case SDA_DOB_OID:
  4974. oid = extSubjDirAttrDobOid;
  4975. *oidSz = sizeof(extSubjDirAttrDobOid);
  4976. break;
  4977. case SDA_POB_OID:
  4978. oid = extSubjDirAttrPobOid;
  4979. *oidSz = sizeof(extSubjDirAttrPobOid);
  4980. break;
  4981. case SDA_GENDER_OID:
  4982. oid = extSubjDirAttrGenderOid;
  4983. *oidSz = sizeof(extSubjDirAttrGenderOid);
  4984. break;
  4985. case SDA_COC_OID:
  4986. oid = extSubjDirAttrCocOid;
  4987. *oidSz = sizeof(extSubjDirAttrCocOid);
  4988. break;
  4989. case SDA_COR_OID:
  4990. oid = extSubjDirAttrCorOid;
  4991. *oidSz = sizeof(extSubjDirAttrCorOid);
  4992. break;
  4993. default:
  4994. break;
  4995. }
  4996. break;
  4997. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  4998. case oidIgnoreType:
  4999. default:
  5000. break;
  5001. }
  5002. return oid;
  5003. }
  5004. #ifdef HAVE_ECC
  5005. /* Check the OID id is for a known elliptic curve.
  5006. *
  5007. * @param [in] oid OID id.
  5008. * @return ECC set id on success.
  5009. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  5010. */
  5011. static int CheckCurve(word32 oid)
  5012. {
  5013. int ret;
  5014. word32 oidSz;
  5015. /* Lookup OID id. */
  5016. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  5017. /* Check for error or zero length OID size (can't get OID for encoding). */
  5018. if ((ret < 0) || (oidSz == 0)) {
  5019. WOLFSSL_MSG("CheckCurve not found");
  5020. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  5021. ret = ECC_CURVE_OID_E;
  5022. }
  5023. /* Return ECC set id or error code. */
  5024. return ret;
  5025. }
  5026. #endif
  5027. #ifdef HAVE_OID_ENCODING
  5028. /* Encode dotted form of OID into byte array version.
  5029. *
  5030. * @param [in] in Dotted form of OID.
  5031. * @param [in] inSz Count of numbers in dotted form.
  5032. * @param [in] out Buffer to hold OID.
  5033. * @param [in, out] outSz On in, size of buffer.
  5034. * On out, number of bytes in buffer.
  5035. * @return 0 on success
  5036. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5037. * @return BUFFER_E when buffer too small.
  5038. */
  5039. int wc_EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5040. {
  5041. return EncodeObjectId(in, inSz, out, outSz);
  5042. }
  5043. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5044. {
  5045. int i, x, len;
  5046. word32 d, t;
  5047. /* check args */
  5048. if (in == NULL || outSz == NULL || inSz <= 0) {
  5049. return BAD_FUNC_ARG;
  5050. }
  5051. /* compute length of encoded OID */
  5052. d = (in[0] * 40) + in[1];
  5053. len = 0;
  5054. for (i = 1; i < (int)inSz; i++) {
  5055. x = 0;
  5056. t = d;
  5057. while (t) {
  5058. x++;
  5059. t >>= 1;
  5060. }
  5061. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5062. if (i < (int)inSz - 1) {
  5063. d = in[i + 1];
  5064. }
  5065. }
  5066. if (out) {
  5067. /* verify length */
  5068. if ((int)*outSz < len) {
  5069. return BUFFER_E; /* buffer provided is not large enough */
  5070. }
  5071. /* calc first byte */
  5072. d = (in[0] * 40) + in[1];
  5073. /* encode bytes */
  5074. x = 0;
  5075. for (i = 1; i < (int)inSz; i++) {
  5076. if (d) {
  5077. int y = x, z;
  5078. byte mask = 0;
  5079. while (d) {
  5080. out[x++] = (byte)((d & 0x7F) | mask);
  5081. d >>= 7;
  5082. mask |= 0x80; /* upper bit is set on all but the last byte */
  5083. }
  5084. /* now swap bytes y...x-1 */
  5085. z = x - 1;
  5086. while (y < z) {
  5087. mask = out[y];
  5088. out[y] = out[z];
  5089. out[z] = mask;
  5090. ++y;
  5091. --z;
  5092. }
  5093. }
  5094. else {
  5095. out[x++] = 0x00; /* zero value */
  5096. }
  5097. /* next word */
  5098. if (i < (int)inSz - 1) {
  5099. d = in[i + 1];
  5100. }
  5101. }
  5102. }
  5103. /* return length */
  5104. *outSz = len;
  5105. return 0;
  5106. }
  5107. #endif /* HAVE_OID_ENCODING */
  5108. #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT) || \
  5109. defined(OPENSSL_ALL)
  5110. /* Encode dotted form of OID into byte array version.
  5111. *
  5112. * @param [in] in Byte array containing OID.
  5113. * @param [in] inSz Size of OID in bytes.
  5114. * @param [in] out Array to hold dotted form of OID.
  5115. * @param [in, out] outSz On in, number of elements in array.
  5116. * On out, count of numbers in dotted form.
  5117. * @return 0 on success
  5118. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5119. * @return BUFFER_E when dotted form buffer too small.
  5120. */
  5121. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5122. {
  5123. int x = 0, y = 0;
  5124. word32 t = 0;
  5125. /* check args */
  5126. if (in == NULL || outSz == NULL) {
  5127. return BAD_FUNC_ARG;
  5128. }
  5129. /* decode bytes */
  5130. while (inSz--) {
  5131. t = (t << 7) | (in[x] & 0x7F);
  5132. if (!(in[x] & 0x80)) {
  5133. if (y >= (int)*outSz) {
  5134. return BUFFER_E;
  5135. }
  5136. if (y == 0) {
  5137. out[0] = (word16)(t / 40);
  5138. out[1] = (word16)(t % 40);
  5139. y = 2;
  5140. }
  5141. else {
  5142. out[y++] = (word16)t;
  5143. }
  5144. t = 0; /* reset tmp */
  5145. }
  5146. x++;
  5147. }
  5148. /* return length */
  5149. *outSz = (word32)y;
  5150. return 0;
  5151. }
  5152. #endif /* HAVE_OID_DECODING || WOLFSSL_ASN_PRINT || OPENSSL_ALL */
  5153. /* Decode the header of a BER/DER encoded OBJECT ID.
  5154. *
  5155. * @param [in] input Buffer holding DER/BER encoded data.
  5156. * @param [in, out] inOutIdx On in, starting index of header.
  5157. * On out, end of parsed header.
  5158. * @param [out] len Number of bytes in the ASN.1 data.
  5159. * @param [in] maxIdx Length of data in buffer.
  5160. * @return 0 on success.
  5161. * @return BUFFER_E when there is not enough data to parse.
  5162. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5163. */
  5164. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5165. {
  5166. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5167. if (ret > 0) {
  5168. /* Only return 0 on success. */
  5169. ret = 0;
  5170. }
  5171. return ret;
  5172. }
  5173. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5174. *
  5175. * When output is NULL, calculate the header length only.
  5176. *
  5177. * @param [in] len Length of OBJECT ID data in bytes.
  5178. * @param [out] output Buffer to write into.
  5179. * @return Number of bytes added to the buffer.
  5180. */
  5181. int SetObjectId(int len, byte* output)
  5182. {
  5183. int idx = 0;
  5184. if (output) {
  5185. /* Write out tag. */
  5186. output[idx] = ASN_OBJECT_ID;
  5187. }
  5188. /* Skip tag. */
  5189. idx += ASN_TAG_SZ;
  5190. /* Encode length - passing NULL for output will not encode. */
  5191. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  5192. /* Return index after header. */
  5193. return idx;
  5194. }
  5195. #ifdef ASN_DUMP_OID
  5196. /* Dump the OID information.
  5197. *
  5198. * Decode the OID too if function available.
  5199. *
  5200. * @param [in] oidData OID data from buffer.
  5201. * @param [in] oidSz Size of OID data in buffer.
  5202. * @param [in] oid OID id.
  5203. * @param [in] oidType Type of OID.
  5204. * @return 0 on success.
  5205. * @return BUFFER_E when not enough bytes for proper decode.
  5206. * (HAVE_OID_DECODING)
  5207. */
  5208. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5209. word32 oidType)
  5210. {
  5211. int ret = 0;
  5212. word32 i;
  5213. /* support for dumping OID information */
  5214. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5215. /* Dump bytes in decimal. */
  5216. for (i = 0; i < oidSz; i++) {
  5217. printf("%d, ", oidData[i]);
  5218. }
  5219. printf("\n");
  5220. /* Dump bytes in hexadecimal. */
  5221. for (i = 0; i < oidSz; i++) {
  5222. printf("%02x, ", oidData[i]);
  5223. }
  5224. printf("\n");
  5225. #ifdef HAVE_OID_DECODING
  5226. {
  5227. word16 decOid[MAX_OID_SZ];
  5228. word32 decOidSz = sizeof(decOid);
  5229. /* Decode the OID into dotted form. */
  5230. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5231. if (ret == 0) {
  5232. printf(" Decoded (Sz %d): ", decOidSz);
  5233. for (i=0; i<decOidSz; i++) {
  5234. printf("%d.", decOid[i]);
  5235. }
  5236. printf("\n");
  5237. }
  5238. else {
  5239. printf("DecodeObjectId failed: %d\n", ret);
  5240. }
  5241. }
  5242. #endif /* HAVE_OID_DECODING */
  5243. return ret;
  5244. }
  5245. #endif /* ASN_DUMP_OID */
  5246. /* Get the OID data and verify it is of the type specified when compiled in.
  5247. *
  5248. * @param [in] input Buffer holding OID.
  5249. * @param [in, out] inOutIdx On in, starting index of OID.
  5250. * On out, end of parsed OID.
  5251. * @param [out] oid OID id.
  5252. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5253. * not compile in check.
  5254. * @param [in] length Length of OID data in buffer.
  5255. * @return 0 on success.
  5256. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5257. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5258. * HAVE_OID_DECODING)
  5259. */
  5260. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5261. word32 oidType, int length)
  5262. {
  5263. int ret = 0;
  5264. word32 idx = *inOutIdx;
  5265. #ifndef NO_VERIFY_OID
  5266. word32 actualOidSz;
  5267. const byte* actualOid;
  5268. const byte* checkOid = NULL;
  5269. word32 checkOidSz;
  5270. #endif /* NO_VERIFY_OID */
  5271. #ifdef HAVE_PQC
  5272. word32 found_collision = 0;
  5273. #endif
  5274. (void)oidType;
  5275. *oid = 0;
  5276. #ifndef NO_VERIFY_OID
  5277. /* Keep references to OID data and length for check. */
  5278. actualOid = &input[idx];
  5279. actualOidSz = (word32)length;
  5280. #endif /* NO_VERIFY_OID */
  5281. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS) && defined(HAVE_SPHINCS)
  5282. /* Since we are summing it up, there could be collisions...and indeed there
  5283. * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
  5284. *
  5285. * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
  5286. * 283 instead of 281; 282 is taken.
  5287. *
  5288. * These hacks will hopefully disappear when new standardized OIDs appear.
  5289. */
  5290. if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
  5291. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5292. found_collision = SPHINCS_FAST_LEVEL3k;
  5293. }
  5294. #endif /* HAVE_PQC */
  5295. /* Sum it up for now. */
  5296. while (length--) {
  5297. /* odd HC08 compiler behavior here when input[idx++] */
  5298. *oid += (word32)input[idx];
  5299. idx++;
  5300. }
  5301. #ifdef HAVE_PQC
  5302. if (found_collision) {
  5303. *oid = found_collision;
  5304. }
  5305. #endif /* HAVE_PQC */
  5306. /* Return the index after the OID data. */
  5307. *inOutIdx = idx;
  5308. #ifndef NO_VERIFY_OID
  5309. /* 'Ignore' type means we don't care which OID it is. */
  5310. if (oidType != oidIgnoreType) {
  5311. /* Get the OID data for the id-type. */
  5312. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5313. #if defined(WOLFSSL_FPKI)
  5314. /* Handle OID sum collision of
  5315. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5316. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5317. */
  5318. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5319. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5320. (XMEMCMP(actualOid, blkAes256CbcOid,
  5321. sizeof(blkAes256CbcOid)) == 0)) {
  5322. checkOid = blkAes256CbcOid;
  5323. checkOidSz = sizeof(blkAes256CbcOid);
  5324. }
  5325. #endif /* HAVE_AES_CBC */
  5326. #endif /* WOLFSSL_FPKI */
  5327. #ifdef ASN_DUMP_OID
  5328. /* Dump out the data for debug. */
  5329. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5330. #endif
  5331. /* TODO: Want to fail when checkOid is NULL.
  5332. * Can't as too many situations where unknown OID is to be
  5333. * supported. Extra parameter for must not be NULL?
  5334. */
  5335. /* Check that the OID data matches what we found for the OID id. */
  5336. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5337. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5338. WOLFSSL_MSG("OID Check Failed");
  5339. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5340. ret = ASN_UNKNOWN_OID_E;
  5341. }
  5342. }
  5343. #endif /* NO_VERIFY_OID */
  5344. return ret;
  5345. }
  5346. #ifdef WOLFSSL_ASN_TEMPLATE
  5347. /* ASN.1 template for an OBJECT_ID. */
  5348. static const ASNItem objectIdASN[] = {
  5349. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5350. };
  5351. enum {
  5352. OBJECTIDASN_IDX_OID = 0
  5353. };
  5354. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5355. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5356. #endif
  5357. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5358. *
  5359. * @param [in] input Buffer holding BER encoded data.
  5360. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5361. * On out, start of ASN.1 item after OBJECT_ID.
  5362. * @param [out] oid Id of OID in OBJECT_ID data.
  5363. * @param [in] oidType Type of OID to expect.
  5364. * @param [in] maxIdx Maximum index of data in buffer.
  5365. * @return 0 on success.
  5366. * @return ASN_PARSE_E when encoding is invalid.
  5367. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5368. */
  5369. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5370. word32 oidType, word32 maxIdx)
  5371. {
  5372. #ifndef WOLFSSL_ASN_TEMPLATE
  5373. int ret, length;
  5374. WOLFSSL_ENTER("GetObjectId");
  5375. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5376. if (ret != 0)
  5377. return ret;
  5378. return GetOID(input, inOutIdx, oid, oidType, length);
  5379. #else
  5380. ASNGetData dataASN[objectIdASN_Length];
  5381. int ret;
  5382. WOLFSSL_ENTER("GetObjectId");
  5383. /* Clear dynamic data and set OID type expected. */
  5384. XMEMSET(dataASN, 0, sizeof(dataASN));
  5385. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5386. /* Decode OBJECT_ID. */
  5387. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5388. inOutIdx, maxIdx);
  5389. if (ret == 0) {
  5390. /* Return the id/sum. */
  5391. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5392. }
  5393. return ret;
  5394. #endif /* WOLFSSL_ASN_TEMPLATE */
  5395. }
  5396. #ifndef WOLFSSL_ASN_TEMPLATE
  5397. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5398. {
  5399. word32 idx = *inOutIdx;
  5400. int length;
  5401. int ret;
  5402. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5403. if (ret != 0)
  5404. return ret;
  5405. idx += (word32)length;
  5406. *inOutIdx = idx;
  5407. return 0;
  5408. }
  5409. #endif
  5410. #ifdef WOLFSSL_ASN_TEMPLATE
  5411. /* ASN.1 template for an algorithm identifier. */
  5412. static const ASNItem algoIdASN[] = {
  5413. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5414. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5415. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5416. };
  5417. enum {
  5418. ALGOIDASN_IDX_SEQ = 0,
  5419. ALGOIDASN_IDX_OID,
  5420. ALGOIDASN_IDX_NULL
  5421. };
  5422. /* Number of items in ASN.1 template for an algorithm identifier. */
  5423. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5424. #endif
  5425. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5426. *
  5427. * NULL tag is skipped if present.
  5428. *
  5429. * @param [in] input Buffer holding BER encoded data.
  5430. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5431. * On out, start of ASN.1 item after algorithm id.
  5432. * @param [out] oid Id of OID in algorithm identifier data.
  5433. * @param [in] oidType Type of OID to expect.
  5434. * @param [in] maxIdx Maximum index of data in buffer.
  5435. * @return 0 on success.
  5436. * @return ASN_PARSE_E when encoding is invalid.
  5437. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5438. */
  5439. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5440. word32 oidType, word32 maxIdx)
  5441. {
  5442. #ifndef WOLFSSL_ASN_TEMPLATE
  5443. int length;
  5444. word32 idx = *inOutIdx;
  5445. int ret;
  5446. *oid = 0;
  5447. WOLFSSL_ENTER("GetAlgoId");
  5448. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5449. return ASN_PARSE_E;
  5450. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5451. return ASN_OBJECT_ID_E;
  5452. /* could have NULL tag and 0 terminator, but may not */
  5453. if (idx < maxIdx) {
  5454. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5455. byte tag;
  5456. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5457. if (tag == ASN_TAG_NULL) {
  5458. ret = GetASNNull(input, &idx, maxIdx);
  5459. if (ret != 0)
  5460. return ret;
  5461. }
  5462. }
  5463. }
  5464. *inOutIdx = idx;
  5465. return 0;
  5466. #else
  5467. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5468. int ret = 0;
  5469. WOLFSSL_ENTER("GetAlgoId");
  5470. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5471. if (ret == 0) {
  5472. /* Set OID type expected. */
  5473. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5474. /* Decode the algorithm identifier. */
  5475. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5476. inOutIdx, maxIdx);
  5477. }
  5478. if (ret == 0) {
  5479. /* Return the OID id/sum. */
  5480. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5481. }
  5482. FREE_ASNGETDATA(dataASN, NULL);
  5483. return ret;
  5484. #endif /* WOLFSSL_ASN_TEMPLATE */
  5485. }
  5486. #ifndef NO_RSA
  5487. #ifdef WC_RSA_PSS
  5488. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5489. /* Convert a hash OID to a hash type.
  5490. *
  5491. * @param [in] oid Hash OID.
  5492. * @param [out] type Hash type.
  5493. * @return 0 on success.
  5494. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5495. */
  5496. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5497. {
  5498. int ret = 0;
  5499. switch (oid) {
  5500. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5501. #ifdef WOLFSSL_SHA224
  5502. case SHA224h:
  5503. *type = WC_HASH_TYPE_SHA224;
  5504. break;
  5505. #endif
  5506. #ifndef NO_SHA256
  5507. case SHA256h:
  5508. *type = WC_HASH_TYPE_SHA256;
  5509. break;
  5510. #endif
  5511. #ifdef WOLFSSL_SHA384
  5512. case SHA384h:
  5513. *type = WC_HASH_TYPE_SHA384;
  5514. break;
  5515. #endif
  5516. #ifdef WOLFSSL_SHA512
  5517. case SHA512h:
  5518. *type = WC_HASH_TYPE_SHA512;
  5519. break;
  5520. /* TODO: SHA512_224h */
  5521. /* TODO: SHA512_256h */
  5522. #endif
  5523. default:
  5524. ret = ASN_PARSE_E;
  5525. break;
  5526. }
  5527. return ret;
  5528. }
  5529. /* Convert a hash OID to a MGF1 type.
  5530. *
  5531. * @param [in] oid Hash OID.
  5532. * @param [out] mgf MGF type.
  5533. * @return 0 on success.
  5534. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5535. */
  5536. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5537. {
  5538. int ret = 0;
  5539. switch (oid) {
  5540. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5541. #ifdef WOLFSSL_SHA224
  5542. case SHA224h:
  5543. *mgf = WC_MGF1SHA224;
  5544. break;
  5545. #endif
  5546. #ifndef NO_SHA256
  5547. case SHA256h:
  5548. *mgf = WC_MGF1SHA256;
  5549. break;
  5550. #endif
  5551. #ifdef WOLFSSL_SHA384
  5552. case SHA384h:
  5553. *mgf = WC_MGF1SHA384;
  5554. break;
  5555. #endif
  5556. #ifdef WOLFSSL_SHA512
  5557. case SHA512h:
  5558. *mgf = WC_MGF1SHA512;
  5559. break;
  5560. /* TODO: SHA512_224h */
  5561. /* TODO: SHA512_256h */
  5562. #endif
  5563. default:
  5564. ret = ASN_PARSE_E;
  5565. break;
  5566. }
  5567. return ret;
  5568. }
  5569. #ifndef NO_CERTS
  5570. /* Convert a hash OID to a fake signature OID.
  5571. *
  5572. * @param [in] oid Hash OID.
  5573. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5574. * @return 0 on success.
  5575. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5576. */
  5577. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5578. {
  5579. int ret = 0;
  5580. switch (oid) {
  5581. #ifndef NO_SHA
  5582. case WC_HASH_TYPE_SHA:
  5583. *sigOid = CTC_SHAwRSA;
  5584. break;
  5585. #endif
  5586. #ifdef WOLFSSL_SHA224
  5587. case WC_HASH_TYPE_SHA224:
  5588. *sigOid = CTC_SHA224wRSA;
  5589. break;
  5590. #endif
  5591. #ifndef NO_SHA256
  5592. case WC_HASH_TYPE_SHA256:
  5593. *sigOid = CTC_SHA256wRSA;
  5594. break;
  5595. #endif
  5596. #ifdef WOLFSSL_SHA384
  5597. case WC_HASH_TYPE_SHA384:
  5598. *sigOid = CTC_SHA384wRSA;
  5599. break;
  5600. #endif
  5601. #ifdef WOLFSSL_SHA512
  5602. case WC_HASH_TYPE_SHA512:
  5603. *sigOid = CTC_SHA512wRSA;
  5604. break;
  5605. #endif
  5606. /* TODO: SHA512_224h */
  5607. /* TODO: SHA512_256h */
  5608. /* Not supported by HashForSignature() */
  5609. default:
  5610. ret = ASN_PARSE_E;
  5611. break;
  5612. }
  5613. return ret;
  5614. }
  5615. #endif
  5616. #ifdef WOLFSSL_ASN_TEMPLATE
  5617. /* ASN tag for hashAlgorigthm. */
  5618. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5619. /* ASN tag for maskGenAlgorithm. */
  5620. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5621. /* ASN tag for saltLength. */
  5622. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5623. /* ASN tag for trailerField. */
  5624. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5625. /* ASN.1 template for RSA PSS parameters. */
  5626. static const ASNItem rsaPssParamsASN[] = {
  5627. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5628. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5629. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5630. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5631. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5632. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5633. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5634. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5635. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5636. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5637. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5638. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5639. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5640. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5641. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5642. };
  5643. enum {
  5644. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5645. RSAPSSPARAMSASN_IDX_HASH,
  5646. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5647. RSAPSSPARAMSASN_IDX_HASHOID,
  5648. RSAPSSPARAMSASN_IDX_HASHNULL,
  5649. RSAPSSPARAMSASN_IDX_MGF,
  5650. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5651. RSAPSSPARAMSASN_IDX_MGFOID,
  5652. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5653. RSAPSSPARAMSASN_IDX_MGFHOID,
  5654. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5655. RSAPSSPARAMSASN_IDX_SALTLEN,
  5656. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5657. RSAPSSPARAMSASN_IDX_TRAILER,
  5658. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5659. };
  5660. /* Number of items in ASN.1 template for an algorithm identifier. */
  5661. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5662. #else
  5663. /* ASN tag for hashAlgorigthm. */
  5664. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5665. /* ASN tag for maskGenAlgorithm. */
  5666. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5667. /* ASN tag for saltLength. */
  5668. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5669. /* ASN tag for trailerField. */
  5670. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5671. #endif
  5672. /* Decode the RSA PSS parameters.
  5673. *
  5674. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5675. * @param [in] sz Size of data in buffer in bytes.
  5676. * @param [out] hash Hash algorithm to use on message.
  5677. * @param [out] mgf MGF algorithm to use with PSS padding.
  5678. * @param [out] saltLen Length of salt in PSS padding.
  5679. * @return BAD_FUNC_ARG when the params is NULL.
  5680. * @return ASN_PARSE_E when the decoding fails.
  5681. * @return 0 on success.
  5682. */
  5683. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5684. enum wc_HashType* hash, int* mgf, int* saltLen)
  5685. {
  5686. #ifndef WOLFSSL_ASN_TEMPLATE
  5687. int ret = 0;
  5688. word32 idx = 0;
  5689. int len = 0;
  5690. word32 oid = 0;
  5691. byte tag;
  5692. int length;
  5693. if (params == NULL) {
  5694. ret = BAD_FUNC_ARG;
  5695. }
  5696. if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
  5697. ret = ASN_PARSE_E;
  5698. }
  5699. if (ret == 0) {
  5700. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5701. /* Hash algorithm to use on message. */
  5702. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5703. ret = ASN_PARSE_E;
  5704. }
  5705. if (ret == 0) {
  5706. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5707. ret = ASN_PARSE_E;
  5708. }
  5709. }
  5710. if (ret == 0) {
  5711. ret = RsaPssHashOidToType(oid, hash);
  5712. }
  5713. }
  5714. else {
  5715. /* Default hash algorithm. */
  5716. *hash = WC_HASH_TYPE_SHA;
  5717. }
  5718. }
  5719. if (ret == 0) {
  5720. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5721. /* MGF and hash algorithm to use with padding. */
  5722. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5723. ret = ASN_PARSE_E;
  5724. }
  5725. if (ret == 0) {
  5726. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5727. ret = ASN_PARSE_E;
  5728. }
  5729. }
  5730. if ((ret == 0) && (oid != MGF1_OID)) {
  5731. ret = ASN_PARSE_E;
  5732. }
  5733. if (ret == 0) {
  5734. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5735. if (ret == 0) {
  5736. ret = RsaPssHashOidToMgf1(oid, mgf);
  5737. }
  5738. }
  5739. }
  5740. else {
  5741. /* Default MGF/Hash algorithm. */
  5742. *mgf = WC_MGF1SHA1;
  5743. }
  5744. }
  5745. if (ret == 0) {
  5746. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5747. /* Salt length to use with padding. */
  5748. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5749. ret = ASN_PARSE_E;
  5750. }
  5751. if (ret == 0) {
  5752. ret = GetInteger16Bit(params, &idx, sz);
  5753. if (ret >= 0) {
  5754. *saltLen = ret;
  5755. ret = 0;
  5756. }
  5757. }
  5758. }
  5759. else {
  5760. /* Default salt length. */
  5761. *saltLen = 20;
  5762. }
  5763. }
  5764. if (ret == 0) {
  5765. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5766. /* Unused - trialerField. */
  5767. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5768. ret = ASN_PARSE_E;
  5769. }
  5770. if (ret == 0) {
  5771. ret = GetInteger16Bit(params, &idx, sz);
  5772. if (ret > 0) {
  5773. ret = 0;
  5774. }
  5775. }
  5776. }
  5777. }
  5778. if ((ret == 0) && (idx != sz)) {
  5779. ret = ASN_PARSE_E;
  5780. }
  5781. return ret;
  5782. #else
  5783. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5784. int ret = 0;
  5785. word16 sLen = 20;
  5786. if (params == NULL) {
  5787. ret = BAD_FUNC_ARG;
  5788. }
  5789. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5790. if (ret == 0) {
  5791. word32 inOutIdx = 0;
  5792. /* Default values. */
  5793. *hash = WC_HASH_TYPE_SHA;
  5794. *mgf = WC_MGF1SHA1;
  5795. /* Set OID type expected. */
  5796. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5797. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5798. /* Place the salt length into 16-bit var sLen. */
  5799. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5800. /* Decode the algorithm identifier. */
  5801. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5802. params, &inOutIdx, sz);
  5803. }
  5804. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5805. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5806. ret = RsaPssHashOidToType(oid, hash);
  5807. }
  5808. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5809. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5810. ret = RsaPssHashOidToMgf1(oid, mgf);
  5811. }
  5812. if (ret == 0) {
  5813. *saltLen = sLen;
  5814. }
  5815. FREE_ASNGETDATA(dataASN, NULL);
  5816. return ret;
  5817. #endif /* WOLFSSL_ASN_TEMPLATE */
  5818. }
  5819. #endif /* WC_RSA_PSS */
  5820. #ifndef HAVE_USER_RSA
  5821. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5822. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5823. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5824. /* Byte offset of numbers in RSA key. */
  5825. size_t rsaIntOffset[] = {
  5826. OFFSETOF(RsaKey, n),
  5827. OFFSETOF(RsaKey, e),
  5828. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5829. OFFSETOF(RsaKey, d),
  5830. OFFSETOF(RsaKey, p),
  5831. OFFSETOF(RsaKey, q),
  5832. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5833. OFFSETOF(RsaKey, dP),
  5834. OFFSETOF(RsaKey, dQ),
  5835. OFFSETOF(RsaKey, u)
  5836. #endif
  5837. #endif
  5838. };
  5839. /* Get a number from the RSA key based on an index.
  5840. *
  5841. * Order: { n, e, d, p, q, dP, dQ, u }
  5842. *
  5843. * Caller must ensure index is not invalid!
  5844. *
  5845. * @param [in] key RSA key object.
  5846. * @param [in] idx Index of number.
  5847. * @return A pointer to an mp_int when valid index.
  5848. * @return NULL when invalid index.
  5849. */
  5850. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5851. {
  5852. /* Cast key to byte array to and use offset to get to mp_int field. */
  5853. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5854. }
  5855. #endif
  5856. #ifdef WOLFSSL_ASN_TEMPLATE
  5857. /* ASN.1 template for an RSA private key.
  5858. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5859. */
  5860. static const ASNItem rsaKeyASN[] = {
  5861. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5862. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5863. /* Integers need to be in this specific order
  5864. * as asn code depends on this. */
  5865. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5866. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5867. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5868. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5869. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5870. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5871. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5872. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5873. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5874. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5875. * v2 - multiprime */
  5876. #endif
  5877. };
  5878. enum {
  5879. RSAKEYASN_IDX_SEQ = 0,
  5880. RSAKEYASN_IDX_VER,
  5881. /* Integers need to be in this specific order
  5882. * as asn code depends on this. */
  5883. RSAKEYASN_IDX_N,
  5884. RSAKEYASN_IDX_E,
  5885. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5886. RSAKEYASN_IDX_D,
  5887. RSAKEYASN_IDX_P,
  5888. RSAKEYASN_IDX_Q,
  5889. RSAKEYASN_IDX_DP,
  5890. RSAKEYASN_IDX_DQ,
  5891. RSAKEYASN_IDX_U,
  5892. #endif
  5893. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  5894. };
  5895. /* Number of items in ASN.1 template for an RSA private key. */
  5896. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5897. #endif
  5898. /* Decode RSA private key.
  5899. *
  5900. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5901. *
  5902. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5903. * being extracted.
  5904. *
  5905. * @param [in] input Buffer holding BER encoded data.
  5906. * @param [in, out] inOutIdx On in, start of RSA private key.
  5907. * On out, start of ASN.1 item after RSA private key.
  5908. * @param [in, out] key RSA key object. May be NULL.
  5909. * @param [out] keySz Size of key in bytes. May be NULL.
  5910. * @param [in] inSz Number of bytes in buffer.
  5911. * @return 0 on success.
  5912. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  5913. * @return BAD_FUNC_ARG when key and keySz are NULL.
  5914. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5915. * is invalid.
  5916. * @return BUFFER_E when data in buffer is too small.
  5917. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5918. * non-zero length.
  5919. * @return MP_INIT_E when the unable to initialize an mp_int.
  5920. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5921. */
  5922. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  5923. RsaKey* key, int* keySz, word32 inSz)
  5924. {
  5925. #ifndef WOLFSSL_ASN_TEMPLATE
  5926. int version, length;
  5927. word32 algId = 0;
  5928. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  5929. return BAD_FUNC_ARG;
  5930. }
  5931. /* if has pkcs8 header skip it */
  5932. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5933. /* ignore error, did not have pkcs8 header */
  5934. }
  5935. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5936. return ASN_PARSE_E;
  5937. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5938. return ASN_PARSE_E;
  5939. if (key == NULL) {
  5940. int i;
  5941. /* Modulus */
  5942. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  5943. return ASN_PARSE_E;
  5944. }
  5945. *inOutIdx += (word32)*keySz;
  5946. for (i = 1; i < RSA_INTS; i++) {
  5947. if (SkipInt(input, inOutIdx, inSz) < 0) {
  5948. return ASN_RSA_KEY_E;
  5949. }
  5950. }
  5951. }
  5952. else {
  5953. key->type = RSA_PRIVATE;
  5954. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5955. mp_memzero_add("Decode RSA key d", &key->d);
  5956. mp_memzero_add("Decode RSA key p", &key->p);
  5957. mp_memzero_add("Decode RSA key q", &key->q);
  5958. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5959. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5960. mp_memzero_add("Decode RSA key dP", &key->dP);
  5961. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  5962. mp_memzero_add("Decode RSA key u", &key->u);
  5963. #endif
  5964. #endif
  5965. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  5966. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  5967. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5968. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  5969. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  5970. GetInt(&key->q, input, inOutIdx, inSz) < 0
  5971. #else
  5972. SkipInt(input, inOutIdx, inSz) < 0 ||
  5973. SkipInt(input, inOutIdx, inSz) < 0 ||
  5974. SkipInt(input, inOutIdx, inSz) < 0
  5975. #endif
  5976. ) {
  5977. return ASN_RSA_KEY_E;
  5978. }
  5979. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  5980. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5981. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  5982. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  5983. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5984. #else
  5985. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  5986. SkipInt(input, inOutIdx, inSz) < 0 ||
  5987. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5988. #endif
  5989. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  5990. if (wc_InitRsaHw(key) != 0) {
  5991. return BAD_STATE_E;
  5992. }
  5993. #endif
  5994. }
  5995. return 0;
  5996. #else
  5997. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5998. int ret = 0;
  5999. byte version = (byte)-1;
  6000. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6001. word32 algId = 0;
  6002. #endif
  6003. void* heap = NULL;
  6004. /* Check validity of parameters. */
  6005. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  6006. (keySz == NULL))) {
  6007. ret = BAD_FUNC_ARG;
  6008. }
  6009. if ((ret == 0) && (key != NULL)) {
  6010. heap = key->heap;
  6011. }
  6012. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6013. if (ret == 0) {
  6014. /* if has pkcs8 header skip it */
  6015. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  6016. /* ignore error, did not have pkcs8 header */
  6017. }
  6018. }
  6019. #endif
  6020. (void)heap;
  6021. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  6022. if (ret == 0) {
  6023. /* Register variable to hold version field. */
  6024. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  6025. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  6026. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6027. #define RSA_ASN_INTS RSA_PUB_INTS
  6028. /* Not extracting all data from BER encoding. */
  6029. #define RSA_ASN_COMPLETE 0
  6030. #else
  6031. #define RSA_ASN_INTS RSA_INTS
  6032. /* Extracting all data from BER encoding. */
  6033. #define RSA_ASN_COMPLETE 1
  6034. #endif
  6035. if (key != NULL) {
  6036. int i;
  6037. /* Extract all public fields. */
  6038. for (i = 0; i < RSA_ASN_INTS; i++) {
  6039. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  6040. GetRsaInt(key, i));
  6041. }
  6042. }
  6043. /* Parse BER encoding for RSA private key. */
  6044. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  6045. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  6046. }
  6047. /* Check version: 0 - two prime, 1 - multi-prime
  6048. * Multi-prime has optional sequence after coefficient for extra primes.
  6049. * If extra primes, parsing will fail as not all the buffer was used.
  6050. */
  6051. if ((ret == 0) && (version > PKCS1v1)) {
  6052. ret = ASN_PARSE_E;
  6053. }
  6054. if ((ret == 0) && (key != NULL)) {
  6055. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6056. /* RSA key object has all private key values. */
  6057. key->type = RSA_PRIVATE;
  6058. #else
  6059. /* RSA key object has all public key values. */
  6060. key->type = RSA_PUBLIC;
  6061. #endif
  6062. #ifdef WOLFSSL_XILINX_CRYPT
  6063. if (wc_InitRsaHw(key) != 0)
  6064. ret = BAD_STATE_E;
  6065. #endif
  6066. }
  6067. else if (ret == 0) {
  6068. /* Not filling in key but do want key size. */
  6069. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6070. /* Check whether first byte of data is 0x00 and drop it. */
  6071. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6072. (*keySz)--;
  6073. }
  6074. }
  6075. FREE_ASNGETDATA(dataASN, heap);
  6076. return ret;
  6077. #endif /* WOLFSSL_ASN_TEMPLATE */
  6078. }
  6079. /* Decode RSA private key.
  6080. *
  6081. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6082. *
  6083. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6084. * being extracted.
  6085. *
  6086. * @param [in] input Buffer holding BER encoded data.
  6087. * @param [in, out] inOutIdx On in, start of RSA private key.
  6088. * On out, start of ASN.1 item after RSA private key.
  6089. * @param [in, out] key RSA key object.
  6090. * @param [in] inSz Number of bytes in buffer.
  6091. * @return 0 on success.
  6092. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6093. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6094. * is invalid.
  6095. * @return BUFFER_E when data in buffer is too small.
  6096. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6097. * non-zero length.
  6098. * @return MP_INIT_E when the unable to initialize an mp_int.
  6099. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6100. */
  6101. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6102. word32 inSz)
  6103. {
  6104. if (key == NULL) {
  6105. return BAD_FUNC_ARG;
  6106. }
  6107. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6108. }
  6109. /* Valdidate RSA private key ASN.1 encoding.
  6110. *
  6111. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6112. *
  6113. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6114. * being extracted.
  6115. *
  6116. * @param [in] input Buffer holding BER encoded data.
  6117. * @param [in, out] inOutIdx On in, start of RSA private key.
  6118. * On out, start of ASN.1 item after RSA private key.
  6119. * @param [in] inSz Number of bytes in buffer.
  6120. * @return 0 on success.
  6121. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6122. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6123. * is invalid.
  6124. * @return BUFFER_E when data in buffer is too small.
  6125. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6126. * non-zero length.
  6127. * @return MP_INIT_E when the unable to initialize an mp_int.
  6128. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6129. */
  6130. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6131. word32 inSz)
  6132. {
  6133. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6134. }
  6135. #endif /* HAVE_USER_RSA */
  6136. #endif /* NO_RSA */
  6137. #ifdef WOLFSSL_ASN_TEMPLATE
  6138. /* ASN.1 template for a PKCS #8 key.
  6139. * Ignoring optional attributes and public key.
  6140. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6141. */
  6142. static const ASNItem pkcs8KeyASN[] = {
  6143. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6144. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6145. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6146. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6147. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6148. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6149. #ifdef WC_RSA_PSS
  6150. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6151. #endif
  6152. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6153. /* attributes [0] Attributes OPTIONAL */
  6154. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6155. };
  6156. enum {
  6157. PKCS8KEYASN_IDX_SEQ = 0,
  6158. PKCS8KEYASN_IDX_VER,
  6159. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6160. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6161. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6162. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6163. #ifdef WC_RSA_PSS
  6164. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6165. #endif
  6166. PKCS8KEYASN_IDX_PKEY_DATA,
  6167. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6168. };
  6169. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6170. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6171. #endif
  6172. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6173. *
  6174. * @param [in] input Buffer holding BER data.
  6175. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6176. * On out, start of encoded key.
  6177. * @param [in] sz Size of data in buffer.
  6178. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6179. * @return Length of key data on success.
  6180. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6181. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6182. * is invalid.
  6183. * @return BUFFER_E when data in buffer is too small.
  6184. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6185. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6186. * non-zero length.
  6187. */
  6188. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6189. word32* algId)
  6190. {
  6191. #ifndef WOLFSSL_ASN_TEMPLATE
  6192. word32 idx;
  6193. int version, length;
  6194. int ret;
  6195. byte tag;
  6196. if (input == NULL || inOutIdx == NULL)
  6197. return BAD_FUNC_ARG;
  6198. idx = *inOutIdx;
  6199. if (GetSequence(input, &idx, &length, sz) < 0)
  6200. return ASN_PARSE_E;
  6201. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6202. return ASN_PARSE_E;
  6203. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6204. return ASN_PARSE_E;
  6205. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6206. return ASN_PARSE_E;
  6207. idx = idx - 1; /* reset idx after finding tag */
  6208. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6209. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6210. word32 seqIdx = idx;
  6211. int seqLen;
  6212. /* Not set when -1. */
  6213. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6214. int mgf = -1;
  6215. int saltLen = 0;
  6216. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6217. return ASN_PARSE_E;
  6218. }
  6219. /* Get the private key parameters. */
  6220. ret = DecodeRsaPssParams(input + seqIdx,
  6221. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6222. if (ret != 0) {
  6223. return ASN_PARSE_E;
  6224. }
  6225. /* TODO: store parameters so that usage can be checked. */
  6226. idx += seqLen;
  6227. }
  6228. #endif /* WC_RSA_PSS && !NO_RSA */
  6229. if (tag == ASN_OBJECT_ID) {
  6230. if (SkipObjectId(input, &idx, sz) < 0)
  6231. return ASN_PARSE_E;
  6232. }
  6233. ret = GetOctetString(input, &idx, &length, sz);
  6234. if (ret < 0) {
  6235. if (ret == BUFFER_E)
  6236. return ASN_PARSE_E;
  6237. /* Some private keys don't expect an octet string */
  6238. WOLFSSL_MSG("Couldn't find Octet string");
  6239. }
  6240. *inOutIdx = idx;
  6241. return length;
  6242. #else
  6243. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6244. int ret = 0;
  6245. word32 oid = 9;
  6246. byte version;
  6247. word32 idx;
  6248. /* Check validity of parameters. */
  6249. if (input == NULL || inOutIdx == NULL) {
  6250. return BAD_FUNC_ARG;
  6251. }
  6252. idx = *inOutIdx;
  6253. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6254. if (ret == 0) {
  6255. /* Get version, check key type and curve type. */
  6256. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6257. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6258. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6259. /* Parse data. */
  6260. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6261. &idx, sz);
  6262. }
  6263. if (ret == 0) {
  6264. /* Key type OID. */
  6265. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6266. /* Version 1 includes an optional public key.
  6267. * If public key is included then the parsing will fail as it did not
  6268. * use all the data.
  6269. */
  6270. if (version > PKCS8v1) {
  6271. ret = ASN_PARSE_E;
  6272. }
  6273. }
  6274. if (ret == 0) {
  6275. switch (oid) {
  6276. #ifndef NO_RSA
  6277. case RSAk:
  6278. /* Must have NULL item but not OBJECT_ID item. */
  6279. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6280. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6281. ret = ASN_PARSE_E;
  6282. }
  6283. break;
  6284. #ifdef WC_RSA_PSS
  6285. case RSAPSSk:
  6286. /* Must not have NULL item. */
  6287. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6288. ret = ASN_PARSE_E;
  6289. }
  6290. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6291. enum wc_HashType hash;
  6292. int mgf;
  6293. int saltLen;
  6294. const byte* params = GetASNItem_Addr(
  6295. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6296. word32 paramsSz = GetASNItem_Length(
  6297. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6298. /* Validate the private key parameters. */
  6299. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6300. &saltLen);
  6301. if (ret != 0) {
  6302. return ASN_PARSE_E;
  6303. }
  6304. /* TODO: store parameters so that usage can be checked. */
  6305. }
  6306. break;
  6307. #endif
  6308. #endif
  6309. #ifdef HAVE_ECC
  6310. case ECDSAk:
  6311. /* Must not have NULL item. */
  6312. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6313. ret = ASN_PARSE_E;
  6314. }
  6315. break;
  6316. #endif
  6317. #ifdef HAVE_ED25519
  6318. case ED25519k:
  6319. /* Neither NULL item nor OBJECT_ID item allowed. */
  6320. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6321. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6322. ret = ASN_PARSE_E;
  6323. }
  6324. break;
  6325. #endif
  6326. #ifdef HAVE_CURVE25519
  6327. case X25519k:
  6328. /* Neither NULL item nor OBJECT_ID item allowed. */
  6329. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6330. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6331. ret = ASN_PARSE_E;
  6332. }
  6333. break;
  6334. #endif
  6335. #ifdef HAVE_ED448
  6336. case ED448k:
  6337. /* Neither NULL item nor OBJECT_ID item allowed. */
  6338. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6339. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6340. ret = ASN_PARSE_E;
  6341. }
  6342. break;
  6343. #endif
  6344. #ifdef HAVE_CURVE448
  6345. case X448k:
  6346. /* Neither NULL item nor OBJECT_ID item allowed. */
  6347. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6348. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6349. ret = ASN_PARSE_E;
  6350. }
  6351. break;
  6352. #endif
  6353. /* DSAk not supported. */
  6354. /* Falcon, Dilithium and Sphincs not supported. */
  6355. /* Ignore OID lookup failures. */
  6356. default:
  6357. break;
  6358. }
  6359. }
  6360. if (ret == 0) {
  6361. /* Return algorithm id of internal key. */
  6362. *algId = oid;
  6363. /* Return index to start of internal key. */
  6364. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6365. /* Return value is length of internal key. */
  6366. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6367. }
  6368. FREE_ASNGETDATA(dataASN, NULL);
  6369. return ret;
  6370. #endif
  6371. }
  6372. /* TODO: test case */
  6373. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6374. {
  6375. word32 oid;
  6376. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6377. }
  6378. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6379. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6380. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6381. {
  6382. word32 inOutIdx = 0;
  6383. int length;
  6384. if (input == NULL)
  6385. return BAD_FUNC_ARG;
  6386. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6387. if (length < 0)
  6388. return length;
  6389. if ((word32)length + inOutIdx > sz)
  6390. return BUFFER_E;
  6391. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6392. return length;
  6393. }
  6394. int ToTraditional(byte* input, word32 sz)
  6395. {
  6396. word32 oid;
  6397. return ToTraditional_ex(input, sz, &oid);
  6398. }
  6399. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6400. #if defined(HAVE_PKCS8)
  6401. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6402. {
  6403. int length;
  6404. word32 algId;
  6405. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6406. return BAD_FUNC_ARG;
  6407. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6408. return length;
  6409. }
  6410. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6411. int algoID, const byte* curveOID, word32 oidSz)
  6412. {
  6413. #ifndef WOLFSSL_ASN_TEMPLATE
  6414. word32 keyIdx = 0;
  6415. word32 tmpSz = 0;
  6416. word32 sz;
  6417. word32 tmpAlgId = 0;
  6418. /* If out is NULL then return the max size needed
  6419. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6420. if (out == NULL && outSz != NULL) {
  6421. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6422. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6423. if (curveOID != NULL)
  6424. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6425. WOLFSSL_MSG("Checking size of PKCS8");
  6426. return LENGTH_ONLY_E;
  6427. }
  6428. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6429. if (key == NULL || out == NULL || outSz == NULL) {
  6430. return BAD_FUNC_ARG;
  6431. }
  6432. /* check the buffer has enough room for largest possible size */
  6433. if (curveOID != NULL) {
  6434. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6435. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6436. return BUFFER_E;
  6437. }
  6438. else {
  6439. oidSz = 0; /* with no curveOID oid size must be 0 */
  6440. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6441. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6442. return BUFFER_E;
  6443. }
  6444. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6445. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6446. (void)tmpAlgId;
  6447. return ASN_PARSE_E;
  6448. }
  6449. /* PrivateKeyInfo ::= SEQUENCE */
  6450. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6451. /* version Version
  6452. * no header information just INTEGER */
  6453. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6454. tmpSz += sz; keyIdx += sz;
  6455. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6456. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6457. if (curveOID != NULL && oidSz > 0) {
  6458. byte buf[MAX_LENGTH_SZ];
  6459. sz = SetLength(oidSz, buf);
  6460. sz += 1; /* plus one for ASN object id */
  6461. }
  6462. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6463. tmpSz += sz; keyIdx += sz;
  6464. /* privateKey PrivateKey *
  6465. * pkcs8 ecc uses slightly different format. Places curve oid in
  6466. * buffer */
  6467. if (curveOID != NULL && oidSz > 0) {
  6468. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6469. keyIdx += sz; tmpSz += sz;
  6470. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6471. keyIdx += oidSz; tmpSz += oidSz;
  6472. }
  6473. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6474. keyIdx += sz; tmpSz += sz;
  6475. XMEMCPY(out + keyIdx, key, keySz);
  6476. tmpSz += keySz;
  6477. /* attributes optional
  6478. * No attributes currently added */
  6479. /* rewind and add sequence */
  6480. sz = SetSequence(tmpSz, out);
  6481. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6482. *outSz = tmpSz + sz;
  6483. return (int)(tmpSz + sz);
  6484. #else
  6485. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6486. int sz;
  6487. int ret = 0;
  6488. word32 keyIdx = 0;
  6489. word32 tmpAlgId = 0;
  6490. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6491. /* Check validity of parameters. */
  6492. if (out == NULL && outSz != NULL) {
  6493. }
  6494. else if (key == NULL || out == NULL || outSz == NULL) {
  6495. ret = BAD_FUNC_ARG;
  6496. }
  6497. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6498. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6499. (void)tmpAlgId;
  6500. ret = ASN_PARSE_E;
  6501. }
  6502. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6503. if (ret == 0) {
  6504. /* Only support default PKCS #8 format - v0. */
  6505. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6506. /* Set key OID that corresponds to key data. */
  6507. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6508. oidKeyType);
  6509. if (curveOID != NULL && oidSz > 0) {
  6510. /* ECC key and curveOID set to write. */
  6511. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE],
  6512. curveOID, oidSz);
  6513. }
  6514. else {
  6515. /* EC curve OID to encode. */
  6516. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6517. }
  6518. /* Only RSA keys have NULL tagged item after OID. */
  6519. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6520. #ifdef WC_RSA_PSS
  6521. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6522. #endif
  6523. /* Set key data to encode. */
  6524. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6525. /* Get the size of the DER encoding. */
  6526. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6527. }
  6528. if (ret == 0) {
  6529. /* Always return the calculated size. */
  6530. *outSz = (word32)sz;
  6531. }
  6532. /* Check for buffer to encoded into. */
  6533. if ((ret == 0) && (out == NULL)) {
  6534. WOLFSSL_MSG("Checking size of PKCS8");
  6535. ret = LENGTH_ONLY_E;
  6536. }
  6537. if (ret == 0) {
  6538. /* Encode PKCS #8 key into buffer. */
  6539. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6540. ret = sz;
  6541. }
  6542. FREE_ASNSETDATA(dataASN, NULL);
  6543. return ret;
  6544. #endif /* WOLFSSL_ASN_TEMPLATE */
  6545. }
  6546. #endif /* HAVE_PKCS8 */
  6547. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6548. /* check that the private key is a pair for the public key
  6549. * return 1 (true) on match
  6550. * return 0 or negative value on failure/error
  6551. *
  6552. * privKey : buffer holding DER format private key
  6553. * privKeySz : size of private key buffer
  6554. * pubKey : buffer holding DER format public key
  6555. * pubKeySz : size of public key buffer
  6556. * ks : type of key */
  6557. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6558. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6559. {
  6560. int ret;
  6561. (void)privKeySz;
  6562. (void)pubKeySz;
  6563. (void)ks;
  6564. if (privKey == NULL || pubKey == NULL) {
  6565. return BAD_FUNC_ARG;
  6566. }
  6567. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6568. /* test if RSA key */
  6569. if (ks == RSAk
  6570. #ifdef WC_RSA_PSS
  6571. || ks == RSAPSSk
  6572. #endif
  6573. ) {
  6574. #ifdef WOLFSSL_SMALL_STACK
  6575. RsaKey* a;
  6576. RsaKey* b = NULL;
  6577. #else
  6578. RsaKey a[1], b[1];
  6579. #endif
  6580. word32 keyIdx = 0;
  6581. #ifdef WOLFSSL_SMALL_STACK
  6582. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6583. if (a == NULL)
  6584. return MEMORY_E;
  6585. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6586. if (b == NULL) {
  6587. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6588. return MEMORY_E;
  6589. }
  6590. #endif
  6591. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6592. #ifdef WOLFSSL_SMALL_STACK
  6593. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6594. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6595. #endif
  6596. return ret;
  6597. }
  6598. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6599. wc_FreeRsaKey(a);
  6600. #ifdef WOLFSSL_SMALL_STACK
  6601. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6602. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6603. #endif
  6604. return ret;
  6605. }
  6606. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6607. WOLFSSL_MSG("Checking RSA key pair");
  6608. keyIdx = 0; /* reset to 0 for parsing public key */
  6609. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6610. pubKeySz)) == 0) {
  6611. /* limit for user RSA crypto because of RsaKey
  6612. * dereference. */
  6613. #if defined(HAVE_USER_RSA)
  6614. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6615. ret = 1; /* return first RSA cert as match */
  6616. #else
  6617. /* both keys extracted successfully now check n and e
  6618. * values are the same. This is dereferencing RsaKey */
  6619. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6620. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6621. ret = MP_CMP_E;
  6622. WOLFSSL_ERROR_VERBOSE(ret);
  6623. }
  6624. else
  6625. ret = 1;
  6626. #endif
  6627. }
  6628. else {
  6629. WOLFSSL_ERROR_VERBOSE(ret);
  6630. }
  6631. }
  6632. wc_FreeRsaKey(b);
  6633. wc_FreeRsaKey(a);
  6634. #ifdef WOLFSSL_SMALL_STACK
  6635. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6636. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6637. #endif
  6638. }
  6639. else
  6640. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6641. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6642. if (ks == ECDSAk) {
  6643. #ifdef WOLFSSL_SMALL_STACK
  6644. ecc_key* key_pair;
  6645. byte* privDer;
  6646. #else
  6647. ecc_key key_pair[1];
  6648. byte privDer[MAX_ECC_BYTES];
  6649. #endif
  6650. word32 privSz = MAX_ECC_BYTES;
  6651. word32 keyIdx = 0;
  6652. #ifdef WOLFSSL_SMALL_STACK
  6653. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6654. if (key_pair == NULL)
  6655. return MEMORY_E;
  6656. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6657. if (privDer == NULL) {
  6658. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6659. return MEMORY_E;
  6660. }
  6661. #endif
  6662. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6663. #ifdef WOLFSSL_SMALL_STACK
  6664. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6665. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6666. #endif
  6667. return ret;
  6668. }
  6669. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6670. privKeySz)) == 0) {
  6671. WOLFSSL_MSG("Checking ECC key pair");
  6672. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6673. == 0) {
  6674. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6675. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6676. #endif
  6677. wc_ecc_free(key_pair);
  6678. ret = wc_ecc_init(key_pair);
  6679. if (ret == 0) {
  6680. ret = wc_ecc_import_private_key(privDer,
  6681. privSz, pubKey,
  6682. pubKeySz, key_pair);
  6683. }
  6684. /* public and private extracted successfully now check if is
  6685. * a pair and also do sanity checks on key. wc_ecc_check_key
  6686. * checks that private * base generator equals pubkey */
  6687. if (ret == 0) {
  6688. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6689. ret = 1;
  6690. }
  6691. else {
  6692. WOLFSSL_ERROR_VERBOSE(ret);
  6693. }
  6694. }
  6695. ForceZero(privDer, privSz);
  6696. }
  6697. }
  6698. else {
  6699. WOLFSSL_ERROR_VERBOSE(ret);
  6700. }
  6701. wc_ecc_free(key_pair);
  6702. #ifdef WOLFSSL_SMALL_STACK
  6703. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6704. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6705. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6706. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6707. #endif
  6708. }
  6709. else
  6710. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6711. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6712. if (ks == ED25519k) {
  6713. #ifdef WOLFSSL_SMALL_STACK
  6714. ed25519_key* key_pair;
  6715. #else
  6716. ed25519_key key_pair[1];
  6717. #endif
  6718. word32 keyIdx = 0;
  6719. #ifdef WOLFSSL_SMALL_STACK
  6720. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6721. DYNAMIC_TYPE_ED25519);
  6722. if (key_pair == NULL)
  6723. return MEMORY_E;
  6724. #endif
  6725. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6726. #ifdef WOLFSSL_SMALL_STACK
  6727. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6728. #endif
  6729. return ret;
  6730. }
  6731. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6732. privKeySz)) == 0) {
  6733. WOLFSSL_MSG("Checking ED25519 key pair");
  6734. keyIdx = 0;
  6735. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6736. key_pair)) == 0) {
  6737. /* public and private extracted successfully no check if is
  6738. * a pair and also do sanity checks on key. wc_ecc_check_key
  6739. * checks that private * base generator equals pubkey */
  6740. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6741. ret = 1;
  6742. }
  6743. else {
  6744. WOLFSSL_ERROR_VERBOSE(ret);
  6745. }
  6746. }
  6747. }
  6748. else {
  6749. WOLFSSL_ERROR_VERBOSE(ret);
  6750. }
  6751. wc_ed25519_free(key_pair);
  6752. #ifdef WOLFSSL_SMALL_STACK
  6753. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6754. #endif
  6755. }
  6756. else
  6757. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6758. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6759. if (ks == ED448k) {
  6760. #ifdef WOLFSSL_SMALL_STACK
  6761. ed448_key* key_pair = NULL;
  6762. #else
  6763. ed448_key key_pair[1];
  6764. #endif
  6765. word32 keyIdx = 0;
  6766. #ifdef WOLFSSL_SMALL_STACK
  6767. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6768. DYNAMIC_TYPE_ED448);
  6769. if (key_pair == NULL)
  6770. return MEMORY_E;
  6771. #endif
  6772. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6773. #ifdef WOLFSSL_SMALL_STACK
  6774. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6775. #endif
  6776. return ret;
  6777. }
  6778. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6779. privKeySz)) == 0) {
  6780. WOLFSSL_MSG("Checking ED448 key pair");
  6781. keyIdx = 0;
  6782. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6783. key_pair)) == 0) {
  6784. /* public and private extracted successfully no check if is
  6785. * a pair and also do sanity checks on key. wc_ecc_check_key
  6786. * checks that private * base generator equals pubkey */
  6787. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6788. ret = 1;
  6789. }
  6790. else {
  6791. WOLFSSL_ERROR_VERBOSE(ret);
  6792. }
  6793. }
  6794. }
  6795. else {
  6796. WOLFSSL_ERROR_VERBOSE(ret);
  6797. }
  6798. wc_ed448_free(key_pair);
  6799. #ifdef WOLFSSL_SMALL_STACK
  6800. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6801. #endif
  6802. }
  6803. else
  6804. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6805. #if defined(HAVE_PQC)
  6806. #if defined(HAVE_FALCON)
  6807. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6808. #ifdef WOLFSSL_SMALL_STACK
  6809. falcon_key* key_pair = NULL;
  6810. #else
  6811. falcon_key key_pair[1];
  6812. #endif
  6813. word32 keyIdx = 0;
  6814. #ifdef WOLFSSL_SMALL_STACK
  6815. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6816. DYNAMIC_TYPE_FALCON);
  6817. if (key_pair == NULL)
  6818. return MEMORY_E;
  6819. #endif
  6820. ret = wc_falcon_init(key_pair);
  6821. if (ret < 0) {
  6822. #ifdef WOLFSSL_SMALL_STACK
  6823. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6824. #endif
  6825. return ret;
  6826. }
  6827. if (ks == FALCON_LEVEL1k) {
  6828. ret = wc_falcon_set_level(key_pair, 1);
  6829. }
  6830. else if (ks == FALCON_LEVEL5k) {
  6831. ret = wc_falcon_set_level(key_pair, 5);
  6832. }
  6833. if (ret < 0) {
  6834. #ifdef WOLFSSL_SMALL_STACK
  6835. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6836. #endif
  6837. return ret;
  6838. }
  6839. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6840. privKeySz)) == 0) {
  6841. WOLFSSL_MSG("Checking Falcon key pair");
  6842. keyIdx = 0;
  6843. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6844. key_pair)) == 0) {
  6845. /* Public and private extracted successfully. Sanity check. */
  6846. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6847. ret = 1;
  6848. }
  6849. else {
  6850. WOLFSSL_ERROR_VERBOSE(ret);
  6851. }
  6852. }
  6853. }
  6854. else {
  6855. WOLFSSL_ERROR_VERBOSE(ret);
  6856. }
  6857. wc_falcon_free(key_pair);
  6858. #ifdef WOLFSSL_SMALL_STACK
  6859. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6860. #endif
  6861. }
  6862. else
  6863. #endif /* HAVE_FALCON */
  6864. #if defined(HAVE_DILITHIUM)
  6865. if ((ks == DILITHIUM_LEVEL2k) ||
  6866. (ks == DILITHIUM_LEVEL3k) ||
  6867. (ks == DILITHIUM_LEVEL5k)) {
  6868. #ifdef WOLFSSL_SMALL_STACK
  6869. dilithium_key* key_pair = NULL;
  6870. #else
  6871. dilithium_key key_pair[1];
  6872. #endif
  6873. word32 keyIdx = 0;
  6874. #ifdef WOLFSSL_SMALL_STACK
  6875. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6876. DYNAMIC_TYPE_DILITHIUM);
  6877. if (key_pair == NULL)
  6878. return MEMORY_E;
  6879. #endif
  6880. ret = wc_dilithium_init(key_pair);
  6881. if (ret < 0) {
  6882. #ifdef WOLFSSL_SMALL_STACK
  6883. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6884. #endif
  6885. return ret;
  6886. }
  6887. if (ks == DILITHIUM_LEVEL2k) {
  6888. ret = wc_dilithium_set_level(key_pair, 2);
  6889. }
  6890. else if (ks == DILITHIUM_LEVEL3k) {
  6891. ret = wc_dilithium_set_level(key_pair, 3);
  6892. }
  6893. else if (ks == DILITHIUM_LEVEL5k) {
  6894. ret = wc_dilithium_set_level(key_pair, 5);
  6895. }
  6896. if (ret < 0) {
  6897. #ifdef WOLFSSL_SMALL_STACK
  6898. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6899. #endif
  6900. return ret;
  6901. }
  6902. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6903. privKeySz)) == 0) {
  6904. WOLFSSL_MSG("Checking Dilithium key pair");
  6905. keyIdx = 0;
  6906. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6907. key_pair)) == 0) {
  6908. /* Public and private extracted successfully. Sanity check. */
  6909. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6910. ret = 1;
  6911. }
  6912. }
  6913. wc_dilithium_free(key_pair);
  6914. #ifdef WOLFSSL_SMALL_STACK
  6915. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6916. #endif
  6917. }
  6918. else
  6919. #endif /* HAVE_DILITHIUM */
  6920. #if defined(HAVE_SPHINCS)
  6921. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6922. (ks == SPHINCS_FAST_LEVEL3k) ||
  6923. (ks == SPHINCS_FAST_LEVEL5k) ||
  6924. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6925. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6926. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6927. #ifdef WOLFSSL_SMALL_STACK
  6928. sphincs_key* key_pair = NULL;
  6929. #else
  6930. sphincs_key key_pair[1];
  6931. #endif
  6932. word32 keyIdx = 0;
  6933. #ifdef WOLFSSL_SMALL_STACK
  6934. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6935. DYNAMIC_TYPE_SPHINCS);
  6936. if (key_pair == NULL)
  6937. return MEMORY_E;
  6938. #endif
  6939. ret = wc_sphincs_init(key_pair);
  6940. if (ret < 0) {
  6941. #ifdef WOLFSSL_SMALL_STACK
  6942. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6943. #endif
  6944. return ret;
  6945. }
  6946. if (ks == SPHINCS_FAST_LEVEL1k) {
  6947. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6948. }
  6949. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6950. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6951. }
  6952. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6953. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6954. }
  6955. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6956. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6957. }
  6958. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6959. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6960. }
  6961. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6962. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6963. }
  6964. if (ret < 0) {
  6965. #ifdef WOLFSSL_SMALL_STACK
  6966. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6967. #endif
  6968. return ret;
  6969. }
  6970. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6971. privKeySz)) == 0) {
  6972. WOLFSSL_MSG("Checking Sphincs key pair");
  6973. keyIdx = 0;
  6974. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6975. key_pair)) == 0) {
  6976. /* Public and private extracted successfully. Sanity check. */
  6977. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6978. ret = 1;
  6979. }
  6980. }
  6981. wc_sphincs_free(key_pair);
  6982. #ifdef WOLFSSL_SMALL_STACK
  6983. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6984. #endif
  6985. }
  6986. else
  6987. #endif /* HAVE_SPHINCS */
  6988. #endif /* HAVE_PQC */
  6989. {
  6990. ret = 0;
  6991. }
  6992. (void)ks;
  6993. return ret;
  6994. }
  6995. /* check that the private key is a pair for the public key in certificate
  6996. * return 1 (true) on match
  6997. * return 0 or negative value on failure/error
  6998. *
  6999. * key : buffer holding DER format key
  7000. * keySz : size of key buffer
  7001. * der : a initialized and parsed DecodedCert holding a certificate */
  7002. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  7003. {
  7004. if (key == NULL || der == NULL) {
  7005. return BAD_FUNC_ARG;
  7006. }
  7007. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  7008. der->pubKeySize, (enum Key_Sum) der->keyOID);
  7009. }
  7010. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  7011. #ifndef NO_PWDBASED
  7012. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7013. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  7014. * size of encryption algorithm.
  7015. *
  7016. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  7017. * blockSz based on encryption algorithm.
  7018. *
  7019. * @param [in] first First byte of OID to use in check.
  7020. * @param [in] second Second byte of OID to use in check.
  7021. * @param [out] id wolfSSL id for PBE algorithm.
  7022. * @param [out] version Version of PBE OID:
  7023. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7024. * @param [out] blockSz Block size of encryption algorithm.
  7025. * @return 0 on success.
  7026. * @return ALGO_ID_E when OID not supported.
  7027. * @return ASN_INPUT_E when first byte is invalid.
  7028. */
  7029. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  7030. {
  7031. int ret = 0;
  7032. (void)id;
  7033. (void)blockSz;
  7034. *version = -1;
  7035. /* pkcs-12 1 = pkcs-12PbeIds */
  7036. if (first == 1) {
  7037. /* PKCS #12: Appendix C */
  7038. switch (second) {
  7039. #if !defined(NO_SHA)
  7040. #ifndef NO_RC4
  7041. case PBE_SHA1_RC4_128:
  7042. *id = PBE_SHA1_RC4_128;
  7043. *version = PKCS12v1;
  7044. if (blockSz != NULL) {
  7045. *blockSz = 1;
  7046. }
  7047. break;
  7048. #endif
  7049. #ifndef NO_DES3
  7050. case PBE_SHA1_DES3:
  7051. *id = PBE_SHA1_DES3;
  7052. *version = PKCS12v1;
  7053. if (blockSz != NULL) {
  7054. *blockSz = DES_BLOCK_SIZE;
  7055. }
  7056. break;
  7057. #endif
  7058. #ifdef WC_RC2
  7059. case PBE_SHA1_40RC2_CBC:
  7060. *id = PBE_SHA1_40RC2_CBC;
  7061. *version = PKCS12v1;
  7062. if (blockSz != NULL) {
  7063. *blockSz = RC2_BLOCK_SIZE;
  7064. }
  7065. break;
  7066. #endif
  7067. #endif /* !NO_SHA */
  7068. default:
  7069. ret = ALGO_ID_E;
  7070. break;
  7071. }
  7072. }
  7073. else if (first != PKCS5) {
  7074. /* Bad OID. */
  7075. ret = ASN_INPUT_E;
  7076. }
  7077. /* PKCS #5 PBES2: Appendix A.4
  7078. * pkcs-5 13 = id-PBES2 */
  7079. else if (second == PBES2) {
  7080. *version = PKCS5v2;
  7081. /* Id and block size come from CheckAlgoV2() */
  7082. }
  7083. else {
  7084. /* PKCS #5 PBES1: Appendix A.3 */
  7085. /* see RFC 2898 for ids */
  7086. switch (second) {
  7087. #ifndef NO_DES3
  7088. #ifndef NO_MD5
  7089. case PBES1_MD5_DES:
  7090. *id = PBE_MD5_DES;
  7091. *version = PKCS5;
  7092. if (blockSz != NULL) {
  7093. *blockSz = DES_BLOCK_SIZE;
  7094. }
  7095. break;
  7096. #endif
  7097. #ifndef NO_SHA
  7098. case PBES1_SHA1_DES:
  7099. *id = PBE_SHA1_DES;
  7100. *version = PKCS5;
  7101. if (blockSz != NULL) {
  7102. *blockSz = DES_BLOCK_SIZE;
  7103. }
  7104. break;
  7105. #endif
  7106. #endif /* !NO_DES3 */
  7107. default:
  7108. ret = ALGO_ID_E;
  7109. break;
  7110. }
  7111. }
  7112. /* Return error code. */
  7113. return ret;
  7114. }
  7115. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7116. #ifdef HAVE_PKCS8
  7117. /* Check the encryption algorithm with PBES2 is supported and return block size
  7118. * and wolfSSL id for the PBE.
  7119. *
  7120. * @param [in] oid Encryption algorithm OID id.
  7121. * @param [out] id wolfSSL id for PBE algorithm.
  7122. * @param [out] version Version of PBE OID:
  7123. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7124. * @return 0 on success.
  7125. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7126. */
  7127. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7128. {
  7129. int ret = 0;
  7130. (void)id;
  7131. (void)blockSz;
  7132. switch (oid) {
  7133. #if !defined(NO_DES3) && !defined(NO_SHA)
  7134. case DESb:
  7135. *id = PBE_SHA1_DES;
  7136. if (blockSz != NULL) {
  7137. *blockSz = DES_BLOCK_SIZE;
  7138. }
  7139. break;
  7140. case DES3b:
  7141. *id = PBE_SHA1_DES3;
  7142. if (blockSz != NULL) {
  7143. *blockSz = DES_BLOCK_SIZE;
  7144. }
  7145. break;
  7146. #endif
  7147. #ifdef WOLFSSL_AES_256
  7148. case AES256CBCb:
  7149. *id = PBE_AES256_CBC;
  7150. if (blockSz != NULL) {
  7151. *blockSz = AES_BLOCK_SIZE;
  7152. }
  7153. break;
  7154. #endif
  7155. #ifdef WOLFSSL_AES_128
  7156. case AES128CBCb:
  7157. *id = PBE_AES128_CBC;
  7158. if (blockSz != NULL) {
  7159. *blockSz = AES_BLOCK_SIZE;
  7160. }
  7161. break;
  7162. #endif
  7163. default:
  7164. WOLFSSL_MSG("No PKCS v2 algo found");
  7165. ret = ALGO_ID_E;
  7166. break;
  7167. }
  7168. /* Return error code. */
  7169. return ret;
  7170. }
  7171. #endif /* HAVE_PKCS8 */
  7172. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7173. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7174. int* algoID, void* heap)
  7175. {
  7176. word32 tmpIdx = 0;
  7177. if (key == NULL || algoID == NULL)
  7178. return BAD_FUNC_ARG;
  7179. *algoID = 0;
  7180. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7181. {
  7182. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7183. if (rsa == NULL)
  7184. return MEMORY_E;
  7185. wc_InitRsaKey(rsa, heap);
  7186. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7187. *algoID = RSAk;
  7188. }
  7189. else {
  7190. WOLFSSL_MSG("Not RSA DER key");
  7191. }
  7192. wc_FreeRsaKey(rsa);
  7193. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7194. }
  7195. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7196. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7197. if (*algoID == 0) {
  7198. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7199. if (ecc == NULL)
  7200. return MEMORY_E;
  7201. tmpIdx = 0;
  7202. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7203. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7204. *algoID = ECDSAk;
  7205. /* now find oid */
  7206. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7207. WOLFSSL_MSG("Error getting ECC curve OID");
  7208. wc_ecc_free(ecc);
  7209. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7210. return BAD_FUNC_ARG;
  7211. }
  7212. }
  7213. else {
  7214. WOLFSSL_MSG("Not ECC DER key either");
  7215. }
  7216. wc_ecc_free(ecc);
  7217. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7218. }
  7219. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7220. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7221. if (*algoID == 0) {
  7222. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7223. DYNAMIC_TYPE_TMP_BUFFER);
  7224. if (ed25519 == NULL)
  7225. return MEMORY_E;
  7226. tmpIdx = 0;
  7227. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7228. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7229. *algoID = ED25519k;
  7230. }
  7231. else {
  7232. WOLFSSL_MSG("Not ED25519 DER key");
  7233. }
  7234. wc_ed25519_free(ed25519);
  7235. }
  7236. else {
  7237. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7238. }
  7239. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7240. }
  7241. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7242. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7243. if (*algoID == 0) {
  7244. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7245. DYNAMIC_TYPE_TMP_BUFFER);
  7246. if (ed448 == NULL)
  7247. return MEMORY_E;
  7248. tmpIdx = 0;
  7249. if (wc_ed448_init(ed448) == 0) {
  7250. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7251. *algoID = ED448k;
  7252. }
  7253. else {
  7254. WOLFSSL_MSG("Not ED448 DER key");
  7255. }
  7256. wc_ed448_free(ed448);
  7257. }
  7258. else {
  7259. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7260. }
  7261. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7262. }
  7263. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7264. #if defined(HAVE_PQC)
  7265. #if defined(HAVE_FALCON)
  7266. if (*algoID == 0) {
  7267. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7268. DYNAMIC_TYPE_TMP_BUFFER);
  7269. if (falcon == NULL)
  7270. return MEMORY_E;
  7271. if (wc_falcon_init(falcon) != 0) {
  7272. tmpIdx = 0;
  7273. if (wc_falcon_set_level(falcon, 1) == 0) {
  7274. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7275. == 0) {
  7276. *algoID = FALCON_LEVEL1k;
  7277. }
  7278. else {
  7279. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7280. }
  7281. }
  7282. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7283. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7284. == 0) {
  7285. *algoID = FALCON_LEVEL5k;
  7286. }
  7287. else {
  7288. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7289. }
  7290. }
  7291. else {
  7292. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7293. }
  7294. wc_falcon_free(falcon);
  7295. }
  7296. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7297. }
  7298. #endif /* HAVE_FALCON */
  7299. #if defined(HAVE_DILITHIUM)
  7300. if (*algoID == 0) {
  7301. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7302. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7303. if (dilithium == NULL)
  7304. return MEMORY_E;
  7305. if (wc_dilithium_init(dilithium) != 0) {
  7306. tmpIdx = 0;
  7307. if (wc_dilithium_set_level(dilithium, 2)
  7308. == 0) {
  7309. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7310. keySz) == 0) {
  7311. *algoID = DILITHIUM_LEVEL2k;
  7312. }
  7313. else {
  7314. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7315. }
  7316. }
  7317. else if (wc_dilithium_set_level(dilithium, 3)
  7318. == 0) {
  7319. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7320. keySz) == 0) {
  7321. *algoID = DILITHIUM_LEVEL3k;
  7322. }
  7323. else {
  7324. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7325. }
  7326. }
  7327. else if (wc_dilithium_set_level(dilithium, 5)
  7328. == 0) {
  7329. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7330. keySz) == 0) {
  7331. *algoID = DILITHIUM_LEVEL5k;
  7332. }
  7333. else {
  7334. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7335. }
  7336. }
  7337. else {
  7338. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7339. }
  7340. wc_dilithium_free(dilithium);
  7341. }
  7342. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7343. }
  7344. #endif /* HAVE_DILITHIUM */
  7345. #if defined(HAVE_SPHINCS)
  7346. if (*algoID == 0) {
  7347. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7348. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7349. if (sphincs == NULL)
  7350. return MEMORY_E;
  7351. if (wc_sphincs_init(sphincs) != 0) {
  7352. tmpIdx = 0;
  7353. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7354. == 0) {
  7355. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7356. keySz) == 0) {
  7357. *algoID = SPHINCS_FAST_LEVEL1k;
  7358. }
  7359. else {
  7360. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7361. }
  7362. }
  7363. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7364. == 0) {
  7365. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7366. keySz) == 0) {
  7367. *algoID = SPHINCS_FAST_LEVEL3k;
  7368. }
  7369. else {
  7370. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7371. }
  7372. }
  7373. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7374. == 0) {
  7375. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7376. keySz) == 0) {
  7377. *algoID = SPHINCS_FAST_LEVEL5k;
  7378. }
  7379. else {
  7380. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7381. }
  7382. }
  7383. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7384. == 0) {
  7385. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7386. keySz) == 0) {
  7387. *algoID = SPHINCS_SMALL_LEVEL1k;
  7388. }
  7389. else {
  7390. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7391. }
  7392. }
  7393. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7394. == 0) {
  7395. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7396. keySz) == 0) {
  7397. *algoID = SPHINCS_SMALL_LEVEL3k;
  7398. }
  7399. else {
  7400. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7401. }
  7402. }
  7403. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7404. == 0) {
  7405. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7406. keySz) == 0) {
  7407. *algoID = SPHINCS_SMALL_LEVEL5k;
  7408. }
  7409. else {
  7410. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7411. }
  7412. }
  7413. else {
  7414. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7415. }
  7416. wc_sphincs_free(sphincs);
  7417. }
  7418. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7419. }
  7420. #endif /* HAVE_SPHINCS */
  7421. #endif /* HAVE_PQC */
  7422. /* if flag is not set then this is not a key that we understand. */
  7423. if (*algoID == 0) {
  7424. WOLFSSL_MSG("Bad key DER or compile options");
  7425. return BAD_FUNC_ARG;
  7426. }
  7427. (void)tmpIdx;
  7428. (void)curveOID;
  7429. (void)oidSz;
  7430. (void)keySz;
  7431. (void)heap;
  7432. return 1;
  7433. }
  7434. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7435. #ifdef WOLFSSL_ASN_TEMPLATE
  7436. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7437. /* ASN.1 template for PBES2 parameters.
  7438. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7439. * A.2 - PBKDF2-params
  7440. * B.2 - Encryption schemes
  7441. * C - AlgorithmIdentifier
  7442. */
  7443. static const ASNItem pbes2ParamsASN[] = {
  7444. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7445. /* PBKDF2 */
  7446. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7447. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7448. /* Salt */
  7449. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7450. /* Iteration count */
  7451. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7452. /* Key length */
  7453. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7454. /* PRF - default is HMAC-SHA1 */
  7455. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7456. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7457. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7458. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7459. /* Encryption algorithm */
  7460. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7461. /* IV for CBC */
  7462. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7463. };
  7464. enum {
  7465. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7466. PBES2PARAMSASN_IDX_KDF_OID,
  7467. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7468. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7469. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7470. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7471. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7472. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7473. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7474. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7475. PBES2PARAMSASN_IDX_ENCS_OID,
  7476. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7477. };
  7478. /* Number of items in ASN.1 template for PBES2 parameters. */
  7479. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7480. /* ASN.1 template for PBES1 parameters.
  7481. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7482. */
  7483. static const ASNItem pbes1ParamsASN[] = {
  7484. /* Salt */
  7485. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7486. /* Iteration count */
  7487. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7488. };
  7489. enum {
  7490. PBES1PARAMSASN_IDX_SALT = 0,
  7491. PBES1PARAMSASN_IDX_ITER
  7492. };
  7493. /* Number of items in ASN.1 template for PBES1 parameters. */
  7494. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7495. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7496. #endif /* WOLFSSL_ASN_TEMPLATE */
  7497. #ifdef HAVE_PKCS8
  7498. /*
  7499. * Equivalent to calling TraditionalEnc with the same parameters but with
  7500. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7501. * part of the API (WOLFSSL_ASN_API).
  7502. */
  7503. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7504. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7505. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7506. {
  7507. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7508. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7509. }
  7510. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7511. int *blkSz)
  7512. {
  7513. int ret = 0;
  7514. switch (encAlgId) {
  7515. #if !defined(NO_DES3) && !defined(NO_SHA)
  7516. case DESb:
  7517. *len = sizeof(blkDesCbcOid);
  7518. *oid = blkDesCbcOid;
  7519. *id = PBE_SHA1_DES;
  7520. *blkSz = 8;
  7521. break;
  7522. case DES3b:
  7523. *len = sizeof(blkDes3CbcOid);
  7524. *oid = blkDes3CbcOid;
  7525. *id = PBE_SHA1_DES3;
  7526. *blkSz = 8;
  7527. break;
  7528. #endif
  7529. #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
  7530. case AES128CBCb:
  7531. *len = sizeof(blkAes128CbcOid);
  7532. *oid = blkAes128CbcOid;
  7533. *id = PBE_AES128_CBC;
  7534. *blkSz = 16;
  7535. break;
  7536. #endif
  7537. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7538. case AES256CBCb:
  7539. *len = sizeof(blkAes256CbcOid);
  7540. *oid = blkAes256CbcOid;
  7541. *id = PBE_AES256_CBC;
  7542. *blkSz = 16;
  7543. break;
  7544. #endif
  7545. default:
  7546. (void)len;
  7547. (void)oid;
  7548. (void)id;
  7549. (void)blkSz;
  7550. ret = ALGO_ID_E;
  7551. }
  7552. return ret;
  7553. }
  7554. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7555. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7556. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7557. void* heap)
  7558. {
  7559. #ifdef WOLFSSL_SMALL_STACK
  7560. byte* saltTmp = NULL;
  7561. #else
  7562. byte saltTmp[MAX_SALT_SIZE];
  7563. #endif
  7564. int genSalt = 0;
  7565. int ret = 0;
  7566. int version = 0;
  7567. int pbeId = 0;
  7568. int blockSz = 0;
  7569. const byte* encOid = NULL;
  7570. int encOidSz = 0;
  7571. word32 padSz = 0;
  7572. word32 innerLen = 0;
  7573. const byte* pbeOidBuf = NULL;
  7574. word32 pbeOidBufSz = 0;
  7575. word32 pbeLen = 0;
  7576. word32 kdfLen = 0;
  7577. word32 encLen = 0;
  7578. byte cbcIv[MAX_IV_SIZE];
  7579. word32 idx = 0;
  7580. word32 encIdx = 0;
  7581. (void)heap;
  7582. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7583. if (key == NULL || outSz == NULL || password == NULL) {
  7584. ret = BAD_FUNC_ARG;
  7585. }
  7586. if (ret == 0) {
  7587. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7588. }
  7589. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7590. genSalt = 1;
  7591. saltSz = 8;
  7592. }
  7593. if (ret == 0 && version == PKCS5v2) {
  7594. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7595. }
  7596. if (ret == 0) {
  7597. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7598. (blockSz - 1));
  7599. /* inner = OCT salt INT itt */
  7600. innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
  7601. if (version != PKCS5v2) {
  7602. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7603. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7604. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7605. }
  7606. else {
  7607. pbeOidBuf = pbes2;
  7608. pbeOidBufSz = sizeof(pbes2);
  7609. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7610. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7611. /* enc = OBJ enc_alg OCT iv */
  7612. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7613. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7614. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7615. (size_t)encLen);
  7616. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7617. }
  7618. }
  7619. if (ret == 0) {
  7620. /* outerLen = length of PBE encoding + octet string data */
  7621. /* Plus 2 for tag and length for pbe */
  7622. word32 outerLen = 2 + pbeLen;
  7623. /* Octet string tag, length */
  7624. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7625. /* Octet string bytes */
  7626. outerLen += keySz + padSz;
  7627. if (out == NULL) {
  7628. /* Sequence tag, length */
  7629. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7630. return LENGTH_ONLY_E;
  7631. }
  7632. SetOctetString(keySz + padSz, out);
  7633. idx += SetSequence(outerLen, out + idx);
  7634. encIdx = idx + outerLen - keySz - padSz;
  7635. /* Put Encrypted content in place. */
  7636. XMEMCPY(out + encIdx, key, keySz);
  7637. if (padSz > 0) {
  7638. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7639. keySz += padSz;
  7640. }
  7641. if (genSalt == 1) {
  7642. #ifdef WOLFSSL_SMALL_STACK
  7643. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7644. if (saltTmp == NULL) {
  7645. ret = MEMORY_E;
  7646. }
  7647. else
  7648. #endif
  7649. {
  7650. salt = saltTmp;
  7651. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7652. WOLFSSL_MSG("Error generating random salt");
  7653. }
  7654. }
  7655. }
  7656. }
  7657. if (ret == 0) {
  7658. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7659. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7660. }
  7661. if (ret == 0) {
  7662. if (version != PKCS5v2) {
  7663. /* PBE algorithm */
  7664. idx += SetSequence(pbeLen, out + idx);
  7665. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7666. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7667. idx += pbeOidBufSz;
  7668. }
  7669. else {
  7670. /* PBES2 algorithm identifier */
  7671. idx += SetSequence(pbeLen, out + idx);
  7672. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7673. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7674. idx += pbeOidBufSz;
  7675. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7676. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7677. /* KDF Algorithm Identifier */
  7678. idx += SetSequence(kdfLen, out + idx);
  7679. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7680. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7681. idx += sizeof(pbkdf2Oid);
  7682. }
  7683. idx += SetSequence(innerLen, out + idx);
  7684. idx += SetOctetString(saltSz, out + idx);
  7685. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7686. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7687. if (ret > 0)
  7688. ret = 0;
  7689. }
  7690. if (ret == 0) {
  7691. if (version == PKCS5v2) {
  7692. /* Encryption Algorithm Identifier */
  7693. idx += SetSequence(encLen, out + idx);
  7694. idx += (word32)SetObjectId(encOidSz, out + idx);
  7695. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7696. idx += (word32)encOidSz;
  7697. /* Encryption Algorithm Parameter: CBC IV */
  7698. idx += SetOctetString((word32)blockSz, out + idx);
  7699. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7700. idx += (word32)blockSz;
  7701. }
  7702. idx += SetOctetString(keySz, out + idx);
  7703. /* Default PRF - no need to write out OID */
  7704. idx += keySz;
  7705. ret = (int)idx;
  7706. }
  7707. #ifdef WOLFSSL_SMALL_STACK
  7708. if (saltTmp != NULL) {
  7709. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7710. }
  7711. #endif
  7712. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7713. return ret;
  7714. }
  7715. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7716. int passwordSz)
  7717. {
  7718. int ret;
  7719. int length;
  7720. word32 inOutIdx = 0;
  7721. if (input == NULL || password == NULL) {
  7722. return BAD_FUNC_ARG;
  7723. }
  7724. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7725. ret = ASN_PARSE_E;
  7726. }
  7727. else {
  7728. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7729. passwordSz);
  7730. if (ret > 0) {
  7731. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7732. }
  7733. }
  7734. if (ret > 0) {
  7735. /* DecryptContent will decrypt the data, but it will leave any padding
  7736. * bytes intact. This code calculates the length without the padding
  7737. * and we return that to the user. */
  7738. inOutIdx = 0;
  7739. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7740. ret = ASN_PARSE_E;
  7741. }
  7742. else {
  7743. ret = (int)inOutIdx + length;
  7744. }
  7745. }
  7746. return ret;
  7747. }
  7748. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7749. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7750. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7751. * buffer size. */
  7752. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7753. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7754. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7755. void* heap)
  7756. {
  7757. int ret = 0;
  7758. byte *pkcs8Key = NULL;
  7759. word32 pkcs8KeySz = 0;
  7760. int algId = 0;
  7761. const byte* curveOid = NULL;
  7762. word32 curveOidSz = 0;
  7763. if (ret == 0) {
  7764. /* check key type and get OID if ECC */
  7765. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7766. if (ret == 1)
  7767. ret = 0;
  7768. }
  7769. if (ret == 0) {
  7770. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7771. curveOidSz);
  7772. if (ret == LENGTH_ONLY_E)
  7773. ret = 0;
  7774. }
  7775. if (ret == 0) {
  7776. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7777. if (pkcs8Key == NULL)
  7778. ret = MEMORY_E;
  7779. }
  7780. if (ret == 0) {
  7781. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7782. curveOid, curveOidSz);
  7783. if (ret >= 0) {
  7784. pkcs8KeySz = (word32)ret;
  7785. ret = 0;
  7786. }
  7787. }
  7788. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7789. if (ret == 0) {
  7790. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7791. }
  7792. #endif
  7793. if (ret == 0) {
  7794. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7795. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7796. }
  7797. if (pkcs8Key != NULL) {
  7798. ForceZero(pkcs8Key, pkcs8KeySz);
  7799. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7800. }
  7801. (void)rng;
  7802. return ret;
  7803. }
  7804. /* Same as TraditionalEnc, but in the public API. */
  7805. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7806. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7807. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7808. WC_RNG* rng, void* heap)
  7809. {
  7810. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7811. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7812. }
  7813. #ifdef WOLFSSL_ASN_TEMPLATE
  7814. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7815. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7816. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7817. */
  7818. static const ASNItem pkcs8DecASN[] = {
  7819. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7820. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7821. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7822. /* PKCS #7 */
  7823. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7824. 0, 0, 2 },
  7825. /* PKCS #8 */
  7826. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7827. };
  7828. enum {
  7829. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7830. PKCS8DECASN_IDX_ENCALGO_OID,
  7831. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7832. PKCS8DECASN_IDX_ENCCONTENT,
  7833. PKCS8DECASN_IDX_ENCDATA
  7834. };
  7835. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7836. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7837. #endif
  7838. /* Decrypt data using PBE algorithm.
  7839. *
  7840. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7841. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7842. *
  7843. * Note: input buffer is overwritten with decrypted data!
  7844. *
  7845. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7846. *
  7847. * @param [in] input Data to decrypt and unwrap.
  7848. * @param [in] sz Size of encrypted data.
  7849. * @param [in] password Password to derive encryption key with.
  7850. * @param [in] passwordSz Size of password in bytes.
  7851. * @return Length of decrypted data on success.
  7852. * @return MEMORY_E when dynamic memory allocation fails.
  7853. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7854. * is invalid.
  7855. * @return BUFFER_E when data in buffer is too small.
  7856. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7857. * @return Other when decryption fails.
  7858. */
  7859. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7860. {
  7861. #ifndef WOLFSSL_ASN_TEMPLATE
  7862. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7863. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7864. int iterations = 0, keySz = 0;
  7865. #ifdef WOLFSSL_SMALL_STACK
  7866. byte* salt = NULL;
  7867. byte* cbcIv = NULL;
  7868. #else
  7869. byte salt[MAX_SALT_SIZE];
  7870. byte cbcIv[MAX_IV_SIZE];
  7871. #endif
  7872. byte tag;
  7873. if (passwordSz < 0) {
  7874. WOLFSSL_MSG("Bad password size");
  7875. return BAD_FUNC_ARG;
  7876. }
  7877. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7878. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7879. }
  7880. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7881. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7882. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7883. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7884. }
  7885. if (version == PKCS5v2) {
  7886. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7887. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7888. }
  7889. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7890. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7891. }
  7892. if (oid != PBKDF2_OID) {
  7893. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7894. }
  7895. }
  7896. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7897. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7898. }
  7899. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7900. * DEFAULT items. */
  7901. seqEnd = inOutIdx + (word32)length;
  7902. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7903. if (ret < 0)
  7904. goto exit_dc;
  7905. if (saltSz > MAX_SALT_SIZE) {
  7906. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7907. }
  7908. #ifdef WOLFSSL_SMALL_STACK
  7909. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7910. if (salt == NULL) {
  7911. ERROR_OUT(MEMORY_E, exit_dc);
  7912. }
  7913. #endif
  7914. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  7915. inOutIdx += (word32)saltSz;
  7916. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7917. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7918. }
  7919. /* OPTIONAL key length */
  7920. if (seqEnd > inOutIdx) {
  7921. word32 localIdx = inOutIdx;
  7922. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7923. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7924. }
  7925. if (tag == ASN_INTEGER &&
  7926. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7927. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7928. }
  7929. }
  7930. /* DEFAULT HMAC is SHA-1 */
  7931. if (seqEnd > inOutIdx) {
  7932. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7933. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7934. }
  7935. shaOid = oid;
  7936. }
  7937. #ifdef WOLFSSL_SMALL_STACK
  7938. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7939. if (cbcIv == NULL) {
  7940. ERROR_OUT(MEMORY_E, exit_dc);
  7941. }
  7942. #endif
  7943. if (version == PKCS5v2) {
  7944. /* get encryption algo */
  7945. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7946. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7947. }
  7948. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  7949. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7950. }
  7951. if (shaOid == 0)
  7952. shaOid = oid;
  7953. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7954. if (ret < 0)
  7955. goto exit_dc;
  7956. if (length > MAX_IV_SIZE) {
  7957. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7958. }
  7959. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  7960. inOutIdx += (word32)length;
  7961. }
  7962. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7963. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7964. }
  7965. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7966. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7967. }
  7968. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7969. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7970. }
  7971. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7972. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  7973. exit_dc:
  7974. #ifdef WOLFSSL_SMALL_STACK
  7975. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7976. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7977. #endif
  7978. if (ret == 0) {
  7979. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  7980. ret = length;
  7981. }
  7982. return ret;
  7983. #else
  7984. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7985. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7986. int ret = 0;
  7987. int id = 0;
  7988. int version;
  7989. word32 idx = 0;
  7990. word32 pIdx = 0;
  7991. word32 iterations;
  7992. word32 keySz = 0;
  7993. word32 saltSz = 0;
  7994. word32 shaOid = 0;
  7995. byte* salt = NULL;
  7996. byte* key = NULL;
  7997. byte cbcIv[MAX_IV_SIZE];
  7998. byte* params = NULL;
  7999. WOLFSSL_ENTER("DecryptContent");
  8000. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  8001. if (ret == 0) {
  8002. /* Check OID is a PBE Type */
  8003. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  8004. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  8005. &idx, sz);
  8006. }
  8007. if (ret == 0) {
  8008. /* Check the PBE algorithm and get the version and id. */
  8009. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  8010. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  8011. * Last byte: Alg or PBES2 */
  8012. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  8013. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  8014. &id, &version, NULL);
  8015. }
  8016. if (ret == 0) {
  8017. /* Get the parameters data. */
  8018. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  8019. /* Having a numbered choice means none or both will have errored out. */
  8020. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  8021. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  8022. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  8023. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  8024. else
  8025. ret = ASN_RSA_KEY_E;
  8026. }
  8027. if (ret == 0) {
  8028. if (version != PKCS5v2) {
  8029. /* Initialize for PBES1 parameters and put iterations in var. */
  8030. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  8031. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  8032. /* Parse the PBES1 parameters. */
  8033. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  8034. 0, params, &pIdx, sz);
  8035. if (ret == 0) {
  8036. /* Get the salt data. */
  8037. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  8038. }
  8039. }
  8040. else {
  8041. word32 ivSz = MAX_IV_SIZE;
  8042. /* Initialize for PBES2 parameters. Put iterations in var; match
  8043. * KDF, HMAC and cipher, and copy CBC into buffer. */
  8044. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  8045. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  8046. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  8047. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  8048. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  8049. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  8050. /* Parse the PBES2 parameters */
  8051. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  8052. 0, params, &pIdx, sz);
  8053. if (ret == 0) {
  8054. /* Get the salt data. */
  8055. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  8056. /* Get the digest and encryption algorithm id. */
  8057. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  8058. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8059. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8060. CheckAlgoV2(id, &id, NULL);
  8061. }
  8062. }
  8063. }
  8064. if (ret == 0) {
  8065. /* Decrypt the key. */
  8066. ret = wc_CryptKey(
  8067. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8068. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8069. }
  8070. if (ret == 0) {
  8071. /* Copy the decrypted key into the input (inline). */
  8072. XMEMMOVE(input, key, keySz);
  8073. ret = (int)keySz;
  8074. }
  8075. FREE_ASNGETDATA(dataASN, NULL);
  8076. return ret;
  8077. #endif
  8078. }
  8079. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8080. *
  8081. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8082. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8083. *
  8084. * Note: input buffer is overwritten with decrypted key!
  8085. *
  8086. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8087. *
  8088. * @param [in] input Data to decrypt and unwrap.
  8089. * @param [in] sz Size of encrypted data.
  8090. * @param [in] password Password to derive encryption key with.
  8091. * @param [in] passwordSz Size of password in bytes.
  8092. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8093. * @return Length of decrypted data on success.
  8094. * @return MEMORY_E when dynamic memory allocation fails.
  8095. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8096. * is invalid.
  8097. * @return BUFFER_E when data in buffer is too small.
  8098. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8099. * @return Other when decryption fails.
  8100. */
  8101. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8102. int passwordSz, word32* algId)
  8103. {
  8104. int ret;
  8105. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8106. if (ret > 0) {
  8107. ret = ToTraditional_ex(input, (word32)ret, algId);
  8108. }
  8109. return ret;
  8110. }
  8111. #endif /* HAVE_PKCS8 */
  8112. #ifdef HAVE_PKCS12
  8113. #define PKCS8_MIN_BLOCK_SIZE 8
  8114. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8115. {
  8116. int padSz;
  8117. /* calculate pad size */
  8118. padSz = blockSz - (sz & (blockSz - 1));
  8119. /* pad with padSz value */
  8120. if (buf) {
  8121. int i;
  8122. for (i = 0; i < padSz; i++) {
  8123. buf[sz+i] = (byte)(padSz & 0xFF);
  8124. }
  8125. }
  8126. /* return adjusted length */
  8127. return sz + padSz;
  8128. }
  8129. #ifdef WOLFSSL_ASN_TEMPLATE
  8130. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8131. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8132. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8133. */
  8134. static const ASNItem p8EncPbes1ASN[] = {
  8135. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8136. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8137. /* PBE algorithm */
  8138. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8139. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8140. /* Salt */
  8141. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8142. /* Iteration Count */
  8143. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8144. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8145. };
  8146. enum {
  8147. P8ENCPBES1ASN_IDX_SEQ = 0,
  8148. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8149. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8150. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8151. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8152. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8153. P8ENCPBES1ASN_IDX_ENCDATA
  8154. };
  8155. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8156. #endif
  8157. /* Wrap a private key in PKCS#8 and encrypt.
  8158. *
  8159. * Used for PKCS#12 and PKCS#7.
  8160. * vPKCS is the version of PKCS to use.
  8161. * vAlgo is the algorithm version to use.
  8162. *
  8163. * When salt is NULL, a random number is generated.
  8164. *
  8165. * data returned is :
  8166. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8167. *
  8168. * @param [in] input Data to encrypt.
  8169. * @param [in] inputSz Length of data in bytes.
  8170. * @param [out] out Buffer to write wrapped encrypted data into.
  8171. * @param [out] outSz Length of encrypted data in bytes.
  8172. * @param [in] password Password used to create encryption key.
  8173. * @param [in] passwordSz Length of password in bytes.
  8174. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8175. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8176. * @param [in] salt Salt to use with KDF.
  8177. * @param [in] saltSz Length of salt in bytes.
  8178. * @param [in] itt Number of iterations to use in KDF.
  8179. * @param [in] rng Random number generator to use to generate salt.
  8180. * @param [in] heap Dynamic memory allocator hint.
  8181. * @return The size of encrypted data on success
  8182. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8183. * @return ASN_PARSE_E when the salt size is too large.
  8184. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8185. * TraditionalEnc).
  8186. * @return MEMORY_E when dynamic memory allocation fails.
  8187. * @return Other when encryption or random number generation fails.
  8188. */
  8189. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8190. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8191. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8192. {
  8193. #ifndef WOLFSSL_ASN_TEMPLATE
  8194. word32 sz;
  8195. word32 inOutIdx = 0;
  8196. word32 tmpIdx = 0;
  8197. word32 totalSz = 0;
  8198. word32 seqSz;
  8199. word32 innerSz;
  8200. int ret;
  8201. int version, id, blockSz = 0;
  8202. #ifdef WOLFSSL_SMALL_STACK
  8203. byte* saltTmp = NULL;
  8204. byte* cbcIv = NULL;
  8205. #else
  8206. byte saltTmp[MAX_SALT_SIZE];
  8207. byte cbcIv[MAX_IV_SIZE];
  8208. #endif
  8209. byte seq[MAX_SEQ_SZ];
  8210. byte shr[MAX_SHORT_SZ];
  8211. word32 maxShr = MAX_SHORT_SZ;
  8212. word32 algoSz;
  8213. const byte* algoName;
  8214. (void)heap;
  8215. WOLFSSL_ENTER("EncryptContent");
  8216. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8217. return ASN_INPUT_E; /* Algo ID error */
  8218. if (version == PKCS5v2) {
  8219. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8220. return BAD_FUNC_ARG;
  8221. }
  8222. if (saltSz > MAX_SALT_SIZE)
  8223. return ASN_PARSE_E;
  8224. if (outSz == NULL) {
  8225. return BAD_FUNC_ARG;
  8226. }
  8227. /* calculate size */
  8228. /* size of constructed string at end */
  8229. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8230. totalSz = ASN_TAG_SZ;
  8231. totalSz += SetLength(sz, seq);
  8232. totalSz += sz;
  8233. /* size of sequence holding object id and sub sequence of salt and itt */
  8234. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8235. if (algoName == NULL) {
  8236. WOLFSSL_MSG("Unknown Algorithm");
  8237. return 0;
  8238. }
  8239. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8240. innerSz += algoSz;
  8241. /* get subsequence of salt and itt */
  8242. if (salt == NULL || saltSz == 0) {
  8243. sz = 8;
  8244. }
  8245. else {
  8246. sz = saltSz;
  8247. }
  8248. seqSz = SetOctetString(sz, seq);
  8249. seqSz += sz;
  8250. tmpIdx = 0;
  8251. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8252. if (ret >= 0) {
  8253. seqSz += (word32)ret;
  8254. }
  8255. else {
  8256. return ret;
  8257. }
  8258. innerSz += seqSz + SetSequence(seqSz, seq);
  8259. totalSz += innerSz + SetSequence(innerSz, seq);
  8260. if (out == NULL) {
  8261. *outSz = totalSz;
  8262. return LENGTH_ONLY_E;
  8263. }
  8264. inOutIdx = 0;
  8265. if (totalSz > *outSz)
  8266. return BUFFER_E;
  8267. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8268. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8269. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8270. inOutIdx += algoSz;
  8271. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8272. /* create random salt if one not provided */
  8273. if (salt == NULL || saltSz == 0) {
  8274. saltSz = 8;
  8275. #ifdef WOLFSSL_SMALL_STACK
  8276. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8277. if (saltTmp == NULL)
  8278. return MEMORY_E;
  8279. #endif
  8280. salt = saltTmp;
  8281. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8282. WOLFSSL_MSG("Error generating random salt");
  8283. #ifdef WOLFSSL_SMALL_STACK
  8284. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8285. #endif
  8286. return ret;
  8287. }
  8288. }
  8289. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8290. if (saltSz + inOutIdx > *outSz) {
  8291. #ifdef WOLFSSL_SMALL_STACK
  8292. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8293. #endif
  8294. return BUFFER_E;
  8295. }
  8296. XMEMCPY(out + inOutIdx, salt, saltSz);
  8297. inOutIdx += saltSz;
  8298. /* place iteration setting in buffer */
  8299. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8300. if (ret < 0) {
  8301. #ifdef WOLFSSL_SMALL_STACK
  8302. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8303. #endif
  8304. return ret;
  8305. }
  8306. if (inOutIdx + 1 > *outSz) {
  8307. #ifdef WOLFSSL_SMALL_STACK
  8308. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8309. #endif
  8310. return BUFFER_E;
  8311. }
  8312. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8313. /* get pad size and verify buffer room */
  8314. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8315. if (sz + inOutIdx > *outSz) {
  8316. #ifdef WOLFSSL_SMALL_STACK
  8317. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8318. #endif
  8319. return BUFFER_E;
  8320. }
  8321. inOutIdx += SetLength(sz, out + inOutIdx);
  8322. /* copy input to output buffer and pad end */
  8323. XMEMCPY(out + inOutIdx, input, inputSz);
  8324. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8325. #ifdef WOLFSSL_SMALL_STACK
  8326. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8327. if (cbcIv == NULL) {
  8328. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8329. return MEMORY_E;
  8330. }
  8331. #endif
  8332. /* encrypt */
  8333. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8334. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8335. #ifdef WOLFSSL_SMALL_STACK
  8336. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8337. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8338. #endif
  8339. return ret; /* encrypt failure */
  8340. }
  8341. #ifdef WOLFSSL_SMALL_STACK
  8342. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8343. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8344. #endif
  8345. (void)rng;
  8346. return (int)(inOutIdx + sz);
  8347. #else
  8348. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8349. int ret = 0;
  8350. int sz = 0;
  8351. int version = 0;
  8352. int id = -1;
  8353. int blockSz = 0;
  8354. word32 pkcs8Sz = 0;
  8355. (void)heap;
  8356. WOLFSSL_ENTER("EncryptContent");
  8357. /* Must have a output size to return or check. */
  8358. if (outSz == NULL) {
  8359. ret = BAD_FUNC_ARG;
  8360. }
  8361. /* Check salt size is valid. */
  8362. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8363. ret = ASN_PARSE_E;
  8364. }
  8365. /* Get algorithm parameters for algorithm identifier. */
  8366. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8367. ret = ASN_INPUT_E;
  8368. }
  8369. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8370. if ((ret == 0) && (version == PKCS5v2)) {
  8371. ret = BAD_FUNC_ARG;
  8372. }
  8373. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8374. if (ret == 0) {
  8375. /* Setup data to go into encoding including PBE algorithm, salt,
  8376. * iteration count, and padded key length. */
  8377. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8378. oidPBEType);
  8379. if (salt == NULL || saltSz == 0) {
  8380. salt = NULL;
  8381. saltSz = PKCS5_SALT_SZ;
  8382. /* Salt generated into encoding below. */
  8383. }
  8384. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8385. salt, saltSz);
  8386. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8387. (word16)itt);
  8388. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8389. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8390. /* Calculate size of encoding. */
  8391. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8392. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8393. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8394. &sz);
  8395. }
  8396. /* Return size when no output buffer. */
  8397. if ((ret == 0) && (out == NULL)) {
  8398. *outSz = (word32)sz;
  8399. ret = LENGTH_ONLY_E;
  8400. }
  8401. /* Check output buffer is big enough for encoded data. */
  8402. if ((ret == 0) && (sz > (int)*outSz)) {
  8403. ret = BAD_FUNC_ARG;
  8404. }
  8405. if (ret == 0) {
  8406. /* Encode PKCS#8 key. */
  8407. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8408. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8409. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8410. out);
  8411. if (salt == NULL) {
  8412. /* Generate salt into encoding. */
  8413. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8414. data.buffer.data;
  8415. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8416. }
  8417. }
  8418. if (ret == 0) {
  8419. byte cbcIv[MAX_IV_SIZE];
  8420. /* Store PKCS#8 key in output buffer. */
  8421. byte* pkcs8 =
  8422. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8423. XMEMCPY(pkcs8, input, inputSz);
  8424. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8425. /* Encrypt PKCS#8 key inline. */
  8426. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8427. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8428. }
  8429. if (ret == 0) {
  8430. /* Returning size on success. */
  8431. ret = sz;
  8432. }
  8433. FREE_ASNSETDATA(dataASN, heap);
  8434. return ret;
  8435. #endif /* WOLFSSL_ASN_TEMPLATE */
  8436. }
  8437. #endif /* HAVE_PKCS12 */
  8438. #endif /* NO_PWDBASED */
  8439. #ifndef NO_RSA
  8440. #ifndef HAVE_USER_RSA
  8441. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  8442. /* This function is to retrieve key position information in a cert.*
  8443. * The information will be used to call TSIP TLS-linked API for *
  8444. * certificate verification. */
  8445. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8446. word32 inSz, word32* key_n,
  8447. word32* key_n_len, word32* key_e,
  8448. word32* key_e_len)
  8449. {
  8450. int ret = 0;
  8451. int length = 0;
  8452. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8453. byte b;
  8454. #endif
  8455. if (input == NULL || inOutIdx == NULL)
  8456. return BAD_FUNC_ARG;
  8457. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8458. return ASN_PARSE_E;
  8459. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8460. if ((*inOutIdx + 1) > inSz)
  8461. return BUFFER_E;
  8462. b = input[*inOutIdx];
  8463. if (b != ASN_INTEGER) {
  8464. /* not from decoded cert, will have algo id, skip past */
  8465. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8466. return ASN_PARSE_E;
  8467. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8468. return ASN_PARSE_E;
  8469. /* Option NULL ASN.1 tag */
  8470. if (*inOutIdx >= inSz) {
  8471. return BUFFER_E;
  8472. }
  8473. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8474. ret = GetASNNull(input, inOutIdx, inSz);
  8475. if (ret != 0)
  8476. return ret;
  8477. }
  8478. /* TODO: support RSA PSS */
  8479. /* should have bit tag length and seq next */
  8480. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8481. if (ret != 0)
  8482. return ret;
  8483. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8484. return ASN_PARSE_E;
  8485. }
  8486. #endif /* OPENSSL_EXTRA */
  8487. /* Get modulus */
  8488. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8489. *key_n += *inOutIdx;
  8490. if (ret < 0) {
  8491. return ASN_RSA_KEY_E;
  8492. }
  8493. if (key_n_len)
  8494. *key_n_len = length;
  8495. *inOutIdx += length;
  8496. /* Get exponent */
  8497. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8498. *key_e += *inOutIdx;
  8499. if (ret < 0) {
  8500. return ASN_RSA_KEY_E;
  8501. }
  8502. if (key_e_len)
  8503. *key_e_len = length;
  8504. return ret;
  8505. }
  8506. #endif /* WOLFSSL_RENESAS_TSIP */
  8507. #ifdef WOLFSSL_ASN_TEMPLATE
  8508. /* ASN.1 template for an RSA public key.
  8509. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8510. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8511. */
  8512. static const ASNItem rsaPublicKeyASN[] = {
  8513. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8514. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8515. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8516. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8517. #ifdef WC_RSA_PSS
  8518. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8519. #endif
  8520. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8521. /* RSAPublicKey */
  8522. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8523. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8524. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8525. };
  8526. enum {
  8527. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8528. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8529. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8530. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8531. #ifdef WC_RSA_PSS
  8532. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8533. #endif
  8534. RSAPUBLICKEYASN_IDX_PUBKEY,
  8535. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8536. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8537. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8538. };
  8539. /* Number of items in ASN.1 template for an RSA public key. */
  8540. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8541. #endif
  8542. /* Decode RSA public key.
  8543. *
  8544. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8545. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8546. *
  8547. * @param [in] input Buffer holding BER encoded data.
  8548. * @param [in, out] inOutIdx On in, start of RSA public key.
  8549. * On out, start of ASN.1 item after RSA public key.
  8550. * @param [in] inSz Number of bytes in buffer.
  8551. * @param [out] n Pointer to modulus in buffer.
  8552. * @param [out] nSz Size of modulus in bytes.
  8553. * @param [out] e Pointer to exponent in buffer.
  8554. * @param [out] eSz Size of exponent in bytes.
  8555. * @return 0 on success.
  8556. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8557. * is invalid.
  8558. * @return BUFFER_E when data in buffer is too small.
  8559. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8560. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8561. * non-zero length.
  8562. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8563. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8564. */
  8565. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8566. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8567. {
  8568. #ifndef WOLFSSL_ASN_TEMPLATE
  8569. int ret = 0;
  8570. int length = 0;
  8571. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8572. word32 localIdx;
  8573. byte tag;
  8574. #endif
  8575. if (input == NULL || inOutIdx == NULL)
  8576. return BAD_FUNC_ARG;
  8577. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8578. return ASN_PARSE_E;
  8579. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8580. localIdx = *inOutIdx;
  8581. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8582. return BUFFER_E;
  8583. if (tag != ASN_INTEGER) {
  8584. /* not from decoded cert, will have algo id, skip past */
  8585. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8586. return ASN_PARSE_E;
  8587. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8588. return ASN_PARSE_E;
  8589. /* Option NULL ASN.1 tag */
  8590. if (*inOutIdx >= inSz) {
  8591. return BUFFER_E;
  8592. }
  8593. localIdx = *inOutIdx;
  8594. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8595. return ASN_PARSE_E;
  8596. if (tag == ASN_TAG_NULL) {
  8597. ret = GetASNNull(input, inOutIdx, inSz);
  8598. if (ret != 0)
  8599. return ret;
  8600. }
  8601. #ifdef WC_RSA_PSS
  8602. /* Skip RSA PSS parameters. */
  8603. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8604. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8605. return ASN_PARSE_E;
  8606. *inOutIdx += length;
  8607. }
  8608. #endif
  8609. /* should have bit tag length and seq next */
  8610. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8611. if (ret != 0)
  8612. return ret;
  8613. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8614. return ASN_PARSE_E;
  8615. }
  8616. #endif /* OPENSSL_EXTRA */
  8617. /* Get modulus */
  8618. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8619. if (ret < 0) {
  8620. return ASN_RSA_KEY_E;
  8621. }
  8622. if (nSz)
  8623. *nSz = (word32)length;
  8624. if (n)
  8625. *n = &input[*inOutIdx];
  8626. *inOutIdx += (word32)length;
  8627. /* Get exponent */
  8628. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8629. if (ret < 0) {
  8630. return ASN_RSA_KEY_E;
  8631. }
  8632. if (eSz)
  8633. *eSz = (word32)length;
  8634. if (e)
  8635. *e = &input[*inOutIdx];
  8636. *inOutIdx += (word32)length;
  8637. return ret;
  8638. #else
  8639. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8640. int ret = 0;
  8641. #ifdef WC_RSA_PSS
  8642. word32 oid = RSAk;
  8643. #endif
  8644. /* Check validity of parameters. */
  8645. if (input == NULL || inOutIdx == NULL) {
  8646. ret = BAD_FUNC_ARG;
  8647. }
  8648. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8649. if (ret == 0) {
  8650. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8651. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8652. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8653. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8654. 0, input, inOutIdx, inSz);
  8655. if (ret != 0) {
  8656. /* Didn't work - try whole SubjectKeyInfo instead. */
  8657. #ifdef WC_RSA_PSS
  8658. /* Could be RSA or RSA PSS key. */
  8659. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8660. #else
  8661. /* Set the OID to expect. */
  8662. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8663. keyRsaOid, sizeof(keyRsaOid));
  8664. #endif
  8665. /* Decode SubjectKeyInfo. */
  8666. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8667. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8668. inSz);
  8669. }
  8670. }
  8671. #ifdef WC_RSA_PSS
  8672. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8673. /* Two possible OIDs supported - RSA and RSA PSS. */
  8674. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8675. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8676. ret = ASN_PARSE_E;
  8677. }
  8678. }
  8679. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8680. /* Can't have NULL and SEQ. */
  8681. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8682. ret = ASN_PARSE_E;
  8683. }
  8684. /* SEQ present only with RSA PSS. */
  8685. if ((ret == 0) && (oid != RSAPSSk)) {
  8686. ret = ASN_PARSE_E;
  8687. }
  8688. if (ret == 0) {
  8689. enum wc_HashType hash;
  8690. int mgf;
  8691. int saltLen;
  8692. const byte* params = GetASNItem_Addr(
  8693. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8694. word32 paramsSz = GetASNItem_Length(
  8695. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8696. /* Validate the private key parameters. */
  8697. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8698. /* TODO: store parameters so that usage can be checked. */
  8699. }
  8700. }
  8701. #endif
  8702. if (ret == 0) {
  8703. /* Return the buffers and lengths asked for. */
  8704. if (n != NULL) {
  8705. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8706. }
  8707. if (nSz != NULL) {
  8708. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8709. }
  8710. if (e != NULL) {
  8711. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8712. }
  8713. if (eSz != NULL) {
  8714. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8715. }
  8716. }
  8717. FREE_ASNGETDATA(dataASN, NULL);
  8718. return ret;
  8719. #endif /* WOLFSSL_ASN_TEMPLATE */
  8720. }
  8721. /* Decode RSA public key.
  8722. *
  8723. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8724. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8725. *
  8726. * @param [in] input Buffer holding BER encoded data.
  8727. * @param [in, out] inOutIdx On in, start of RSA public key.
  8728. * On out, start of ASN.1 item after RSA public key.
  8729. * @param [in, out] key RSA key object.
  8730. * @param [in] inSz Number of bytes in buffer.
  8731. * @return 0 on success.
  8732. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8733. * is invalid.
  8734. * @return BUFFER_E when data in buffer is too small.
  8735. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8736. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8737. * non-zero length.
  8738. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8739. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8740. */
  8741. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8742. word32 inSz)
  8743. {
  8744. int ret;
  8745. const byte *n = NULL, *e = NULL;
  8746. word32 nSz = 0, eSz = 0;
  8747. if (key == NULL)
  8748. return BAD_FUNC_ARG;
  8749. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8750. if (ret == 0) {
  8751. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8752. }
  8753. return ret;
  8754. }
  8755. #endif /* HAVE_USER_RSA */
  8756. #endif /* !NO_RSA */
  8757. #ifndef NO_DH
  8758. #if defined(WOLFSSL_DH_EXTRA)
  8759. /*
  8760. * Decodes DH public key to fill specified DhKey.
  8761. *
  8762. * return 0 on success, negative on failure
  8763. */
  8764. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8765. DhKey* key, word32 inSz)
  8766. {
  8767. int ret = 0;
  8768. int length;
  8769. word32 oid = 0;
  8770. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8771. return BAD_FUNC_ARG;
  8772. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8773. return ASN_PARSE_E;
  8774. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8775. return ASN_PARSE_E;
  8776. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8777. if (oid != DHk || ret < 0)
  8778. return ASN_DH_KEY_E;
  8779. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8780. return ASN_PARSE_E;
  8781. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8782. return ASN_DH_KEY_E;
  8783. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8784. mp_clear(&key->p);
  8785. return ASN_DH_KEY_E;
  8786. }
  8787. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8788. if (ret > 0) {
  8789. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8790. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8791. mp_clear(&key->p);
  8792. mp_clear(&key->g);
  8793. return ASN_DH_KEY_E;
  8794. }
  8795. }
  8796. else {
  8797. mp_clear(&key->p);
  8798. mp_clear(&key->g);
  8799. return ASN_DH_KEY_E;
  8800. }
  8801. return 0;
  8802. }
  8803. #endif /* WOLFSSL_DH_EXTRA */
  8804. #ifdef WOLFSSL_ASN_TEMPLATE
  8805. /* ASN.1 template for DH key.
  8806. * PKCS #3, 9 - DHParameter.
  8807. * (Also in: RFC 2786, 3)
  8808. */
  8809. static const ASNItem dhParamASN[] = {
  8810. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8811. /* prime */
  8812. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8813. /* base */
  8814. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8815. /* privateValueLength */
  8816. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8817. };
  8818. enum {
  8819. DHPARAMASN_IDX_SEQ = 0,
  8820. DHPARAMASN_IDX_PRIME,
  8821. DHPARAMASN_IDX_BASE,
  8822. DHPARAMASN_IDX_PRIVLEN
  8823. };
  8824. /* Number of items in ASN.1 template for DH key. */
  8825. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8826. #ifdef WOLFSSL_DH_EXTRA
  8827. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8828. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8829. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8830. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8831. */
  8832. static const ASNItem dhKeyPkcs8ASN[] = {
  8833. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8834. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8835. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8836. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8837. /* DHParameter */
  8838. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8839. /* p */
  8840. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8841. /* g */
  8842. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8843. /* q - factor of p-1 */
  8844. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8845. /* j - subgroup factor */
  8846. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8847. /* ValidationParms */
  8848. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8849. /* PrivateKey - PKCS #8 */
  8850. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8851. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8852. /* PublicKey - SubjectPublicKeyInfo. */
  8853. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8854. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8855. };
  8856. enum {
  8857. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8858. DHKEYPKCS8ASN_IDX_VER,
  8859. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8860. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8861. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8862. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8863. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8864. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8865. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8866. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8867. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8868. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8869. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8870. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8871. };
  8872. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8873. #endif
  8874. #endif
  8875. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8876. *
  8877. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8878. * object.
  8879. *
  8880. * @param [in] input BER/DER encoded data.
  8881. * @param [in, out] inOutIdx On in, start of DH key data.
  8882. * On out, end of DH key data.
  8883. * @param [in, out] key DH key object.
  8884. * @param [in] inSz Size of data in bytes.
  8885. * @return 0 on success.
  8886. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8887. * @return MEMORY_E when dynamic memory allocation fails.
  8888. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8889. * is invalid.
  8890. * @return BUFFER_E when data in buffer is too small.
  8891. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8892. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8893. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8894. * non-zero length.
  8895. * @return MP_INIT_E when the unable to initialize an mp_int.
  8896. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8897. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8898. */
  8899. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8900. {
  8901. #ifndef WOLFSSL_ASN_TEMPLATE
  8902. int ret = 0;
  8903. int length;
  8904. #ifdef WOLFSSL_DH_EXTRA
  8905. #if !defined(HAVE_FIPS) || \
  8906. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8907. word32 oid = 0, temp = 0;
  8908. #endif
  8909. #endif
  8910. WOLFSSL_ENTER("wc_DhKeyDecode");
  8911. if (inOutIdx == NULL)
  8912. return BAD_FUNC_ARG;
  8913. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8914. return ASN_PARSE_E;
  8915. #ifdef WOLFSSL_DH_EXTRA
  8916. #if !defined(HAVE_FIPS) || \
  8917. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8918. temp = *inOutIdx;
  8919. #endif
  8920. #endif
  8921. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8922. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8923. ret = ASN_DH_KEY_E;
  8924. }
  8925. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8926. mp_clear(&key->p);
  8927. ret = ASN_DH_KEY_E;
  8928. }
  8929. #ifdef WOLFSSL_DH_EXTRA
  8930. #if !defined(HAVE_FIPS) || \
  8931. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8932. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8933. if (ret == ASN_DH_KEY_E) {
  8934. *inOutIdx = temp;
  8935. /* the version (0) - private only (for public skip) */
  8936. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8937. *inOutIdx += (word32)length;
  8938. }
  8939. /* Size of dhKeyAgreement section */
  8940. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8941. return ASN_PARSE_E;
  8942. /* Check for dhKeyAgreement */
  8943. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8944. if (oid != DHk || ret < 0)
  8945. return ASN_DH_KEY_E;
  8946. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8947. return ASN_PARSE_E;
  8948. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8949. return ASN_DH_KEY_E;
  8950. }
  8951. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8952. mp_clear(&key->p);
  8953. return ASN_DH_KEY_E;
  8954. }
  8955. }
  8956. temp = *inOutIdx;
  8957. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8958. if (ret > 0) {
  8959. /* Found Bit String */
  8960. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8961. WOLFSSL_MSG("Found Public Key");
  8962. ret = 0;
  8963. }
  8964. } else {
  8965. *inOutIdx = temp;
  8966. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8967. if (ret > 0) {
  8968. /* Found Octet String */
  8969. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8970. WOLFSSL_MSG("Found Private Key");
  8971. /* Compute public */
  8972. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8973. }
  8974. } else {
  8975. /* Don't use length from failed CheckBitString/GetOctetString */
  8976. *inOutIdx = temp;
  8977. ret = 0;
  8978. }
  8979. }
  8980. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8981. #endif /* WOLFSSL_DH_EXTRA */
  8982. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8983. return ret;
  8984. #else
  8985. #ifdef WOLFSSL_DH_EXTRA
  8986. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8987. #else
  8988. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8989. #endif
  8990. int ret = 0;
  8991. /* Check input parameters are valid. */
  8992. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8993. ret = BAD_FUNC_ARG;
  8994. }
  8995. #ifdef WOLFSSL_DH_EXTRA
  8996. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8997. #else
  8998. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8999. #endif
  9000. if (ret == 0) {
  9001. /* Initialize data and set mp_ints to hold p and g. */
  9002. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  9003. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9004. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9005. /* Try simple PKCS #3 template. */
  9006. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9007. inOutIdx, inSz);
  9008. #ifdef WOLFSSL_DH_EXTRA
  9009. if (ret != 0) {
  9010. mp_free(&key->p);
  9011. mp_free(&key->g);
  9012. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  9013. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  9014. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  9015. keyDhOid, sizeof(keyDhOid));
  9016. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9017. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9018. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  9019. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9020. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9021. /* Try PKCS #8 wrapped template. */
  9022. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  9023. input, inOutIdx, inSz);
  9024. if (ret == 0) {
  9025. /* VERSION only present in PKCS #8 private key structure */
  9026. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  9027. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  9028. ret = ASN_PARSE_E;
  9029. }
  9030. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  9031. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  9032. ret = ASN_PARSE_E;
  9033. }
  9034. }
  9035. if ((ret == 0) && mp_iszero(&key->pub)) {
  9036. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  9037. }
  9038. }
  9039. #endif
  9040. }
  9041. FREE_ASNGETDATA(dataASN, key->heap);
  9042. return ret;
  9043. #endif /* WOLFSSL_ASN_TEMPLATE */
  9044. }
  9045. #ifdef WOLFSSL_DH_EXTRA
  9046. /* Export DH Key (private or public) */
  9047. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  9048. {
  9049. #ifndef WOLFSSL_ASN_TEMPLATE
  9050. int ret, privSz = 0, pubSz = 0;
  9051. word32 keySz, idx, len, total;
  9052. if (key == NULL || outSz == NULL) {
  9053. return BAD_FUNC_ARG;
  9054. }
  9055. /* determine size */
  9056. if (exportPriv) {
  9057. /* octet string: priv */
  9058. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9059. if (privSz < 0)
  9060. return privSz;
  9061. idx = 1 + SetLength((word32)privSz, NULL) +
  9062. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9063. }
  9064. else {
  9065. /* bit string: public */
  9066. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9067. if (pubSz < 0)
  9068. return pubSz;
  9069. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9070. }
  9071. keySz = idx;
  9072. /* DH Parameters sequence with P and G */
  9073. total = 0;
  9074. ret = wc_DhParamsToDer(key, NULL, &total);
  9075. if (ret != LENGTH_ONLY_E)
  9076. return ret;
  9077. idx += total;
  9078. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9079. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9080. idx += (word32)sizeof(keyDhOid);
  9081. len = idx - keySz;
  9082. /* sequence - all but pub/priv */
  9083. idx += SetSequence(len, NULL);
  9084. if (exportPriv) {
  9085. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9086. idx += 3;
  9087. }
  9088. /* sequence */
  9089. total = idx + SetSequence(idx, NULL);
  9090. /* if no output, then just getting size */
  9091. if (output == NULL) {
  9092. *outSz = total;
  9093. return LENGTH_ONLY_E;
  9094. }
  9095. /* make sure output fits in buffer */
  9096. if (total > *outSz) {
  9097. return BUFFER_E;
  9098. }
  9099. total = idx;
  9100. /* sequence */
  9101. idx = SetSequence(total, output);
  9102. if (exportPriv) {
  9103. /* version: 0 */
  9104. idx += (word32)SetMyVersion(0, output + idx, 0);
  9105. }
  9106. /* sequence - all but pub/priv */
  9107. idx += SetSequence(len, output + idx);
  9108. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9109. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9110. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9111. idx += sizeof(keyDhOid);
  9112. /* DH Parameters sequence with P and G */
  9113. total = *outSz - idx;
  9114. ret = wc_DhParamsToDer(key, output + idx, &total);
  9115. if (ret < 0)
  9116. return ret;
  9117. idx += total;
  9118. /* octet string: priv */
  9119. if (exportPriv) {
  9120. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9121. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9122. }
  9123. else {
  9124. /* bit string: public */
  9125. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9126. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9127. }
  9128. *outSz = idx;
  9129. return (int)idx;
  9130. #else
  9131. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9132. int ret = 0;
  9133. int sz;
  9134. WOLFSSL_ENTER("wc_DhKeyToDer");
  9135. XMEMSET(dataASN, 0, sizeof(dataASN));
  9136. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9137. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9138. /* Set mp_int containing p and g. */
  9139. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9140. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9141. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9142. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9143. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9144. if (exportPriv) {
  9145. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9146. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9147. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9148. }
  9149. else {
  9150. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9151. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9152. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9153. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9154. }
  9155. /* Calculate the size of the DH parameters. */
  9156. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9157. if (output == NULL) {
  9158. *outSz = (word32)sz;
  9159. ret = LENGTH_ONLY_E;
  9160. }
  9161. /* Check buffer is big enough for encoding. */
  9162. if ((ret == 0) && ((int)*outSz < sz)) {
  9163. ret = BUFFER_E;
  9164. }
  9165. if (ret == 0) {
  9166. /* Encode the DH parameters into buffer. */
  9167. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9168. /* Set the actual encoding size. */
  9169. *outSz = (word32)sz;
  9170. /* Return the actual encoding size. */
  9171. ret = sz;
  9172. }
  9173. return ret;
  9174. #endif
  9175. }
  9176. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9177. {
  9178. return wc_DhKeyToDer(key, out, outSz, 0);
  9179. }
  9180. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9181. {
  9182. return wc_DhKeyToDer(key, out, outSz, 1);
  9183. }
  9184. /* Convert DH key parameters to DER format, write to output (outSz)
  9185. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9186. * returned.
  9187. *
  9188. * Note : static function due to redefinition complications with DhKey and FIPS
  9189. * version 2 build.
  9190. *
  9191. * return bytes written on success */
  9192. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9193. {
  9194. #ifndef WOLFSSL_ASN_TEMPLATE
  9195. int ret;
  9196. word32 idx, total;
  9197. if (key == NULL || outSz == NULL) {
  9198. return BAD_FUNC_ARG;
  9199. }
  9200. /* determine size */
  9201. /* integer - g */
  9202. ret = SetASNIntMP(&key->g, -1, NULL);
  9203. if (ret < 0)
  9204. return ret;
  9205. idx = (word32)ret;
  9206. /* integer - p */
  9207. ret = SetASNIntMP(&key->p, -1, NULL);
  9208. if (ret < 0)
  9209. return ret;
  9210. idx += (word32)ret;
  9211. total = idx;
  9212. /* sequence */
  9213. idx += SetSequence(idx, NULL);
  9214. if (output == NULL) {
  9215. *outSz = idx;
  9216. return LENGTH_ONLY_E;
  9217. }
  9218. /* make sure output fits in buffer */
  9219. if (idx > *outSz) {
  9220. return BUFFER_E;
  9221. }
  9222. /* write DH parameters */
  9223. /* sequence - for P and G only */
  9224. idx = SetSequence(total, output);
  9225. /* integer - p */
  9226. ret = SetASNIntMP(&key->p, -1, output + idx);
  9227. if (ret < 0)
  9228. return ret;
  9229. idx += (word32)ret;
  9230. /* integer - g */
  9231. ret = SetASNIntMP(&key->g, -1, output + idx);
  9232. if (ret < 0)
  9233. return ret;
  9234. idx += (word32)ret;
  9235. *outSz = idx;
  9236. return (int)idx;
  9237. #else
  9238. ASNSetData dataASN[dhParamASN_Length];
  9239. int ret = 0;
  9240. int sz = 0;
  9241. WOLFSSL_ENTER("wc_DhParamsToDer");
  9242. if (key == NULL || outSz == NULL) {
  9243. ret = BAD_FUNC_ARG;
  9244. }
  9245. if (ret == 0) {
  9246. XMEMSET(dataASN, 0, sizeof(dataASN));
  9247. /* Set mp_int containing p and g. */
  9248. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9249. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9250. /* privateValueLength not encoded. */
  9251. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9252. /* Calculate the size of the DH parameters. */
  9253. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9254. }
  9255. if ((ret == 0) && (output == NULL)) {
  9256. *outSz = (word32)sz;
  9257. ret = LENGTH_ONLY_E;
  9258. }
  9259. /* Check buffer is big enough for encoding. */
  9260. if ((ret == 0) && (*outSz < (word32)sz)) {
  9261. ret = BUFFER_E;
  9262. }
  9263. if (ret == 0) {
  9264. /* Encode the DH parameters into buffer. */
  9265. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9266. /* Set the actual encoding size. */
  9267. *outSz = (word32)sz;
  9268. /* Return count of bytes written. */
  9269. ret = sz;
  9270. }
  9271. return ret;
  9272. #endif
  9273. }
  9274. #endif /* WOLFSSL_DH_EXTRA */
  9275. /* Decode DH parameters.
  9276. *
  9277. * PKCS #3, 9 - DHParameter.
  9278. * (Also in: RFC 2786, 3)
  9279. *
  9280. * @param [in] input Buffer holding BER encoded data.
  9281. * @param [in, out] inOutIdx On in, start of RSA public key.
  9282. * On out, start of ASN.1 item after RSA public key.
  9283. * @param [in] inSz Number of bytes in buffer.
  9284. * @param [in, out] p Buffer to hold prime.
  9285. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9286. * On out, size of prime in bytes.
  9287. * @param [in, out] g Buffer to hold base.
  9288. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9289. * On out, size of base in bytes.
  9290. * @return 0 on success.
  9291. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9292. * is invalid.
  9293. * @return BUFFER_E when data in buffer is too small.
  9294. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9295. */
  9296. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9297. byte* g, word32* gInOutSz)
  9298. {
  9299. #ifndef WOLFSSL_ASN_TEMPLATE
  9300. word32 idx = 0;
  9301. int ret;
  9302. int length;
  9303. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9304. return ASN_PARSE_E;
  9305. ret = GetASNInt(input, &idx, &length, inSz);
  9306. if (ret != 0)
  9307. return ret;
  9308. if (length <= (int)*pInOutSz) {
  9309. XMEMCPY(p, &input[idx], (size_t)length);
  9310. *pInOutSz = (word32)length;
  9311. }
  9312. else {
  9313. return BUFFER_E;
  9314. }
  9315. idx += (word32)length;
  9316. ret = GetASNInt(input, &idx, &length, inSz);
  9317. if (ret != 0)
  9318. return ret;
  9319. if (length <= (int)*gInOutSz) {
  9320. XMEMCPY(g, &input[idx], (size_t)length);
  9321. *gInOutSz = (word32)length;
  9322. }
  9323. else {
  9324. return BUFFER_E;
  9325. }
  9326. return 0;
  9327. #else
  9328. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9329. word32 idx = 0;
  9330. int ret = 0;
  9331. /* Make sure pointers are valid before use. */
  9332. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9333. (gInOutSz == NULL)) {
  9334. ret = BAD_FUNC_ARG;
  9335. }
  9336. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9337. if (ret == 0) {
  9338. /* Set the buffers to copy p and g into. */
  9339. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9340. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9341. /* Decode the DH Parameters. */
  9342. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9343. &idx, inSz);
  9344. }
  9345. FREE_ASNGETDATA(dataASN, NULL);
  9346. return ret;
  9347. #endif /* WOLFSSL_ASN_TEMPLATE */
  9348. }
  9349. #endif /* !NO_DH */
  9350. #ifndef NO_DSA
  9351. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9352. {
  9353. if (idx == 0)
  9354. return &key->p;
  9355. if (idx == 1)
  9356. return &key->q;
  9357. if (idx == 2)
  9358. return &key->g;
  9359. if (idx == 3)
  9360. return &key->y;
  9361. if (idx == 4)
  9362. return &key->x;
  9363. return NULL;
  9364. }
  9365. #ifdef WOLFSSL_ASN_TEMPLATE
  9366. /* ASN.1 template for DSA public and private keys.
  9367. * Public key: seq, p, q, g, y
  9368. * Private key: seq, version, p, q, g, y, x
  9369. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9370. */
  9371. static const ASNItem dsaKeyASN[] = {
  9372. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9373. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9374. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9375. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9376. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9377. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9378. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9379. };
  9380. enum {
  9381. DSAKEYASN_IDX_SEQ = 0,
  9382. DSAKEYASN_IDX_VER,
  9383. DSAKEYASN_IDX_P,
  9384. DSAKEYASN_IDX_Q,
  9385. DSAKEYASN_IDX_G,
  9386. DSAKEYASN_IDX_Y,
  9387. DSAKEYASN_IDX_X
  9388. };
  9389. /* Number of items in ASN.1 template for DSA private key. */
  9390. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9391. /* Number of items in ASN.1 template for DSA public key. */
  9392. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9393. /* ASN.1 template for PublicKeyInfo with DSA.
  9394. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9395. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9396. */
  9397. static const ASNItem dsaPubKeyASN[] = {
  9398. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9399. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9400. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9401. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9402. /* p */
  9403. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9404. /* q */
  9405. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9406. /* g */
  9407. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9408. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9409. /* y */
  9410. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9411. };
  9412. enum {
  9413. DSAPUBKEYASN_IDX_SEQ = 0,
  9414. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9415. DSAPUBKEYASN_IDX_ALGOID_OID,
  9416. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9417. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9418. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9419. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9420. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9421. DSAPUBKEYASN_IDX_PUBKEY_Y
  9422. };
  9423. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9424. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9425. #endif /* WOLFSSL_ASN_TEMPLATE */
  9426. /* Decode DSA public key.
  9427. *
  9428. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9429. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9430. *
  9431. * @param [in] input Buffer holding BER encoded data.
  9432. * @param [in, out] inOutIdx On in, start of DSA public key.
  9433. * On out, start of ASN.1 item after DSA public key.
  9434. * @param [in, out] key DSA key object.
  9435. * @param [in] inSz Number of bytes in buffer.
  9436. * @return 0 on success.
  9437. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9438. * is invalid.
  9439. * @return BUFFER_E when data in buffer is too small.
  9440. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9441. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9442. * non-zero length.
  9443. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9444. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9445. */
  9446. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9447. word32 inSz)
  9448. {
  9449. #ifndef WOLFSSL_ASN_TEMPLATE
  9450. int length;
  9451. int ret = 0;
  9452. word32 oid;
  9453. word32 maxIdx;
  9454. if (input == NULL || inOutIdx == NULL || key == NULL)
  9455. return BAD_FUNC_ARG;
  9456. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9457. return ASN_PARSE_E;
  9458. maxIdx = (word32)(*inOutIdx + (word32)length);
  9459. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9460. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9461. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9462. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9463. ret = ASN_DH_KEY_E;
  9464. if (ret != 0) {
  9465. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9466. return ASN_PARSE_E;
  9467. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9468. if (ret != 0)
  9469. return ret;
  9470. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9471. return ASN_PARSE_E;
  9472. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9473. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9474. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9475. return ASN_DH_KEY_E;
  9476. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9477. return ASN_PARSE_E;
  9478. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9479. return ASN_DH_KEY_E;
  9480. ret = 0;
  9481. }
  9482. key->type = DSA_PUBLIC;
  9483. return ret;
  9484. #else
  9485. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9486. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9487. int ret = 0;
  9488. /* Validated parameters. */
  9489. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9490. ret = BAD_FUNC_ARG;
  9491. }
  9492. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9493. if (ret == 0) {
  9494. int i;
  9495. /* Clear dynamic data items. */
  9496. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9497. /* seq
  9498. * p, q, g, y
  9499. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9500. for (i = 0; i < DSA_INTS - 1; i++)
  9501. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9502. /* Parse as simple form. */
  9503. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9504. inOutIdx, inSz);
  9505. if (ret != 0) {
  9506. /* Clear dynamic data items. */
  9507. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9508. /* Set DSA OID to expect. */
  9509. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9510. keyDsaOid, sizeof(keyDsaOid));
  9511. /* p, q, g */
  9512. for (i = 0; i < DSA_INTS - 2; i++)
  9513. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9514. GetDsaInt(key, i));
  9515. /* y */
  9516. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9517. /* Parse as SubjectPublicKeyInfo. */
  9518. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9519. input, inOutIdx, inSz);
  9520. }
  9521. }
  9522. if (ret == 0) {
  9523. /* Data parsed - set type of key parsed. */
  9524. key->type = DSA_PUBLIC;
  9525. }
  9526. FREE_ASNGETDATA(dataASN, key->heap);
  9527. return ret;
  9528. #endif
  9529. }
  9530. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9531. word32 inSz)
  9532. {
  9533. int length;
  9534. word32 maxIdx;
  9535. if (input == NULL || inOutIdx == NULL || key == NULL)
  9536. return BAD_FUNC_ARG;
  9537. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9538. return ASN_PARSE_E;
  9539. maxIdx = (word32)(*inOutIdx + (word32)length);
  9540. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9541. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9542. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9543. return ASN_DH_KEY_E;
  9544. return 0;
  9545. }
  9546. #ifdef WOLFSSL_ASN_TEMPLATE
  9547. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9548. static const ASNItem dsaKeyOctASN[] = {
  9549. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9550. /* p */
  9551. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9552. /* q */
  9553. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9554. /* g */
  9555. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9556. /* Private key */
  9557. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9558. /* x */
  9559. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9560. };
  9561. enum {
  9562. DSAKEYOCTASN_IDX_SEQ = 0,
  9563. DSAKEYOCTASN_IDX_P,
  9564. DSAKEYOCTASN_IDX_Q,
  9565. DSAKEYOCTASN_IDX_G,
  9566. DSAKEYOCTASN_IDX_PKEY_STR,
  9567. DSAKEYOCTASN_IDX_X
  9568. };
  9569. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9570. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9571. #endif
  9572. /* Decode DSA private key.
  9573. *
  9574. * @param [in] input Buffer holding BER encoded data.
  9575. * @param [in, out] inOutIdx On in, start of DSA public key.
  9576. * On out, start of ASN.1 item after DSA public key.
  9577. * @param [in, out] key DSA key object.
  9578. * @param [in] inSz Number of bytes in buffer.
  9579. * @return 0 on success.
  9580. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9581. * is invalid.
  9582. * @return BUFFER_E when data in buffer is too small.
  9583. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9584. * non-zero length.
  9585. */
  9586. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9587. word32 inSz)
  9588. {
  9589. #ifndef WOLFSSL_ASN_TEMPLATE
  9590. int length, version, ret = 0, temp = 0;
  9591. word32 algId = 0;
  9592. /* Sanity checks on input */
  9593. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9594. return BAD_FUNC_ARG;
  9595. }
  9596. /* if has pkcs8 header skip it */
  9597. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9598. /* ignore error, did not have pkcs8 header */
  9599. }
  9600. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9601. return ASN_PARSE_E;
  9602. temp = (int)*inOutIdx;
  9603. /* Default case expects a certificate with OctetString but no version ID */
  9604. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9605. if (ret < 0) {
  9606. mp_clear(&key->p);
  9607. ret = ASN_PARSE_E;
  9608. }
  9609. else {
  9610. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9611. if (ret < 0) {
  9612. mp_clear(&key->p);
  9613. mp_clear(&key->q);
  9614. ret = ASN_PARSE_E;
  9615. }
  9616. else {
  9617. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9618. if (ret < 0) {
  9619. mp_clear(&key->p);
  9620. mp_clear(&key->q);
  9621. mp_clear(&key->g);
  9622. ret = ASN_PARSE_E;
  9623. }
  9624. else {
  9625. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9626. if (ret < 0) {
  9627. mp_clear(&key->p);
  9628. mp_clear(&key->q);
  9629. mp_clear(&key->g);
  9630. ret = ASN_PARSE_E;
  9631. }
  9632. else {
  9633. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9634. if (ret < 0) {
  9635. mp_clear(&key->p);
  9636. mp_clear(&key->q);
  9637. mp_clear(&key->g);
  9638. mp_clear(&key->y);
  9639. ret = ASN_PARSE_E;
  9640. }
  9641. }
  9642. }
  9643. }
  9644. }
  9645. /* An alternate pass if default certificate fails parsing */
  9646. if (ret == ASN_PARSE_E) {
  9647. *inOutIdx = (word32)temp;
  9648. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9649. return ASN_PARSE_E;
  9650. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9651. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9652. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9653. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9654. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9655. return ASN_DH_KEY_E;
  9656. }
  9657. key->type = DSA_PRIVATE;
  9658. return 0;
  9659. #else
  9660. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9661. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9662. int ret = 0;
  9663. byte version = 0;
  9664. /* Sanity checks on input */
  9665. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9666. ret = BAD_FUNC_ARG;
  9667. }
  9668. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9669. if (ret == 0) {
  9670. int i;
  9671. /* Try dsaKeyOctASN */
  9672. /* Initialize key data and set mp_ints for params */
  9673. for (i = 0; i < DSA_INTS - 2; i++) {
  9674. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9675. }
  9676. /* and priv */
  9677. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9678. /* Try simple form. */
  9679. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9680. inOutIdx, inSz);
  9681. if (ret != 0) {
  9682. /* Try dsaKeyASN */
  9683. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9684. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9685. for (i = 0; i < DSA_INTS; i++) {
  9686. mp_int* n = GetDsaInt(key, i);
  9687. mp_clear(n);
  9688. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9689. }
  9690. /* Try simple OCTET_STRING form. */
  9691. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9692. inOutIdx, inSz);
  9693. }
  9694. }
  9695. if (ret == 0) {
  9696. /* Set the contents to be a private key. */
  9697. key->type = DSA_PRIVATE;
  9698. }
  9699. FREE_ASNGETDATA(dataASN, key->heap);
  9700. return ret;
  9701. #endif
  9702. }
  9703. #ifndef WOLFSSL_ASN_TEMPLATE
  9704. /* Release Tmp DSA resources */
  9705. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9706. {
  9707. int i;
  9708. for (i = 0; i < ints; i++)
  9709. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9710. (void)heap;
  9711. }
  9712. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9713. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9714. defined(WOLFSSL_CERT_GEN))
  9715. /* Encode a DSA public key into buffer.
  9716. *
  9717. * @param [out] output Buffer to hold encoded data.
  9718. * @param [in] key DSA key object.
  9719. * @param [out] outLen Length of buffer.
  9720. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9721. * @return Size of encoded data in bytes on success.
  9722. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9723. * than a minimal size (5 bytes), or buffer size is smaller than
  9724. * encoding size.
  9725. * @return MEMORY_E when dynamic memory allocation fails.
  9726. */
  9727. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9728. {
  9729. #ifndef WOLFSSL_ASN_TEMPLATE
  9730. /* p, g, q = DSA params, y = public exponent */
  9731. #ifdef WOLFSSL_SMALL_STACK
  9732. byte* p = NULL;
  9733. byte* g = NULL;
  9734. byte* q = NULL;
  9735. byte* y = NULL;
  9736. #else
  9737. byte p[MAX_DSA_INT_SZ];
  9738. byte g[MAX_DSA_INT_SZ];
  9739. byte q[MAX_DSA_INT_SZ];
  9740. byte y[MAX_DSA_INT_SZ];
  9741. #endif
  9742. byte innerSeq[MAX_SEQ_SZ];
  9743. byte outerSeq[MAX_SEQ_SZ];
  9744. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9745. int pSz, gSz, qSz, ySz;
  9746. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9747. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9748. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9749. return BAD_FUNC_ARG;
  9750. }
  9751. /* p */
  9752. #ifdef WOLFSSL_SMALL_STACK
  9753. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9754. if (p == NULL)
  9755. return MEMORY_E;
  9756. #endif
  9757. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9758. WOLFSSL_MSG("SetASNIntMP Error with p");
  9759. #ifdef WOLFSSL_SMALL_STACK
  9760. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9761. #endif
  9762. return pSz;
  9763. }
  9764. /* q */
  9765. #ifdef WOLFSSL_SMALL_STACK
  9766. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9767. if (q == NULL)
  9768. return MEMORY_E;
  9769. #endif
  9770. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9771. WOLFSSL_MSG("SetASNIntMP Error with q");
  9772. #ifdef WOLFSSL_SMALL_STACK
  9773. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9774. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9775. #endif
  9776. return qSz;
  9777. }
  9778. /* g */
  9779. #ifdef WOLFSSL_SMALL_STACK
  9780. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9781. if (g == NULL)
  9782. return MEMORY_E;
  9783. #endif
  9784. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9785. WOLFSSL_MSG("SetASNIntMP Error with g");
  9786. #ifdef WOLFSSL_SMALL_STACK
  9787. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9788. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9789. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9790. #endif
  9791. return gSz;
  9792. }
  9793. /* y */
  9794. #ifdef WOLFSSL_SMALL_STACK
  9795. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9796. if (y == NULL)
  9797. return MEMORY_E;
  9798. #endif
  9799. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9800. WOLFSSL_MSG("SetASNIntMP Error with y");
  9801. #ifdef WOLFSSL_SMALL_STACK
  9802. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9803. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9804. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9805. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9806. #endif
  9807. return ySz;
  9808. }
  9809. if (with_header) {
  9810. word32 algoSz;
  9811. #ifdef WOLFSSL_SMALL_STACK
  9812. byte* algo = NULL;
  9813. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9814. if (algo == NULL) {
  9815. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9816. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9817. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9818. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9819. return MEMORY_E;
  9820. }
  9821. #else
  9822. byte algo[MAX_ALGO_SZ];
  9823. #endif
  9824. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9825. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9826. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9827. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9828. (word32)(pSz + qSz + gSz), outerSeq);
  9829. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9830. bitStringSz + (word32)ySz + outerSeqSz, output);
  9831. /* check output size */
  9832. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9833. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9834. {
  9835. #ifdef WOLFSSL_SMALL_STACK
  9836. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9837. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9838. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9839. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9840. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9841. #endif
  9842. WOLFSSL_MSG("Error, output size smaller than outlen");
  9843. return BUFFER_E;
  9844. }
  9845. /* outerSeq */
  9846. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9847. idx += outerSeqSz;
  9848. /* algo */
  9849. XMEMCPY(output + idx, algo, algoSz);
  9850. idx += algoSz;
  9851. #ifdef WOLFSSL_SMALL_STACK
  9852. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9853. #endif
  9854. } else {
  9855. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9856. /* check output size */
  9857. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9858. #ifdef WOLFSSL_SMALL_STACK
  9859. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9860. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9861. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9862. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9863. #endif
  9864. WOLFSSL_MSG("Error, output size smaller than outlen");
  9865. return BUFFER_E;
  9866. }
  9867. idx = 0;
  9868. }
  9869. /* innerSeq */
  9870. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9871. idx += innerSeqSz;
  9872. /* p */
  9873. XMEMCPY(output + idx, p, (size_t)pSz);
  9874. idx += (word32)pSz;
  9875. /* q */
  9876. XMEMCPY(output + idx, q, (size_t)qSz);
  9877. idx += (word32)qSz;
  9878. /* g */
  9879. XMEMCPY(output + idx, g, (size_t)gSz);
  9880. idx += (word32)gSz;
  9881. /* bit string */
  9882. if (bitStringSz > 0) {
  9883. XMEMCPY(output + idx, bitString, bitStringSz);
  9884. idx += bitStringSz;
  9885. }
  9886. /* y */
  9887. XMEMCPY(output + idx, y, (size_t)ySz);
  9888. idx += (word32)ySz;
  9889. #ifdef WOLFSSL_SMALL_STACK
  9890. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9891. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9892. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9893. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9894. #endif
  9895. return (int)idx;
  9896. #else
  9897. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9898. int ret = 0;
  9899. int i;
  9900. int sz = 0;
  9901. const ASNItem *data = NULL;
  9902. int count = 0;
  9903. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9904. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9905. ret = BAD_FUNC_ARG;
  9906. }
  9907. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9908. if (ret == 0) {
  9909. if (with_header) {
  9910. /* Using dsaPubKeyASN */
  9911. data = dsaPubKeyASN;
  9912. count = dsaPubKeyASN_Length;
  9913. /* Set the algorithm OID to write out. */
  9914. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9915. /* Set the mp_ints to encode - parameters and public value. */
  9916. for (i = 0; i < DSA_INTS - 2; i++) {
  9917. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9918. GetDsaInt(key, i));
  9919. }
  9920. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9921. }
  9922. else {
  9923. /* Using dsaKeyASN */
  9924. data = dsaKeyASN;
  9925. count = dsaPublicKeyASN_Length;
  9926. /* Set the mp_ints to encode - parameters and public value. */
  9927. for (i = 0; i < DSA_INTS - 1; i++) {
  9928. /* Move all DSA ints up one slot (ignore VERSION so now
  9929. * it means P) */
  9930. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9931. GetDsaInt(key, i));
  9932. }
  9933. }
  9934. ret = SizeASN_Items(data, dataASN, count, &sz);
  9935. }
  9936. /* Check buffer is big enough for encoding. */
  9937. if ((ret == 0) && (sz > (int)outLen)) {
  9938. ret = BAD_FUNC_ARG;
  9939. }
  9940. /* Encode the DSA public key into output buffer. */
  9941. if (ret == 0) {
  9942. ret = SetASN_Items(data, dataASN, count, output);
  9943. }
  9944. FREE_ASNSETDATA(dataASN, key->heap);
  9945. return ret;
  9946. #endif /* WOLFSSL_ASN_TEMPLATE */
  9947. }
  9948. /* Encode a DSA public key into buffer.
  9949. *
  9950. * @param [out] output Buffer to hold encoded data.
  9951. * @param [in] key DSA key object.
  9952. * @param [out] outLen Length of buffer.
  9953. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9954. * @return Size of encoded data in bytes on success.
  9955. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9956. * than a minimal size (5 bytes), or buffer size is smaller than
  9957. * encoding size.
  9958. * @return MEMORY_E when dynamic memory allocation fails.
  9959. */
  9960. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9961. {
  9962. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  9963. }
  9964. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9965. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9966. int ints, int includeVersion)
  9967. {
  9968. #ifndef WOLFSSL_ASN_TEMPLATE
  9969. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  9970. word32 sizes[DSA_INTS];
  9971. int i, ret = 0;
  9972. byte seq[MAX_SEQ_SZ];
  9973. byte ver[MAX_VERSION_SZ];
  9974. byte* tmps[DSA_INTS];
  9975. if (ints > DSA_INTS || inLen == NULL)
  9976. return BAD_FUNC_ARG;
  9977. XMEMSET(sizes, 0, sizeof(sizes));
  9978. for (i = 0; i < ints; i++)
  9979. tmps[i] = NULL;
  9980. /* write all big ints from key to DER tmps */
  9981. for (i = 0; i < ints; i++) {
  9982. int mpSz;
  9983. mp_int* keyInt = GetDsaInt(key, i);
  9984. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  9985. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9986. DYNAMIC_TYPE_DSA);
  9987. if (tmps[i] == NULL) {
  9988. ret = MEMORY_E;
  9989. break;
  9990. }
  9991. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9992. if (mpSz < 0) {
  9993. ret = mpSz;
  9994. break;
  9995. }
  9996. sizes[i] = (word32)mpSz;
  9997. intTotalLen += (word32)mpSz;
  9998. }
  9999. if (ret != 0) {
  10000. FreeTmpDsas(tmps, key->heap, ints);
  10001. return ret;
  10002. }
  10003. /* make headers */
  10004. if (includeVersion)
  10005. verSz = (word32)SetMyVersion(0, ver, FALSE);
  10006. seqSz = SetSequence(verSz + intTotalLen, seq);
  10007. outLen = seqSz + verSz + intTotalLen;
  10008. *inLen = outLen;
  10009. if (output == NULL) {
  10010. FreeTmpDsas(tmps, key->heap, ints);
  10011. return LENGTH_ONLY_E;
  10012. }
  10013. if (outLen > *inLen) {
  10014. FreeTmpDsas(tmps, key->heap, ints);
  10015. return BAD_FUNC_ARG;
  10016. }
  10017. /* write to output */
  10018. XMEMCPY(output, seq, seqSz);
  10019. j = seqSz;
  10020. if (includeVersion) {
  10021. XMEMCPY(output + j, ver, verSz);
  10022. j += verSz;
  10023. }
  10024. for (i = 0; i < ints; i++) {
  10025. XMEMCPY(output + j, tmps[i], sizes[i]);
  10026. j += sizes[i];
  10027. }
  10028. FreeTmpDsas(tmps, key->heap, ints);
  10029. return (int)outLen;
  10030. #else
  10031. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  10032. int ret = 0;
  10033. int sz = 0;
  10034. (void)ints;
  10035. if ((key == NULL) || (inLen == NULL)) {
  10036. ret = BAD_FUNC_ARG;
  10037. }
  10038. if ((ret == 0) && (ints > DSA_INTS)) {
  10039. ret = BAD_FUNC_ARG;
  10040. }
  10041. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  10042. if (ret == 0) {
  10043. int i;
  10044. if (includeVersion) {
  10045. /* Set the version. */
  10046. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  10047. }
  10048. else {
  10049. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  10050. }
  10051. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10052. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10053. /* Set the mp_ints to encode - params, public and private value. */
  10054. for (i = 0; i < DSA_INTS; i++) {
  10055. if (i < ints)
  10056. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10057. else
  10058. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10059. }
  10060. /* Calculate size of the encoding. */
  10061. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10062. }
  10063. if ((ret == 0) && (output == NULL)) {
  10064. *inLen = (word32)sz;
  10065. ret = LENGTH_ONLY_E;
  10066. }
  10067. /* Check buffer is big enough for encoding. */
  10068. if ((ret == 0) && (sz > (int)*inLen)) {
  10069. ret = BAD_FUNC_ARG;
  10070. }
  10071. if (ret == 0) {
  10072. /* Encode the DSA private key into output buffer. */
  10073. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10074. /* Return the size of the encoding. */
  10075. ret = sz;
  10076. }
  10077. FREE_ASNSETDATA(dataASN, key->heap);
  10078. return ret;
  10079. #endif /* WOLFSSL_ASN_TEMPLATE */
  10080. }
  10081. /* Encode a DSA private key into buffer.
  10082. *
  10083. * @param [in] key DSA key object.
  10084. * @param [out] output Buffer to hold encoded data.
  10085. * @param [out] inLen Length of buffer.
  10086. * @return Size of encoded data in bytes on success.
  10087. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10088. * or, buffer size is smaller than encoding size.
  10089. * @return MEMORY_E when dynamic memory allocation fails.
  10090. */
  10091. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10092. {
  10093. if (!key || !output)
  10094. return BAD_FUNC_ARG;
  10095. if (key->type != DSA_PRIVATE)
  10096. return BAD_FUNC_ARG;
  10097. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10098. }
  10099. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10100. return bytes written. Version is excluded to be compatible with
  10101. OpenSSL d2i_DSAparams */
  10102. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10103. {
  10104. if (!key || !output)
  10105. return BAD_FUNC_ARG;
  10106. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10107. }
  10108. /* This version of the function allows output to be NULL. In that case, the
  10109. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10110. size will be pointed to by inLen. */
  10111. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10112. {
  10113. if (!key || !inLen)
  10114. return BAD_FUNC_ARG;
  10115. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10116. }
  10117. #endif /* NO_DSA */
  10118. #ifndef NO_CERTS
  10119. /* Initialize decoded certificate object with buffer of DER encoding.
  10120. *
  10121. * @param [in, out] cert Decoded certificate object.
  10122. * @param [in] source Buffer containing DER encoded certificate.
  10123. * @param [in] inSz Size of DER data in buffer in bytes.
  10124. * @param [in] heap Dynamic memory hint.
  10125. */
  10126. void InitDecodedCert(DecodedCert* cert,
  10127. const byte* source, word32 inSz, void* heap)
  10128. {
  10129. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10130. }
  10131. /* Initialize decoded certificate object with buffer of DER encoding.
  10132. *
  10133. * @param [in, out] cert Decoded certificate object.
  10134. * @param [in] source Buffer containing DER encoded certificate.
  10135. * @param [in] inSz Size of DER data in buffer in bytes.
  10136. * @param [in] heap Dynamic memory hint.
  10137. * @param [in] devId Crypto callback ID to use.
  10138. */
  10139. void InitDecodedCert_ex(DecodedCert* cert,
  10140. const byte* source, word32 inSz, void* heap, int devId)
  10141. {
  10142. if (cert != NULL) {
  10143. XMEMSET(cert, 0, sizeof(DecodedCert));
  10144. cert->subjectCNEnc = CTC_UTF8;
  10145. cert->issuer[0] = '\0';
  10146. cert->subject[0] = '\0';
  10147. cert->source = source; /* don't own */
  10148. cert->maxIdx = inSz; /* can't go over this index */
  10149. cert->heap = heap;
  10150. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10151. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10152. #ifdef WOLFSSL_CERT_NAME_ALL
  10153. cert->subjectNEnc = CTC_UTF8;
  10154. cert->subjectIEnc = CTC_UTF8;
  10155. cert->subjectDNQEnc = CTC_UTF8;
  10156. cert->subjectGNEnc = CTC_UTF8;
  10157. #endif
  10158. cert->subjectSNEnc = CTC_UTF8;
  10159. cert->subjectCEnc = CTC_PRINTABLE;
  10160. cert->subjectLEnc = CTC_UTF8;
  10161. cert->subjectSTEnc = CTC_UTF8;
  10162. cert->subjectOEnc = CTC_UTF8;
  10163. cert->subjectOUEnc = CTC_UTF8;
  10164. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10165. cert->issuerSNEnc = CTC_UTF8;
  10166. cert->issuerCEnc = CTC_PRINTABLE;
  10167. cert->issuerLEnc = CTC_UTF8;
  10168. cert->issuerSTEnc = CTC_UTF8;
  10169. cert->issuerOEnc = CTC_UTF8;
  10170. cert->issuerOUEnc = CTC_UTF8;
  10171. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10172. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10173. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10174. }
  10175. }
  10176. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10177. void* heap)
  10178. {
  10179. InitDecodedCert(cert, source, inSz, heap);
  10180. }
  10181. /* Free the alternative names object.
  10182. *
  10183. * Frees each linked list items and its name.
  10184. *
  10185. * @param [in, out] altNames Alternative names.
  10186. * @param [in] heap Dynamic memory hint.
  10187. */
  10188. void FreeAltNames(DNS_entry* altNames, void* heap)
  10189. {
  10190. (void)heap;
  10191. while (altNames) {
  10192. DNS_entry* tmp = altNames->next;
  10193. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10194. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10195. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10196. #endif
  10197. #if defined(OPENSSL_ALL)
  10198. XFREE(altNames->ridString, heap, DYNAMIC_TYPE_ALTNAME);
  10199. #endif
  10200. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10201. altNames = tmp;
  10202. }
  10203. }
  10204. /* malloc and initialize a new alt name structure */
  10205. DNS_entry* AltNameNew(void* heap)
  10206. {
  10207. DNS_entry* ret;
  10208. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10209. if (ret != NULL) {
  10210. XMEMSET(ret, 0, sizeof(DNS_entry));
  10211. }
  10212. (void)heap;
  10213. return ret;
  10214. }
  10215. #ifndef IGNORE_NAME_CONSTRAINTS
  10216. /* Free the subtree names object.
  10217. *
  10218. * Frees each linked list items and its name.
  10219. *
  10220. * @param [in, out] names Subtree names.
  10221. * @param [in] heap Dynamic memory hint.
  10222. */
  10223. void FreeNameSubtrees(Base_entry* names, void* heap)
  10224. {
  10225. (void)heap;
  10226. while (names) {
  10227. Base_entry* tmp = names->next;
  10228. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10229. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10230. names = tmp;
  10231. }
  10232. }
  10233. #endif /* IGNORE_NAME_CONSTRAINTS */
  10234. /* Free the decoded cert object's dynamic data.
  10235. *
  10236. * @param [in, out] cert Decoded certificate object.
  10237. */
  10238. void FreeDecodedCert(DecodedCert* cert)
  10239. {
  10240. if (cert == NULL)
  10241. return;
  10242. if (cert->subjectCNStored == 1) {
  10243. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10244. }
  10245. if (cert->pubKeyStored == 1) {
  10246. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10247. }
  10248. if (cert->weOwnAltNames && cert->altNames)
  10249. FreeAltNames(cert->altNames, cert->heap);
  10250. #ifndef IGNORE_NAME_CONSTRAINTS
  10251. if (cert->altEmailNames)
  10252. FreeAltNames(cert->altEmailNames, cert->heap);
  10253. if (cert->altDirNames)
  10254. FreeAltNames(cert->altDirNames, cert->heap);
  10255. if (cert->permittedNames)
  10256. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10257. if (cert->excludedNames)
  10258. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10259. #endif /* IGNORE_NAME_CONSTRAINTS */
  10260. #ifdef WOLFSSL_SEP
  10261. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10262. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10263. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10264. #endif /* WOLFSSL_SEP */
  10265. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10266. if (cert->issuerName != NULL)
  10267. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10268. if (cert->subjectName != NULL)
  10269. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10270. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10271. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  10272. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10273. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10274. #endif
  10275. FreeSignatureCtx(&cert->sigCtx);
  10276. }
  10277. void wc_FreeDecodedCert(DecodedCert* cert)
  10278. {
  10279. FreeDecodedCert(cert);
  10280. }
  10281. #ifndef WOLFSSL_ASN_TEMPLATE
  10282. static int GetCertHeader(DecodedCert* cert)
  10283. {
  10284. int ret = 0, len;
  10285. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10286. return ASN_PARSE_E;
  10287. /* Reset the max index for the size indicated in the outer wrapper. */
  10288. cert->maxIdx = (word32)len + cert->srcIdx;
  10289. cert->certBegin = cert->srcIdx;
  10290. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10291. return ASN_PARSE_E;
  10292. cert->sigIndex = (word32)len + cert->srcIdx;
  10293. if (cert->sigIndex > cert->maxIdx)
  10294. return ASN_PARSE_E;
  10295. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10296. cert->sigIndex) < 0)
  10297. return ASN_PARSE_E;
  10298. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10299. &cert->serialSz, cert->sigIndex) < 0)
  10300. return ASN_PARSE_E;
  10301. return ret;
  10302. }
  10303. #endif
  10304. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10305. defined(HAVE_LIBOQS))
  10306. /* Store the key data under the BIT_STRING in dynamically allocated data.
  10307. *
  10308. * @param [in, out] cert Certificate object.
  10309. * @param [in] source Buffer containing encoded key.
  10310. * @param [in, out] srcIdx On in, start of key data.
  10311. * On out, start of element after key data.
  10312. * @param [in] maxIdx Maximum index of certificate data.
  10313. */
  10314. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10315. word32 maxIdx)
  10316. {
  10317. int ret;
  10318. int length;
  10319. byte* publicKey;
  10320. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10321. if (ret == 0) {
  10322. #ifdef HAVE_OCSP
  10323. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10324. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10325. }
  10326. if (ret == 0) {
  10327. #endif
  10328. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10329. DYNAMIC_TYPE_PUBLIC_KEY);
  10330. if (publicKey == NULL) {
  10331. ret = MEMORY_E;
  10332. }
  10333. else {
  10334. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10335. cert->publicKey = publicKey;
  10336. cert->pubKeyStored = 1;
  10337. cert->pubKeySize = (word32)length;
  10338. *srcIdx += (word32)length;
  10339. }
  10340. }
  10341. return ret;
  10342. }
  10343. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10344. #endif
  10345. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10346. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  10347. {
  10348. #ifdef HAVE_OID_ENCODING
  10349. int ret;
  10350. #endif
  10351. int idx;
  10352. word32 oidSz = 0;
  10353. /* validate key */
  10354. if (key == NULL || key->dp == NULL) {
  10355. return BAD_FUNC_ARG;
  10356. }
  10357. #ifdef HAVE_OID_ENCODING
  10358. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  10359. if (ret != 0) {
  10360. return ret;
  10361. }
  10362. #else
  10363. oidSz = key->dp->oidSz;
  10364. #endif
  10365. idx = SetObjectId((int)oidSz, output);
  10366. /* length only */
  10367. if (output == NULL) {
  10368. return idx + (int)oidSz;
  10369. }
  10370. /* verify output buffer has room */
  10371. if (oidSz > outSz)
  10372. return BUFFER_E;
  10373. #ifdef HAVE_OID_ENCODING
  10374. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  10375. if (ret != 0) {
  10376. return ret;
  10377. }
  10378. #else
  10379. XMEMCPY(output+idx, key->dp->oid, oidSz);
  10380. #endif
  10381. idx += (int)oidSz;
  10382. return idx;
  10383. }
  10384. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10385. #ifdef HAVE_ECC
  10386. #ifdef WOLFSSL_ASN_TEMPLATE
  10387. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  10388. * RFC 5480, 2 - Subject Public Key Information Fields
  10389. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10390. * X9.62 ECC point format.
  10391. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  10392. */
  10393. static const ASNItem eccPublicKeyASN[] = {
  10394. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10395. /* AlgorithmIdentifier */
  10396. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10397. /* algorithm */
  10398. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  10399. /* namedCurve */
  10400. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  10401. /* specifiedCurve - explicit parameters */
  10402. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  10403. /* Public Key */
  10404. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10405. };
  10406. enum {
  10407. ECCPUBLICKEYASN_IDX_SEQ = 0,
  10408. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  10409. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  10410. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  10411. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  10412. ECCPUBLICKEYASN_IDX_PUBKEY
  10413. };
  10414. /* Number of items in ASN.1 template for ECC public key. */
  10415. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  10416. #endif /* WOLFSSL_ASN_TEMPLATE */
  10417. #endif /* HAVE_ECC */
  10418. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10419. /* Encode public ECC key in DER format.
  10420. *
  10421. * RFC 5480, 2 - Subject Public Key Information Fields
  10422. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10423. * X9.62 ECC point format.
  10424. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  10425. *
  10426. * @param [out] output Buffer to put encoded data in.
  10427. * @param [in] key ECC key object.
  10428. * @param [in] outLen Size of buffer in bytes.
  10429. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  10430. * @return Size of encoded data in bytes on success.
  10431. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10432. * @return MEMORY_E when dynamic memory allocation failed.
  10433. */
  10434. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  10435. int with_header, int comp)
  10436. {
  10437. #ifndef WOLFSSL_ASN_TEMPLATE
  10438. int ret;
  10439. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  10440. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  10441. byte algo[MAX_ALGO_SZ]; /* 20 */
  10442. /* public size */
  10443. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  10444. if (comp)
  10445. pubSz = 1 + pubSz;
  10446. else
  10447. pubSz = 1 + 2 * pubSz;
  10448. /* check for buffer overflow */
  10449. if (output != NULL && pubSz > (word32)outLen) {
  10450. return BUFFER_E;
  10451. }
  10452. /* headers */
  10453. if (with_header) {
  10454. ret = SetCurve(key, NULL, 0);
  10455. if (ret <= 0) {
  10456. return ret;
  10457. }
  10458. curveSz = (word32)ret;
  10459. ret = 0;
  10460. /* calculate size */
  10461. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  10462. bitStringSz = SetBitString(pubSz, 0, bitString);
  10463. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  10464. /* check for buffer overflow */
  10465. if (output != NULL &&
  10466. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  10467. return BUFFER_E;
  10468. }
  10469. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  10470. output);
  10471. /* algo */
  10472. if (output)
  10473. XMEMCPY(output + idx, algo, algoSz);
  10474. idx += algoSz;
  10475. /* curve */
  10476. if (output)
  10477. (void)SetCurve(key, output + idx, curveSz);
  10478. idx += curveSz;
  10479. /* bit string */
  10480. if (output)
  10481. XMEMCPY(output + idx, bitString, bitStringSz);
  10482. idx += bitStringSz;
  10483. }
  10484. /* pub */
  10485. if (output) {
  10486. PRIVATE_KEY_UNLOCK();
  10487. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  10488. PRIVATE_KEY_LOCK();
  10489. if (ret != 0) {
  10490. return ret;
  10491. }
  10492. }
  10493. idx += pubSz;
  10494. return (int)idx;
  10495. #else
  10496. word32 pubSz = 0;
  10497. int sz = 0;
  10498. int ret = 0;
  10499. int curveIdSz = 0;
  10500. byte* curveOid = NULL;
  10501. /* Check key validity. */
  10502. if ((key == NULL) || (key->dp == NULL)) {
  10503. ret = BAD_FUNC_ARG;
  10504. }
  10505. if (ret == 0) {
  10506. /* Calculate the size of the encoded public point. */
  10507. PRIVATE_KEY_UNLOCK();
  10508. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  10509. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  10510. /* in earlier versions of FIPS the get length functionality is not
  10511. * available with compressed keys */
  10512. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  10513. if (comp)
  10514. pubSz = 1 + pubSz;
  10515. else
  10516. pubSz = 1 + 2 * pubSz;
  10517. ret = LENGTH_ONLY_E;
  10518. #else
  10519. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  10520. #endif
  10521. PRIVATE_KEY_LOCK();
  10522. /* LENGTH_ONLY_E on success. */
  10523. if (ret == LENGTH_ONLY_E) {
  10524. ret = 0;
  10525. }
  10526. }
  10527. if ((ret == 0) && with_header) {
  10528. /* Including SubjectPublicKeyInfo header. */
  10529. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  10530. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  10531. /* Get the length of the named curve OID to put into the encoding. */
  10532. curveIdSz = SetCurve(key, NULL, 0);
  10533. if (curveIdSz < 0) {
  10534. ret = curveIdSz;
  10535. }
  10536. if (ret == 0) {
  10537. /* Set the key type OID. */
  10538. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  10539. oidKeyType);
  10540. /* Set the curve OID. */
  10541. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  10542. NULL, (word32)curveIdSz);
  10543. /* Don't try to write out explicit parameters. */
  10544. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  10545. /* Set size of public point to ensure space is made for it. */
  10546. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  10547. /* Calculate size of ECC public key. */
  10548. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  10549. eccPublicKeyASN_Length, &sz);
  10550. }
  10551. /* Check buffer, if passed in, is big enough for encoded data. */
  10552. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  10553. ret = BUFFER_E;
  10554. }
  10555. if ((ret == 0) && (output != NULL)) {
  10556. /* Encode ECC public key. */
  10557. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  10558. output);
  10559. /* Skip to where public point is to be encoded. */
  10560. output += sz - (int)pubSz;
  10561. /* Cache the location to place the name curve OID. */
  10562. curveOid = (byte*)
  10563. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  10564. }
  10565. FREE_ASNSETDATA(dataASN, key->heap);
  10566. }
  10567. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  10568. ret = BUFFER_E;
  10569. }
  10570. else {
  10571. /* Total size is the public point size. */
  10572. sz = (int)pubSz;
  10573. }
  10574. if ((ret == 0) && (output != NULL)) {
  10575. /* Put named curve OID data into encoding. */
  10576. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  10577. if (curveIdSz < 0) {
  10578. ret = curveIdSz;
  10579. }
  10580. }
  10581. if ((ret == 0) && (output != NULL)) {
  10582. /* Encode public point. */
  10583. PRIVATE_KEY_UNLOCK();
  10584. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  10585. PRIVATE_KEY_LOCK();
  10586. }
  10587. if (ret == 0) {
  10588. /* Return the size of the encoding. */
  10589. ret = sz;
  10590. }
  10591. return ret;
  10592. #endif
  10593. }
  10594. /* Encode the public part of an ECC key in a DER.
  10595. *
  10596. * Pass NULL for output to get the size of the encoding.
  10597. *
  10598. * @param [in] key ECC key object.
  10599. * @param [out] output Buffer to hold DER encoding.
  10600. * @param [in] inLen Size of buffer in bytes.
  10601. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  10602. * @return Size of encoded data in bytes on success.
  10603. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10604. * @return MEMORY_E when dynamic memory allocation failed.
  10605. */
  10606. WOLFSSL_ABI
  10607. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  10608. int with_AlgCurve)
  10609. {
  10610. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  10611. }
  10612. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  10613. int with_AlgCurve, int comp)
  10614. {
  10615. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  10616. }
  10617. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  10618. {
  10619. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  10620. }
  10621. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10622. #ifdef WOLFSSL_ASN_TEMPLATE
  10623. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  10624. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  10625. * RFC 8410, 4 - Subject Public Key Fields
  10626. */
  10627. static const ASNItem edPubKeyASN[] = {
  10628. /* SubjectPublicKeyInfo */
  10629. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10630. /* AlgorithmIdentifier */
  10631. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10632. /* Ed25519/Ed448 OID */
  10633. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  10634. /* Public key stream */
  10635. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10636. };
  10637. enum {
  10638. EDPUBKEYASN_IDX_SEQ = 0,
  10639. EDPUBKEYASN_IDX_ALGOID_SEQ,
  10640. EDPUBKEYASN_IDX_ALGOID_OID,
  10641. EDPUBKEYASN_IDX_PUBKEY
  10642. };
  10643. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  10644. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  10645. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  10646. #endif /* WOLFSSL_ASN_TEMPLATE */
  10647. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  10648. /* Build ASN.1 formatted public key based on RFC 8410
  10649. *
  10650. * Pass NULL for output to get the size of the encoding.
  10651. *
  10652. * @param [in] pubKey public key buffer
  10653. * @param [in] pubKeyLen public key buffer length
  10654. * @param [out] output Buffer to put encoded data in (optional)
  10655. * @param [in] outLen Size of buffer in bytes
  10656. * @param [in] keyType is "enum Key_Sum" like ED25519k
  10657. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  10658. * @return Size of encoded data in bytes on success
  10659. * @return BAD_FUNC_ARG when key is NULL.
  10660. * @return MEMORY_E when dynamic memory allocation failed.
  10661. */
  10662. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  10663. byte* output, word32 outLen, int keyType, int withHeader)
  10664. {
  10665. int ret = 0;
  10666. #ifndef WOLFSSL_ASN_TEMPLATE
  10667. word32 idx = 0;
  10668. word32 seqDataSz = 0;
  10669. word32 sz;
  10670. #else
  10671. int sz = 0;
  10672. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  10673. #endif
  10674. if (pubKey == NULL) {
  10675. return BAD_FUNC_ARG;
  10676. }
  10677. #ifndef WOLFSSL_ASN_TEMPLATE
  10678. /* calculate size */
  10679. if (withHeader) {
  10680. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  10681. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  10682. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  10683. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  10684. }
  10685. else {
  10686. sz = pubKeyLen;
  10687. }
  10688. /* checkout output size */
  10689. if (output != NULL && sz > outLen) {
  10690. ret = BUFFER_E;
  10691. }
  10692. /* headers */
  10693. if (ret == 0 && output != NULL && withHeader) {
  10694. /* sequence */
  10695. idx = SetSequence(seqDataSz, output);
  10696. /* algo */
  10697. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  10698. /* bit string */
  10699. idx += SetBitString(pubKeyLen, 0, output + idx);
  10700. }
  10701. if (ret == 0 && output != NULL) {
  10702. /* pub */
  10703. XMEMCPY(output + idx, pubKey, pubKeyLen);
  10704. idx += pubKeyLen;
  10705. sz = idx;
  10706. }
  10707. if (ret == 0) {
  10708. ret = (int)sz;
  10709. }
  10710. #else
  10711. if (withHeader) {
  10712. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  10713. if (ret == 0) {
  10714. /* Set the OID. */
  10715. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  10716. oidKeyType);
  10717. /* Leave space for public point. */
  10718. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  10719. /* Calculate size of public key encoding. */
  10720. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  10721. }
  10722. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  10723. ret = BUFFER_E;
  10724. }
  10725. if ((ret == 0) && (output != NULL)) {
  10726. /* Encode public key. */
  10727. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  10728. /* Set location to encode public point. */
  10729. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  10730. }
  10731. FREE_ASNSETDATA(dataASN, NULL);
  10732. }
  10733. else if ((output != NULL) && (pubKeyLen > outLen)) {
  10734. ret = BUFFER_E;
  10735. }
  10736. else if (ret == 0) {
  10737. sz = (int)pubKeyLen;
  10738. }
  10739. if ((ret == 0) && (output != NULL)) {
  10740. /* Put public key into space provided. */
  10741. XMEMCPY(output, pubKey, pubKeyLen);
  10742. }
  10743. if (ret == 0) {
  10744. ret = sz;
  10745. }
  10746. #endif /* WOLFSSL_ASN_TEMPLATE */
  10747. return ret;
  10748. }
  10749. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  10750. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  10751. /* Encode the public part of an Ed25519 key in DER.
  10752. *
  10753. * Pass NULL for output to get the size of the encoding.
  10754. *
  10755. * @param [in] key Ed25519 key object.
  10756. * @param [out] output Buffer to put encoded data in.
  10757. * @param [in] outLen Size of buffer in bytes.
  10758. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10759. * @return Size of encoded data in bytes on success.
  10760. * @return BAD_FUNC_ARG when key is NULL.
  10761. * @return MEMORY_E when dynamic memory allocation failed.
  10762. */
  10763. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  10764. int withAlg)
  10765. {
  10766. int ret;
  10767. byte pubKey[ED25519_PUB_KEY_SIZE];
  10768. word32 pubKeyLen = (word32)sizeof(pubKey);
  10769. if (key == NULL) {
  10770. return BAD_FUNC_ARG;
  10771. }
  10772. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  10773. if (ret == 0) {
  10774. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10775. ED25519k, withAlg);
  10776. }
  10777. return ret;
  10778. }
  10779. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  10780. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  10781. /* Encode the public part of an Ed448 key in DER.
  10782. *
  10783. * Pass NULL for output to get the size of the encoding.
  10784. *
  10785. * @param [in] key Ed448 key object.
  10786. * @param [out] output Buffer to put encoded data in.
  10787. * @param [in] outLen Size of buffer in bytes.
  10788. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10789. * @return Size of encoded data in bytes on success.
  10790. * @return BAD_FUNC_ARG when key is NULL.
  10791. * @return MEMORY_E when dynamic memory allocation failed.
  10792. */
  10793. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  10794. int withAlg)
  10795. {
  10796. int ret;
  10797. byte pubKey[ED448_PUB_KEY_SIZE];
  10798. word32 pubKeyLen = (word32)sizeof(pubKey);
  10799. if (key == NULL) {
  10800. return BAD_FUNC_ARG;
  10801. }
  10802. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  10803. if (ret == 0) {
  10804. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10805. ED448k, withAlg);
  10806. }
  10807. return ret;
  10808. }
  10809. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  10810. #if !defined(NO_RSA) && !defined(NO_CERTS)
  10811. #ifdef WOLFSSL_ASN_TEMPLATE
  10812. /* ASN.1 template for header before RSA key in certificate. */
  10813. static const ASNItem rsaCertKeyASN[] = {
  10814. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10815. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10816. };
  10817. enum {
  10818. RSACERTKEYASN_IDX_STR = 0,
  10819. RSACERTKEYASN_IDX_SEQ
  10820. };
  10821. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10822. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10823. #endif
  10824. /* Store RSA key pointer and length in certificate object.
  10825. *
  10826. * @param [in, out] cert Certificate object.
  10827. * @param [in] source Buffer containing encoded key.
  10828. * @param [in, out] srcIdx On in, start of RSA key data.
  10829. * On out, start of element after RSA key data.
  10830. * @param [in] maxIdx Maximum index of key data.
  10831. * @return 0 on success.
  10832. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10833. * is invalid.
  10834. * @return BUFFER_E when data in buffer is too small.
  10835. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10836. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10837. * non-zero length.
  10838. */
  10839. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10840. word32 maxIdx)
  10841. {
  10842. #ifndef WOLFSSL_ASN_TEMPLATE
  10843. int length;
  10844. int pubLen;
  10845. word32 pubIdx;
  10846. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10847. return ASN_PARSE_E;
  10848. pubIdx = *srcIdx;
  10849. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10850. return ASN_PARSE_E;
  10851. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  10852. cert->sigCtx.CertAtt.pubkey_n_start =
  10853. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10854. #endif
  10855. cert->pubKeySize = (word32)pubLen;
  10856. cert->publicKey = source + pubIdx;
  10857. #ifdef WOLFSSL_MAXQ10XX_TLS
  10858. cert->publicKeyIndex = pubIdx;
  10859. #endif
  10860. *srcIdx += (word32)length;
  10861. #ifdef HAVE_OCSP
  10862. return CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10863. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10864. #else
  10865. return 0;
  10866. #endif
  10867. #else
  10868. ASNGetData dataASN[rsaCertKeyASN_Length];
  10869. int ret;
  10870. /* No dynamic data. */
  10871. XMEMSET(dataASN, 0, sizeof(dataASN));
  10872. /* Decode the header before the key data. */
  10873. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10874. srcIdx, maxIdx);
  10875. if (ret == 0) {
  10876. /* Store the pointer and length in certificate object starting at
  10877. * SEQUENCE. */
  10878. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10879. &cert->publicKey, &cert->pubKeySize);
  10880. #ifdef WOLFSSL_MAXQ10XX_TLS
  10881. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10882. #endif
  10883. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  10884. /* Start of SEQUENCE. */
  10885. cert->sigCtx.CertAtt.pubkey_n_start =
  10886. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10887. #endif
  10888. #ifdef HAVE_OCSP
  10889. /* Calculate the hash of the public key for OCSP. */
  10890. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10891. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10892. #endif
  10893. }
  10894. return ret;
  10895. #endif /* WOLFSSL_ASN_TEMPLATE */
  10896. }
  10897. #endif /* !NO_RSA && !NO_CERTS */
  10898. #if defined(HAVE_ECC) && !defined(NO_CERTS)
  10899. #ifdef WOLFSSL_ASN_TEMPLATE
  10900. /* ASN.1 template for header before ECC key in certificate. */
  10901. static const ASNItem eccCertKeyASN[] = {
  10902. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10903. /* Algo parameters */
  10904. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10905. /* Subject public key */
  10906. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10907. };
  10908. enum {
  10909. ECCCERTKEYASN_IDX_OID = 0,
  10910. ECCCERTKEYASN_IDX_PARAMS,
  10911. ECCCERTKEYASN_IDX_SUBJPUBKEY
  10912. };
  10913. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10914. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10915. #endif /* WOLFSSL_ASN_TEMPLATE */
  10916. /* Store public ECC key in certificate object.
  10917. *
  10918. * Parse parameters and store public key data.
  10919. *
  10920. * @param [in, out] cert Certificate object.
  10921. * @param [in] source Buffer containing encoded key.
  10922. * @param [in, out] srcIdx On in, start of ECC key data.
  10923. * On out, start of element after ECC key data.
  10924. * @param [in] maxIdx Maximum index of key data.
  10925. * @param [in] pubKey Buffer holding encoded public key.
  10926. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10927. * @return 0 on success.
  10928. * @return BAD_FUNC_ARG when pubKey is NULL.
  10929. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10930. * is invalid.
  10931. * @return BUFFER_E when data in buffer is too small.
  10932. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10933. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10934. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10935. * non-zero length.
  10936. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10937. */
  10938. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10939. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10940. {
  10941. #ifndef WOLFSSL_ASN_TEMPLATE
  10942. int ret;
  10943. word32 localIdx;
  10944. byte* publicKey;
  10945. byte tag;
  10946. int length;
  10947. if (pubKey == NULL) {
  10948. return BAD_FUNC_ARG;
  10949. }
  10950. localIdx = *srcIdx;
  10951. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10952. return ASN_PARSE_E;
  10953. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10954. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10955. maxIdx) < 0)
  10956. return ASN_PARSE_E;
  10957. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10958. return ECC_CURVE_OID_E;
  10959. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10960. cert->sigCtx.CertAtt.curve_id = ret;
  10961. #else
  10962. (void)ret;
  10963. #endif
  10964. /* key header */
  10965. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10966. if (ret != 0)
  10967. return ret;
  10968. #if defined(WOLFSSL_RENESAS_FSPSM_TLS) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10969. cert->sigCtx.CertAtt.pubkey_n_start =
  10970. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10971. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10972. cert->sigCtx.CertAtt.pubkey_e_start +=
  10973. cert->sigCtx.CertAtt.pubkey_n_len;
  10974. cert->sigCtx.CertAtt.pubkey_e_len =
  10975. cert->sigCtx.CertAtt.pubkey_n_len;
  10976. #endif
  10977. #ifdef WOLFSSL_MAXQ10XX_TLS
  10978. cert->publicKeyIndex = *srcIdx + 1;
  10979. #endif
  10980. #ifdef HAVE_OCSP
  10981. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10982. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10983. if (ret != 0)
  10984. return ret;
  10985. #endif
  10986. *srcIdx += (word32)length;
  10987. }
  10988. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10989. if (publicKey == NULL)
  10990. return MEMORY_E;
  10991. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10992. cert->publicKey = publicKey;
  10993. cert->pubKeyStored = 1;
  10994. cert->pubKeySize = pubKeyLen;
  10995. return 0;
  10996. #else
  10997. int ret = 0;
  10998. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10999. byte* publicKey;
  11000. /* Validate parameters. */
  11001. if (pubKey == NULL) {
  11002. ret = BAD_FUNC_ARG;
  11003. }
  11004. /* Clear dynamic data and check OID is a curve. */
  11005. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  11006. if (ret == 0) {
  11007. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  11008. /* Parse ECC public key header. */
  11009. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  11010. source, srcIdx, maxIdx);
  11011. }
  11012. if (ret == 0) {
  11013. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  11014. /* Store curve OID. */
  11015. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  11016. }
  11017. /* Ignore explicit parameters. */
  11018. #ifdef WOLFSSL_MAXQ10XX_TLS
  11019. cert->publicKeyIndex =
  11020. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  11021. + 1;
  11022. #endif
  11023. #ifdef HAVE_OCSP
  11024. /* Calculate the hash of the subject public key for OCSP. */
  11025. ret = CalcHashId_ex(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  11026. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  11027. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  11028. }
  11029. if (ret == 0) {
  11030. #endif
  11031. /* Store public key data length. */
  11032. cert->pubKeySize = pubKeyLen;
  11033. /* Must allocated space for key.
  11034. * Don't memcpy into constant pointer so use temp. */
  11035. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  11036. DYNAMIC_TYPE_PUBLIC_KEY);
  11037. if (publicKey == NULL) {
  11038. ret = MEMORY_E;
  11039. }
  11040. else {
  11041. /* Copy in whole public key and store pointer. */
  11042. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  11043. cert->publicKey = publicKey;
  11044. /* Indicate publicKey needs to be freed. */
  11045. cert->pubKeyStored = 1;
  11046. }
  11047. }
  11048. FREE_ASNGETDATA(dataASN, cert->heap);
  11049. return ret;
  11050. #endif /* WOLFSSL_ASN_TEMPLATE */
  11051. }
  11052. #endif /* HAVE_ECC && !NO_CERTS */
  11053. #ifndef NO_CERTS
  11054. #if !defined(NO_DSA)
  11055. #ifdef WOLFSSL_ASN_TEMPLATE
  11056. /* ASN.1 template for DSA key in certificate.
  11057. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  11058. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  11059. */
  11060. static const ASNItem dsaCertKeyASN[] = {
  11061. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  11062. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11063. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11064. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11065. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  11066. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  11067. };
  11068. /* Number of items in ASN.1 template for DSA key in certificate. */
  11069. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  11070. #endif /* WOLFSSL_ASN_TEMPLATE */
  11071. /* Parse DSA parameters to ensure valid.
  11072. *
  11073. * @param [in] source Buffer containing encoded key.
  11074. * @param [in, out] srcIdx On in, start of DSA key data.
  11075. * On out, start of element after DSA key data.
  11076. * @param [in] maxIdx Maximum index of key data.
  11077. * @param [in] heap Dynamic memory hint.
  11078. * @return 0 on success.
  11079. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11080. * is invalid.
  11081. * @return BUFFER_E when data in buffer is too small.
  11082. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11083. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  11084. * non-zero length.
  11085. */
  11086. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  11087. void* heap)
  11088. {
  11089. #ifndef WOLFSSL_ASN_TEMPLATE
  11090. int ret;
  11091. int length;
  11092. (void)heap;
  11093. ret = GetSequence(source, srcIdx, &length, maxIdx);
  11094. if (ret < 0)
  11095. return ret;
  11096. ret = SkipInt(source, srcIdx, maxIdx);
  11097. if (ret != 0)
  11098. return ret;
  11099. ret = SkipInt(source, srcIdx, maxIdx);
  11100. if (ret != 0)
  11101. return ret;
  11102. ret = SkipInt(source, srcIdx, maxIdx);
  11103. if (ret != 0)
  11104. return ret;
  11105. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  11106. if (ret != 0)
  11107. return ret;
  11108. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  11109. if (ret != 0)
  11110. return ASN_PARSE_E;
  11111. *srcIdx += (word32)length;
  11112. return 0;
  11113. #else
  11114. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  11115. int ret = 0;
  11116. (void)heap;
  11117. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  11118. if (ret == 0) {
  11119. /* Parse the DSA key data to ensure valid. */
  11120. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  11121. source, srcIdx, maxIdx);
  11122. }
  11123. FREE_ASNGETDATA(dataASN, heap);
  11124. return ret;
  11125. #endif /* WOLFSSL_ASN_TEMPLATE */
  11126. }
  11127. #endif /* !NO_DSA */
  11128. /* Decode the SubjectPublicKeyInfo block in a certificate.
  11129. *
  11130. * Stores the public key in fields of the certificate object.
  11131. * Validates the BER/DER items and does not store in a key object.
  11132. *
  11133. * @param [in, out] cert Decoded certificate object.
  11134. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  11135. * @param [in, out] inOutIdx On in, start of public key.
  11136. * On out, start of ASN.1 item after public key.
  11137. * @param [in] maxIdx Maximum index of key data.
  11138. * @return 0 on success.
  11139. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11140. * is invalid.
  11141. * @return BUFFER_E when data in buffer is too small.
  11142. */
  11143. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  11144. word32 maxIdx)
  11145. {
  11146. word32 srcIdx = *inOutIdx;
  11147. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11148. int pubLen;
  11149. #endif
  11150. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11151. int pubIdx = (int)srcIdx;
  11152. #endif
  11153. int ret = 0;
  11154. int length;
  11155. /* Validate parameters. */
  11156. if (source == NULL) {
  11157. return ASN_PARSE_E;
  11158. }
  11159. #ifndef WOLFSSL_ASN_TEMPLATE
  11160. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  11161. #else
  11162. /* Get SEQUENCE and expect all data to be accounted for. */
  11163. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  11164. #endif
  11165. {
  11166. return ASN_PARSE_E;
  11167. }
  11168. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11169. pubLen = (int)srcIdx - pubIdx + length;
  11170. #endif
  11171. maxIdx = srcIdx + (word32)length;
  11172. /* Decode the algorithm identifier for the key. */
  11173. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  11174. return ASN_PARSE_E;
  11175. }
  11176. (void)length;
  11177. /* Parse each type of public key. */
  11178. switch (cert->keyOID) {
  11179. #ifndef NO_RSA
  11180. #ifdef WC_RSA_PSS
  11181. case RSAPSSk:
  11182. if (srcIdx != maxIdx &&
  11183. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  11184. word32 seqIdx = srcIdx;
  11185. int seqLen;
  11186. /* Not set when -1. */
  11187. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  11188. int mgf = -1;
  11189. int saltLen = 0;
  11190. /* Defaults for sig algorithm parameters. */
  11191. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  11192. int sigMgf = WC_MGF1SHA1;
  11193. int sigSaltLen = 20;
  11194. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  11195. return ASN_PARSE_E;
  11196. }
  11197. /* Get the pubic key parameters. */
  11198. ret = DecodeRsaPssParams(source + seqIdx,
  11199. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  11200. if (ret != 0) {
  11201. return ASN_PARSE_E;
  11202. }
  11203. /* Get the signature parameters. */
  11204. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  11205. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  11206. if (ret != 0) {
  11207. return ASN_PARSE_E;
  11208. }
  11209. /* Validated signature params match public key params. */
  11210. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  11211. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  11212. return ASN_PARSE_E;
  11213. }
  11214. if (mgf != -1 && mgf != sigMgf) {
  11215. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  11216. return ASN_PARSE_E;
  11217. }
  11218. if (saltLen > sigSaltLen) {
  11219. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  11220. return ASN_PARSE_E;
  11221. }
  11222. srcIdx += (word32)seqLen;
  11223. }
  11224. FALL_THROUGH;
  11225. #endif /* WC_RSA_PSS */
  11226. case RSAk:
  11227. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  11228. break;
  11229. #endif /* NO_RSA */
  11230. #ifdef HAVE_ECC
  11231. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11232. case SM2k:
  11233. #endif
  11234. case ECDSAk:
  11235. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  11236. (word32)pubLen);
  11237. break;
  11238. #endif /* HAVE_ECC */
  11239. #ifdef HAVE_ED25519
  11240. case ED25519k:
  11241. cert->pkCurveOID = ED25519k;
  11242. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11243. break;
  11244. #endif /* HAVE_ED25519 */
  11245. #ifdef HAVE_ED448
  11246. case ED448k:
  11247. cert->pkCurveOID = ED448k;
  11248. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11249. break;
  11250. #endif /* HAVE_ED448 */
  11251. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  11252. #ifdef HAVE_FALCON
  11253. case FALCON_LEVEL1k:
  11254. cert->pkCurveOID = FALCON_LEVEL1k;
  11255. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11256. break;
  11257. case FALCON_LEVEL5k:
  11258. cert->pkCurveOID = FALCON_LEVEL5k;
  11259. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11260. break;
  11261. #endif /* HAVE_FALCON */
  11262. #ifdef HAVE_DILITHIUM
  11263. case DILITHIUM_LEVEL2k:
  11264. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  11265. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11266. break;
  11267. case DILITHIUM_LEVEL3k:
  11268. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  11269. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11270. break;
  11271. case DILITHIUM_LEVEL5k:
  11272. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  11273. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11274. break;
  11275. #endif /* HAVE_DILITHIUM */
  11276. #ifdef HAVE_SPHINCS
  11277. case SPHINCS_FAST_LEVEL1k:
  11278. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  11279. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11280. break;
  11281. case SPHINCS_FAST_LEVEL3k:
  11282. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  11283. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11284. break;
  11285. case SPHINCS_FAST_LEVEL5k:
  11286. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  11287. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11288. break;
  11289. case SPHINCS_SMALL_LEVEL1k:
  11290. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  11291. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11292. break;
  11293. case SPHINCS_SMALL_LEVEL3k:
  11294. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  11295. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11296. break;
  11297. case SPHINCS_SMALL_LEVEL5k:
  11298. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  11299. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11300. break;
  11301. #endif /* HAVE_SPHINCS */
  11302. #endif /* HAVE_PQC */
  11303. #ifndef NO_DSA
  11304. case DSAk:
  11305. cert->publicKey = source + pubIdx;
  11306. cert->pubKeySize = (word32)pubLen;
  11307. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  11308. break;
  11309. #endif /* NO_DSA */
  11310. default:
  11311. WOLFSSL_MSG("Unknown or not compiled in key OID");
  11312. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  11313. ret = ASN_UNKNOWN_OID_E;
  11314. }
  11315. /* Return index after public key. */
  11316. *inOutIdx = srcIdx;
  11317. /* Return error code. */
  11318. return ret;
  11319. }
  11320. #endif
  11321. /* Return the hash algorithm to use with the signature algorithm.
  11322. *
  11323. * @param [in] oidSum Signature id.
  11324. * @return Hash algorithm id.
  11325. */
  11326. int HashIdAlg(word32 oidSum)
  11327. {
  11328. (void)oidSum;
  11329. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11330. if (oidSum == CTC_SM3wSM2) {
  11331. return WC_SM3;
  11332. }
  11333. if (oidSum == SM2k) {
  11334. return WC_SM3;
  11335. }
  11336. #endif
  11337. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11338. return WC_SHA256;
  11339. #else
  11340. return WC_SHA;
  11341. #endif
  11342. }
  11343. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11344. *
  11345. * @param [in] data Data to hash.
  11346. * @param [in] len Length of data to hash.
  11347. * @param [out] hash Buffer to hold hash.
  11348. * @return 0 on success.
  11349. * @return MEMORY_E when dynamic memory allocation fails.
  11350. */
  11351. int CalcHashId(const byte* data, word32 len, byte* hash)
  11352. {
  11353. /* Use default hash algorithm. */
  11354. return CalcHashId_ex(data, len, hash,
  11355. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11356. WC_SHA256
  11357. #else
  11358. WC_SHA
  11359. #endif
  11360. );
  11361. }
  11362. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11363. *
  11364. * @param [in] data Data to hash.
  11365. * @param [in] len Length of data to hash.
  11366. * @param [out] hash Buffer to hold hash.
  11367. * @return 0 on success.
  11368. * @return MEMORY_E when dynamic memory allocation fails.
  11369. */
  11370. int CalcHashId_ex(const byte* data, word32 len, byte* hash, int hashAlg)
  11371. {
  11372. int ret;
  11373. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11374. if (hashAlg == WC_SM3) {
  11375. ret = wc_Sm3Hash(data, len, hash);
  11376. }
  11377. else
  11378. #endif
  11379. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11380. if (hashAlg == WC_SHA256) {
  11381. ret = wc_Sha256Hash(data, len, hash);
  11382. }
  11383. else
  11384. #elif !defined(NO_SHA)
  11385. if (hashAlg == WC_SHA) {
  11386. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11387. XMEMSET(hash + WC_SHA_DIGEST_SIZE, 0, KEYID_SIZE - WC_SHA_DIGEST_SIZE);
  11388. #endif
  11389. ret = wc_ShaHash(data, len, hash);
  11390. }
  11391. else
  11392. #else
  11393. (void)data;
  11394. (void)len;
  11395. (void)hash;
  11396. #endif
  11397. {
  11398. ret = NOT_COMPILED_IN;
  11399. }
  11400. return ret;
  11401. }
  11402. #ifndef NO_CERTS
  11403. /* Get the hash of the id using the SHA-1 or SHA-256.
  11404. *
  11405. * If the id is not the length of the hash, then hash it.
  11406. *
  11407. * @param [in] id Id to get hash for.
  11408. * @param [in] len Length of id in bytes.
  11409. * @param [out] hash Buffer to hold hash.
  11410. * @return 0 on success.
  11411. * @return MEMORY_E when dynamic memory allocation fails.
  11412. */
  11413. static int GetHashId(const byte* id, int length, byte* hash, int hashAlg)
  11414. {
  11415. int ret;
  11416. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11417. if (length == wc_HashGetDigestSize(wc_HashTypeConvert(hashAlg)))
  11418. #else
  11419. if (length == KEYID_SIZE)
  11420. #endif
  11421. {
  11422. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11423. XMEMSET(hash + length, 0, KEYID_SIZE - length);
  11424. #endif
  11425. XMEMCPY(hash, id, (size_t)length);
  11426. ret = 0;
  11427. }
  11428. else {
  11429. ret = CalcHashId_ex(id, (word32)length, hash, hashAlg);
  11430. }
  11431. return ret;
  11432. }
  11433. #endif /* !NO_CERTS */
  11434. #ifdef WOLFSSL_ASN_TEMPLATE
  11435. /* Id for email address. */
  11436. #define ASN_EMAIL 0x100
  11437. /* Id for domain component. */
  11438. #define ASN_DC 0x102
  11439. /* Id for jurisdiction country. */
  11440. #define ASN_JURIS_C 0x203
  11441. /* Id for jurisdiction state. */
  11442. #define ASN_JURIS_ST 0x202
  11443. /* Set the string for a name component into the subject name. */
  11444. #define SetCertNameSubject(cert, id, val) \
  11445. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  11446. /* Set the string length for a name component into the subject name. */
  11447. #define SetCertNameSubjectLen(cert, id, val) \
  11448. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  11449. /* Set the encoding for a name component into the subject name. */
  11450. #define SetCertNameSubjectEnc(cert, id, val) \
  11451. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  11452. /* Get the string of a name component from the subject name. */
  11453. #define GetCertNameSubjectStr(id) \
  11454. (certNameSubject[(id) - 3].str)
  11455. /* Get the string length of a name component from the subject name. */
  11456. #define GetCertNameSubjectStrLen(id) \
  11457. (certNameSubject[(id) - 3].strLen)
  11458. /* Get the NID of a name component from the subject name. */
  11459. #define GetCertNameSubjectNID(id) \
  11460. (certNameSubject[(id) - 3].nid)
  11461. #define ValidCertNameSubject(id) \
  11462. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  11463. (certNameSubject[(id) - 3].strLen > 0))
  11464. /* Mapping of certificate name component to useful information. */
  11465. typedef struct CertNameData {
  11466. /* Type string of name component. */
  11467. const char* str;
  11468. /* Length of type string of name component. */
  11469. byte strLen;
  11470. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11471. /* Offset of data in subject name component. */
  11472. size_t data;
  11473. /* Offset of length in subject name component. */
  11474. size_t len;
  11475. /* Offset of encoding in subject name component. */
  11476. size_t enc;
  11477. #endif
  11478. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11479. /* NID of type for subject name component. */
  11480. int nid;
  11481. #endif
  11482. } CertNameData;
  11483. /* List of data for common name components. */
  11484. static const CertNameData certNameSubject[] = {
  11485. /* Common Name */
  11486. {
  11487. "/CN=", 4,
  11488. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11489. OFFSETOF(DecodedCert, subjectCN),
  11490. OFFSETOF(DecodedCert, subjectCNLen),
  11491. OFFSETOF(DecodedCert, subjectCNEnc),
  11492. #endif
  11493. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11494. NID_commonName
  11495. #endif
  11496. },
  11497. /* Surname */
  11498. {
  11499. "/SN=", 4,
  11500. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11501. OFFSETOF(DecodedCert, subjectSN),
  11502. OFFSETOF(DecodedCert, subjectSNLen),
  11503. OFFSETOF(DecodedCert, subjectSNEnc),
  11504. #endif
  11505. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11506. NID_surname
  11507. #endif
  11508. },
  11509. /* Serial Number */
  11510. {
  11511. "/serialNumber=", 14,
  11512. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11513. OFFSETOF(DecodedCert, subjectSND),
  11514. OFFSETOF(DecodedCert, subjectSNDLen),
  11515. OFFSETOF(DecodedCert, subjectSNDEnc),
  11516. #endif
  11517. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11518. NID_serialNumber
  11519. #endif
  11520. },
  11521. /* Country Name */
  11522. {
  11523. "/C=", 3,
  11524. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11525. OFFSETOF(DecodedCert, subjectC),
  11526. OFFSETOF(DecodedCert, subjectCLen),
  11527. OFFSETOF(DecodedCert, subjectCEnc),
  11528. #endif
  11529. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11530. NID_countryName
  11531. #endif
  11532. },
  11533. /* Locality Name */
  11534. {
  11535. "/L=", 3,
  11536. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11537. OFFSETOF(DecodedCert, subjectL),
  11538. OFFSETOF(DecodedCert, subjectLLen),
  11539. OFFSETOF(DecodedCert, subjectLEnc),
  11540. #endif
  11541. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11542. NID_localityName
  11543. #endif
  11544. },
  11545. /* State Name */
  11546. {
  11547. "/ST=", 4,
  11548. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11549. OFFSETOF(DecodedCert, subjectST),
  11550. OFFSETOF(DecodedCert, subjectSTLen),
  11551. OFFSETOF(DecodedCert, subjectSTEnc),
  11552. #endif
  11553. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11554. NID_stateOrProvinceName
  11555. #endif
  11556. },
  11557. /* Street Address */
  11558. {
  11559. "/street=", 8,
  11560. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11561. OFFSETOF(DecodedCert, subjectStreet),
  11562. OFFSETOF(DecodedCert, subjectStreetLen),
  11563. OFFSETOF(DecodedCert, subjectStreetEnc),
  11564. #endif
  11565. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11566. NID_streetAddress
  11567. #endif
  11568. },
  11569. /* Organization Name */
  11570. {
  11571. "/O=", 3,
  11572. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11573. OFFSETOF(DecodedCert, subjectO),
  11574. OFFSETOF(DecodedCert, subjectOLen),
  11575. OFFSETOF(DecodedCert, subjectOEnc),
  11576. #endif
  11577. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11578. NID_organizationName
  11579. #endif
  11580. },
  11581. /* Organization Unit Name */
  11582. {
  11583. "/OU=", 4,
  11584. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11585. OFFSETOF(DecodedCert, subjectOU),
  11586. OFFSETOF(DecodedCert, subjectOULen),
  11587. OFFSETOF(DecodedCert, subjectOUEnc),
  11588. #endif
  11589. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11590. NID_organizationalUnitName
  11591. #endif
  11592. },
  11593. /* Title */
  11594. {
  11595. NULL, 0,
  11596. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11597. 0,
  11598. 0,
  11599. 0,
  11600. #endif
  11601. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11602. 0,
  11603. #endif
  11604. },
  11605. /* Undefined */
  11606. {
  11607. NULL, 0,
  11608. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11609. 0,
  11610. 0,
  11611. 0,
  11612. #endif
  11613. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11614. 0,
  11615. #endif
  11616. },
  11617. /* Undefined */
  11618. {
  11619. NULL, 0,
  11620. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11621. 0,
  11622. 0,
  11623. 0,
  11624. #endif
  11625. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11626. 0,
  11627. #endif
  11628. },
  11629. /* Business Category */
  11630. {
  11631. "/businessCategory=", 18,
  11632. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11633. OFFSETOF(DecodedCert, subjectBC),
  11634. OFFSETOF(DecodedCert, subjectBCLen),
  11635. OFFSETOF(DecodedCert, subjectBCEnc),
  11636. #endif
  11637. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11638. NID_businessCategory
  11639. #endif
  11640. },
  11641. /* Undefined */
  11642. {
  11643. NULL, 0,
  11644. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11645. 0,
  11646. 0,
  11647. 0,
  11648. #endif
  11649. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11650. 0,
  11651. #endif
  11652. },
  11653. /* Postal Code */
  11654. {
  11655. "/postalCode=", 12,
  11656. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11657. OFFSETOF(DecodedCert, subjectPC),
  11658. OFFSETOF(DecodedCert, subjectPCLen),
  11659. OFFSETOF(DecodedCert, subjectPCEnc),
  11660. #endif
  11661. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11662. NID_postalCode
  11663. #endif
  11664. },
  11665. /* User Id */
  11666. {
  11667. "/userid=", 8,
  11668. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11669. OFFSETOF(DecodedCert, subjectUID),
  11670. OFFSETOF(DecodedCert, subjectUIDLen),
  11671. OFFSETOF(DecodedCert, subjectUIDEnc),
  11672. #endif
  11673. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11674. NID_userId
  11675. #endif
  11676. },
  11677. #ifdef WOLFSSL_CERT_NAME_ALL
  11678. /* Name, id 41 */
  11679. {
  11680. "/N=", 3,
  11681. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11682. OFFSETOF(DecodedCert, subjectN),
  11683. OFFSETOF(DecodedCert, subjectNLen),
  11684. OFFSETOF(DecodedCert, subjectNEnc),
  11685. #endif
  11686. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11687. NID_name
  11688. #endif
  11689. },
  11690. /* Given Name, id 42 */
  11691. {
  11692. "/GN=", 4,
  11693. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11694. OFFSETOF(DecodedCert, subjectGN),
  11695. OFFSETOF(DecodedCert, subjectGNLen),
  11696. OFFSETOF(DecodedCert, subjectGNEnc),
  11697. #endif
  11698. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11699. NID_givenName
  11700. #endif
  11701. },
  11702. /* initials, id 43 */
  11703. {
  11704. "/initials=", 10,
  11705. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11706. OFFSETOF(DecodedCert, subjectI),
  11707. OFFSETOF(DecodedCert, subjectILen),
  11708. OFFSETOF(DecodedCert, subjectIEnc),
  11709. #endif
  11710. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11711. NID_initials
  11712. #endif
  11713. },
  11714. /* DN Qualifier Name, id 46 */
  11715. {
  11716. "/dnQualifier=", 13,
  11717. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11718. OFFSETOF(DecodedCert, subjectDNQ),
  11719. OFFSETOF(DecodedCert, subjectDNQLen),
  11720. OFFSETOF(DecodedCert, subjectDNQEnc),
  11721. #endif
  11722. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11723. NID_dnQualifier
  11724. #endif
  11725. },
  11726. #endif /* WOLFSSL_CERT_NAME_ALL */
  11727. };
  11728. static const int certNameSubjectSz =
  11729. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11730. /* ASN.1 template for an RDN.
  11731. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11732. */
  11733. static const ASNItem rdnASN[] = {
  11734. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11735. /* AttributeTypeAndValue */
  11736. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11737. /* AttributeType */
  11738. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11739. /* AttributeValue: Choice of tags - rdnChoice. */
  11740. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11741. };
  11742. enum {
  11743. RDNASN_IDX_SET = 0,
  11744. RDNASN_IDX_ATTR_SEQ,
  11745. RDNASN_IDX_ATTR_TYPE,
  11746. RDNASN_IDX_ATTR_VAL
  11747. };
  11748. /* Number of items in ASN.1 template for an RDN. */
  11749. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11750. /* Supported types of encodings (tags) for RDN strings.
  11751. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11752. * (IA5 String not listed in RFC but required for alternative types)
  11753. */
  11754. static const byte rdnChoice[] = {
  11755. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11756. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11757. };
  11758. #endif
  11759. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11760. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11761. * DNS entry
  11762. * return 0 on success
  11763. */
  11764. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11765. {
  11766. int ret = 0;
  11767. size_t nameSz;
  11768. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11769. unsigned char* ip;
  11770. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11771. return BAD_FUNC_ARG;
  11772. }
  11773. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11774. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11775. WOLFSSL_MSG("Unexpected IP size");
  11776. return BAD_FUNC_ARG;
  11777. }
  11778. ip = (unsigned char*)entry->name;
  11779. /* store IP addresses as a string */
  11780. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11781. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11782. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11783. >= (int)sizeof(tmpName))
  11784. {
  11785. WOLFSSL_MSG("IP buffer overrun");
  11786. return BUFFER_E;
  11787. }
  11788. }
  11789. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11790. size_t i;
  11791. for (i = 0; i < 8; i++) {
  11792. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11793. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11794. (i < 7) ? ":" : "")
  11795. >= (int)sizeof(tmpName))
  11796. {
  11797. WOLFSSL_MSG("IPv6 buffer overrun");
  11798. return BUFFER_E;
  11799. }
  11800. }
  11801. }
  11802. nameSz = XSTRLEN(tmpName);
  11803. entry->ipString = (char*)XMALLOC(nameSz + 1, heap,
  11804. DYNAMIC_TYPE_ALTNAME);
  11805. if (entry->ipString == NULL) {
  11806. ret = MEMORY_E;
  11807. }
  11808. if (ret == 0) {
  11809. XMEMCPY(entry->ipString, tmpName, nameSz);
  11810. entry->ipString[nameSz] = '\0';
  11811. }
  11812. (void)heap;
  11813. return ret;
  11814. }
  11815. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11816. #if defined(OPENSSL_ALL)
  11817. /* used to set the human readable string for the registeredID with an
  11818. * ASN_RID_TYPE DNS entry
  11819. * return 0 on success
  11820. */
  11821. static int GenerateDNSEntryRIDString(DNS_entry* entry, void* heap)
  11822. {
  11823. int i, j, ret = 0;
  11824. int nameSz = 0;
  11825. int nid = 0;
  11826. int tmpSize = MAX_OID_SZ;
  11827. word32 oid = 0;
  11828. word32 idx = 0;
  11829. word16 tmpName[MAX_OID_SZ];
  11830. char oidName[MAX_OID_SZ];
  11831. char* finalName;
  11832. if (entry == NULL || entry->type != ASN_RID_TYPE) {
  11833. return BAD_FUNC_ARG;
  11834. }
  11835. if (entry->len <= 0) {
  11836. return BAD_FUNC_ARG;
  11837. }
  11838. XMEMSET(&oidName, 0, MAX_OID_SZ);
  11839. ret = GetOID((const byte*)entry->name, &idx, &oid, oidIgnoreType,
  11840. entry->len);
  11841. if (ret == 0 && (nid = oid2nid(oid, oidCsrAttrType)) > 0) {
  11842. /* OID has known string value */
  11843. finalName = (char*)wolfSSL_OBJ_nid2ln(nid);
  11844. }
  11845. else {
  11846. /* Decode OBJECT_ID into dotted form array. */
  11847. ret = DecodeObjectId((const byte*)(entry->name),(word32)entry->len,
  11848. tmpName, (word32*)&tmpSize);
  11849. if (ret == 0) {
  11850. j = 0;
  11851. /* Append each number of dotted form. */
  11852. for (i = 0; i < tmpSize; i++) {
  11853. if (j >= MAX_OID_SZ) {
  11854. return BUFFER_E;
  11855. }
  11856. if (i < tmpSize - 1) {
  11857. ret = XSNPRINTF(oidName + j, MAX_OID_SZ - j, "%d.", tmpName[i]);
  11858. }
  11859. else {
  11860. ret = XSNPRINTF(oidName + j, MAX_OID_SZ - j, "%d", tmpName[i]);
  11861. }
  11862. if (ret >= 0) {
  11863. j += ret;
  11864. }
  11865. else {
  11866. return BUFFER_E;
  11867. }
  11868. }
  11869. ret = 0;
  11870. finalName = oidName;
  11871. }
  11872. }
  11873. if (ret == 0) {
  11874. nameSz = (int)XSTRLEN((const char*)finalName);
  11875. entry->ridString = (char*)XMALLOC(nameSz + 1, heap,
  11876. DYNAMIC_TYPE_ALTNAME);
  11877. if (entry->ridString == NULL) {
  11878. ret = MEMORY_E;
  11879. }
  11880. if (ret == 0) {
  11881. XMEMCPY(entry->ridString, finalName, nameSz + 1);
  11882. }
  11883. }
  11884. return ret;
  11885. }
  11886. #endif /* OPENSSL_ALL && WOLFSSL_ASN_TEMPLATE */
  11887. #ifdef WOLFSSL_ASN_TEMPLATE
  11888. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11889. /* Adds a DNS entry to a list of DNS entries
  11890. *
  11891. * @param [in, out] lst Linked list of DNS name entries.
  11892. * @param [in] entry Entry to add to the list
  11893. * @return 0 on success.
  11894. */
  11895. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11896. {
  11897. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11898. entry->next = NULL;
  11899. if (*lst == NULL) {
  11900. /* First on list */
  11901. *lst = entry;
  11902. }
  11903. else {
  11904. DNS_entry* temp = *lst;
  11905. /* Find end */
  11906. for (; (temp->next != NULL); temp = temp->next);
  11907. /* Add to end */
  11908. temp->next = entry;
  11909. }
  11910. #else
  11911. /* Prepend entry to linked list. */
  11912. entry->next = *lst;
  11913. *lst = entry;
  11914. #endif
  11915. return 0;
  11916. }
  11917. /* Allocate a DNS entry and set the fields.
  11918. *
  11919. * @param [in] cert Certificate object.
  11920. * @param [in] str DNS name string.
  11921. * @param [in] strLen Length of DNS name string.
  11922. * @param [in] type Type of DNS name string.
  11923. * @param [in, out] entries Linked list of DNS name entries.
  11924. * @return 0 on success.
  11925. * @return MEMORY_E when dynamic memory allocation fails.
  11926. */
  11927. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11928. int type, DNS_entry** entries)
  11929. {
  11930. DNS_entry* dnsEntry;
  11931. int ret = 0;
  11932. /* Only used for heap. */
  11933. (void)cert;
  11934. /* TODO: consider one malloc. */
  11935. /* Allocate DNS Entry object. */
  11936. dnsEntry = AltNameNew(cert->heap);
  11937. if (dnsEntry == NULL) {
  11938. ret = MEMORY_E;
  11939. }
  11940. if (ret == 0) {
  11941. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11942. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  11943. DYNAMIC_TYPE_ALTNAME);
  11944. if (dnsEntry->name == NULL) {
  11945. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11946. ret = MEMORY_E;
  11947. }
  11948. }
  11949. if (ret == 0) {
  11950. /* Set tag type, name length, name and NUL terminate name. */
  11951. dnsEntry->type = type;
  11952. dnsEntry->len = strLen;
  11953. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  11954. dnsEntry->name[strLen] = '\0';
  11955. #if defined(OPENSSL_ALL)
  11956. /* store registeredID as a string */
  11957. if (type == ASN_RID_TYPE) {
  11958. if ((ret = GenerateDNSEntryRIDString(dnsEntry, cert->heap)) != 0) {
  11959. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11960. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11961. }
  11962. }
  11963. #endif
  11964. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11965. /* store IP addresses as a string */
  11966. if (type == ASN_IP_TYPE) {
  11967. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11968. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11969. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11970. }
  11971. }
  11972. }
  11973. if (ret == 0) {
  11974. #endif
  11975. ret = AddDNSEntryToList(entries, dnsEntry);
  11976. }
  11977. return ret;
  11978. }
  11979. #endif
  11980. /* Set the details of a subject name component into a certificate.
  11981. *
  11982. * @param [in, out] cert Certificate object.
  11983. * @param [in] id Id of component.
  11984. * @param [in] str String for component.
  11985. * @param [in] strLen Length of string.
  11986. * @param [in] tag BER tag representing encoding of string.
  11987. * @return 0 on success, negative values on failure.
  11988. */
  11989. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  11990. byte tag)
  11991. {
  11992. int ret = 0;
  11993. /* Put string and encoding into certificate. */
  11994. if (id == ASN_COMMON_NAME) {
  11995. cert->subjectCN = (char *)str;
  11996. cert->subjectCNLen = (int)strLen;
  11997. cert->subjectCNEnc = (char)tag;
  11998. }
  11999. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12000. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  12001. /* Use table and offsets to put data into appropriate fields. */
  12002. SetCertNameSubject(cert, id, (char*)str);
  12003. SetCertNameSubjectLen(cert, id, strLen);
  12004. SetCertNameSubjectEnc(cert, id, tag);
  12005. }
  12006. #endif
  12007. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12008. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12009. else if (id == ASN_EMAIL) {
  12010. cert->subjectEmail = (char*)str;
  12011. cert->subjectEmailLen = strLen;
  12012. }
  12013. #endif
  12014. #ifdef WOLFSSL_CERT_EXT
  12015. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  12016. else if (id == ASN_JURIS_C) {
  12017. cert->subjectJC = (char*)str;
  12018. cert->subjectJCLen = strLen;
  12019. cert->subjectJCEnc = (char)tag;
  12020. }
  12021. else if (id == ASN_JURIS_ST) {
  12022. cert->subjectJS = (char*)str;
  12023. cert->subjectJSLen = strLen;
  12024. cert->subjectJSEnc = (char)tag;
  12025. }
  12026. #endif
  12027. return ret;
  12028. }
  12029. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  12030. *
  12031. * @param [in, out] cert Certificate object.
  12032. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  12033. * @param [in, out] idx Index int full name to place next component.
  12034. * @param [in, out] nid NID of component type.
  12035. * @param [in] isSubject Whether this data is for a subject name.
  12036. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  12037. * @return 0 on success.
  12038. * @return MEMORY_E when dynamic memory allocation fails.
  12039. * @return ASN_PARSE_E when type not supported.
  12040. */
  12041. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  12042. int isSubject, ASNGetData* dataASN)
  12043. {
  12044. int ret = 0;
  12045. const char* typeStr = NULL;
  12046. byte typeStrLen = 0;
  12047. byte* oid;
  12048. word32 oidSz;
  12049. int id = 0;
  12050. (void)nid;
  12051. /* Get name type OID from data items. */
  12052. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  12053. /* v1 name types */
  12054. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  12055. id = oid[2];
  12056. /* Check range of supported ids in table. */
  12057. if (ValidCertNameSubject(id)) {
  12058. /* Get the type string, length and NID from table. */
  12059. typeStr = GetCertNameSubjectStr(id);
  12060. typeStrLen = GetCertNameSubjectStrLen(id);
  12061. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12062. *nid = GetCertNameSubjectNID(id);
  12063. #endif
  12064. }
  12065. }
  12066. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  12067. /* Set the email id, type string, length and NID. */
  12068. id = ASN_EMAIL;
  12069. typeStr = WOLFSSL_EMAIL_ADDR;
  12070. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12071. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12072. *nid = NID_emailAddress;
  12073. #endif
  12074. }
  12075. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  12076. /* Set the user id, type string, length and NID. */
  12077. id = ASN_USER_ID;
  12078. typeStr = WOLFSSL_USER_ID;
  12079. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  12080. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12081. *nid = NID_userId;
  12082. #endif
  12083. }
  12084. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  12085. /* Set the domain component, type string, length and NID. */
  12086. id = ASN_DC;
  12087. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  12088. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12089. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12090. *nid = NID_domainComponent;
  12091. #endif
  12092. }
  12093. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  12094. /* Set the favourite drink, type string, length and NID. */
  12095. id = ASN_FAVOURITE_DRINK;
  12096. typeStr = WOLFSSL_FAVOURITE_DRINK;
  12097. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12098. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12099. *nid = NID_favouriteDrink;
  12100. #endif
  12101. }
  12102. #ifdef WOLFSSL_CERT_REQ
  12103. else if (oidSz == sizeof(attrPkcs9ContentTypeOid) &&
  12104. XMEMCMP(oid, attrPkcs9ContentTypeOid, oidSz) == 0) {
  12105. /* Set the pkcs9_contentType, type string, length and NID. */
  12106. id = ASN_CONTENT_TYPE;
  12107. typeStr = WOLFSSL_CONTENT_TYPE;
  12108. typeStrLen = sizeof(WOLFSSL_CONTENT_TYPE) - 1;
  12109. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12110. *nid = NID_pkcs9_contentType;
  12111. #endif
  12112. }
  12113. #endif
  12114. /* Other OIDs that start with the same values. */
  12115. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  12116. WOLFSSL_MSG("Unknown pilot attribute type");
  12117. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  12118. ret = ASN_PARSE_E;
  12119. }
  12120. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  12121. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  12122. /* Set the jurisdiction id. */
  12123. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  12124. /* Set the jurisdiction type string, length and NID if known. */
  12125. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  12126. typeStr = WOLFSSL_JOI_C;
  12127. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  12128. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12129. *nid = NID_jurisdictionCountryName;
  12130. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12131. }
  12132. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  12133. typeStr = WOLFSSL_JOI_ST;
  12134. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12135. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12136. *nid = NID_jurisdictionStateOrProvinceName;
  12137. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12138. }
  12139. else {
  12140. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  12141. }
  12142. }
  12143. if ((ret == 0) && (typeStr != NULL)) {
  12144. /* OID type to store for subject name and add to full string. */
  12145. byte* str;
  12146. word32 strLen;
  12147. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12148. /* Get the string reference and length. */
  12149. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12150. if (isSubject) {
  12151. /* Store subject field components. */
  12152. ret = SetSubject(cert, id, str, (int)strLen, tag);
  12153. }
  12154. if (ret == 0) {
  12155. /* Check there is space for this in the full name string and
  12156. * terminating NUL character. */
  12157. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  12158. {
  12159. /* Add RDN to full string. */
  12160. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  12161. *idx += typeStrLen;
  12162. XMEMCPY(&full[*idx], str, strLen);
  12163. *idx += strLen;
  12164. }
  12165. else {
  12166. WOLFSSL_MSG("ASN Name too big, skipping");
  12167. }
  12168. }
  12169. }
  12170. return ret;
  12171. }
  12172. #endif /* WOLFSSL_ASN_TEMPLATE */
  12173. /* Get a certificate name into the certificate object.
  12174. *
  12175. * @param [in, out] cert Decoded certificate object.
  12176. * @param [out] full Buffer to hold full name as a string.
  12177. * @param [out] hash Buffer to hold hash of name.
  12178. * @param [in] nameType ISSUER or SUBJECT.
  12179. * @param [in] input Buffer holding certificate name.
  12180. * @param [in, out] inOutIdx On in, start of certificate name.
  12181. * On out, start of ASN.1 item after cert name.
  12182. * @param [in] maxIdx Index of next item after certificate name.
  12183. * @return 0 on success.
  12184. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12185. * is invalid.
  12186. * @return BUFFER_E when data in buffer is too small.
  12187. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12188. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12189. * @return MEMORY_E when dynamic memory allocation fails.
  12190. */
  12191. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  12192. const byte* input, word32* inOutIdx, word32 maxIdx)
  12193. {
  12194. #ifndef WOLFSSL_ASN_TEMPLATE
  12195. int length; /* length of all distinguished names */
  12196. int dummy;
  12197. int ret;
  12198. word32 idx;
  12199. word32 srcIdx = *inOutIdx;
  12200. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12201. !defined(WOLFCRYPT_ONLY)
  12202. WOLFSSL_X509_NAME* dName = NULL;
  12203. #endif
  12204. WOLFSSL_MSG("Getting Cert Name");
  12205. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12206. * calculated over the entire DER encoding of the Name field, including
  12207. * the tag and length. */
  12208. if (CalcHashId_ex(input + *inOutIdx, maxIdx - *inOutIdx, hash,
  12209. HashIdAlg(cert->signatureOID)) != 0) {
  12210. return ASN_PARSE_E;
  12211. }
  12212. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12213. !defined(WOLFCRYPT_ONLY)
  12214. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12215. if (dName == NULL) {
  12216. return MEMORY_E;
  12217. }
  12218. #endif /* OPENSSL_EXTRA */
  12219. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  12220. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12221. !defined(WOLFCRYPT_ONLY)
  12222. wolfSSL_X509_NAME_free(dName);
  12223. #endif /* OPENSSL_EXTRA */
  12224. return ASN_PARSE_E;
  12225. }
  12226. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12227. /* store pointer to raw issuer */
  12228. if (nameType == ISSUER) {
  12229. cert->issuerRaw = &input[srcIdx];
  12230. cert->issuerRawLen = length;
  12231. }
  12232. #endif
  12233. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12234. if (nameType == SUBJECT) {
  12235. cert->subjectRaw = &input[srcIdx];
  12236. cert->subjectRawLen = length;
  12237. }
  12238. #endif
  12239. length += (int)srcIdx;
  12240. idx = 0;
  12241. while (srcIdx < (word32)length) {
  12242. byte b = 0;
  12243. byte joint[3];
  12244. byte tooBig = FALSE;
  12245. int oidSz;
  12246. const char* copy = NULL;
  12247. int copyLen = 0;
  12248. int strLen = 0;
  12249. byte id = 0;
  12250. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12251. && !defined(WOLFCRYPT_ONLY)
  12252. int nid = NID_undef;
  12253. int enc;
  12254. #endif /* OPENSSL_EXTRA */
  12255. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  12256. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  12257. }
  12258. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  12259. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12260. !defined(WOLFCRYPT_ONLY)
  12261. wolfSSL_X509_NAME_free(dName);
  12262. #endif /* OPENSSL_EXTRA */
  12263. return ASN_PARSE_E;
  12264. }
  12265. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  12266. if (ret != 0) {
  12267. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12268. !defined(WOLFCRYPT_ONLY)
  12269. wolfSSL_X509_NAME_free(dName);
  12270. #endif /* OPENSSL_EXTRA */
  12271. return ret;
  12272. }
  12273. /* make sure there is room for joint */
  12274. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  12275. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12276. !defined(WOLFCRYPT_ONLY)
  12277. wolfSSL_X509_NAME_free(dName);
  12278. #endif /* OPENSSL_EXTRA */
  12279. return ASN_PARSE_E;
  12280. }
  12281. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  12282. /* v1 name types */
  12283. if (joint[0] == 0x55 && joint[1] == 0x04) {
  12284. srcIdx += 3;
  12285. id = joint[2];
  12286. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  12287. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12288. !defined(WOLFCRYPT_ONLY)
  12289. wolfSSL_X509_NAME_free(dName);
  12290. #endif /* OPENSSL_EXTRA */
  12291. return ASN_PARSE_E;
  12292. }
  12293. if (id == ASN_COMMON_NAME) {
  12294. if (nameType == SUBJECT) {
  12295. cert->subjectCN = (char *)&input[srcIdx];
  12296. cert->subjectCNLen = strLen;
  12297. cert->subjectCNEnc = (char)b;
  12298. }
  12299. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12300. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12301. else if (nameType == ISSUER) {
  12302. cert->issuerCN = (char*)&input[srcIdx];
  12303. cert->issuerCNLen = strLen;
  12304. cert->issuerCNEnc = (char)b;
  12305. }
  12306. #endif
  12307. copy = WOLFSSL_COMMON_NAME;
  12308. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  12309. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12310. && !defined(WOLFCRYPT_ONLY)
  12311. nid = NID_commonName;
  12312. #endif /* OPENSSL_EXTRA */
  12313. }
  12314. #ifdef WOLFSSL_CERT_NAME_ALL
  12315. else if (id == ASN_NAME) {
  12316. copy = WOLFSSL_NAME;
  12317. copyLen = sizeof(WOLFSSL_NAME) - 1;
  12318. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12319. if (nameType == SUBJECT) {
  12320. cert->subjectN = (char*)&input[srcIdx];
  12321. cert->subjectNLen = strLen;
  12322. cert->subjectNEnc = b;
  12323. }
  12324. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12325. #if (defined(OPENSSL_EXTRA) || \
  12326. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12327. && !defined(WOLFCRYPT_ONLY)
  12328. nid = NID_name;
  12329. #endif /* OPENSSL_EXTRA */
  12330. }
  12331. else if (id == ASN_INITIALS) {
  12332. copy = WOLFSSL_INITIALS;
  12333. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  12334. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12335. if (nameType == SUBJECT) {
  12336. cert->subjectI = (char*)&input[srcIdx];
  12337. cert->subjectILen = strLen;
  12338. cert->subjectIEnc = b;
  12339. }
  12340. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12341. #if (defined(OPENSSL_EXTRA) || \
  12342. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12343. && !defined(WOLFCRYPT_ONLY)
  12344. nid = NID_initials;
  12345. #endif /* OPENSSL_EXTRA */
  12346. }
  12347. else if (id == ASN_GIVEN_NAME) {
  12348. copy = WOLFSSL_GIVEN_NAME;
  12349. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  12350. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12351. if (nameType == SUBJECT) {
  12352. cert->subjectGN = (char*)&input[srcIdx];
  12353. cert->subjectGNLen = strLen;
  12354. cert->subjectGNEnc = b;
  12355. }
  12356. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12357. #if (defined(OPENSSL_EXTRA) || \
  12358. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12359. && !defined(WOLFCRYPT_ONLY)
  12360. nid = NID_givenName;
  12361. #endif /* OPENSSL_EXTRA */
  12362. }
  12363. else if (id == ASN_DNQUALIFIER) {
  12364. copy = WOLFSSL_DNQUALIFIER;
  12365. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  12366. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12367. if (nameType == SUBJECT) {
  12368. cert->subjectDNQ = (char*)&input[srcIdx];
  12369. cert->subjectDNQLen = strLen;
  12370. cert->subjectDNQEnc = b;
  12371. }
  12372. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12373. #if (defined(OPENSSL_EXTRA) || \
  12374. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12375. && !defined(WOLFCRYPT_ONLY)
  12376. nid = NID_dnQualifier;
  12377. #endif /* OPENSSL_EXTRA */
  12378. }
  12379. #endif /* WOLFSSL_CERT_NAME_ALL */
  12380. else if (id == ASN_SUR_NAME) {
  12381. copy = WOLFSSL_SUR_NAME;
  12382. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  12383. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12384. if (nameType == SUBJECT) {
  12385. cert->subjectSN = (char*)&input[srcIdx];
  12386. cert->subjectSNLen = strLen;
  12387. cert->subjectSNEnc = (char)b;
  12388. }
  12389. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12390. else if (nameType == ISSUER) {
  12391. cert->issuerSN = (char*)&input[srcIdx];
  12392. cert->issuerSNLen = strLen;
  12393. cert->issuerSNEnc = (char)b;
  12394. }
  12395. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12396. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12397. #if (defined(OPENSSL_EXTRA) || \
  12398. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12399. && !defined(WOLFCRYPT_ONLY)
  12400. nid = NID_surname;
  12401. #endif /* OPENSSL_EXTRA */
  12402. }
  12403. else if (id == ASN_COUNTRY_NAME) {
  12404. copy = WOLFSSL_COUNTRY_NAME;
  12405. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  12406. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12407. if (nameType == SUBJECT) {
  12408. cert->subjectC = (char*)&input[srcIdx];
  12409. cert->subjectCLen = strLen;
  12410. cert->subjectCEnc = (char)b;
  12411. }
  12412. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12413. else if (nameType == ISSUER) {
  12414. cert->issuerC = (char*)&input[srcIdx];
  12415. cert->issuerCLen = strLen;
  12416. cert->issuerCEnc = (char)b;
  12417. }
  12418. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12419. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12420. #if (defined(OPENSSL_EXTRA) || \
  12421. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12422. && !defined(WOLFCRYPT_ONLY)
  12423. nid = NID_countryName;
  12424. #endif /* OPENSSL_EXTRA */
  12425. }
  12426. else if (id == ASN_LOCALITY_NAME) {
  12427. copy = WOLFSSL_LOCALITY_NAME;
  12428. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  12429. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12430. if (nameType == SUBJECT) {
  12431. cert->subjectL = (char*)&input[srcIdx];
  12432. cert->subjectLLen = strLen;
  12433. cert->subjectLEnc = (char)b;
  12434. }
  12435. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12436. else if (nameType == ISSUER) {
  12437. cert->issuerL = (char*)&input[srcIdx];
  12438. cert->issuerLLen = strLen;
  12439. cert->issuerLEnc = (char)b;
  12440. }
  12441. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12442. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12443. #if (defined(OPENSSL_EXTRA) || \
  12444. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12445. && !defined(WOLFCRYPT_ONLY)
  12446. nid = NID_localityName;
  12447. #endif /* OPENSSL_EXTRA */
  12448. }
  12449. else if (id == ASN_STATE_NAME) {
  12450. copy = WOLFSSL_STATE_NAME;
  12451. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  12452. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12453. if (nameType == SUBJECT) {
  12454. cert->subjectST = (char*)&input[srcIdx];
  12455. cert->subjectSTLen = strLen;
  12456. cert->subjectSTEnc = (char)b;
  12457. }
  12458. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12459. else if (nameType == ISSUER) {
  12460. cert->issuerST = (char*)&input[srcIdx];
  12461. cert->issuerSTLen = strLen;
  12462. cert->issuerSTEnc = (char)b;
  12463. }
  12464. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12465. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12466. #if (defined(OPENSSL_EXTRA) || \
  12467. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12468. && !defined(WOLFCRYPT_ONLY)
  12469. nid = NID_stateOrProvinceName;
  12470. #endif /* OPENSSL_EXTRA */
  12471. }
  12472. else if (id == ASN_ORG_NAME) {
  12473. copy = WOLFSSL_ORG_NAME;
  12474. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  12475. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12476. if (nameType == SUBJECT) {
  12477. cert->subjectO = (char*)&input[srcIdx];
  12478. cert->subjectOLen = strLen;
  12479. cert->subjectOEnc = (char)b;
  12480. }
  12481. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12482. else if (nameType == ISSUER) {
  12483. cert->issuerO = (char*)&input[srcIdx];
  12484. cert->issuerOLen = strLen;
  12485. cert->issuerOEnc = (char)b;
  12486. }
  12487. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12488. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12489. #if (defined(OPENSSL_EXTRA) || \
  12490. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12491. && !defined(WOLFCRYPT_ONLY)
  12492. nid = NID_organizationName;
  12493. #endif /* OPENSSL_EXTRA */
  12494. }
  12495. else if (id == ASN_ORGUNIT_NAME) {
  12496. copy = WOLFSSL_ORGUNIT_NAME;
  12497. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  12498. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12499. if (nameType == SUBJECT) {
  12500. cert->subjectOU = (char*)&input[srcIdx];
  12501. cert->subjectOULen = strLen;
  12502. cert->subjectOUEnc = (char)b;
  12503. }
  12504. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12505. else if (nameType == ISSUER) {
  12506. cert->issuerOU = (char*)&input[srcIdx];
  12507. cert->issuerOULen = strLen;
  12508. cert->issuerOUEnc = (char)b;
  12509. }
  12510. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12511. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12512. #if (defined(OPENSSL_EXTRA) || \
  12513. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12514. && !defined(WOLFCRYPT_ONLY)
  12515. nid = NID_organizationalUnitName;
  12516. #endif /* OPENSSL_EXTRA */
  12517. }
  12518. else if (id == ASN_SERIAL_NUMBER) {
  12519. copy = WOLFSSL_SERIAL_NUMBER;
  12520. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  12521. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12522. if (nameType == SUBJECT) {
  12523. cert->subjectSND = (char*)&input[srcIdx];
  12524. cert->subjectSNDLen = strLen;
  12525. cert->subjectSNDEnc = (char)b;
  12526. }
  12527. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12528. else if (nameType == ISSUER) {
  12529. cert->issuerSND = (char*)&input[srcIdx];
  12530. cert->issuerSNDLen = strLen;
  12531. cert->issuerSNDEnc = (char)b;
  12532. }
  12533. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12534. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12535. #if (defined(OPENSSL_EXTRA) || \
  12536. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12537. && !defined(WOLFCRYPT_ONLY)
  12538. nid = NID_serialNumber;
  12539. #endif /* OPENSSL_EXTRA */
  12540. }
  12541. else if (id == ASN_USER_ID) {
  12542. copy = WOLFSSL_USER_ID;
  12543. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12544. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12545. if (nameType == SUBJECT) {
  12546. cert->subjectUID = (char*)&input[srcIdx];
  12547. cert->subjectUIDLen = strLen;
  12548. cert->subjectUIDEnc = (char)b;
  12549. }
  12550. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12551. #if (defined(OPENSSL_EXTRA) || \
  12552. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12553. && !defined(WOLFCRYPT_ONLY)
  12554. nid = NID_userId;
  12555. #endif /* OPENSSL_EXTRA */
  12556. }
  12557. #ifdef WOLFSSL_CERT_EXT
  12558. else if (id == ASN_STREET_ADDR) {
  12559. copy = WOLFSSL_STREET_ADDR_NAME;
  12560. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  12561. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12562. if (nameType == SUBJECT) {
  12563. cert->subjectStreet = (char*)&input[srcIdx];
  12564. cert->subjectStreetLen = strLen;
  12565. cert->subjectStreetEnc = (char)b;
  12566. }
  12567. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12568. #if (defined(OPENSSL_EXTRA) || \
  12569. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12570. && !defined(WOLFCRYPT_ONLY)
  12571. nid = NID_streetAddress;
  12572. #endif /* OPENSSL_EXTRA */
  12573. }
  12574. else if (id == ASN_BUS_CAT) {
  12575. copy = WOLFSSL_BUS_CAT;
  12576. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  12577. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12578. if (nameType == SUBJECT) {
  12579. cert->subjectBC = (char*)&input[srcIdx];
  12580. cert->subjectBCLen = strLen;
  12581. cert->subjectBCEnc = (char)b;
  12582. }
  12583. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12584. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12585. && !defined(WOLFCRYPT_ONLY)
  12586. nid = NID_businessCategory;
  12587. #endif /* OPENSSL_EXTRA */
  12588. }
  12589. else if (id == ASN_POSTAL_CODE) {
  12590. copy = WOLFSSL_POSTAL_NAME;
  12591. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  12592. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12593. if (nameType == SUBJECT) {
  12594. cert->subjectPC = (char*)&input[srcIdx];
  12595. cert->subjectPCLen = strLen;
  12596. cert->subjectPCEnc = (char)b;
  12597. }
  12598. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12599. #if (defined(OPENSSL_EXTRA) || \
  12600. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12601. && !defined(WOLFCRYPT_ONLY)
  12602. nid = NID_postalCode;
  12603. #endif /* OPENSSL_EXTRA */
  12604. }
  12605. #endif /* WOLFSSL_CERT_EXT */
  12606. }
  12607. #ifdef WOLFSSL_CERT_EXT
  12608. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  12609. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  12610. ASN_JOI_PREFIX_SZ)) &&
  12611. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  12612. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  12613. {
  12614. srcIdx += ASN_JOI_PREFIX_SZ;
  12615. id = input[srcIdx++];
  12616. b = input[srcIdx++]; /* encoding */
  12617. if (GetLength(input, &srcIdx, &strLen,
  12618. maxIdx) < 0) {
  12619. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12620. !defined(WOLFCRYPT_ONLY)
  12621. wolfSSL_X509_NAME_free(dName);
  12622. #endif /* OPENSSL_EXTRA */
  12623. return ASN_PARSE_E;
  12624. }
  12625. /* Check for jurisdiction of incorporation country name */
  12626. if (id == ASN_JOI_C) {
  12627. copy = WOLFSSL_JOI_C;
  12628. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  12629. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12630. if (nameType == SUBJECT) {
  12631. cert->subjectJC = (char*)&input[srcIdx];
  12632. cert->subjectJCLen = strLen;
  12633. cert->subjectJCEnc = (char)b;
  12634. }
  12635. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12636. #if (defined(OPENSSL_EXTRA) || \
  12637. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12638. && !defined(WOLFCRYPT_ONLY)
  12639. nid = NID_jurisdictionCountryName;
  12640. #endif /* OPENSSL_EXTRA */
  12641. }
  12642. /* Check for jurisdiction of incorporation state name */
  12643. else if (id == ASN_JOI_ST) {
  12644. copy = WOLFSSL_JOI_ST;
  12645. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12646. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12647. if (nameType == SUBJECT) {
  12648. cert->subjectJS = (char*)&input[srcIdx];
  12649. cert->subjectJSLen = strLen;
  12650. cert->subjectJSEnc = (char)b;
  12651. }
  12652. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12653. #if (defined(OPENSSL_EXTRA) || \
  12654. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12655. && !defined(WOLFCRYPT_ONLY)
  12656. nid = NID_jurisdictionStateOrProvinceName;
  12657. #endif /* OPENSSL_EXTRA */
  12658. }
  12659. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12660. WOLFSSL_MSG("ASN Name too big, skipping");
  12661. tooBig = TRUE;
  12662. }
  12663. }
  12664. #endif /* WOLFSSL_CERT_EXT */
  12665. else {
  12666. /* skip */
  12667. byte email = FALSE;
  12668. byte pilot = FALSE;
  12669. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  12670. id = ASN_EMAIL_NAME;
  12671. email = TRUE;
  12672. }
  12673. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  12674. /* last value of OID is the type of pilot attribute */
  12675. id = input[srcIdx + (word32)oidSz - 1];
  12676. if (id == 0x01)
  12677. id = ASN_USER_ID;
  12678. pilot = TRUE;
  12679. }
  12680. srcIdx += (word32)oidSz + 1;
  12681. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  12682. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12683. !defined(WOLFCRYPT_ONLY)
  12684. wolfSSL_X509_NAME_free(dName);
  12685. #endif /* OPENSSL_EXTRA */
  12686. return ASN_PARSE_E;
  12687. }
  12688. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12689. WOLFSSL_MSG("ASN name too big, skipping");
  12690. tooBig = TRUE;
  12691. }
  12692. if (email) {
  12693. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12694. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12695. WOLFSSL_MSG("ASN name too big, skipping");
  12696. tooBig = TRUE;
  12697. }
  12698. else {
  12699. copy = WOLFSSL_EMAIL_ADDR;
  12700. }
  12701. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12702. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12703. if (nameType == SUBJECT) {
  12704. cert->subjectEmail = (char*)&input[srcIdx];
  12705. cert->subjectEmailLen = strLen;
  12706. }
  12707. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12708. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12709. else if (nameType == ISSUER) {
  12710. cert->issuerEmail = (char*)&input[srcIdx];
  12711. cert->issuerEmailLen = strLen;
  12712. }
  12713. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12714. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12715. #if (defined(OPENSSL_EXTRA) || \
  12716. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12717. && !defined(WOLFCRYPT_ONLY)
  12718. nid = NID_emailAddress;
  12719. #endif /* OPENSSL_EXTRA */
  12720. }
  12721. if (pilot) {
  12722. switch (id) {
  12723. case ASN_USER_ID:
  12724. copy = WOLFSSL_USER_ID;
  12725. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12726. #if (defined(OPENSSL_EXTRA) || \
  12727. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12728. && !defined(WOLFCRYPT_ONLY)
  12729. nid = NID_userId;
  12730. #endif /* OPENSSL_EXTRA */
  12731. break;
  12732. case ASN_DOMAIN_COMPONENT:
  12733. copy = WOLFSSL_DOMAIN_COMPONENT;
  12734. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12735. #if (defined(OPENSSL_EXTRA) || \
  12736. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12737. && !defined(WOLFCRYPT_ONLY)
  12738. nid = NID_domainComponent;
  12739. #endif /* OPENSSL_EXTRA */
  12740. break;
  12741. case ASN_FAVOURITE_DRINK:
  12742. copy = WOLFSSL_FAVOURITE_DRINK;
  12743. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12744. #if (defined(OPENSSL_EXTRA) || \
  12745. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12746. && !defined(WOLFCRYPT_ONLY)
  12747. nid = NID_favouriteDrink;
  12748. #endif /* OPENSSL_EXTRA */
  12749. break;
  12750. case ASN_CONTENT_TYPE:
  12751. copy = WOLFSSL_CONTENT_TYPE;
  12752. copyLen = sizeof(WOLFSSL_CONTENT_TYPE) - 1;
  12753. #if (defined(OPENSSL_EXTRA) || \
  12754. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12755. && !defined(WOLFCRYPT_ONLY)
  12756. nid = NID_pkcs9_contentType;
  12757. #endif /* OPENSSL_EXTRA */
  12758. break;
  12759. default:
  12760. WOLFSSL_MSG("Unknown pilot attribute type");
  12761. #if (defined(OPENSSL_EXTRA) || \
  12762. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12763. !defined(WOLFCRYPT_ONLY)
  12764. wolfSSL_X509_NAME_free(dName);
  12765. #endif /* OPENSSL_EXTRA */
  12766. return ASN_PARSE_E;
  12767. }
  12768. }
  12769. }
  12770. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12771. {
  12772. WOLFSSL_MSG("ASN Name too big, skipping");
  12773. tooBig = TRUE;
  12774. }
  12775. if ((copy != NULL) && !tooBig) {
  12776. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  12777. idx += (word32)copyLen;
  12778. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  12779. idx += (word32)strLen;
  12780. }
  12781. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12782. !defined(WOLFCRYPT_ONLY)
  12783. switch (b) {
  12784. case CTC_UTF8:
  12785. enc = MBSTRING_UTF8;
  12786. break;
  12787. case CTC_PRINTABLE:
  12788. enc = V_ASN1_PRINTABLESTRING;
  12789. break;
  12790. default:
  12791. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12792. enc = MBSTRING_UTF8;
  12793. }
  12794. if (nid != NID_undef) {
  12795. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12796. &input[srcIdx], strLen, -1, -1) !=
  12797. WOLFSSL_SUCCESS) {
  12798. wolfSSL_X509_NAME_free(dName);
  12799. return ASN_PARSE_E;
  12800. }
  12801. }
  12802. #endif /* OPENSSL_EXTRA */
  12803. srcIdx += (word32)strLen;
  12804. }
  12805. full[idx++] = 0;
  12806. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12807. !defined(WOLFCRYPT_ONLY)
  12808. if (nameType == ISSUER) {
  12809. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12810. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12811. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12812. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12813. #endif
  12814. cert->issuerName = dName;
  12815. }
  12816. else {
  12817. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12818. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12819. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12820. #endif
  12821. cert->subjectName = dName;
  12822. }
  12823. #endif
  12824. *inOutIdx = srcIdx;
  12825. return 0;
  12826. #else
  12827. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12828. int ret = 0;
  12829. word32 idx = 0;
  12830. int len;
  12831. word32 srcIdx = *inOutIdx;
  12832. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12833. WOLFSSL_X509_NAME* dName = NULL;
  12834. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12835. WOLFSSL_MSG("Getting Cert Name");
  12836. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12837. * calculated over the entire DER encoding of the Name field, including
  12838. * the tag and length. */
  12839. if (CalcHashId_ex(input + srcIdx, maxIdx - srcIdx, hash,
  12840. HashIdAlg(cert->signatureOID)) != 0) {
  12841. ret = ASN_PARSE_E;
  12842. }
  12843. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12844. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12845. if (ret == 0) {
  12846. /* Create an X509_NAME to hold data for OpenSSL compatibility APIs. */
  12847. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12848. if (dName == NULL) {
  12849. ret = MEMORY_E;
  12850. }
  12851. }
  12852. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12853. if (ret == 0) {
  12854. /* Expecting a SEQUENCE using up all data. */
  12855. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12856. }
  12857. if (ret == 0) {
  12858. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12859. /* Store pointer and length to raw issuer. */
  12860. if (nameType == ISSUER) {
  12861. cert->issuerRaw = &input[srcIdx];
  12862. cert->issuerRawLen = len;
  12863. }
  12864. #endif
  12865. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12866. /* Store pointer and length to raw subject. */
  12867. if (nameType == SUBJECT) {
  12868. cert->subjectRaw = &input[srcIdx];
  12869. cert->subjectRawLen = len;
  12870. }
  12871. #endif
  12872. /* Process all RDNs in name. */
  12873. while ((ret == 0) && (srcIdx < maxIdx)) {
  12874. int nid = 0;
  12875. /* Initialize for data and setup RDN choice. */
  12876. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12877. /* Ignore type OID as too many to store in table. */
  12878. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12879. /* Parse RDN. */
  12880. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12881. &srcIdx, maxIdx);
  12882. if (ret == 0) {
  12883. /* Put RDN data into certificate. */
  12884. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12885. dataASN);
  12886. }
  12887. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12888. /* TODO: push this back up to ssl.c
  12889. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12890. if (ret == 0) {
  12891. int enc;
  12892. byte* str;
  12893. word32 strLen;
  12894. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12895. /* Get string reference. */
  12896. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12897. /* Convert BER tag to a OpenSSL type. */
  12898. switch (tag) {
  12899. case CTC_UTF8:
  12900. enc = MBSTRING_UTF8;
  12901. break;
  12902. case CTC_PRINTABLE:
  12903. enc = V_ASN1_PRINTABLESTRING;
  12904. break;
  12905. default:
  12906. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12907. enc = MBSTRING_UTF8;
  12908. }
  12909. if (nid != 0) {
  12910. /* Add an entry to the X509_NAME. */
  12911. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12912. (int)strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12913. ret = ASN_PARSE_E;
  12914. }
  12915. }
  12916. }
  12917. #endif
  12918. }
  12919. }
  12920. if (ret == 0) {
  12921. /* Terminate string. */
  12922. full[idx] = 0;
  12923. /* Return index into encoding after name. */
  12924. *inOutIdx = srcIdx;
  12925. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12926. /* Store X509_NAME in certificate. */
  12927. if (nameType == ISSUER) {
  12928. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12929. defined(HAVE_LIGHTY)) && \
  12930. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12931. dName->rawLen = (int)min((word32)cert->issuerRawLen,
  12932. WC_ASN_NAME_MAX);
  12933. XMEMCPY(dName->raw, cert->issuerRaw, (size_t)dName->rawLen);
  12934. #endif
  12935. cert->issuerName = dName;
  12936. }
  12937. else {
  12938. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12939. dName->rawLen = (int)min((word32)cert->subjectRawLen,
  12940. WC_ASN_NAME_MAX);
  12941. XMEMCPY(dName->raw, cert->subjectRaw, (size_t)dName->rawLen);
  12942. #endif
  12943. cert->subjectName = dName;
  12944. }
  12945. }
  12946. else {
  12947. /* Dispose of unused X509_NAME. */
  12948. wolfSSL_X509_NAME_free(dName);
  12949. #endif
  12950. }
  12951. FREE_ASNGETDATA(dataASN, cert->heap);
  12952. return ret;
  12953. #endif /* WOLFSSL_ASN_TEMPLATE */
  12954. }
  12955. #ifdef WOLFSSL_ASN_TEMPLATE
  12956. /* ASN.1 template for certificate name. */
  12957. static const ASNItem certNameASN[] = {
  12958. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12959. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12960. };
  12961. enum {
  12962. CERTNAMEASN_IDX_OID = 0,
  12963. CERTNAMEASN_IDX_NAME
  12964. };
  12965. /* Number of items in ASN.1 template for certificate name. */
  12966. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12967. #endif
  12968. /* Get a certificate name into the certificate object.
  12969. *
  12970. * Either the issuer or subject name.
  12971. *
  12972. * @param [in, out] cert Decoded certificate object.
  12973. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12974. * @param [in] maxIdx Index of next item after certificate name.
  12975. * @return 0 on success.
  12976. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12977. * is invalid.
  12978. * @return BUFFER_E when data in buffer is too small.
  12979. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12980. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12981. * @return MEMORY_E when dynamic memory allocation fails.
  12982. */
  12983. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12984. {
  12985. #ifndef WOLFSSL_ASN_TEMPLATE
  12986. char* full;
  12987. byte* hash;
  12988. int length;
  12989. word32 localIdx;
  12990. byte tag;
  12991. WOLFSSL_MSG("Getting Name");
  12992. if (nameType == ISSUER) {
  12993. full = cert->issuer;
  12994. hash = cert->issuerHash;
  12995. }
  12996. else {
  12997. full = cert->subject;
  12998. hash = cert->subjectHash;
  12999. }
  13000. if (cert->srcIdx >= (word32)maxIdx) {
  13001. return BUFFER_E;
  13002. }
  13003. localIdx = cert->srcIdx;
  13004. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  13005. return ASN_PARSE_E;
  13006. }
  13007. if (tag == ASN_OBJECT_ID) {
  13008. WOLFSSL_MSG("Trying optional prefix...");
  13009. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  13010. return ASN_PARSE_E;
  13011. WOLFSSL_MSG("Got optional prefix");
  13012. }
  13013. localIdx = cert->srcIdx;
  13014. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  13015. return ASN_PARSE_E;
  13016. }
  13017. localIdx = cert->srcIdx + 1;
  13018. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  13019. return ASN_PARSE_E;
  13020. }
  13021. length += (int)(localIdx - cert->srcIdx);
  13022. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  13023. cert->srcIdx + (word32)length);
  13024. #else
  13025. ASNGetData dataASN[certNameASN_Length];
  13026. word32 idx = cert->srcIdx;
  13027. int ret = 0;
  13028. WOLFSSL_MSG("Getting Name");
  13029. XMEMSET(dataASN, 0, sizeof(dataASN));
  13030. /* Initialize for data and don't check optional prefix OID. */
  13031. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  13032. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  13033. cert->source, &idx, (word32)maxIdx);
  13034. if (ret == 0) {
  13035. char* full;
  13036. byte* hash;
  13037. /* Store offset of SEQUENCE that is start of name. */
  13038. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  13039. /* Get fields to fill in based on name type. */
  13040. if (nameType == ISSUER) {
  13041. full = cert->issuer;
  13042. hash = cert->issuerHash;
  13043. }
  13044. else {
  13045. full = cert->subject;
  13046. hash = cert->subjectHash;
  13047. }
  13048. /* Parse certificate name. */
  13049. ret = GetCertName(cert, full, hash, nameType, cert->source,
  13050. &cert->srcIdx, idx);
  13051. }
  13052. return ret;
  13053. #endif
  13054. }
  13055. #ifndef NO_ASN_TIME
  13056. /* two byte date/time, add to value */
  13057. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  13058. {
  13059. int i = *idx;
  13060. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  13061. date[i+1] > 0x39) {
  13062. return ASN_PARSE_E;
  13063. }
  13064. *value += (int)btoi(date[i++]) * 10;
  13065. *value += (int)btoi(date[i++]);
  13066. *idx = i;
  13067. return 0;
  13068. }
  13069. #ifdef WOLFSSL_LINUXKM
  13070. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  13071. {
  13072. int i = *idx;
  13073. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  13074. date[i+1] > 0x39) {
  13075. return ASN_PARSE_E;
  13076. }
  13077. *value += (long)btoi(date[i++]) * 10;
  13078. *value += (long)btoi(date[i++]);
  13079. *idx = i;
  13080. return 0;
  13081. }
  13082. #endif
  13083. int ExtractDate(const unsigned char* date, unsigned char format,
  13084. struct tm* certTime, int* idx)
  13085. {
  13086. XMEMSET(certTime, 0, sizeof(struct tm));
  13087. if (format == ASN_UTC_TIME) {
  13088. if (btoi(date[*idx]) >= 5)
  13089. certTime->tm_year = 1900;
  13090. else
  13091. certTime->tm_year = 2000;
  13092. }
  13093. else { /* format == GENERALIZED_TIME */
  13094. #ifdef WOLFSSL_LINUXKM
  13095. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  13096. #else
  13097. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  13098. #endif
  13099. certTime->tm_year *= 100;
  13100. }
  13101. #ifdef AVR
  13102. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  13103. /* AVR libc stores these as uint8_t instead of int */
  13104. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  13105. int tm_year = certTime->tm_year - 2000;
  13106. int tm_mon = certTime->tm_mon - 1;
  13107. int tm_mday = certTime->tm_mday;
  13108. int tm_hour = certTime->tm_hour;
  13109. int tm_min = certTime->tm_min;
  13110. int tm_sec = certTime->tm_sec;
  13111. #ifdef WOLFSSL_LINUXKM
  13112. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  13113. #else
  13114. if (GetTime(&tm_year, date, idx) != 0) return 0;
  13115. #endif
  13116. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  13117. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  13118. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  13119. if (GetTime(&tm_min , date, idx) != 0) return 0;
  13120. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  13121. /* Re-populate certTime with computed values */
  13122. certTime->tm_year = tm_year;
  13123. certTime->tm_mon = tm_mon;
  13124. certTime->tm_mday = tm_mday;
  13125. certTime->tm_hour = tm_hour;
  13126. certTime->tm_min = tm_min;
  13127. certTime->tm_sec = tm_sec;
  13128. #else
  13129. /* adjust tm_year, tm_mon */
  13130. #ifdef WOLFSSL_LINUXKM
  13131. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  13132. #else
  13133. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  13134. #endif
  13135. certTime->tm_year -= 1900;
  13136. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  13137. certTime->tm_mon -= 1;
  13138. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  13139. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  13140. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  13141. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  13142. #endif
  13143. return 1;
  13144. }
  13145. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  13146. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  13147. int GetTimeString(byte* date, int format, char* buf, int len)
  13148. {
  13149. struct tm t;
  13150. int idx = 0;
  13151. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  13152. return 0;
  13153. }
  13154. if (date[idx] != 'Z') {
  13155. WOLFSSL_MSG("UTCtime, not Zulu") ;
  13156. return 0;
  13157. }
  13158. /* place month in buffer */
  13159. buf[0] = '\0';
  13160. switch(t.tm_mon) {
  13161. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  13162. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  13163. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  13164. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  13165. case 4: XSTRNCAT(buf, "May ", 5); break;
  13166. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  13167. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  13168. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  13169. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  13170. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  13171. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  13172. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  13173. default:
  13174. return 0;
  13175. }
  13176. idx = 4; /* use idx now for char buffer */
  13177. if (XSNPRINTF(buf + idx, (size_t)(len - idx), "%2d %02d:%02d:%02d %d GMT",
  13178. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  13179. >= len - idx)
  13180. {
  13181. WOLFSSL_MSG("buffer overrun in GetTimeString");
  13182. return 0;
  13183. }
  13184. return 1;
  13185. }
  13186. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  13187. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  13188. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  13189. /* Set current time string, either UTC or GeneralizedTime.
  13190. * (void*) tm should be a pointer to time_t, output is placed in buf.
  13191. *
  13192. * Return time string length placed in buf on success, negative on error */
  13193. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  13194. {
  13195. byte* data_ptr = buf;
  13196. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  13197. int data_len = 0;
  13198. WOLFSSL_ENTER("GetAsnTimeString");
  13199. if (buf == NULL || len == 0)
  13200. return BAD_FUNC_ARG;
  13201. XMEMSET(uf_time, 0, sizeof(uf_time));
  13202. /* GetFormattedTime returns length with null terminator */
  13203. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  13204. if (data_len <= 0) {
  13205. return ASN_TIME_E;
  13206. }
  13207. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  13208. else if (len < (word32)data_len + 2) {
  13209. return BUFFER_E;
  13210. }
  13211. if (data_len == ASN_UTC_TIME_SIZE-1) {
  13212. /* increment data_len for ASN length byte after adding the data_ptr */
  13213. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  13214. /* -1 below excludes null terminator */
  13215. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  13216. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  13217. data_ptr += ASN_UTC_TIME_SIZE - 1;
  13218. }
  13219. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  13220. /* increment data_len for ASN length byte after adding the data_ptr */
  13221. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  13222. /* -1 below excludes null terminator */
  13223. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  13224. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  13225. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  13226. }
  13227. else {
  13228. WOLFSSL_MSG("Invalid time size returned");
  13229. return ASN_TIME_E;
  13230. }
  13231. /* append null terminator */
  13232. *data_ptr = 0;
  13233. /* return length without null terminator */
  13234. return data_len;
  13235. }
  13236. /* return just the time string as either UTC or Generalized Time*/
  13237. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  13238. {
  13239. struct tm* ts = NULL;
  13240. struct tm* tmpTime = NULL;
  13241. int year, mon, day, hour, mini, sec;
  13242. int ret;
  13243. #if defined(NEED_TMP_TIME)
  13244. struct tm tmpTimeStorage;
  13245. tmpTime = &tmpTimeStorage;
  13246. #endif
  13247. /* Needed in case XGMTIME does not use the tmpTime argument. */
  13248. (void)tmpTime;
  13249. WOLFSSL_ENTER("GetFormattedTime");
  13250. if (buf == NULL || len == 0)
  13251. return BAD_FUNC_ARG;
  13252. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  13253. if (ts == NULL) {
  13254. WOLFSSL_MSG("failed to get time data.");
  13255. return ASN_TIME_E;
  13256. }
  13257. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  13258. * the null terminator. ASN encoded values leave off the terminator. */
  13259. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  13260. /* UTC Time */
  13261. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  13262. year = ts->tm_year;
  13263. }
  13264. else {
  13265. year = ts->tm_year - 100;
  13266. }
  13267. mon = ts->tm_mon + 1;
  13268. day = ts->tm_mday;
  13269. hour = ts->tm_hour;
  13270. mini = ts->tm_min;
  13271. sec = ts->tm_sec;
  13272. #if defined(WOLF_C89)
  13273. if (len < ASN_UTC_TIME_SIZE) {
  13274. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13275. return BUFFER_E;
  13276. }
  13277. ret = XSPRINTF((char*)buf,
  13278. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13279. hour, mini, sec);
  13280. #else
  13281. ret = XSNPRINTF((char*)buf, len,
  13282. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13283. hour, mini, sec);
  13284. #endif
  13285. }
  13286. else {
  13287. /* GeneralizedTime */
  13288. year = ts->tm_year + 1900;
  13289. mon = ts->tm_mon + 1;
  13290. day = ts->tm_mday;
  13291. hour = ts->tm_hour;
  13292. mini = ts->tm_min;
  13293. sec = ts->tm_sec;
  13294. #if defined(WOLF_C89)
  13295. if (len < ASN_GENERALIZED_TIME_SIZE) {
  13296. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13297. return BUFFER_E;
  13298. }
  13299. ret = XSPRINTF((char*)buf,
  13300. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13301. hour, mini, sec);
  13302. #else
  13303. ret = XSNPRINTF((char*)buf, len,
  13304. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13305. hour, mini, sec);
  13306. #endif
  13307. }
  13308. return ret;
  13309. }
  13310. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  13311. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  13312. #if defined(USE_WOLF_VALIDDATE)
  13313. /* to the second */
  13314. int DateGreaterThan(const struct tm* a, const struct tm* b)
  13315. {
  13316. if (a->tm_year > b->tm_year)
  13317. return 1;
  13318. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  13319. return 1;
  13320. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13321. a->tm_mday > b->tm_mday)
  13322. return 1;
  13323. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13324. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  13325. return 1;
  13326. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13327. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13328. a->tm_min > b->tm_min)
  13329. return 1;
  13330. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13331. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13332. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  13333. return 1;
  13334. return 0; /* false */
  13335. }
  13336. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  13337. {
  13338. return DateGreaterThan(b,a);
  13339. }
  13340. /* like atoi but only use first byte */
  13341. /* Make sure before and after dates are valid */
  13342. int wc_ValidateDate(const byte* date, byte format, int dateType)
  13343. {
  13344. time_t ltime;
  13345. struct tm certTime;
  13346. struct tm* localTime;
  13347. struct tm* tmpTime;
  13348. int i = 0;
  13349. int timeDiff = 0;
  13350. int diffHH = 0, diffMM = 0;
  13351. #if defined(NEED_TMP_TIME)
  13352. struct tm tmpTimeStorage;
  13353. tmpTime = &tmpTimeStorage;
  13354. #else
  13355. tmpTime = NULL;
  13356. #endif
  13357. (void)tmpTime;
  13358. ltime = wc_Time(0);
  13359. if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
  13360. /* A negative response here could be due to a 32-bit time_t
  13361. * where the year is 2038 or later. */
  13362. WOLFSSL_MSG("wc_Time failed to return a valid value");
  13363. return 0;
  13364. }
  13365. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  13366. if (dateType == BEFORE) {
  13367. WOLFSSL_MSG("Skewing local time for before date check");
  13368. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  13369. }
  13370. #endif
  13371. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  13372. if (dateType == AFTER) {
  13373. WOLFSSL_MSG("Skewing local time for after date check");
  13374. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  13375. }
  13376. #endif
  13377. if (!ExtractDate(date, format, &certTime, &i)) {
  13378. WOLFSSL_MSG("Error extracting the date");
  13379. return 0;
  13380. }
  13381. if ((date[i] == '+') || (date[i] == '-')) {
  13382. int diffSign;
  13383. WOLFSSL_MSG("Using time differential, not Zulu") ;
  13384. diffSign = date[i++] == '+' ? 1 : -1 ;
  13385. if (GetTime(&diffHH, date, &i) != 0)
  13386. return 0;
  13387. if (GetTime(&diffMM, date, &i) != 0)
  13388. return 0;
  13389. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  13390. } else if (date[i] != 'Z') {
  13391. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  13392. return 0;
  13393. }
  13394. ltime -= (time_t)timeDiff;
  13395. localTime = XGMTIME(&ltime, tmpTime);
  13396. if (localTime == NULL) {
  13397. WOLFSSL_MSG("XGMTIME failed");
  13398. return 0;
  13399. }
  13400. if (dateType == BEFORE) {
  13401. if (DateLessThan(localTime, &certTime)) {
  13402. WOLFSSL_MSG("Date BEFORE check failed");
  13403. return 0;
  13404. }
  13405. }
  13406. else { /* dateType == AFTER */
  13407. if (DateGreaterThan(localTime, &certTime)) {
  13408. WOLFSSL_MSG("Date AFTER check failed");
  13409. return 0;
  13410. }
  13411. }
  13412. return 1;
  13413. }
  13414. #endif /* USE_WOLF_VALIDDATE */
  13415. int wc_GetTime(void* timePtr, word32 timeSize)
  13416. {
  13417. time_t* ltime = (time_t*)timePtr;
  13418. if (timePtr == NULL) {
  13419. return BAD_FUNC_ARG;
  13420. }
  13421. if ((word32)sizeof(time_t) > timeSize) {
  13422. return BUFFER_E;
  13423. }
  13424. *ltime = wc_Time(0);
  13425. return 0;
  13426. }
  13427. #ifdef TIME_OVERRIDES
  13428. #ifndef HAVE_TIME_T_TYPE
  13429. typedef long time_t;
  13430. #endif
  13431. extern time_t XTIME(time_t* t);
  13432. #endif
  13433. static wc_time_cb timeFunc = NULL;
  13434. int wc_SetTimeCb(wc_time_cb f)
  13435. {
  13436. timeFunc = f;
  13437. return 0;
  13438. }
  13439. time_t wc_Time(time_t* t)
  13440. {
  13441. if (timeFunc != NULL) {
  13442. return timeFunc(t);
  13443. }
  13444. return XTIME(t);
  13445. }
  13446. #endif /* !NO_ASN_TIME */
  13447. #ifdef WOLFSSL_ASN_TEMPLATE
  13448. /* TODO: use a CHOICE instead of two items? */
  13449. /* ASN.1 template for a date - either UTC or Generalized Time. */
  13450. static const ASNItem dateASN[] = {
  13451. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  13452. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  13453. };
  13454. enum {
  13455. DATEASN_IDX_UTC = 0,
  13456. DATEASN_IDX_GT
  13457. };
  13458. /* Number of items in ASN.1 template for a date. */
  13459. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  13460. #endif /* WOLFSSL_ASN_TEMPLATE */
  13461. /* Get date buffer, format and length. Returns 0=success or error */
  13462. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  13463. *
  13464. * @param [in] source Buffer containing encoded date.
  13465. * @param [in, out] idx On in, the index of the date.
  13466. * On out, index after date.
  13467. * @param [out] pDate Pointer into buffer of data bytes.
  13468. * @param [out] pFormat Format of date - BER/DER tag.
  13469. * @param [out] pLength Length of date bytes.
  13470. * @param [in] maxIdx Index of next item after date.
  13471. * @return 0 on success.
  13472. * @return BAD_FUNC_ARG when source or idx is NULL.
  13473. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13474. * is invalid.
  13475. * @return BUFFER_E when data in buffer is too small.
  13476. */
  13477. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  13478. byte* pFormat, int* pLength, word32 maxIdx)
  13479. {
  13480. #ifndef WOLFSSL_ASN_TEMPLATE
  13481. int length;
  13482. byte format;
  13483. if (source == NULL || idx == NULL)
  13484. return BAD_FUNC_ARG;
  13485. /* get ASN format header */
  13486. if (*idx+1 > maxIdx)
  13487. return BUFFER_E;
  13488. format = source[*idx];
  13489. *idx += 1;
  13490. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  13491. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  13492. return ASN_TIME_E;
  13493. }
  13494. /* get length */
  13495. if (GetLength(source, idx, &length, maxIdx) < 0)
  13496. return ASN_PARSE_E;
  13497. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  13498. return ASN_DATE_SZ_E;
  13499. /* return format, date and length */
  13500. if (pFormat)
  13501. *pFormat = format;
  13502. if (pDate)
  13503. *pDate = &source[*idx];
  13504. if (pLength)
  13505. *pLength = length;
  13506. *idx += (word32)length;
  13507. return 0;
  13508. #else
  13509. ASNGetData dataASN[dateASN_Length];
  13510. int ret = 0;
  13511. if ((source == NULL) || (idx == NULL)) {
  13512. ret = BAD_FUNC_ARG;
  13513. }
  13514. if (ret == 0) {
  13515. /* Initialize data. */
  13516. XMEMSET(dataASN, 0, sizeof(dataASN));
  13517. /* Parse date. */
  13518. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  13519. maxIdx);
  13520. }
  13521. if (ret == 0) {
  13522. /* Determine which tag was seen. */
  13523. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  13524. : DATEASN_IDX_GT;
  13525. /* Return data from seen item. */
  13526. if (pFormat != NULL) {
  13527. *pFormat = dataASN[i].tag;
  13528. }
  13529. if (pDate != NULL) {
  13530. *pDate = dataASN[i].data.ref.data;
  13531. }
  13532. if (pLength != NULL) {
  13533. *pLength = (int)dataASN[i].data.ref.length;
  13534. }
  13535. }
  13536. return ret;
  13537. #endif
  13538. }
  13539. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13540. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  13541. {
  13542. int ret, length;
  13543. const byte *datePtr = NULL;
  13544. byte date[MAX_DATE_SIZE];
  13545. byte format;
  13546. word32 startIdx = 0;
  13547. if (dateType == BEFORE)
  13548. cert->beforeDate = &cert->source[cert->srcIdx];
  13549. else
  13550. cert->afterDate = &cert->source[cert->srcIdx];
  13551. startIdx = cert->srcIdx;
  13552. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  13553. &length, (word32)maxIdx);
  13554. if (ret < 0)
  13555. return ret;
  13556. XMEMSET(date, 0, MAX_DATE_SIZE);
  13557. XMEMCPY(date, datePtr, (size_t)length);
  13558. if (dateType == BEFORE)
  13559. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  13560. else
  13561. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  13562. #ifndef NO_ASN_TIME_CHECK
  13563. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  13564. !XVALIDATE_DATE(date, format, dateType)) {
  13565. if (dateType == BEFORE) {
  13566. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  13567. return ASN_BEFORE_DATE_E;
  13568. }
  13569. else {
  13570. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  13571. return ASN_AFTER_DATE_E;
  13572. }
  13573. }
  13574. #else
  13575. (void)verify;
  13576. #endif
  13577. return 0;
  13578. }
  13579. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  13580. {
  13581. int length;
  13582. int badDate = 0;
  13583. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  13584. return ASN_PARSE_E;
  13585. maxIdx = (int)cert->srcIdx + length;
  13586. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  13587. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  13588. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  13589. return ASN_AFTER_DATE_E;
  13590. if (badDate != 0)
  13591. return badDate;
  13592. return 0;
  13593. }
  13594. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13595. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  13596. byte* format, int* length)
  13597. {
  13598. int ret;
  13599. word32 idx = 0;
  13600. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  13601. return ret;
  13602. }
  13603. #ifndef NO_ASN_TIME
  13604. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  13605. struct tm* timearg)
  13606. {
  13607. int idx = 0;
  13608. (void)length;
  13609. if (!ExtractDate(date, format, timearg, &idx))
  13610. return ASN_TIME_E;
  13611. return 0;
  13612. }
  13613. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  13614. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  13615. {
  13616. int ret = 0;
  13617. const byte* date;
  13618. byte format;
  13619. int length;
  13620. if (cert == NULL)
  13621. return BAD_FUNC_ARG;
  13622. if (before && cert->beforeDateSz > 0) {
  13623. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  13624. &format, &length);
  13625. if (ret == 0)
  13626. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  13627. }
  13628. if (after && cert->afterDateSz > 0) {
  13629. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  13630. &format, &length);
  13631. if (ret == 0)
  13632. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  13633. }
  13634. return ret;
  13635. }
  13636. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  13637. #endif /* !NO_ASN_TIME */
  13638. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  13639. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  13640. {
  13641. int length;
  13642. word32 endSeqIdx;
  13643. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13644. return ASN_PARSE_E;
  13645. endSeqIdx = cert->srcIdx + (word32)length;
  13646. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  13647. maxIdx) < 0) {
  13648. return ASN_OBJECT_ID_E;
  13649. }
  13650. if (cert->srcIdx != endSeqIdx) {
  13651. #ifdef WC_RSA_PSS
  13652. if (*sigOid == CTC_RSASSAPSS) {
  13653. cert->sigParamsIndex = cert->srcIdx;
  13654. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  13655. }
  13656. else
  13657. #endif
  13658. /* Only allowed a ASN NULL header with zero length. */
  13659. if (endSeqIdx - cert->srcIdx != 2)
  13660. return ASN_PARSE_E;
  13661. else {
  13662. byte tag;
  13663. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  13664. return ASN_PARSE_E;
  13665. if (tag != ASN_TAG_NULL)
  13666. return ASN_PARSE_E;
  13667. }
  13668. }
  13669. cert->srcIdx = endSeqIdx;
  13670. return 0;
  13671. }
  13672. #endif
  13673. #ifndef NO_CERTS
  13674. #ifdef WOLFSSL_ASN_TEMPLATE
  13675. /* TODO: move code around to not require this. */
  13676. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  13677. int* badDateRet, int stopAtPubKey,
  13678. int stopAfterPubKey);
  13679. #endif
  13680. /* Assumes the target is a Raw-Public-Key certificate and parsed up to the
  13681. * public key. Returns CRYPTOCB_UNAVAILABLE if it determines that the cert is
  13682. * different from the Paw-Public-Key cert. In that case, cert->srcIdx is not
  13683. * consumed so as succeeding parse function can take over.
  13684. * In case that the target is Raw-Public-Key cert and contains a public key,
  13685. * returns 0 and consumes cert->srcIdx so as a public key retrieval function
  13686. * can follow.
  13687. */
  13688. #if defined(HAVE_RPK)
  13689. int TryDecodeRPKToKey(DecodedCert* cert)
  13690. {
  13691. int ret = 0, len;
  13692. word32 tmpIdx;
  13693. word32 oid;
  13694. WOLFSSL_ENTER("TryDecodeRPKToKey");
  13695. if (cert == NULL)
  13696. return BAD_FUNC_ARG;
  13697. tmpIdx = cert->srcIdx;
  13698. /* both X509 cert and RPK cert should start with a Sequence tag */
  13699. if (ret == 0) {
  13700. if (GetSequence(cert->source, &tmpIdx, &len, cert->maxIdx) < 0)
  13701. ret = ASN_PARSE_E;
  13702. }
  13703. /* TBSCertificate of X509 or AlgorithmIdentifier of RPK cert */
  13704. if (ret == 0) {
  13705. if (GetSequence(cert->source, &tmpIdx, &len, cert->maxIdx) < 0)
  13706. ret = ASN_PARSE_E;
  13707. }
  13708. /* OBJ ID should be next in RPK cert */
  13709. if (ret == 0) {
  13710. if (GetObjectId(cert->source, &tmpIdx, &oid, oidKeyType, cert->maxIdx)
  13711. < 0)
  13712. ret = CRYPTOCB_UNAVAILABLE;
  13713. }
  13714. /* consume cert->srcIdx */
  13715. if (ret == 0) {
  13716. WOLFSSL_MSG("Looks like RPK certificate");
  13717. cert->srcIdx = tmpIdx;
  13718. }
  13719. WOLFSSL_LEAVE("TryDecodeRPKToKey", ret);
  13720. return ret;
  13721. }
  13722. #endif /* HAVE_RPK */
  13723. /* Parse the certificate up to the X.509 public key.
  13724. *
  13725. * If cert data is invalid then badDate get set to error value.
  13726. *
  13727. * @param [in, out] cert Decoded certificate object.
  13728. * @param [in] verify Whether to verify dates.
  13729. * @param [out] badDate Error code when verify dates.
  13730. * @return 0 on success.
  13731. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  13732. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13733. * @return ASN_DATE_SZ_E when time data is not supported.
  13734. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13735. * is invalid.
  13736. * @return BUFFER_E when data in buffer is too small.
  13737. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13738. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13739. */
  13740. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  13741. {
  13742. #ifndef WOLFSSL_ASN_TEMPLATE
  13743. int ret;
  13744. if (cert == NULL || badDate == NULL)
  13745. return BAD_FUNC_ARG;
  13746. *badDate = 0;
  13747. if ( (ret = GetCertHeader(cert)) < 0)
  13748. return ret;
  13749. WOLFSSL_MSG("Got Cert Header");
  13750. #ifdef WOLFSSL_CERT_REQ
  13751. if (!cert->isCSR) {
  13752. #endif
  13753. /* Using the sigIndex as the upper bound because that's where the
  13754. * actual certificate data ends. */
  13755. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  13756. return ret;
  13757. WOLFSSL_MSG("Got Algo ID");
  13758. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  13759. return ret;
  13760. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  13761. *badDate = ret;
  13762. #ifdef WOLFSSL_CERT_REQ
  13763. }
  13764. #endif
  13765. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  13766. return ret;
  13767. WOLFSSL_MSG("Got Subject Name");
  13768. return ret;
  13769. #else
  13770. /* Use common decode routine and stop at public key. */
  13771. int ret;
  13772. *badDate = 0;
  13773. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13774. if (ret >= 0) {
  13775. /* Store current index: public key. */
  13776. cert->srcIdx = (word32)ret;
  13777. }
  13778. return ret;
  13779. #endif /* WOLFSSL_ASN_TEMPLATE */
  13780. }
  13781. /* Parse the certificate up to and including X.509 public key.
  13782. *
  13783. * @param [in, out] cert Decoded certificate object.
  13784. * @param [in] verify Whether to verify dates.
  13785. * @return 0 on success.
  13786. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13787. * @return ASN_DATE_SZ_E when time data is not supported.
  13788. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13789. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13790. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13791. * is invalid.
  13792. * @return BUFFER_E when data in buffer is too small.
  13793. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13794. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13795. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13796. */
  13797. int DecodeToKey(DecodedCert* cert, int verify)
  13798. {
  13799. #ifndef WOLFSSL_ASN_TEMPLATE
  13800. int badDate = 0;
  13801. int ret;
  13802. #if defined(HAVE_RPK)
  13803. /* Raw Public Key certificate has only a SubjectPublicKeyInfo structure
  13804. * as its contents. So try to call GetCertKey to get public key from it.
  13805. * If it fails, the cert should be a X509 cert and proceed to process as
  13806. * x509 cert. */
  13807. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13808. if (ret == 0) {
  13809. WOLFSSL_MSG("Raw Public Key certificate found and parsed");
  13810. cert->isRPK = 1;
  13811. return ret;
  13812. }
  13813. #endif /* HAVE_RPK */
  13814. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13815. return ret;
  13816. /* Determine if self signed */
  13817. #ifdef WOLFSSL_CERT_REQ
  13818. if (cert->isCSR)
  13819. cert->selfSigned = 1;
  13820. else
  13821. #endif
  13822. {
  13823. cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
  13824. KEYID_SIZE) == 0 ? 1 : 0;
  13825. }
  13826. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13827. if (ret != 0)
  13828. return ret;
  13829. WOLFSSL_MSG("Got Key");
  13830. if (badDate != 0)
  13831. return badDate;
  13832. return ret;
  13833. #else
  13834. int ret;
  13835. int badDate = 0;
  13836. /* Call internal version and stop after public key. */
  13837. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13838. /* Always return date errors. */
  13839. if (ret == 0) {
  13840. ret = badDate;
  13841. }
  13842. return ret;
  13843. #endif /* WOLFSSL_ASN_TEMPLATE */
  13844. }
  13845. #if !defined(WOLFSSL_ASN_TEMPLATE)
  13846. static int GetSignature(DecodedCert* cert)
  13847. {
  13848. int length;
  13849. int ret;
  13850. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13851. NULL);
  13852. if (ret != 0)
  13853. return ret;
  13854. cert->sigLength = (word32)length;
  13855. cert->signature = &cert->source[cert->srcIdx];
  13856. cert->srcIdx += cert->sigLength;
  13857. if (cert->srcIdx != cert->maxIdx)
  13858. return ASN_PARSE_E;
  13859. return 0;
  13860. }
  13861. #endif /* !WOLFSSL_ASN_TEMPLATE */
  13862. #endif /* !NO_CERTS */
  13863. #ifndef WOLFSSL_ASN_TEMPLATE
  13864. static word32 SetOctetString8Bit(word32 len, byte* output)
  13865. {
  13866. output[0] = ASN_OCTET_STRING;
  13867. output[1] = (byte)len;
  13868. return 2;
  13869. }
  13870. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13871. {
  13872. word32 idx = SetOctetString8Bit(digSz, output);
  13873. XMEMCPY(&output[idx], digest, digSz);
  13874. return idx + digSz;
  13875. }
  13876. #endif
  13877. /* Encode a length for DER.
  13878. *
  13879. * @param [in] length Value to encode.
  13880. * @param [out] output Buffer to encode into.
  13881. * @return Number of bytes encoded.
  13882. */
  13883. word32 SetLength(word32 length, byte* output)
  13884. {
  13885. /* Start encoding at start of buffer. */
  13886. word32 i = 0;
  13887. if (length < ASN_LONG_LENGTH) {
  13888. /* Only one byte needed to encode. */
  13889. if (output) {
  13890. /* Write out length value. */
  13891. output[i] = (byte)length;
  13892. }
  13893. /* Skip over length. */
  13894. i++;
  13895. }
  13896. else {
  13897. /* Calculate the number of bytes required to encode value. */
  13898. byte j = (byte)BytePrecision(length);
  13899. if (output) {
  13900. /* Encode count byte. */
  13901. output[i] = (byte)(j | ASN_LONG_LENGTH);
  13902. }
  13903. /* Skip over count byte. */
  13904. i++;
  13905. /* Encode value as a big-endian byte array. */
  13906. for (; j > 0; --j) {
  13907. if (output) {
  13908. /* Encode next most-significant byte. */
  13909. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13910. }
  13911. /* Skip over byte. */
  13912. i++;
  13913. }
  13914. }
  13915. /* Return number of bytes in encoded length. */
  13916. return i;
  13917. }
  13918. /* Encode a DER header - type/tag and length.
  13919. *
  13920. * @param [in] tag DER tag of ASN.1 item.
  13921. * @param [in] len Length of data in ASN.1 item.
  13922. * @param [out] output Buffer to encode into.
  13923. * @return Number of bytes encoded.
  13924. */
  13925. static word32 SetHeader(byte tag, word32 len, byte* output)
  13926. {
  13927. if (output) {
  13928. /* Encode tag first. */
  13929. output[0] = tag;
  13930. }
  13931. /* Encode the length. */
  13932. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13933. }
  13934. /* Encode a SEQUENCE header in DER.
  13935. *
  13936. * @param [in] len Length of data in SEQUENCE.
  13937. * @param [out] output Buffer to encode into.
  13938. * @return Number of bytes encoded.
  13939. */
  13940. word32 SetSequence(word32 len, byte* output)
  13941. {
  13942. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13943. }
  13944. /* Encode an OCTET STRING header in DER.
  13945. *
  13946. * @param [in] len Length of data in OCTET STRING.
  13947. * @param [out] output Buffer to encode into.
  13948. * @return Number of bytes encoded.
  13949. */
  13950. word32 SetOctetString(word32 len, byte* output)
  13951. {
  13952. return SetHeader(ASN_OCTET_STRING, len, output);
  13953. }
  13954. /* Encode a SET header in DER.
  13955. *
  13956. * @param [in] len Length of data in SET.
  13957. * @param [out] output Buffer to encode into.
  13958. * @return Number of bytes encoded.
  13959. */
  13960. word32 SetSet(word32 len, byte* output)
  13961. {
  13962. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13963. }
  13964. /* Encode an implicit context specific header in DER.
  13965. *
  13966. * Implicit means that it is constructed only if the included ASN.1 item is.
  13967. *
  13968. * @param [in] tag Tag for the implicit ASN.1 item.
  13969. * @param [in] number Context specific number.
  13970. * @param [in] len Length of data in SET.
  13971. * @param [out] output Buffer to encode into.
  13972. * @return Number of bytes encoded.
  13973. */
  13974. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13975. {
  13976. tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13977. | ASN_CONTEXT_SPECIFIC | number);
  13978. return SetHeader(tag, len, output);
  13979. }
  13980. /* Encode an explicit context specific header in DER.
  13981. *
  13982. * Explicit means that there will be an ASN.1 item underneath.
  13983. *
  13984. * @param [in] number Context specific number.
  13985. * @param [in] len Length of data in SET.
  13986. * @param [out] output Buffer to encode into.
  13987. * @return Number of bytes encoded.
  13988. */
  13989. word32 SetExplicit(byte number, word32 len, byte* output)
  13990. {
  13991. return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
  13992. len, output);
  13993. }
  13994. #if defined(OPENSSL_EXTRA)
  13995. /* Encode an Othername into DER.
  13996. *
  13997. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  13998. * @param [out] output Buffer to encode into. If NULL, don't encode.
  13999. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  14000. */
  14001. word32 SetOthername(void *name, byte *output)
  14002. {
  14003. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  14004. char *nameStr = NULL;
  14005. word32 nameSz = 0;
  14006. word32 len = 0;
  14007. if ((nm == NULL) || (nm->value == NULL)) {
  14008. WOLFSSL_MSG("otherName value is NULL");
  14009. return WOLFSSL_FAILURE;
  14010. }
  14011. nameStr = nm->value->value.utf8string->data;
  14012. nameSz = (word32)nm->value->value.utf8string->length;
  14013. len = nm->type_id->objSz +
  14014. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
  14015. SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
  14016. if (output != NULL) {
  14017. /* otherName OID */
  14018. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  14019. output += nm->type_id->objSz;
  14020. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  14021. output);
  14022. output += SetHeader(CTC_UTF8, nameSz, output);
  14023. XMEMCPY(output, nameStr, nameSz);
  14024. }
  14025. return len;
  14026. }
  14027. #endif /* OPENSSL_EXTRA */
  14028. #ifdef HAVE_ECC
  14029. /* Determines whether the signature algorithm is using ECDSA.
  14030. *
  14031. * @param [in] algoOID Signature algorithm identifier.
  14032. * @return 1 when algorithm is using ECDSA.
  14033. * @return 0 otherwise.
  14034. */
  14035. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  14036. {
  14037. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  14038. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  14039. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  14040. return 1;
  14041. }
  14042. return 0;
  14043. }
  14044. #endif
  14045. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  14046. * and post-quantum algorithms.
  14047. *
  14048. * @param [in] algoOID Algorithm OID.
  14049. * @return 1 when is EC signing algorithm.
  14050. * @return 0 otherwise.
  14051. */
  14052. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  14053. {
  14054. (void)algoOID;
  14055. return (0
  14056. #ifdef HAVE_ECC
  14057. || IsSigAlgoECDSA(algoOID)
  14058. #endif
  14059. #ifdef WOLFSSL_SM2
  14060. || (algoOID == SM2k)
  14061. #endif
  14062. #ifdef HAVE_ED25519
  14063. || (algoOID == ED25519k)
  14064. #endif
  14065. #ifdef HAVE_CURVE25519
  14066. || (algoOID == X25519k)
  14067. #endif
  14068. #ifdef HAVE_ED448
  14069. || (algoOID == ED448k)
  14070. #endif
  14071. #ifdef HAVE_CURVE448
  14072. || (algoOID == X448k)
  14073. #endif
  14074. #ifdef HAVE_PQC
  14075. #ifdef HAVE_FACON
  14076. || (algoOID == FALCON_LEVEL1k)
  14077. || (algoOID == FALCON_LEVEL5k)
  14078. #endif
  14079. #ifdef HAVE_DILITHIUM
  14080. || (algoOID == DILITHIUM_LEVEL2k)
  14081. || (algoOID == DILITHIUM_LEVEL3k)
  14082. || (algoOID == DILITHIUM_LEVEL5k)
  14083. #endif
  14084. #ifdef HAVE_SPHINCS
  14085. || (algoOID == SPHINCS_FAST_LEVEL1k)
  14086. || (algoOID == SPHINCS_FAST_LEVEL3k)
  14087. || (algoOID == SPHINCS_FAST_LEVEL5k)
  14088. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  14089. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  14090. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  14091. #endif
  14092. #endif /* HAVE_PQC */
  14093. );
  14094. }
  14095. /* Encode an algorithm identifier.
  14096. *
  14097. * [algoOID, type] is unique.
  14098. *
  14099. * @param [in] algoOID Algorithm identifier.
  14100. * @param [out] output Buffer to hold encoding.
  14101. * @param [in] type Type of OID being encoded.
  14102. * @param [in] curveSz Add extra space for curve data.
  14103. * @return Encoded data size on success.
  14104. * @return 0 when dynamic memory allocation fails.
  14105. */
  14106. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  14107. {
  14108. #ifndef WOLFSSL_ASN_TEMPLATE
  14109. word32 tagSz, idSz, seqSz, algoSz = 0;
  14110. const byte* algoName = 0;
  14111. byte ID_Length[1 + MAX_LENGTH_SZ];
  14112. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  14113. word32 length = 0;
  14114. tagSz = (type == oidHashType ||
  14115. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  14116. (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
  14117. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  14118. if (algoName == NULL) {
  14119. WOLFSSL_MSG("Unknown Algorithm");
  14120. return 0;
  14121. }
  14122. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  14123. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  14124. /* Copy only algo to output for DSA keys */
  14125. if (algoOID == DSAk && output) {
  14126. XMEMCPY(output, ID_Length, idSz);
  14127. XMEMCPY(output + idSz, algoName, algoSz);
  14128. if (tagSz == 2)
  14129. SetASNNull(&output[seqSz + idSz + algoSz]);
  14130. }
  14131. else if (output) {
  14132. XMEMCPY(output, seqArray, seqSz);
  14133. XMEMCPY(output + seqSz, ID_Length, idSz);
  14134. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  14135. if (tagSz == 2)
  14136. SetASNNull(&output[seqSz + idSz + algoSz]);
  14137. }
  14138. if (algoOID == DSAk)
  14139. length = idSz + algoSz + tagSz;
  14140. else
  14141. length = seqSz + idSz + algoSz + tagSz;
  14142. return length;
  14143. #else
  14144. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  14145. int ret = 0;
  14146. const byte* algoName = 0;
  14147. word32 algoSz = 0;
  14148. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  14149. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  14150. if (algoName == NULL) {
  14151. WOLFSSL_MSG("Unknown Algorithm");
  14152. }
  14153. else {
  14154. int sz;
  14155. int o = 0;
  14156. /* Set the OID and OID type to encode. */
  14157. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  14158. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  14159. if (!(type == oidHashType ||
  14160. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  14161. (type == oidKeyType && algoOID == RSAk))) {
  14162. /* Don't put out NULL DER item. */
  14163. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  14164. }
  14165. if (algoOID == DSAk) {
  14166. /* Don't include SEQUENCE for DSA keys. */
  14167. o = 1;
  14168. }
  14169. else if (curveSz > 0) {
  14170. /* Don't put out NULL DER item. */
  14171. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  14172. /* Include space for extra data of length curveSz.
  14173. * Subtract 1 for sequence and 1 for length encoding. */
  14174. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  14175. (word32)curveSz - 2);
  14176. }
  14177. /* Calculate size of encoding. */
  14178. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  14179. (int)algoIdASN_Length - (int)o, &sz);
  14180. if (ret == 0 && output != NULL) {
  14181. /* Encode into buffer. */
  14182. SetASN_Items(algoIdASN + o, dataASN + o,
  14183. (int)algoIdASN_Length - (int)o, output);
  14184. if (curveSz > 0) {
  14185. /* Return size excluding curve data. */
  14186. sz = (int)(dataASN[o].offset -
  14187. dataASN[ALGOIDASN_IDX_NULL].offset);
  14188. }
  14189. }
  14190. if (ret == 0) {
  14191. /* Return encoded size. */
  14192. ret = sz;
  14193. }
  14194. else {
  14195. /* Unsigned return type so 0 indicates error. */
  14196. ret = 0;
  14197. }
  14198. }
  14199. FREE_ASNSETDATA(dataASN, NULL);
  14200. return (word32)ret;
  14201. #endif /* WOLFSSL_ASN_TEMPLATE */
  14202. }
  14203. #ifdef WOLFSSL_ASN_TEMPLATE
  14204. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  14205. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  14206. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  14207. */
  14208. static const ASNItem digestInfoASN[] = {
  14209. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14210. /* digestAlgorithm */
  14211. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14212. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  14213. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  14214. /* digest */
  14215. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  14216. };
  14217. enum {
  14218. DIGESTINFOASN_IDX_SEQ = 0,
  14219. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  14220. DIGESTINFOASN_IDX_DIGALGO_OID,
  14221. DIGESTINFOASN_IDX_DIGALGO_NULL,
  14222. DIGESTINFOASN_IDX_DIGEST
  14223. };
  14224. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  14225. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  14226. #endif
  14227. /* Encode signature.
  14228. *
  14229. * @param [out] out Buffer to hold encoding.
  14230. * @param [in] digest Buffer holding digest.
  14231. * @param [in] digSz Length of digest in bytes.
  14232. * @return Encoded data size on success.
  14233. * @return 0 when dynamic memory allocation fails.
  14234. */
  14235. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  14236. int hashOID)
  14237. {
  14238. #ifndef WOLFSSL_ASN_TEMPLATE
  14239. byte digArray[MAX_ENCODED_DIG_SZ];
  14240. byte algoArray[MAX_ALGO_SZ];
  14241. byte seqArray[MAX_SEQ_SZ];
  14242. word32 encDigSz, algoSz, seqSz;
  14243. encDigSz = SetDigest(digest, digSz, digArray);
  14244. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  14245. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  14246. XMEMCPY(out, seqArray, seqSz);
  14247. XMEMCPY(out + seqSz, algoArray, algoSz);
  14248. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  14249. return encDigSz + algoSz + seqSz;
  14250. #else
  14251. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  14252. int ret = 0;
  14253. int sz;
  14254. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  14255. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  14256. if (ret == 0) {
  14257. /* Set hash OID and type. */
  14258. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  14259. oidHashType);
  14260. /* Set digest. */
  14261. if (digest == out) {
  14262. XMEMCPY(dgst, digest, digSz);
  14263. digest = dgst;
  14264. }
  14265. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  14266. /* Calculate size of encoding. */
  14267. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  14268. }
  14269. if (ret == 0) {
  14270. /* Encode PKCS#1 v1.5 RSA signature. */
  14271. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  14272. ret = sz;
  14273. }
  14274. else {
  14275. /* Unsigned return type so 0 indicates error. */
  14276. ret = 0;
  14277. }
  14278. FREE_ASNSETDATA(dataASN, NULL);
  14279. return (word32)ret;
  14280. #endif
  14281. }
  14282. #ifndef NO_CERTS
  14283. int wc_GetCTC_HashOID(int type)
  14284. {
  14285. int ret;
  14286. enum wc_HashType hType;
  14287. hType = wc_HashTypeConvert(type);
  14288. ret = wc_HashGetOID(hType);
  14289. if (ret < 0) {
  14290. ret = 0; /* backwards compatibility */
  14291. }
  14292. return ret;
  14293. }
  14294. /* Initialize a signature context object.
  14295. *
  14296. * Object used for signing and verifying a certificate signature.
  14297. *
  14298. * @param [in, out] sigCtx Signature context object.
  14299. * @param [in] heap Dynamic memory hint.
  14300. * @param [in] devId Hardware device identifier.
  14301. */
  14302. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  14303. {
  14304. if (sigCtx) {
  14305. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  14306. sigCtx->devId = devId;
  14307. sigCtx->heap = heap;
  14308. }
  14309. }
  14310. /* Free dynamic data in a signature context object.
  14311. *
  14312. * @param [in, out] sigCtx Signature context object.
  14313. */
  14314. void FreeSignatureCtx(SignatureCtx* sigCtx)
  14315. {
  14316. if (sigCtx == NULL)
  14317. return;
  14318. if (sigCtx->digest) {
  14319. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  14320. sigCtx->digest = NULL;
  14321. }
  14322. #if !(defined(NO_RSA) && defined(NO_DSA))
  14323. if (sigCtx->sigCpy) {
  14324. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14325. sigCtx->sigCpy = NULL;
  14326. }
  14327. #endif
  14328. #ifndef NO_ASN_CRYPT
  14329. if (sigCtx->key.ptr) {
  14330. switch (sigCtx->keyOID) {
  14331. #ifndef NO_RSA
  14332. #ifdef WC_RSA_PSS
  14333. case RSAPSSk:
  14334. #endif
  14335. case RSAk:
  14336. wc_FreeRsaKey(sigCtx->key.rsa);
  14337. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  14338. sigCtx->key.rsa = NULL;
  14339. break;
  14340. #endif /* !NO_RSA */
  14341. #ifndef NO_DSA
  14342. case DSAk:
  14343. wc_FreeDsaKey(sigCtx->key.dsa);
  14344. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  14345. sigCtx->key.dsa = NULL;
  14346. break;
  14347. #endif
  14348. #ifdef HAVE_ECC
  14349. case ECDSAk:
  14350. #ifdef WOLFSSL_SM2
  14351. case SM2k:
  14352. #endif
  14353. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14354. defined(WC_ASYNC_ENABLE_ECC)
  14355. if (sigCtx->key.ecc->nb_ctx != NULL) {
  14356. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  14357. DYNAMIC_TYPE_TMP_BUFFER);
  14358. }
  14359. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14360. WC_ASYNC_ENABLE_ECC */
  14361. wc_ecc_free(sigCtx->key.ecc);
  14362. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  14363. sigCtx->key.ecc = NULL;
  14364. break;
  14365. #endif /* HAVE_ECC */
  14366. #ifdef HAVE_ED25519
  14367. case ED25519k:
  14368. wc_ed25519_free(sigCtx->key.ed25519);
  14369. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  14370. sigCtx->key.ed25519 = NULL;
  14371. break;
  14372. #endif /* HAVE_ED25519 */
  14373. #ifdef HAVE_ED448
  14374. case ED448k:
  14375. wc_ed448_free(sigCtx->key.ed448);
  14376. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  14377. sigCtx->key.ed448 = NULL;
  14378. break;
  14379. #endif /* HAVE_ED448 */
  14380. #if defined(HAVE_PQC)
  14381. #if defined(HAVE_FALCON)
  14382. case FALCON_LEVEL1k:
  14383. case FALCON_LEVEL5k:
  14384. wc_falcon_free(sigCtx->key.falcon);
  14385. XFREE(sigCtx->key.falcon, sigCtx->heap,
  14386. DYNAMIC_TYPE_FALCON);
  14387. sigCtx->key.falcon = NULL;
  14388. break;
  14389. #endif /* HAVE_FALCON */
  14390. #if defined(HAVE_DILITHIUM)
  14391. case DILITHIUM_LEVEL2k:
  14392. case DILITHIUM_LEVEL3k:
  14393. case DILITHIUM_LEVEL5k:
  14394. wc_dilithium_free(sigCtx->key.dilithium);
  14395. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  14396. DYNAMIC_TYPE_DILITHIUM);
  14397. sigCtx->key.dilithium = NULL;
  14398. break;
  14399. #endif /* HAVE_DILITHIUM */
  14400. #if defined(HAVE_SPHINCS)
  14401. case SPHINCS_FAST_LEVEL1k:
  14402. case SPHINCS_FAST_LEVEL3k:
  14403. case SPHINCS_FAST_LEVEL5k:
  14404. case SPHINCS_SMALL_LEVEL1k:
  14405. case SPHINCS_SMALL_LEVEL3k:
  14406. case SPHINCS_SMALL_LEVEL5k:
  14407. wc_sphincs_free(sigCtx->key.sphincs);
  14408. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  14409. DYNAMIC_TYPE_SPHINCS);
  14410. sigCtx->key.sphincs = NULL;
  14411. break;
  14412. #endif /* HAVE_SPHINCS */
  14413. #endif /* HAVE_PQC */
  14414. default:
  14415. break;
  14416. } /* switch (keyOID) */
  14417. sigCtx->key.ptr = NULL;
  14418. }
  14419. #endif
  14420. /* reset state, we are done */
  14421. sigCtx->state = SIG_STATE_BEGIN;
  14422. }
  14423. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  14424. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  14425. byte* digest, int* typeH, int* digestSz, int verify)
  14426. {
  14427. int ret = 0;
  14428. switch (sigOID) {
  14429. #if defined(WOLFSSL_MD2)
  14430. case CTC_MD2wRSA:
  14431. if (!verify) {
  14432. ret = HASH_TYPE_E;
  14433. WOLFSSL_MSG("MD2 not supported for signing");
  14434. }
  14435. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  14436. *typeH = MD2h;
  14437. *digestSz = MD2_DIGEST_SIZE;
  14438. }
  14439. break;
  14440. #endif
  14441. #ifndef NO_MD5
  14442. case CTC_MD5wRSA:
  14443. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  14444. *typeH = MD5h;
  14445. *digestSz = WC_MD5_DIGEST_SIZE;
  14446. }
  14447. break;
  14448. #endif
  14449. #ifndef NO_SHA
  14450. case CTC_SHAwRSA:
  14451. case CTC_SHAwDSA:
  14452. case CTC_SHAwECDSA:
  14453. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  14454. *typeH = SHAh;
  14455. *digestSz = WC_SHA_DIGEST_SIZE;
  14456. }
  14457. break;
  14458. #endif
  14459. #ifdef WOLFSSL_SHA224
  14460. case CTC_SHA224wRSA:
  14461. case CTC_SHA224wECDSA:
  14462. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  14463. *typeH = SHA224h;
  14464. *digestSz = WC_SHA224_DIGEST_SIZE;
  14465. }
  14466. break;
  14467. #endif
  14468. #ifndef NO_SHA256
  14469. case CTC_SHA256wRSA:
  14470. case CTC_SHA256wECDSA:
  14471. case CTC_SHA256wDSA:
  14472. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  14473. *typeH = SHA256h;
  14474. *digestSz = WC_SHA256_DIGEST_SIZE;
  14475. }
  14476. break;
  14477. #endif
  14478. #ifdef WOLFSSL_SHA384
  14479. case CTC_SHA384wRSA:
  14480. case CTC_SHA384wECDSA:
  14481. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  14482. *typeH = SHA384h;
  14483. *digestSz = WC_SHA384_DIGEST_SIZE;
  14484. }
  14485. break;
  14486. #endif
  14487. #ifdef WOLFSSL_SHA512
  14488. case CTC_SHA512wRSA:
  14489. case CTC_SHA512wECDSA:
  14490. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  14491. *typeH = SHA512h;
  14492. *digestSz = WC_SHA512_DIGEST_SIZE;
  14493. }
  14494. break;
  14495. #endif
  14496. #ifdef WOLFSSL_SHA3
  14497. #ifndef WOLFSSL_NOSHA3_224
  14498. case CTC_SHA3_224wRSA:
  14499. case CTC_SHA3_224wECDSA:
  14500. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  14501. *typeH = SHA3_224h;
  14502. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  14503. }
  14504. break;
  14505. #endif
  14506. #ifndef WOLFSSL_NOSHA3_256
  14507. case CTC_SHA3_256wRSA:
  14508. case CTC_SHA3_256wECDSA:
  14509. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  14510. *typeH = SHA3_256h;
  14511. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  14512. }
  14513. break;
  14514. #endif
  14515. #ifndef WOLFSSL_NOSHA3_384
  14516. case CTC_SHA3_384wRSA:
  14517. case CTC_SHA3_384wECDSA:
  14518. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  14519. *typeH = SHA3_384h;
  14520. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  14521. }
  14522. break;
  14523. #endif
  14524. #ifndef WOLFSSL_NOSHA3_512
  14525. case CTC_SHA3_512wRSA:
  14526. case CTC_SHA3_512wECDSA:
  14527. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  14528. *typeH = SHA3_512h;
  14529. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  14530. }
  14531. break;
  14532. #endif
  14533. #endif
  14534. #if defined(WOLFSSL_SM2) & defined(WOLFSSL_SM3)
  14535. case CTC_SM3wSM2:
  14536. if ((ret = wc_Sm3Hash(buf, bufSz, digest)) == 0) {
  14537. *typeH = SM3h;
  14538. *digestSz = WC_SM3_DIGEST_SIZE;
  14539. }
  14540. break;
  14541. #endif
  14542. #ifdef HAVE_ED25519
  14543. case CTC_ED25519:
  14544. /* Hashes done in signing operation.
  14545. * Two dependent hashes with prefixes performed.
  14546. */
  14547. break;
  14548. #endif
  14549. #ifdef HAVE_ED448
  14550. case CTC_ED448:
  14551. /* Hashes done in signing operation.
  14552. * Two dependent hashes with prefixes performed.
  14553. */
  14554. break;
  14555. #endif
  14556. #ifdef HAVE_PQC
  14557. #ifdef HAVE_FALCON
  14558. case CTC_FALCON_LEVEL1:
  14559. case CTC_FALCON_LEVEL5:
  14560. /* Hashes done in signing operation. */
  14561. break;
  14562. #endif
  14563. #ifdef HAVE_DILITHIUM
  14564. case CTC_DILITHIUM_LEVEL2:
  14565. case CTC_DILITHIUM_LEVEL3:
  14566. case CTC_DILITHIUM_LEVEL5:
  14567. /* Hashes done in signing operation. */
  14568. break;
  14569. #endif
  14570. #ifdef HAVE_SPHINCS
  14571. case CTC_SPHINCS_FAST_LEVEL1:
  14572. case CTC_SPHINCS_FAST_LEVEL3:
  14573. case CTC_SPHINCS_FAST_LEVEL5:
  14574. case CTC_SPHINCS_SMALL_LEVEL1:
  14575. case CTC_SPHINCS_SMALL_LEVEL3:
  14576. case CTC_SPHINCS_SMALL_LEVEL5:
  14577. /* Hashes done in signing operation. */
  14578. break;
  14579. #endif
  14580. #endif /* HAVE_PQC */
  14581. default:
  14582. ret = HASH_TYPE_E;
  14583. WOLFSSL_MSG("Hash for Signature has unsupported type");
  14584. }
  14585. (void)buf;
  14586. (void)bufSz;
  14587. (void)sigOID;
  14588. (void)digest;
  14589. (void)digestSz;
  14590. (void)typeH;
  14591. (void)verify;
  14592. return ret;
  14593. }
  14594. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  14595. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  14596. static int ConfirmSignature(SignatureCtx* sigCtx,
  14597. const byte* buf, word32 bufSz,
  14598. const byte* key, word32 keySz, word32 keyOID,
  14599. const byte* sig, word32 sigSz, word32 sigOID,
  14600. const byte* sigParams, word32 sigParamsSz,
  14601. byte* rsaKeyIdx)
  14602. {
  14603. int ret = 0;
  14604. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  14605. CertAttribute* certatt = NULL;
  14606. #endif
  14607. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  14608. keySz == 0 || sig == NULL || sigSz == 0) {
  14609. return BAD_FUNC_ARG;
  14610. }
  14611. (void)key;
  14612. (void)keySz;
  14613. (void)sig;
  14614. (void)sigSz;
  14615. (void)sigParams;
  14616. (void)sigParamsSz;
  14617. WOLFSSL_ENTER("ConfirmSignature");
  14618. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_FSPSM_TLS)
  14619. (void)rsaKeyIdx;
  14620. #else
  14621. #if !defined(NO_RSA) || defined(HAVE_ECC)
  14622. certatt = (CertAttribute*)&sigCtx->CertAtt;
  14623. #endif
  14624. if (certatt) {
  14625. certatt->keyIndex = rsaKeyIdx;
  14626. certatt->cert = buf;
  14627. certatt->certSz = bufSz;
  14628. }
  14629. #endif
  14630. #ifndef NO_ASN_CRYPT
  14631. switch (sigCtx->state) {
  14632. case SIG_STATE_BEGIN:
  14633. {
  14634. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  14635. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  14636. DYNAMIC_TYPE_DIGEST);
  14637. if (sigCtx->digest == NULL) {
  14638. ERROR_OUT(MEMORY_E, exit_cs);
  14639. }
  14640. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14641. /* RSA PSS Defaults */
  14642. sigCtx->hash = WC_HASH_TYPE_SHA;
  14643. sigCtx->mgf = WC_MGF1SHA1;
  14644. sigCtx->saltLen = 20;
  14645. #endif
  14646. sigCtx->state = SIG_STATE_HASH;
  14647. } /* SIG_STATE_BEGIN */
  14648. FALL_THROUGH;
  14649. case SIG_STATE_HASH:
  14650. {
  14651. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14652. if (sigOID == RSAPSSk) {
  14653. word32 fakeSigOID = 0;
  14654. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  14655. &sigCtx->mgf, &sigCtx->saltLen);
  14656. if (ret != 0) {
  14657. goto exit_cs;
  14658. }
  14659. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  14660. if (ret != 0) {
  14661. goto exit_cs;
  14662. }
  14663. /* Decode parameters. */
  14664. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  14665. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14666. if (ret != 0) {
  14667. goto exit_cs;
  14668. }
  14669. }
  14670. else
  14671. #endif
  14672. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14673. if (sigOID == CTC_SM3wSM2) {
  14674. ; /* SM2 hash requires public key. Done later. */
  14675. }
  14676. else
  14677. #endif
  14678. {
  14679. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  14680. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14681. if (ret != 0) {
  14682. goto exit_cs;
  14683. }
  14684. }
  14685. sigCtx->state = SIG_STATE_KEY;
  14686. } /* SIG_STATE_HASH */
  14687. FALL_THROUGH;
  14688. case SIG_STATE_KEY:
  14689. {
  14690. switch (keyOID) {
  14691. #ifndef NO_RSA
  14692. #ifdef WC_RSA_PSS
  14693. case RSAPSSk:
  14694. #endif
  14695. case RSAk:
  14696. {
  14697. word32 idx = 0;
  14698. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  14699. sigCtx->heap, DYNAMIC_TYPE_RSA);
  14700. if (sigCtx->key.rsa == NULL) {
  14701. ERROR_OUT(MEMORY_E, exit_cs);
  14702. }
  14703. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  14704. sigCtx->devId)) != 0) {
  14705. goto exit_cs;
  14706. }
  14707. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  14708. DYNAMIC_TYPE_SIGNATURE);
  14709. if (sigCtx->sigCpy == NULL) {
  14710. ERROR_OUT(MEMORY_E, exit_cs);
  14711. }
  14712. if (sigSz > MAX_ENCODED_SIG_SZ) {
  14713. WOLFSSL_MSG("Verify Signature is too big");
  14714. ERROR_OUT(BUFFER_E, exit_cs);
  14715. }
  14716. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  14717. keySz)) != 0) {
  14718. WOLFSSL_MSG("ASN Key decode error RSA");
  14719. WOLFSSL_ERROR_VERBOSE(ret);
  14720. goto exit_cs;
  14721. }
  14722. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14723. sigCtx->out = NULL;
  14724. #ifdef WOLFSSL_ASYNC_CRYPT
  14725. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  14726. #endif
  14727. break;
  14728. }
  14729. #endif /* !NO_RSA */
  14730. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14731. case DSAk:
  14732. {
  14733. word32 idx = 0;
  14734. if (sigSz < DSA_MIN_SIG_SIZE) {
  14735. WOLFSSL_MSG("Verify Signature is too small");
  14736. ERROR_OUT(BUFFER_E, exit_cs);
  14737. }
  14738. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  14739. sigCtx->heap, DYNAMIC_TYPE_DSA);
  14740. if (sigCtx->key.dsa == NULL) {
  14741. ERROR_OUT(MEMORY_E, exit_cs);
  14742. }
  14743. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  14744. WOLFSSL_MSG("wc_InitDsaKey_h error");
  14745. goto exit_cs;
  14746. }
  14747. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  14748. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14749. if (sigCtx->sigCpy == NULL) {
  14750. ERROR_OUT(MEMORY_E, exit_cs);
  14751. }
  14752. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  14753. keySz)) != 0) {
  14754. WOLFSSL_MSG("ASN Key decode error DSA");
  14755. WOLFSSL_ERROR_VERBOSE(ret);
  14756. goto exit_cs;
  14757. }
  14758. if (sigSz != DSA_160_SIG_SIZE &&
  14759. sigSz != DSA_256_SIG_SIZE) {
  14760. /* Try to parse it as the contents of a bitstring */
  14761. #ifdef WOLFSSL_SMALL_STACK
  14762. mp_int* r;
  14763. mp_int* s;
  14764. #else
  14765. mp_int r[1];
  14766. mp_int s[1];
  14767. #endif
  14768. int rSz;
  14769. int sSz;
  14770. #ifdef WOLFSSL_SMALL_STACK
  14771. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14772. DYNAMIC_TYPE_TMP_BUFFER);
  14773. if (r == NULL) {
  14774. ERROR_OUT(MEMORY_E, exit_cs);
  14775. }
  14776. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14777. DYNAMIC_TYPE_TMP_BUFFER);
  14778. if (s == NULL) {
  14779. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14780. ERROR_OUT(MEMORY_E, exit_cs);
  14781. }
  14782. #endif
  14783. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  14784. goto exit_cs;
  14785. }
  14786. idx = 0;
  14787. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14788. != 0) {
  14789. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14790. "incorrect format");
  14791. mp_free(r);
  14792. mp_free(s);
  14793. #ifdef WOLFSSL_SMALL_STACK
  14794. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14795. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14796. #endif
  14797. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14798. }
  14799. rSz = mp_unsigned_bin_size(r);
  14800. sSz = mp_unsigned_bin_size(s);
  14801. if (rSz + sSz > (int)sigSz) {
  14802. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14803. "incorrect format");
  14804. mp_free(r);
  14805. mp_free(s);
  14806. #ifdef WOLFSSL_SMALL_STACK
  14807. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14808. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14809. #endif
  14810. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14811. }
  14812. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14813. mp_to_unsigned_bin(s,
  14814. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14815. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14816. "incorrect format");
  14817. mp_free(r);
  14818. mp_free(s);
  14819. #ifdef WOLFSSL_SMALL_STACK
  14820. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14821. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14822. #endif
  14823. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14824. }
  14825. mp_free(r);
  14826. mp_free(s);
  14827. #ifdef WOLFSSL_SMALL_STACK
  14828. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14829. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14830. #endif
  14831. }
  14832. else {
  14833. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14834. }
  14835. break;
  14836. }
  14837. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14838. #ifdef HAVE_ECC
  14839. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14840. case SM2k:
  14841. #endif
  14842. case ECDSAk:
  14843. {
  14844. word32 idx = 0;
  14845. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14846. defined(WC_ASYNC_ENABLE_ECC)
  14847. ecc_nb_ctx_t* nbCtx;
  14848. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14849. WC_ASYNC_ENABLE_ECC */
  14850. sigCtx->verify = 0;
  14851. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14852. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14853. if (sigCtx->key.ecc == NULL) {
  14854. ERROR_OUT(MEMORY_E, exit_cs);
  14855. }
  14856. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14857. sigCtx->devId)) < 0) {
  14858. goto exit_cs;
  14859. }
  14860. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14861. defined(WC_ASYNC_ENABLE_ECC)
  14862. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14863. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14864. if (nbCtx == NULL) {
  14865. ERROR_OUT(MEMORY_E, exit_cs);
  14866. }
  14867. else {
  14868. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14869. if (ret != 0) {
  14870. goto exit_cs;
  14871. }
  14872. }
  14873. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14874. WC_ASYNC_ENABLE_ECC */
  14875. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14876. keySz);
  14877. if (ret < 0) {
  14878. WOLFSSL_MSG("ASN Key import error ECC");
  14879. WOLFSSL_ERROR_VERBOSE(ret);
  14880. goto exit_cs;
  14881. }
  14882. #ifdef WOLFSSL_ASYNC_CRYPT
  14883. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14884. #endif
  14885. break;
  14886. }
  14887. #endif /* HAVE_ECC */
  14888. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14889. case ED25519k:
  14890. {
  14891. sigCtx->verify = 0;
  14892. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14893. sizeof(ed25519_key), sigCtx->heap,
  14894. DYNAMIC_TYPE_ED25519);
  14895. if (sigCtx->key.ed25519 == NULL) {
  14896. ERROR_OUT(MEMORY_E, exit_cs);
  14897. }
  14898. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14899. sigCtx->heap, sigCtx->devId)) < 0) {
  14900. goto exit_cs;
  14901. }
  14902. if ((ret = wc_ed25519_import_public(key, keySz,
  14903. sigCtx->key.ed25519)) < 0) {
  14904. WOLFSSL_MSG("ASN Key import error ED25519");
  14905. WOLFSSL_ERROR_VERBOSE(ret);
  14906. goto exit_cs;
  14907. }
  14908. #ifdef WOLFSSL_ASYNC_CRYPT
  14909. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14910. #endif
  14911. break;
  14912. }
  14913. #endif
  14914. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14915. case ED448k:
  14916. {
  14917. sigCtx->verify = 0;
  14918. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14919. sizeof(ed448_key), sigCtx->heap,
  14920. DYNAMIC_TYPE_ED448);
  14921. if (sigCtx->key.ed448 == NULL) {
  14922. ERROR_OUT(MEMORY_E, exit_cs);
  14923. }
  14924. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14925. goto exit_cs;
  14926. }
  14927. if ((ret = wc_ed448_import_public(key, keySz,
  14928. sigCtx->key.ed448)) < 0) {
  14929. WOLFSSL_MSG("ASN Key import error ED448");
  14930. WOLFSSL_ERROR_VERBOSE(ret);
  14931. goto exit_cs;
  14932. }
  14933. #ifdef WOLFSSL_ASYNC_CRYPT
  14934. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14935. #endif
  14936. break;
  14937. }
  14938. #endif
  14939. #if defined(HAVE_PQC)
  14940. #if defined(HAVE_FALCON)
  14941. case FALCON_LEVEL1k:
  14942. {
  14943. sigCtx->verify = 0;
  14944. sigCtx->key.falcon =
  14945. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14946. sigCtx->heap,
  14947. DYNAMIC_TYPE_FALCON);
  14948. if (sigCtx->key.falcon == NULL) {
  14949. ERROR_OUT(MEMORY_E, exit_cs);
  14950. }
  14951. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14952. goto exit_cs;
  14953. }
  14954. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14955. < 0) {
  14956. goto exit_cs;
  14957. }
  14958. if ((ret = wc_falcon_import_public(key, keySz,
  14959. sigCtx->key.falcon)) < 0) {
  14960. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14961. WOLFSSL_ERROR_VERBOSE(ret);
  14962. goto exit_cs;
  14963. }
  14964. break;
  14965. }
  14966. case FALCON_LEVEL5k:
  14967. {
  14968. sigCtx->verify = 0;
  14969. sigCtx->key.falcon =
  14970. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14971. sigCtx->heap,
  14972. DYNAMIC_TYPE_FALCON);
  14973. if (sigCtx->key.falcon == NULL) {
  14974. ERROR_OUT(MEMORY_E, exit_cs);
  14975. }
  14976. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14977. goto exit_cs;
  14978. }
  14979. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14980. < 0) {
  14981. goto exit_cs;
  14982. }
  14983. if ((ret = wc_falcon_import_public(key, keySz,
  14984. sigCtx->key.falcon)) < 0) {
  14985. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14986. WOLFSSL_ERROR_VERBOSE(ret);
  14987. goto exit_cs;
  14988. }
  14989. break;
  14990. }
  14991. #endif /* HAVE_FALCON */
  14992. #if defined(HAVE_DILITHIUM)
  14993. case DILITHIUM_LEVEL2k:
  14994. {
  14995. sigCtx->verify = 0;
  14996. sigCtx->key.dilithium =
  14997. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14998. sigCtx->heap,
  14999. DYNAMIC_TYPE_DILITHIUM);
  15000. if (sigCtx->key.dilithium == NULL) {
  15001. ERROR_OUT(MEMORY_E, exit_cs);
  15002. }
  15003. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  15004. goto exit_cs;
  15005. }
  15006. if ((ret = wc_dilithium_set_level(
  15007. sigCtx->key.dilithium, 2))
  15008. < 0) {
  15009. goto exit_cs;
  15010. }
  15011. if ((ret = wc_dilithium_import_public(key, keySz,
  15012. sigCtx->key.dilithium)) < 0) {
  15013. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  15014. goto exit_cs;
  15015. }
  15016. break;
  15017. }
  15018. case DILITHIUM_LEVEL3k:
  15019. {
  15020. sigCtx->verify = 0;
  15021. sigCtx->key.dilithium =
  15022. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  15023. sigCtx->heap,
  15024. DYNAMIC_TYPE_DILITHIUM);
  15025. if (sigCtx->key.dilithium == NULL) {
  15026. ERROR_OUT(MEMORY_E, exit_cs);
  15027. }
  15028. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  15029. goto exit_cs;
  15030. }
  15031. if ((ret = wc_dilithium_set_level(
  15032. sigCtx->key.dilithium, 3))
  15033. < 0) {
  15034. goto exit_cs;
  15035. }
  15036. if ((ret = wc_dilithium_import_public(key, keySz,
  15037. sigCtx->key.dilithium)) < 0) {
  15038. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  15039. goto exit_cs;
  15040. }
  15041. break;
  15042. }
  15043. case DILITHIUM_LEVEL5k:
  15044. {
  15045. sigCtx->verify = 0;
  15046. sigCtx->key.dilithium =
  15047. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  15048. sigCtx->heap,
  15049. DYNAMIC_TYPE_DILITHIUM);
  15050. if (sigCtx->key.dilithium == NULL) {
  15051. ERROR_OUT(MEMORY_E, exit_cs);
  15052. }
  15053. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  15054. goto exit_cs;
  15055. }
  15056. if ((ret = wc_dilithium_set_level(
  15057. sigCtx->key.dilithium, 5))
  15058. < 0) {
  15059. goto exit_cs;
  15060. }
  15061. if ((ret = wc_dilithium_import_public(key, keySz,
  15062. sigCtx->key.dilithium)) < 0) {
  15063. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  15064. goto exit_cs;
  15065. }
  15066. break;
  15067. }
  15068. #endif /* HAVE_DILITHIUM */
  15069. #if defined(HAVE_SPHINCS)
  15070. case SPHINCS_FAST_LEVEL1k:
  15071. {
  15072. sigCtx->verify = 0;
  15073. sigCtx->key.sphincs =
  15074. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15075. sigCtx->heap,
  15076. DYNAMIC_TYPE_SPHINCS);
  15077. if (sigCtx->key.sphincs == NULL) {
  15078. ERROR_OUT(MEMORY_E, exit_cs);
  15079. }
  15080. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15081. goto exit_cs;
  15082. }
  15083. if ((ret = wc_sphincs_set_level_and_optim(
  15084. sigCtx->key.sphincs, 1, FAST_VARIANT))
  15085. < 0) {
  15086. goto exit_cs;
  15087. }
  15088. if ((ret = wc_sphincs_import_public(key, keySz,
  15089. sigCtx->key.sphincs)) < 0) {
  15090. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  15091. goto exit_cs;
  15092. }
  15093. break;
  15094. }
  15095. case SPHINCS_FAST_LEVEL3k:
  15096. {
  15097. sigCtx->verify = 0;
  15098. sigCtx->key.sphincs =
  15099. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15100. sigCtx->heap,
  15101. DYNAMIC_TYPE_SPHINCS);
  15102. if (sigCtx->key.sphincs == NULL) {
  15103. ERROR_OUT(MEMORY_E, exit_cs);
  15104. }
  15105. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15106. goto exit_cs;
  15107. }
  15108. if ((ret = wc_sphincs_set_level_and_optim(
  15109. sigCtx->key.sphincs, 3, FAST_VARIANT))
  15110. < 0) {
  15111. goto exit_cs;
  15112. }
  15113. if ((ret = wc_sphincs_import_public(key, keySz,
  15114. sigCtx->key.sphincs)) < 0) {
  15115. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  15116. goto exit_cs;
  15117. }
  15118. break;
  15119. }
  15120. case SPHINCS_FAST_LEVEL5k:
  15121. {
  15122. sigCtx->verify = 0;
  15123. sigCtx->key.sphincs =
  15124. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15125. sigCtx->heap,
  15126. DYNAMIC_TYPE_SPHINCS);
  15127. if (sigCtx->key.sphincs == NULL) {
  15128. ERROR_OUT(MEMORY_E, exit_cs);
  15129. }
  15130. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15131. goto exit_cs;
  15132. }
  15133. if ((ret = wc_sphincs_set_level_and_optim(
  15134. sigCtx->key.sphincs, 5, FAST_VARIANT))
  15135. < 0) {
  15136. goto exit_cs;
  15137. }
  15138. if ((ret = wc_sphincs_import_public(key, keySz,
  15139. sigCtx->key.sphincs)) < 0) {
  15140. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  15141. goto exit_cs;
  15142. }
  15143. break;
  15144. }
  15145. case SPHINCS_SMALL_LEVEL1k:
  15146. {
  15147. sigCtx->verify = 0;
  15148. sigCtx->key.sphincs =
  15149. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15150. sigCtx->heap,
  15151. DYNAMIC_TYPE_SPHINCS);
  15152. if (sigCtx->key.sphincs == NULL) {
  15153. ERROR_OUT(MEMORY_E, exit_cs);
  15154. }
  15155. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15156. goto exit_cs;
  15157. }
  15158. if ((ret = wc_sphincs_set_level_and_optim(
  15159. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  15160. < 0) {
  15161. goto exit_cs;
  15162. }
  15163. if ((ret = wc_sphincs_import_public(key, keySz,
  15164. sigCtx->key.sphincs)) < 0) {
  15165. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  15166. goto exit_cs;
  15167. }
  15168. break;
  15169. }
  15170. case SPHINCS_SMALL_LEVEL3k:
  15171. {
  15172. sigCtx->verify = 0;
  15173. sigCtx->key.sphincs =
  15174. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15175. sigCtx->heap,
  15176. DYNAMIC_TYPE_SPHINCS);
  15177. if (sigCtx->key.sphincs == NULL) {
  15178. ERROR_OUT(MEMORY_E, exit_cs);
  15179. }
  15180. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15181. goto exit_cs;
  15182. }
  15183. if ((ret = wc_sphincs_set_level_and_optim(
  15184. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  15185. < 0) {
  15186. goto exit_cs;
  15187. }
  15188. if ((ret = wc_sphincs_import_public(key, keySz,
  15189. sigCtx->key.sphincs)) < 0) {
  15190. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  15191. goto exit_cs;
  15192. }
  15193. break;
  15194. }
  15195. case SPHINCS_SMALL_LEVEL5k:
  15196. {
  15197. sigCtx->verify = 0;
  15198. sigCtx->key.sphincs =
  15199. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15200. sigCtx->heap,
  15201. DYNAMIC_TYPE_SPHINCS);
  15202. if (sigCtx->key.sphincs == NULL) {
  15203. ERROR_OUT(MEMORY_E, exit_cs);
  15204. }
  15205. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15206. goto exit_cs;
  15207. }
  15208. if ((ret = wc_sphincs_set_level_and_optim(
  15209. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  15210. < 0) {
  15211. goto exit_cs;
  15212. }
  15213. if ((ret = wc_sphincs_import_public(key, keySz,
  15214. sigCtx->key.sphincs)) < 0) {
  15215. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  15216. goto exit_cs;
  15217. }
  15218. break;
  15219. }
  15220. #endif /* HAVE_SPHINCS */
  15221. #endif /* HAVE_PQC */
  15222. default:
  15223. WOLFSSL_MSG("Verify Key type unknown");
  15224. ret = ASN_UNKNOWN_OID_E;
  15225. WOLFSSL_ERROR_VERBOSE(ret);
  15226. break;
  15227. } /* switch (keyOID) */
  15228. if (ret != 0) {
  15229. goto exit_cs;
  15230. }
  15231. sigCtx->state = SIG_STATE_DO;
  15232. #ifdef WOLFSSL_ASYNC_CRYPT
  15233. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  15234. /* make sure event is initialized */
  15235. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  15236. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  15237. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  15238. }
  15239. #endif
  15240. } /* SIG_STATE_KEY */
  15241. FALL_THROUGH;
  15242. case SIG_STATE_DO:
  15243. {
  15244. switch (keyOID) {
  15245. #ifndef NO_RSA
  15246. case RSAk:
  15247. #ifdef WC_RSA_PSS
  15248. case RSAPSSk:
  15249. if (sigOID == RSAPSSk) {
  15250. /* TODO: pkCbRsaPss - RSA PSS callback. */
  15251. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  15252. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  15253. sigCtx->saltLen, sigCtx->key.rsa);
  15254. }
  15255. else
  15256. #endif
  15257. {
  15258. #if defined(HAVE_PK_CALLBACKS)
  15259. if (sigCtx->pkCbRsa) {
  15260. ret = sigCtx->pkCbRsa(
  15261. sigCtx->sigCpy, sigSz, &sigCtx->out,
  15262. key, keySz,
  15263. sigCtx->pkCtxRsa);
  15264. }
  15265. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  15266. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15267. else
  15268. #else
  15269. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  15270. #endif /* WOLFSSL_RENESAS_FSPSM_TLS */
  15271. #endif /* HAVE_PK_CALLBACKS */
  15272. {
  15273. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  15274. &sigCtx->out, sigCtx->key.rsa);
  15275. }
  15276. }
  15277. break;
  15278. #endif /* !NO_RSA */
  15279. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15280. case DSAk:
  15281. {
  15282. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  15283. sigCtx->key.dsa, &sigCtx->verify);
  15284. break;
  15285. }
  15286. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15287. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15288. case SM2k:
  15289. {
  15290. /* OpenSSL creates signature without CERT_SIG_ID. */
  15291. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID, 0, buf, bufSz,
  15292. WC_HASH_TYPE_SM3, sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15293. sigCtx->key.ecc);
  15294. if (ret == 0) {
  15295. sigCtx->typeH = SM3h;
  15296. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15297. }
  15298. else {
  15299. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15300. WOLFSSL_ERROR_VERBOSE(ret);
  15301. goto exit_cs;
  15302. }
  15303. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15304. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15305. break;
  15306. }
  15307. #endif
  15308. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  15309. case ECDSAk:
  15310. {
  15311. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15312. if (sigOID == CTC_SM3wSM2) {
  15313. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID,
  15314. CERT_SIG_ID_SZ, buf, bufSz, WC_HASH_TYPE_SM3,
  15315. sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15316. sigCtx->key.ecc);
  15317. if (ret == 0) {
  15318. sigCtx->typeH = SM3h;
  15319. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15320. }
  15321. else {
  15322. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15323. WOLFSSL_ERROR_VERBOSE(ret);
  15324. goto exit_cs;
  15325. }
  15326. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15327. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15328. }
  15329. else
  15330. #endif
  15331. #if defined(HAVE_PK_CALLBACKS)
  15332. if (sigCtx->pkCbEcc) {
  15333. ret = sigCtx->pkCbEcc(
  15334. sig, sigSz,
  15335. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  15336. key, keySz, &sigCtx->verify,
  15337. sigCtx->pkCtxEcc);
  15338. }
  15339. #if !defined(WOLFSSL_RENESAS_FSPSM_TLS) && \
  15340. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15341. else
  15342. #else
  15343. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  15344. #endif /* WOLFSSL_RENESAS_FSPSM_TLS */
  15345. #endif /* HAVE_PK_CALLBACKS */
  15346. {
  15347. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  15348. (word32)sigCtx->digestSz, &sigCtx->verify,
  15349. sigCtx->key.ecc);
  15350. }
  15351. break;
  15352. }
  15353. #endif /* HAVE_ECC */
  15354. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  15355. case ED25519k:
  15356. {
  15357. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  15358. &sigCtx->verify, sigCtx->key.ed25519);
  15359. break;
  15360. }
  15361. #endif
  15362. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  15363. case ED448k:
  15364. {
  15365. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  15366. &sigCtx->verify, sigCtx->key.ed448,
  15367. NULL, 0);
  15368. break;
  15369. }
  15370. #endif
  15371. #if defined(HAVE_PQC)
  15372. #if defined(HAVE_FALCON)
  15373. case FALCON_LEVEL1k:
  15374. case FALCON_LEVEL5k:
  15375. {
  15376. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  15377. &sigCtx->verify,
  15378. sigCtx->key.falcon);
  15379. break;
  15380. }
  15381. #endif /* HAVE_FALCON */
  15382. #if defined(HAVE_DILITHIUM)
  15383. case DILITHIUM_LEVEL2k:
  15384. case DILITHIUM_LEVEL3k:
  15385. case DILITHIUM_LEVEL5k:
  15386. {
  15387. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  15388. &sigCtx->verify,
  15389. sigCtx->key.dilithium);
  15390. break;
  15391. }
  15392. #endif /* HAVE_DILITHIUM */
  15393. #if defined(HAVE_SPHINCS)
  15394. case SPHINCS_FAST_LEVEL1k:
  15395. case SPHINCS_FAST_LEVEL3k:
  15396. case SPHINCS_FAST_LEVEL5k:
  15397. case SPHINCS_SMALL_LEVEL1k:
  15398. case SPHINCS_SMALL_LEVEL3k:
  15399. case SPHINCS_SMALL_LEVEL5k:
  15400. {
  15401. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  15402. &sigCtx->verify,
  15403. sigCtx->key.sphincs);
  15404. break;
  15405. }
  15406. #endif /* HAVE_SPHINCS */
  15407. #endif /* HAVE_PQC */
  15408. default:
  15409. break;
  15410. } /* switch (keyOID) */
  15411. #ifdef WOLFSSL_ASYNC_CRYPT
  15412. if (ret == WC_PENDING_E) {
  15413. goto exit_cs;
  15414. }
  15415. #endif
  15416. if (ret < 0) {
  15417. /* treat all errors as ASN_SIG_CONFIRM_E */
  15418. ret = ASN_SIG_CONFIRM_E;
  15419. WOLFSSL_ERROR_VERBOSE(ret);
  15420. goto exit_cs;
  15421. }
  15422. sigCtx->state = SIG_STATE_CHECK;
  15423. } /* SIG_STATE_DO */
  15424. FALL_THROUGH;
  15425. case SIG_STATE_CHECK:
  15426. {
  15427. switch (keyOID) {
  15428. #ifndef NO_RSA
  15429. case RSAk:
  15430. #ifdef WC_RSA_PSS
  15431. case RSAPSSk:
  15432. if (sigOID == RSAPSSk) {
  15433. #if (defined(HAVE_SELFTEST) && \
  15434. (!defined(HAVE_SELFTEST_VERSION) || \
  15435. (HAVE_SELFTEST_VERSION < 2))) || \
  15436. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15437. (HAVE_FIPS_VERSION < 2))
  15438. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15439. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15440. sigCtx->saltLen);
  15441. #elif (defined(HAVE_SELFTEST) && \
  15442. (HAVE_SELFTEST_VERSION == 2)) || \
  15443. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15444. (HAVE_FIPS_VERSION == 2))
  15445. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15446. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15447. sigCtx->saltLen, 0);
  15448. #else
  15449. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  15450. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  15451. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  15452. sigCtx->heap);
  15453. #endif
  15454. break;
  15455. }
  15456. else
  15457. #endif
  15458. {
  15459. int encodedSigSz, verifySz;
  15460. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  15461. defined(WOLFSSL_RENESAS_FSPSM_TLS)
  15462. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  15463. #endif
  15464. #ifdef WOLFSSL_SMALL_STACK
  15465. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  15466. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15467. if (encodedSig == NULL) {
  15468. ERROR_OUT(MEMORY_E, exit_cs);
  15469. }
  15470. #else
  15471. byte encodedSig[MAX_ENCODED_SIG_SZ];
  15472. #endif
  15473. verifySz = ret;
  15474. /* make sure we're right justified */
  15475. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  15476. sigCtx->digest, (word32)sigCtx->digestSz,
  15477. sigCtx->typeH);
  15478. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  15479. XMEMCMP(sigCtx->out, encodedSig,
  15480. (size_t)encodedSigSz) == 0) {
  15481. ret = 0;
  15482. }
  15483. else {
  15484. WOLFSSL_MSG("RSA SSL verify match encode error");
  15485. ret = ASN_SIG_CONFIRM_E;
  15486. WOLFSSL_ERROR_VERBOSE(ret);
  15487. }
  15488. #ifdef WOLFSSL_SMALL_STACK
  15489. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15490. #endif
  15491. break;
  15492. }
  15493. #endif /* NO_RSA */
  15494. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15495. case DSAk:
  15496. {
  15497. if (sigCtx->verify == 1) {
  15498. ret = 0;
  15499. }
  15500. else {
  15501. WOLFSSL_MSG("DSA Verify didn't match");
  15502. ret = ASN_SIG_CONFIRM_E;
  15503. WOLFSSL_ERROR_VERBOSE(ret);
  15504. }
  15505. break;
  15506. }
  15507. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15508. #ifdef HAVE_ECC
  15509. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15510. case SM2k:
  15511. #endif
  15512. case ECDSAk:
  15513. {
  15514. if (sigCtx->verify == 1) {
  15515. ret = 0;
  15516. }
  15517. else {
  15518. WOLFSSL_MSG("ECC Verify didn't match");
  15519. ret = ASN_SIG_CONFIRM_E;
  15520. WOLFSSL_ERROR_VERBOSE(ret);
  15521. }
  15522. break;
  15523. }
  15524. #endif /* HAVE_ECC */
  15525. #ifdef HAVE_ED25519
  15526. case ED25519k:
  15527. {
  15528. if (sigCtx->verify == 1) {
  15529. ret = 0;
  15530. }
  15531. else {
  15532. WOLFSSL_MSG("ED25519 Verify didn't match");
  15533. ret = ASN_SIG_CONFIRM_E;
  15534. WOLFSSL_ERROR_VERBOSE(ret);
  15535. }
  15536. break;
  15537. }
  15538. #endif /* HAVE_ED25519 */
  15539. #ifdef HAVE_ED448
  15540. case ED448k:
  15541. {
  15542. if (sigCtx->verify == 1) {
  15543. ret = 0;
  15544. }
  15545. else {
  15546. WOLFSSL_MSG("ED448 Verify didn't match");
  15547. ret = ASN_SIG_CONFIRM_E;
  15548. WOLFSSL_ERROR_VERBOSE(ret);
  15549. }
  15550. break;
  15551. }
  15552. #endif /* HAVE_ED448 */
  15553. #ifdef HAVE_PQC
  15554. #ifdef HAVE_FALCON
  15555. case FALCON_LEVEL1k:
  15556. {
  15557. if (sigCtx->verify == 1) {
  15558. ret = 0;
  15559. }
  15560. else {
  15561. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  15562. ret = ASN_SIG_CONFIRM_E;
  15563. WOLFSSL_ERROR_VERBOSE(ret);
  15564. }
  15565. break;
  15566. }
  15567. case FALCON_LEVEL5k:
  15568. {
  15569. if (sigCtx->verify == 1) {
  15570. ret = 0;
  15571. }
  15572. else {
  15573. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  15574. ret = ASN_SIG_CONFIRM_E;
  15575. WOLFSSL_ERROR_VERBOSE(ret);
  15576. }
  15577. break;
  15578. }
  15579. #endif /* HAVE_FALCON */
  15580. #ifdef HAVE_DILITHIUM
  15581. case DILITHIUM_LEVEL2k:
  15582. {
  15583. if (sigCtx->verify == 1) {
  15584. ret = 0;
  15585. }
  15586. else {
  15587. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  15588. ret = ASN_SIG_CONFIRM_E;
  15589. }
  15590. break;
  15591. }
  15592. case DILITHIUM_LEVEL3k:
  15593. {
  15594. if (sigCtx->verify == 1) {
  15595. ret = 0;
  15596. }
  15597. else {
  15598. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  15599. ret = ASN_SIG_CONFIRM_E;
  15600. }
  15601. break;
  15602. }
  15603. case DILITHIUM_LEVEL5k:
  15604. {
  15605. if (sigCtx->verify == 1) {
  15606. ret = 0;
  15607. }
  15608. else {
  15609. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  15610. ret = ASN_SIG_CONFIRM_E;
  15611. }
  15612. break;
  15613. }
  15614. #endif /* HAVE_DILITHIUM */
  15615. #ifdef HAVE_SPHINCS
  15616. case SPHINCS_FAST_LEVEL1k:
  15617. {
  15618. if (sigCtx->verify == 1) {
  15619. ret = 0;
  15620. }
  15621. else {
  15622. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  15623. ret = ASN_SIG_CONFIRM_E;
  15624. }
  15625. break;
  15626. }
  15627. case SPHINCS_FAST_LEVEL3k:
  15628. {
  15629. if (sigCtx->verify == 1) {
  15630. ret = 0;
  15631. }
  15632. else {
  15633. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  15634. ret = ASN_SIG_CONFIRM_E;
  15635. }
  15636. break;
  15637. }
  15638. case SPHINCS_FAST_LEVEL5k:
  15639. {
  15640. if (sigCtx->verify == 1) {
  15641. ret = 0;
  15642. }
  15643. else {
  15644. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  15645. ret = ASN_SIG_CONFIRM_E;
  15646. }
  15647. break;
  15648. }
  15649. case SPHINCS_SMALL_LEVEL1k:
  15650. {
  15651. if (sigCtx->verify == 1) {
  15652. ret = 0;
  15653. }
  15654. else {
  15655. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  15656. ret = ASN_SIG_CONFIRM_E;
  15657. }
  15658. break;
  15659. }
  15660. case SPHINCS_SMALL_LEVEL3k:
  15661. {
  15662. if (sigCtx->verify == 1) {
  15663. ret = 0;
  15664. }
  15665. else {
  15666. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  15667. ret = ASN_SIG_CONFIRM_E;
  15668. }
  15669. break;
  15670. }
  15671. case SPHINCS_SMALL_LEVEL5k:
  15672. {
  15673. if (sigCtx->verify == 1) {
  15674. ret = 0;
  15675. }
  15676. else {
  15677. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  15678. ret = ASN_SIG_CONFIRM_E;
  15679. }
  15680. break;
  15681. }
  15682. #endif /* HAVE_SPHINCS */
  15683. #endif /* HAVE_PQC */
  15684. default:
  15685. break;
  15686. } /* switch (keyOID) */
  15687. break;
  15688. } /* SIG_STATE_CHECK */
  15689. default:
  15690. break;
  15691. } /* switch (sigCtx->state) */
  15692. exit_cs:
  15693. #endif /* !NO_ASN_CRYPT */
  15694. (void)keyOID;
  15695. (void)sigOID;
  15696. WOLFSSL_LEAVE("ConfirmSignature", ret);
  15697. #ifdef WOLFSSL_ASYNC_CRYPT
  15698. if (ret == WC_PENDING_E)
  15699. return ret;
  15700. #endif
  15701. FreeSignatureCtx(sigCtx);
  15702. return ret;
  15703. }
  15704. #ifndef IGNORE_NAME_CONSTRAINTS
  15705. static int MatchBaseName(int type, const char* name, int nameSz,
  15706. const char* base, int baseSz)
  15707. {
  15708. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  15709. name[0] == '.' || nameSz < baseSz ||
  15710. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  15711. type != ASN_DIR_TYPE)) {
  15712. return 0;
  15713. }
  15714. if (type == ASN_DIR_TYPE)
  15715. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  15716. /* If an email type, handle special cases where the base is only
  15717. * a domain, or is an email address itself. */
  15718. if (type == ASN_RFC822_TYPE) {
  15719. const char* p = NULL;
  15720. int count = 0;
  15721. if (base[0] != '.') {
  15722. p = base;
  15723. count = 0;
  15724. /* find the '@' in the base */
  15725. while (*p != '@' && count < baseSz) {
  15726. count++;
  15727. p++;
  15728. }
  15729. /* No '@' in base, reset p to NULL */
  15730. if (count >= baseSz)
  15731. p = NULL;
  15732. }
  15733. if (p == NULL) {
  15734. /* Base isn't an email address, it is a domain name,
  15735. * wind the name forward one character past its '@'. */
  15736. p = name;
  15737. count = 0;
  15738. while (*p != '@' && count < baseSz) {
  15739. count++;
  15740. p++;
  15741. }
  15742. if (count < baseSz && *p == '@') {
  15743. name = p + 1;
  15744. nameSz -= count + 1;
  15745. }
  15746. }
  15747. }
  15748. /* RFC 5280 section 4.2.1.10
  15749. * "...Any DNS name that can be constructed by simply adding zero or more
  15750. * labels to the left-hand side of the name satisfies the name constraint."
  15751. * i.e www.host.example.com works for host.example.com name constraint and
  15752. * host1.example.com does not. */
  15753. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  15754. int szAdjust = nameSz - baseSz;
  15755. name += szAdjust;
  15756. nameSz -= szAdjust;
  15757. }
  15758. while (nameSz > 0) {
  15759. if (XTOLOWER((unsigned char)*name) !=
  15760. XTOLOWER((unsigned char)*base))
  15761. return 0;
  15762. name++;
  15763. base++;
  15764. nameSz--;
  15765. }
  15766. return 1;
  15767. }
  15768. /* Search through the list to find if the name is permitted.
  15769. * name The DNS name to search for
  15770. * dnsList The list to search through
  15771. * nameType Type of DNS name to currently searching
  15772. * return 1 if found in list or if not needed
  15773. * return 0 if not found in the list but is needed
  15774. */
  15775. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15776. {
  15777. Base_entry* current = dnsList;
  15778. int match = 0;
  15779. int need = 0;
  15780. int ret = 1; /* is ok unless needed and no match found */
  15781. while (current != NULL) {
  15782. if (current->type == nameType) {
  15783. need = 1; /* restriction on permitted names is set for this type */
  15784. if (name->len >= current->nameSz &&
  15785. MatchBaseName(nameType, name->name, name->len,
  15786. current->name, current->nameSz)) {
  15787. match = 1; /* found the current name in the permitted list*/
  15788. break;
  15789. }
  15790. }
  15791. current = current->next;
  15792. }
  15793. /* check if permitted name restriction was set and no matching name found */
  15794. if (need && !match)
  15795. ret = 0;
  15796. return ret;
  15797. }
  15798. /* Search through the list to find if the name is excluded.
  15799. * name The DNS name to search for
  15800. * dnsList The list to search through
  15801. * nameType Type of DNS name to currently searching
  15802. * return 1 if found in list and 0 if not found in the list
  15803. */
  15804. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15805. {
  15806. int ret = 0; /* default of not found in the list */
  15807. Base_entry* current = dnsList;
  15808. while (current != NULL) {
  15809. if (current->type == nameType) {
  15810. if (name->len >= current->nameSz &&
  15811. MatchBaseName(nameType, name->name, name->len,
  15812. current->name, current->nameSz)) {
  15813. ret = 1;
  15814. break;
  15815. }
  15816. }
  15817. current = current->next;
  15818. }
  15819. return ret;
  15820. }
  15821. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15822. {
  15823. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15824. int i;
  15825. if (signer == NULL || cert == NULL)
  15826. return 0;
  15827. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15828. return 1;
  15829. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15830. byte nameType = nameTypes[i];
  15831. DNS_entry* name = NULL;
  15832. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15833. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15834. switch (nameType) {
  15835. case ASN_DNS_TYPE:
  15836. /* Should it also consider CN in subject? It could use
  15837. * subjectDnsName too */
  15838. name = cert->altNames;
  15839. break;
  15840. case ASN_RFC822_TYPE:
  15841. /* Shouldn't it validate E= in subject as well? */
  15842. name = cert->altEmailNames;
  15843. /* Add subject email for checking. */
  15844. if (cert->subjectEmail != NULL) {
  15845. /* RFC 5280 section 4.2.1.10
  15846. * "When constraints are imposed on the rfc822Name name
  15847. * form, but the certificate does not include a subject
  15848. * alternative name, the rfc822Name constraint MUST be
  15849. * applied to the attribute of type emailAddress in the
  15850. * subject distinguished name" */
  15851. subjectDnsName.next = NULL;
  15852. subjectDnsName.type = ASN_RFC822_TYPE;
  15853. subjectDnsName.len = cert->subjectEmailLen;
  15854. subjectDnsName.name = (char *)cert->subjectEmail;
  15855. }
  15856. break;
  15857. case ASN_DIR_TYPE:
  15858. #ifndef WOLFSSL_NO_ASN_STRICT
  15859. name = cert->altDirNames;
  15860. #endif
  15861. /* RFC 5280 section 4.2.1.10
  15862. "Restrictions of the form directoryName MUST be
  15863. applied to the subject field .... and to any names
  15864. of type directoryName in the subjectAltName
  15865. extension"
  15866. */
  15867. if (cert->subjectRaw != NULL) {
  15868. subjectDnsName.next = NULL;
  15869. subjectDnsName.type = ASN_DIR_TYPE;
  15870. subjectDnsName.len = cert->subjectRawLen;
  15871. subjectDnsName.name = (char *)cert->subjectRaw;
  15872. }
  15873. break;
  15874. default:
  15875. /* Other types of names are ignored for now.
  15876. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15877. * and signer->extNameConstraintCrit is set? */
  15878. return 0;
  15879. }
  15880. while (name != NULL) {
  15881. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15882. WOLFSSL_MSG("Excluded name was found!");
  15883. return 0;
  15884. }
  15885. /* Check against the permitted list */
  15886. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15887. WOLFSSL_MSG("Permitted name was not found!");
  15888. return 0;
  15889. }
  15890. name = name->next;
  15891. }
  15892. /* handle comparing against subject name too */
  15893. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15894. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15895. nameType) == 1) {
  15896. WOLFSSL_MSG("Excluded name was found!");
  15897. return 0;
  15898. }
  15899. /* Check against the permitted list */
  15900. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15901. nameType) != 1) {
  15902. WOLFSSL_MSG("Permitted name was not found!");
  15903. return 0;
  15904. }
  15905. }
  15906. }
  15907. return 1;
  15908. }
  15909. #endif /* IGNORE_NAME_CONSTRAINTS */
  15910. #ifndef WOLFSSL_ASN_TEMPLATE
  15911. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15912. {
  15913. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15914. dnsEntry->next = NULL;
  15915. if (cert->altNames == NULL) {
  15916. /* First on list */
  15917. cert->altNames = dnsEntry;
  15918. }
  15919. else {
  15920. DNS_entry* temp = cert->altNames;
  15921. /* Find end */
  15922. for (; (temp->next != NULL); temp = temp->next);
  15923. /* Add to end */
  15924. temp->next = dnsEntry;
  15925. }
  15926. #else
  15927. dnsEntry->next = cert->altNames;
  15928. cert->altNames = dnsEntry;
  15929. #endif
  15930. }
  15931. #endif
  15932. #ifdef WOLFSSL_ASN_TEMPLATE
  15933. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15934. /* ASN.1 template for OtherName of an X.509 certificate.
  15935. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15936. * HW Name: RFC 4108, 5 - Hardware Module Name
  15937. * Only support HW Name where the type is a HW serial number.
  15938. *
  15939. * Other Names handled for FPKI (Federal PKI) use:
  15940. * UPN (Universal Principal Name), a non-standard Other Name
  15941. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15942. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15943. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15944. */
  15945. static const ASNItem otherNameASN[] = {
  15946. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15947. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15948. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15949. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15950. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15951. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15952. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15953. };
  15954. enum {
  15955. OTHERNAMEASN_IDX_TYPEID = 0,
  15956. OTHERNAMEASN_IDX_VALUE,
  15957. OTHERNAMEASN_IDX_UPN,
  15958. OTHERNAMEASN_IDX_FASCN,
  15959. OTHERNAMEASN_IDX_HWN_SEQ,
  15960. OTHERNAMEASN_IDX_HWN_TYPE,
  15961. OTHERNAMEASN_IDX_HWN_NUM
  15962. };
  15963. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15964. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15965. #ifdef WOLFSSL_SEP
  15966. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15967. {
  15968. int ret = 0;
  15969. word32 oidLen, serialLen;
  15970. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15971. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15972. /* Allocate space for HW type OID. */
  15973. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15974. DYNAMIC_TYPE_X509_EXT);
  15975. if (cert->hwType == NULL)
  15976. ret = MEMORY_E;
  15977. if (ret == 0) {
  15978. /* Copy, into cert HW type OID */
  15979. XMEMCPY(cert->hwType,
  15980. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15981. cert->hwTypeSz = (int)oidLen;
  15982. /* TODO: check this is the HW serial number OID - no test data. */
  15983. /* Allocate space for HW serial number, +1 for null terminator. */
  15984. cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
  15985. DYNAMIC_TYPE_X509_EXT);
  15986. if (cert->hwSerialNum == NULL) {
  15987. WOLFSSL_MSG("\tOut of Memory");
  15988. ret = MEMORY_E;
  15989. }
  15990. }
  15991. if (ret == 0) {
  15992. /* Copy into cert HW serial number. */
  15993. XMEMCPY(cert->hwSerialNum,
  15994. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15995. cert->hwSerialNum[serialLen] = '\0';
  15996. cert->hwSerialNumSz = (int)serialLen;
  15997. }
  15998. return ret;
  15999. }
  16000. #endif /* WOLFSSL_SEP */
  16001. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  16002. {
  16003. DNS_entry* entry = NULL;
  16004. int ret = 0;
  16005. word32 bufLen = 0;
  16006. const char* buf = NULL;
  16007. switch (oid) {
  16008. #ifdef WOLFSSL_FPKI
  16009. case FASCN_OID:
  16010. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  16011. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  16012. break;
  16013. #endif /* WOLFSSL_FPKI */
  16014. case UPN_OID:
  16015. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  16016. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  16017. break;
  16018. default:
  16019. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  16020. ret = ASN_UNKNOWN_OID_E;
  16021. break;
  16022. }
  16023. if (ret == 0) {
  16024. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  16025. if (ret == 0) {
  16026. #ifdef WOLFSSL_FPKI
  16027. entry->oidSum = oid;
  16028. #endif
  16029. AddDNSEntryToList(&cert->altNames, entry);
  16030. }
  16031. }
  16032. return ret;
  16033. }
  16034. /* Decode data with OtherName format from after implicit SEQUENCE.
  16035. *
  16036. * @param [in, out] cert Certificate object.
  16037. * @param [in] input Buffer containing encoded OtherName.
  16038. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  16039. * On out, index after OtherName.
  16040. * @param [in] maxIdx Maximum index of data in buffer.
  16041. * @return 0 on success.
  16042. * @return MEMORY_E on dynamic memory allocation failure.
  16043. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16044. * is invalid.
  16045. * @return ASN_PARSE_E when OID does is not HW Name.
  16046. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16047. * @return BUFFER_E when data in buffer is too small.
  16048. */
  16049. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  16050. word32* inOutIdx, word32 maxIdx)
  16051. {
  16052. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  16053. int ret = 0;
  16054. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  16055. if (ret == 0) {
  16056. /* Check the first OID is a recognized Alt Cert Name type. */
  16057. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  16058. /* Parse OtherName. */
  16059. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  16060. inOutIdx, maxIdx);
  16061. }
  16062. if (ret == 0) {
  16063. /* Ensure expected OID. */
  16064. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  16065. #ifdef WOLFSSL_SEP
  16066. case HW_NAME_OID:
  16067. /* Only support HW serial number. */
  16068. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  16069. ret = DecodeSEP(dataASN, cert);
  16070. break;
  16071. #endif /* WOLFSSL_SEP */
  16072. #ifdef WOLFSSL_FPKI
  16073. case FASCN_OID:
  16074. #endif /* WOLFSSL_FPKI */
  16075. case UPN_OID:
  16076. ret = DecodeOtherHelper(dataASN, cert,
  16077. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  16078. break;
  16079. default:
  16080. WOLFSSL_MSG("\tunsupported OID skipping");
  16081. break;
  16082. }
  16083. }
  16084. FREE_ASNGETDATA(dataASN, cert->heap);
  16085. return ret;
  16086. }
  16087. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  16088. /* Decode a GeneralName.
  16089. *
  16090. * @param [in] input Buffer containing encoded OtherName.
  16091. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  16092. * On out, index after OtherName.
  16093. * @param [in] len Length of data in buffer.
  16094. * @param [in] cert Decoded certificate object.
  16095. * @return 0 on success.
  16096. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16097. * is invalid.
  16098. * @return BUFFER_E when data in buffer is too small.
  16099. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16100. * @return MEMORY_E when dynamic memory allocation fails.
  16101. */
  16102. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  16103. int len, DecodedCert* cert)
  16104. {
  16105. int ret = 0;
  16106. word32 idx = *inOutIdx;
  16107. /* GeneralName choice: dnsName */
  16108. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16109. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  16110. &cert->altNames);
  16111. if (ret == 0) {
  16112. idx += (word32)len;
  16113. }
  16114. }
  16115. #ifndef IGNORE_NAME_CONSTRAINTS
  16116. /* GeneralName choice: directoryName */
  16117. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16118. int strLen;
  16119. word32 idxDir = idx;
  16120. /* Expecting a SEQUENCE using up all data. */
  16121. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  16122. {
  16123. WOLFSSL_MSG("\tfail: seq length");
  16124. return ASN_PARSE_E;
  16125. }
  16126. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  16127. ASN_DIR_TYPE, &cert->altDirNames);
  16128. if (ret == 0) {
  16129. idx += (word32)len;
  16130. }
  16131. }
  16132. /* GeneralName choice: rfc822Name */
  16133. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16134. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  16135. ASN_RFC822_TYPE, &cert->altEmailNames);
  16136. if (ret == 0) {
  16137. idx += (word32)len;
  16138. }
  16139. }
  16140. /* GeneralName choice: uniformResourceIdentifier */
  16141. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16142. WOLFSSL_MSG("\tPutting URI into list but not using");
  16143. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16144. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16145. "The name MUST NOT be a relative URI"
  16146. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16147. a scheme and hier-part. So the only strict requirement is a ':'
  16148. being present after the scheme. If a '/' is present as part of the
  16149. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16150. {
  16151. int i;
  16152. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16153. for (i = 0; i < len; i++) {
  16154. if (input[idx + (word32)i] == ':') {
  16155. break;
  16156. }
  16157. if (input[idx + (word32)i] == '/') {
  16158. i = len; /* error, found relative path since '/' was
  16159. * encountered before ':'. Returning error
  16160. * value in next if statement. */
  16161. }
  16162. }
  16163. /* test hier-part is empty */
  16164. if (i == 0 || i == len) {
  16165. WOLFSSL_MSG("\tEmpty or malformed URI");
  16166. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16167. return ASN_ALT_NAME_E;
  16168. }
  16169. /* test if scheme is missing */
  16170. if (input[idx + (word32)i] != ':') {
  16171. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16172. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16173. return ASN_ALT_NAME_E;
  16174. }
  16175. }
  16176. #endif
  16177. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  16178. &cert->altNames);
  16179. if (ret == 0) {
  16180. idx += (word32)len;
  16181. }
  16182. }
  16183. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  16184. defined(WOLFSSL_IP_ALT_NAME)
  16185. /* GeneralName choice: iPAddress */
  16186. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16187. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  16188. &cert->altNames);
  16189. if (ret == 0) {
  16190. idx += (word32)len;
  16191. }
  16192. }
  16193. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16194. /* GeneralName choice: registeredID */
  16195. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) {
  16196. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  16197. ASN_RID_TYPE, &cert->altNames);
  16198. if (ret == 0) {
  16199. idx += (word32)len;
  16200. }
  16201. }
  16202. #endif /* IGNORE_NAME_CONSTRAINTS */
  16203. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  16204. /* GeneralName choice: otherName */
  16205. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16206. /* TODO: test data for code path */
  16207. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  16208. }
  16209. #endif
  16210. /* GeneralName choice: dNSName, x400Address, ediPartyName */
  16211. else {
  16212. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16213. idx += (word32)len;
  16214. }
  16215. if (ret == 0) {
  16216. /* Return index of next encoded byte. */
  16217. *inOutIdx = idx;
  16218. }
  16219. return ret;
  16220. }
  16221. /* ASN.1 choices for GeneralName.
  16222. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16223. */
  16224. static const byte generalNameChoice[] = {
  16225. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  16226. ASN_CONTEXT_SPECIFIC | 1,
  16227. ASN_CONTEXT_SPECIFIC | 2,
  16228. ASN_CONTEXT_SPECIFIC | 3,
  16229. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  16230. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  16231. ASN_CONTEXT_SPECIFIC | 6,
  16232. ASN_CONTEXT_SPECIFIC | 7,
  16233. ASN_CONTEXT_SPECIFIC | 8,
  16234. 0
  16235. };
  16236. /* ASN.1 template for GeneralName.
  16237. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16238. */
  16239. static const ASNItem altNameASN[] = {
  16240. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  16241. };
  16242. enum {
  16243. ALTNAMEASN_IDX_GN = 0
  16244. };
  16245. /* Number of items in ASN.1 template for GeneralName. */
  16246. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  16247. #endif /* WOLFSSL_ASN_TEMPLATE */
  16248. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  16249. /* return 0 on success */
  16250. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  16251. word32* idxIn, word32 sz)
  16252. {
  16253. word32 idx = *idxIn;
  16254. int strLen;
  16255. int ret;
  16256. byte tag;
  16257. /* Certificates issued with this OID in the subject alt name are for
  16258. * verifying signatures created on a module.
  16259. * RFC 4108 Section 5. */
  16260. if (cert->hwType != NULL) {
  16261. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  16262. return ASN_PARSE_E;
  16263. }
  16264. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16265. return ASN_PARSE_E;
  16266. }
  16267. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  16268. WOLFSSL_MSG("\twrong type");
  16269. return ASN_PARSE_E;
  16270. }
  16271. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16272. WOLFSSL_MSG("\tfail: str len");
  16273. return ASN_PARSE_E;
  16274. }
  16275. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16276. WOLFSSL_MSG("\tBad Sequence");
  16277. return ASN_PARSE_E;
  16278. }
  16279. ret = GetASNObjectId(input, &idx, &strLen, sz);
  16280. if (ret != 0) {
  16281. WOLFSSL_MSG("\tbad OID");
  16282. return ret;
  16283. }
  16284. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  16285. DYNAMIC_TYPE_X509_EXT);
  16286. if (cert->hwType == NULL) {
  16287. WOLFSSL_MSG("\tOut of Memory");
  16288. return MEMORY_E;
  16289. }
  16290. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  16291. cert->hwTypeSz = strLen;
  16292. idx += (word32)strLen;
  16293. ret = GetOctetString(input, &idx, &strLen, sz);
  16294. if (ret < 0) {
  16295. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16296. cert->hwType = NULL;
  16297. return ret;
  16298. }
  16299. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  16300. DYNAMIC_TYPE_X509_EXT);
  16301. if (cert->hwSerialNum == NULL) {
  16302. WOLFSSL_MSG("\tOut of Memory");
  16303. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16304. cert->hwType = NULL;
  16305. return MEMORY_E;
  16306. }
  16307. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  16308. cert->hwSerialNum[strLen] = '\0';
  16309. cert->hwSerialNumSz = strLen;
  16310. idx += (word32)strLen;
  16311. *idxIn = idx;
  16312. return 0;
  16313. }
  16314. #endif /* WOLFSSL_SEP */
  16315. #if !defined(WOLFSSL_ASN_TEMPLATE)
  16316. /* return 0 on success */
  16317. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  16318. word32* idx, word32 sz, int oid)
  16319. {
  16320. int ret = 0;
  16321. int strLen = 0;
  16322. byte tag;
  16323. DNS_entry* dnsEntry = NULL;
  16324. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16325. ret = ASN_PARSE_E;
  16326. }
  16327. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  16328. ret = ASN_PARSE_E;
  16329. }
  16330. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16331. ret = ASN_PARSE_E;
  16332. }
  16333. if (ret == 0) {
  16334. dnsEntry = AltNameNew(cert->heap);
  16335. if (dnsEntry == NULL) {
  16336. WOLFSSL_MSG("\tOut of Memory");
  16337. return MEMORY_E;
  16338. }
  16339. switch (oid) {
  16340. #ifdef WOLFSSL_FPKI
  16341. case FASCN_OID:
  16342. ret = GetOctetString(input, idx, &strLen, sz);
  16343. if (ret > 0) {
  16344. ret = 0;
  16345. }
  16346. break;
  16347. #endif /* WOLFSSL_FPKI */
  16348. case UPN_OID:
  16349. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16350. ret = ASN_PARSE_E;
  16351. }
  16352. if (ret == 0 &&
  16353. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16354. tag != ASN_IA5_STRING) {
  16355. WOLFSSL_MSG("Was expecting a string for UPN");
  16356. ret = ASN_PARSE_E;
  16357. }
  16358. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16359. WOLFSSL_MSG("Was expecting a string for UPN");
  16360. ret = ASN_PARSE_E;
  16361. }
  16362. break;
  16363. default:
  16364. WOLFSSL_MSG("Unknown constructed other name, skipping");
  16365. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16366. dnsEntry = NULL;
  16367. }
  16368. }
  16369. if (ret == 0 && dnsEntry != NULL) {
  16370. dnsEntry->type = ASN_OTHER_TYPE;
  16371. dnsEntry->len = strLen;
  16372. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16373. DYNAMIC_TYPE_ALTNAME);
  16374. #ifdef WOLFSSL_FPKI
  16375. dnsEntry->oidSum = oid;
  16376. #endif /* WOLFSSL_FPKI */
  16377. if (dnsEntry->name == NULL) {
  16378. WOLFSSL_MSG("\tOut of Memory");
  16379. ret = MEMORY_E;
  16380. }
  16381. else {
  16382. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  16383. dnsEntry->name[strLen] = '\0';
  16384. AddAltName(cert, dnsEntry);
  16385. }
  16386. }
  16387. if (ret == 0) {
  16388. *idx += (word32)strLen;
  16389. }
  16390. else {
  16391. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16392. }
  16393. return ret;
  16394. }
  16395. #endif
  16396. /* Decode subject alternative names extension.
  16397. *
  16398. * RFC 5280 4.2.1.6. Subject Alternative Name
  16399. *
  16400. * @param [in] input Buffer holding encoded data.
  16401. * @param [in] sz Size of encoded data in bytes.
  16402. * @param [in, out] cert Decoded certificate object.
  16403. * @return 0 on success.
  16404. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16405. * is invalid.
  16406. * @return BUFFER_E when data in buffer is too small.
  16407. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16408. * @return MEMORY_E when dynamic memory allocation fails.
  16409. */
  16410. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  16411. {
  16412. #ifndef WOLFSSL_ASN_TEMPLATE
  16413. word32 idx = 0;
  16414. int length = 0;
  16415. WOLFSSL_ENTER("DecodeAltNames");
  16416. if (GetSequence(input, &idx, &length, sz) < 0) {
  16417. WOLFSSL_MSG("\tBad Sequence");
  16418. return ASN_PARSE_E;
  16419. }
  16420. if (length == 0) {
  16421. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16422. If the subjectAltName extension is present, the sequence MUST
  16423. contain at least one entry. */
  16424. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16425. return ASN_PARSE_E;
  16426. }
  16427. #ifdef OPENSSL_ALL
  16428. cert->extSubjAltNameSrc = input;
  16429. cert->extSubjAltNameSz = sz;
  16430. #endif
  16431. cert->weOwnAltNames = 1;
  16432. while (length > 0) {
  16433. byte current_byte;
  16434. /* Verify idx can't overflow input buffer */
  16435. if (idx >= (word32)sz) {
  16436. WOLFSSL_MSG("\tBad Index");
  16437. return BUFFER_E;
  16438. }
  16439. current_byte = input[idx++];
  16440. length--;
  16441. /* Save DNS Type names in the altNames list. */
  16442. /* Save Other Type names in the cert's OidMap */
  16443. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16444. DNS_entry* dnsEntry;
  16445. int strLen;
  16446. word32 lenStartIdx = idx;
  16447. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16448. WOLFSSL_MSG("\tfail: str length");
  16449. return ASN_PARSE_E;
  16450. }
  16451. length -= (int)(idx - lenStartIdx);
  16452. dnsEntry = AltNameNew(cert->heap);
  16453. if (dnsEntry == NULL) {
  16454. WOLFSSL_MSG("\tOut of Memory");
  16455. return MEMORY_E;
  16456. }
  16457. dnsEntry->type = ASN_DNS_TYPE;
  16458. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16459. DYNAMIC_TYPE_ALTNAME);
  16460. if (dnsEntry->name == NULL) {
  16461. WOLFSSL_MSG("\tOut of Memory");
  16462. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16463. return MEMORY_E;
  16464. }
  16465. dnsEntry->len = strLen;
  16466. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  16467. dnsEntry->name[strLen] = '\0';
  16468. AddAltName(cert, dnsEntry);
  16469. length -= strLen;
  16470. idx += (word32)strLen;
  16471. }
  16472. #ifndef IGNORE_NAME_CONSTRAINTS
  16473. else if (current_byte ==
  16474. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16475. DNS_entry* dirEntry;
  16476. int strLen;
  16477. word32 lenStartIdx = idx;
  16478. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16479. WOLFSSL_MSG("\tfail: str length");
  16480. return ASN_PARSE_E;
  16481. }
  16482. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16483. WOLFSSL_MSG("\tfail: seq length");
  16484. return ASN_PARSE_E;
  16485. }
  16486. length -= (int)(idx - lenStartIdx);
  16487. dirEntry = AltNameNew(cert->heap);
  16488. if (dirEntry == NULL) {
  16489. WOLFSSL_MSG("\tOut of Memory");
  16490. return MEMORY_E;
  16491. }
  16492. dirEntry->type = ASN_DIR_TYPE;
  16493. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16494. DYNAMIC_TYPE_ALTNAME);
  16495. if (dirEntry->name == NULL) {
  16496. WOLFSSL_MSG("\tOut of Memory");
  16497. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16498. return MEMORY_E;
  16499. }
  16500. dirEntry->len = strLen;
  16501. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  16502. dirEntry->name[strLen] = '\0';
  16503. dirEntry->next = cert->altDirNames;
  16504. cert->altDirNames = dirEntry;
  16505. length -= strLen;
  16506. idx += (word32)strLen;
  16507. }
  16508. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16509. DNS_entry* emailEntry;
  16510. int strLen;
  16511. word32 lenStartIdx = idx;
  16512. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16513. WOLFSSL_MSG("\tfail: str length");
  16514. return ASN_PARSE_E;
  16515. }
  16516. length -= (int)(idx - lenStartIdx);
  16517. emailEntry = AltNameNew(cert->heap);
  16518. if (emailEntry == NULL) {
  16519. WOLFSSL_MSG("\tOut of Memory");
  16520. return MEMORY_E;
  16521. }
  16522. emailEntry->type = ASN_RFC822_TYPE;
  16523. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16524. DYNAMIC_TYPE_ALTNAME);
  16525. if (emailEntry->name == NULL) {
  16526. WOLFSSL_MSG("\tOut of Memory");
  16527. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16528. return MEMORY_E;
  16529. }
  16530. emailEntry->len = strLen;
  16531. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  16532. emailEntry->name[strLen] = '\0';
  16533. emailEntry->next = cert->altEmailNames;
  16534. cert->altEmailNames = emailEntry;
  16535. length -= strLen;
  16536. idx += (word32)strLen;
  16537. }
  16538. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16539. DNS_entry* uriEntry;
  16540. int strLen;
  16541. word32 lenStartIdx = idx;
  16542. WOLFSSL_MSG("\tPutting URI into list but not using");
  16543. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16544. WOLFSSL_MSG("\tfail: str length");
  16545. return ASN_PARSE_E;
  16546. }
  16547. length -= (int)(idx - lenStartIdx);
  16548. /* check that strLen at index is not past input buffer */
  16549. if ((word32)strLen + idx > sz) {
  16550. return BUFFER_E;
  16551. }
  16552. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16553. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16554. "The name MUST NOT be a relative URI"
  16555. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16556. a scheme and hier-part. So the only strict requirement is a ':'
  16557. being present after the scheme. If a '/' is present as part of the
  16558. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16559. {
  16560. word32 i;
  16561. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16562. for (i = 0; i < (word32)strLen; i++) {
  16563. if (input[idx + i] == ':') {
  16564. break;
  16565. }
  16566. if (input[idx + i] == '/') {
  16567. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16568. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16569. return ASN_ALT_NAME_E;
  16570. }
  16571. }
  16572. /* test hier-part is empty */
  16573. if (i == 0 || i == (word32)strLen) {
  16574. WOLFSSL_MSG("\tEmpty or malformed URI");
  16575. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16576. return ASN_ALT_NAME_E;
  16577. }
  16578. /* test if scheme is missing */
  16579. if (input[idx + i] != ':') {
  16580. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16581. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16582. return ASN_ALT_NAME_E;
  16583. }
  16584. }
  16585. #endif
  16586. uriEntry = AltNameNew(cert->heap);
  16587. if (uriEntry == NULL) {
  16588. WOLFSSL_MSG("\tOut of Memory");
  16589. return MEMORY_E;
  16590. }
  16591. uriEntry->type = ASN_URI_TYPE;
  16592. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16593. DYNAMIC_TYPE_ALTNAME);
  16594. if (uriEntry->name == NULL) {
  16595. WOLFSSL_MSG("\tOut of Memory");
  16596. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16597. return MEMORY_E;
  16598. }
  16599. uriEntry->len = strLen;
  16600. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  16601. uriEntry->name[strLen] = '\0';
  16602. AddAltName(cert, uriEntry);
  16603. length -= strLen;
  16604. idx += (word32)strLen;
  16605. }
  16606. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16607. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16608. DNS_entry* ipAddr;
  16609. int strLen;
  16610. word32 lenStartIdx = idx;
  16611. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  16612. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16613. WOLFSSL_MSG("\tfail: str length");
  16614. return ASN_PARSE_E;
  16615. }
  16616. length -= (idx - lenStartIdx);
  16617. /* check that strLen at index is not past input buffer */
  16618. if (strLen + idx > sz) {
  16619. return BUFFER_E;
  16620. }
  16621. ipAddr = AltNameNew(cert->heap);
  16622. if (ipAddr == NULL) {
  16623. WOLFSSL_MSG("\tOut of Memory");
  16624. return MEMORY_E;
  16625. }
  16626. ipAddr->type = ASN_IP_TYPE;
  16627. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16628. DYNAMIC_TYPE_ALTNAME);
  16629. if (ipAddr->name == NULL) {
  16630. WOLFSSL_MSG("\tOut of Memory");
  16631. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16632. return MEMORY_E;
  16633. }
  16634. ipAddr->len = strLen;
  16635. XMEMCPY(ipAddr->name, &input[idx], strLen);
  16636. ipAddr->name[strLen] = '\0';
  16637. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16638. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  16639. WOLFSSL_MSG("\tOut of Memory for IP string");
  16640. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16641. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16642. return MEMORY_E;
  16643. }
  16644. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  16645. AddAltName(cert, ipAddr);
  16646. length -= strLen;
  16647. idx += (word32)strLen;
  16648. }
  16649. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  16650. #if defined(OPENSSL_ALL)
  16651. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RID_TYPE)) {
  16652. DNS_entry* rid;
  16653. int strLen;
  16654. word32 lenStartIdx = idx;
  16655. WOLFSSL_MSG("Decoding Subject Alt. Name: Registered Id");
  16656. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16657. WOLFSSL_MSG("\tfail: str length");
  16658. return ASN_PARSE_E;
  16659. }
  16660. length -= (idx - lenStartIdx);
  16661. /* check that strLen at index is not past input buffer */
  16662. if (strLen + idx > sz) {
  16663. return BUFFER_E;
  16664. }
  16665. rid = AltNameNew(cert->heap);
  16666. if (rid == NULL) {
  16667. WOLFSSL_MSG("\tOut of Memory");
  16668. return MEMORY_E;
  16669. }
  16670. rid->type = ASN_RID_TYPE;
  16671. rid->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16672. DYNAMIC_TYPE_ALTNAME);
  16673. if (rid->name == NULL) {
  16674. WOLFSSL_MSG("\tOut of Memory");
  16675. XFREE(rid, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16676. return MEMORY_E;
  16677. }
  16678. rid->len = strLen;
  16679. XMEMCPY(rid->name, &input[idx], strLen);
  16680. rid->name[strLen] = '\0';
  16681. if (GenerateDNSEntryRIDString(rid, cert->heap) != 0) {
  16682. WOLFSSL_MSG("\tOut of Memory for registered Id string");
  16683. XFREE(rid->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16684. XFREE(rid, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16685. return MEMORY_E;
  16686. }
  16687. AddAltName(cert, rid);
  16688. length -= strLen;
  16689. idx += (word32)strLen;
  16690. }
  16691. #endif /* OPENSSL_ALL */
  16692. #endif /* IGNORE_NAME_CONSTRAINTS */
  16693. else if (current_byte ==
  16694. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16695. int strLen;
  16696. word32 lenStartIdx = idx;
  16697. word32 oid = 0;
  16698. int ret = 0;
  16699. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16700. WOLFSSL_MSG("\tfail: other name length");
  16701. return ASN_PARSE_E;
  16702. }
  16703. /* Consume the rest of this sequence. */
  16704. length -= (int)(((word32)strLen + idx - lenStartIdx));
  16705. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  16706. WOLFSSL_MSG("\tbad OID");
  16707. return ASN_PARSE_E;
  16708. }
  16709. /* handle parsing other type alt names */
  16710. switch (oid) {
  16711. #ifdef WOLFSSL_SEP
  16712. case HW_NAME_OID:
  16713. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  16714. if (ret != 0)
  16715. return ret;
  16716. break;
  16717. #endif /* WOLFSSL_SEP */
  16718. #ifdef WOLFSSL_FPKI
  16719. case FASCN_OID:
  16720. case UPN_OID:
  16721. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  16722. oid);
  16723. if (ret != 0)
  16724. return ret;
  16725. break;
  16726. #endif /* WOLFSSL_FPKI */
  16727. default:
  16728. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  16729. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16730. /* check to skip constructed other names too */
  16731. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  16732. (int)oid) != 0) {
  16733. WOLFSSL_MSG("\tfail: unsupported other name length");
  16734. return ASN_PARSE_E;
  16735. }
  16736. }
  16737. else {
  16738. idx += (word32)strLen;
  16739. }
  16740. }
  16741. (void)ret;
  16742. }
  16743. else {
  16744. int strLen;
  16745. word32 lenStartIdx = idx;
  16746. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16747. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16748. WOLFSSL_MSG("\tfail: unsupported name length");
  16749. return ASN_PARSE_E;
  16750. }
  16751. length -= (int)((word32)strLen + idx - lenStartIdx);
  16752. idx += (word32)strLen;
  16753. }
  16754. }
  16755. return 0;
  16756. #else
  16757. word32 idx = 0;
  16758. int length = 0;
  16759. int ret = 0;
  16760. WOLFSSL_ENTER("DecodeAltNames");
  16761. /* Get SEQUENCE and expect all data to be accounted for. */
  16762. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  16763. WOLFSSL_MSG("\tBad Sequence");
  16764. ret = ASN_PARSE_E;
  16765. }
  16766. if ((ret == 0) && (length == 0)) {
  16767. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16768. If the subjectAltName extension is present, the sequence MUST
  16769. contain at least one entry. */
  16770. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16771. ret = ASN_PARSE_E;
  16772. }
  16773. if (ret == 0) {
  16774. #ifdef OPENSSL_ALL
  16775. cert->extSubjAltNameSrc = input;
  16776. cert->extSubjAltNameSz = sz;
  16777. #endif
  16778. cert->weOwnAltNames = 1;
  16779. if ((word32)length + idx != sz) {
  16780. ret = ASN_PARSE_E;
  16781. }
  16782. }
  16783. while ((ret == 0) && (idx < sz)) {
  16784. ASNGetData dataASN[altNameASN_Length];
  16785. /* Clear dynamic data items. */
  16786. XMEMSET(dataASN, 0, sizeof(dataASN));
  16787. /* Parse GeneralName with the choices supported. */
  16788. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  16789. /* Decode a GeneralName choice. */
  16790. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  16791. &idx, sz);
  16792. if (ret == 0) {
  16793. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  16794. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  16795. }
  16796. }
  16797. return ret;
  16798. #endif
  16799. }
  16800. #ifdef WOLFSSL_ASN_TEMPLATE
  16801. /* ASN.1 template for BasicConstraints.
  16802. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16803. */
  16804. static const ASNItem basicConsASN[] = {
  16805. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16806. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  16807. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  16808. };
  16809. enum {
  16810. BASICCONSASN_IDX_SEQ = 0,
  16811. BASICCONSASN_IDX_CA,
  16812. BASICCONSASN_IDX_PLEN
  16813. };
  16814. /* Number of items in ASN.1 template for BasicContraints. */
  16815. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  16816. #endif
  16817. /* Decode basic constraints extension in a certificate.
  16818. *
  16819. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16820. *
  16821. * @param [in] input Buffer holding data.
  16822. * @param [in] sz Size of data in buffer.
  16823. * @param [in, out] cert Certificate object.
  16824. * @return 0 on success.
  16825. * @return MEMORY_E on dynamic memory allocation failure.
  16826. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  16827. * @return ASN_PARSE_E when CA boolean is not present unless
  16828. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  16829. * @return ASN_PARSE_E when path length more than 7 bits.
  16830. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16831. * is invalid.
  16832. * @return BUFFER_E when data in buffer is too small.
  16833. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  16834. * non-zero length.
  16835. */
  16836. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  16837. {
  16838. #ifndef WOLFSSL_ASN_TEMPLATE
  16839. word32 idx = 0;
  16840. int length = 0;
  16841. int ret;
  16842. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  16843. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16844. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16845. return ASN_PARSE_E;
  16846. }
  16847. if (length == 0)
  16848. return 0;
  16849. /* If the basic ca constraint is false, this extension may be named, but
  16850. * left empty. So, if the length is 0, just return. */
  16851. ret = GetBoolean(input, &idx, (word32)sz);
  16852. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  16853. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16854. * When CA Boolean not asserted use the default value "False" */
  16855. if (ret < 0) {
  16856. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16857. ret = 0;
  16858. }
  16859. cert->isCA = ret ? 1 : 0;
  16860. /* If there isn't any more data, return. */
  16861. if (idx >= (word32)sz) {
  16862. return 0;
  16863. }
  16864. ret = GetInteger7Bit(input, &idx, (word32)sz);
  16865. if (ret < 0)
  16866. return ret;
  16867. cert->pathLength = (byte)ret;
  16868. cert->pathLengthSet = 1;
  16869. return 0;
  16870. #else
  16871. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16872. int ret = 0;
  16873. word32 idx = 0;
  16874. byte isCA = 0;
  16875. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16876. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16877. if (ret == 0) {
  16878. /* Get the CA boolean and path length when present. */
  16879. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16880. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16881. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16882. &idx, (word32)sz);
  16883. }
  16884. /* Empty SEQUENCE is OK - nothing to store. */
  16885. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16886. /* Bad encoding when CA Boolean is false
  16887. * (default when not present). */
  16888. #ifndef ASN_TEMPLATE_SKIP_ISCA_CHECK
  16889. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16890. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16891. ret = ASN_PARSE_E;
  16892. }
  16893. #endif
  16894. /* Path length must be a 7-bit value. */
  16895. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16896. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16897. ret = ASN_PARSE_E;
  16898. }
  16899. if ((ret == 0) && cert->pathLength > WOLFSSL_MAX_PATH_LEN) {
  16900. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_SIZE_E);
  16901. ret = ASN_PATHLEN_SIZE_E;
  16902. }
  16903. /* Store CA boolean and whether a path length was seen. */
  16904. if (ret == 0) {
  16905. /* isCA in certificate is a 1 bit of a byte. */
  16906. cert->isCA = isCA ? 1 : 0;
  16907. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16908. }
  16909. }
  16910. FREE_ASNGETDATA(dataASN, cert->heap);
  16911. return ret;
  16912. #endif
  16913. }
  16914. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16915. {
  16916. word32 idx = 0;
  16917. int length = 0;
  16918. int skipLength = 0;
  16919. int ret;
  16920. byte tag;
  16921. WOLFSSL_ENTER("DecodePolicyConstraints");
  16922. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16923. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16924. return ASN_PARSE_E;
  16925. }
  16926. if (length == 0)
  16927. return ASN_PARSE_E;
  16928. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  16929. WOLFSSL_MSG("\tfail: bad TAG");
  16930. return ASN_PARSE_E;
  16931. }
  16932. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16933. /* requireExplicitPolicy */
  16934. cert->extPolicyConstRxpSet = 1;
  16935. }
  16936. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16937. /* inhibitPolicyMapping */
  16938. cert->extPolicyConstIpmSet = 1;
  16939. }
  16940. else {
  16941. WOLFSSL_MSG("\tfail: invalid TAG");
  16942. return ASN_PARSE_E;
  16943. }
  16944. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  16945. if (ret < 0) {
  16946. WOLFSSL_MSG("\tfail: invalid length");
  16947. return ret;
  16948. }
  16949. if (skipLength > 1) {
  16950. WOLFSSL_MSG("\tfail: skip value too big");
  16951. return BUFFER_E;
  16952. }
  16953. if (idx >= (word32)sz) {
  16954. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16955. return BUFFER_E;
  16956. }
  16957. cert->policyConstSkip = input[idx];
  16958. return 0;
  16959. }
  16960. /* Context-Specific value for: DistributionPoint.distributionPoint
  16961. * From RFC5280 SS4.2.1.13, Distribution Point */
  16962. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16963. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16964. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16965. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16966. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16967. * From RFC3280 SS4.2.1.7, GeneralName */
  16968. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16969. #ifdef WOLFSSL_ASN_TEMPLATE
  16970. /* ASN.1 template for CRL distribution points.
  16971. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16972. */
  16973. static const ASNItem crlDistASN[] = {
  16974. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16975. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16976. /* Distribution point name */
  16977. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16978. /* fullName */
  16979. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16980. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16981. /* nameRelativeToCRLIssuer */
  16982. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16983. /* reasons: IMPLICIT BIT STRING */
  16984. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16985. /* cRLIssuer */
  16986. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16987. };
  16988. enum {
  16989. CRLDISTASN_IDX_SEQ = 0,
  16990. CRLDISTASN_IDX_DP_SEQ,
  16991. CRLDISTASN_IDX_DP_DISTPOINT,
  16992. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16993. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16994. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16995. CRLDISTASN_IDX_DP_REASONS,
  16996. CRLDISTASN_IDX_DP_CRLISSUER
  16997. };
  16998. /* Number of items in ASN.1 template for CRL distribution points. */
  16999. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  17000. #endif
  17001. /* Decode CRL distribution point extension in a certificate.
  17002. *
  17003. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  17004. *
  17005. * @param [in] input Buffer holding data.
  17006. * @param [in] sz Size of data in buffer.
  17007. * @param [in, out] cert Certificate object.
  17008. * @return 0 on success.
  17009. * @return MEMORY_E on dynamic memory allocation failure.
  17010. * @return ASN_PARSE_E when invalid bits of reason are set.
  17011. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  17012. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  17013. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17014. * is invalid.
  17015. * @return BUFFER_E when data in buffer is too small.
  17016. */
  17017. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  17018. {
  17019. #ifndef WOLFSSL_ASN_TEMPLATE
  17020. word32 idx = 0, localIdx;
  17021. int length = 0;
  17022. byte tag = 0;
  17023. WOLFSSL_ENTER("DecodeCrlDist");
  17024. cert->extCrlInfoRaw = input;
  17025. cert->extCrlInfoRawSz = (int)sz;
  17026. /* Unwrap the list of Distribution Points*/
  17027. if (GetSequence(input, &idx, &length, sz) < 0)
  17028. return ASN_PARSE_E;
  17029. /* Unwrap a single Distribution Point */
  17030. if (GetSequence(input, &idx, &length, sz) < 0)
  17031. return ASN_PARSE_E;
  17032. /* The Distribution Point has three explicit optional members
  17033. * First check for a DistributionPointName
  17034. */
  17035. localIdx = idx;
  17036. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17037. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  17038. {
  17039. idx++;
  17040. if (GetLength(input, &idx, &length, sz) < 0)
  17041. return ASN_PARSE_E;
  17042. localIdx = idx;
  17043. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17044. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  17045. {
  17046. idx++;
  17047. if (GetLength(input, &idx, &length, sz) < 0)
  17048. return ASN_PARSE_E;
  17049. localIdx = idx;
  17050. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17051. tag == GENERALNAME_URI)
  17052. {
  17053. idx++;
  17054. if (GetLength(input, &idx, &length, sz) < 0)
  17055. return ASN_PARSE_E;
  17056. cert->extCrlInfoSz = length;
  17057. cert->extCrlInfo = input + idx;
  17058. idx += (word32)length;
  17059. }
  17060. else
  17061. /* This isn't a URI, skip it. */
  17062. idx += (word32)length;
  17063. }
  17064. else {
  17065. /* This isn't a FULLNAME, skip it. */
  17066. idx += (word32)length;
  17067. }
  17068. }
  17069. /* Check for reasonFlags */
  17070. localIdx = idx;
  17071. if (idx < (word32)sz &&
  17072. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17073. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  17074. {
  17075. idx++;
  17076. if (GetLength(input, &idx, &length, sz) < 0)
  17077. return ASN_PARSE_E;
  17078. idx += (word32)length;
  17079. }
  17080. /* Check for cRLIssuer */
  17081. localIdx = idx;
  17082. if (idx < (word32)sz &&
  17083. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  17084. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  17085. {
  17086. idx++;
  17087. if (GetLength(input, &idx, &length, sz) < 0)
  17088. return ASN_PARSE_E;
  17089. idx += (word32)length;
  17090. }
  17091. if (idx < (word32)sz)
  17092. {
  17093. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  17094. "but we only use the first one.");
  17095. }
  17096. return 0;
  17097. #else
  17098. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  17099. word32 idx = 0;
  17100. int ret = 0;
  17101. #ifdef CRLDP_VALIDATE_DATA
  17102. word16 reason;
  17103. #endif
  17104. WOLFSSL_ENTER("DecodeCrlDist");
  17105. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  17106. cert->extCrlInfoRaw = input;
  17107. cert->extCrlInfoRawSz = (int)sz;
  17108. if (ret == 0) {
  17109. /* Get the GeneralName choice */
  17110. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  17111. /* Parse CRL distribution point. */
  17112. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  17113. &idx, sz);
  17114. }
  17115. if (ret == 0) {
  17116. /* If the choice was a URI, store it in certificate. */
  17117. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  17118. word32 sz32;
  17119. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  17120. &cert->extCrlInfo, &sz32);
  17121. cert->extCrlInfoSz = (int)sz32;
  17122. }
  17123. #ifdef CRLDP_VALIDATE_DATA
  17124. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  17125. /* TODO: test case */
  17126. /* Validate ReasonFlags. */
  17127. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  17128. &reason);
  17129. /* First bit (LSB) unused and eight other bits defined. */
  17130. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  17131. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17132. ret = ASN_PARSE_E;
  17133. }
  17134. }
  17135. #endif
  17136. }
  17137. /* Only parsing the first one. */
  17138. if (ret == 0 && idx < (word32)sz) {
  17139. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  17140. "but we only use the first one.");
  17141. }
  17142. /* TODO: validate other points. */
  17143. FREE_ASNGETDATA(dataASN, cert->heap);
  17144. return ret;
  17145. #endif /* WOLFSSL_ASN_TEMPLATE */
  17146. }
  17147. #ifdef WOLFSSL_ASN_TEMPLATE
  17148. /* ASN.1 template for the access description.
  17149. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17150. */
  17151. static const ASNItem accessDescASN[] = {
  17152. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17153. /* accessMethod */
  17154. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17155. /* accessLocation: GeneralName */
  17156. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  17157. };
  17158. enum {
  17159. ACCESSDESCASN_IDX_SEQ = 0,
  17160. ACCESSDESCASN_IDX_METH,
  17161. ACCESSDESCASN_IDX_LOC
  17162. };
  17163. /* Number of items in ASN.1 template for the access description. */
  17164. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  17165. #endif
  17166. /* Decode authority information access extension in a certificate.
  17167. *
  17168. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17169. *
  17170. * @param [in] input Buffer holding data.
  17171. * @param [in] sz Size of data in buffer.
  17172. * @param [in, out] cert Certificate object.
  17173. * @return 0 on success.
  17174. * @return MEMORY_E on dynamic memory allocation failure.
  17175. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17176. * is invalid.
  17177. * @return BUFFER_E when data in buffer is too small.
  17178. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  17179. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  17180. */
  17181. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  17182. {
  17183. #ifndef WOLFSSL_ASN_TEMPLATE
  17184. word32 idx = 0;
  17185. int length = 0;
  17186. int count = 0;
  17187. byte b = 0;
  17188. word32 oid;
  17189. WOLFSSL_ENTER("DecodeAuthInfo");
  17190. /* Unwrap the list of AIAs */
  17191. if (GetSequence(input, &idx, &length, sz) < 0)
  17192. return ASN_PARSE_E;
  17193. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  17194. /* Unwrap a single AIA */
  17195. if (GetSequence(input, &idx, &length, sz) < 0)
  17196. return ASN_PARSE_E;
  17197. oid = 0;
  17198. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  17199. return ASN_PARSE_E;
  17200. }
  17201. /* Only supporting URIs right now. */
  17202. if (GetASNTag(input, &idx, &b, sz) < 0)
  17203. return ASN_PARSE_E;
  17204. if (GetLength(input, &idx, &length, sz) < 0)
  17205. return ASN_PARSE_E;
  17206. /* Set ocsp entry */
  17207. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  17208. {
  17209. cert->extAuthInfoSz = length;
  17210. cert->extAuthInfo = input + idx;
  17211. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17212. count++;
  17213. #else
  17214. break;
  17215. #endif
  17216. }
  17217. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17218. /* Set CaIssuers entry */
  17219. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  17220. {
  17221. cert->extAuthInfoCaIssuerSz = length;
  17222. cert->extAuthInfoCaIssuer = input + idx;
  17223. count++;
  17224. }
  17225. #endif
  17226. idx += (word32)length;
  17227. }
  17228. return 0;
  17229. #else
  17230. word32 idx = 0;
  17231. int length = 0;
  17232. int count = 0;
  17233. int ret = 0;
  17234. WOLFSSL_ENTER("DecodeAuthInfo");
  17235. /* Unwrap the list of AIAs */
  17236. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17237. ret = ASN_PARSE_E;
  17238. }
  17239. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  17240. ASNGetData dataASN[accessDescASN_Length];
  17241. /* Clear dynamic data and retrieve OID and name. */
  17242. XMEMSET(dataASN, 0, sizeof(dataASN));
  17243. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  17244. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  17245. /* Parse AccessDescription. */
  17246. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  17247. input, &idx, sz);
  17248. if (ret == 0) {
  17249. word32 sz32;
  17250. /* Check we have OCSP and URI. */
  17251. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  17252. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  17253. /* Store URI for OCSP lookup. */
  17254. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17255. &cert->extAuthInfo, &sz32);
  17256. cert->extAuthInfoSz = (int)sz32;
  17257. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17258. count++;
  17259. #else
  17260. break;
  17261. #endif
  17262. }
  17263. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17264. /* Check we have CA Issuer and URI. */
  17265. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  17266. AIA_CA_ISSUER_OID) &&
  17267. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  17268. /* Set CaIssuers entry */
  17269. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17270. &cert->extAuthInfoCaIssuer, &sz32);
  17271. cert->extAuthInfoCaIssuerSz = (int)sz32;
  17272. count++;
  17273. }
  17274. #endif
  17275. /* Otherwise skip. */
  17276. }
  17277. }
  17278. return ret;
  17279. #endif
  17280. }
  17281. #ifdef WOLFSSL_ASN_TEMPLATE
  17282. /* ASN.1 template for AuthorityKeyIdentifier.
  17283. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  17284. */
  17285. static const ASNItem authKeyIdASN[] = {
  17286. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17287. /* keyIdentifier */
  17288. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  17289. /* authorityCertIssuer */
  17290. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  17291. /* authorityCertSerialNumber */
  17292. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  17293. };
  17294. enum {
  17295. AUTHKEYIDASN_IDX_SEQ = 0,
  17296. AUTHKEYIDASN_IDX_KEYID,
  17297. AUTHKEYIDASN_IDX_ISSUER,
  17298. AUTHKEYIDASN_IDX_SERIAL
  17299. };
  17300. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  17301. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  17302. #endif
  17303. /* Decode authority key identifier extension in a certificate.
  17304. *
  17305. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  17306. *
  17307. * @param [in] input Buffer holding data.
  17308. * @param [in] sz Size of data in buffer.
  17309. * @param [in, out] cert Certificate object.
  17310. * @return 0 on success.
  17311. * @return MEMORY_E on dynamic memory allocation failure.
  17312. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17313. * is invalid.
  17314. * @return BUFFER_E when data in buffer is too small.
  17315. */
  17316. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17317. {
  17318. #ifndef WOLFSSL_ASN_TEMPLATE
  17319. word32 idx = 0;
  17320. int length = 0;
  17321. byte tag;
  17322. WOLFSSL_ENTER("DecodeAuthKeyId");
  17323. if (GetSequence(input, &idx, &length, sz) < 0) {
  17324. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17325. return ASN_PARSE_E;
  17326. }
  17327. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  17328. return ASN_PARSE_E;
  17329. }
  17330. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  17331. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  17332. cert->extAuthKeyIdSet = 0;
  17333. return 0;
  17334. }
  17335. if (GetLength(input, &idx, &length, sz) <= 0) {
  17336. WOLFSSL_MSG("\tfail: extension data length");
  17337. return ASN_PARSE_E;
  17338. }
  17339. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17340. #ifdef WOLFSSL_AKID_NAME
  17341. cert->extRawAuthKeyIdSrc = input;
  17342. cert->extRawAuthKeyIdSz = sz;
  17343. #endif
  17344. cert->extAuthKeyIdSrc = &input[idx];
  17345. cert->extAuthKeyIdSz = length;
  17346. #endif /* OPENSSL_EXTRA */
  17347. return GetHashId(input + idx, length, cert->extAuthKeyId,
  17348. HashIdAlg(cert->signatureOID));
  17349. #else
  17350. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  17351. int ret = 0;
  17352. WOLFSSL_ENTER("DecodeAuthKeyId");
  17353. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  17354. if (ret == 0) {
  17355. /* Parse an authority key identifier. */
  17356. word32 idx = 0;
  17357. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  17358. &idx, sz);
  17359. }
  17360. /* Each field is optional */
  17361. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data != NULL) {
  17362. #ifdef OPENSSL_EXTRA
  17363. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID],
  17364. &cert->extAuthKeyIdSrc, &cert->extAuthKeyIdSz);
  17365. #endif /* OPENSSL_EXTRA */
  17366. /* Get the hash or hash of the hash if wrong size. */
  17367. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  17368. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  17369. cert->extAuthKeyId, HashIdAlg(cert->signatureOID));
  17370. }
  17371. #ifdef WOLFSSL_AKID_NAME
  17372. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.data != NULL) {
  17373. /* We only support using one (first) name. Parse the name to perform
  17374. * a sanity check. */
  17375. word32 idx = 0;
  17376. ASNGetData nameASN[altNameASN_Length];
  17377. XMEMSET(nameASN, 0, sizeof(nameASN));
  17378. /* Parse GeneralName with the choices supported. */
  17379. GetASN_Choice(&nameASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  17380. /* Decode a GeneralName choice. */
  17381. ret = GetASN_Items(altNameASN, nameASN, altNameASN_Length, 0,
  17382. dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.data, &idx,
  17383. dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.length);
  17384. if (ret == 0) {
  17385. GetASN_GetConstRef(&nameASN[ALTNAMEASN_IDX_GN],
  17386. &cert->extAuthKeyIdIssuer, &cert->extAuthKeyIdIssuerSz);
  17387. }
  17388. }
  17389. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_SERIAL].data.ref.data != NULL) {
  17390. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_SERIAL],
  17391. &cert->extAuthKeyIdIssuerSN, &cert->extAuthKeyIdIssuerSNSz);
  17392. }
  17393. if (ret == 0) {
  17394. if ((cert->extAuthKeyIdIssuerSz > 0) ^
  17395. (cert->extAuthKeyIdIssuerSNSz > 0)) {
  17396. WOLFSSL_MSG("authorityCertIssuer and authorityCertSerialNumber MUST"
  17397. " both be present or both be absent");
  17398. }
  17399. }
  17400. #endif /* WOLFSSL_AKID_NAME */
  17401. if (ret == 0) {
  17402. #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_AKID_NAME)
  17403. /* Store the raw authority key id. */
  17404. cert->extRawAuthKeyIdSrc = input;
  17405. cert->extRawAuthKeyIdSz = sz;
  17406. #endif /* OPENSSL_EXTRA */
  17407. }
  17408. FREE_ASNGETDATA(dataASN, cert->heap);
  17409. return ret;
  17410. #endif /* WOLFSSL_ASN_TEMPLATE */
  17411. }
  17412. /* Decode subject key id extension in a certificate.
  17413. *
  17414. * X.509: RFC 5280, 4.2.1.2 - Subject Key Identifier.
  17415. *
  17416. * @param [in] input Buffer holding data.
  17417. * @param [in] sz Size of data in buffer.
  17418. * @param [in, out] cert Certificate object.
  17419. * @return 0 on success.
  17420. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  17421. * invalid.
  17422. * @return MEMORY_E on dynamic memory allocation failure.
  17423. */
  17424. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17425. {
  17426. word32 idx = 0;
  17427. int length = 0;
  17428. int ret = 0;
  17429. WOLFSSL_ENTER("DecodeSubjKeyId");
  17430. ret = GetOctetString(input, &idx, &length, sz);
  17431. if (ret > 0) {
  17432. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17433. cert->extSubjKeyIdSrc = &input[idx];
  17434. cert->extSubjKeyIdSz = (word32)length;
  17435. #endif /* OPENSSL_EXTRA */
  17436. /* Get the hash or hash of the hash if wrong size. */
  17437. ret = GetHashId(input + idx, length, cert->extSubjKeyId,
  17438. HashIdAlg(cert->signatureOID));
  17439. }
  17440. return ret;
  17441. }
  17442. #ifdef WOLFSSL_ASN_TEMPLATE
  17443. /* ASN.1 template for KeyUsage.
  17444. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17445. */
  17446. static const ASNItem keyUsageASN[] = {
  17447. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  17448. };
  17449. enum {
  17450. KEYUSAGEASN_IDX_STR = 0
  17451. };
  17452. /* Number of items in ASN.1 template for KeyUsage. */
  17453. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  17454. #endif
  17455. /* Decode key usage extension in a certificate.
  17456. *
  17457. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17458. *
  17459. * @param [in] input Buffer holding data.
  17460. * @param [in] sz Size of data in buffer.
  17461. * @param [in, out] cert Certificate object.
  17462. * @return 0 on success.
  17463. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17464. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17465. * is invalid.
  17466. * @return MEMORY_E on dynamic memory allocation failure.
  17467. */
  17468. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17469. {
  17470. #ifndef WOLFSSL_ASN_TEMPLATE
  17471. word32 idx = 0;
  17472. int length;
  17473. int ret;
  17474. WOLFSSL_ENTER("DecodeKeyUsage");
  17475. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  17476. if (ret != 0)
  17477. return ret;
  17478. if (length == 0 || length > 2)
  17479. return ASN_PARSE_E;
  17480. cert->extKeyUsage = (word16)(input[idx]);
  17481. if (length == 2)
  17482. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  17483. return 0;
  17484. #else
  17485. ASNGetData dataASN[keyUsageASN_Length];
  17486. word32 idx = 0;
  17487. byte keyUsage[2];
  17488. word32 keyUsageSz = sizeof(keyUsage);
  17489. int ret;
  17490. WOLFSSL_ENTER("DecodeKeyUsage");
  17491. /* Clear dynamic data and set where to store extended key usage. */
  17492. XMEMSET(dataASN, 0, sizeof(dataASN));
  17493. GetASN_Buffer(&dataASN[KEYUSAGEASN_IDX_STR], keyUsage, &keyUsageSz);
  17494. /* Parse key usage. */
  17495. ret = GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  17496. &idx, sz);
  17497. if (ret == 0) {
  17498. /* Decode the bit string number as LE */
  17499. cert->extKeyUsage = (word16)(keyUsage[0]);
  17500. if (keyUsageSz == 2)
  17501. cert->extKeyUsage |= (word16)(keyUsage[1] << 8);
  17502. }
  17503. return ret;
  17504. #endif /* WOLFSSL_ASN_TEMPLATE */
  17505. }
  17506. #ifdef WOLFSSL_ASN_TEMPLATE
  17507. /* ASN.1 template for KeyPurposeId.
  17508. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17509. */
  17510. static const ASNItem keyPurposeIdASN[] = {
  17511. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  17512. };
  17513. enum {
  17514. KEYPURPOSEIDASN_IDX_OID = 0
  17515. };
  17516. /* Number of items in ASN.1 template for KeyPurposeId. */
  17517. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  17518. #endif
  17519. /* Decode extended key usage extension in a certificate.
  17520. *
  17521. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17522. *
  17523. * @param [in] input Buffer holding data.
  17524. * @param [in] sz Size of data in buffer.
  17525. * @param [in, out] cert Certificate object.
  17526. * @return 0 on success.
  17527. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17528. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17529. * is invalid.
  17530. * @return MEMORY_E on dynamic memory allocation failure.
  17531. */
  17532. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17533. {
  17534. #ifndef WOLFSSL_ASN_TEMPLATE
  17535. word32 idx = 0, oid;
  17536. int length, ret;
  17537. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17538. if (GetSequence(input, &idx, &length, sz) < 0) {
  17539. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17540. return ASN_PARSE_E;
  17541. }
  17542. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17543. cert->extExtKeyUsageSrc = input + idx;
  17544. cert->extExtKeyUsageSz = length;
  17545. #endif
  17546. while (idx < (word32)sz) {
  17547. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  17548. if (ret == ASN_UNKNOWN_OID_E)
  17549. continue;
  17550. else if (ret < 0)
  17551. return ret;
  17552. switch (oid) {
  17553. case EKU_ANY_OID:
  17554. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17555. break;
  17556. case EKU_SERVER_AUTH_OID:
  17557. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17558. break;
  17559. case EKU_CLIENT_AUTH_OID:
  17560. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17561. break;
  17562. case EKU_CODESIGNING_OID:
  17563. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17564. break;
  17565. case EKU_EMAILPROTECT_OID:
  17566. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17567. break;
  17568. case EKU_TIMESTAMP_OID:
  17569. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17570. break;
  17571. case EKU_OCSP_SIGN_OID:
  17572. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17573. break;
  17574. #ifdef WOLFSSL_WOLFSSH
  17575. case EKU_SSH_CLIENT_AUTH_OID:
  17576. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  17577. break;
  17578. case EKU_SSH_MSCL_OID:
  17579. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  17580. break;
  17581. case EKU_SSH_KP_CLIENT_AUTH_OID:
  17582. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  17583. break;
  17584. #endif /* WOLFSSL_WOLFSSH */
  17585. default:
  17586. break;
  17587. }
  17588. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17589. cert->extExtKeyUsageCount++;
  17590. #endif
  17591. }
  17592. return 0;
  17593. #else
  17594. word32 idx = 0;
  17595. int length;
  17596. int ret = 0;
  17597. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17598. /* Strip SEQUENCE OF and expect to account for all the data. */
  17599. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17600. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17601. ret = ASN_PARSE_E;
  17602. }
  17603. if (ret == 0) {
  17604. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17605. /* Keep reference for WOLFSSL_X509. */
  17606. cert->extExtKeyUsageSrc = input + idx;
  17607. cert->extExtKeyUsageSz = (word32)length;
  17608. #endif
  17609. }
  17610. /* Check all OIDs. */
  17611. while ((ret == 0) && (idx < (word32)sz)) {
  17612. ASNGetData dataASN[keyPurposeIdASN_Length];
  17613. /* Clear dynamic data items and set OID type expected. */
  17614. XMEMSET(dataASN, 0, sizeof(dataASN));
  17615. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  17616. /* Decode KeyPurposeId. */
  17617. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  17618. input, &idx, sz);
  17619. /* Skip unknown OIDs. */
  17620. if (ret == ASN_UNKNOWN_OID_E) {
  17621. ret = 0;
  17622. }
  17623. else if (ret == 0) {
  17624. /* Store the bit for the OID. */
  17625. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  17626. case EKU_ANY_OID:
  17627. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17628. break;
  17629. case EKU_SERVER_AUTH_OID:
  17630. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17631. break;
  17632. case EKU_CLIENT_AUTH_OID:
  17633. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17634. break;
  17635. case EKU_CODESIGNING_OID:
  17636. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17637. break;
  17638. case EKU_EMAILPROTECT_OID:
  17639. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17640. break;
  17641. case EKU_TIMESTAMP_OID:
  17642. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17643. break;
  17644. case EKU_OCSP_SIGN_OID:
  17645. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17646. break;
  17647. }
  17648. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17649. /* Keep count for WOLFSSL_X509. */
  17650. cert->extExtKeyUsageCount++;
  17651. #endif
  17652. }
  17653. }
  17654. return ret;
  17655. #endif /* WOLFSSL_ASN_TEMPLATE */
  17656. }
  17657. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17658. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  17659. {
  17660. word32 idx = 0;
  17661. int len = 0;
  17662. WOLFSSL_ENTER("DecodeNsCertType");
  17663. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  17664. return ASN_PARSE_E;
  17665. /* Don't need to worry about unused bits as CheckBitString makes sure
  17666. * they're zero. */
  17667. if (idx < (word32)sz)
  17668. cert->nsCertType = input[idx];
  17669. else
  17670. return ASN_PARSE_E;
  17671. return 0;
  17672. }
  17673. #endif
  17674. #ifndef IGNORE_NAME_CONSTRAINTS
  17675. #ifdef WOLFSSL_ASN_TEMPLATE
  17676. /* ASN.1 template for GeneralSubtree.
  17677. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17678. */
  17679. static const ASNItem subTreeASN[] = {
  17680. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17681. /* base GeneralName */
  17682. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  17683. /* minimum BaseDistance DEFAULT 0*/
  17684. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  17685. /* maximum BaseDistance OPTIONAL */
  17686. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  17687. };
  17688. enum {
  17689. SUBTREEASN_IDX_SEQ = 0,
  17690. SUBTREEASN_IDX_BASE,
  17691. SUBTREEASN_IDX_MIN,
  17692. SUBTREEASN_IDX_MAX
  17693. };
  17694. /* Number of items in ASN.1 template for GeneralSubtree. */
  17695. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  17696. #endif
  17697. #ifdef WOLFSSL_ASN_TEMPLATE
  17698. /* Decode the Subtree's GeneralName.
  17699. *
  17700. * @param [in] input Buffer holding data.
  17701. * @param [in] sz Size of data in buffer.
  17702. * @param [in] tag BER tag on GeneralName.
  17703. * @param [in, out] head Linked list of subtree names.
  17704. * @param [in] heap Dynamic memory hint.
  17705. * @return 0 on success.
  17706. * @return MEMORY_E when dynamic memory allocation fails.
  17707. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17708. */
  17709. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  17710. Base_entry** head, void* heap)
  17711. {
  17712. Base_entry* entry;
  17713. word32 nameIdx = 0;
  17714. word32 len = sz;
  17715. int strLen;
  17716. int ret = 0;
  17717. (void)heap;
  17718. /* if constructed has leading sequence */
  17719. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  17720. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  17721. if (ret < 0) {
  17722. ret = ASN_PARSE_E;
  17723. }
  17724. else {
  17725. len = (word32)strLen;
  17726. ret = 0;
  17727. }
  17728. }
  17729. if (ret == 0) {
  17730. /* TODO: consider one malloc. */
  17731. /* Allocate Base Entry object. */
  17732. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17733. DYNAMIC_TYPE_ALTNAME);
  17734. if (entry == NULL) {
  17735. ret = MEMORY_E;
  17736. }
  17737. }
  17738. if (ret == 0) {
  17739. /* Allocate name. */
  17740. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  17741. if (entry->name == NULL) {
  17742. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17743. ret = MEMORY_E;
  17744. }
  17745. }
  17746. if (ret == 0) {
  17747. /* Store name, size and tag in object. */
  17748. XMEMCPY(entry->name, &input[nameIdx], len);
  17749. entry->name[len] = '\0';
  17750. entry->nameSz = (int)len;
  17751. entry->type = tag & ASN_TYPE_MASK;
  17752. /* Put entry at front of linked list. */
  17753. entry->next = *head;
  17754. *head = entry;
  17755. }
  17756. return ret;
  17757. }
  17758. #endif
  17759. /* Decode a subtree of a name constraints in a certificate.
  17760. *
  17761. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17762. *
  17763. * @param [in] input Buffer holding data.
  17764. * @param [in] sz Size of data in buffer.
  17765. * @param [in, out] head Linked list of subtree names.
  17766. * @param [in] heap Dynamic memory hint.
  17767. * @return 0 on success.
  17768. * @return MEMORY_E when dynamic memory allocation fails.
  17769. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17770. */
  17771. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  17772. void* heap)
  17773. {
  17774. #ifndef WOLFSSL_ASN_TEMPLATE
  17775. word32 idx = 0;
  17776. int ret = 0;
  17777. (void)heap;
  17778. while (idx < (word32)sz) {
  17779. int seqLength, strLength;
  17780. word32 nameIdx;
  17781. byte b, bType;
  17782. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  17783. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17784. return ASN_PARSE_E;
  17785. }
  17786. if (idx >= (word32)sz) {
  17787. WOLFSSL_MSG("\tfail: expecting tag");
  17788. return ASN_PARSE_E;
  17789. }
  17790. nameIdx = idx;
  17791. b = input[nameIdx++];
  17792. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  17793. WOLFSSL_MSG("\tinvalid length");
  17794. return ASN_PARSE_E;
  17795. }
  17796. /* Get type, LSB 4-bits */
  17797. bType = (byte)(b & ASN_TYPE_MASK);
  17798. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  17799. bType == ASN_DIR_TYPE) {
  17800. Base_entry* entry;
  17801. /* if constructed has leading sequence */
  17802. if (b & ASN_CONSTRUCTED) {
  17803. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  17804. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  17805. return ASN_PARSE_E;
  17806. }
  17807. }
  17808. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17809. DYNAMIC_TYPE_ALTNAME);
  17810. if (entry == NULL) {
  17811. WOLFSSL_MSG("allocate error");
  17812. return MEMORY_E;
  17813. }
  17814. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  17815. DYNAMIC_TYPE_ALTNAME);
  17816. if (entry->name == NULL) {
  17817. WOLFSSL_MSG("allocate error");
  17818. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17819. return MEMORY_E;
  17820. }
  17821. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  17822. entry->name[strLength] = '\0';
  17823. entry->nameSz = strLength;
  17824. entry->type = bType;
  17825. entry->next = *head;
  17826. *head = entry;
  17827. }
  17828. idx += (word32)seqLength;
  17829. }
  17830. return ret;
  17831. #else
  17832. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  17833. word32 idx = 0;
  17834. int ret = 0;
  17835. (void)heap;
  17836. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  17837. /* Process all subtrees. */
  17838. while ((ret == 0) && (idx < (word32)sz)) {
  17839. byte minVal = 0;
  17840. byte maxVal = 0;
  17841. /* Clear dynamic data and set choice for GeneralName and location to
  17842. * store minimum and maximum.
  17843. */
  17844. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  17845. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  17846. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  17847. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  17848. /* Parse GeneralSubtree. */
  17849. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  17850. &idx, sz);
  17851. if (ret == 0) {
  17852. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  17853. /* Check GeneralName tag is one of the types we can handle. */
  17854. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  17855. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  17856. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  17857. /* Parse the general name and store a new entry. */
  17858. ret = DecodeSubtreeGeneralName(input +
  17859. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  17860. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  17861. }
  17862. /* Skip entry. */
  17863. }
  17864. }
  17865. FREE_ASNGETDATA(dataASN, heap);
  17866. return ret;
  17867. #endif
  17868. }
  17869. #ifdef WOLFSSL_ASN_TEMPLATE
  17870. /* ASN.1 template for NameConstraints.
  17871. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17872. */
  17873. static const ASNItem nameConstraintsASN[] = {
  17874. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17875. /* permittedSubtrees */
  17876. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  17877. /* excludededSubtrees */
  17878. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17879. };
  17880. enum {
  17881. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  17882. NAMECONSTRAINTSASN_IDX_PERMIT,
  17883. NAMECONSTRAINTSASN_IDX_EXCLUDE
  17884. };
  17885. /* Number of items in ASN.1 template for NameConstraints. */
  17886. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  17887. #endif
  17888. /* Decode name constraints extension in a certificate.
  17889. *
  17890. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17891. *
  17892. * @param [in] input Buffer holding data.
  17893. * @param [in] sz Size of data in buffer.
  17894. * @param [in, out] cert Certificate object.
  17895. * @return 0 on success.
  17896. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17897. * is invalid.
  17898. * @return MEMORY_E on dynamic memory allocation failure.
  17899. */
  17900. static int DecodeNameConstraints(const byte* input, word32 sz,
  17901. DecodedCert* cert)
  17902. {
  17903. #ifndef WOLFSSL_ASN_TEMPLATE
  17904. word32 idx = 0;
  17905. int length = 0;
  17906. WOLFSSL_ENTER("DecodeNameConstraints");
  17907. if (GetSequence(input, &idx, &length, sz) < 0) {
  17908. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17909. return ASN_PARSE_E;
  17910. }
  17911. while (idx < (word32)sz) {
  17912. byte b = input[idx++];
  17913. Base_entry** subtree = NULL;
  17914. if (GetLength(input, &idx, &length, sz) <= 0) {
  17915. WOLFSSL_MSG("\tinvalid length");
  17916. return ASN_PARSE_E;
  17917. }
  17918. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17919. subtree = &cert->permittedNames;
  17920. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17921. subtree = &cert->excludedNames;
  17922. else {
  17923. WOLFSSL_MSG("\tinvalid subtree");
  17924. return ASN_PARSE_E;
  17925. }
  17926. if (DecodeSubtree(input + idx, (word32)length, subtree,
  17927. cert->heap) < 0) {
  17928. WOLFSSL_MSG("\terror parsing subtree");
  17929. return ASN_PARSE_E;
  17930. }
  17931. idx += (word32)length;
  17932. }
  17933. return 0;
  17934. #else
  17935. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17936. word32 idx = 0;
  17937. int ret = 0;
  17938. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17939. if (ret == 0) {
  17940. /* Parse NameConstraints. */
  17941. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17942. nameConstraintsASN_Length, 1, input, &idx, sz);
  17943. }
  17944. if (ret == 0) {
  17945. /* If there was a permittedSubtrees then parse it. */
  17946. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17947. ret = DecodeSubtree(
  17948. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17949. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17950. &cert->permittedNames, cert->heap);
  17951. }
  17952. }
  17953. if (ret == 0) {
  17954. /* If there was a excludedSubtrees then parse it. */
  17955. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17956. ret = DecodeSubtree(
  17957. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17958. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17959. &cert->excludedNames, cert->heap);
  17960. }
  17961. }
  17962. FREE_ASNGETDATA(dataASN, cert->heap);
  17963. return ret;
  17964. #endif /* WOLFSSL_ASN_TEMPLATE */
  17965. }
  17966. #endif /* IGNORE_NAME_CONSTRAINTS */
  17967. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17968. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17969. /* Decode ITU-T X.690 OID format to a string representation
  17970. * return string length */
  17971. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17972. {
  17973. word32 val, inIdx = 0, outIdx = 0;
  17974. int w = 0;
  17975. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17976. return BAD_FUNC_ARG;
  17977. /* The first byte expands into b/40 dot b%40. */
  17978. val = in[inIdx++];
  17979. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17980. if (w < 0) {
  17981. w = BUFFER_E;
  17982. goto exit;
  17983. }
  17984. outIdx += (word32)w;
  17985. val = 0;
  17986. while (inIdx < inSz && outIdx < outSz) {
  17987. /* extract the next OID digit from in to val */
  17988. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17989. if (in[inIdx] & 0x80) {
  17990. val += in[inIdx] & 0x7F;
  17991. val *= 128;
  17992. }
  17993. else {
  17994. /* write val as text into out */
  17995. val += in[inIdx];
  17996. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17997. if (w < 0 || (word32)w > outSz - outIdx) {
  17998. w = BUFFER_E;
  17999. goto exit;
  18000. }
  18001. outIdx += (word32)w;
  18002. val = 0;
  18003. }
  18004. inIdx++;
  18005. }
  18006. if (outIdx == outSz)
  18007. outIdx--;
  18008. out[outIdx] = 0;
  18009. w = (int)outIdx;
  18010. exit:
  18011. return w;
  18012. }
  18013. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  18014. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  18015. #ifdef WOLFSSL_ASN_TEMPLATE
  18016. /* ASN.1 template for PolicyInformation.
  18017. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  18018. */
  18019. static const ASNItem policyInfoASN[] = {
  18020. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18021. /* policyIdentifier */
  18022. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18023. /* policyQualifiers */
  18024. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  18025. };
  18026. enum {
  18027. POLICYINFOASN_IDX_SEQ = 0,
  18028. POLICYINFOASN_IDX_ID,
  18029. POLICYINFOASN_IDX_QUALI
  18030. };
  18031. /* Number of items in ASN.1 template for PolicyInformation. */
  18032. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  18033. #endif
  18034. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  18035. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  18036. {
  18037. #ifndef WOLFSSL_ASN_TEMPLATE
  18038. word32 idx = 0;
  18039. word32 oldIdx;
  18040. int policy_length = 0;
  18041. int ret;
  18042. int total_length = 0;
  18043. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  18044. !defined(WOLFSSL_DUP_CERTPOL)
  18045. int i;
  18046. #endif
  18047. WOLFSSL_ENTER("DecodeCertPolicy");
  18048. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  18049. /* Check if cert is null before dereferencing below */
  18050. if (cert == NULL)
  18051. return BAD_FUNC_ARG;
  18052. #else
  18053. (void)cert;
  18054. #endif
  18055. #if defined(WOLFSSL_CERT_EXT)
  18056. cert->extCertPoliciesNb = 0;
  18057. #endif
  18058. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  18059. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  18060. return ASN_PARSE_E;
  18061. }
  18062. /* Validate total length */
  18063. if (total_length > (int)(sz - idx)) {
  18064. WOLFSSL_MSG("\tCertPolicy length mismatch");
  18065. return ASN_PARSE_E;
  18066. }
  18067. /* Unwrap certificatePolicies */
  18068. do {
  18069. int length = 0;
  18070. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  18071. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  18072. return ASN_PARSE_E;
  18073. }
  18074. oldIdx = idx;
  18075. ret = GetASNObjectId(input, &idx, &length, sz);
  18076. if (ret != 0)
  18077. return ret;
  18078. policy_length -= (int)(idx - oldIdx);
  18079. if (length > 0) {
  18080. /* Verify length won't overrun buffer */
  18081. if (length > (int)(sz - idx)) {
  18082. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  18083. return ASN_PARSE_E;
  18084. }
  18085. #if defined(WOLFSSL_SEP)
  18086. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  18087. DYNAMIC_TYPE_X509_EXT);
  18088. if (cert->deviceType == NULL) {
  18089. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  18090. return MEMORY_E;
  18091. }
  18092. cert->deviceTypeSz = length;
  18093. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  18094. break;
  18095. #elif defined(WOLFSSL_CERT_EXT)
  18096. /* decode cert policy */
  18097. if (DecodePolicyOID(cert->extCertPolicies[
  18098. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  18099. input + idx, length) <= 0) {
  18100. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  18101. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18102. return ASN_PARSE_E;
  18103. }
  18104. #ifndef WOLFSSL_DUP_CERTPOL
  18105. /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST
  18106. * NOT appear more than once in a certificate policies
  18107. * extension". This is a sanity check for duplicates.
  18108. * extCertPolicies should only have OID values, additional
  18109. * qualifiers need to be stored in a separate array. */
  18110. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  18111. if (XMEMCMP(cert->extCertPolicies[i],
  18112. cert->extCertPolicies[cert->extCertPoliciesNb],
  18113. MAX_CERTPOL_SZ) == 0) {
  18114. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  18115. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  18116. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  18117. return CERTPOLICIES_E;
  18118. }
  18119. }
  18120. #endif /* !WOLFSSL_DUP_CERTPOL */
  18121. cert->extCertPoliciesNb++;
  18122. #else
  18123. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  18124. return 0;
  18125. #endif
  18126. }
  18127. idx += (word32)policy_length;
  18128. } while((int)idx < total_length
  18129. #if defined(WOLFSSL_CERT_EXT)
  18130. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  18131. #endif
  18132. );
  18133. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  18134. return 0;
  18135. #else /* WOLFSSL_ASN_TEMPLATE */
  18136. word32 idx = 0;
  18137. int ret = 0;
  18138. int total_length = 0;
  18139. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  18140. !defined(WOLFSSL_DUP_CERTPOL)
  18141. int i;
  18142. #endif
  18143. WOLFSSL_ENTER("DecodeCertPolicy");
  18144. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  18145. /* Check if cert is null before dereferencing below */
  18146. if (cert == NULL)
  18147. ret = BAD_FUNC_ARG;
  18148. #endif
  18149. if (ret == 0) {
  18150. #if defined(WOLFSSL_CERT_EXT)
  18151. cert->extCertPoliciesNb = 0;
  18152. #endif
  18153. /* Strip SEQUENCE OF and check using all data. */
  18154. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  18155. {
  18156. ret = ASN_PARSE_E;
  18157. }
  18158. }
  18159. /* Unwrap certificatePolicies */
  18160. while ((ret == 0) && ((int)idx < total_length)
  18161. #if defined(WOLFSSL_CERT_EXT)
  18162. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  18163. #endif
  18164. ) {
  18165. ASNGetData dataASN[policyInfoASN_Length];
  18166. byte* data = NULL;
  18167. word32 length = 0;
  18168. /* Clear dynamic data and check OID is a cert policy type. */
  18169. XMEMSET(dataASN, 0, sizeof(dataASN));
  18170. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  18171. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  18172. input, &idx, (word32)sz);
  18173. if (ret == 0) {
  18174. /* Get the OID. */
  18175. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  18176. if (length == 0) {
  18177. ret = ASN_PARSE_E;
  18178. }
  18179. }
  18180. #if defined(WOLFSSL_SEP)
  18181. /* Store OID in device type. */
  18182. if (ret == 0) {
  18183. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  18184. DYNAMIC_TYPE_X509_EXT);
  18185. if (cert->deviceType == NULL) {
  18186. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  18187. ret = MEMORY_E;
  18188. }
  18189. }
  18190. if (ret == 0) {
  18191. /* Store device type data and length. */
  18192. cert->deviceTypeSz = (int)length;
  18193. XMEMCPY(cert->deviceType, data, length);
  18194. break;
  18195. }
  18196. #elif defined(WOLFSSL_CERT_EXT)
  18197. if (ret == 0) {
  18198. /* Decode cert policy. */
  18199. if (DecodePolicyOID(
  18200. cert->extCertPolicies[cert->extCertPoliciesNb],
  18201. MAX_CERTPOL_SZ, data, length) <= 0) {
  18202. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  18203. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18204. ret = ASN_PARSE_E;
  18205. }
  18206. }
  18207. #ifndef WOLFSSL_DUP_CERTPOL
  18208. /* From RFC 5280 section 4.2.1.4 "A certificate policy OID MUST
  18209. * NOT appear more than once in a certificate policies
  18210. * extension". This is a sanity check for duplicates.
  18211. * extCertPolicies should only have OID values, additional
  18212. * qualifiers need to be stored in a separate array. */
  18213. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  18214. if (XMEMCMP(cert->extCertPolicies[i],
  18215. cert->extCertPolicies[cert->extCertPoliciesNb],
  18216. MAX_CERTPOL_SZ) == 0) {
  18217. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  18218. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  18219. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  18220. ret = CERTPOLICIES_E;
  18221. }
  18222. }
  18223. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  18224. if (ret == 0) {
  18225. /* Keep count of policies seen. */
  18226. cert->extCertPoliciesNb++;
  18227. }
  18228. #else
  18229. (void)data;
  18230. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  18231. break;
  18232. #endif
  18233. }
  18234. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  18235. return ret;
  18236. #endif /* WOLFSSL_ASN_TEMPLATE */
  18237. }
  18238. #endif /* WOLFSSL_SEP */
  18239. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18240. #ifdef WOLFSSL_ASN_TEMPLATE
  18241. /* ASN.1 template for subject dir attribute.
  18242. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  18243. */
  18244. static const ASNItem subjDirAttrASN[] = {
  18245. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18246. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18247. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  18248. };
  18249. enum {
  18250. SUBJDIRATTRASN_IDX_SEQ = 0,
  18251. SUBJDIRATTRASN_IDX_OID,
  18252. SUBJDIRATTRASN_IDX_SET,
  18253. };
  18254. /* Number of items in ASN.1 template for BasicConstraints. */
  18255. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  18256. #endif
  18257. /* Decode subject directory attributes extension in a certificate.
  18258. *
  18259. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  18260. *
  18261. * @param [in] input Buffer holding data.
  18262. * @param [in] sz Size of data in buffer.
  18263. * @param [in, out] cert Certificate object.
  18264. * @return 0 on success.
  18265. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18266. * is invalid.
  18267. */
  18268. static int DecodeSubjDirAttr(const byte* input, word32 sz, DecodedCert* cert)
  18269. {
  18270. #ifndef WOLFSSL_ASN_TEMPLATE
  18271. word32 idx = 0;
  18272. int length = 0;
  18273. int ret = 0;
  18274. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18275. #ifdef OPENSSL_ALL
  18276. cert->extSubjDirAttrSrc = input;
  18277. cert->extSubjDirAttrSz = sz;
  18278. #endif /* OPENSSL_ALL */
  18279. /* Unwrap the list of Attributes */
  18280. if (GetSequence(input, &idx, &length, sz) < 0)
  18281. return ASN_PARSE_E;
  18282. if (length == 0) {
  18283. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  18284. If the subjectDirectoryAttributes extension is present, the
  18285. sequence MUST contain at least one entry. */
  18286. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18287. return ASN_PARSE_E;
  18288. }
  18289. /* length is the length of the list contents */
  18290. while (idx < (word32)sz) {
  18291. word32 oid;
  18292. if (GetSequence(input, &idx, &length, sz) < 0)
  18293. return ASN_PARSE_E;
  18294. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  18295. return ASN_PARSE_E;
  18296. if (GetSet(input, &idx, &length, sz) < 0)
  18297. return ASN_PARSE_E;
  18298. /* There may be more than one countryOfCitizenship, but save the
  18299. * first one for now. */
  18300. if (oid == SDA_COC_OID) {
  18301. byte tag;
  18302. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  18303. return ASN_PARSE_E;
  18304. if (length != COUNTRY_CODE_LEN)
  18305. return ASN_PARSE_E;
  18306. if (tag == ASN_PRINTABLE_STRING) {
  18307. XMEMCPY(cert->countryOfCitizenship,
  18308. input + idx, COUNTRY_CODE_LEN);
  18309. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18310. }
  18311. }
  18312. idx += length;
  18313. }
  18314. return ret;
  18315. #else
  18316. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  18317. int ret = 0;
  18318. word32 idx = 0;
  18319. int length;
  18320. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18321. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  18322. /* Strip outer SEQUENCE. */
  18323. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  18324. ret = ASN_PARSE_E;
  18325. }
  18326. /* Handle each inner SEQUENCE. */
  18327. while ((ret == 0) && (idx < (word32)sz)) {
  18328. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  18329. input, &idx, sz);
  18330. /* There may be more than one countryOfCitizenship, but save the
  18331. * first one for now. */
  18332. if ((ret == 0) &&
  18333. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  18334. int cuLen;
  18335. word32 setIdx = 0;
  18336. byte* setData;
  18337. word32 setLen;
  18338. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  18339. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  18340. setLen) < 0) {
  18341. ret = ASN_PARSE_E;
  18342. }
  18343. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  18344. ret = ASN_PARSE_E;
  18345. }
  18346. if (ret == 0) {
  18347. XMEMCPY(cert->countryOfCitizenship, setData + setIdx,
  18348. (size_t)cuLen);
  18349. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18350. }
  18351. }
  18352. }
  18353. FREE_ASNGETDATA(dataASN, cert->heap);
  18354. return ret;
  18355. #endif /* WOLFSSL_ASN_TEMPLATE */
  18356. }
  18357. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  18358. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18359. /* Decode subject information access extension in a certificate.
  18360. *
  18361. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  18362. *
  18363. * @param [in] input Buffer holding data.
  18364. * @param [in] sz Size of data in buffer.
  18365. * @param [in, out] cert Certificate object.
  18366. * @return 0 on success.
  18367. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18368. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18369. * is invalid.
  18370. * @return MEMORY_E on dynamic memory allocation failure.
  18371. */
  18372. static int DecodeSubjInfoAcc(const byte* input, word32 sz, DecodedCert* cert)
  18373. {
  18374. word32 idx = 0;
  18375. int length = 0;
  18376. int ret = 0;
  18377. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  18378. #ifdef OPENSSL_ALL
  18379. cert->extSubjAltNameSrc = input;
  18380. cert->extSubjAltNameSz = sz;
  18381. #endif /* OPENSSL_ALL */
  18382. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  18383. if (GetSequence(input, &idx, &length, sz) < 0)
  18384. return ASN_PARSE_E;
  18385. if (length == 0) {
  18386. /* RFC 5280 4.2.2.2. Subject Information Access
  18387. If the subjectInformationAccess extension is present, the
  18388. sequence MUST contain at least one entry. */
  18389. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18390. return ASN_PARSE_E;
  18391. }
  18392. /* Per fpkx-x509-cert-profile-common... section 5.3.
  18393. * [The] subjectInfoAccess extension must contain at least one
  18394. * instance of the id-ad-caRepository access method containing a
  18395. * publicly accessible HTTP URI which returns as certs-only
  18396. * CMS.
  18397. */
  18398. while (idx < (word32)sz) {
  18399. word32 oid = 0;
  18400. byte b;
  18401. /* Unwrap an AccessDescription */
  18402. if (GetSequence(input, &idx, &length, sz) < 0)
  18403. return ASN_PARSE_E;
  18404. /* Get the accessMethod */
  18405. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  18406. return ASN_PARSE_E;
  18407. /* Only supporting URIs right now. */
  18408. if (GetASNTag(input, &idx, &b, sz) < 0)
  18409. return ASN_PARSE_E;
  18410. if (GetLength(input, &idx, &length, sz) < 0)
  18411. return ASN_PARSE_E;
  18412. /* Set caRepo entry */
  18413. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  18414. cert->extSubjInfoAccCaRepoSz = (word32)length;
  18415. cert->extSubjInfoAccCaRepo = input + idx;
  18416. break;
  18417. }
  18418. idx += (word32)length;
  18419. }
  18420. if (cert->extSubjInfoAccCaRepo == NULL ||
  18421. cert->extSubjInfoAccCaRepoSz == 0) {
  18422. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  18423. ret = ASN_PARSE_E;
  18424. }
  18425. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  18426. return ret;
  18427. }
  18428. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  18429. /* Macro to check if bit is set, if not sets and return success.
  18430. Otherwise returns failure */
  18431. /* Macro required here because bit-field operation */
  18432. #ifndef WOLFSSL_NO_ASN_STRICT
  18433. #define VERIFY_AND_SET_OID(bit) \
  18434. if ((bit) == 0) \
  18435. (bit) = 1; \
  18436. else \
  18437. return ASN_OBJECT_ID_E;
  18438. #else
  18439. /* With no strict defined, the verify is skipped */
  18440. #define VERIFY_AND_SET_OID(bit) bit = 1;
  18441. #endif
  18442. /* Parse extension type specific data based on OID sum.
  18443. *
  18444. * Supported extensions:
  18445. * Basic Constraints - BASIC_CA_OID
  18446. * CRL Distribution Points - CRL_DIST_OID
  18447. * Authority Information Access - AUTH_INFO_OID
  18448. * Subject Alternative Name - ALT_NAMES_OID
  18449. * Authority Key Identifier - AUTH_KEY_OID
  18450. * Subject Key Identifier - SUBJ_KEY_OID
  18451. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  18452. * Key Usage - KEY_USAGE_OID
  18453. * Extended Key Usage - EXT_KEY_USAGE_OID
  18454. * Name Constraints - NAME_CONS_OID
  18455. * Inhibit anyPolicy - INHIBIT_ANY_OID
  18456. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  18457. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  18458. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  18459. * Subject Information Access - SUBJ_INFO_ACC_OID
  18460. * Unsupported extensions from RFC 5280:
  18461. * 4.2.1.5 - Policy mappings
  18462. * 4.2.1.7 - Issuer Alternative Name
  18463. * 4.2.1.11 - Policy Constraints
  18464. * 4.2.1.15 - Freshest CRL
  18465. *
  18466. * @param [in] input Buffer containing extension type specific data.
  18467. * @param [in] length Length of data.
  18468. * @param [in] oid OID sum for extension.
  18469. * @param [in] critical Whether extension is critical.
  18470. * @param [in, out] cert Certificate object.
  18471. * @return 0 on success.
  18472. * @return ASN_PARSE_E when BER encoding is invalid.
  18473. * @return MEMORY_E on dynamic memory allocation failure.
  18474. * @return Other negative values on error.
  18475. */
  18476. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  18477. byte critical, DecodedCert* cert,
  18478. int *isUnknownExt)
  18479. {
  18480. int ret = 0;
  18481. word32 idx = 0;
  18482. if (isUnknownExt != NULL)
  18483. *isUnknownExt = 0;
  18484. switch (oid) {
  18485. /* Basic Constraints. */
  18486. case BASIC_CA_OID:
  18487. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  18488. cert->extBasicConstCrit = critical ? 1 : 0;
  18489. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  18490. ret = ASN_PARSE_E;
  18491. }
  18492. break;
  18493. /* CRL Distribution point. */
  18494. case CRL_DIST_OID:
  18495. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  18496. cert->extCRLdistCrit = critical ? 1 : 0;
  18497. if (DecodeCrlDist(input, length, cert) < 0) {
  18498. ret = ASN_PARSE_E;
  18499. }
  18500. break;
  18501. /* Authority information access. */
  18502. case AUTH_INFO_OID:
  18503. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  18504. cert->extAuthInfoCrit = critical ? 1 : 0;
  18505. #ifndef WOLFSSL_ALLOW_CRIT_AIA
  18506. /* This check is added due to RFC 5280 section 4.2.2.1
  18507. * stating that conforming CA's must mark this extension
  18508. * as non-critical. When parsing extensions check that
  18509. * certificate was made in compliance with this. */
  18510. if (critical) {
  18511. WOLFSSL_MSG("Critical Authority Information Access is not"
  18512. "allowed");
  18513. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_AIA if wanted");
  18514. ret = ASN_CRIT_EXT_E;
  18515. }
  18516. #endif
  18517. if ((ret == 0) && (DecodeAuthInfo(input, length, cert) < 0)) {
  18518. ret = ASN_PARSE_E;
  18519. }
  18520. break;
  18521. /* Subject alternative name. */
  18522. case ALT_NAMES_OID:
  18523. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  18524. cert->extSubjAltNameCrit = critical ? 1 : 0;
  18525. ret = DecodeAltNames(input, length, cert);
  18526. break;
  18527. /* Authority Key Identifier. */
  18528. case AUTH_KEY_OID:
  18529. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  18530. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  18531. #ifndef WOLFSSL_ALLOW_CRIT_AKID
  18532. /* This check is added due to RFC 5280 section 4.2.1.1
  18533. * stating that conforming CA's must mark this extension
  18534. * as non-critical. When parsing extensions check that
  18535. * certificate was made in compliance with this. */
  18536. if (critical) {
  18537. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  18538. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_AKID if wanted");
  18539. ret = ASN_CRIT_EXT_E;
  18540. }
  18541. #endif
  18542. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  18543. ret = ASN_PARSE_E;
  18544. }
  18545. break;
  18546. /* Subject Key Identifier. */
  18547. case SUBJ_KEY_OID:
  18548. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  18549. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  18550. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18551. /* This check is added due to RFC 5280 section 4.2.1.2
  18552. * stating that conforming CA's must mark this extension
  18553. * as non-critical. When parsing extensions check that
  18554. * certificate was made in compliance with this. */
  18555. if (critical) {
  18556. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  18557. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18558. ret = ASN_CRIT_EXT_E;
  18559. }
  18560. #endif
  18561. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  18562. ret = ASN_PARSE_E;
  18563. }
  18564. break;
  18565. /* Certificate policies. */
  18566. case CERT_POLICY_OID:
  18567. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  18568. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  18569. #if defined(OPENSSL_EXTRA) || \
  18570. defined(OPENSSL_EXTRA_X509_SMALL)
  18571. cert->extCertPolicyCrit = critical ? 1 : 0;
  18572. #endif
  18573. #endif
  18574. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  18575. defined(WOLFSSL_QT)
  18576. if (DecodeCertPolicy(input, length, cert) < 0) {
  18577. ret = ASN_PARSE_E;
  18578. }
  18579. #else
  18580. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  18581. #endif
  18582. break;
  18583. /* Key usage. */
  18584. case KEY_USAGE_OID:
  18585. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  18586. cert->extKeyUsageCrit = critical ? 1 : 0;
  18587. if (DecodeKeyUsage(input, length, cert) < 0) {
  18588. ret = ASN_PARSE_E;
  18589. }
  18590. break;
  18591. /* Extended key usage. */
  18592. case EXT_KEY_USAGE_OID:
  18593. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  18594. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  18595. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  18596. ret = ASN_PARSE_E;
  18597. }
  18598. break;
  18599. #ifndef IGNORE_NAME_CONSTRAINTS
  18600. /* Name constraints. */
  18601. case NAME_CONS_OID:
  18602. #ifndef WOLFSSL_NO_ASN_STRICT
  18603. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  18604. "The name constraints extension,
  18605. which MUST be used only in a CA certificate" */
  18606. if (!cert->isCA) {
  18607. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  18608. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  18609. ret = ASN_NAME_INVALID_E;
  18610. }
  18611. #endif
  18612. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  18613. cert->extNameConstraintCrit = critical ? 1 : 0;
  18614. if (DecodeNameConstraints(input, length, cert) < 0) {
  18615. ret = ASN_PARSE_E;
  18616. }
  18617. break;
  18618. #endif /* IGNORE_NAME_CONSTRAINTS */
  18619. /* Inhibit anyPolicy. */
  18620. case INHIBIT_ANY_OID:
  18621. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  18622. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  18623. break;
  18624. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18625. /* Netscape's certificate type. */
  18626. case NETSCAPE_CT_OID:
  18627. if (DecodeNsCertType(input, (int)length, cert) < 0)
  18628. ret = ASN_PARSE_E;
  18629. break;
  18630. #endif
  18631. #ifdef HAVE_OCSP
  18632. /* OCSP no check. */
  18633. case OCSP_NOCHECK_OID:
  18634. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  18635. ret = GetASNNull(input, &idx, length);
  18636. if (ret != 0) {
  18637. ret = ASN_PARSE_E;
  18638. }
  18639. break;
  18640. #endif
  18641. case POLICY_CONST_OID:
  18642. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  18643. cert->extPolicyConstCrit = critical ? 1 : 0;
  18644. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  18645. return ASN_PARSE_E;
  18646. break;
  18647. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18648. case SUBJ_DIR_ATTR_OID:
  18649. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  18650. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  18651. return ASN_PARSE_E;
  18652. break;
  18653. #endif
  18654. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18655. case SUBJ_INFO_ACC_OID:
  18656. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  18657. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  18658. return ASN_PARSE_E;
  18659. break;
  18660. #endif
  18661. default:
  18662. if (isUnknownExt != NULL)
  18663. *isUnknownExt = 1;
  18664. #ifndef WOLFSSL_NO_ASN_STRICT
  18665. /* While it is a failure to not support critical extensions,
  18666. * still parse the certificate ignoring the unsupported
  18667. * extension to allow caller to accept it with the verify
  18668. * callback. */
  18669. if (critical) {
  18670. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  18671. ret = ASN_CRIT_EXT_E;
  18672. }
  18673. #endif
  18674. break;
  18675. }
  18676. return ret;
  18677. }
  18678. #ifdef WOLFSSL_ASN_TEMPLATE
  18679. /* ASN.1 template for extensions.
  18680. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18681. */
  18682. static const ASNItem certExtHdrASN[] = {
  18683. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  18684. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18685. };
  18686. enum {
  18687. CERTEXTHDRASN_IDX_EXTTAG = 0,
  18688. CERTEXTHDRASN_IDX_EXTSEQ
  18689. };
  18690. /* Number of items in ASN.1 template for extensions. */
  18691. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  18692. /* ASN.1 template for Extension.
  18693. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18694. */
  18695. static const ASNItem certExtASN[] = {
  18696. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18697. /* Extension object id */
  18698. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18699. /* critical - when true, must be parseable. */
  18700. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  18701. /* Data for extension - leave index at start of data. */
  18702. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  18703. };
  18704. enum {
  18705. CERTEXTASN_IDX_SEQ = 0,
  18706. CERTEXTASN_IDX_OID,
  18707. CERTEXTASN_IDX_CRIT,
  18708. CERTEXTASN_IDX_VAL
  18709. };
  18710. /* Number of items in ASN.1 template for Extension. */
  18711. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  18712. #endif
  18713. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  18714. && defined(HAVE_OID_DECODING)
  18715. int wc_SetUnknownExtCallback(DecodedCert* cert,
  18716. wc_UnknownExtCallback cb) {
  18717. if (cert == NULL) {
  18718. return BAD_FUNC_ARG;
  18719. }
  18720. cert->unknownExtCallback = cb;
  18721. return 0;
  18722. }
  18723. #endif
  18724. /*
  18725. * Processing the Certificate Extensions. This does not modify the current
  18726. * index. It is works starting with the recorded extensions pointer.
  18727. */
  18728. static int DecodeCertExtensions(DecodedCert* cert)
  18729. {
  18730. #ifndef WOLFSSL_ASN_TEMPLATE
  18731. int ret = 0;
  18732. word32 idx = 0;
  18733. word32 sz = (word32)cert->extensionsSz;
  18734. const byte* input = cert->extensions;
  18735. int length;
  18736. word32 oid;
  18737. byte critical = 0;
  18738. byte criticalFail = 0;
  18739. byte tag = 0;
  18740. WOLFSSL_ENTER("DecodeCertExtensions");
  18741. if (input == NULL || sz == 0)
  18742. return BAD_FUNC_ARG;
  18743. #ifdef WOLFSSL_CERT_REQ
  18744. if (!cert->isCSR)
  18745. #endif
  18746. { /* Not included in CSR */
  18747. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  18748. return ASN_PARSE_E;
  18749. }
  18750. if (tag != ASN_EXTENSIONS) {
  18751. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  18752. return ASN_PARSE_E;
  18753. }
  18754. if (GetLength(input, &idx, &length, sz) < 0) {
  18755. WOLFSSL_MSG("\tfail: invalid length");
  18756. return ASN_PARSE_E;
  18757. }
  18758. }
  18759. if (GetSequence(input, &idx, &length, sz) < 0) {
  18760. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  18761. return ASN_PARSE_E;
  18762. }
  18763. while (idx < (word32)sz) {
  18764. word32 localIdx;
  18765. if (GetSequence(input, &idx, &length, sz) < 0) {
  18766. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18767. return ASN_PARSE_E;
  18768. }
  18769. oid = 0;
  18770. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  18771. WOLFSSL_MSG("\tfail: OBJECT ID");
  18772. return ret;
  18773. }
  18774. /* check for critical flag */
  18775. critical = 0;
  18776. if ((idx + 1) > (word32)sz) {
  18777. WOLFSSL_MSG("\tfail: malformed buffer");
  18778. return BUFFER_E;
  18779. }
  18780. localIdx = idx;
  18781. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  18782. if (tag == ASN_BOOLEAN) {
  18783. ret = GetBoolean(input, &idx, sz);
  18784. if (ret < 0) {
  18785. WOLFSSL_MSG("\tfail: critical boolean");
  18786. return ret;
  18787. }
  18788. critical = (byte)ret;
  18789. }
  18790. }
  18791. /* process the extension based on the OID */
  18792. ret = GetOctetString(input, &idx, &length, sz);
  18793. if (ret < 0) {
  18794. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  18795. return ret;
  18796. }
  18797. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  18798. cert, NULL);
  18799. if (ret == ASN_CRIT_EXT_E) {
  18800. ret = 0;
  18801. criticalFail = 1;
  18802. }
  18803. if (ret < 0)
  18804. goto end;
  18805. idx += (word32)length;
  18806. }
  18807. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  18808. end:
  18809. return ret;
  18810. #else
  18811. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18812. ASNGetData dataExtsASN[certExtHdrASN_Length];
  18813. int ret = 0;
  18814. const byte* input = cert->extensions;
  18815. int sz = cert->extensionsSz;
  18816. word32 idx = 0;
  18817. int criticalRet = 0;
  18818. int offset = 0;
  18819. WOLFSSL_ENTER("DecodeCertExtensions");
  18820. if (input == NULL || sz == 0)
  18821. ret = BAD_FUNC_ARG;
  18822. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  18823. #ifdef WOLFSSL_CERT_REQ
  18824. if (cert->isCSR) {
  18825. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  18826. }
  18827. #endif
  18828. if (ret == 0) {
  18829. /* Clear dynamic data. */
  18830. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  18831. /* Parse extensions header. */
  18832. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  18833. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  18834. input, &idx, (word32)sz);
  18835. }
  18836. /* Parse each extension. */
  18837. while ((ret == 0) && (idx < (word32)sz)) {
  18838. byte critical = 0;
  18839. int isUnknownExt = 0;
  18840. /* Clear dynamic data. */
  18841. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18842. /* Ensure OID is an extension type. */
  18843. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18844. /* Set criticality variable. */
  18845. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18846. /* Parse extension wrapper. */
  18847. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18848. &idx, (word32)sz);
  18849. if (ret == 0) {
  18850. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  18851. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  18852. /* Decode the extension by type. */
  18853. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  18854. &isUnknownExt);
  18855. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  18856. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  18857. word16 decOid[MAX_OID_SZ];
  18858. word32 decOidSz = sizeof(decOid);
  18859. ret = DecodeObjectId(
  18860. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  18861. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  18862. decOid, &decOidSz);
  18863. if (ret != 0) {
  18864. /* Should never get here as the extension was successfully
  18865. * decoded earlier. Something might be corrupted. */
  18866. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  18867. WOLFSSL_ERROR(ret);
  18868. }
  18869. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  18870. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  18871. dataASN[CERTEXTASN_IDX_VAL].length);
  18872. }
  18873. #endif
  18874. (void)isUnknownExt;
  18875. /* Move index on to next extension. */
  18876. idx += length;
  18877. }
  18878. /* Don't fail criticality until all other extensions have been checked.
  18879. */
  18880. if (ret == ASN_CRIT_EXT_E) {
  18881. criticalRet = ASN_CRIT_EXT_E;
  18882. ret = 0;
  18883. }
  18884. }
  18885. if (ret == 0) {
  18886. /* Use criticality return. */
  18887. ret = criticalRet;
  18888. }
  18889. FREE_ASNGETDATA(dataASN, cert->heap);
  18890. return ret;
  18891. #endif
  18892. }
  18893. #ifdef WOLFSSL_ASN_TEMPLATE
  18894. #if defined(HAVE_RPK)
  18895. /* ASN template for a Raw Public Key certificate defined RFC7250. */
  18896. static const ASNItem RPKCertASN[] = {
  18897. /* SubjectPublicKeyInfo ::= SEQUENCE */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18898. /* algorithm AlgorithmIdentifier */
  18899. /* AlgorithmIdentifier ::= SEQUENCE */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18900. /* Algorithm OBJECT IDENTIFIER */
  18901. /* TBS_SPUBKEYINFO_ALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18902. /* parameters ANY defined by algorithm OPTIONAL */
  18903. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18904. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  18905. #ifdef WC_RSA_PSS
  18906. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18907. #endif
  18908. /* subjectPublicKey BIT STRING */
  18909. /* TBS_SPUBKEYINFO_PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18910. };
  18911. /* Number of items in ASN template for a RawPublicKey certificate. */
  18912. #define RPKCertASN_Length (sizeof(RPKCertASN) / sizeof(ASNItem))
  18913. enum {
  18914. RPKCERTASN_IDX_SPUBKEYINFO_SEQ = 0,
  18915. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_SEQ,
  18916. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID,
  18917. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_NULL,
  18918. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_CURVEID,
  18919. #ifdef WC_RSA_PSS
  18920. RPKCERTASN_IDX_SPUBKEYINFO_ALGO_P_SEQ,
  18921. #endif
  18922. RPKCERTASN_IDX_SPUBKEYINFO_PUBKEY,
  18923. };
  18924. #endif /* HAVE_RPK */
  18925. /* ASN template for an X509 certificate.
  18926. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18927. */
  18928. static const ASNItem x509CertASN[] = {
  18929. /* Certificate ::= SEQUENCE */
  18930. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18931. /* tbsCertificate TBSCertificate */
  18932. /* TBSCertificate ::= SEQUENCE */
  18933. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18934. /* version [0] EXPLICIT Version DEFAULT v1 */
  18935. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  18936. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  18937. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18938. /* serialNumber CertificateSerialNumber */
  18939. /* CertificateSerialNumber ::= INTEGER */
  18940. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18941. /* signature AlgorithmIdentifier */
  18942. /* AlgorithmIdentifier ::= SEQUENCE */
  18943. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18944. /* Algorithm OBJECT IDENTIFIER */
  18945. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18946. /* parameters ANY defined by algorithm OPTIONAL */
  18947. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18948. #ifdef WC_RSA_PSS
  18949. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18950. #endif
  18951. /* issuer Name */
  18952. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18953. /* validity Validity */
  18954. /* Validity ::= SEQUENCE */
  18955. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18956. /* notBefore Time */
  18957. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18958. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18959. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18960. /* notAfter Time */
  18961. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18962. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18963. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18964. /* subject Name */
  18965. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18966. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18967. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18968. /* algorithm AlgorithmIdentifier */
  18969. /* AlgorithmIdentifier ::= SEQUENCE */
  18970. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18971. /* Algorithm OBJECT IDENTIFIER */
  18972. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18973. /* parameters ANY defined by algorithm OPTIONAL */
  18974. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18975. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18976. #ifdef WC_RSA_PSS
  18977. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18978. #endif
  18979. /* subjectPublicKey BIT STRING */
  18980. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18981. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18982. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18983. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18984. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18985. /* extensions Extensions OPTIONAL */
  18986. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18987. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18988. /* signatureAlgorithm AlgorithmIdentifier */
  18989. /* AlgorithmIdentifier ::= SEQUENCE */
  18990. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18991. /* Algorithm OBJECT IDENTIFIER */
  18992. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18993. /* parameters ANY defined by algorithm OPTIONAL */
  18994. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18995. #ifdef WC_RSA_PSS
  18996. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18997. #endif
  18998. /* signature BIT STRING */
  18999. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19000. };
  19001. enum {
  19002. X509CERTASN_IDX_SEQ = 0,
  19003. X509CERTASN_IDX_TBS_SEQ,
  19004. X509CERTASN_IDX_TBS_VER,
  19005. X509CERTASN_IDX_TBS_VER_INT,
  19006. X509CERTASN_IDX_TBS_SERIAL,
  19007. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  19008. X509CERTASN_IDX_TBS_ALGOID_OID,
  19009. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  19010. #ifdef WC_RSA_PSS
  19011. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  19012. #endif
  19013. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  19014. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  19015. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  19016. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  19017. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  19018. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  19019. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  19020. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  19021. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  19022. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  19023. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  19024. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  19025. #ifdef WC_RSA_PSS
  19026. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  19027. #endif
  19028. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  19029. X509CERTASN_IDX_TBS_ISSUERUID,
  19030. X509CERTASN_IDX_TBS_SUBJECTUID,
  19031. X509CERTASN_IDX_TBS_EXT,
  19032. X509CERTASN_IDX_TBS_EXT_SEQ,
  19033. X509CERTASN_IDX_SIGALGO_SEQ,
  19034. X509CERTASN_IDX_SIGALGO_OID,
  19035. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  19036. #ifdef WC_RSA_PSS
  19037. X509CERTASN_IDX_SIGALGO_PARAMS,
  19038. #endif
  19039. X509CERTASN_IDX_SIGNATURE,
  19040. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  19041. };
  19042. /* Number of items in ASN template for an X509 certificate. */
  19043. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  19044. /* Check the data data.
  19045. *
  19046. * @param [in] dataASN ASN template dynamic data item.
  19047. * @param [in] dataType BEFORE or AFTER date.
  19048. * @return 0 on success.
  19049. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  19050. * @return ASN_DATE_SZ_E when time data is not supported.
  19051. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19052. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19053. */
  19054. static int CheckDate(ASNGetData *dataASN, int dateType)
  19055. {
  19056. int ret = 0;
  19057. /* Check BER tag is valid. */
  19058. if ((dataASN->tag != ASN_UTC_TIME) &&
  19059. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  19060. ret = ASN_TIME_E;
  19061. }
  19062. /* Check date length is valid. */
  19063. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  19064. (dataASN->length < MIN_DATE_SIZE))) {
  19065. ret = ASN_DATE_SZ_E;
  19066. }
  19067. #ifndef NO_ASN_TIME_CHECK
  19068. /* Check date is a valid string and BEFORE or AFTER now. */
  19069. if ((ret == 0) &&
  19070. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  19071. if (dateType == BEFORE) {
  19072. ret = ASN_BEFORE_DATE_E;
  19073. }
  19074. else {
  19075. ret = ASN_AFTER_DATE_E;
  19076. }
  19077. }
  19078. #endif
  19079. (void)dateType;
  19080. return ret;
  19081. }
  19082. /* Decode a certificate. Internal/non-public API.
  19083. *
  19084. * @param [in] cert Certificate object.
  19085. * @param [in] verify Whether to verify dates before and after now.
  19086. * @param [out] criticalExt Critical extension return code.
  19087. * @param [out] badDateRet Bad date return code.
  19088. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  19089. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  19090. * @return 0 on success.
  19091. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19092. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  19093. * @return ASN_DATE_SZ_E when time data is not supported.
  19094. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19095. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19096. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19097. * is invalid.
  19098. * @return BUFFER_E when data in buffer is too small.
  19099. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19100. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  19101. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19102. * non-zero length.
  19103. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19104. */
  19105. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  19106. int* badDateRet, int stopAtPubKey,
  19107. int stopAfterPubKey)
  19108. {
  19109. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19110. int ret = 0;
  19111. int badDate = 0;
  19112. byte version;
  19113. word32 idx;
  19114. word32 serialSz;
  19115. const unsigned char* issuer = NULL;
  19116. word32 issuerSz = 0;
  19117. const unsigned char* subject = NULL;
  19118. word32 subjectSz = 0;
  19119. word32 pubKeyOffset = 0;
  19120. word32 pubKeyEnd = 0;
  19121. int done = 0;
  19122. #if defined(HAVE_RPK)
  19123. /* try to parse the cert as Raw Public Key cert */
  19124. DECL_ASNGETDATA(RPKdataASN, RPKCertASN_Length);
  19125. CALLOC_ASNGETDATA(RPKdataASN, RPKCertASN_Length, ret, cert->heap);
  19126. GetASN_OID(&RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID],
  19127. oidKeyType);
  19128. GetASN_OID(&RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_CURVEID],
  19129. oidCurveType);
  19130. ret = GetASN_Items(RPKCertASN, RPKdataASN, RPKCertASN_Length, 1,
  19131. cert->source, &cert->srcIdx, cert->maxIdx);
  19132. if (ret == 0) {
  19133. cert->keyOID =
  19134. RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  19135. /* Parse the public key. */
  19136. pubKeyOffset = RPKdataASN[RPKCERTASN_IDX_SPUBKEYINFO_SEQ].offset;
  19137. pubKeyEnd = cert->maxIdx;
  19138. ret = GetCertKey(cert, cert->source, &pubKeyOffset, pubKeyEnd);
  19139. if (ret == 0) {
  19140. WOLFSSL_MSG("Raw Public Key certificate found and parsed");
  19141. cert->isRPK = 1;
  19142. }
  19143. }
  19144. /* Dispose of memory before allocating for extension decoding. */
  19145. FREE_ASNGETDATA(RPKdataASN, cert->heap);
  19146. if (ret == 0) {
  19147. return ret;
  19148. }
  19149. else {
  19150. ret = 0; /* proceed to the original x509 parsing */
  19151. }
  19152. #endif /* HAVE_RPK */
  19153. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  19154. if (ret == 0) {
  19155. version = 0;
  19156. serialSz = EXTERNAL_SERIAL_SIZE;
  19157. /* Get the version and put the serial number into the buffer. */
  19158. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  19159. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  19160. &serialSz);
  19161. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  19162. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19163. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19164. oidKeyType);
  19165. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19166. oidCurveType);
  19167. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19168. /* Parse the X509 certificate. */
  19169. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  19170. cert->source, &cert->srcIdx, cert->maxIdx);
  19171. #ifdef WOLFSSL_CLANG_TIDY
  19172. /* work around clang-tidy false positive re cert->source. */
  19173. if ((ret == 0) && (cert->source == NULL)) {
  19174. ret = ASN_PARSE_E;
  19175. }
  19176. #endif
  19177. }
  19178. /* Check version is valid/supported - can't be negative. */
  19179. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  19180. WOLFSSL_MSG("Unexpected certificate version");
  19181. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19182. ret = ASN_PARSE_E;
  19183. }
  19184. if (ret == 0) {
  19185. int i;
  19186. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  19187. /* Set fields extracted from data. */
  19188. cert->version = version;
  19189. cert->serialSz = (int)serialSz;
  19190. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  19191. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  19192. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  19193. /* No bad date error - don't always care. */
  19194. badDate = 0;
  19195. /* Find the item with the BEFORE date and check it. */
  19196. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  19197. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  19198. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  19199. if ((CheckDate(&dataASN[i], BEFORE) < 0) && (verify != NO_VERIFY) &&
  19200. (verify != VERIFY_SKIP_DATE)) {
  19201. badDate = ASN_BEFORE_DATE_E;
  19202. }
  19203. /* Store reference to BEFOREdate. */
  19204. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  19205. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  19206. /* Find the item with the AFTER date and check it. */
  19207. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  19208. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  19209. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  19210. if ((CheckDate(&dataASN[i], AFTER) < 0) && (verify != NO_VERIFY) &&
  19211. (verify != VERIFY_SKIP_DATE)) {
  19212. badDate = ASN_AFTER_DATE_E;
  19213. }
  19214. /* Store reference to AFTER date. */
  19215. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  19216. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  19217. /* Get the issuer name. */
  19218. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  19219. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  19220. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  19221. /* Get the subject name. */
  19222. subject = cert->source +
  19223. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  19224. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  19225. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  19226. }
  19227. if ((ret == 0) && stopAtPubKey) {
  19228. /* Return any bad date error through badDateRet and return offset of
  19229. * subjectPublicKeyInfo.
  19230. */
  19231. if (badDateRet != NULL) {
  19232. *badDateRet = badDate;
  19233. }
  19234. done = 1;
  19235. }
  19236. if ((ret == 0) && (!done)) {
  19237. /* Store the signature information. */
  19238. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  19239. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  19240. &cert->signature, &cert->sigLength);
  19241. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  19242. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  19243. != cert->signatureOID) {
  19244. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  19245. ret = ASN_SIG_OID_E;
  19246. }
  19247. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  19248. else if (IsSigAlgoECC(cert->signatureOID)) {
  19249. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  19250. #ifdef WC_RSA_PSS
  19251. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  19252. #endif
  19253. ) {
  19254. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19255. ret = ASN_PARSE_E;
  19256. }
  19257. }
  19258. #ifdef WC_RSA_PSS
  19259. /* Check parameters starting with a SEQUENCE. */
  19260. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19261. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19262. word32 sigAlgParamsSz = 0;
  19263. /* Parameters only with RSA PSS. */
  19264. if (oid != CTC_RSASSAPSS) {
  19265. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19266. ret = ASN_PARSE_E;
  19267. }
  19268. if (ret == 0) {
  19269. const byte* tbsParams;
  19270. word32 tbsParamsSz;
  19271. const byte* sigAlgParams;
  19272. /* Check RSA PSS parameters are the same. */
  19273. tbsParams =
  19274. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19275. cert->source);
  19276. tbsParamsSz =
  19277. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19278. cert->source);
  19279. sigAlgParams =
  19280. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19281. cert->source);
  19282. sigAlgParamsSz =
  19283. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19284. cert->source);
  19285. if ((tbsParamsSz != sigAlgParamsSz) ||
  19286. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  19287. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  19288. ret = ASN_PARSE_E;
  19289. }
  19290. }
  19291. if (ret == 0) {
  19292. /* Store parameters for use in signature verification. */
  19293. cert->sigParamsIndex =
  19294. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  19295. cert->sigParamsLength = sigAlgParamsSz;
  19296. }
  19297. }
  19298. #endif
  19299. }
  19300. if ((ret == 0) && (!done)) {
  19301. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  19302. if (stopAfterPubKey) {
  19303. /* Return any bad date error through badDateRed and return offset
  19304. * after subjectPublicKeyInfo.
  19305. */
  19306. if (badDateRet != NULL) {
  19307. *badDateRet = badDate;
  19308. }
  19309. done = 1;
  19310. }
  19311. }
  19312. if ((ret == 0) && (!done) &&
  19313. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  19314. #ifndef ALLOW_V1_EXTENSIONS
  19315. /* Certificate extensions were only defined in version 2. */
  19316. if (cert->version < 2) {
  19317. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  19318. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  19319. ret = ASN_VERSION_E;
  19320. }
  19321. #endif
  19322. if (ret == 0) {
  19323. /* Save references to extension data. */
  19324. cert->extensions = GetASNItem_Addr(
  19325. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  19326. cert->extensionsSz = (int)GetASNItem_Length(
  19327. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  19328. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  19329. /* Advance past extensions. */
  19330. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  19331. }
  19332. }
  19333. /* Dispose of memory before allocating for extension decoding. */
  19334. FREE_ASNGETDATA(dataASN, cert->heap);
  19335. if ((ret == 0) && (issuer != NULL)) {
  19336. idx = 0;
  19337. /* Put issuer into cert and calculate hash. */
  19338. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  19339. &idx, issuerSz);
  19340. }
  19341. if ((ret == 0) && (subject != NULL)) {
  19342. idx = 0;
  19343. /* Put subject into cert and calculate hash. */
  19344. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19345. subject, &idx, subjectSz);
  19346. }
  19347. if (ret == 0) {
  19348. /* Determine if self signed by comparing issuer and subject hashes. */
  19349. #ifdef WOLFSSL_CERT_REQ
  19350. if (cert->isCSR) {
  19351. cert->selfSigned = 1;
  19352. }
  19353. else
  19354. #endif
  19355. {
  19356. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  19357. KEYID_SIZE) == 0);
  19358. }
  19359. if (stopAtPubKey) {
  19360. ret = (int)pubKeyOffset;
  19361. }
  19362. }
  19363. if ((ret == 0) && (!stopAtPubKey)) {
  19364. /* Parse the public key. */
  19365. idx = pubKeyOffset;
  19366. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  19367. }
  19368. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  19369. (cert->extensions != NULL)) {
  19370. /* Decode the extension data starting at [3]. */
  19371. ret = DecodeCertExtensions(cert);
  19372. if (criticalExt != NULL) {
  19373. if (ret == ASN_CRIT_EXT_E) {
  19374. /* Return critical extension not recognized. */
  19375. *criticalExt = ret;
  19376. ret = 0;
  19377. }
  19378. else {
  19379. /* No critical extension error. */
  19380. *criticalExt = 0;
  19381. }
  19382. }
  19383. }
  19384. if ((ret == 0) && (!done) && (badDate != 0)) {
  19385. /* Parsed whole certificate fine but return any date errors. */
  19386. ret = badDate;
  19387. }
  19388. return ret;
  19389. }
  19390. /* Decode BER/DER data into certificate object.
  19391. *
  19392. * BER/DER data information held in source, srcIdx and maxIdx fields of
  19393. * certificate object.
  19394. *
  19395. * @param [in] cert Decoded certificate object.
  19396. * @param [in] verify Whether to find CA and verify certificate.
  19397. * @param [in] criticalExt Any error for critical extensions not recognized.
  19398. * @return 0 on success.
  19399. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19400. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  19401. * @return ASN_DATE_SZ_E when time data is not supported.
  19402. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19403. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19404. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19405. * is invalid.
  19406. * @return BUFFER_E when data in buffer is too small.
  19407. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19408. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  19409. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19410. * non-zero length.
  19411. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19412. */
  19413. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  19414. {
  19415. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  19416. }
  19417. #ifdef WOLFSSL_CERT_REQ
  19418. /* ASN.1 template for certificate request Attribute.
  19419. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  19420. */
  19421. static const ASNItem reqAttrASN[] = {
  19422. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19423. /* type */
  19424. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  19425. /* values */
  19426. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  19427. };
  19428. enum {
  19429. REQATTRASN_IDX_SEQ = 0,
  19430. REQATTRASN_IDX_TYPE,
  19431. REQATTRASN_IDX_VALS
  19432. };
  19433. /* Number of items in ASN.1 template for certificate request Attribute. */
  19434. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  19435. /* ASN.1 template for a string choice. */
  19436. static const ASNItem strAttrASN[] = {
  19437. { 0, 0, 0, 0, 0 },
  19438. };
  19439. enum {
  19440. STRATTRASN_IDX_STR = 0
  19441. };
  19442. /* Number of items in ASN.1 template for a string choice. */
  19443. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  19444. /* ASN.1 choices for types for a string in an attribute. */
  19445. static const byte strAttrChoice[] = {
  19446. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  19447. };
  19448. /* Decode a certificate request attribute's value.
  19449. *
  19450. * @param [in] cert Certificate request object.
  19451. * @param [out] criticalExt Critical extension return code.
  19452. * @param [in] oid OID describing which attribute was found.
  19453. * @param [in] aIdx Index into certificate source to start parsing.
  19454. * @param [in] input Attribute value data.
  19455. * @param [in] maxIdx Maximum index to parse to.
  19456. * @return 0 on success.
  19457. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19458. * is invalid.
  19459. */
  19460. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  19461. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  19462. {
  19463. int ret = 0;
  19464. word32 idx = 0;
  19465. ASNGetData strDataASN[strAttrASN_Length];
  19466. switch (oid) {
  19467. case PKCS9_CONTENT_TYPE_OID:
  19468. /* Clear dynamic data and specify choices acceptable. */
  19469. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19470. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19471. /* Parse a string. */
  19472. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19473. 1, input, &idx, maxIdx);
  19474. if (ret == 0) {
  19475. /* Store references to password data. */
  19476. cert->contentType =
  19477. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19478. cert->contentTypeLen =
  19479. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  19480. }
  19481. break;
  19482. /* A password by which the entity may request certificate revocation.
  19483. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  19484. */
  19485. case CHALLENGE_PASSWORD_OID:
  19486. /* Clear dynamic data and specify choices acceptable. */
  19487. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19488. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19489. /* Parse a string. */
  19490. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19491. 1, input, &idx, maxIdx);
  19492. if (ret == 0) {
  19493. /* Store references to password data. */
  19494. cert->cPwd =
  19495. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19496. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19497. data.ref.length;
  19498. }
  19499. break;
  19500. /* Requested serial number to issue with.
  19501. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  19502. * (References: ISO/IEC 9594-6:1997)
  19503. */
  19504. case SERIAL_NUMBER_OID:
  19505. /* Clear dynamic data and specify choices acceptable. */
  19506. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19507. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19508. /* Parse a string. */
  19509. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19510. 1, input, &idx, maxIdx);
  19511. if (ret == 0) {
  19512. /* Store references to serial number. */
  19513. cert->sNum =
  19514. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19515. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19516. data.ref.length;
  19517. /* Store serial number if small enough. */
  19518. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19519. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  19520. cert->serialSz = cert->sNumLen;
  19521. }
  19522. }
  19523. break;
  19524. case UNSTRUCTURED_NAME_OID:
  19525. /* Clear dynamic data and specify choices acceptable. */
  19526. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19527. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19528. /* Parse a string. */
  19529. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19530. 1, input, &idx, maxIdx);
  19531. if (ret == 0) {
  19532. /* Store references to unstructured name. */
  19533. cert->unstructuredName =
  19534. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19535. cert->unstructuredNameLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19536. data.ref.length;
  19537. }
  19538. break;
  19539. /* Certificate extensions to be included in generated certificate.
  19540. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  19541. */
  19542. case EXTENSION_REQUEST_OID:
  19543. /* Store references to all extensions. */
  19544. cert->extensions = input;
  19545. cert->extensionsSz = (int)maxIdx;
  19546. cert->extensionsIdx = aIdx;
  19547. /* Decode and validate extensions. */
  19548. ret = DecodeCertExtensions(cert);
  19549. if (ret == ASN_CRIT_EXT_E) {
  19550. /* Return critical extension not recognized. */
  19551. *criticalExt = ret;
  19552. ret = 0;
  19553. }
  19554. else {
  19555. /* No critical extension error. */
  19556. *criticalExt = 0;
  19557. }
  19558. break;
  19559. default:
  19560. ret = ASN_PARSE_E;
  19561. break;
  19562. }
  19563. return ret;
  19564. }
  19565. /* Decode attributes of a BER encoded certificate request.
  19566. *
  19567. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19568. *
  19569. * Outer sequence has been removed.
  19570. *
  19571. * @param [in] cert Certificate request object.
  19572. * @param [out] criticalExt Critical extension return code.
  19573. * @param [in] idx Index into certificate source to start parsing.
  19574. * @param [in] maxIdx Maximum index to parse to.
  19575. * @return 0 on success.
  19576. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19577. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19578. * is invalid.
  19579. * @return BUFFER_E when data in buffer is too small.
  19580. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19581. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19582. * non-zero length.
  19583. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19584. */
  19585. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  19586. word32 idx, word32 maxIdx)
  19587. {
  19588. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  19589. int ret = 0;
  19590. WOLFSSL_ENTER("DecodeCertReqAttributes");
  19591. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  19592. /* Parse each attribute until all data used up. */
  19593. while ((ret == 0) && (idx < maxIdx)) {
  19594. /* Clear dynamic data. */
  19595. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  19596. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  19597. /* Parse an attribute. */
  19598. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  19599. cert->source, &idx, maxIdx);
  19600. /* idx is now at end of attribute data. */
  19601. if (ret == 0) {
  19602. ret = DecodeCertReqAttrValue(cert, criticalExt,
  19603. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  19604. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  19605. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  19606. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  19607. }
  19608. }
  19609. FREE_ASNGETDATA(dataASN, cert->heap);
  19610. return ret;
  19611. }
  19612. /* ASN.1 template for a certificate request.
  19613. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  19614. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  19615. */
  19616. static const ASNItem certReqASN[] = {
  19617. /* CertificationRequest */
  19618. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19619. /* CertificationRequestInfo */
  19620. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19621. /* version INTEGER { v1(0), v2(1), v3(2) */
  19622. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  19623. /* subject Name */
  19624. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  19625. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  19626. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19627. /* algorithm AlgorithmIdentifier */
  19628. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  19629. /* Algorithm OBJECT IDENTIFIER */
  19630. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  19631. /* parameters ANY defined by algorithm OPTIONAL */
  19632. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  19633. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  19634. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  19635. /* subjectPublicKey BIT STRING */
  19636. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  19637. /* attributes [0] Attributes */
  19638. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  19639. /* signatureAlgorithm AlgorithmIdentifier */
  19640. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19641. /* Algorithm OBJECT IDENTIFIER */
  19642. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  19643. /* parameters ANY defined by algorithm OPTIONAL */
  19644. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  19645. /* signature BIT STRING */
  19646. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19647. };
  19648. enum {
  19649. CERTREQASN_IDX_SEQ = 0,
  19650. CERTREQASN_IDX_INFO_SEQ,
  19651. CERTREQASN_IDX_INFO_VER,
  19652. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  19653. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  19654. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  19655. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  19656. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  19657. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  19658. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  19659. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  19660. CERTREQASN_IDX_INFO_ATTRS,
  19661. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  19662. CERTREQASN_IDX_INFO_SIGALGO_OID,
  19663. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  19664. CERTREQASN_IDX_INFO_SIGNATURE
  19665. };
  19666. /* Number of items in ASN.1 template for a certificate request. */
  19667. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  19668. /* Parse BER encoded certificate request.
  19669. *
  19670. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19671. *
  19672. * @param [in] cert Certificate request object.
  19673. * @param [out] criticalExt Critical extension return code.
  19674. * @return 0 on success.
  19675. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19676. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19677. * is invalid.
  19678. * @return BUFFER_E when data in buffer is too small.
  19679. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19680. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19681. * non-zero length.
  19682. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19683. * @return MEMORY_E on dynamic memory allocation failure.
  19684. */
  19685. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  19686. {
  19687. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  19688. int ret = 0;
  19689. byte version;
  19690. word32 idx;
  19691. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  19692. if (ret == 0) {
  19693. /* Default version is 0. */
  19694. version = 0;
  19695. /* Set version var and OID types to expect. */
  19696. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  19697. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19698. oidKeyType);
  19699. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19700. oidCurveType);
  19701. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19702. /* Parse a certificate request. */
  19703. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  19704. cert->source, &cert->srcIdx, cert->maxIdx);
  19705. }
  19706. /* Check version is valid/supported - can't be negative. */
  19707. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  19708. WOLFSSL_MSG("Unexpected certificate request version");
  19709. ret = ASN_PARSE_E;
  19710. }
  19711. if (ret == 0) {
  19712. /* Set fields of certificate request. */
  19713. cert->version = version;
  19714. cert->signatureOID =
  19715. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19716. cert->keyOID =
  19717. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  19718. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  19719. /* Parse the subject name. */
  19720. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  19721. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19722. cert->source, &idx,
  19723. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  19724. }
  19725. if (ret == 0) {
  19726. /* Parse the certificate request Attributes. */
  19727. ret = DecodeCertReqAttributes(cert, criticalExt,
  19728. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  19729. cert->source),
  19730. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  19731. }
  19732. if (ret == 0) {
  19733. /* Parse the certificate request's key. */
  19734. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  19735. ret = GetCertKey(cert, cert->source, &idx,
  19736. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  19737. }
  19738. if (ret == 0) {
  19739. /* Store references to signature. */
  19740. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  19741. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  19742. &cert->signature, &cert->sigLength);
  19743. }
  19744. FREE_ASNGETDATA(dataASN, cert->heap);
  19745. return ret;
  19746. }
  19747. #endif /* WOLFSSL_CERT_REQ */
  19748. #endif
  19749. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19750. {
  19751. int ret;
  19752. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19753. defined(WOLFSSL_DYN_CERT)
  19754. char* ptr;
  19755. #endif
  19756. ret = ParseCertRelative(cert, type, verify, cm);
  19757. if (ret < 0)
  19758. return ret;
  19759. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19760. defined(WOLFSSL_DYN_CERT)
  19761. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defined */
  19762. if (cert->subjectCNLen > 0) {
  19763. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  19764. DYNAMIC_TYPE_SUBJECT_CN);
  19765. if (ptr == NULL)
  19766. return MEMORY_E;
  19767. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  19768. ptr[cert->subjectCNLen] = '\0';
  19769. cert->subjectCN = ptr;
  19770. cert->subjectCNStored = 1;
  19771. }
  19772. #endif
  19773. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19774. defined(WOLFSSL_DYN_CERT)
  19775. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  19776. if ((cert->keyOID == RSAk
  19777. #ifdef WC_RSA_PSS
  19778. || cert->keyOID == RSAPSSk
  19779. #endif
  19780. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  19781. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  19782. DYNAMIC_TYPE_PUBLIC_KEY);
  19783. if (ptr == NULL)
  19784. return MEMORY_E;
  19785. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  19786. cert->publicKey = (byte *)ptr;
  19787. cert->pubKeyStored = 1;
  19788. }
  19789. #endif
  19790. return ret;
  19791. }
  19792. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19793. {
  19794. return ParseCert(cert, type, verify, cm);
  19795. }
  19796. #ifdef WOLFCRYPT_ONLY
  19797. /* dummy functions, not using wolfSSL so don't need actual ones */
  19798. Signer* GetCA(void* signers, byte* hash);
  19799. Signer* GetCA(void* signers, byte* hash)
  19800. {
  19801. (void)hash;
  19802. return (Signer*)signers;
  19803. }
  19804. #ifndef NO_SKID
  19805. Signer* GetCAByName(void* signers, byte* hash);
  19806. Signer* GetCAByName(void* signers, byte* hash)
  19807. {
  19808. (void)hash;
  19809. return (Signer*)signers;
  19810. }
  19811. #endif /* NO_SKID */
  19812. #ifdef WOLFSSL_AKID_NAME
  19813. Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
  19814. const byte* serial, word32 serialSz);
  19815. Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
  19816. const byte* serial, word32 serialSz)
  19817. {
  19818. (void)issuer;
  19819. (void)issuerSz;
  19820. (void)serial;
  19821. (void)serialSz;
  19822. return (Signer*)vp;
  19823. }
  19824. #endif
  19825. #endif /* WOLFCRYPT_ONLY */
  19826. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  19827. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  19828. {
  19829. Signer* ca = NULL;
  19830. if (cert->extSubjKeyIdSet)
  19831. ca = GetCA(cm, cert->extSubjKeyId);
  19832. if (ca == NULL)
  19833. ca = GetCAByName(cm, cert->subjectHash);
  19834. if (ca) {
  19835. if ((ca->pubKeySize == cert->pubKeySize) &&
  19836. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  19837. return ca;
  19838. }
  19839. }
  19840. return NULL;
  19841. }
  19842. #endif
  19843. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  19844. #ifdef WOLFSSL_ASN_TEMPLATE
  19845. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  19846. *
  19847. * @param [in] input Input data.
  19848. * @param [in] maxIdx Maximum index for data.
  19849. * @param [in] sigOID Signature OID for determining hash algorithm.
  19850. * @param [out] hash Hash of AKI.
  19851. * @param [out] set Whether the hash buffer was set.
  19852. * @param [in] heap Dynamic memory allocation hint.
  19853. * @return 0 on success.
  19854. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19855. * is invalid.
  19856. * @return MEMORY_E on dynamic memory allocation failure.
  19857. */
  19858. static int GetAKIHash(const byte* input, word32 maxIdx, word32 sigOID,
  19859. byte* hash, int* set, void* heap)
  19860. {
  19861. /* AKI and Certificate Extension ASN.1 templates are the same length. */
  19862. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  19863. int ret = 0;
  19864. word32 idx = 0;
  19865. word32 extEndIdx;
  19866. byte* extData;
  19867. word32 extDataSz;
  19868. byte critical;
  19869. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  19870. (void)heap;
  19871. extEndIdx = idx + maxIdx;
  19872. /* Step through each extension looking for AKI. */
  19873. while ((ret == 0) && (idx < extEndIdx)) {
  19874. /* Clear dynamic data and check for certificate extension type OIDs. */
  19875. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  19876. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  19877. /* Set criticality variable. */
  19878. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  19879. /* Parse an extension. */
  19880. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  19881. &idx, extEndIdx);
  19882. if (ret == 0) {
  19883. /* Get reference to extension data and move index on past this
  19884. * extension. */
  19885. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  19886. idx += extDataSz;
  19887. /* Check whether we have the AKI extension. */
  19888. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  19889. /* Clear dynamic data. */
  19890. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  19891. /* Start parsing extension data from the start. */
  19892. idx = 0;
  19893. /* Parse AKI extension data. */
  19894. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  19895. 1, extData, &idx, extDataSz);
  19896. if ((ret == 0) &&
  19897. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  19898. != NULL)) {
  19899. /* We parsed successfully and have data. */
  19900. *set = 1;
  19901. /* Get the hash or hash of the hash if wrong size. */
  19902. ret = GetHashId(
  19903. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  19904. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  19905. hash, HashIdAlg(sigOID));
  19906. }
  19907. break;
  19908. }
  19909. }
  19910. }
  19911. FREE_ASNGETDATA(dataASN, heap);
  19912. return ret;
  19913. }
  19914. #endif
  19915. /* Only quick step through the certificate to find fields that are then used
  19916. * in certificate signature verification.
  19917. * Must use the signature OID from the signed part of the certificate.
  19918. * Works also on certificate signing requests.
  19919. *
  19920. * This is only for minimizing dynamic memory usage during TLS certificate
  19921. * chain processing.
  19922. * Doesn't support:
  19923. * OCSP Only: alt lookup using subject and pub key w/o sig check
  19924. */
  19925. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  19926. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  19927. {
  19928. #ifndef WOLFSSL_ASN_TEMPLATE
  19929. #ifndef WOLFSSL_SMALL_STACK
  19930. SignatureCtx sigCtx[1];
  19931. #else
  19932. SignatureCtx* sigCtx;
  19933. #endif
  19934. byte hash[KEYID_SIZE];
  19935. Signer* ca = NULL;
  19936. word32 idx = 0;
  19937. int len;
  19938. word32 tbsCertIdx = 0;
  19939. word32 sigIndex = 0;
  19940. word32 signatureOID = 0;
  19941. word32 oid = 0;
  19942. word32 issuerIdx = 0;
  19943. word32 issuerSz = 0;
  19944. #ifndef NO_SKID
  19945. int extLen = 0;
  19946. word32 extIdx = 0;
  19947. word32 extEndIdx = 0;
  19948. int extAuthKeyIdSet = 0;
  19949. #endif
  19950. int ret = 0;
  19951. word32 localIdx;
  19952. byte tag;
  19953. const byte* sigParams = NULL;
  19954. word32 sigParamsSz = 0;
  19955. if (cert == NULL) {
  19956. return BAD_FUNC_ARG;
  19957. }
  19958. #ifdef WOLFSSL_SMALL_STACK
  19959. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  19960. if (sigCtx == NULL)
  19961. return MEMORY_E;
  19962. #endif
  19963. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19964. /* Certificate SEQUENCE */
  19965. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19966. ret = ASN_PARSE_E;
  19967. if (ret == 0) {
  19968. tbsCertIdx = idx;
  19969. /* TBSCertificate SEQUENCE */
  19970. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19971. ret = ASN_PARSE_E;
  19972. }
  19973. if (ret == 0) {
  19974. sigIndex = len + idx;
  19975. if ((idx + 1) > certSz)
  19976. ret = BUFFER_E;
  19977. }
  19978. if (ret == 0) {
  19979. /* version - optional */
  19980. localIdx = idx;
  19981. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19982. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19983. idx++;
  19984. if (GetLength(cert, &idx, &len, certSz) < 0)
  19985. ret = ASN_PARSE_E;
  19986. idx += len;
  19987. }
  19988. }
  19989. }
  19990. if (ret == 0) {
  19991. /* serialNumber */
  19992. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19993. ret = ASN_PARSE_E;
  19994. }
  19995. if (ret == 0) {
  19996. idx += len;
  19997. /* signature */
  19998. if (!req) {
  19999. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  20000. ret = ASN_PARSE_E;
  20001. #ifdef WC_RSA_PSS
  20002. else if (signatureOID == CTC_RSASSAPSS) {
  20003. int start = idx;
  20004. sigParams = cert + idx;
  20005. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20006. ret = ASN_PARSE_E;
  20007. if (ret == 0) {
  20008. idx += len;
  20009. sigParamsSz = idx - start;
  20010. }
  20011. }
  20012. #endif
  20013. }
  20014. }
  20015. if (ret == 0) {
  20016. issuerIdx = idx;
  20017. /* issuer for cert or subject for csr */
  20018. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20019. ret = ASN_PARSE_E;
  20020. }
  20021. if (ret == 0) {
  20022. issuerSz = len + idx - issuerIdx;
  20023. }
  20024. #ifndef NO_SKID
  20025. if (!req && ret == 0) {
  20026. idx += len;
  20027. /* validity */
  20028. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20029. ret = ASN_PARSE_E;
  20030. }
  20031. if (!req && ret == 0) {
  20032. idx += len;
  20033. /* subject */
  20034. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20035. ret = ASN_PARSE_E;
  20036. }
  20037. if (ret == 0) {
  20038. idx += len;
  20039. /* subjectPublicKeyInfo */
  20040. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20041. ret = ASN_PARSE_E;
  20042. }
  20043. if (req && ret == 0) {
  20044. idx += len;
  20045. /* attributes */
  20046. if (GetASNHeader_ex(cert,
  20047. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  20048. &len, certSz, 1) < 0)
  20049. ret = ASN_PARSE_E;
  20050. }
  20051. if (!req) {
  20052. if (ret == 0) {
  20053. idx += len;
  20054. if ((idx + 1) > certSz)
  20055. ret = BUFFER_E;
  20056. }
  20057. if (ret == 0) {
  20058. /* issuerUniqueID - optional */
  20059. localIdx = idx;
  20060. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  20061. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  20062. idx++;
  20063. if (GetLength(cert, &idx, &len, certSz) < 0)
  20064. ret = ASN_PARSE_E;
  20065. idx += len;
  20066. }
  20067. }
  20068. }
  20069. if (ret == 0) {
  20070. if ((idx + 1) > certSz)
  20071. ret = BUFFER_E;
  20072. }
  20073. if (ret == 0) {
  20074. /* subjectUniqueID - optional */
  20075. localIdx = idx;
  20076. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  20077. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  20078. idx++;
  20079. if (GetLength(cert, &idx, &len, certSz) < 0)
  20080. ret = ASN_PARSE_E;
  20081. idx += len;
  20082. }
  20083. }
  20084. }
  20085. if (ret == 0) {
  20086. if ((idx + 1) > certSz)
  20087. ret = BUFFER_E;
  20088. }
  20089. /* extensions - optional */
  20090. localIdx = idx;
  20091. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  20092. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  20093. idx++;
  20094. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  20095. ret = ASN_PARSE_E;
  20096. if (ret == 0) {
  20097. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  20098. ret = ASN_PARSE_E;
  20099. }
  20100. if (ret == 0) {
  20101. extEndIdx = idx + extLen;
  20102. /* Check each extension for the ones we want. */
  20103. while (ret == 0 && idx < extEndIdx) {
  20104. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20105. ret = ASN_PARSE_E;
  20106. if (ret == 0) {
  20107. extIdx = idx;
  20108. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  20109. certSz) < 0) {
  20110. ret = ASN_PARSE_E;
  20111. }
  20112. if (ret == 0) {
  20113. if ((extIdx + 1) > certSz)
  20114. ret = BUFFER_E;
  20115. }
  20116. }
  20117. if (ret == 0) {
  20118. localIdx = extIdx;
  20119. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  20120. tag == ASN_BOOLEAN) {
  20121. if (GetBoolean(cert, &extIdx, certSz) < 0)
  20122. ret = ASN_PARSE_E;
  20123. }
  20124. }
  20125. if (ret == 0) {
  20126. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  20127. ret = ASN_PARSE_E;
  20128. }
  20129. if (ret == 0) {
  20130. switch (oid) {
  20131. case AUTH_KEY_OID:
  20132. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  20133. ret = ASN_PARSE_E;
  20134. if (ret == 0 && (extIdx + 1) >= certSz)
  20135. ret = BUFFER_E;
  20136. if (ret == 0 &&
  20137. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  20138. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  20139. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  20140. ret = ASN_PARSE_E;
  20141. if (ret == 0) {
  20142. extAuthKeyIdSet = 1;
  20143. /* Get the hash or hash of the hash if wrong
  20144. * size. */
  20145. ret = GetHashId(cert + extIdx, extLen,
  20146. hash, HashIdAlg(signatureOID));
  20147. }
  20148. }
  20149. break;
  20150. default:
  20151. break;
  20152. }
  20153. }
  20154. idx += len;
  20155. }
  20156. }
  20157. }
  20158. }
  20159. else if (ret == 0) {
  20160. idx += len;
  20161. }
  20162. if (ret == 0 && pubKey == NULL) {
  20163. if (extAuthKeyIdSet)
  20164. ca = GetCA(cm, hash);
  20165. if (ca == NULL) {
  20166. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  20167. HashIdAlg(signatureOID));
  20168. if (ret == 0)
  20169. ca = GetCAByName(cm, hash);
  20170. }
  20171. }
  20172. #else
  20173. if (ret == 0 && pubKey == NULL) {
  20174. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  20175. HashIdAlg(signatureOID));
  20176. if (ret == 0)
  20177. ca = GetCA(cm, hash);
  20178. }
  20179. #endif /* !NO_SKID */
  20180. if (ca == NULL && pubKey == NULL)
  20181. ret = ASN_NO_SIGNER_E;
  20182. if (ret == 0) {
  20183. idx = sigIndex;
  20184. /* signatureAlgorithm */
  20185. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  20186. ret = ASN_PARSE_E;
  20187. #ifdef WC_RSA_PSS
  20188. else if (signatureOID == CTC_RSASSAPSS) {
  20189. word32 sz = idx;
  20190. const byte* params = cert + idx;
  20191. if (GetSequence(cert, &idx, &len, certSz) < 0)
  20192. ret = ASN_PARSE_E;
  20193. if (ret == 0) {
  20194. idx += len;
  20195. sz = idx - sz;
  20196. if (req) {
  20197. if ((sz != sigParamsSz) ||
  20198. (XMEMCMP(sigParams, params, sz) != 0)) {
  20199. ret = ASN_PARSE_E;
  20200. }
  20201. }
  20202. else {
  20203. sigParams = params;
  20204. sigParamsSz = sz;
  20205. }
  20206. }
  20207. }
  20208. #endif
  20209. /* In CSR signature data is not present in body */
  20210. if (req)
  20211. signatureOID = oid;
  20212. }
  20213. if (ret == 0) {
  20214. if (oid != signatureOID)
  20215. ret = ASN_SIG_OID_E;
  20216. }
  20217. if (ret == 0) {
  20218. /* signatureValue */
  20219. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  20220. ret = ASN_PARSE_E;
  20221. }
  20222. if (ret == 0) {
  20223. if (pubKey != NULL) {
  20224. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  20225. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  20226. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  20227. }
  20228. else {
  20229. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  20230. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  20231. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  20232. sigParamsSz, NULL);
  20233. }
  20234. if (ret != 0) {
  20235. WOLFSSL_ERROR_VERBOSE(ret);
  20236. WOLFSSL_MSG("Confirm signature failed");
  20237. }
  20238. }
  20239. FreeSignatureCtx(sigCtx);
  20240. #ifdef WOLFSSL_SMALL_STACK
  20241. if (sigCtx != NULL)
  20242. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  20243. #endif
  20244. return ret;
  20245. #else /* WOLFSSL_ASN_TEMPLATE */
  20246. /* X509 ASN.1 template longer than Certificate Request template. */
  20247. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  20248. #ifndef WOLFSSL_SMALL_STACK
  20249. SignatureCtx sigCtx[1];
  20250. #else
  20251. SignatureCtx* sigCtx = NULL;
  20252. #endif
  20253. byte hash[KEYID_SIZE];
  20254. Signer* ca = NULL;
  20255. int ret = 0;
  20256. word32 idx = 0;
  20257. #ifndef NO_SKID
  20258. int extAuthKeyIdSet = 0;
  20259. #endif
  20260. const byte* tbs = NULL;
  20261. word32 tbsSz = 0;
  20262. #ifdef WC_RSA_PSS
  20263. const byte* tbsParams = NULL;
  20264. word32 tbsParamsSz = 0;
  20265. #endif
  20266. const byte* sig = NULL;
  20267. word32 sigSz = 0;
  20268. word32 sigOID = 0;
  20269. const byte* sigParams = NULL;
  20270. word32 sigParamsSz = 0;
  20271. const byte* caName = NULL;
  20272. word32 caNameLen = 0;
  20273. #ifndef NO_SKID
  20274. const byte* akiData = NULL;
  20275. word32 akiLen = 0;
  20276. #endif
  20277. (void)req;
  20278. (void)heap;
  20279. if (cert == NULL) {
  20280. ret = BAD_FUNC_ARG;
  20281. }
  20282. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  20283. if ((ret == 0) && (!req)) {
  20284. /* Clear dynamic data for certificate items. */
  20285. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  20286. /* Set OID types expected for signature and public key. */
  20287. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  20288. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  20289. oidKeyType);
  20290. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  20291. oidCurveType);
  20292. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  20293. /* Parse certificate. */
  20294. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  20295. &idx, certSz);
  20296. /* Check signature OIDs match. */
  20297. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  20298. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  20299. ret = ASN_SIG_OID_E;
  20300. }
  20301. /* Store the data for verification in the certificate. */
  20302. if (ret == 0) {
  20303. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  20304. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  20305. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  20306. cert);
  20307. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  20308. cert);
  20309. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  20310. #ifdef WC_RSA_PSS
  20311. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  20312. tbsParams =
  20313. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  20314. cert);
  20315. tbsParamsSz =
  20316. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  20317. cert);
  20318. }
  20319. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  20320. sigParams =
  20321. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20322. cert);
  20323. sigParamsSz =
  20324. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20325. cert);
  20326. }
  20327. #endif
  20328. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  20329. #ifdef WC_RSA_PSS
  20330. if (tbsParamsSz != sigParamsSz) {
  20331. ret = ASN_PARSE_E;
  20332. }
  20333. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  20334. ret = ASN_PARSE_E;
  20335. }
  20336. else if ((tbsParamsSz > 0) &&
  20337. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  20338. ret = ASN_PARSE_E;
  20339. }
  20340. #endif
  20341. }
  20342. }
  20343. else if (ret == 0) {
  20344. #ifndef WOLFSSL_CERT_REQ
  20345. ret = NOT_COMPILED_IN;
  20346. #else
  20347. /* Clear dynamic data for certificate request items. */
  20348. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  20349. /* Set OID types expected for signature and public key. */
  20350. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  20351. oidKeyType);
  20352. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  20353. oidCurveType);
  20354. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  20355. /* Parse certificate request. */
  20356. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  20357. &idx, certSz);
  20358. if (ret == 0) {
  20359. /* Store the data for verification in the certificate. */
  20360. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  20361. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  20362. caName = GetASNItem_Addr(
  20363. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20364. caNameLen = GetASNItem_Length(
  20365. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20366. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  20367. #ifdef WC_RSA_PSS
  20368. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20369. cert);
  20370. sigParamsSz =
  20371. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20372. cert);
  20373. #endif
  20374. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  20375. &sigSz);
  20376. }
  20377. #endif
  20378. }
  20379. #ifndef NO_SKID
  20380. if ((ret == 0) && (pubKey == NULL) && !req) {
  20381. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  20382. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  20383. }
  20384. #endif
  20385. FREE_ASNGETDATA(dataASN, heap);
  20386. /* If no public passed, then find the CA. */
  20387. if ((ret == 0) && (pubKey == NULL)) {
  20388. #ifndef NO_SKID
  20389. /* Find the AKI extension in list of extensions and get hash. */
  20390. if ((!req) && (akiData != NULL)) {
  20391. /* TODO: test case */
  20392. ret = GetAKIHash(akiData, akiLen, sigOID, hash, &extAuthKeyIdSet,
  20393. heap);
  20394. }
  20395. /* Get the CA by hash one was found. */
  20396. if (extAuthKeyIdSet) {
  20397. ca = GetCA(cm, hash);
  20398. }
  20399. if (ca == NULL)
  20400. #endif
  20401. {
  20402. /* Try hash of issuer name. */
  20403. ret = CalcHashId_ex(caName, caNameLen, hash, HashIdAlg(sigOID));
  20404. if (ret == 0) {
  20405. ca = GetCAByName(cm, hash);
  20406. }
  20407. }
  20408. if (ca != NULL) {
  20409. /* Extract public key information. */
  20410. pubKey = ca->publicKey;
  20411. pubKeySz = ca->pubKeySize;
  20412. pubKeyOID = (int)ca->keyOID;
  20413. }
  20414. else {
  20415. /* No public key to verify with. */
  20416. ret = ASN_NO_SIGNER_E;
  20417. }
  20418. }
  20419. if (ret == 0) {
  20420. #ifdef WOLFSSL_SMALL_STACK
  20421. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  20422. DYNAMIC_TYPE_SIGNATURE);
  20423. if (sigCtx == NULL) {
  20424. ret = MEMORY_E;
  20425. }
  20426. if (ret == 0)
  20427. #endif
  20428. {
  20429. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  20430. /* Check signature. */
  20431. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  20432. (word32)pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz,
  20433. NULL);
  20434. if (ret != 0) {
  20435. WOLFSSL_MSG("Confirm signature failed");
  20436. }
  20437. FreeSignatureCtx(sigCtx);
  20438. #ifdef WOLFSSL_SMALL_STACK
  20439. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  20440. #endif
  20441. }
  20442. }
  20443. return ret;
  20444. #endif /* WOLFSSL_ASN_TEMPLATE */
  20445. }
  20446. #ifdef OPENSSL_EXTRA
  20447. /* Call CheckCertSignature_ex using a public key buffer for verification
  20448. */
  20449. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20450. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20451. {
  20452. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20453. pubKey, pubKeySz, pubKeyOID, 0);
  20454. }
  20455. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  20456. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20457. {
  20458. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  20459. pubKeyOID);
  20460. }
  20461. #ifdef WOLFSSL_CERT_REQ
  20462. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20463. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20464. {
  20465. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20466. pubKey, pubKeySz, pubKeyOID, 1);
  20467. }
  20468. #endif /* WOLFSSL_CERT_REQ */
  20469. #endif /* OPENSSL_EXTRA */
  20470. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  20471. /* Call CheckCertSignature_ex using a certificate manager (cm)
  20472. */
  20473. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  20474. {
  20475. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  20476. }
  20477. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  20478. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  20479. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  20480. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  20481. /* ASN.1 DER decode instruction. */
  20482. typedef struct DecodeInstr {
  20483. /* Tag expected. */
  20484. byte tag;
  20485. /* Operation to perform: step in or go over */
  20486. byte op:1;
  20487. /* ASN.1 item is optional. */
  20488. byte optional:1;
  20489. } DecodeInstr;
  20490. /* Step into ASN.1 item. */
  20491. #define DECODE_INSTR_IN 0
  20492. /* Step over ASN.1 item. */
  20493. #define DECODE_INSTR_OVER 1
  20494. /* Get the public key data from the DER encoded X.509 certificate.
  20495. *
  20496. * Assumes data has previously been parsed for complete validity.
  20497. *
  20498. * @param [in] cert DER encoded X.509 certificate data.
  20499. * @param [in] certSz Length of DER encoding.
  20500. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  20501. * @param [out] pubKeySz Length of public key data in bytes.
  20502. * @return 0 on success.
  20503. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  20504. * @return ASN_PARSE_E when certificate encoding is invalid.
  20505. */
  20506. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  20507. const unsigned char** pubKey, word32* pubKeySz)
  20508. {
  20509. int ret = 0;
  20510. int l;
  20511. word32 o = 0;
  20512. int i;
  20513. static DecodeInstr ops[] = {
  20514. /* Outer SEQ */
  20515. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20516. /* TBSCertificate: SEQ */
  20517. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20518. /* Version: [0] */
  20519. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  20520. DECODE_INSTR_OVER, 1 },
  20521. /* CertificateSerialNumber: INT */
  20522. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  20523. /* AlgorithmIdentifier: SEQ */
  20524. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20525. /* issuer: SEQ */
  20526. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20527. /* Validity: SEQ */
  20528. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20529. /* subject: SEQ */
  20530. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20531. /* subjectPublicKeyInfo SEQ */
  20532. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20533. /* AlgorithmIdentifier: SEQ */
  20534. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20535. /* PublicKey: BIT_STRING */
  20536. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  20537. };
  20538. /* Validate parameters. */
  20539. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  20540. ret = BAD_FUNC_ARG;
  20541. }
  20542. /* Process each instruction to take us to public key data. */
  20543. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  20544. DecodeInstr op = ops[i];
  20545. /* Check the current ASN.1 item has the expected tag. */
  20546. if (cert[o] != op.tag) {
  20547. /* If not optional then error, otherwise skip op. */
  20548. if (!op.optional) {
  20549. ret = ASN_PARSE_E;
  20550. }
  20551. }
  20552. else {
  20553. /* Move past tag. */
  20554. o++;
  20555. /* Get the length of ASN.1 item and move past length encoding. */
  20556. if (GetLength(cert, &o, &l, certSz) < 0) {
  20557. ret = ASN_PARSE_E;
  20558. }
  20559. /* Skip data if required. */
  20560. else if (op.op == DECODE_INSTR_OVER) {
  20561. o += (word32)l;
  20562. }
  20563. }
  20564. }
  20565. if (ret == 0) {
  20566. /* Return the public key data and length.
  20567. * Skip first byte of BIT_STRING data: unused bits. */
  20568. *pubKey = cert + o + 1;
  20569. *pubKeySz = (word32)(l - 1);
  20570. }
  20571. return ret;
  20572. }
  20573. #endif
  20574. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  20575. {
  20576. int ret = 0;
  20577. #ifndef WOLFSSL_ASN_TEMPLATE
  20578. word32 confirmOID = 0;
  20579. #ifdef WOLFSSL_CERT_REQ
  20580. int len = 0;
  20581. #endif
  20582. #endif
  20583. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  20584. int idx = 0;
  20585. #endif
  20586. byte* sce_tsip_encRsaKeyIdx;
  20587. if (cert == NULL) {
  20588. return BAD_FUNC_ARG;
  20589. }
  20590. #ifdef WOLFSSL_CERT_REQ
  20591. if (type == CERTREQ_TYPE)
  20592. cert->isCSR = 1;
  20593. #endif
  20594. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  20595. #ifndef WOLFSSL_ASN_TEMPLATE
  20596. cert->badDate = 0;
  20597. cert->criticalExt = 0;
  20598. if ((ret = DecodeToKey(cert, verify)) < 0) {
  20599. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20600. cert->badDate = ret;
  20601. if (verify == VERIFY_SKIP_DATE)
  20602. ret = 0;
  20603. }
  20604. else
  20605. return ret;
  20606. }
  20607. WOLFSSL_MSG("Parsed Past Key");
  20608. #if defined(HAVE_RPK)
  20609. if (cert->isRPK) {
  20610. return ret;
  20611. }
  20612. #endif /* HAVE_RPK */
  20613. #ifdef WOLFSSL_CERT_REQ
  20614. /* Read attributes */
  20615. if (cert->isCSR) {
  20616. if (GetASNHeader_ex(cert->source,
  20617. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  20618. &len, cert->maxIdx, 1) < 0) {
  20619. WOLFSSL_MSG("GetASNHeader_ex error");
  20620. return ASN_PARSE_E;
  20621. }
  20622. if (len) {
  20623. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  20624. word32 oid;
  20625. byte tag;
  20626. if (attrMaxIdx > cert->maxIdx) {
  20627. WOLFSSL_MSG("Attribute length greater than CSR length");
  20628. return ASN_PARSE_E;
  20629. }
  20630. while (cert->srcIdx < attrMaxIdx) {
  20631. /* Attributes have the structure:
  20632. * SEQ -> OID -> SET -> ATTRIBUTE */
  20633. if (GetSequence(cert->source, &cert->srcIdx, &len,
  20634. attrMaxIdx) < 0) {
  20635. WOLFSSL_MSG("attr GetSequence error");
  20636. return ASN_PARSE_E;
  20637. }
  20638. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  20639. oidCsrAttrType, attrMaxIdx) < 0) {
  20640. WOLFSSL_MSG("attr GetObjectId error");
  20641. return ASN_PARSE_E;
  20642. }
  20643. if (GetSet(cert->source, &cert->srcIdx, &len,
  20644. attrMaxIdx) < 0) {
  20645. WOLFSSL_MSG("attr GetSet error");
  20646. return ASN_PARSE_E;
  20647. }
  20648. switch (oid) {
  20649. case PKCS9_CONTENT_TYPE_OID:
  20650. if (GetHeader(cert->source, &tag,
  20651. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20652. WOLFSSL_MSG("attr GetHeader error");
  20653. return ASN_PARSE_E;
  20654. }
  20655. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20656. tag != ASN_IA5_STRING) {
  20657. WOLFSSL_MSG("Unsupported attribute value format");
  20658. return ASN_PARSE_E;
  20659. }
  20660. cert->contentType = (char*)cert->source + cert->srcIdx;
  20661. cert->contentTypeLen = len;
  20662. cert->srcIdx += (word32)len;
  20663. break;
  20664. case CHALLENGE_PASSWORD_OID:
  20665. if (GetHeader(cert->source, &tag,
  20666. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20667. WOLFSSL_MSG("attr GetHeader error");
  20668. return ASN_PARSE_E;
  20669. }
  20670. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20671. tag != ASN_IA5_STRING) {
  20672. WOLFSSL_MSG("Unsupported attribute value format");
  20673. return ASN_PARSE_E;
  20674. }
  20675. cert->cPwd = (char*)cert->source + cert->srcIdx;
  20676. cert->cPwdLen = len;
  20677. cert->srcIdx += (word32)len;
  20678. break;
  20679. case SERIAL_NUMBER_OID:
  20680. if (GetHeader(cert->source, &tag,
  20681. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20682. WOLFSSL_MSG("attr GetHeader error");
  20683. return ASN_PARSE_E;
  20684. }
  20685. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20686. tag != ASN_IA5_STRING) {
  20687. WOLFSSL_MSG("Unsupported attribute value format");
  20688. return ASN_PARSE_E;
  20689. }
  20690. cert->sNum = (char*)cert->source + cert->srcIdx;
  20691. cert->sNumLen = len;
  20692. cert->srcIdx += (word32)len;
  20693. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  20694. XMEMCPY(cert->serial, cert->sNum,
  20695. (size_t)cert->sNumLen);
  20696. cert->serialSz = cert->sNumLen;
  20697. }
  20698. break;
  20699. case DNQUALIFIER_OID:
  20700. if (GetHeader(cert->source, &tag,
  20701. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20702. WOLFSSL_MSG("attr GetHeader error");
  20703. return ASN_PARSE_E;
  20704. }
  20705. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  20706. cert->dnQualifierLen = len;
  20707. cert->srcIdx += (word32)len;
  20708. break;
  20709. case INITIALS_OID:
  20710. if (GetHeader(cert->source, &tag,
  20711. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20712. WOLFSSL_MSG("attr GetHeader error");
  20713. return ASN_PARSE_E;
  20714. }
  20715. cert->initials = (char*)cert->source + cert->srcIdx;
  20716. cert->initialsLen = len;
  20717. cert->srcIdx += (word32)len;
  20718. break;
  20719. case SURNAME_OID:
  20720. if (GetHeader(cert->source, &tag,
  20721. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20722. WOLFSSL_MSG("attr GetHeader error");
  20723. return ASN_PARSE_E;
  20724. }
  20725. cert->surname = (char*)cert->source + cert->srcIdx;
  20726. cert->surnameLen = len;
  20727. cert->srcIdx += (word32)len;
  20728. break;
  20729. case GIVEN_NAME_OID:
  20730. if (GetHeader(cert->source, &tag,
  20731. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20732. WOLFSSL_MSG("attr GetHeader error");
  20733. return ASN_PARSE_E;
  20734. }
  20735. cert->givenName = (char*)cert->source + cert->srcIdx;
  20736. cert->givenNameLen = len;
  20737. cert->srcIdx += (word32)len;
  20738. break;
  20739. case UNSTRUCTURED_NAME_OID:
  20740. if (GetHeader(cert->source, &tag,
  20741. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20742. WOLFSSL_MSG("attr GetHeader error");
  20743. return ASN_PARSE_E;
  20744. }
  20745. cert->unstructuredName =
  20746. (char*)cert->source + cert->srcIdx;
  20747. cert->unstructuredNameLen = len;
  20748. cert->srcIdx += (word32)len;
  20749. break;
  20750. case EXTENSION_REQUEST_OID:
  20751. /* save extensions */
  20752. cert->extensions = &cert->source[cert->srcIdx];
  20753. cert->extensionsSz = len;
  20754. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20755. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20756. if (ret == ASN_CRIT_EXT_E) {
  20757. cert->criticalExt = ret;
  20758. }
  20759. else {
  20760. return ret;
  20761. }
  20762. }
  20763. cert->srcIdx += (word32)len;
  20764. break;
  20765. default:
  20766. WOLFSSL_MSG("Unsupported attribute type");
  20767. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20768. return ASN_PARSE_E;
  20769. }
  20770. }
  20771. }
  20772. }
  20773. #endif
  20774. if (cert->srcIdx < cert->sigIndex) {
  20775. #ifndef ALLOW_V1_EXTENSIONS
  20776. if (cert->version < 2) {
  20777. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  20778. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  20779. return ASN_VERSION_E;
  20780. }
  20781. #endif
  20782. /* save extensions */
  20783. cert->extensions = &cert->source[cert->srcIdx];
  20784. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  20785. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20786. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20787. if (ret == ASN_CRIT_EXT_E)
  20788. cert->criticalExt = ret;
  20789. else
  20790. return ret;
  20791. }
  20792. #ifdef HAVE_OCSP
  20793. if (verify == VERIFY_OCSP_CERT) {
  20794. /* trust for the lifetime of the responder's cert*/
  20795. if (cert->ocspNoCheckSet)
  20796. verify = VERIFY;
  20797. else
  20798. verify = VERIFY_OCSP;
  20799. }
  20800. #endif
  20801. /* advance past extensions */
  20802. cert->srcIdx = cert->sigIndex;
  20803. }
  20804. if ((ret = GetSigAlg(cert,
  20805. #ifdef WOLFSSL_CERT_REQ
  20806. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  20807. #else
  20808. &confirmOID,
  20809. #endif
  20810. cert->maxIdx)) < 0) {
  20811. return ret;
  20812. }
  20813. if ((ret = GetSignature(cert)) < 0) {
  20814. return ret;
  20815. }
  20816. if (confirmOID != cert->signatureOID
  20817. #ifdef WOLFSSL_CERT_REQ
  20818. && !cert->isCSR
  20819. #endif
  20820. ) {
  20821. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  20822. return ASN_SIG_OID_E;
  20823. }
  20824. #else
  20825. #ifdef WOLFSSL_CERT_REQ
  20826. if (cert->isCSR) {
  20827. ret = DecodeCertReq(cert, &cert->criticalExt);
  20828. if (ret < 0) {
  20829. return ret;
  20830. }
  20831. }
  20832. else
  20833. #endif
  20834. {
  20835. ret = DecodeCert(cert, verify, &cert->criticalExt);
  20836. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20837. cert->badDate = ret;
  20838. if (verify == VERIFY_SKIP_DATE)
  20839. ret = 0;
  20840. }
  20841. else if (ret < 0) {
  20842. WOLFSSL_ERROR_VERBOSE(ret);
  20843. return ret;
  20844. }
  20845. #if defined(HAVE_RPK)
  20846. if (cert->isRPK) {
  20847. return ret;
  20848. }
  20849. #endif /* HAVE_RPK */
  20850. }
  20851. #endif
  20852. #ifndef ALLOW_INVALID_CERTSIGN
  20853. /* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.9
  20854. * If the cA boolean is not asserted, then the keyCertSign bit in the
  20855. * key usage extension MUST NOT be asserted. */
  20856. if (!cert->isCA && cert->extKeyUsageSet &&
  20857. (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  20858. WOLFSSL_ERROR_VERBOSE(KEYUSAGE_E);
  20859. return KEYUSAGE_E;
  20860. }
  20861. #endif
  20862. #ifndef NO_SKID
  20863. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  20864. cert->pubKeySize > 0) {
  20865. if (cert->signatureOID == CTC_SM3wSM2) {
  20866. /* TODO: GmSSL creates IDs this way but whole public key info
  20867. * block should be hashed. */
  20868. ret = CalcHashId_ex(cert->publicKey + cert->pubKeySize - 65, 65,
  20869. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  20870. }
  20871. else {
  20872. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  20873. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  20874. }
  20875. if (ret != 0) {
  20876. WOLFSSL_ERROR_VERBOSE(ret);
  20877. return ret;
  20878. }
  20879. }
  20880. #endif /* !NO_SKID */
  20881. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  20882. type != TRUSTED_PEER_TYPE)) {
  20883. cert->ca = NULL;
  20884. #ifndef NO_SKID
  20885. if (cert->extAuthKeyIdSet) {
  20886. cert->ca = GetCA(cm, cert->extAuthKeyId);
  20887. #ifdef WOLFSSL_AKID_NAME
  20888. if (cert->ca == NULL) {
  20889. cert->ca = GetCAByAKID(cm, cert->extAuthKeyIdIssuer,
  20890. cert->extAuthKeyIdIssuerSz, cert->extAuthKeyIdIssuerSN,
  20891. cert->extAuthKeyIdIssuerSNSz);
  20892. }
  20893. #endif
  20894. }
  20895. if (cert->ca == NULL && cert->extSubjKeyIdSet
  20896. && verify != VERIFY_OCSP) {
  20897. cert->ca = GetCA(cm, cert->extSubjKeyId);
  20898. }
  20899. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  20900. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  20901. cert->ca = NULL;
  20902. }
  20903. if (cert->ca == NULL) {
  20904. cert->ca = GetCAByName(cm, cert->issuerHash);
  20905. /* If AKID is available then this CA doesn't have the public
  20906. * key required */
  20907. if (cert->ca && cert->extAuthKeyIdSet) {
  20908. WOLFSSL_MSG("CA SKID doesn't match AKID");
  20909. cert->ca = NULL;
  20910. }
  20911. }
  20912. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  20913. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  20914. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  20915. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  20916. if (cert->ca) {
  20917. ret = 0; /* success */
  20918. goto exit_pcr;
  20919. }
  20920. }
  20921. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  20922. #else
  20923. cert->ca = GetCA(cm, cert->issuerHash);
  20924. #endif /* !NO_SKID */
  20925. if (cert->ca) {
  20926. WOLFSSL_MSG("CA found");
  20927. }
  20928. }
  20929. /* Set to WOLFSSL_MAX_PATH_LEN by default in InitDecodedCert_ex */
  20930. if (cert->pathLengthSet)
  20931. cert->maxPathLen = cert->pathLength;
  20932. if (!cert->selfSigned) {
  20933. /* Need to perform a pathlen check on anything that will be used
  20934. * to sign certificates later on. Otherwise, pathLen doesn't
  20935. * mean anything.
  20936. * Nothing to check if we don't have the issuer of this cert. */
  20937. if (type != CERT_TYPE && cert->isCA && cert->extKeyUsageSet &&
  20938. (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0 && cert->ca) {
  20939. if (cert->ca->maxPathLen == 0) {
  20940. /* This cert CAN NOT be used as an intermediate cert. The
  20941. * issuer does not allow it. */
  20942. cert->maxPathLen = 0;
  20943. if (verify != NO_VERIFY) {
  20944. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20945. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20946. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20947. return ASN_PATHLEN_INV_E;
  20948. }
  20949. }
  20950. else {
  20951. cert->maxPathLen = (byte)min(cert->ca->maxPathLen - 1,
  20952. cert->maxPathLen);
  20953. }
  20954. }
  20955. }
  20956. #ifdef HAVE_OCSP
  20957. if (verify != NO_VERIFY && type != CA_TYPE &&
  20958. type != TRUSTED_PEER_TYPE) {
  20959. if (cert->ca) {
  20960. /* Need the CA's public key hash for OCSP */
  20961. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20962. KEYID_SIZE);
  20963. }
  20964. }
  20965. #endif /* HAVE_OCSP */
  20966. }
  20967. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_FSPSM_TLS)
  20968. /* prepare for TSIP TLS cert verification API use */
  20969. if (cert->keyOID == RSAk) {
  20970. /* to call TSIP API, it needs keys position info in bytes */
  20971. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20972. cert->pubKeySize,
  20973. &cert->sigCtx.CertAtt.pubkey_n_start,
  20974. &cert->sigCtx.CertAtt.pubkey_n_len,
  20975. &cert->sigCtx.CertAtt.pubkey_e_start,
  20976. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20977. WOLFSSL_MSG("Decoding index from cert failed.");
  20978. return ret;
  20979. }
  20980. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20981. }
  20982. else if (cert->keyOID == ECDSAk) {
  20983. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20984. }
  20985. /* check if we can use TSIP for cert verification */
  20986. /* if the ca is verified as tsip root ca. */
  20987. /* TSIP can only handle 2048 bits(256 byte) key. */
  20988. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20989. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20990. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20991. /* assign memory to encrypted tsip Rsa key index */
  20992. if (!cert->sce_tsip_encRsaKeyIdx)
  20993. cert->sce_tsip_encRsaKeyIdx =
  20994. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20995. cert->heap, DYNAMIC_TYPE_RSA);
  20996. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20997. return MEMORY_E;
  20998. }
  20999. else {
  21000. if (cert->ca) {
  21001. /* TSIP isn't usable */
  21002. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  21003. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  21004. "by TSIP.");
  21005. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  21006. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  21007. "RSA 2048.");
  21008. else
  21009. WOLFSSL_MSG("SCE-TSIP isn't usable");
  21010. }
  21011. cert->sce_tsip_encRsaKeyIdx = NULL;
  21012. }
  21013. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  21014. #else
  21015. sce_tsip_encRsaKeyIdx = NULL;
  21016. #endif
  21017. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  21018. if (cert->ca) {
  21019. if (verify == VERIFY || verify == VERIFY_OCSP ||
  21020. verify == VERIFY_SKIP_DATE) {
  21021. /* try to confirm/verify signature */
  21022. if ((ret = ConfirmSignature(&cert->sigCtx,
  21023. cert->source + cert->certBegin,
  21024. cert->sigIndex - cert->certBegin,
  21025. cert->ca->publicKey, cert->ca->pubKeySize,
  21026. cert->ca->keyOID, cert->signature,
  21027. cert->sigLength, cert->signatureOID,
  21028. #ifdef WC_RSA_PSS
  21029. cert->source + cert->sigParamsIndex,
  21030. cert->sigParamsLength,
  21031. #else
  21032. NULL, 0,
  21033. #endif
  21034. sce_tsip_encRsaKeyIdx)) != 0) {
  21035. if (ret != WC_PENDING_E) {
  21036. WOLFSSL_MSG("Confirm signature failed");
  21037. }
  21038. WOLFSSL_ERROR_VERBOSE(ret);
  21039. return ret;
  21040. }
  21041. }
  21042. #ifndef IGNORE_NAME_CONSTRAINTS
  21043. if (verify == VERIFY || verify == VERIFY_OCSP ||
  21044. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  21045. /* check that this cert's name is permitted by the signer's
  21046. * name constraints */
  21047. if (!ConfirmNameConstraints(cert->ca, cert)) {
  21048. WOLFSSL_MSG("Confirm name constraint failed");
  21049. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  21050. return ASN_NAME_INVALID_E;
  21051. }
  21052. }
  21053. #endif /* IGNORE_NAME_CONSTRAINTS */
  21054. }
  21055. #ifdef WOLFSSL_CERT_REQ
  21056. else if (type == CERTREQ_TYPE) {
  21057. if ((ret = ConfirmSignature(&cert->sigCtx,
  21058. cert->source + cert->certBegin,
  21059. cert->sigIndex - cert->certBegin,
  21060. cert->publicKey, cert->pubKeySize,
  21061. cert->keyOID, cert->signature,
  21062. cert->sigLength, cert->signatureOID,
  21063. #ifdef WC_RSA_PSS
  21064. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  21065. #else
  21066. NULL, 0,
  21067. #endif
  21068. sce_tsip_encRsaKeyIdx)) != 0) {
  21069. if (ret != WC_PENDING_E) {
  21070. WOLFSSL_MSG("Confirm signature failed");
  21071. }
  21072. WOLFSSL_ERROR_VERBOSE(ret);
  21073. return ret;
  21074. }
  21075. }
  21076. #endif
  21077. else {
  21078. /* no signer */
  21079. WOLFSSL_MSG("No CA signer to verify with");
  21080. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  21081. /* ret needs to be self-signer error for Qt compat */
  21082. if (cert->selfSigned) {
  21083. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  21084. return ASN_SELF_SIGNED_E;
  21085. }
  21086. else
  21087. #endif
  21088. {
  21089. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  21090. return ASN_NO_SIGNER_E;
  21091. }
  21092. }
  21093. }
  21094. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  21095. exit_pcr:
  21096. #endif
  21097. if (cert->badDate != 0) {
  21098. if (verify != VERIFY_SKIP_DATE) {
  21099. return cert->badDate;
  21100. }
  21101. WOLFSSL_MSG("Date error: Verify option is skipping");
  21102. }
  21103. if (cert->criticalExt != 0)
  21104. return cert->criticalExt;
  21105. return ret;
  21106. }
  21107. /* Create and init an new signer */
  21108. Signer* MakeSigner(void* heap)
  21109. {
  21110. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  21111. DYNAMIC_TYPE_SIGNER);
  21112. if (signer) {
  21113. XMEMSET(signer, 0, sizeof(Signer));
  21114. }
  21115. (void)heap;
  21116. return signer;
  21117. }
  21118. /* Free an individual signer.
  21119. *
  21120. * Used by Certificate Manager.
  21121. *
  21122. * @param [in, out] signer On in, signer object.
  21123. * On out, pointer is no longer valid.
  21124. * @param [in] heap Dynamic memory hint.
  21125. */
  21126. void FreeSigner(Signer* signer, void* heap)
  21127. {
  21128. (void)signer;
  21129. (void)heap;
  21130. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  21131. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  21132. #ifndef IGNORE_NAME_CONSTRAINTS
  21133. if (signer->permittedNames)
  21134. FreeNameSubtrees(signer->permittedNames, heap);
  21135. if (signer->excludedNames)
  21136. FreeNameSubtrees(signer->excludedNames, heap);
  21137. #endif
  21138. #ifdef WOLFSSL_SIGNER_DER_CERT
  21139. FreeDer(&signer->derCert);
  21140. #endif
  21141. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  21142. }
  21143. /* Free the whole singer table with number of rows.
  21144. *
  21145. * Each table entry is a linked list of signers.
  21146. * Used by Certificate Manager.
  21147. *
  21148. * @param [in, out] table Array of signer objects.
  21149. * @param [in] rows Number of entries in table.
  21150. * @param [in] heap Dynamic memory hint.
  21151. */
  21152. void FreeSignerTable(Signer** table, int rows, void* heap)
  21153. {
  21154. int i;
  21155. for (i = 0; i < rows; i++) {
  21156. Signer* signer = table[i];
  21157. while (signer) {
  21158. Signer* next = signer->next;
  21159. FreeSigner(signer, heap);
  21160. signer = next;
  21161. }
  21162. table[i] = NULL;
  21163. }
  21164. }
  21165. #ifdef WOLFSSL_TRUST_PEER_CERT
  21166. /* Free an individual trusted peer cert.
  21167. *
  21168. * @param [in, out] tp Trusted peer certificate object.
  21169. * @param [in] heap Dynamic memory hint.
  21170. */
  21171. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  21172. {
  21173. if (tp == NULL) {
  21174. return;
  21175. }
  21176. if (tp->name) {
  21177. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  21178. }
  21179. if (tp->sig) {
  21180. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  21181. }
  21182. #ifndef IGNORE_NAME_CONSTRAINTS
  21183. if (tp->permittedNames)
  21184. FreeNameSubtrees(tp->permittedNames, heap);
  21185. if (tp->excludedNames)
  21186. FreeNameSubtrees(tp->excludedNames, heap);
  21187. #endif
  21188. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  21189. (void)heap;
  21190. }
  21191. /* Free the whole Trusted Peer linked list.
  21192. *
  21193. * Each table entry is a linked list of trusted peer certificates.
  21194. * Used by Certificate Manager.
  21195. *
  21196. * @param [in, out] table Array of trusted peer certificate objects.
  21197. * @param [in] rows Number of entries in table.
  21198. * @param [in] heap Dynamic memory hint.
  21199. */
  21200. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  21201. {
  21202. int i;
  21203. for (i = 0; i < rows; i++) {
  21204. TrustedPeerCert* tp = table[i];
  21205. while (tp) {
  21206. TrustedPeerCert* next = tp->next;
  21207. FreeTrustedPeer(tp, heap);
  21208. tp = next;
  21209. }
  21210. table[i] = NULL;
  21211. }
  21212. }
  21213. #endif /* WOLFSSL_TRUST_PEER_CERT */
  21214. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  21215. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  21216. word32 outputSz, int maxSnSz)
  21217. {
  21218. int i;
  21219. int snSzInt = (int)snSz;
  21220. if (sn == NULL || output == NULL || snSzInt < 0)
  21221. return BAD_FUNC_ARG;
  21222. /* remove leading zeros */
  21223. while (snSzInt > 0 && sn[0] == 0) {
  21224. snSzInt--;
  21225. sn++;
  21226. }
  21227. /* RFC 5280 - 4.1.2.2:
  21228. * Serial numbers must be a positive value (and not zero) */
  21229. if (snSzInt == 0) {
  21230. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  21231. return BAD_FUNC_ARG;
  21232. }
  21233. if (sn[0] & 0x80)
  21234. maxSnSz--;
  21235. /* truncate if input is too long */
  21236. if (snSzInt > maxSnSz)
  21237. snSzInt = maxSnSz;
  21238. i = SetASNInt(snSzInt, sn[0], NULL);
  21239. /* truncate if input is too long */
  21240. if (snSzInt > (int)outputSz - i)
  21241. snSzInt = (int)outputSz - i;
  21242. /* sanity check number of bytes to copy */
  21243. if (snSzInt <= 0) {
  21244. return BUFFER_E;
  21245. }
  21246. /* write out ASN.1 Integer */
  21247. (void)SetASNInt(snSzInt, sn[0], output);
  21248. XMEMCPY(output + i, sn, (size_t)snSzInt);
  21249. /* compute final length */
  21250. i += snSzInt;
  21251. return i;
  21252. }
  21253. #endif /* !WOLFSSL_ASN_TEMPLATE */
  21254. #endif /* !NO_CERTS */
  21255. #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \
  21256. (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT))
  21257. int SetMyVersion(word32 version, byte* output, int header)
  21258. {
  21259. int i = 0;
  21260. if (output == NULL)
  21261. return BAD_FUNC_ARG;
  21262. if (header) {
  21263. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  21264. output[i++] = 3;
  21265. }
  21266. output[i++] = ASN_INTEGER;
  21267. output[i++] = 0x01;
  21268. output[i++] = (byte)version;
  21269. return i;
  21270. }
  21271. #endif
  21272. #ifndef WOLFSSL_ASN_TEMPLATE
  21273. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  21274. byte* serial, int* serialSz, word32 maxIdx)
  21275. {
  21276. int result = 0;
  21277. int ret;
  21278. WOLFSSL_ENTER("wc_GetSerialNumber");
  21279. if (serial == NULL || input == NULL || serialSz == NULL) {
  21280. return BAD_FUNC_ARG;
  21281. }
  21282. /* First byte is ASN type */
  21283. if ((*inOutIdx+1) > maxIdx) {
  21284. WOLFSSL_MSG("Bad idx first");
  21285. return BUFFER_E;
  21286. }
  21287. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  21288. if (ret != 0)
  21289. return ret;
  21290. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  21291. WOLFSSL_MSG("Serial size bad");
  21292. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  21293. return ASN_PARSE_E;
  21294. }
  21295. /* return serial */
  21296. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  21297. *inOutIdx += (word32)*serialSz;
  21298. return result;
  21299. }
  21300. #endif
  21301. #ifndef NO_CERTS
  21302. /* TODO: consider moving PEM code out to a different file. */
  21303. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  21304. {
  21305. int ret = BAD_FUNC_ARG;
  21306. if (pDer) {
  21307. int dynType = 0;
  21308. DerBuffer* der;
  21309. /* Determine dynamic type */
  21310. switch (type) {
  21311. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  21312. case CHAIN_CERT_TYPE:
  21313. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  21314. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  21315. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  21316. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  21317. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  21318. default: dynType = DYNAMIC_TYPE_KEY; break;
  21319. }
  21320. /* Setup new buffer */
  21321. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  21322. if (*pDer == NULL) {
  21323. return MEMORY_E;
  21324. }
  21325. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  21326. der = *pDer;
  21327. der->type = type;
  21328. der->dynType = dynType; /* Cache this for FreeDer */
  21329. der->heap = heap;
  21330. der->buffer = (byte*)der + sizeof(DerBuffer);
  21331. der->length = length;
  21332. ret = 0; /* Success */
  21333. }
  21334. return ret;
  21335. }
  21336. void FreeDer(DerBuffer** pDer)
  21337. {
  21338. if (pDer && *pDer)
  21339. {
  21340. DerBuffer* der = (DerBuffer*)*pDer;
  21341. /* ForceZero private keys */
  21342. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  21343. ForceZero(der->buffer, der->length);
  21344. }
  21345. der->buffer = NULL;
  21346. der->length = 0;
  21347. XFREE(der, der->heap, der->dynType);
  21348. *pDer = NULL;
  21349. }
  21350. }
  21351. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  21352. {
  21353. return AllocDer(pDer, length, type, heap);
  21354. }
  21355. void wc_FreeDer(DerBuffer** pDer)
  21356. {
  21357. FreeDer(pDer);
  21358. }
  21359. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  21360. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  21361. updated to reflect maximum length and pem_struct_min_sz
  21362. to reflect minimum size */
  21363. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  21364. wcchar END_CERT = "-----END CERTIFICATE-----";
  21365. #ifdef WOLFSSL_CERT_REQ
  21366. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  21367. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  21368. #endif
  21369. #ifndef NO_DH
  21370. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  21371. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  21372. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  21373. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  21374. #endif
  21375. #ifndef NO_DSA
  21376. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  21377. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  21378. #endif
  21379. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  21380. wcchar END_X509_CRL = "-----END X509 CRL-----";
  21381. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  21382. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  21383. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  21384. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  21385. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  21386. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  21387. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  21388. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  21389. #ifdef HAVE_ECC
  21390. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  21391. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  21392. #ifdef OPENSSL_EXTRA
  21393. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  21394. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  21395. #endif
  21396. #endif
  21397. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21398. !defined(NO_DSA)
  21399. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  21400. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  21401. #endif
  21402. #ifdef OPENSSL_EXTRA
  21403. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  21404. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  21405. const char END_PRIV_KEY_PREFIX[] = "-----END";
  21406. #endif
  21407. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  21408. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  21409. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21410. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  21411. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  21412. #endif
  21413. #if defined(HAVE_PQC)
  21414. #if defined(HAVE_FALCON)
  21415. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  21416. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  21417. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  21418. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  21419. #endif /* HAVE_FALCON */
  21420. #if defined(HAVE_DILITHIUM)
  21421. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21422. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21423. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21424. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21425. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21426. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21427. #endif /* HAVE_DILITHIUM */
  21428. #if defined(HAVE_SPHINCS)
  21429. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21430. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21431. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21432. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21433. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21434. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21435. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21436. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21437. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21438. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21439. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21440. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21441. #endif /* HAVE_SPHINCS */
  21442. #endif /* HAVE_PQC */
  21443. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  21444. "-----END X509 CRL-----");
  21445. #ifdef WOLFSSL_PEM_TO_DER
  21446. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  21447. const char* endOfLine)
  21448. {
  21449. /* eat end of line characters */
  21450. while (line < endOfLine &&
  21451. (line[0] == '\r' || line[0] == '\n')) {
  21452. line++;
  21453. }
  21454. return line;
  21455. }
  21456. #endif
  21457. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  21458. {
  21459. int ret = BAD_FUNC_ARG;
  21460. switch (type) {
  21461. case CA_TYPE: /* same as below */
  21462. case TRUSTED_PEER_TYPE:
  21463. case CHAIN_CERT_TYPE:
  21464. case CERT_TYPE:
  21465. if (header) *header = BEGIN_CERT;
  21466. if (footer) *footer = END_CERT;
  21467. ret = 0;
  21468. break;
  21469. case CRL_TYPE:
  21470. if (header) *header = BEGIN_X509_CRL;
  21471. if (footer) *footer = END_X509_CRL;
  21472. ret = 0;
  21473. break;
  21474. #ifndef NO_DH
  21475. case DH_PARAM_TYPE:
  21476. if (header) *header = BEGIN_DH_PARAM;
  21477. if (footer) *footer = END_DH_PARAM;
  21478. ret = 0;
  21479. break;
  21480. case X942_PARAM_TYPE:
  21481. if (header) *header = BEGIN_X942_PARAM;
  21482. if (footer) *footer = END_X942_PARAM;
  21483. ret = 0;
  21484. break;
  21485. #endif
  21486. #ifndef NO_DSA
  21487. case DSA_PARAM_TYPE:
  21488. if (header) *header = BEGIN_DSA_PARAM;
  21489. if (footer) *footer = END_DSA_PARAM;
  21490. ret = 0;
  21491. break;
  21492. #endif
  21493. #ifdef WOLFSSL_CERT_REQ
  21494. case CERTREQ_TYPE:
  21495. if (header) *header = BEGIN_CERT_REQ;
  21496. if (footer) *footer = END_CERT_REQ;
  21497. ret = 0;
  21498. break;
  21499. #endif
  21500. #ifndef NO_DSA
  21501. case DSA_TYPE:
  21502. case DSA_PRIVATEKEY_TYPE:
  21503. if (header) *header = BEGIN_DSA_PRIV;
  21504. if (footer) *footer = END_DSA_PRIV;
  21505. ret = 0;
  21506. break;
  21507. #endif
  21508. #ifdef HAVE_ECC
  21509. case ECC_TYPE:
  21510. case ECC_PRIVATEKEY_TYPE:
  21511. if (header) *header = BEGIN_EC_PRIV;
  21512. if (footer) *footer = END_EC_PRIV;
  21513. ret = 0;
  21514. break;
  21515. #ifdef OPENSSL_EXTRA
  21516. case ECC_PARAM_TYPE:
  21517. if (header) *header = BEGIN_EC_PARAM;
  21518. if (footer) *footer = END_EC_PARAM;
  21519. ret = 0;
  21520. break;
  21521. #endif
  21522. #endif
  21523. case RSA_TYPE:
  21524. case PRIVATEKEY_TYPE:
  21525. if (header) *header = BEGIN_RSA_PRIV;
  21526. if (footer) *footer = END_RSA_PRIV;
  21527. ret = 0;
  21528. break;
  21529. #ifdef HAVE_ED25519
  21530. case ED25519_TYPE:
  21531. #endif
  21532. #ifdef HAVE_ED448
  21533. case ED448_TYPE:
  21534. #endif
  21535. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21536. case EDDSA_PRIVATEKEY_TYPE:
  21537. if (header) *header = BEGIN_EDDSA_PRIV;
  21538. if (footer) *footer = END_EDDSA_PRIV;
  21539. ret = 0;
  21540. break;
  21541. #endif
  21542. #ifdef HAVE_PQC
  21543. #ifdef HAVE_FALCON
  21544. case FALCON_LEVEL1_TYPE:
  21545. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  21546. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  21547. ret = 0;
  21548. break;
  21549. case FALCON_LEVEL5_TYPE:
  21550. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  21551. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  21552. ret = 0;
  21553. break;
  21554. #endif /* HAVE_FALCON */
  21555. #ifdef HAVE_DILITHIUM
  21556. case DILITHIUM_LEVEL2_TYPE:
  21557. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  21558. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  21559. ret = 0;
  21560. break;
  21561. case DILITHIUM_LEVEL3_TYPE:
  21562. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  21563. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  21564. ret = 0;
  21565. break;
  21566. case DILITHIUM_LEVEL5_TYPE:
  21567. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  21568. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  21569. ret = 0;
  21570. break;
  21571. #endif /* HAVE_DILITHIUM */
  21572. #ifdef HAVE_SPHINCS
  21573. case SPHINCS_FAST_LEVEL1_TYPE:
  21574. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  21575. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  21576. ret = 0;
  21577. break;
  21578. case SPHINCS_FAST_LEVEL3_TYPE:
  21579. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  21580. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  21581. ret = 0;
  21582. break;
  21583. case SPHINCS_FAST_LEVEL5_TYPE:
  21584. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  21585. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  21586. ret = 0;
  21587. break;
  21588. case SPHINCS_SMALL_LEVEL1_TYPE:
  21589. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  21590. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  21591. ret = 0;
  21592. break;
  21593. case SPHINCS_SMALL_LEVEL3_TYPE:
  21594. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  21595. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  21596. ret = 0;
  21597. break;
  21598. case SPHINCS_SMALL_LEVEL5_TYPE:
  21599. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  21600. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  21601. ret = 0;
  21602. break;
  21603. #endif /* HAVE_SPHINCS */
  21604. #endif /* HAVE_PQC */
  21605. case PUBLICKEY_TYPE:
  21606. case ECC_PUBLICKEY_TYPE:
  21607. if (header) *header = BEGIN_PUB_KEY;
  21608. if (footer) *footer = END_PUB_KEY;
  21609. ret = 0;
  21610. break;
  21611. case RSA_PUBLICKEY_TYPE:
  21612. if (header) *header = BEGIN_RSA_PUB;
  21613. if (footer) *footer = END_RSA_PUB;
  21614. ret = 0;
  21615. break;
  21616. #ifndef NO_DH
  21617. case DH_PRIVATEKEY_TYPE:
  21618. #endif
  21619. case PKCS8_PRIVATEKEY_TYPE:
  21620. if (header) *header = BEGIN_PRIV_KEY;
  21621. if (footer) *footer = END_PRIV_KEY;
  21622. ret = 0;
  21623. break;
  21624. case PKCS8_ENC_PRIVATEKEY_TYPE:
  21625. if (header) *header = BEGIN_ENC_PRIV_KEY;
  21626. if (footer) *footer = END_ENC_PRIV_KEY;
  21627. ret = 0;
  21628. break;
  21629. default:
  21630. break;
  21631. }
  21632. return ret;
  21633. }
  21634. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21635. static wcchar kProcTypeHeader = "Proc-Type";
  21636. static wcchar kDecInfoHeader = "DEK-Info";
  21637. #ifdef WOLFSSL_PEM_TO_DER
  21638. #ifndef NO_DES3
  21639. static wcchar kEncTypeDes = "DES-CBC";
  21640. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  21641. #endif
  21642. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21643. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  21644. #endif
  21645. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21646. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  21647. #endif
  21648. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21649. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  21650. #endif
  21651. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  21652. {
  21653. int ret = 0;
  21654. if (info == NULL || cipherInfo == NULL)
  21655. return BAD_FUNC_ARG;
  21656. /* determine cipher information */
  21657. #ifndef NO_DES3
  21658. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  21659. info->cipherType = WC_CIPHER_DES;
  21660. info->keySz = DES_KEY_SIZE;
  21661. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  21662. * block size. */
  21663. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21664. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21665. #else
  21666. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21667. #endif
  21668. }
  21669. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  21670. info->cipherType = WC_CIPHER_DES3;
  21671. info->keySz = DES3_KEY_SIZE;
  21672. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21673. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21674. #else
  21675. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21676. #endif
  21677. }
  21678. else
  21679. #endif /* !NO_DES3 */
  21680. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21681. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  21682. info->cipherType = WC_CIPHER_AES_CBC;
  21683. info->keySz = AES_128_KEY_SIZE;
  21684. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21685. }
  21686. else
  21687. #endif
  21688. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21689. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  21690. info->cipherType = WC_CIPHER_AES_CBC;
  21691. info->keySz = AES_192_KEY_SIZE;
  21692. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21693. }
  21694. else
  21695. #endif
  21696. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21697. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  21698. info->cipherType = WC_CIPHER_AES_CBC;
  21699. info->keySz = AES_256_KEY_SIZE;
  21700. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21701. }
  21702. else
  21703. #endif
  21704. {
  21705. ret = NOT_COMPILED_IN;
  21706. }
  21707. return ret;
  21708. }
  21709. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  21710. size_t bufSz)
  21711. {
  21712. int err = 0;
  21713. const char* bufferStart;
  21714. const char* bufferEnd;
  21715. char* line;
  21716. if (info == NULL || pBuffer == NULL || bufSz == 0)
  21717. return BAD_FUNC_ARG;
  21718. bufferStart = *pBuffer;
  21719. bufferEnd = bufferStart + bufSz;
  21720. /* find encrypted info marker */
  21721. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  21722. min((word32)bufSz, PEM_LINE_LEN));
  21723. if (line != NULL) {
  21724. word32 lineSz;
  21725. char* finish;
  21726. char* start;
  21727. word32 startSz;
  21728. const char* newline = NULL;
  21729. if (line >= bufferEnd) {
  21730. return BUFFER_E;
  21731. }
  21732. lineSz = (word32)(bufferEnd - line);
  21733. /* find DEC-Info marker */
  21734. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  21735. if (start == NULL)
  21736. return BUFFER_E;
  21737. /* skip dec-info and ": " */
  21738. start += XSTRLEN(kDecInfoHeader);
  21739. if (start >= bufferEnd)
  21740. return BUFFER_E;
  21741. if (start[0] == ':') {
  21742. start++;
  21743. if (start >= bufferEnd)
  21744. return BUFFER_E;
  21745. }
  21746. if (start[0] == ' ')
  21747. start++;
  21748. startSz = (word32)(bufferEnd - start);
  21749. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  21750. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  21751. word32 finishSz;
  21752. if (finish >= bufferEnd) {
  21753. return BUFFER_E;
  21754. }
  21755. finishSz = (word32)(bufferEnd - finish);
  21756. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  21757. /* get cipher name */
  21758. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  21759. return BUFFER_E;
  21760. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  21761. return BUFFER_E;
  21762. info->name[finish - start] = '\0'; /* null term */
  21763. /* populate info */
  21764. err = wc_EncryptedInfoGet(info, info->name);
  21765. if (err != 0)
  21766. return err;
  21767. /* get IV */
  21768. if (finishSz < info->ivSz + 1)
  21769. return BUFFER_E;
  21770. if (newline == NULL) {
  21771. newline = XSTRNSTR(finish, "\n", min(finishSz,
  21772. PEM_LINE_LEN));
  21773. }
  21774. if ((newline != NULL) && (newline > finish)) {
  21775. finish++;
  21776. info->ivSz = (word32)(newline - finish);
  21777. if (info->ivSz > IV_SZ)
  21778. return BUFFER_E;
  21779. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  21780. return BUFFER_E;
  21781. info->set = 1;
  21782. }
  21783. else
  21784. return BUFFER_E;
  21785. }
  21786. else
  21787. return BUFFER_E;
  21788. /* eat end of line characters */
  21789. newline = SkipEndOfLineChars(newline, bufferEnd);
  21790. /* return new headerEnd */
  21791. *pBuffer = newline;
  21792. }
  21793. return err;
  21794. }
  21795. #endif /* WOLFSSL_PEM_TO_DER */
  21796. #ifdef WOLFSSL_DER_TO_PEM
  21797. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  21798. {
  21799. if (cipherInfo != NULL) {
  21800. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  21801. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  21802. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  21803. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  21804. /* strncat's src length needs to include the NULL */
  21805. XSTRNCAT(dest, kProcTypeHeader, 10);
  21806. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  21807. XSTRNCAT(dest, kDecInfoHeader, 9);
  21808. XSTRNCAT(dest, ": ", 3);
  21809. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  21810. XSTRNCAT(dest, "\n\n", 4);
  21811. }
  21812. }
  21813. return 0;
  21814. }
  21815. #endif /* WOLFSSL_DER_TO_PEM */
  21816. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21817. #ifdef WOLFSSL_DER_TO_PEM
  21818. /* Used for compatibility API */
  21819. WOLFSSL_ABI
  21820. int wc_DerToPem(const byte* der, word32 derSz,
  21821. byte* output, word32 outSz, int type)
  21822. {
  21823. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  21824. }
  21825. /* convert der buffer to pem into output, can't do inplace, der and output
  21826. need to be different */
  21827. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  21828. byte *cipher_info, int type)
  21829. {
  21830. const char* headerStr = NULL;
  21831. const char* footerStr = NULL;
  21832. #ifdef WOLFSSL_SMALL_STACK
  21833. char* header = NULL;
  21834. char* footer = NULL;
  21835. #else
  21836. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  21837. char footer[MAX_X509_HEADER_SZ];
  21838. #endif
  21839. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  21840. int footerLen = MAX_X509_HEADER_SZ;
  21841. int i;
  21842. int err;
  21843. int outLen; /* return length or error */
  21844. (void)cipher_info;
  21845. if (der == output) /* no in place conversion */
  21846. return BAD_FUNC_ARG;
  21847. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  21848. if (err != 0)
  21849. return err;
  21850. #ifdef WOLFSSL_SMALL_STACK
  21851. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21852. if (header == NULL)
  21853. return MEMORY_E;
  21854. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21855. if (footer == NULL) {
  21856. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21857. return MEMORY_E;
  21858. }
  21859. #endif
  21860. /* build header and footer based on type */
  21861. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  21862. header[headerLen - 2] = 0;
  21863. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  21864. footer[footerLen - 2] = 0;
  21865. /* add new line to end */
  21866. XSTRNCAT(header, "\n", 2);
  21867. XSTRNCAT(footer, "\n", 2);
  21868. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21869. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  21870. if (err != 0) {
  21871. #ifdef WOLFSSL_SMALL_STACK
  21872. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21873. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21874. #endif
  21875. return err;
  21876. }
  21877. #endif
  21878. headerLen = (int)XSTRLEN(header);
  21879. footerLen = (int)XSTRLEN(footer);
  21880. /* if null output and 0 size passed in then return size needed */
  21881. if (!output && outSz == 0) {
  21882. #ifdef WOLFSSL_SMALL_STACK
  21883. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21884. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21885. #endif
  21886. outLen = 0;
  21887. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  21888. != LENGTH_ONLY_E) {
  21889. WOLFSSL_ERROR_VERBOSE(err);
  21890. return err;
  21891. }
  21892. return headerLen + footerLen + outLen;
  21893. }
  21894. if (!der || !output) {
  21895. #ifdef WOLFSSL_SMALL_STACK
  21896. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21897. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21898. #endif
  21899. return BAD_FUNC_ARG;
  21900. }
  21901. /* don't even try if outSz too short */
  21902. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  21903. #ifdef WOLFSSL_SMALL_STACK
  21904. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21905. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21906. #endif
  21907. return BAD_FUNC_ARG;
  21908. }
  21909. /* header */
  21910. XMEMCPY(output, header, (size_t)headerLen);
  21911. i = headerLen;
  21912. #ifdef WOLFSSL_SMALL_STACK
  21913. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21914. #endif
  21915. /* body */
  21916. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  21917. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  21918. #ifdef WOLFSSL_SMALL_STACK
  21919. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21920. #endif
  21921. WOLFSSL_ERROR_VERBOSE(err);
  21922. return err;
  21923. }
  21924. i += outLen;
  21925. /* footer */
  21926. if ( (i + footerLen) > (int)outSz) {
  21927. #ifdef WOLFSSL_SMALL_STACK
  21928. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21929. #endif
  21930. return BAD_FUNC_ARG;
  21931. }
  21932. XMEMCPY(output + i, footer, (size_t)footerLen);
  21933. #ifdef WOLFSSL_SMALL_STACK
  21934. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21935. #endif
  21936. return outLen + headerLen + footerLen;
  21937. }
  21938. #endif /* WOLFSSL_DER_TO_PEM */
  21939. #ifdef WOLFSSL_PEM_TO_DER
  21940. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  21941. info->consumed tracks of PEM bytes consumed in case multiple parts */
  21942. int PemToDer(const unsigned char* buff, long longSz, int type,
  21943. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21944. {
  21945. const char* header = NULL;
  21946. const char* footer = NULL;
  21947. const char* headerEnd;
  21948. const char* footerEnd;
  21949. const char* consumedEnd;
  21950. const char* bufferEnd = (const char*)(buff + longSz);
  21951. long neededSz;
  21952. int ret = 0;
  21953. word32 sz = (word32)longSz;
  21954. int encrypted_key = 0;
  21955. DerBuffer* der;
  21956. word32 algId = 0;
  21957. word32 idx;
  21958. #ifdef OPENSSL_EXTRA
  21959. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21960. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21961. #endif
  21962. WOLFSSL_ENTER("PemToDer");
  21963. /* get PEM header and footer based on type */
  21964. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  21965. if (ret != 0)
  21966. return ret;
  21967. /* map header if not found for type */
  21968. for (;;) {
  21969. headerEnd = XSTRNSTR((char*)buff, header, sz);
  21970. if (headerEnd) {
  21971. break;
  21972. }
  21973. if (type == PRIVATEKEY_TYPE) {
  21974. if (header == BEGIN_RSA_PRIV) {
  21975. header = BEGIN_PRIV_KEY;
  21976. footer = END_PRIV_KEY;
  21977. }
  21978. else if (header == BEGIN_PRIV_KEY) {
  21979. header = BEGIN_ENC_PRIV_KEY;
  21980. footer = END_ENC_PRIV_KEY;
  21981. }
  21982. #ifdef HAVE_ECC
  21983. else if (header == BEGIN_ENC_PRIV_KEY) {
  21984. header = BEGIN_EC_PRIV;
  21985. footer = END_EC_PRIV;
  21986. }
  21987. else if (header == BEGIN_EC_PRIV) {
  21988. header = BEGIN_DSA_PRIV;
  21989. footer = END_DSA_PRIV;
  21990. }
  21991. #endif
  21992. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21993. #ifdef HAVE_ECC
  21994. else if (header == BEGIN_DSA_PRIV) {
  21995. #else
  21996. else if (header == BEGIN_ENC_PRIV_KEY) {
  21997. #endif
  21998. header = BEGIN_EDDSA_PRIV;
  21999. footer = END_EDDSA_PRIV;
  22000. }
  22001. #endif
  22002. else {
  22003. #ifdef WOLF_PRIVATE_KEY_ID
  22004. /* allow loading a public key for use with crypto or PK callbacks */
  22005. type = PUBLICKEY_TYPE;
  22006. header = BEGIN_PUB_KEY;
  22007. footer = END_PUB_KEY;
  22008. #else
  22009. break;
  22010. #endif
  22011. }
  22012. }
  22013. else if (type == PUBLICKEY_TYPE) {
  22014. if (header == BEGIN_PUB_KEY) {
  22015. header = BEGIN_RSA_PUB;
  22016. footer = END_RSA_PUB;
  22017. }
  22018. else {
  22019. break;
  22020. }
  22021. }
  22022. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  22023. else if (type == ECC_PARAM_TYPE) {
  22024. if (header == BEGIN_EC_PARAM) {
  22025. header = BEGIN_EC_PARAM;
  22026. footer = END_EC_PARAM;
  22027. }
  22028. else {
  22029. break;
  22030. }
  22031. }
  22032. #endif
  22033. #ifdef HAVE_CRL
  22034. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  22035. header = BEGIN_X509_CRL;
  22036. footer = END_X509_CRL;
  22037. }
  22038. #endif
  22039. else {
  22040. break;
  22041. }
  22042. }
  22043. if (!headerEnd) {
  22044. #ifdef OPENSSL_EXTRA
  22045. if (type == PRIVATEKEY_TYPE) {
  22046. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  22047. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  22048. if (headerEnd) {
  22049. const char* beginEnd;
  22050. unsigned int endLen;
  22051. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  22052. if (beginEnd >= (char*)buff + sz) {
  22053. return BUFFER_E;
  22054. }
  22055. /* back up to BEGIN_PRIV_KEY_PREFIX */
  22056. while (headerEnd > (char*)buff &&
  22057. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  22058. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  22059. *headerEnd != '\n') {
  22060. headerEnd--;
  22061. }
  22062. if (headerEnd <= (char*)buff ||
  22063. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  22064. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  22065. beginEnd - headerEnd > PEM_LINE_LEN) {
  22066. WOLFSSL_MSG("Couldn't find PEM header");
  22067. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  22068. return ASN_NO_PEM_HEADER;
  22069. }
  22070. /* headerEnd now points to beginning of header */
  22071. XMEMCPY(beginBuf, headerEnd, (size_t)(beginEnd - headerEnd));
  22072. beginBuf[beginEnd - headerEnd] = '\0';
  22073. /* look for matching footer */
  22074. footer = XSTRNSTR(beginEnd,
  22075. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  22076. (unsigned int)((char*)buff + sz - beginEnd));
  22077. if (!footer) {
  22078. WOLFSSL_MSG("Couldn't find PEM footer");
  22079. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  22080. return ASN_NO_PEM_HEADER;
  22081. }
  22082. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  22083. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  22084. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  22085. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  22086. WOLFSSL_MSG("Unexpected footer for PEM");
  22087. return BUFFER_E;
  22088. }
  22089. endLen = (unsigned int)((size_t)(beginEnd - headerEnd) -
  22090. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  22091. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  22092. XMEMCPY(endBuf, footer, (size_t)endLen);
  22093. endBuf[endLen] = '\0';
  22094. header = beginBuf;
  22095. footer = endBuf;
  22096. headerEnd = beginEnd;
  22097. }
  22098. }
  22099. if (!headerEnd) {
  22100. WOLFSSL_MSG("Couldn't find PEM header");
  22101. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  22102. return ASN_NO_PEM_HEADER;
  22103. }
  22104. #else
  22105. WOLFSSL_MSG("Couldn't find PEM header");
  22106. return ASN_NO_PEM_HEADER;
  22107. #endif
  22108. } else {
  22109. headerEnd += XSTRLEN(header);
  22110. }
  22111. /* eat end of line characters */
  22112. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  22113. if (keyFormat) {
  22114. /* keyFormat is Key_Sum enum */
  22115. if (type == PRIVATEKEY_TYPE) {
  22116. #ifndef NO_RSA
  22117. if (header == BEGIN_RSA_PRIV)
  22118. *keyFormat = RSAk;
  22119. #endif
  22120. #ifdef HAVE_ECC
  22121. if (header == BEGIN_EC_PRIV)
  22122. *keyFormat = ECDSAk;
  22123. #endif
  22124. #ifndef NO_DSA
  22125. if (header == BEGIN_DSA_PRIV)
  22126. *keyFormat = DSAk;
  22127. #endif
  22128. }
  22129. #ifdef WOLF_PRIVATE_KEY_ID
  22130. else if (type == PUBLICKEY_TYPE) {
  22131. #ifndef NO_RSA
  22132. if (header == BEGIN_RSA_PUB)
  22133. *keyFormat = RSAk;
  22134. #endif
  22135. }
  22136. #endif
  22137. }
  22138. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22139. if (info) {
  22140. ret = wc_EncryptedInfoParse(info, &headerEnd,
  22141. (size_t)(bufferEnd - headerEnd));
  22142. if (ret < 0)
  22143. return ret;
  22144. if (info->set)
  22145. encrypted_key = 1;
  22146. }
  22147. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  22148. /* find footer */
  22149. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  22150. sz - headerEnd));
  22151. if (!footerEnd) {
  22152. if (info)
  22153. info->consumed = longSz; /* No more certs if no footer */
  22154. return BUFFER_E;
  22155. }
  22156. consumedEnd = footerEnd + XSTRLEN(footer);
  22157. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  22158. /* eat end of line characters */
  22159. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  22160. /* skip possible null term */
  22161. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  22162. consumedEnd++;
  22163. }
  22164. if (info)
  22165. info->consumed = (long)(consumedEnd - (const char*)buff);
  22166. /* set up der buffer */
  22167. neededSz = (long)(footerEnd - headerEnd);
  22168. if (neededSz > (long)sz || neededSz <= 0)
  22169. return BUFFER_E;
  22170. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  22171. if (ret < 0) {
  22172. return ret;
  22173. }
  22174. der = *pDer;
  22175. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  22176. der->buffer, &der->length) < 0) {
  22177. WOLFSSL_ERROR(BUFFER_E);
  22178. return BUFFER_E;
  22179. }
  22180. if ((header == BEGIN_PRIV_KEY
  22181. #ifdef OPENSSL_EXTRA
  22182. || header == beginBuf
  22183. #endif
  22184. #ifdef HAVE_ECC
  22185. || header == BEGIN_EC_PRIV
  22186. #endif
  22187. ) && !encrypted_key)
  22188. {
  22189. /* detect pkcs8 key and get alg type */
  22190. /* keep PKCS8 header */
  22191. idx = 0;
  22192. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  22193. if (ret > 0) {
  22194. if (keyFormat)
  22195. *keyFormat = (int)algId;
  22196. }
  22197. else {
  22198. /* ignore failure here and assume key is not pkcs8 wrapped */
  22199. }
  22200. return 0;
  22201. }
  22202. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22203. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  22204. int passwordSz = NAME_SZ;
  22205. #ifdef WOLFSSL_SMALL_STACK
  22206. char* password = NULL;
  22207. #else
  22208. char password[NAME_SZ];
  22209. #endif
  22210. if (!info || !info->passwd_cb) {
  22211. WOLFSSL_MSG("No password callback set");
  22212. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  22213. return NO_PASSWORD;
  22214. }
  22215. #ifdef WOLFSSL_SMALL_STACK
  22216. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  22217. if (password == NULL) {
  22218. return MEMORY_E;
  22219. }
  22220. #endif
  22221. /* get password */
  22222. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  22223. info->passwd_userdata);
  22224. if (ret >= 0) {
  22225. passwordSz = ret;
  22226. #ifdef WOLFSSL_CHECK_MEM_ZERO
  22227. wc_MemZero_Add("PEM password", password, passwordSz);
  22228. #endif
  22229. /* convert and adjust length */
  22230. if (header == BEGIN_ENC_PRIV_KEY) {
  22231. #ifndef NO_PWDBASED
  22232. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  22233. password, passwordSz);
  22234. if (ret > 0) {
  22235. /* update length by decrypted content */
  22236. der->length = (word32)ret;
  22237. idx = 0;
  22238. /* detect pkcs8 key and get alg type */
  22239. /* keep PKCS8 header */
  22240. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  22241. &algId);
  22242. if (ret >= 0) {
  22243. if (keyFormat)
  22244. *keyFormat = (int)algId;
  22245. ret = 0;
  22246. }
  22247. }
  22248. #else
  22249. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  22250. ret = NOT_COMPILED_IN;
  22251. #endif
  22252. }
  22253. /* decrypt the key */
  22254. else {
  22255. if (passwordSz == 0) {
  22256. /* The key is encrypted but does not have a password */
  22257. WOLFSSL_MSG("No password for encrypted key");
  22258. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  22259. ret = NO_PASSWORD;
  22260. }
  22261. else {
  22262. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  22263. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  22264. defined(HAVE_AES_DECRYPT))) && \
  22265. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  22266. int padVal = 0;
  22267. #endif
  22268. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  22269. (byte*)password, passwordSz, WC_MD5);
  22270. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  22271. #ifndef NO_DES3
  22272. if (info->cipherType == WC_CIPHER_DES3) {
  22273. /* Assuming there is padding:
  22274. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  22275. * (der->length % DES_BLOCK_SIZE) != 0)
  22276. * and assuming the last value signifies the number of
  22277. * padded bytes IE if last value is 0x08 then there are
  22278. * 8 bytes of padding:
  22279. * padVal = der->buffer[der->length-1];
  22280. * then strip this padding before proceeding:
  22281. * der->length -= padVal;
  22282. */
  22283. if (der->length > DES_BLOCK_SIZE &&
  22284. (der->length % DES_BLOCK_SIZE) != 0) {
  22285. padVal = der->buffer[der->length-1];
  22286. if (padVal < DES_BLOCK_SIZE) {
  22287. der->length -= (word32)padVal;
  22288. }
  22289. }
  22290. }
  22291. #endif /* !NO_DES3 */
  22292. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  22293. defined(HAVE_AES_DECRYPT)
  22294. if (info->cipherType == WC_CIPHER_AES_CBC) {
  22295. if (der->length > AES_BLOCK_SIZE) {
  22296. padVal = der->buffer[der->length-1];
  22297. if (padVal <= AES_BLOCK_SIZE) {
  22298. der->length -= (word32)padVal;
  22299. }
  22300. }
  22301. }
  22302. #endif
  22303. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  22304. }
  22305. }
  22306. #ifdef OPENSSL_EXTRA
  22307. if (ret) {
  22308. PEMerr(0, PEM_R_BAD_DECRYPT);
  22309. }
  22310. #endif
  22311. ForceZero(password, (word32)passwordSz);
  22312. }
  22313. #ifdef OPENSSL_EXTRA
  22314. else {
  22315. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  22316. }
  22317. #endif
  22318. #ifdef WOLFSSL_SMALL_STACK
  22319. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  22320. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  22321. wc_MemZero_Check(password, NAME_SZ);
  22322. #endif
  22323. }
  22324. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  22325. return ret;
  22326. }
  22327. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  22328. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  22329. {
  22330. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  22331. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  22332. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  22333. DerBuffer* der = *pDer;
  22334. /* if a PKCS8 key header exists remove it */
  22335. ret = ToTraditional(der->buffer, der->length);
  22336. if (ret > 0) {
  22337. der->length = (word32)ret;
  22338. }
  22339. ret = 0; /* ignore error removing PKCS8 header */
  22340. }
  22341. #endif
  22342. return ret;
  22343. }
  22344. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22345. /* our KeyPemToDer password callback, password in userData */
  22346. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  22347. {
  22348. (void)rw;
  22349. if (userdata == NULL)
  22350. return 0;
  22351. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  22352. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  22353. }
  22354. #endif
  22355. /* Return bytes written to buff or < 0 for error */
  22356. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  22357. unsigned char* buff, int buffSz, const char* pass)
  22358. {
  22359. int ret;
  22360. DerBuffer* der = NULL;
  22361. #ifdef WOLFSSL_SMALL_STACK
  22362. EncryptedInfo* info = NULL;
  22363. #else
  22364. EncryptedInfo info[1];
  22365. #endif
  22366. WOLFSSL_ENTER("wc_KeyPemToDer");
  22367. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22368. WOLFSSL_MSG("Bad pem der args");
  22369. return BAD_FUNC_ARG;
  22370. }
  22371. #ifdef WOLFSSL_SMALL_STACK
  22372. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  22373. DYNAMIC_TYPE_ENCRYPTEDINFO);
  22374. if (info == NULL)
  22375. return MEMORY_E;
  22376. #endif
  22377. XMEMSET(info, 0, sizeof(EncryptedInfo));
  22378. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22379. info->passwd_cb = KeyPemToDerPassCb;
  22380. info->passwd_userdata = (void*)pass;
  22381. #else
  22382. (void)pass;
  22383. #endif
  22384. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  22385. #ifdef WOLFSSL_SMALL_STACK
  22386. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  22387. #endif
  22388. if (ret < 0 || der == NULL) {
  22389. WOLFSSL_MSG("Bad Pem To Der");
  22390. }
  22391. else if (buff == NULL) {
  22392. WOLFSSL_MSG("Return needed der buff length");
  22393. ret = (int)der->length;
  22394. }
  22395. else if (der->length <= (word32)buffSz) {
  22396. XMEMCPY(buff, der->buffer, der->length);
  22397. ret = (int)der->length;
  22398. }
  22399. else {
  22400. WOLFSSL_MSG("Bad der length");
  22401. ret = BAD_FUNC_ARG;
  22402. }
  22403. FreeDer(&der);
  22404. return ret;
  22405. }
  22406. /* Return bytes written to buff or < 0 for error */
  22407. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  22408. unsigned char* buff, int buffSz, int type)
  22409. {
  22410. int ret;
  22411. DerBuffer* der = NULL;
  22412. WOLFSSL_ENTER("wc_CertPemToDer");
  22413. if (pem == NULL || buff == NULL || buffSz <= 0) {
  22414. WOLFSSL_MSG("Bad pem der args");
  22415. return BAD_FUNC_ARG;
  22416. }
  22417. if (type != CERT_TYPE && type != CHAIN_CERT_TYPE && type != CA_TYPE &&
  22418. type != CERTREQ_TYPE) {
  22419. WOLFSSL_MSG("Bad cert type");
  22420. return BAD_FUNC_ARG;
  22421. }
  22422. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  22423. if (ret < 0 || der == NULL) {
  22424. WOLFSSL_MSG("Bad Pem To Der");
  22425. }
  22426. else {
  22427. if (der->length <= (word32)buffSz) {
  22428. XMEMCPY(buff, der->buffer, der->length);
  22429. ret = (int)der->length;
  22430. }
  22431. else {
  22432. WOLFSSL_MSG("Bad der length");
  22433. ret = BAD_FUNC_ARG;
  22434. }
  22435. }
  22436. FreeDer(&der);
  22437. return ret;
  22438. }
  22439. #endif /* WOLFSSL_PEM_TO_DER */
  22440. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  22441. #ifdef WOLFSSL_PEM_TO_DER
  22442. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22443. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  22444. zero for error */
  22445. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  22446. unsigned char* buff, int buffSz)
  22447. {
  22448. int ret;
  22449. DerBuffer* der = NULL;
  22450. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  22451. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22452. WOLFSSL_MSG("Bad pem der args");
  22453. return BAD_FUNC_ARG;
  22454. }
  22455. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  22456. if (ret < 0 || der == NULL) {
  22457. WOLFSSL_MSG("Bad Pem To Der");
  22458. }
  22459. else if (buff == NULL) {
  22460. WOLFSSL_MSG("Return needed der buff length");
  22461. ret = (int)der->length;
  22462. }
  22463. else if (der->length <= (word32)buffSz) {
  22464. XMEMCPY(buff, der->buffer, der->length);
  22465. ret = (int)der->length;
  22466. }
  22467. else {
  22468. WOLFSSL_MSG("Bad der length");
  22469. ret = BAD_FUNC_ARG;
  22470. }
  22471. FreeDer(&der);
  22472. return ret;
  22473. }
  22474. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22475. #endif /* WOLFSSL_PEM_TO_DER */
  22476. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  22477. #ifdef WOLFSSL_CERT_GEN
  22478. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  22479. {
  22480. #ifndef WOLFSSL_SMALL_STACK
  22481. byte staticBuffer[FILE_BUFFER_SIZE];
  22482. #endif
  22483. byte* fileBuf = NULL;
  22484. int ret = 0;
  22485. XFILE file = XBADFILE;
  22486. int dynamic = 0;
  22487. long sz = 0;
  22488. WOLFSSL_ENTER("wc_PemCertToDer");
  22489. if (fileName == NULL) {
  22490. ret = BAD_FUNC_ARG;
  22491. }
  22492. else {
  22493. file = XFOPEN(fileName, "rb");
  22494. if (file == XBADFILE) {
  22495. ret = IO_FAILED_E;
  22496. }
  22497. }
  22498. if (ret == 0) {
  22499. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22500. ret = IO_FAILED_E;
  22501. }
  22502. }
  22503. if (ret == 0) {
  22504. sz = XFTELL(file);
  22505. if (sz <= 0) {
  22506. ret = IO_FAILED_E;
  22507. }
  22508. }
  22509. if (ret == 0) {
  22510. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22511. ret = IO_FAILED_E;
  22512. }
  22513. }
  22514. if (ret == 0) {
  22515. #ifndef WOLFSSL_SMALL_STACK
  22516. if (sz <= (long)sizeof(staticBuffer))
  22517. fileBuf = staticBuffer;
  22518. else
  22519. #endif
  22520. {
  22521. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22522. if (fileBuf == NULL)
  22523. ret = MEMORY_E;
  22524. else
  22525. dynamic = 1;
  22526. }
  22527. }
  22528. if (ret == 0) {
  22529. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22530. ret = IO_FAILED_E;
  22531. }
  22532. else {
  22533. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  22534. }
  22535. }
  22536. if (file != XBADFILE)
  22537. XFCLOSE(file);
  22538. if (dynamic)
  22539. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22540. return ret;
  22541. }
  22542. /* load pem cert from file into der buffer, return der size or error */
  22543. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  22544. {
  22545. int ret;
  22546. DerBuffer* converted = NULL;
  22547. ret = wc_PemCertToDer_ex(fileName, &converted);
  22548. if (ret == 0) {
  22549. if (converted->length < (word32)derSz) {
  22550. XMEMCPY(derBuf, converted->buffer, converted->length);
  22551. ret = (int)converted->length;
  22552. }
  22553. else
  22554. ret = BUFFER_E;
  22555. FreeDer(&converted);
  22556. }
  22557. return ret;
  22558. }
  22559. #endif /* WOLFSSL_CERT_GEN */
  22560. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22561. /* load pem public key from file into der buffer, return der size or error */
  22562. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  22563. {
  22564. #ifndef WOLFSSL_SMALL_STACK
  22565. byte staticBuffer[FILE_BUFFER_SIZE];
  22566. #endif
  22567. byte* fileBuf = NULL;
  22568. int dynamic = 0;
  22569. int ret = 0;
  22570. long sz = 0;
  22571. XFILE file = XBADFILE;
  22572. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  22573. if (fileName == NULL) {
  22574. ret = BAD_FUNC_ARG;
  22575. }
  22576. else {
  22577. file = XFOPEN(fileName, "rb");
  22578. if (file == XBADFILE) {
  22579. ret = IO_FAILED_E;
  22580. }
  22581. }
  22582. if (ret == 0) {
  22583. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22584. ret = IO_FAILED_E;
  22585. }
  22586. }
  22587. if (ret == 0) {
  22588. sz = XFTELL(file);
  22589. if (sz <= 0) {
  22590. ret = IO_FAILED_E;
  22591. }
  22592. }
  22593. if (ret == 0) {
  22594. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22595. ret = IO_FAILED_E;
  22596. }
  22597. }
  22598. if (ret == 0) {
  22599. #ifndef WOLFSSL_SMALL_STACK
  22600. if (sz <= (long)sizeof(staticBuffer))
  22601. fileBuf = staticBuffer;
  22602. else
  22603. #endif
  22604. {
  22605. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22606. if (fileBuf == NULL)
  22607. ret = MEMORY_E;
  22608. else
  22609. dynamic = 1;
  22610. }
  22611. }
  22612. if (ret == 0) {
  22613. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22614. ret = BUFFER_E;
  22615. }
  22616. else {
  22617. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  22618. 0, NULL, NULL);
  22619. }
  22620. }
  22621. if (file != XBADFILE)
  22622. XFCLOSE(file);
  22623. if (dynamic)
  22624. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22625. return ret;
  22626. }
  22627. /* load pem public key from file into der buffer, return der size or error */
  22628. int wc_PemPubKeyToDer(const char* fileName,
  22629. unsigned char* derBuf, int derSz)
  22630. {
  22631. int ret;
  22632. DerBuffer* converted = NULL;
  22633. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  22634. if (ret == 0) {
  22635. if (converted->length < (word32)derSz) {
  22636. XMEMCPY(derBuf, converted->buffer, converted->length);
  22637. ret = (int)converted->length;
  22638. }
  22639. else
  22640. ret = BUFFER_E;
  22641. FreeDer(&converted);
  22642. }
  22643. return ret;
  22644. }
  22645. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22646. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  22647. /* Get public key in DER format from a populated DecodedCert struct.
  22648. *
  22649. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  22650. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  22651. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  22652. * wc_InitDecodedCert().
  22653. *
  22654. * cert - populated DecodedCert struct holding X.509 certificate
  22655. * derKey - output buffer to place DER/ASN.1 encoded public key
  22656. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  22657. * on return. If derKey is passed in as NULL, derKeySz
  22658. * will be set to required buffer size for public key
  22659. * and LENGTH_ONLY_E will be returned from function.
  22660. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  22661. * if derKey is NULL and returning length only.
  22662. */
  22663. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  22664. byte* derKey, word32* derKeySz)
  22665. {
  22666. int ret = 0;
  22667. /* derKey may be NULL to return length only */
  22668. if (cert == NULL || derKeySz == NULL ||
  22669. (derKey != NULL && *derKeySz == 0)) {
  22670. return BAD_FUNC_ARG;
  22671. }
  22672. if (cert->publicKey == NULL) {
  22673. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  22674. return BAD_FUNC_ARG;
  22675. }
  22676. /* if derKey is NULL, return required output buffer size in derKeySz */
  22677. if (derKey == NULL) {
  22678. *derKeySz = cert->pubKeySize;
  22679. ret = LENGTH_ONLY_E;
  22680. }
  22681. if (ret == 0) {
  22682. if (cert->pubKeySize > *derKeySz) {
  22683. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  22684. ret = BAD_FUNC_ARG;
  22685. }
  22686. else {
  22687. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  22688. *derKeySz = cert->pubKeySize;
  22689. }
  22690. }
  22691. return ret;
  22692. }
  22693. #ifdef WOLFSSL_FPKI
  22694. /* Search through list for first matching alt name of the same type
  22695. * If 'current' is null then the search starts at the head of the list
  22696. * otherwise the search starts from the node after 'current' alt name.
  22697. * Returns 0 on success
  22698. */
  22699. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  22700. DNS_entry* current)
  22701. {
  22702. DNS_entry* entry;
  22703. if (current == NULL) {
  22704. entry = cert->altNames;
  22705. }
  22706. else {
  22707. entry = current->next;
  22708. }
  22709. /* cycle through alt names to check for needed types */
  22710. while (entry != NULL) {
  22711. if (entry->type == nameType) {
  22712. break;
  22713. }
  22714. entry = entry->next;
  22715. }
  22716. return entry;
  22717. }
  22718. /* returns 0 on success */
  22719. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  22720. {
  22721. int ret = ALT_NAME_E;
  22722. DNS_entry* id = NULL;
  22723. do {
  22724. id = FindAltName(cert, ASN_URI_TYPE, id);
  22725. if (id != NULL) {
  22726. /* check if URI string matches expected format for UUID */
  22727. if (id->len != DEFAULT_UUID_SZ) {
  22728. continue; /* size not right not a UUID URI */
  22729. }
  22730. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  22731. continue; /* beginning text not right for a UUID URI */
  22732. }
  22733. if (uuid == NULL) {
  22734. *uuidSz = (word32)id->len;
  22735. return LENGTH_ONLY_E;
  22736. }
  22737. if ((int)*uuidSz < id->len) {
  22738. return BUFFER_E;
  22739. }
  22740. XMEMCPY(uuid, id->name, (size_t)id->len);
  22741. ret = 0; /* success */
  22742. break;
  22743. }
  22744. } while (id != NULL);
  22745. return ret;
  22746. }
  22747. /* returns 0 on success */
  22748. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  22749. {
  22750. int ret = ALT_NAME_E;
  22751. DNS_entry* id = NULL;
  22752. do {
  22753. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  22754. if (id != NULL && id->oidSum == FASCN_OID) {
  22755. if (fascn == NULL) {
  22756. *fascnSz = (word32)id->len;
  22757. return LENGTH_ONLY_E;
  22758. }
  22759. if ((int)*fascnSz < id->len) {
  22760. return BUFFER_E;
  22761. }
  22762. XMEMCPY(fascn, id->name, (size_t)id->len);
  22763. ret = 0; /* success */
  22764. }
  22765. } while (id != NULL);
  22766. return ret;
  22767. }
  22768. #endif /* WOLFSSL_FPKI */
  22769. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  22770. defined(WOLFSSL_KCAPI_RSA) || \
  22771. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  22772. /* USER RSA ifdef portions used instead of refactor in consideration for
  22773. possible fips build */
  22774. /* Encode a public RSA key to output.
  22775. *
  22776. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22777. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22778. *
  22779. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22780. * (RSAPublicKey).
  22781. *
  22782. * @param [out] output Buffer to put encoded data in.
  22783. * @param [in] key RSA key object.
  22784. * @param [in] outLen Size of the output buffer in bytes.
  22785. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22786. * @return Size of encoded data in bytes on success.
  22787. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  22788. * minimum length (5 bytes).
  22789. * @return MEMORY_E when dynamic memory allocation failed.
  22790. */
  22791. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  22792. int with_header)
  22793. {
  22794. #ifndef WOLFSSL_ASN_TEMPLATE
  22795. int nSz, eSz;
  22796. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  22797. byte seq[MAX_SEQ_SZ];
  22798. byte headSeq[MAX_SEQ_SZ];
  22799. byte bitString[1 + MAX_LENGTH_SZ + 1];
  22800. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  22801. if (key == NULL) {
  22802. return BAD_FUNC_ARG;
  22803. }
  22804. #ifdef HAVE_USER_RSA
  22805. nSz = SetASNIntRSA(key->n, NULL);
  22806. #else
  22807. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  22808. #endif
  22809. if (nSz < 0)
  22810. return nSz;
  22811. #ifdef HAVE_USER_RSA
  22812. eSz = SetASNIntRSA(key->e, NULL);
  22813. #else
  22814. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  22815. #endif
  22816. if (eSz < 0)
  22817. return eSz;
  22818. seqSz = SetSequence((word32)(nSz + eSz), seq);
  22819. /* headers */
  22820. if (with_header) {
  22821. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  22822. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  22823. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  22824. headSeq);
  22825. }
  22826. /* if getting length only */
  22827. if (output == NULL) {
  22828. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  22829. }
  22830. /* check output size */
  22831. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  22832. return BUFFER_E;
  22833. }
  22834. /* write output */
  22835. idx = 0;
  22836. if (with_header) {
  22837. /* header size */
  22838. XMEMCPY(output + idx, headSeq, headSz);
  22839. idx += headSz;
  22840. /* algo */
  22841. XMEMCPY(output + idx, algo, algoSz);
  22842. idx += algoSz;
  22843. /* bit string */
  22844. XMEMCPY(output + idx, bitString, bitStringSz);
  22845. idx += bitStringSz;
  22846. }
  22847. /* seq */
  22848. XMEMCPY(output + idx, seq, seqSz);
  22849. idx += seqSz;
  22850. /* n */
  22851. #ifdef HAVE_USER_RSA
  22852. nSz = SetASNIntRSA(key->n, output + idx);
  22853. #else
  22854. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  22855. #endif
  22856. idx += (word32)nSz;
  22857. /* e */
  22858. #ifdef HAVE_USER_RSA
  22859. eSz = SetASNIntRSA(key->e, output + idx);
  22860. #else
  22861. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  22862. #endif
  22863. idx += (word32)eSz;
  22864. return (int)idx;
  22865. #else
  22866. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  22867. int sz = 0;
  22868. int ret = 0;
  22869. int o = 0;
  22870. /* Check parameter validity. */
  22871. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  22872. ret = BAD_FUNC_ARG;
  22873. }
  22874. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  22875. if (ret == 0) {
  22876. if (!with_header) {
  22877. /* Start encoding with items after header. */
  22878. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  22879. }
  22880. /* Set OID for RSA key. */
  22881. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  22882. #ifdef WC_RSA_PSS
  22883. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  22884. #endif
  22885. /* Set public key mp_ints. */
  22886. #ifdef HAVE_USER_RSA
  22887. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  22888. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  22889. #else
  22890. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  22891. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  22892. #endif
  22893. /* Calculate size of RSA public key. */
  22894. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22895. (int)rsaPublicKeyASN_Length - o, &sz);
  22896. }
  22897. /* Check output buffer is big enough for encoding. */
  22898. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22899. ret = BUFFER_E;
  22900. }
  22901. if ((ret == 0) && (output != NULL)) {
  22902. /* Encode RSA public key. */
  22903. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22904. (int)rsaPublicKeyASN_Length - o, output);
  22905. }
  22906. if (ret == 0) {
  22907. /* Return size of encoding. */
  22908. ret = sz;
  22909. }
  22910. FREE_ASNSETDATA(dataASN, key->heap);
  22911. return ret;
  22912. #endif /* WOLFSSL_ASN_TEMPLATE */
  22913. }
  22914. /* Calculate size of encoded public RSA key in bytes.
  22915. *
  22916. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22917. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22918. *
  22919. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22920. * (RSAPublicKey).
  22921. *
  22922. * @param [in] key RSA key object.
  22923. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22924. * @return Size of encoded data in bytes on success.
  22925. * @return BAD_FUNC_ARG when key is NULL.
  22926. * @return MEMORY_E when dynamic memory allocation failed.
  22927. */
  22928. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  22929. {
  22930. return SetRsaPublicKey(NULL, key, 0, with_header);
  22931. }
  22932. /* Encode public RSA key in DER format.
  22933. *
  22934. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22935. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22936. *
  22937. * @param [in] key RSA key object.
  22938. * @param [out] output Buffer to put encoded data in.
  22939. * @param [in] inLen Size of buffer in bytes.
  22940. * @return Size of encoded data in bytes on success.
  22941. * @return BAD_FUNC_ARG when key or output is NULL.
  22942. * @return MEMORY_E when dynamic memory allocation failed.
  22943. */
  22944. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  22945. {
  22946. return SetRsaPublicKey(output, key, (int)inLen, 1);
  22947. }
  22948. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  22949. * seq + n + e is returned in ASN.1 DER format */
  22950. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  22951. int with_header)
  22952. {
  22953. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  22954. }
  22955. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  22956. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  22957. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  22958. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  22959. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  22960. /* Encode private RSA key in DER format.
  22961. *
  22962. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  22963. *
  22964. * @param [in] key RSA key object.
  22965. * @param [out] output Buffer to put encoded data in.
  22966. * @param [in] inLen Size of buffer in bytes.
  22967. * @return Size of encoded data in bytes on success.
  22968. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22969. * @return MEMORY_E when dynamic memory allocation failed.
  22970. */
  22971. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22972. {
  22973. #ifndef WOLFSSL_ASN_TEMPLATE
  22974. int ret = 0, i;
  22975. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
  22976. word32 sizes[RSA_INTS];
  22977. byte seq[MAX_SEQ_SZ];
  22978. byte ver[MAX_VERSION_SZ];
  22979. byte* tmps[RSA_INTS];
  22980. if (key == NULL)
  22981. return BAD_FUNC_ARG;
  22982. if (key->type != RSA_PRIVATE)
  22983. return BAD_FUNC_ARG;
  22984. for (i = 0; i < RSA_INTS; i++)
  22985. tmps[i] = NULL;
  22986. /* write all big ints from key to DER tmps */
  22987. for (i = 0; i < RSA_INTS; i++) {
  22988. mp_int* keyInt = GetRsaInt(key, i);
  22989. int mpSz;
  22990. word32 rawLen;
  22991. ret = mp_unsigned_bin_size(keyInt);
  22992. if (ret < 0)
  22993. return ret;
  22994. rawLen = (word32)ret + 1;
  22995. ret = 0;
  22996. if (output != NULL) {
  22997. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22998. DYNAMIC_TYPE_RSA);
  22999. if (tmps[i] == NULL) {
  23000. ret = MEMORY_E;
  23001. break;
  23002. }
  23003. }
  23004. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  23005. if (mpSz < 0) {
  23006. ret = mpSz;
  23007. break;
  23008. }
  23009. sizes[i] = (word32)mpSz;
  23010. intTotalLen += (word32)mpSz;
  23011. }
  23012. if (ret == 0) {
  23013. /* make headers */
  23014. ret = SetMyVersion(0, ver, FALSE);
  23015. }
  23016. if (ret >= 0) {
  23017. verSz = (word32)ret;
  23018. ret = 0;
  23019. seqSz = SetSequence(verSz + intTotalLen, seq);
  23020. outLen = seqSz + verSz + intTotalLen;
  23021. if (output != NULL && outLen > inLen)
  23022. ret = BUFFER_E;
  23023. }
  23024. if (ret == 0 && output != NULL) {
  23025. word32 j;
  23026. /* write to output */
  23027. XMEMCPY(output, seq, seqSz);
  23028. j = seqSz;
  23029. XMEMCPY(output + j, ver, verSz);
  23030. j += verSz;
  23031. for (i = 0; i < RSA_INTS; i++) {
  23032. XMEMCPY(output + j, tmps[i], sizes[i]);
  23033. j += sizes[i];
  23034. }
  23035. }
  23036. for (i = 0; i < RSA_INTS; i++) {
  23037. if (tmps[i])
  23038. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  23039. }
  23040. if (ret == 0)
  23041. ret = (int)outLen;
  23042. return ret;
  23043. #else
  23044. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  23045. int i;
  23046. int sz = 0;
  23047. int ret = 0;
  23048. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  23049. ret = BAD_FUNC_ARG;
  23050. }
  23051. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  23052. if (ret == 0) {
  23053. /* Set the version. */
  23054. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  23055. /* Set all the mp_ints in private key. */
  23056. for (i = 0; i < RSA_INTS; i++) {
  23057. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  23058. }
  23059. /* Calculate size of RSA private key encoding. */
  23060. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  23061. }
  23062. /* Check output buffer has enough space for encoding. */
  23063. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  23064. ret = BAD_FUNC_ARG;
  23065. }
  23066. if ((ret == 0) && (output != NULL)) {
  23067. /* Encode RSA private key. */
  23068. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  23069. }
  23070. if (ret == 0) {
  23071. /* Return size of encoding. */
  23072. ret = sz;
  23073. }
  23074. FREE_ASNSETDATA(dataASN, key->heap);
  23075. return ret;
  23076. #endif
  23077. }
  23078. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  23079. #ifdef WOLFSSL_CERT_GEN
  23080. /* Initialize and Set Certificate defaults:
  23081. version = 3 (0x2)
  23082. serial = 0
  23083. sigType = SHA_WITH_RSA
  23084. issuer = blank
  23085. daysValid = 500
  23086. selfSigned = 1 (true) use subject as issuer
  23087. subject = blank
  23088. */
  23089. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  23090. {
  23091. #ifdef WOLFSSL_MULTI_ATTRIB
  23092. int i = 0;
  23093. #endif
  23094. if (cert == NULL) {
  23095. return BAD_FUNC_ARG;
  23096. }
  23097. XMEMSET(cert, 0, sizeof(Cert));
  23098. cert->version = 2; /* version 3 is hex 2 */
  23099. #ifndef NO_SHA
  23100. cert->sigType = CTC_SHAwRSA;
  23101. #elif !defined(NO_SHA256)
  23102. cert->sigType = CTC_SHA256wRSA;
  23103. #else
  23104. cert->sigType = 0;
  23105. #endif
  23106. cert->daysValid = 500;
  23107. cert->selfSigned = 1;
  23108. cert->keyType = RSA_KEY;
  23109. cert->issuer.countryEnc = CTC_PRINTABLE;
  23110. cert->issuer.stateEnc = CTC_UTF8;
  23111. cert->issuer.streetEnc = CTC_UTF8;
  23112. cert->issuer.localityEnc = CTC_UTF8;
  23113. cert->issuer.surEnc = CTC_UTF8;
  23114. #ifdef WOLFSSL_CERT_NAME_ALL
  23115. cert->issuer.givenNameEnc = CTC_UTF8;
  23116. cert->issuer.initialsEnc = CTC_UTF8;
  23117. cert->issuer.dnQualifierEnc = CTC_UTF8;
  23118. cert->issuer.dnNameEnc = CTC_UTF8;
  23119. #endif
  23120. cert->issuer.orgEnc = CTC_UTF8;
  23121. cert->issuer.unitEnc = CTC_UTF8;
  23122. cert->issuer.commonNameEnc = CTC_UTF8;
  23123. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  23124. cert->issuer.userIdEnc = CTC_UTF8;
  23125. cert->issuer.postalCodeEnc = CTC_UTF8;
  23126. #ifdef WOLFSSL_CERT_EXT
  23127. cert->issuer.busCatEnc = CTC_UTF8;
  23128. cert->issuer.joiCEnc = CTC_UTF8;
  23129. cert->issuer.joiStEnc = CTC_UTF8;
  23130. #endif
  23131. cert->subject.countryEnc = CTC_PRINTABLE;
  23132. cert->subject.stateEnc = CTC_UTF8;
  23133. cert->subject.streetEnc = CTC_UTF8;
  23134. cert->subject.localityEnc = CTC_UTF8;
  23135. cert->subject.surEnc = CTC_UTF8;
  23136. #ifdef WOLFSSL_CERT_NAME_ALL
  23137. cert->subject.givenNameEnc = CTC_UTF8;
  23138. cert->subject.initialsEnc = CTC_UTF8;
  23139. cert->subject.dnQualifierEnc = CTC_UTF8;
  23140. cert->subject.dnNameEnc = CTC_UTF8;
  23141. #endif
  23142. cert->subject.orgEnc = CTC_UTF8;
  23143. cert->subject.unitEnc = CTC_UTF8;
  23144. cert->subject.commonNameEnc = CTC_UTF8;
  23145. cert->subject.serialDevEnc = CTC_PRINTABLE;
  23146. cert->subject.userIdEnc = CTC_UTF8;
  23147. cert->subject.postalCodeEnc = CTC_UTF8;
  23148. #ifdef WOLFSSL_CERT_EXT
  23149. cert->subject.busCatEnc = CTC_UTF8;
  23150. cert->subject.joiCEnc = CTC_UTF8;
  23151. cert->subject.joiStEnc = CTC_UTF8;
  23152. #endif
  23153. #ifdef WOLFSSL_MULTI_ATTRIB
  23154. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  23155. cert->issuer.name[i].type = CTC_UTF8;
  23156. cert->subject.name[i].type = CTC_UTF8;
  23157. }
  23158. #endif /* WOLFSSL_MULTI_ATTRIB */
  23159. cert->heap = heap;
  23160. (void)devId; /* future */
  23161. return 0;
  23162. }
  23163. WOLFSSL_ABI
  23164. int wc_InitCert(Cert* cert)
  23165. {
  23166. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  23167. }
  23168. WOLFSSL_ABI
  23169. Cert* wc_CertNew(void* heap)
  23170. {
  23171. Cert* certNew;
  23172. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  23173. if (certNew) {
  23174. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  23175. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  23176. certNew = NULL;
  23177. }
  23178. }
  23179. return certNew;
  23180. }
  23181. WOLFSSL_ABI
  23182. void wc_CertFree(Cert* cert)
  23183. {
  23184. if (cert) {
  23185. void* heap = cert->heap;
  23186. ForceZero(cert, sizeof(Cert));
  23187. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  23188. (void)heap;
  23189. }
  23190. }
  23191. /* DER encoded x509 Certificate */
  23192. typedef struct DerCert {
  23193. byte size[MAX_LENGTH_SZ]; /* length encoded */
  23194. byte version[MAX_VERSION_SZ]; /* version encoded */
  23195. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  23196. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  23197. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  23198. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  23199. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  23200. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  23201. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  23202. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  23203. #ifdef WOLFSSL_CERT_EXT
  23204. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  23205. byte akid[MAX_KID_SZ
  23206. #ifdef WOLFSSL_AKID_NAME
  23207. + sizeof(CertName) + CTC_SERIAL_SIZE
  23208. #endif
  23209. ]; /* Authority Key Identifier extension */
  23210. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  23211. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  23212. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23213. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  23214. #endif
  23215. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  23216. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  23217. #endif
  23218. #ifdef WOLFSSL_CERT_REQ
  23219. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  23220. #ifdef WOLFSSL_CUSTOM_OID
  23221. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  23222. #endif
  23223. #endif
  23224. #ifdef WOLFSSL_ALT_NAMES
  23225. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  23226. #endif
  23227. int sizeSz; /* encoded size length */
  23228. int versionSz; /* encoded version length */
  23229. int serialSz; /* encoded serial length */
  23230. int sigAlgoSz; /* encoded sig algo length */
  23231. int issuerSz; /* encoded issuer length */
  23232. int subjectSz; /* encoded subject length */
  23233. int validitySz; /* encoded validity length */
  23234. int publicKeySz; /* encoded public key length */
  23235. int caSz; /* encoded CA extension length */
  23236. #ifdef WOLFSSL_CERT_EXT
  23237. int skidSz; /* encoded SKID extension length */
  23238. int akidSz; /* encoded SKID extension length */
  23239. int keyUsageSz; /* encoded KeyUsage extension length */
  23240. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  23241. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23242. int nsCertTypeSz; /* encoded Netscape Certificate Type
  23243. * extension length */
  23244. #endif
  23245. int certPoliciesSz; /* encoded CertPolicies extension length*/
  23246. int crlInfoSz; /* encoded CRL Dist Points length */
  23247. #endif
  23248. #ifdef WOLFSSL_ALT_NAMES
  23249. int altNamesSz; /* encoded AltNames extension length */
  23250. #endif
  23251. int extensionsSz; /* encoded extensions total length */
  23252. int total; /* total encoded lengths */
  23253. #ifdef WOLFSSL_CERT_REQ
  23254. int attribSz;
  23255. #ifdef WOLFSSL_CUSTOM_OID
  23256. int extCustomSz;
  23257. #endif
  23258. #endif
  23259. } DerCert;
  23260. #ifdef WOLFSSL_CERT_REQ
  23261. #ifndef WOLFSSL_ASN_TEMPLATE
  23262. /* Write a set header to output */
  23263. static word32 SetPrintableString(word32 len, byte* output)
  23264. {
  23265. output[0] = ASN_PRINTABLE_STRING;
  23266. return SetLength(len, output + 1) + 1;
  23267. }
  23268. static word32 SetUTF8String(word32 len, byte* output)
  23269. {
  23270. output[0] = ASN_UTF8STRING;
  23271. return SetLength(len, output + 1) + 1;
  23272. }
  23273. #endif
  23274. #endif /* WOLFSSL_CERT_REQ */
  23275. #ifndef WOLFSSL_CERT_GEN_CACHE
  23276. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  23277. static
  23278. #endif
  23279. WOLFSSL_ABI
  23280. void wc_SetCert_Free(Cert* cert)
  23281. {
  23282. if (cert != NULL) {
  23283. cert->der = NULL;
  23284. if (cert->decodedCert) {
  23285. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  23286. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  23287. cert->decodedCert = NULL;
  23288. }
  23289. }
  23290. }
  23291. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  23292. int devId)
  23293. {
  23294. int ret;
  23295. if (cert == NULL) {
  23296. ret = BAD_FUNC_ARG;
  23297. }
  23298. else {
  23299. /* Allocate DecodedCert struct and Zero */
  23300. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  23301. DYNAMIC_TYPE_DCERT);
  23302. if (cert->decodedCert == NULL) {
  23303. ret = MEMORY_E;
  23304. }
  23305. else {
  23306. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  23307. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  23308. cert->heap, devId);
  23309. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  23310. CERT_TYPE, 0, NULL);
  23311. if (ret >= 0) {
  23312. cert->der = (byte*)der;
  23313. }
  23314. else {
  23315. wc_SetCert_Free(cert);
  23316. }
  23317. }
  23318. }
  23319. return ret;
  23320. }
  23321. #endif /* WOLFSSL_CERT_GEN */
  23322. #ifdef WOLFSSL_CERT_GEN
  23323. #ifndef NO_ASN_TIME
  23324. static WC_INLINE byte itob(int number)
  23325. {
  23326. return (byte)number + 0x30;
  23327. }
  23328. /* write time to output, format */
  23329. static void SetTime(struct tm* date, byte* output)
  23330. {
  23331. int i = 0;
  23332. output[i++] = itob((date->tm_year % 10000) / 1000);
  23333. output[i++] = itob((date->tm_year % 1000) / 100);
  23334. output[i++] = itob((date->tm_year % 100) / 10);
  23335. output[i++] = itob( date->tm_year % 10);
  23336. output[i++] = itob(date->tm_mon / 10);
  23337. output[i++] = itob(date->tm_mon % 10);
  23338. output[i++] = itob(date->tm_mday / 10);
  23339. output[i++] = itob(date->tm_mday % 10);
  23340. output[i++] = itob(date->tm_hour / 10);
  23341. output[i++] = itob(date->tm_hour % 10);
  23342. output[i++] = itob(date->tm_min / 10);
  23343. output[i++] = itob(date->tm_min % 10);
  23344. output[i++] = itob(date->tm_sec / 10);
  23345. output[i++] = itob(date->tm_sec % 10);
  23346. output[i] = 'Z'; /* Zulu profile */
  23347. }
  23348. #endif
  23349. #ifndef WOLFSSL_ASN_TEMPLATE
  23350. /* Copy Dates from cert, return bytes written */
  23351. static int CopyValidity(byte* output, Cert* cert)
  23352. {
  23353. word32 seqSz;
  23354. WOLFSSL_ENTER("CopyValidity");
  23355. /* headers and output */
  23356. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  23357. output);
  23358. if (output) {
  23359. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  23360. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  23361. (size_t)cert->afterDateSz);
  23362. }
  23363. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  23364. }
  23365. #endif /* !WOLFSSL_ASN_TEMPLATE */
  23366. /* Simple name OID size. */
  23367. #define NAME_OID_SZ 3
  23368. /* Domain name OIDs. */
  23369. static const byte nameOid[][NAME_OID_SZ] = {
  23370. { 0x55, 0x04, ASN_COUNTRY_NAME },
  23371. { 0x55, 0x04, ASN_STATE_NAME },
  23372. { 0x55, 0x04, ASN_STREET_ADDR },
  23373. { 0x55, 0x04, ASN_LOCALITY_NAME },
  23374. #ifdef WOLFSSL_CERT_NAME_ALL
  23375. { 0x55, 0x04, ASN_NAME },
  23376. { 0x55, 0x04, ASN_GIVEN_NAME },
  23377. { 0x55, 0x04, ASN_INITIALS },
  23378. { 0x55, 0x04, ASN_DNQUALIFIER },
  23379. #endif
  23380. { 0x55, 0x04, ASN_SUR_NAME },
  23381. { 0x55, 0x04, ASN_ORG_NAME },
  23382. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  23383. /* list all DC values before OUs */
  23384. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  23385. { 0x55, 0x04, ASN_COMMON_NAME },
  23386. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  23387. #ifdef WOLFSSL_CERT_EXT
  23388. { 0x55, 0x04, ASN_BUS_CAT },
  23389. #endif
  23390. { 0x55, 0x04, ASN_POSTAL_CODE },
  23391. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  23392. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  23393. #ifdef WOLFSSL_CUSTOM_OID
  23394. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  23395. #endif
  23396. };
  23397. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  23398. /* Get ASN Name from index */
  23399. byte GetCertNameId(int idx)
  23400. {
  23401. if (idx < NAME_ENTRIES)
  23402. return nameOid[idx][2];
  23403. return 0;
  23404. }
  23405. /* Get Which Name from index */
  23406. const char* GetOneCertName(CertName* name, int idx)
  23407. {
  23408. byte type = GetCertNameId(idx);
  23409. switch (type) {
  23410. case ASN_COUNTRY_NAME:
  23411. return name->country;
  23412. case ASN_STATE_NAME:
  23413. return name->state;
  23414. case ASN_STREET_ADDR:
  23415. return name->street;
  23416. case ASN_LOCALITY_NAME:
  23417. return name->locality;
  23418. #ifdef WOLFSSL_CERT_NAME_ALL
  23419. case ASN_NAME:
  23420. return name->dnName;
  23421. case ASN_GIVEN_NAME:
  23422. return name->givenName;
  23423. case ASN_INITIALS:
  23424. return name->initials;
  23425. case ASN_DNQUALIFIER:
  23426. return name->dnQualifier;
  23427. #endif /* WOLFSSL_CERT_NAME_ALL */
  23428. case ASN_SUR_NAME:
  23429. return name->sur;
  23430. case ASN_ORG_NAME:
  23431. return name->org;
  23432. case ASN_ORGUNIT_NAME:
  23433. return name->unit;
  23434. case ASN_COMMON_NAME:
  23435. return name->commonName;
  23436. case ASN_SERIAL_NUMBER:
  23437. return name->serialDev;
  23438. case ASN_USER_ID:
  23439. return name->userId;
  23440. case ASN_POSTAL_CODE:
  23441. return name->postalCode;
  23442. case ASN_EMAIL_NAME:
  23443. return name->email;
  23444. #ifdef WOLFSSL_CERT_EXT
  23445. case ASN_BUS_CAT:
  23446. return name->busCat;
  23447. #endif
  23448. #ifdef WOLFSSL_CUSTOM_OID
  23449. case ASN_CUSTOM_NAME:
  23450. return (const char*)name->custom.val;
  23451. #endif
  23452. default:
  23453. return NULL;
  23454. }
  23455. }
  23456. /* Get Which Name Encoding from index */
  23457. static char GetNameType(CertName* name, int idx)
  23458. {
  23459. byte type = GetCertNameId(idx);
  23460. switch (type) {
  23461. case ASN_COUNTRY_NAME:
  23462. return name->countryEnc;
  23463. case ASN_STATE_NAME:
  23464. return name->stateEnc;
  23465. case ASN_STREET_ADDR:
  23466. return name->streetEnc;
  23467. case ASN_LOCALITY_NAME:
  23468. return name->localityEnc;
  23469. #ifdef WOLFSSL_CERT_NAME_ALL
  23470. case ASN_NAME:
  23471. return name->dnNameEnc;
  23472. case ASN_GIVEN_NAME:
  23473. return name->givenNameEnc;
  23474. case ASN_INITIALS:
  23475. return name->initialsEnc;
  23476. case ASN_DNQUALIFIER:
  23477. return name->dnQualifierEnc;
  23478. #endif /* WOLFSSL_CERT_NAME_ALL */
  23479. case ASN_SUR_NAME:
  23480. return name->surEnc;
  23481. case ASN_ORG_NAME:
  23482. return name->orgEnc;
  23483. case ASN_ORGUNIT_NAME:
  23484. return name->unitEnc;
  23485. case ASN_COMMON_NAME:
  23486. return name->commonNameEnc;
  23487. case ASN_SERIAL_NUMBER:
  23488. return name->serialDevEnc;
  23489. case ASN_USER_ID:
  23490. return name->userIdEnc;
  23491. case ASN_POSTAL_CODE:
  23492. return name->postalCodeEnc;
  23493. case ASN_EMAIL_NAME:
  23494. return 0; /* special */
  23495. #ifdef WOLFSSL_CERT_EXT
  23496. case ASN_BUS_CAT:
  23497. return name->busCatEnc;
  23498. #endif
  23499. #ifdef WOLFSSL_CUSTOM_OID
  23500. case ASN_CUSTOM_NAME:
  23501. return name->custom.enc;
  23502. #endif
  23503. default:
  23504. return 0;
  23505. }
  23506. }
  23507. #ifndef WOLFSSL_ASN_TEMPLATE
  23508. /*
  23509. Extensions ::= SEQUENCE OF Extension
  23510. Extension ::= SEQUENCE {
  23511. extnId OBJECT IDENTIFIER,
  23512. critical BOOLEAN DEFAULT FALSE,
  23513. extnValue OCTET STRING }
  23514. */
  23515. /* encode all extensions, return total bytes written */
  23516. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  23517. const byte* ext, int extSz)
  23518. {
  23519. if (out == NULL || IdxInOut == NULL || ext == NULL)
  23520. return BAD_FUNC_ARG;
  23521. if (outSz < (word32)(*IdxInOut+extSz))
  23522. return BUFFER_E;
  23523. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  23524. *IdxInOut += extSz;
  23525. return *IdxInOut;
  23526. }
  23527. /* encode extensions header, return total bytes written */
  23528. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  23529. {
  23530. byte sequence[MAX_SEQ_SZ];
  23531. byte len[MAX_LENGTH_SZ];
  23532. word32 seqSz, lenSz, idx = 0;
  23533. if (out == NULL)
  23534. return BAD_FUNC_ARG;
  23535. if (outSz < 3)
  23536. return BUFFER_E;
  23537. seqSz = SetSequence(extSz, sequence);
  23538. /* encode extensions length provided */
  23539. lenSz = SetLength(extSz+seqSz, len);
  23540. if (outSz < (word32)(lenSz+seqSz+1))
  23541. return BUFFER_E;
  23542. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  23543. XMEMCPY(&out[idx], len, lenSz); /* length */
  23544. idx += lenSz;
  23545. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  23546. idx += seqSz;
  23547. return (int)idx;
  23548. }
  23549. /* encode CA basic constraints true with path length
  23550. * return total bytes written */
  23551. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  23552. {
  23553. /* ASN1->DER sequence for Basic Constraints True and path length */
  23554. const byte caPathLenBasicConstASN1[] = {
  23555. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  23556. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  23557. 0x00
  23558. };
  23559. if (out == NULL)
  23560. return BAD_FUNC_ARG;
  23561. if (outSz < sizeof(caPathLenBasicConstASN1))
  23562. return BUFFER_E;
  23563. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23564. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23565. return (int)sizeof(caPathLenBasicConstASN1);
  23566. }
  23567. /* encode CA basic constraints true
  23568. * return total bytes written */
  23569. static int SetCa(byte* out, word32 outSz)
  23570. {
  23571. /* ASN1->DER sequence for Basic Constraints True */
  23572. const byte caBasicConstASN1[] = {
  23573. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23574. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23575. };
  23576. if (out == NULL)
  23577. return BAD_FUNC_ARG;
  23578. if (outSz < sizeof(caBasicConstASN1))
  23579. return BUFFER_E;
  23580. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23581. return (int)sizeof(caBasicConstASN1);
  23582. }
  23583. /* encode basic constraints without CA Boolean
  23584. * return total bytes written */
  23585. static int SetBC(byte* out, word32 outSz)
  23586. {
  23587. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23588. const byte BasicConstASN1[] = {
  23589. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23590. 0x02, 0x30, 0x00
  23591. };
  23592. if (out == NULL)
  23593. return BAD_FUNC_ARG;
  23594. if (outSz < sizeof(BasicConstASN1))
  23595. return BUFFER_E;
  23596. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23597. return (int)sizeof(BasicConstASN1);
  23598. }
  23599. #endif
  23600. #ifdef WOLFSSL_CERT_EXT
  23601. #ifndef WOLFSSL_ASN_TEMPLATE
  23602. /* encode OID and associated value, return total bytes written */
  23603. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23604. byte *in, word32 inSz)
  23605. {
  23606. word32 idx = 0;
  23607. if (out == NULL || oid == NULL || in == NULL)
  23608. return BAD_FUNC_ARG;
  23609. if (outSz < 3)
  23610. return BUFFER_E;
  23611. /* sequence, + 1 => byte to put value size */
  23612. idx = SetSequence(inSz + oidSz + 1, out);
  23613. if ((idx + inSz + oidSz + 1) > outSz)
  23614. return BUFFER_E;
  23615. XMEMCPY(out+idx, oid, oidSz);
  23616. idx += oidSz;
  23617. out[idx++] = (byte)inSz;
  23618. XMEMCPY(out+idx, in, inSz);
  23619. return (int)(idx+inSz);
  23620. }
  23621. /* encode Subject Key Identifier, return total bytes written
  23622. * RFC5280 : non-critical */
  23623. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23624. {
  23625. byte skid_len[1 + MAX_LENGTH_SZ];
  23626. byte skid_enc_len[MAX_LENGTH_SZ];
  23627. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  23628. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23629. if (output == NULL || input == NULL)
  23630. return BAD_FUNC_ARG;
  23631. /* Octet String header */
  23632. skid_lenSz = SetOctetString(length, skid_len);
  23633. /* length of encoded value */
  23634. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23635. if (outSz < 3)
  23636. return BUFFER_E;
  23637. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  23638. skid_enc_lenSz, output);
  23639. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23640. return BUFFER_E;
  23641. /* put oid */
  23642. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23643. idx += sizeof(skid_oid);
  23644. /* put encoded len */
  23645. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23646. idx += skid_enc_lenSz;
  23647. /* put octet header */
  23648. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23649. idx += skid_lenSz;
  23650. /* put value */
  23651. XMEMCPY(output+idx, input, length);
  23652. idx += length;
  23653. return (int)idx;
  23654. }
  23655. /* encode Authority Key Identifier, return total bytes written
  23656. * RFC5280 : non-critical */
  23657. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23658. byte rawAkid)
  23659. {
  23660. int enc_valSz;
  23661. byte enc_val_buf[MAX_KID_SZ];
  23662. byte* enc_val;
  23663. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23664. const byte akid_cs[] = { 0x80 };
  23665. word32 inSeqSz, idx;
  23666. (void)rawAkid;
  23667. if (output == NULL || input == NULL)
  23668. return BAD_FUNC_ARG;
  23669. #ifdef WOLFSSL_AKID_NAME
  23670. if (rawAkid) {
  23671. enc_val = input;
  23672. enc_valSz = length;
  23673. }
  23674. else
  23675. #endif
  23676. {
  23677. enc_val = enc_val_buf;
  23678. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  23679. if (enc_valSz > (int)sizeof(enc_val_buf))
  23680. return BAD_FUNC_ARG;
  23681. /* sequence for ContentSpec & value */
  23682. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  23683. sizeof(akid_cs), input, length);
  23684. if (enc_valSz <= 0)
  23685. return enc_valSz;
  23686. }
  23687. /* The size of the extension sequence contents */
  23688. inSeqSz = (word32)sizeof(akid_oid) +
  23689. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  23690. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23691. return BAD_FUNC_ARG;
  23692. /* Write out the sequence header */
  23693. idx = SetSequence(inSeqSz, output);
  23694. /* Write out OID */
  23695. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23696. idx += sizeof(akid_oid);
  23697. /* Write out AKID */
  23698. idx += SetOctetString((word32)enc_valSz, output + idx);
  23699. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  23700. return (int)idx + enc_valSz;
  23701. }
  23702. /* encode Key Usage, return total bytes written
  23703. * RFC5280 : critical */
  23704. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23705. {
  23706. byte ku[5];
  23707. word32 idx;
  23708. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23709. 0x01, 0x01, 0xff, 0x04};
  23710. if (output == NULL)
  23711. return BAD_FUNC_ARG;
  23712. idx = SetBitString16Bit(input, ku);
  23713. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23714. ku, idx);
  23715. }
  23716. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  23717. const byte* oid, word32 oidSz)
  23718. {
  23719. /* verify room */
  23720. if (*idx + 2 + oidSz >= outSz)
  23721. return ASN_PARSE_E;
  23722. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  23723. XMEMCPY(&output[*idx], oid, oidSz);
  23724. *idx += oidSz;
  23725. return 0;
  23726. }
  23727. #endif
  23728. #ifdef WOLFSSL_ASN_TEMPLATE
  23729. /* ASN.1 template for extended key usage.
  23730. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23731. * Dynamic creation of template for encoding.
  23732. */
  23733. static const ASNItem ekuASN[] = {
  23734. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23735. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23736. };
  23737. enum {
  23738. EKUASN_IDX_SEQ = 0,
  23739. EKUASN_IDX_OID
  23740. };
  23741. /* OIDs corresponding to extended key usage. */
  23742. struct {
  23743. const byte* oid;
  23744. word32 oidSz;
  23745. } ekuOid[] = {
  23746. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23747. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23748. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23749. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23750. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23751. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23752. };
  23753. #define EKU_OID_LO 1
  23754. #define EKU_OID_HI 6
  23755. #endif /* WOLFSSL_ASN_TEMPLATE */
  23756. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23757. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23758. {
  23759. #ifndef WOLFSSL_ASN_TEMPLATE
  23760. word32 idx = 0, oidListSz = 0, totalSz;
  23761. int ret = 0;
  23762. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23763. if (output == NULL)
  23764. return BAD_FUNC_ARG;
  23765. /* Skip to OID List */
  23766. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23767. idx = totalSz;
  23768. /* Build OID List */
  23769. /* If any set, then just use it */
  23770. if (input & EXTKEYUSE_ANY) {
  23771. ret |= SetOjectIdValue(output, outSz, &idx,
  23772. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23773. }
  23774. else {
  23775. if (input & EXTKEYUSE_SERVER_AUTH)
  23776. ret |= SetOjectIdValue(output, outSz, &idx,
  23777. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23778. if (input & EXTKEYUSE_CLIENT_AUTH)
  23779. ret |= SetOjectIdValue(output, outSz, &idx,
  23780. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23781. if (input & EXTKEYUSE_CODESIGN)
  23782. ret |= SetOjectIdValue(output, outSz, &idx,
  23783. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23784. if (input & EXTKEYUSE_EMAILPROT)
  23785. ret |= SetOjectIdValue(output, outSz, &idx,
  23786. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23787. if (input & EXTKEYUSE_TIMESTAMP)
  23788. ret |= SetOjectIdValue(output, outSz, &idx,
  23789. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23790. if (input & EXTKEYUSE_OCSP_SIGN)
  23791. ret |= SetOjectIdValue(output, outSz, &idx,
  23792. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23793. #ifdef WOLFSSL_EKU_OID
  23794. /* iterate through OID values */
  23795. if (input & EXTKEYUSE_USER) {
  23796. int i, sz;
  23797. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23798. sz = cert->extKeyUsageOIDSz[i];
  23799. if (sz > 0) {
  23800. ret |= SetOjectIdValue(output, outSz, &idx,
  23801. cert->extKeyUsageOID[i], sz);
  23802. }
  23803. }
  23804. }
  23805. #endif /* WOLFSSL_EKU_OID */
  23806. }
  23807. if (ret != 0)
  23808. return ASN_PARSE_E;
  23809. /* Calculate Sizes */
  23810. oidListSz = idx - totalSz;
  23811. totalSz = idx - 2; /* exclude first seq/len (2) */
  23812. /* 1. Seq + Total Len (2) */
  23813. idx = SetSequence(totalSz, output);
  23814. /* 2. Object ID (2) */
  23815. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23816. idx += sizeof(extkeyusage_oid);
  23817. /* 3. Octet String (2) */
  23818. idx += SetOctetString(totalSz - idx, &output[idx]);
  23819. /* 4. Seq + OidListLen (2) */
  23820. idx += SetSequence(oidListSz, &output[idx]);
  23821. /* 5. Oid List (already set in-place above) */
  23822. idx += oidListSz;
  23823. (void)cert;
  23824. return (int)idx;
  23825. #else
  23826. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23827. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23828. ASNSetData* dataASN;
  23829. ASNItem* extKuASN = NULL;
  23830. int asnIdx = 1;
  23831. size_t cnt = 1 + EKU_OID_HI;
  23832. int i;
  23833. int ret = 0;
  23834. int sz = 0;
  23835. #ifdef WOLFSSL_EKU_OID
  23836. cnt += CTC_MAX_EKU_NB;
  23837. #endif
  23838. /* Allocate memory for dynamic data items. */
  23839. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23840. DYNAMIC_TYPE_TMP_BUFFER);
  23841. if (dataASN == NULL) {
  23842. ret = MEMORY_E;
  23843. }
  23844. if (ret == 0) {
  23845. /* Allocate memory for dynamic ASN.1 template. */
  23846. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23847. DYNAMIC_TYPE_TMP_BUFFER);
  23848. if (extKuASN == NULL) {
  23849. ret = MEMORY_E;
  23850. }
  23851. }
  23852. if (ret == 0) {
  23853. /* Copy Sequence into dynamic ASN.1 template. */
  23854. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23855. /* Clear dynamic data. */
  23856. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23857. /* Build up the template and data. */
  23858. /* If 'any' set, then just use it. */
  23859. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23860. /* Set template item. */
  23861. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23862. sizeof(ASNItem));
  23863. /* Set data item. */
  23864. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23865. sizeof(extExtKeyUsageAnyOid));
  23866. asnIdx++;
  23867. }
  23868. else {
  23869. /* Step through the flagged purposes. */
  23870. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23871. if ((input & (1 << i)) != 0) {
  23872. /* Set template item. */
  23873. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23874. sizeof(ASNItem));
  23875. /* Set data item. */
  23876. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23877. ekuOid[i - 1].oidSz);
  23878. asnIdx++;
  23879. }
  23880. }
  23881. #ifdef WOLFSSL_EKU_OID
  23882. if (input & EXTKEYUSE_USER) {
  23883. /* Iterate through OID values */
  23884. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23885. sz = cert->extKeyUsageOIDSz[i];
  23886. if (sz > 0) {
  23887. /* Set template item. */
  23888. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23889. sizeof(ASNItem));
  23890. /* Set data item. */
  23891. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23892. sz);
  23893. asnIdx++;
  23894. }
  23895. }
  23896. }
  23897. #endif /* WOLFSSL_EKU_OID */
  23898. (void)cert;
  23899. }
  23900. /* Calculate size of encoding. */
  23901. sz = 0;
  23902. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23903. }
  23904. /* When buffer to write to, ensure it's big enough. */
  23905. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23906. ret = BUFFER_E;
  23907. }
  23908. if ((ret == 0) && (output != NULL)) {
  23909. /* Encode extended key usage. */
  23910. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23911. }
  23912. if (ret == 0) {
  23913. /* Return the encoding size. */
  23914. ret = sz;
  23915. }
  23916. /* Dispose of allocated data. */
  23917. if (extKuASN != NULL) {
  23918. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23919. }
  23920. if (dataASN != NULL) {
  23921. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23922. }
  23923. return ret;
  23924. #endif
  23925. }
  23926. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23927. #ifndef WOLFSSL_ASN_TEMPLATE
  23928. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23929. {
  23930. word32 idx;
  23931. byte unusedBits = 0;
  23932. byte nsCertType = input;
  23933. word32 totalSz;
  23934. word32 bitStrSz;
  23935. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23936. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23937. if (cert == NULL || output == NULL ||
  23938. input == 0)
  23939. return BAD_FUNC_ARG;
  23940. totalSz = sizeof(nscerttype_oid);
  23941. /* Get amount of lsb zero's */
  23942. for (;(input & 1) == 0; input >>= 1)
  23943. unusedBits++;
  23944. /* 1 byte of NS Cert Type extension */
  23945. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23946. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23947. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23948. return BAD_FUNC_ARG;
  23949. /* 1. Seq + Total Len */
  23950. idx = SetSequence(totalSz, output);
  23951. /* 2. Object ID */
  23952. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23953. idx += sizeof(nscerttype_oid);
  23954. /* 3. Octet String */
  23955. idx += SetOctetString(bitStrSz, &output[idx]);
  23956. /* 4. Bit String */
  23957. idx += SetBitString(1, unusedBits, &output[idx]);
  23958. output[idx++] = nsCertType;
  23959. return (int)idx;
  23960. }
  23961. #endif
  23962. #endif
  23963. #ifndef WOLFSSL_ASN_TEMPLATE
  23964. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23965. int inSz)
  23966. {
  23967. word32 idx;
  23968. word32 totalSz;
  23969. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23970. if (cert == NULL || output == NULL ||
  23971. input == 0 || inSz <= 0)
  23972. return BAD_FUNC_ARG;
  23973. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  23974. (word32)inSz;
  23975. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23976. return BAD_FUNC_ARG;
  23977. /* 1. Seq + Total Len */
  23978. idx = SetSequence(totalSz, output);
  23979. /* 2. Object ID */
  23980. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23981. idx += sizeof(crlinfo_oid);
  23982. /* 3. Octet String */
  23983. idx += SetOctetString((word32)inSz, &output[idx]);
  23984. /* 4. CRL Info */
  23985. XMEMCPY(&output[idx], input, (size_t)inSz);
  23986. idx += (word32)inSz;
  23987. return (int)idx;
  23988. }
  23989. #endif
  23990. /* encode Certificate Policies, return total bytes written
  23991. * each input value must be ITU-T X.690 formatted : a.b.c...
  23992. * input must be an array of values with a NULL terminated for the latest
  23993. * RFC5280 : non-critical */
  23994. static int SetCertificatePolicies(byte *output,
  23995. word32 outputSz,
  23996. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23997. word16 nb_certpol,
  23998. void* heap)
  23999. {
  24000. #ifndef WOLFSSL_ASN_TEMPLATE
  24001. byte oid[MAX_OID_SZ];
  24002. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  24003. byte out[MAX_CERTPOL_SZ];
  24004. word32 oidSz;
  24005. word32 outSz;
  24006. word32 i = 0;
  24007. word32 der_oidSz[MAX_CERTPOL_NB];
  24008. int ret;
  24009. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  24010. const byte oid_oid[] = { 0x06 };
  24011. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  24012. return BAD_FUNC_ARG;
  24013. for (i = 0; i < nb_certpol; i++) {
  24014. oidSz = sizeof(oid);
  24015. XMEMSET(oid, 0, oidSz);
  24016. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  24017. if (ret != 0)
  24018. return ret;
  24019. /* compute sequence value for the oid */
  24020. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  24021. sizeof(oid_oid), oid, oidSz);
  24022. if (ret <= 0)
  24023. return ret;
  24024. else
  24025. der_oidSz[i] = (word32)ret;
  24026. }
  24027. /* concatenate oid, keep two byte for sequence/size of the created value */
  24028. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  24029. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  24030. outSz += der_oidSz[i];
  24031. }
  24032. /* add sequence */
  24033. ret = (int)SetSequence(outSz-2, out);
  24034. if (ret <= 0)
  24035. return ret;
  24036. /* add Policy OID to compute final value */
  24037. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  24038. out, outSz);
  24039. #else
  24040. int i;
  24041. int ret = 0;
  24042. byte oid[MAX_OID_SZ];
  24043. word32 oidSz;
  24044. word32 sz = 0;
  24045. int piSz;
  24046. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  24047. ret = BAD_FUNC_ARG;
  24048. }
  24049. /* Put in policyIdentifier but not policyQualifiers. */
  24050. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  24051. ASNSetData dataASN[policyInfoASN_Length];
  24052. oidSz = sizeof(oid);
  24053. XMEMSET(oid, 0, oidSz);
  24054. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  24055. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  24056. if (ret == 0) {
  24057. XMEMSET(dataASN, 0, sizeof(dataASN));
  24058. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  24059. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  24060. &piSz);
  24061. }
  24062. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  24063. ret = BUFFER_E;
  24064. }
  24065. if (ret == 0) {
  24066. if (output != NULL) {
  24067. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  24068. output);
  24069. output += piSz;
  24070. }
  24071. sz += (word32)piSz;
  24072. }
  24073. }
  24074. if (ret == 0) {
  24075. ret = (int)sz;
  24076. }
  24077. return ret;
  24078. #endif
  24079. }
  24080. #endif /* WOLFSSL_CERT_EXT */
  24081. #ifdef WOLFSSL_ALT_NAMES
  24082. #ifndef WOLFSSL_ASN_TEMPLATE
  24083. /* encode Alternative Names, return total bytes written */
  24084. static int SetAltNames(byte *output, word32 outSz,
  24085. const byte *input, word32 length, int critical)
  24086. {
  24087. byte san_len[1 + MAX_LENGTH_SZ];
  24088. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  24089. const byte san_crit[] = { 0x01, 0x01, 0xff };
  24090. word32 seqSz, san_lenSz, idx = 0;
  24091. if (output == NULL || input == NULL)
  24092. return BAD_FUNC_ARG;
  24093. if (outSz < length)
  24094. return BUFFER_E;
  24095. /* Octet String header */
  24096. san_lenSz = SetOctetString(length, san_len);
  24097. if (outSz < MAX_SEQ_SZ)
  24098. return BUFFER_E;
  24099. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  24100. if (critical)
  24101. seqSz += sizeof(san_crit);
  24102. idx = SetSequence(seqSz, output);
  24103. if (seqSz > outSz)
  24104. return BUFFER_E;
  24105. /* put oid */
  24106. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  24107. idx += sizeof(san_oid);
  24108. if (critical) {
  24109. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  24110. idx += sizeof(san_crit);
  24111. }
  24112. /* put octet header */
  24113. XMEMCPY(output+idx, san_len, san_lenSz);
  24114. idx += san_lenSz;
  24115. /* put value */
  24116. XMEMCPY(output+idx, input, length);
  24117. idx += length;
  24118. return (int)idx;
  24119. }
  24120. #endif /* WOLFSSL_ASN_TEMPLATE */
  24121. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  24122. {
  24123. word32 idx;
  24124. const DNS_entry* curName;
  24125. word32 namesSz = 0;
  24126. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24127. word32 i;
  24128. #endif
  24129. if (output == NULL)
  24130. return BAD_FUNC_ARG;
  24131. if (names == NULL)
  24132. return 0;
  24133. curName = names;
  24134. do {
  24135. namesSz += (word32)curName->len + 2 +
  24136. ((curName->len < ASN_LONG_LENGTH) ? 0
  24137. : BytePrecision((word32)curName->len));
  24138. curName = curName->next;
  24139. } while (curName != NULL);
  24140. if (outputSz < MAX_SEQ_SZ + namesSz)
  24141. return BUFFER_E;
  24142. idx = SetSequence(namesSz, output);
  24143. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24144. namesSz += idx;
  24145. i = namesSz;
  24146. #endif
  24147. curName = names;
  24148. do {
  24149. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24150. word32 len = SetLength(curName->len, NULL);
  24151. idx = i - curName->len - len - 1;
  24152. i = idx;
  24153. #endif
  24154. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  24155. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  24156. output[idx] |= ASN_CONSTRUCTED;
  24157. }
  24158. idx++;
  24159. idx += SetLength((word32)curName->len, output + idx);
  24160. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  24161. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  24162. idx += (word32)curName->len;
  24163. #endif
  24164. curName = curName->next;
  24165. } while (curName != NULL);
  24166. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  24167. idx = namesSz;
  24168. #endif
  24169. return (int)idx;
  24170. }
  24171. #endif /* WOLFSSL_ALT_NAMES */
  24172. #endif /* WOLFSSL_CERT_GEN */
  24173. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  24174. /* Simple domain name OID size. */
  24175. #define DN_OID_SZ 3
  24176. /* Encodes one attribute of the name (issuer/subject)
  24177. *
  24178. * name structure to hold result of encoding
  24179. * nameStr value to be encoded
  24180. * nameTag tag of encoding i.e CTC_UTF8
  24181. * type id of attribute i.e ASN_COMMON_NAME
  24182. * emailTag tag of email i.e CTC_UTF8
  24183. * returns length on success
  24184. */
  24185. static int EncodeName(EncodedName* name, const char* nameStr,
  24186. byte nameTag, byte type, byte emailTag, CertName* cname)
  24187. {
  24188. #if !defined(WOLFSSL_ASN_TEMPLATE)
  24189. word32 idx = 0;
  24190. /* bottom up */
  24191. byte firstLen[1 + MAX_LENGTH_SZ];
  24192. byte secondLen[MAX_LENGTH_SZ];
  24193. byte sequence[MAX_SEQ_SZ];
  24194. byte set[MAX_SET_SZ];
  24195. word32 strLen;
  24196. word32 thisLen;
  24197. word32 firstSz, secondSz, seqSz, setSz;
  24198. if (nameStr == NULL) {
  24199. name->used = 0;
  24200. return 0;
  24201. }
  24202. thisLen = strLen = (word32)XSTRLEN(nameStr);
  24203. #ifdef WOLFSSL_CUSTOM_OID
  24204. if (type == ASN_CUSTOM_NAME) {
  24205. if (cname == NULL || cname->custom.oidSz == 0) {
  24206. name->used = 0;
  24207. return 0;
  24208. }
  24209. thisLen = strLen = (word32)cname->custom.valSz;
  24210. }
  24211. #else
  24212. (void)cname;
  24213. #endif
  24214. if (strLen == 0) { /* no user data for this item */
  24215. name->used = 0;
  24216. return 0;
  24217. }
  24218. /* Restrict country code size */
  24219. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  24220. WOLFSSL_MSG("Country code size error");
  24221. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  24222. return ASN_COUNTRY_SIZE_E;
  24223. }
  24224. secondSz = SetLength(strLen, secondLen);
  24225. thisLen += secondSz;
  24226. switch (type) {
  24227. case ASN_EMAIL_NAME: /* email */
  24228. thisLen += (int)sizeof(attrEmailOid);
  24229. firstSz = (int)sizeof(attrEmailOid);
  24230. break;
  24231. case ASN_DOMAIN_COMPONENT:
  24232. thisLen += (int)sizeof(dcOid);
  24233. firstSz = (int)sizeof(dcOid);
  24234. break;
  24235. case ASN_USER_ID:
  24236. thisLen += (int)sizeof(uidOid);
  24237. firstSz = (int)sizeof(uidOid);
  24238. break;
  24239. case ASN_FAVOURITE_DRINK:
  24240. thisLen += (int)sizeof(fvrtDrk);
  24241. firstSz = (int)sizeof(fvrtDrk);
  24242. break;
  24243. #ifdef WOLFSSL_CUSTOM_OID
  24244. case ASN_CUSTOM_NAME:
  24245. thisLen += cname->custom.oidSz;
  24246. firstSz = cname->custom.oidSz;
  24247. break;
  24248. #endif
  24249. #ifdef WOLFSSL_CERT_REQ
  24250. case ASN_CONTENT_TYPE:
  24251. thisLen += (int)sizeof(attrPkcs9ContentTypeOid);
  24252. firstSz = (int)sizeof(attrPkcs9ContentTypeOid);
  24253. break;
  24254. #endif
  24255. default:
  24256. thisLen += DN_OID_SZ;
  24257. firstSz = DN_OID_SZ;
  24258. }
  24259. thisLen++; /* id type */
  24260. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  24261. thisLen += firstSz;
  24262. seqSz = SetSequence(thisLen, sequence);
  24263. thisLen += seqSz;
  24264. setSz = SetSet(thisLen, set);
  24265. thisLen += setSz;
  24266. if (thisLen > (int)sizeof(name->encoded)) {
  24267. return BUFFER_E;
  24268. }
  24269. /* store it */
  24270. idx = 0;
  24271. /* set */
  24272. XMEMCPY(name->encoded, set, setSz);
  24273. idx += setSz;
  24274. /* seq */
  24275. XMEMCPY(name->encoded + idx, sequence, seqSz);
  24276. idx += seqSz;
  24277. /* asn object id */
  24278. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  24279. idx += firstSz;
  24280. switch (type) {
  24281. case ASN_EMAIL_NAME:
  24282. /* email joint id */
  24283. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  24284. idx += (int)sizeof(attrEmailOid);
  24285. name->encoded[idx++] = emailTag;
  24286. break;
  24287. case ASN_DOMAIN_COMPONENT:
  24288. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  24289. idx += (int)sizeof(dcOid)-1;
  24290. /* id type */
  24291. name->encoded[idx++] = type;
  24292. /* str type */
  24293. name->encoded[idx++] = nameTag;
  24294. break;
  24295. case ASN_USER_ID:
  24296. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  24297. idx += (int)sizeof(uidOid);
  24298. /* str type */
  24299. name->encoded[idx++] = nameTag;
  24300. break;
  24301. case ASN_FAVOURITE_DRINK:
  24302. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  24303. idx += (int)sizeof(fvrtDrk);
  24304. /* str type */
  24305. name->encoded[idx++] = nameTag;
  24306. break;
  24307. #ifdef WOLFSSL_CUSTOM_OID
  24308. case ASN_CUSTOM_NAME:
  24309. XMEMCPY(name->encoded + idx, cname->custom.oid,
  24310. cname->custom.oidSz);
  24311. idx += cname->custom.oidSz;
  24312. /* str type */
  24313. name->encoded[idx++] = nameTag;
  24314. break;
  24315. #endif
  24316. #ifdef WOLFSSL_CERT_REQ
  24317. case ASN_CONTENT_TYPE:
  24318. XMEMCPY(name->encoded + idx, attrPkcs9ContentTypeOid,
  24319. sizeof(attrPkcs9ContentTypeOid));
  24320. idx += (int)sizeof(attrPkcs9ContentTypeOid);
  24321. /* str type */
  24322. name->encoded[idx++] = nameTag;
  24323. break;
  24324. #endif
  24325. default:
  24326. name->encoded[idx++] = 0x55;
  24327. name->encoded[idx++] = 0x04;
  24328. /* id type */
  24329. name->encoded[idx++] = type;
  24330. /* str type */
  24331. name->encoded[idx++] = nameTag;
  24332. }
  24333. /* second length */
  24334. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  24335. idx += secondSz;
  24336. /* str value */
  24337. XMEMCPY(name->encoded + idx, nameStr, strLen);
  24338. idx += strLen;
  24339. name->type = type;
  24340. name->totalLen = (int)idx;
  24341. name->used = 1;
  24342. return (int)idx;
  24343. #else
  24344. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  24345. ASNItem namesASN[rdnASN_Length];
  24346. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  24347. int ret = 0;
  24348. int sz = 0;
  24349. const byte* oid;
  24350. word32 oidSz;
  24351. word32 nameSz;
  24352. /* Validate input parameters. */
  24353. if ((name == NULL) || (nameStr == NULL)) {
  24354. ret = BAD_FUNC_ARG;
  24355. }
  24356. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  24357. if (ret == 0) {
  24358. nameSz = (word32)XSTRLEN(nameStr);
  24359. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  24360. * based on type. */
  24361. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  24362. /* Set OID and ASN.1 tag for name depending on type. */
  24363. switch (type) {
  24364. case ASN_EMAIL_NAME:
  24365. /* email OID different to standard types. */
  24366. oid = attrEmailOid;
  24367. oidSz = sizeof(attrEmailOid);
  24368. /* Use email specific type/tag. */
  24369. nameTag = emailTag;
  24370. break;
  24371. case ASN_DOMAIN_COMPONENT:
  24372. /* Domain component OID different to standard types. */
  24373. oid = dcOid;
  24374. oidSz = sizeof(dcOid);
  24375. break;
  24376. case ASN_USER_ID:
  24377. /* Domain component OID different to standard types. */
  24378. oid = uidOid;
  24379. oidSz = sizeof(uidOid);
  24380. break;
  24381. case ASN_FAVOURITE_DRINK:
  24382. oid = fvrtDrk;
  24383. oidSz = sizeof(fvrtDrk);
  24384. break;
  24385. #ifdef WOLFSSL_CUSTOM_OID
  24386. case ASN_CUSTOM_NAME:
  24387. nameSz = cname->custom.valSz;
  24388. oid = cname->custom.oid;
  24389. oidSz = cname->custom.oidSz;
  24390. break;
  24391. #endif
  24392. #ifdef WOLFSSL_CERT_REQ
  24393. case ASN_CONTENT_TYPE:
  24394. oid = attrPkcs9ContentTypeOid;
  24395. oidSz = sizeof(attrPkcs9ContentTypeOid);
  24396. break;
  24397. #endif
  24398. default:
  24399. /* Construct OID using type. */
  24400. dnOid[2] = type;
  24401. oid = dnOid;
  24402. oidSz = DN_OID_SZ;
  24403. break;
  24404. }
  24405. /* Set OID corresponding to the name type. */
  24406. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24407. /* Set name string. */
  24408. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  24409. /* Set the ASN.1 tag for the name string. */
  24410. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  24411. /* Calculate size of encoded name and indexes of components. */
  24412. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  24413. }
  24414. /* Check if name's buffer is big enough. */
  24415. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  24416. ret = BUFFER_E;
  24417. }
  24418. if (ret == 0) {
  24419. /* Encode name into the buffer. */
  24420. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  24421. /* Cache the type and size, and set that it is used. */
  24422. name->type = type;
  24423. name->totalLen = sz;
  24424. name->used = 1;
  24425. /* Return size of encoding. */
  24426. ret = sz;
  24427. }
  24428. (void)cname;
  24429. FREE_ASNSETDATA(dataASN, NULL);
  24430. return ret;
  24431. #endif /* WOLFSSL_ASN_TEMPLATE */
  24432. }
  24433. /* canonical encoding one attribute of the name (issuer/subject)
  24434. * call EncodeName with CTC_UTF8 for email type
  24435. *
  24436. * name structure to hold result of encoding
  24437. * nameStr value to be encoded
  24438. * nameType type of encoding i.e CTC_UTF8
  24439. * type id of attribute i.e ASN_COMMON_NAME
  24440. *
  24441. * returns length on success
  24442. */
  24443. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  24444. char nameType, byte type)
  24445. {
  24446. return EncodeName(name, nameStr, (byte)nameType, type,
  24447. ASN_UTF8STRING, NULL);
  24448. }
  24449. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  24450. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \
  24451. (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA))
  24452. /* Convert key usage string (comma delimited, null terminated) to word16
  24453. * Returns 0 on success, negative on error */
  24454. int ParseKeyUsageStr(const char* value, word16* keyUsage, void* heap)
  24455. {
  24456. int ret = 0;
  24457. char *token, *str, *ptr;
  24458. word32 len = 0;
  24459. word16 usage = 0;
  24460. if (value == NULL || keyUsage == NULL) {
  24461. return BAD_FUNC_ARG;
  24462. }
  24463. /* duplicate string (including terminator) */
  24464. len = (word32)XSTRLEN(value);
  24465. str = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24466. if (str == NULL) {
  24467. return MEMORY_E;
  24468. }
  24469. XMEMCPY(str, value, len + 1);
  24470. /* parse value, and set corresponding Key Usage value */
  24471. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  24472. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24473. return KEYUSAGE_E;
  24474. }
  24475. while (token != NULL) {
  24476. if (!XSTRCASECMP(token, "digitalSignature"))
  24477. usage |= KEYUSE_DIGITAL_SIG;
  24478. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  24479. !XSTRCASECMP(token, "contentCommitment"))
  24480. usage |= KEYUSE_CONTENT_COMMIT;
  24481. else if (!XSTRCASECMP(token, "keyEncipherment"))
  24482. usage |= KEYUSE_KEY_ENCIPHER;
  24483. else if (!XSTRCASECMP(token, "dataEncipherment"))
  24484. usage |= KEYUSE_DATA_ENCIPHER;
  24485. else if (!XSTRCASECMP(token, "keyAgreement"))
  24486. usage |= KEYUSE_KEY_AGREE;
  24487. else if (!XSTRCASECMP(token, "keyCertSign"))
  24488. usage |= KEYUSE_KEY_CERT_SIGN;
  24489. else if (!XSTRCASECMP(token, "cRLSign"))
  24490. usage |= KEYUSE_CRL_SIGN;
  24491. else if (!XSTRCASECMP(token, "encipherOnly"))
  24492. usage |= KEYUSE_ENCIPHER_ONLY;
  24493. else if (!XSTRCASECMP(token, "decipherOnly"))
  24494. usage |= KEYUSE_DECIPHER_ONLY;
  24495. else {
  24496. ret = KEYUSAGE_E;
  24497. break;
  24498. }
  24499. token = XSTRTOK(NULL, ",", &ptr);
  24500. }
  24501. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24502. if (ret == 0) {
  24503. *keyUsage = usage;
  24504. }
  24505. return ret;
  24506. }
  24507. /* Convert extended key usage string (comma delimited, null terminated) to byte
  24508. * Returns 0 on success, negative on error */
  24509. int ParseExtKeyUsageStr(const char* value, byte* extKeyUsage, void* heap)
  24510. {
  24511. int ret = 0;
  24512. char *token, *str, *ptr;
  24513. word32 len = 0;
  24514. byte usage = 0;
  24515. if (value == NULL || extKeyUsage == NULL) {
  24516. return BAD_FUNC_ARG;
  24517. }
  24518. /* duplicate string (including terminator) */
  24519. len = (word32)XSTRLEN(value);
  24520. str = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24521. if (str == NULL) {
  24522. return MEMORY_E;
  24523. }
  24524. XMEMCPY(str, value, len + 1);
  24525. /* parse value, and set corresponding Key Usage value */
  24526. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  24527. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24528. return EXTKEYUSAGE_E;
  24529. }
  24530. while (token != NULL) {
  24531. if (!XSTRCASECMP(token, "any"))
  24532. usage |= EXTKEYUSE_ANY;
  24533. else if (!XSTRCASECMP(token, "serverAuth"))
  24534. usage |= EXTKEYUSE_SERVER_AUTH;
  24535. else if (!XSTRCASECMP(token, "clientAuth"))
  24536. usage |= EXTKEYUSE_CLIENT_AUTH;
  24537. else if (!XSTRCASECMP(token, "codeSigning"))
  24538. usage |= EXTKEYUSE_CODESIGN;
  24539. else if (!XSTRCASECMP(token, "emailProtection"))
  24540. usage |= EXTKEYUSE_EMAILPROT;
  24541. else if (!XSTRCASECMP(token, "timeStamping"))
  24542. usage |= EXTKEYUSE_TIMESTAMP;
  24543. else if (!XSTRCASECMP(token, "OCSPSigning"))
  24544. usage |= EXTKEYUSE_OCSP_SIGN;
  24545. else {
  24546. ret = EXTKEYUSAGE_E;
  24547. break;
  24548. }
  24549. token = XSTRTOK(NULL, ",", &ptr);
  24550. }
  24551. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24552. if (ret == 0) {
  24553. *extKeyUsage = usage;
  24554. }
  24555. return ret;
  24556. }
  24557. #endif /* (CERT_GEN && CERT_EXT) || (OPENSSL_ALL || OPENSSL_EXTRA) */
  24558. #ifdef WOLFSSL_CERT_GEN
  24559. /* Encodes one attribute of the name (issuer/subject)
  24560. * call we_EncodeName_ex with 0x16, IA5String for email type
  24561. * name structure to hold result of encoding
  24562. * nameStr value to be encoded
  24563. * nameType type of encoding i.e CTC_UTF8
  24564. * type id of attribute i.e ASN_COMMON_NAME
  24565. *
  24566. * returns length on success
  24567. */
  24568. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  24569. byte type)
  24570. {
  24571. return EncodeName(name, nameStr, (byte)nameType, type,
  24572. ASN_IA5_STRING, NULL);
  24573. }
  24574. #ifdef WOLFSSL_ASN_TEMPLATE
  24575. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  24576. word32 oidSz, byte tag, const byte* data, word32 sz)
  24577. {
  24578. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  24579. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24580. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  24581. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  24582. }
  24583. #ifdef WOLFSSL_MULTI_ATTRIB
  24584. static int FindMultiAttrib(CertName* name, int id, int* idx)
  24585. {
  24586. int i;
  24587. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  24588. if (name->name[i].sz > 0 && name->name[i].id == id) {
  24589. break;
  24590. }
  24591. }
  24592. if (i == CTC_MAX_ATTRIB) {
  24593. i = -1;
  24594. }
  24595. *idx = i;
  24596. return i >= 0;
  24597. }
  24598. #endif
  24599. /* ASN.1 template for the SEQUENCE around the RDNs.
  24600. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  24601. */
  24602. static const ASNItem nameASN[] = {
  24603. { 0, ASN_SEQUENCE, 1, 1, 0 },
  24604. };
  24605. enum {
  24606. NAMEASN_IDX_SEQ = 0
  24607. };
  24608. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  24609. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  24610. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  24611. int maxIdx, CertName* name)
  24612. {
  24613. int i;
  24614. int idx;
  24615. int ret = 0;
  24616. word32 nameLen[NAME_ENTRIES];
  24617. #ifdef WOLFSSL_MULTI_ATTRIB
  24618. int j;
  24619. #endif
  24620. for (i = 0; i < NAME_ENTRIES; i++) {
  24621. /* Keep name length to identify component is to be encoded. */
  24622. const char* nameStr = GetOneCertName(name, i);
  24623. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  24624. }
  24625. idx = nameASN_Length;
  24626. for (i = 0; i < NAME_ENTRIES; i++) {
  24627. int type = GetCertNameId(i);
  24628. #ifdef WOLFSSL_MULTI_ATTRIB
  24629. j = -1;
  24630. /* Put DomainComponents before OrgUnitName. */
  24631. while (FindMultiAttrib(name, type, &j)) {
  24632. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  24633. continue;
  24634. }
  24635. if (dataASN != NULL && namesASN != NULL) {
  24636. if (idx > maxIdx - (int)rdnASN_Length) {
  24637. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24638. ret = BUFFER_E;
  24639. break;
  24640. }
  24641. /* Copy data into dynamic vars. */
  24642. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  24643. sizeof(dcOid), (byte)name->name[j].type,
  24644. (byte*)name->name[j].value,
  24645. (word32)name->name[j].sz);
  24646. }
  24647. idx += (int)rdnASN_Length;
  24648. }
  24649. if (ret != 0)
  24650. break;
  24651. #endif
  24652. if (nameLen[i] > 0) {
  24653. if (dataASN != NULL) {
  24654. if (idx > maxIdx - (int)rdnASN_Length) {
  24655. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24656. ret = BUFFER_E;
  24657. break;
  24658. }
  24659. /* Write out first instance of attribute type. */
  24660. if (type == ASN_EMAIL_NAME) {
  24661. /* Copy email data into dynamic vars. */
  24662. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  24663. sizeof(attrEmailOid), ASN_IA5_STRING,
  24664. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24665. }
  24666. else if (type == ASN_USER_ID) {
  24667. /* Copy userID data into dynamic vars. */
  24668. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  24669. sizeof(uidOid), (byte)GetNameType(name, i),
  24670. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24671. }
  24672. else if (type == ASN_FAVOURITE_DRINK) {
  24673. /* Copy favourite drink data into dynamic vars. */
  24674. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  24675. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  24676. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24677. }
  24678. else if (type == ASN_CUSTOM_NAME) {
  24679. #ifdef WOLFSSL_CUSTOM_OID
  24680. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  24681. name->custom.oidSz, name->custom.enc,
  24682. name->custom.val, name->custom.valSz);
  24683. #endif
  24684. }
  24685. else {
  24686. /* Copy name data into dynamic vars. */
  24687. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24688. NAME_OID_SZ, (byte)GetNameType(name, i),
  24689. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24690. }
  24691. }
  24692. idx += (int)rdnASN_Length;
  24693. }
  24694. #ifdef WOLFSSL_MULTI_ATTRIB
  24695. j = -1;
  24696. /* Write all other attributes of this type. */
  24697. while (FindMultiAttrib(name, type, &j)) {
  24698. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  24699. continue;
  24700. }
  24701. if (dataASN != NULL && namesASN != NULL) {
  24702. if (idx > maxIdx - (int)rdnASN_Length) {
  24703. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24704. ret = BUFFER_E;
  24705. break;
  24706. }
  24707. /* Copy data into dynamic vars. */
  24708. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24709. NAME_OID_SZ, (byte)name->name[j].type,
  24710. (byte*)name->name[j].value, (word32)name->name[j].sz);
  24711. }
  24712. idx += (int)rdnASN_Length;
  24713. }
  24714. if (ret != 0)
  24715. break;
  24716. #endif
  24717. }
  24718. if (ret == 0)
  24719. ret = idx;
  24720. return ret;
  24721. }
  24722. #endif
  24723. /* encode CertName into output, return total bytes written */
  24724. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24725. {
  24726. #ifndef WOLFSSL_ASN_TEMPLATE
  24727. int ret;
  24728. int i;
  24729. word32 idx, totalBytes = 0;
  24730. #ifdef WOLFSSL_SMALL_STACK
  24731. EncodedName* names = NULL;
  24732. #else
  24733. EncodedName names[NAME_ENTRIES];
  24734. #endif
  24735. #ifdef WOLFSSL_MULTI_ATTRIB
  24736. EncodedName addNames[CTC_MAX_ATTRIB];
  24737. int j, type;
  24738. #endif
  24739. if (output == NULL || name == NULL)
  24740. return BAD_FUNC_ARG;
  24741. if (outputSz < 3)
  24742. return BUFFER_E;
  24743. #ifdef WOLFSSL_SMALL_STACK
  24744. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24745. DYNAMIC_TYPE_TMP_BUFFER);
  24746. if (names == NULL)
  24747. return MEMORY_E;
  24748. #endif
  24749. for (i = 0; i < NAME_ENTRIES; i++) {
  24750. const char* nameStr = GetOneCertName(name, i);
  24751. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  24752. GetCertNameId(i), ASN_IA5_STRING, name);
  24753. if (ret < 0) {
  24754. #ifdef WOLFSSL_SMALL_STACK
  24755. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24756. #endif
  24757. WOLFSSL_MSG("EncodeName failed");
  24758. return BUFFER_E;
  24759. }
  24760. totalBytes += (word32)ret;
  24761. }
  24762. #ifdef WOLFSSL_MULTI_ATTRIB
  24763. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24764. if (name->name[i].sz > 0) {
  24765. ret = EncodeName(&addNames[i], name->name[i].value,
  24766. (byte)name->name[i].type, (byte)name->name[i].id,
  24767. ASN_IA5_STRING, NULL);
  24768. if (ret < 0) {
  24769. #ifdef WOLFSSL_SMALL_STACK
  24770. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24771. #endif
  24772. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24773. return BUFFER_E;
  24774. }
  24775. totalBytes += (word32)ret;
  24776. }
  24777. else {
  24778. addNames[i].used = 0;
  24779. }
  24780. }
  24781. #endif /* WOLFSSL_MULTI_ATTRIB */
  24782. /* header */
  24783. idx = SetSequence(totalBytes, output);
  24784. totalBytes += idx;
  24785. if (totalBytes > WC_ASN_NAME_MAX) {
  24786. #ifdef WOLFSSL_SMALL_STACK
  24787. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24788. #endif
  24789. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24790. return BUFFER_E;
  24791. }
  24792. for (i = 0; i < NAME_ENTRIES; i++) {
  24793. #ifdef WOLFSSL_MULTI_ATTRIB
  24794. type = GetCertNameId(i);
  24795. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24796. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24797. if (outputSz < idx + (word32)addNames[j].totalLen) {
  24798. #ifdef WOLFSSL_SMALL_STACK
  24799. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24800. #endif
  24801. WOLFSSL_MSG("Not enough space left for DC value");
  24802. return BUFFER_E;
  24803. }
  24804. XMEMCPY(output + idx, addNames[j].encoded,
  24805. (size_t)addNames[j].totalLen);
  24806. idx += (word32)addNames[j].totalLen;
  24807. }
  24808. }
  24809. #endif /* WOLFSSL_MULTI_ATTRIB */
  24810. if (names[i].used) {
  24811. if (outputSz < idx + (word32)names[i].totalLen) {
  24812. #ifdef WOLFSSL_SMALL_STACK
  24813. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24814. #endif
  24815. return BUFFER_E;
  24816. }
  24817. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  24818. idx += (word32)names[i].totalLen;
  24819. }
  24820. }
  24821. #ifdef WOLFSSL_SMALL_STACK
  24822. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24823. #endif
  24824. (void)heap;
  24825. return (int)totalBytes;
  24826. #else
  24827. /* TODO: consider calculating size of entries, putting length into
  24828. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24829. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24830. ASNItem* namesASN = NULL;
  24831. word32 items = 0;
  24832. int ret = 0;
  24833. int sz = 0;
  24834. /* Calculate length of name entries and size for allocating. */
  24835. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24836. if (ret > 0) {
  24837. items = (word32)ret;
  24838. ret = 0;
  24839. }
  24840. /* Allocate dynamic data items. */
  24841. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24842. DYNAMIC_TYPE_TMP_BUFFER);
  24843. if (dataASN == NULL) {
  24844. ret = MEMORY_E;
  24845. }
  24846. else {
  24847. /* Allocate dynamic ASN.1 template items. */
  24848. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24849. DYNAMIC_TYPE_TMP_BUFFER);
  24850. if (namesASN == NULL) {
  24851. ret = MEMORY_E;
  24852. }
  24853. }
  24854. if (ret == 0) {
  24855. /* Clear the dynamic data. */
  24856. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24857. /* Copy in the outer sequence. */
  24858. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24859. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  24860. if (ret == (int)items)
  24861. ret = 0;
  24862. else if (ret > 0) {
  24863. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24864. ret = BUFFER_E;
  24865. }
  24866. }
  24867. if (ret == 0) {
  24868. /* Calculate size of encoding. */
  24869. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  24870. }
  24871. /* Check buffer size if passed in. */
  24872. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24873. ret = BUFFER_E;
  24874. }
  24875. if (ret == 0) {
  24876. if (output != NULL) {
  24877. /* Encode Name. */
  24878. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  24879. }
  24880. else {
  24881. /* Return the encoding size. */
  24882. ret = sz;
  24883. }
  24884. }
  24885. if (namesASN != NULL)
  24886. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24887. if (dataASN != NULL)
  24888. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24889. (void)heap;
  24890. return ret;
  24891. #endif
  24892. }
  24893. int SetName(byte* output, word32 outputSz, CertName* name)
  24894. {
  24895. return SetNameEx(output, outputSz, name, NULL);
  24896. }
  24897. #ifdef WOLFSSL_ASN_TEMPLATE
  24898. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24899. RsaKey* rsaKey, ecc_key* eccKey,
  24900. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24901. DsaKey* dsaKey)
  24902. {
  24903. int ret = 0;
  24904. (void)outLen;
  24905. (void)rsaKey;
  24906. (void)eccKey;
  24907. (void)ed25519Key;
  24908. (void)ed448Key;
  24909. (void)dsaKey;
  24910. switch (keyType) {
  24911. #ifndef NO_RSA
  24912. case RSA_KEY:
  24913. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24914. if (ret <= 0) {
  24915. ret = PUBLIC_KEY_E;
  24916. }
  24917. break;
  24918. #endif
  24919. #ifdef HAVE_ECC
  24920. case ECC_KEY:
  24921. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24922. if (ret <= 0) {
  24923. ret = PUBLIC_KEY_E;
  24924. }
  24925. break;
  24926. #endif /* HAVE_ECC */
  24927. #ifdef HAVE_ED25519
  24928. case ED25519_KEY:
  24929. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  24930. (word32)outLen, 1);
  24931. if (ret <= 0) {
  24932. ret = PUBLIC_KEY_E;
  24933. }
  24934. break;
  24935. #endif
  24936. #ifdef HAVE_ED448
  24937. case ED448_KEY:
  24938. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  24939. if (ret <= 0) {
  24940. ret = PUBLIC_KEY_E;
  24941. }
  24942. break;
  24943. #endif
  24944. default:
  24945. ret = PUBLIC_KEY_E;
  24946. break;
  24947. }
  24948. return ret;
  24949. }
  24950. /* ASN.1 template for certificate extensions.
  24951. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24952. * All extensions supported for encoding are described.
  24953. */
  24954. static const ASNItem static_certExtsASN[] = {
  24955. /* Basic Constraints Extension - 4.2.1.9 */
  24956. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24957. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24958. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24959. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24960. /* cA */
  24961. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24962. /* pathLenConstraint */
  24963. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24964. /* Subject Alternative Name - 4.2.1.6 */
  24965. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24966. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24967. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24968. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24969. /* Subject Key Identifier - 4.2.1.2 */
  24970. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24971. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24972. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24973. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24974. /* Authority Key Identifier - 4.2.1.1 */
  24975. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24976. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24977. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24978. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24979. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24980. /* Key Usage - 4.2.1.3 */
  24981. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24982. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24983. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24984. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24985. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24986. /* Extended Key Usage - 4,2,1,12 */
  24987. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24988. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24989. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24990. /* Certificate Policies - 4.2.1.4 */
  24991. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24992. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24993. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24994. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24995. /* Netscape Certificate Type */
  24996. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24997. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24998. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24999. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  25000. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25001. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25002. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25003. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25004. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25005. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25006. };
  25007. enum {
  25008. CERTEXTSASN_IDX_BC_SEQ = 0,
  25009. CERTEXTSASN_IDX_BC_OID,
  25010. CERTEXTSASN_IDX_BC_STR,
  25011. CERTEXTSASN_IDX_BC_STR_SEQ,
  25012. CERTEXTSASN_IDX_BC_CA,
  25013. CERTEXTSASN_IDX_BC_PATHLEN,
  25014. CERTEXTSASN_IDX_SAN_SEQ,
  25015. CERTEXTSASN_IDX_SAN_OID,
  25016. CERTEXTSASN_IDX_SAN_CRIT,
  25017. CERTEXTSASN_IDX_SAN_STR,
  25018. CERTEXTSASN_IDX_SKID_SEQ,
  25019. CERTEXTSASN_IDX_SKID_OID,
  25020. CERTEXTSASN_IDX_SKID_STR,
  25021. CERTEXTSASN_IDX_SKID_KEYID,
  25022. CERTEXTSASN_IDX_AKID_SEQ,
  25023. CERTEXTSASN_IDX_AKID_OID,
  25024. CERTEXTSASN_IDX_AKID_STR,
  25025. CERTEXTSASN_IDX_AKID_STR_SEQ,
  25026. CERTEXTSASN_IDX_AKID_KEYID,
  25027. CERTEXTSASN_IDX_KU_SEQ,
  25028. CERTEXTSASN_IDX_KU_OID,
  25029. CERTEXTSASN_IDX_KU_CRIT,
  25030. CERTEXTSASN_IDX_KU_STR,
  25031. CERTEXTSASN_IDX_KU_USAGE,
  25032. CERTEXTSASN_IDX_EKU_SEQ,
  25033. CERTEXTSASN_IDX_EKU_OID,
  25034. CERTEXTSASN_IDX_EKU_STR,
  25035. CERTEXTSASN_IDX_POLICIES_SEQ,
  25036. CERTEXTSASN_IDX_POLICIES_OID,
  25037. CERTEXTSASN_IDX_POLICIES_STR,
  25038. CERTEXTSASN_IDX_POLICIES_INFO,
  25039. CERTEXTSASN_IDX_NSTYPE_SEQ,
  25040. CERTEXTSASN_IDX_NSTYPE_OID,
  25041. CERTEXTSASN_IDX_NSTYPE_STR,
  25042. CERTEXTSASN_IDX_NSTYPE_USAGE,
  25043. CERTEXTSASN_IDX_CRLINFO_SEQ,
  25044. CERTEXTSASN_IDX_CRLINFO_OID,
  25045. CERTEXTSASN_IDX_CRLINFO_STR,
  25046. CERTEXTSASN_IDX_CUSTOM_SEQ,
  25047. CERTEXTSASN_IDX_CUSTOM_OID,
  25048. CERTEXTSASN_IDX_CUSTOM_STR,
  25049. CERTEXTSASN_IDX_START_CUSTOM
  25050. };
  25051. /* Number of items in ASN.1 template for certificate extensions. We multiply
  25052. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  25053. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  25054. + (NUM_CUSTOM_EXT * 4))
  25055. static const ASNItem customExtASN[] = {
  25056. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25057. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  25058. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  25059. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  25060. };
  25061. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  25062. int forRequest)
  25063. {
  25064. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  25065. int sz;
  25066. int ret = 0;
  25067. int i = 0;
  25068. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  25069. #ifdef WOLFSSL_ALT_NAMES
  25070. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  25071. #endif
  25072. #ifdef WOLFSSL_CERT_EXT
  25073. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  25074. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  25075. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  25076. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  25077. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  25078. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  25079. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  25080. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  25081. #endif
  25082. #ifdef WOLFSSL_SMALL_STACK
  25083. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25084. byte *encodedOids;
  25085. #endif
  25086. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  25087. sizeof(ASNItem), cert->heap,
  25088. DYNAMIC_TYPE_TMP_BUFFER);
  25089. if (certExtsASN == NULL) {
  25090. return MEMORY_E;
  25091. }
  25092. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25093. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  25094. DYNAMIC_TYPE_TMP_BUFFER);
  25095. if (encodedOids == NULL) {
  25096. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25097. return MEMORY_E;
  25098. }
  25099. #endif
  25100. #else
  25101. ASNItem certExtsASN[certExtsASN_Length];
  25102. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25103. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  25104. #endif
  25105. #endif
  25106. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  25107. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  25108. * above definition of certExtsASN_Length. */
  25109. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  25110. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  25111. i < (int)certExtsASN_Length; i += 4) {
  25112. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  25113. }
  25114. (void)forRequest;
  25115. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  25116. if (ret == 0) {
  25117. if (cert->isCA) {
  25118. /* Set Basic Constraints to be a Certificate Authority. */
  25119. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  25120. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  25121. if (cert->pathLenSet
  25122. #ifdef WOLFSSL_CERT_EXT
  25123. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25124. #endif
  25125. ) {
  25126. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  25127. cert->pathLen);
  25128. }
  25129. else {
  25130. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  25131. }
  25132. }
  25133. else if (cert->basicConstSet) {
  25134. /* Set Basic Constraints to be a non Certificate Authority. */
  25135. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  25136. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  25137. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  25138. }
  25139. else {
  25140. /* Don't write out Basic Constraints extension items. */
  25141. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  25142. CERTEXTSASN_IDX_BC_PATHLEN);
  25143. }
  25144. #ifdef WOLFSSL_ALT_NAMES
  25145. if (cert->altNamesSz > 0) {
  25146. /* Set Subject Alternative Name OID and data. */
  25147. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  25148. sanOID, sizeof(sanOID));
  25149. if (cert->altNamesCrit) {
  25150. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  25151. }
  25152. else {
  25153. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  25154. }
  25155. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  25156. cert->altNames, (word32)cert->altNamesSz);
  25157. }
  25158. else
  25159. #endif
  25160. {
  25161. /* Don't write out Subject Alternative Name extension items. */
  25162. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  25163. CERTEXTSASN_IDX_SAN_STR);
  25164. }
  25165. #ifdef WOLFSSL_CERT_EXT
  25166. if (cert->skidSz > 0) {
  25167. /* Set Subject Key Identifier OID and data. */
  25168. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  25169. skidOID, sizeof(skidOID));
  25170. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  25171. cert->skid, (word32)cert->skidSz);
  25172. }
  25173. else
  25174. #endif
  25175. {
  25176. /* Don't write out Subject Key Identifier extension items. */
  25177. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  25178. CERTEXTSASN_IDX_SKID_KEYID);
  25179. }
  25180. #ifdef WOLFSSL_CERT_EXT
  25181. if (cert->akidSz > 0) {
  25182. /* Set Authority Key Identifier OID and data. */
  25183. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  25184. akidOID, sizeof(akidOID));
  25185. #ifdef WOLFSSL_AKID_NAME
  25186. if (cert->rawAkid) {
  25187. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  25188. cert->akid, (word32)cert->akidSz);
  25189. /* cert->akid contains the internal ext structure */
  25190. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  25191. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  25192. }
  25193. else
  25194. #endif
  25195. {
  25196. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  25197. cert->akid, (word32)cert->akidSz);
  25198. }
  25199. }
  25200. else
  25201. #endif
  25202. {
  25203. /* Don't write out Authority Key Identifier extension items. */
  25204. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  25205. CERTEXTSASN_IDX_AKID_KEYID);
  25206. }
  25207. #ifdef WOLFSSL_CERT_EXT
  25208. if (cert->keyUsage != 0) {
  25209. /* Set Key Usage OID, critical and value. */
  25210. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  25211. kuOID, sizeof(kuOID));
  25212. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  25213. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  25214. cert->keyUsage);
  25215. }
  25216. else
  25217. #endif
  25218. {
  25219. /* Don't write out Key Usage extension items. */
  25220. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  25221. CERTEXTSASN_IDX_KU_USAGE);
  25222. }
  25223. #ifdef WOLFSSL_CERT_EXT
  25224. if (cert->extKeyUsage != 0) {
  25225. /* Calculate size of Extended Key Usage data. */
  25226. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  25227. if (sz <= 0) {
  25228. ret = KEYUSAGE_E;
  25229. }
  25230. /* Set Extended Key Usage OID and data. */
  25231. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  25232. ekuOID, sizeof(ekuOID));
  25233. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  25234. NULL, (word32)sz);
  25235. }
  25236. else
  25237. #endif
  25238. {
  25239. /* Don't write out Extended Key Usage extension items. */
  25240. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  25241. CERTEXTSASN_IDX_EKU_STR);
  25242. }
  25243. #ifdef WOLFSSL_CERT_EXT
  25244. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  25245. /* Calculate size of certificate policies. */
  25246. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  25247. cert->certPoliciesNb, cert->heap);
  25248. if (sz > 0) {
  25249. /* Set Certificate Policies OID. */
  25250. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  25251. cpOID, sizeof(cpOID));
  25252. /* Make space for data. */
  25253. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  25254. NULL, (word32)sz);
  25255. }
  25256. else {
  25257. ret = CERTPOLICIES_E;
  25258. }
  25259. }
  25260. else
  25261. #endif
  25262. {
  25263. /* Don't write out Certificate Policies extension items. */
  25264. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  25265. CERTEXTSASN_IDX_POLICIES_INFO);
  25266. }
  25267. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  25268. /* Netscape Certificate Type */
  25269. if (cert->nsCertType != 0) {
  25270. /* Set Netscape Certificate Type OID and data. */
  25271. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  25272. nsCertOID, sizeof(nsCertOID));
  25273. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  25274. &cert->nsCertType, 1);
  25275. }
  25276. else
  25277. #endif
  25278. {
  25279. /* Don't write out Netscape Certificate Type. */
  25280. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  25281. CERTEXTSASN_IDX_NSTYPE_USAGE);
  25282. }
  25283. #ifdef WOLFSSL_CERT_EXT
  25284. if (cert->crlInfoSz > 0) {
  25285. /* Set CRL Distribution Points OID and data. */
  25286. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  25287. crlInfoOID, sizeof(crlInfoOID));
  25288. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  25289. cert->crlInfo, (word32)cert->crlInfoSz);
  25290. }
  25291. else
  25292. #endif
  25293. {
  25294. /* Don't write out CRL Distribution Points. */
  25295. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  25296. CERTEXTSASN_IDX_CRLINFO_STR);
  25297. }
  25298. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  25299. /* encode a custom oid and value */
  25300. if (cert->extCustom.oidSz > 0) {
  25301. /* Set CRL Distribution Points OID and data. */
  25302. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  25303. cert->extCustom.oid, cert->extCustom.oidSz);
  25304. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  25305. cert->extCustom.val, cert->extCustom.valSz);
  25306. }
  25307. else
  25308. #endif
  25309. {
  25310. /* Don't write out custom OID. */
  25311. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  25312. CERTEXTSASN_IDX_CUSTOM_STR);
  25313. }
  25314. i = 0;
  25315. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  25316. for (; i < cert->customCertExtCount; i++) {
  25317. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  25318. word32 encodedOidSz = MAX_OID_SZ;
  25319. idx++; /* Skip one for for SEQ. */
  25320. /* EncodePolicyOID() will never return error since we parsed this
  25321. * OID when it was set. */
  25322. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  25323. cert->customCertExt[i].oid, NULL);
  25324. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  25325. encodedOidSz);
  25326. idx++;
  25327. if (cert->customCertExt[i].crit) {
  25328. SetASN_Boolean(&dataASN[idx], 1);
  25329. } else {
  25330. dataASN[idx].noOut = 1;
  25331. }
  25332. idx++;
  25333. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  25334. cert->customCertExt[i].valSz);
  25335. }
  25336. #endif
  25337. while (i < NUM_CUSTOM_EXT) {
  25338. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  25339. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  25340. i++;
  25341. }
  25342. }
  25343. if (ret == 0) {
  25344. /* Calculate size of encoded extensions. */
  25345. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  25346. }
  25347. if (ret == 0) {
  25348. /* Only SEQUENCE - don't encode extensions. */
  25349. if (sz == 2) {
  25350. sz = 0;
  25351. }
  25352. /* Check buffer is big enough. */
  25353. else if ((output != NULL) && (sz > (int)maxSz)) {
  25354. ret = BUFFER_E;
  25355. }
  25356. }
  25357. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  25358. /* Encode certificate extensions into buffer. */
  25359. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  25360. #ifdef WOLFSSL_CERT_EXT
  25361. if (cert->extKeyUsage != 0){
  25362. /* Encode Extended Key Usage into space provided. */
  25363. if (SetExtKeyUsage(cert,
  25364. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  25365. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  25366. cert->extKeyUsage) <= 0) {
  25367. ret = KEYUSAGE_E;
  25368. }
  25369. }
  25370. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  25371. /* Encode Certificate Policies into space provided. */
  25372. if (SetCertificatePolicies(
  25373. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  25374. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  25375. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  25376. ret = CERTPOLICIES_E;
  25377. }
  25378. }
  25379. #endif
  25380. }
  25381. if (ret == 0) {
  25382. /* Return the encoding size. */
  25383. ret = sz;
  25384. }
  25385. FREE_ASNSETDATA(dataASN, cert->heap);
  25386. #ifdef WOLFSSL_SMALL_STACK
  25387. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25388. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25389. #endif
  25390. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25391. #endif
  25392. return ret;
  25393. }
  25394. #endif /* WOLFSSL_ASN_TEMPLATE */
  25395. #ifndef WOLFSSL_ASN_TEMPLATE
  25396. /* Set Date validity from now until now + daysValid
  25397. * return size in bytes written to output, 0 on error */
  25398. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  25399. * "MUST always encode certificate validity dates through the year 2049 as
  25400. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  25401. * GeneralizedTime." */
  25402. static int SetValidity(byte* output, int daysValid)
  25403. {
  25404. #ifndef NO_ASN_TIME
  25405. byte before[MAX_DATE_SIZE];
  25406. byte after[MAX_DATE_SIZE];
  25407. word32 beforeSz, afterSz, seqSz;
  25408. time_t now;
  25409. time_t then;
  25410. struct tm* tmpTime;
  25411. struct tm* expandedTime;
  25412. struct tm localTime;
  25413. #if defined(NEED_TMP_TIME)
  25414. /* for use with gmtime_r */
  25415. struct tm tmpTimeStorage;
  25416. tmpTime = &tmpTimeStorage;
  25417. #else
  25418. tmpTime = NULL;
  25419. #endif
  25420. (void)tmpTime;
  25421. now = wc_Time(0);
  25422. /* before now */
  25423. before[0] = ASN_GENERALIZED_TIME;
  25424. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  25425. /* subtract 1 day of seconds for more compliance */
  25426. then = now - 86400;
  25427. expandedTime = XGMTIME(&then, tmpTime);
  25428. if (expandedTime == NULL) {
  25429. WOLFSSL_MSG("XGMTIME failed");
  25430. return 0; /* error */
  25431. }
  25432. localTime = *expandedTime;
  25433. /* adjust */
  25434. localTime.tm_year += 1900;
  25435. localTime.tm_mon += 1;
  25436. SetTime(&localTime, before + beforeSz);
  25437. beforeSz += ASN_GEN_TIME_SZ;
  25438. after[0] = ASN_GENERALIZED_TIME;
  25439. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  25440. /* add daysValid of seconds */
  25441. then = now + (daysValid * (time_t)86400);
  25442. expandedTime = XGMTIME(&then, tmpTime);
  25443. if (expandedTime == NULL) {
  25444. WOLFSSL_MSG("XGMTIME failed");
  25445. return 0; /* error */
  25446. }
  25447. localTime = *expandedTime;
  25448. /* adjust */
  25449. localTime.tm_year += 1900;
  25450. localTime.tm_mon += 1;
  25451. SetTime(&localTime, after + afterSz);
  25452. afterSz += ASN_GEN_TIME_SZ;
  25453. /* headers and output */
  25454. seqSz = SetSequence(beforeSz + afterSz, output);
  25455. XMEMCPY(output + seqSz, before, beforeSz);
  25456. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  25457. return (int)(seqSz + beforeSz + afterSz);
  25458. #else
  25459. (void)output;
  25460. (void)daysValid;
  25461. return NOT_COMPILED_IN;
  25462. #endif
  25463. }
  25464. #else
  25465. static int SetValidity(byte* before, byte* after, int daysValid)
  25466. {
  25467. #ifndef NO_ASN_TIME
  25468. int ret = 0;
  25469. time_t now;
  25470. time_t then;
  25471. struct tm* tmpTime;
  25472. struct tm* expandedTime;
  25473. struct tm localTime;
  25474. #if defined(NEED_TMP_TIME)
  25475. /* for use with gmtime_r */
  25476. struct tm tmpTimeStorage;
  25477. tmpTime = &tmpTimeStorage;
  25478. #else
  25479. tmpTime = NULL;
  25480. #endif
  25481. (void)tmpTime;
  25482. now = wc_Time(0);
  25483. /* subtract 1 day of seconds for more compliance */
  25484. then = now - 86400;
  25485. expandedTime = XGMTIME(&then, tmpTime);
  25486. if (expandedTime == NULL) {
  25487. WOLFSSL_MSG("XGMTIME failed");
  25488. ret = DATE_E;
  25489. }
  25490. if (ret == 0) {
  25491. localTime = *expandedTime;
  25492. /* adjust */
  25493. localTime.tm_year += 1900;
  25494. localTime.tm_mon += 1;
  25495. SetTime(&localTime, before);
  25496. /* add daysValid of seconds */
  25497. then = now + (daysValid * (time_t)86400);
  25498. expandedTime = XGMTIME(&then, tmpTime);
  25499. if (expandedTime == NULL) {
  25500. WOLFSSL_MSG("XGMTIME failed");
  25501. ret = DATE_E;
  25502. }
  25503. }
  25504. if (ret == 0) {
  25505. localTime = *expandedTime;
  25506. /* adjust */
  25507. localTime.tm_year += 1900;
  25508. localTime.tm_mon += 1;
  25509. SetTime(&localTime, after);
  25510. }
  25511. return ret;
  25512. #else
  25513. (void)before;
  25514. (void)after;
  25515. (void)daysValid;
  25516. return NOT_COMPILED_IN;
  25517. #endif
  25518. }
  25519. #endif /* WOLFSSL_ASN_TEMPLATE */
  25520. #ifndef WOLFSSL_ASN_TEMPLATE
  25521. /* encode info from cert into DER encoded format */
  25522. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  25523. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  25524. ed448_key* ed448Key, falcon_key* falconKey,
  25525. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25526. {
  25527. int ret;
  25528. if (cert == NULL || der == NULL || rng == NULL)
  25529. return BAD_FUNC_ARG;
  25530. /* make sure at least one key type is provided */
  25531. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  25532. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  25533. dilithiumKey == NULL && sphincsKey == NULL) {
  25534. return PUBLIC_KEY_E;
  25535. }
  25536. /* init */
  25537. XMEMSET(der, 0, sizeof(DerCert));
  25538. /* version */
  25539. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  25540. /* serial number (must be positive) */
  25541. if (cert->serialSz == 0) {
  25542. /* generate random serial */
  25543. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25544. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  25545. if (ret != 0)
  25546. return ret;
  25547. /* Clear the top bit to avoid a negative value */
  25548. cert->serial[0] &= 0x7f;
  25549. }
  25550. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  25551. der->serial, sizeof(der->serial),
  25552. CTC_SERIAL_SIZE);
  25553. if (der->serialSz < 0)
  25554. return der->serialSz;
  25555. /* signature algo */
  25556. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  25557. if (der->sigAlgoSz <= 0)
  25558. return ALGO_ID_E;
  25559. /* public key */
  25560. #ifndef NO_RSA
  25561. if (cert->keyType == RSA_KEY) {
  25562. if (rsaKey == NULL)
  25563. return PUBLIC_KEY_E;
  25564. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  25565. sizeof(der->publicKey), 1);
  25566. }
  25567. #endif
  25568. #ifdef HAVE_ECC
  25569. if (cert->keyType == ECC_KEY) {
  25570. if (eccKey == NULL)
  25571. return PUBLIC_KEY_E;
  25572. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  25573. sizeof(der->publicKey), 1, 0);
  25574. }
  25575. #endif
  25576. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  25577. if (cert->keyType == DSA_KEY) {
  25578. if (dsaKey == NULL)
  25579. return PUBLIC_KEY_E;
  25580. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  25581. sizeof(der->publicKey), 1);
  25582. }
  25583. #endif
  25584. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  25585. if (cert->keyType == ED25519_KEY) {
  25586. if (ed25519Key == NULL)
  25587. return PUBLIC_KEY_E;
  25588. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  25589. (word32)sizeof(der->publicKey), 1);
  25590. }
  25591. #endif
  25592. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  25593. if (cert->keyType == ED448_KEY) {
  25594. if (ed448Key == NULL)
  25595. return PUBLIC_KEY_E;
  25596. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  25597. (word32)sizeof(der->publicKey), 1);
  25598. }
  25599. #endif
  25600. #if defined(HAVE_PQC)
  25601. #if defined(HAVE_FALCON)
  25602. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  25603. (cert->keyType == FALCON_LEVEL5_KEY)) {
  25604. if (falconKey == NULL)
  25605. return PUBLIC_KEY_E;
  25606. der->publicKeySz =
  25607. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  25608. (word32)sizeof(der->publicKey), 1);
  25609. }
  25610. #endif /* HAVE_FALCON */
  25611. #if defined(HAVE_DILITHIUM)
  25612. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  25613. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  25614. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  25615. if (dilithiumKey == NULL)
  25616. return PUBLIC_KEY_E;
  25617. der->publicKeySz =
  25618. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  25619. (word32)sizeof(der->publicKey), 1);
  25620. }
  25621. #endif /* HAVE_DILITHIUM */
  25622. #if defined(HAVE_SPHINCS)
  25623. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  25624. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  25625. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  25626. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  25627. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  25628. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  25629. if (sphincsKey == NULL)
  25630. return PUBLIC_KEY_E;
  25631. der->publicKeySz =
  25632. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  25633. (word32)sizeof(der->publicKey), 1);
  25634. }
  25635. #endif /* HAVE_SPHINCS */
  25636. #endif /* HAVE_PQC */
  25637. if (der->publicKeySz <= 0)
  25638. return PUBLIC_KEY_E;
  25639. der->validitySz = 0;
  25640. /* copy date validity if already set in cert struct */
  25641. if (cert->beforeDateSz && cert->afterDateSz) {
  25642. der->validitySz = CopyValidity(der->validity, cert);
  25643. if (der->validitySz <= 0)
  25644. return DATE_E;
  25645. }
  25646. /* set date validity using daysValid if not set already */
  25647. if (der->validitySz == 0) {
  25648. der->validitySz = SetValidity(der->validity, cert->daysValid);
  25649. if (der->validitySz <= 0)
  25650. return DATE_E;
  25651. }
  25652. /* subject name */
  25653. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25654. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  25655. /* Use the raw subject */
  25656. word32 idx;
  25657. der->subjectSz = (int)min((word32)sizeof(der->subject),
  25658. (word32)XSTRLEN((const char*)cert->sbjRaw));
  25659. /* header */
  25660. idx = SetSequence((word32)der->subjectSz, der->subject);
  25661. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  25662. return SUBJECT_E;
  25663. }
  25664. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  25665. (size_t)der->subjectSz);
  25666. der->subjectSz += (int)idx;
  25667. }
  25668. else
  25669. #endif
  25670. {
  25671. /* Use the name structure */
  25672. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  25673. &cert->subject, cert->heap);
  25674. }
  25675. if (der->subjectSz <= 0)
  25676. return SUBJECT_E;
  25677. /* issuer name */
  25678. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25679. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  25680. /* Use the raw issuer */
  25681. word32 idx;
  25682. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  25683. (word32)XSTRLEN((const char*)cert->issRaw));
  25684. /* header */
  25685. idx = SetSequence((word32)der->issuerSz, der->issuer);
  25686. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  25687. return ISSUER_E;
  25688. }
  25689. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  25690. (size_t)der->issuerSz);
  25691. der->issuerSz += (int)idx;
  25692. }
  25693. else
  25694. #endif
  25695. {
  25696. /* Use the name structure */
  25697. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  25698. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25699. }
  25700. if (der->issuerSz <= 0)
  25701. return ISSUER_E;
  25702. /* set the extensions */
  25703. der->extensionsSz = 0;
  25704. /* RFC 5280 : 4.2.1.9. Basic Constraints
  25705. * The pathLenConstraint field is meaningful only if the CA boolean is
  25706. * asserted and the key usage extension, if present, asserts the
  25707. * keyCertSign bit */
  25708. /* Set CA and path length */
  25709. if ((cert->isCA) && (cert->pathLenSet)
  25710. #ifdef WOLFSSL_CERT_EXT
  25711. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25712. #endif
  25713. ) {
  25714. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  25715. if (der->caSz <= 0)
  25716. return CA_TRUE_E;
  25717. der->extensionsSz += der->caSz;
  25718. }
  25719. /* Set CA */
  25720. else if (cert->isCA) {
  25721. der->caSz = SetCa(der->ca, sizeof(der->ca));
  25722. if (der->caSz <= 0)
  25723. return CA_TRUE_E;
  25724. der->extensionsSz += der->caSz;
  25725. }
  25726. /* Set Basic Constraint */
  25727. else if (cert->basicConstSet) {
  25728. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25729. if (der->caSz <= 0)
  25730. return EXTENSIONS_E;
  25731. der->extensionsSz += der->caSz;
  25732. }
  25733. else
  25734. der->caSz = 0;
  25735. #ifdef WOLFSSL_ALT_NAMES
  25736. /* Alternative Name */
  25737. if (cert->altNamesSz) {
  25738. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25739. cert->altNames, (word32)cert->altNamesSz,
  25740. cert->altNamesCrit);
  25741. if (der->altNamesSz <= 0)
  25742. return ALT_NAME_E;
  25743. der->extensionsSz += der->altNamesSz;
  25744. }
  25745. else
  25746. der->altNamesSz = 0;
  25747. #endif
  25748. #ifdef WOLFSSL_CERT_EXT
  25749. /* SKID */
  25750. if (cert->skidSz) {
  25751. /* check the provided SKID size */
  25752. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25753. return SKID_E;
  25754. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25755. cert (CTC_MAX_SKID_SIZE). */
  25756. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25757. cert->skid, (word32)cert->skidSz);
  25758. if (der->skidSz <= 0)
  25759. return SKID_E;
  25760. der->extensionsSz += der->skidSz;
  25761. }
  25762. else
  25763. der->skidSz = 0;
  25764. /* AKID */
  25765. if (cert->akidSz) {
  25766. /* check the provided AKID size */
  25767. if ((
  25768. #ifdef WOLFSSL_AKID_NAME
  25769. !cert->rawAkid &&
  25770. #endif
  25771. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25772. #ifdef WOLFSSL_AKID_NAME
  25773. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25774. #endif
  25775. )
  25776. return AKID_E;
  25777. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25778. (word32)cert->akidSz,
  25779. #ifdef WOLFSSL_AKID_NAME
  25780. cert->rawAkid
  25781. #else
  25782. 0
  25783. #endif
  25784. );
  25785. if (der->akidSz <= 0)
  25786. return AKID_E;
  25787. der->extensionsSz += der->akidSz;
  25788. }
  25789. else
  25790. der->akidSz = 0;
  25791. /* Key Usage */
  25792. if (cert->keyUsage != 0){
  25793. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25794. cert->keyUsage);
  25795. if (der->keyUsageSz <= 0)
  25796. return KEYUSAGE_E;
  25797. der->extensionsSz += der->keyUsageSz;
  25798. }
  25799. else
  25800. der->keyUsageSz = 0;
  25801. /* Extended Key Usage */
  25802. if (cert->extKeyUsage != 0){
  25803. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25804. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25805. if (der->extKeyUsageSz <= 0)
  25806. return EXTKEYUSAGE_E;
  25807. der->extensionsSz += der->extKeyUsageSz;
  25808. }
  25809. else
  25810. der->extKeyUsageSz = 0;
  25811. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25812. /* Netscape Certificate Type */
  25813. if (cert->nsCertType != 0) {
  25814. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25815. sizeof(der->nsCertType), cert->nsCertType);
  25816. if (der->nsCertTypeSz <= 0)
  25817. return EXTENSIONS_E;
  25818. der->extensionsSz += der->nsCertTypeSz;
  25819. }
  25820. else
  25821. der->nsCertTypeSz = 0;
  25822. #endif
  25823. if (cert->crlInfoSz > 0) {
  25824. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25825. cert->crlInfo, cert->crlInfoSz);
  25826. if (der->crlInfoSz <= 0)
  25827. return EXTENSIONS_E;
  25828. der->extensionsSz += der->crlInfoSz;
  25829. }
  25830. else
  25831. der->crlInfoSz = 0;
  25832. /* Certificate Policies */
  25833. if (cert->certPoliciesNb != 0) {
  25834. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25835. sizeof(der->certPolicies),
  25836. cert->certPolicies,
  25837. cert->certPoliciesNb,
  25838. cert->heap);
  25839. if (der->certPoliciesSz <= 0)
  25840. return CERTPOLICIES_E;
  25841. der->extensionsSz += der->certPoliciesSz;
  25842. }
  25843. else
  25844. der->certPoliciesSz = 0;
  25845. #endif /* WOLFSSL_CERT_EXT */
  25846. /* put extensions */
  25847. if (der->extensionsSz > 0) {
  25848. /* put the start of extensions sequence (ID, Size) */
  25849. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25850. sizeof(der->extensions),
  25851. (word32)der->extensionsSz);
  25852. if (der->extensionsSz <= 0)
  25853. return EXTENSIONS_E;
  25854. /* put CA */
  25855. if (der->caSz) {
  25856. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25857. &der->extensionsSz,
  25858. der->ca, der->caSz);
  25859. if (ret == 0)
  25860. return EXTENSIONS_E;
  25861. }
  25862. #ifdef WOLFSSL_ALT_NAMES
  25863. /* put Alternative Names */
  25864. if (der->altNamesSz) {
  25865. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25866. &der->extensionsSz,
  25867. der->altNames, der->altNamesSz);
  25868. if (ret <= 0)
  25869. return EXTENSIONS_E;
  25870. }
  25871. #endif
  25872. #ifdef WOLFSSL_CERT_EXT
  25873. /* put SKID */
  25874. if (der->skidSz) {
  25875. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25876. &der->extensionsSz,
  25877. der->skid, der->skidSz);
  25878. if (ret <= 0)
  25879. return EXTENSIONS_E;
  25880. }
  25881. /* put AKID */
  25882. if (der->akidSz) {
  25883. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25884. &der->extensionsSz,
  25885. der->akid, der->akidSz);
  25886. if (ret <= 0)
  25887. return EXTENSIONS_E;
  25888. }
  25889. /* put CRL Distribution Points */
  25890. if (der->crlInfoSz) {
  25891. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25892. &der->extensionsSz,
  25893. der->crlInfo, der->crlInfoSz);
  25894. if (ret <= 0)
  25895. return EXTENSIONS_E;
  25896. }
  25897. /* put KeyUsage */
  25898. if (der->keyUsageSz) {
  25899. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25900. &der->extensionsSz,
  25901. der->keyUsage, der->keyUsageSz);
  25902. if (ret <= 0)
  25903. return EXTENSIONS_E;
  25904. }
  25905. /* put ExtendedKeyUsage */
  25906. if (der->extKeyUsageSz) {
  25907. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25908. &der->extensionsSz,
  25909. der->extKeyUsage, der->extKeyUsageSz);
  25910. if (ret <= 0)
  25911. return EXTENSIONS_E;
  25912. }
  25913. /* put Netscape Cert Type */
  25914. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25915. if (der->nsCertTypeSz) {
  25916. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25917. &der->extensionsSz,
  25918. der->nsCertType, der->nsCertTypeSz);
  25919. if (ret <= 0)
  25920. return EXTENSIONS_E;
  25921. }
  25922. #endif
  25923. /* put Certificate Policies */
  25924. if (der->certPoliciesSz) {
  25925. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25926. &der->extensionsSz,
  25927. der->certPolicies, der->certPoliciesSz);
  25928. if (ret <= 0)
  25929. return EXTENSIONS_E;
  25930. }
  25931. #endif /* WOLFSSL_CERT_EXT */
  25932. }
  25933. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25934. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25935. der->extensionsSz;
  25936. return 0;
  25937. }
  25938. /* write DER encoded cert to buffer, size already checked */
  25939. static int WriteCertBody(DerCert* der, byte* buf)
  25940. {
  25941. word32 idx;
  25942. /* signed part header */
  25943. idx = SetSequence((word32)der->total, buf);
  25944. /* version */
  25945. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  25946. idx += (word32)der->versionSz;
  25947. /* serial */
  25948. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  25949. idx += (word32)der->serialSz;
  25950. /* sig algo */
  25951. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  25952. idx += (word32)der->sigAlgoSz;
  25953. /* issuer */
  25954. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  25955. idx += (word32)der->issuerSz;
  25956. /* validity */
  25957. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  25958. idx += (word32)der->validitySz;
  25959. /* subject */
  25960. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  25961. idx += (word32)der->subjectSz;
  25962. /* public key */
  25963. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  25964. idx += (word32)der->publicKeySz;
  25965. if (der->extensionsSz) {
  25966. /* extensions */
  25967. XMEMCPY(buf + idx, der->extensions,
  25968. min((word32)der->extensionsSz,
  25969. (word32)sizeof(der->extensions)));
  25970. idx += (word32)der->extensionsSz;
  25971. }
  25972. return (int)idx;
  25973. }
  25974. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25975. /* Make signature from buffer (sz), write to sig (sigSz) */
  25976. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  25977. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25978. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25979. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25980. word32 sigAlgoType, void* heap)
  25981. {
  25982. int digestSz = 0, typeH = 0, ret = 0;
  25983. (void)digestSz;
  25984. (void)typeH;
  25985. (void)buf;
  25986. (void)sz;
  25987. (void)sig;
  25988. (void)sigSz;
  25989. (void)rsaKey;
  25990. (void)eccKey;
  25991. (void)ed25519Key;
  25992. (void)ed448Key;
  25993. (void)falconKey;
  25994. (void)dilithiumKey;
  25995. (void)sphincsKey;
  25996. (void)rng;
  25997. (void)heap;
  25998. switch (certSignCtx->state) {
  25999. case CERTSIGN_STATE_BEGIN:
  26000. case CERTSIGN_STATE_DIGEST:
  26001. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  26002. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  26003. DYNAMIC_TYPE_TMP_BUFFER);
  26004. if (certSignCtx->digest == NULL) {
  26005. ret = MEMORY_E; goto exit_ms;
  26006. }
  26007. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  26008. &typeH, &digestSz, 0);
  26009. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  26010. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  26011. if (ret != 0) {
  26012. goto exit_ms;
  26013. }
  26014. FALL_THROUGH;
  26015. case CERTSIGN_STATE_ENCODE:
  26016. #ifndef NO_RSA
  26017. if (rsaKey) {
  26018. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  26019. DYNAMIC_TYPE_TMP_BUFFER);
  26020. if (certSignCtx->encSig == NULL) {
  26021. ret = MEMORY_E; goto exit_ms;
  26022. }
  26023. /* signature */
  26024. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  26025. certSignCtx->digest, (word32)digestSz, typeH);
  26026. }
  26027. #endif /* !NO_RSA */
  26028. FALL_THROUGH;
  26029. case CERTSIGN_STATE_DO:
  26030. certSignCtx->state = CERTSIGN_STATE_DO;
  26031. ret = ALGO_ID_E; /* default to error */
  26032. #ifndef NO_RSA
  26033. if (rsaKey) {
  26034. /* signature */
  26035. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  26036. (word32)certSignCtx->encSigSz,
  26037. sig, sigSz, rsaKey, rng);
  26038. }
  26039. #endif /* !NO_RSA */
  26040. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  26041. if (!rsaKey && eccKey) {
  26042. word32 outSz = sigSz;
  26043. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  26044. sig, &outSz, rng, eccKey);
  26045. if (ret == 0)
  26046. ret = (int)outSz;
  26047. }
  26048. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  26049. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  26050. if (!rsaKey && !eccKey && ed25519Key) {
  26051. word32 outSz = sigSz;
  26052. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  26053. if (ret == 0)
  26054. ret = (int)outSz;
  26055. }
  26056. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  26057. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  26058. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  26059. word32 outSz = sigSz;
  26060. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  26061. if (ret == 0)
  26062. ret = (int)outSz;
  26063. }
  26064. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  26065. #if defined(HAVE_PQC)
  26066. #if defined(HAVE_FALCON)
  26067. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  26068. word32 outSz = sigSz;
  26069. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  26070. if (ret == 0)
  26071. ret = outSz;
  26072. }
  26073. #endif /* HAVE_FALCON */
  26074. #if defined(HAVE_DILITHIUM)
  26075. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  26076. dilithiumKey) {
  26077. word32 outSz = sigSz;
  26078. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  26079. if (ret == 0)
  26080. ret = outSz;
  26081. }
  26082. #endif /* HAVE_DILITHIUM */
  26083. #if defined(HAVE_SPHINCS)
  26084. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  26085. !dilithiumKey && sphincsKey) {
  26086. word32 outSz = sigSz;
  26087. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  26088. if (ret == 0)
  26089. ret = outSz;
  26090. }
  26091. #endif /* HAVE_SPHINCS */
  26092. #endif /* HAVE_PQC */
  26093. break;
  26094. }
  26095. exit_ms:
  26096. #ifdef WOLFSSL_ASYNC_CRYPT
  26097. if (ret == WC_PENDING_E) {
  26098. return ret;
  26099. }
  26100. #endif
  26101. #ifndef NO_RSA
  26102. if (rsaKey) {
  26103. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26104. }
  26105. #endif /* !NO_RSA */
  26106. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26107. certSignCtx->digest = NULL;
  26108. /* reset state */
  26109. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  26110. if (ret < 0) {
  26111. WOLFSSL_ERROR_VERBOSE(ret);
  26112. }
  26113. return ret;
  26114. }
  26115. #ifdef WOLFSSL_ASN_TEMPLATE
  26116. /* Generate a random integer value of at most len bytes.
  26117. *
  26118. * Most-significant bit will not be set when maximum size.
  26119. * Random value may be smaller than maximum size in bytes.
  26120. *
  26121. * @param [in] rng Random number generator.
  26122. * @param [out] out Buffer to hold integer value.
  26123. * @param [in] len Maximum number of bytes of integer.
  26124. * @return 0 on success.
  26125. * @return -ve when random number generation failed.
  26126. */
  26127. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  26128. {
  26129. int ret;
  26130. /* Generate random number. */
  26131. ret = wc_RNG_GenerateBlock(rng, out, len);
  26132. if (ret == 0) {
  26133. int i;
  26134. /* Clear the top bit to make positive. */
  26135. out[0] &= 0x7f;
  26136. /* Find first non-zero byte. One zero byte is valid though. */
  26137. for (i = 0; i < (int)len - 1; i++) {
  26138. if (out[i] != 0) {
  26139. break;
  26140. }
  26141. }
  26142. if (i != 0) {
  26143. /* Remove leading zeros. */
  26144. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  26145. }
  26146. }
  26147. return ret;
  26148. }
  26149. /* ASN.1 template for a Certificate.
  26150. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  26151. */
  26152. static const ASNItem sigASN[] = {
  26153. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26154. /* tbsCertificate */
  26155. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26156. /* signatureAlgorithm */
  26157. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  26158. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  26159. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  26160. /* signatureValue */
  26161. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  26162. };
  26163. enum {
  26164. SIGASN_IDX_SEQ = 0,
  26165. SIGASN_IDX_TBS_SEQ,
  26166. SIGASN_IDX_SIGALGO_SEQ,
  26167. SIGASN_IDX_SIGALGO_OID,
  26168. SIGASN_IDX_SIGALGO_NULL,
  26169. SIGASN_IDX_SIGNATURE
  26170. };
  26171. /* Number of items in ASN.1 template for a Certificate. */
  26172. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  26173. #endif
  26174. /* add signature to end of buffer, size of buffer assumed checked, return
  26175. new length */
  26176. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  26177. int sigAlgoType)
  26178. {
  26179. #ifndef WOLFSSL_ASN_TEMPLATE
  26180. byte seq[MAX_SEQ_SZ];
  26181. word32 idx, seqSz;
  26182. if ((bodySz < 0) || (sigSz < 0))
  26183. return BUFFER_E;
  26184. idx = (word32)bodySz;
  26185. /* algo */
  26186. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  26187. /* bit string */
  26188. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  26189. /* signature */
  26190. if (buf)
  26191. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  26192. idx += (word32)sigSz;
  26193. /* make room for overall header */
  26194. seqSz = SetSequence(idx, seq);
  26195. if (buf) {
  26196. XMEMMOVE(buf + seqSz, buf, idx);
  26197. XMEMCPY(buf, seq, seqSz);
  26198. }
  26199. return (int)(idx + seqSz);
  26200. #else
  26201. DECL_ASNSETDATA(dataASN, sigASN_Length);
  26202. word32 seqSz;
  26203. int sz;
  26204. int ret = 0;
  26205. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  26206. /* In place, put body between SEQUENCE and signature. */
  26207. if (ret == 0) {
  26208. /* Set signature OID and signature data. */
  26209. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  26210. oidSigType);
  26211. if (IsSigAlgoECC((word32)sigAlgoType)) {
  26212. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  26213. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  26214. }
  26215. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  26216. /* Calculate size of signature data. */
  26217. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  26218. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  26219. }
  26220. if (ret == 0) {
  26221. /* Calculate size of outer sequence by calculating size of the encoded
  26222. * length and adding 1 for tag. */
  26223. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  26224. if (buf != NULL) {
  26225. /* Move body to after sequence. */
  26226. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  26227. }
  26228. /* Leave space for body in encoding. */
  26229. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  26230. (word32)bodySz);
  26231. /* Calculate overall size and put in offsets and lengths. */
  26232. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  26233. }
  26234. if ((ret == 0) && (buf != NULL)) {
  26235. /* Write SEQUENCE and signature around body. */
  26236. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  26237. }
  26238. if (ret == 0) {
  26239. /* Return the encoding size. */
  26240. ret = sz;
  26241. }
  26242. FREE_ASNSETDATA(dataASN, NULL);
  26243. return ret;
  26244. #endif /* WOLFSSL_ASN_TEMPLATE */
  26245. }
  26246. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  26247. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  26248. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  26249. DsaKey* dsaKey, ed25519_key* ed25519Key,
  26250. ed448_key* ed448Key, falcon_key* falconKey,
  26251. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  26252. {
  26253. #ifndef WOLFSSL_ASN_TEMPLATE
  26254. int ret;
  26255. #ifdef WOLFSSL_SMALL_STACK
  26256. DerCert* der;
  26257. #else
  26258. DerCert der[1];
  26259. #endif
  26260. if (derBuffer == NULL)
  26261. return BAD_FUNC_ARG;
  26262. if (eccKey)
  26263. cert->keyType = ECC_KEY;
  26264. else if (rsaKey)
  26265. cert->keyType = RSA_KEY;
  26266. else if (dsaKey)
  26267. cert->keyType = DSA_KEY;
  26268. else if (ed25519Key)
  26269. cert->keyType = ED25519_KEY;
  26270. else if (ed448Key)
  26271. cert->keyType = ED448_KEY;
  26272. #ifdef HAVE_PQC
  26273. #ifdef HAVE_FALCON
  26274. else if ((falconKey != NULL) && (falconKey->level == 1))
  26275. cert->keyType = FALCON_LEVEL1_KEY;
  26276. else if ((falconKey != NULL) && (falconKey->level == 5))
  26277. cert->keyType = FALCON_LEVEL5_KEY;
  26278. #endif /* HAVE_FALCON */
  26279. #ifdef HAVE_DILITHIUM
  26280. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26281. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26282. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26283. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26284. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26285. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26286. #endif /* HAVE_DILITHIUM */
  26287. #ifdef HAVE_SPHINCS
  26288. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26289. && (sphincsKey->optim == FAST_VARIANT))
  26290. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26291. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26292. && (sphincsKey->optim == FAST_VARIANT))
  26293. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26294. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26295. && (sphincsKey->optim == FAST_VARIANT))
  26296. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26297. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26298. && (sphincsKey->optim == SMALL_VARIANT))
  26299. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26300. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26301. && (sphincsKey->optim == SMALL_VARIANT))
  26302. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26303. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26304. && (sphincsKey->optim == SMALL_VARIANT))
  26305. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26306. #endif /* HAVE_SPHINCS */
  26307. #endif /* HAVE_PQC */
  26308. else
  26309. return BAD_FUNC_ARG;
  26310. #ifdef WOLFSSL_SMALL_STACK
  26311. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26312. if (der == NULL)
  26313. return MEMORY_E;
  26314. #endif
  26315. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  26316. ed448Key, falconKey, dilithiumKey, sphincsKey);
  26317. if (ret == 0) {
  26318. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26319. ret = BUFFER_E;
  26320. else
  26321. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  26322. }
  26323. #ifdef WOLFSSL_SMALL_STACK
  26324. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26325. #endif
  26326. return ret;
  26327. #else
  26328. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  26329. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  26330. word32 publicKeySz = 0;
  26331. word32 issuerSz = 0;
  26332. word32 subjectSz = 0;
  26333. word32 extSz = 0;
  26334. int sz = 0;
  26335. int ret = 0;
  26336. word32 issRawLen = 0;
  26337. word32 sbjRawLen = 0;
  26338. /* Unused without OQS */
  26339. (void)falconKey;
  26340. (void)dilithiumKey;
  26341. (void)sphincsKey;
  26342. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  26343. if (ret == 0) {
  26344. /* Set key type into certificate object based on key passed in. */
  26345. if (rsaKey) {
  26346. cert->keyType = RSA_KEY;
  26347. }
  26348. else if (eccKey) {
  26349. cert->keyType = ECC_KEY;
  26350. }
  26351. else if (dsaKey) {
  26352. cert->keyType = DSA_KEY;
  26353. }
  26354. else if (ed25519Key) {
  26355. cert->keyType = ED25519_KEY;
  26356. }
  26357. else if (ed448Key) {
  26358. cert->keyType = ED448_KEY;
  26359. }
  26360. #ifdef HAVE_PQC
  26361. #ifdef HAVE_FALCON
  26362. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26363. cert->keyType = FALCON_LEVEL1_KEY;
  26364. }
  26365. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26366. cert->keyType = FALCON_LEVEL5_KEY;
  26367. }
  26368. #endif /* HAVE_FALCON */
  26369. #ifdef HAVE_DILITHIUM
  26370. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26371. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26372. }
  26373. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26374. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26375. }
  26376. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26377. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26378. }
  26379. #endif /* HAVE_DILITHIUM */
  26380. #ifdef HAVE_SPHINCS
  26381. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26382. && (sphincsKey->optim == FAST_VARIANT)) {
  26383. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26384. }
  26385. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26386. && (sphincsKey->optim == FAST_VARIANT)) {
  26387. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26388. }
  26389. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26390. && (sphincsKey->optim == FAST_VARIANT)) {
  26391. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26392. }
  26393. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26394. && (sphincsKey->optim == SMALL_VARIANT)) {
  26395. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26396. }
  26397. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26398. && (sphincsKey->optim == SMALL_VARIANT)) {
  26399. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26400. }
  26401. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26402. && (sphincsKey->optim == SMALL_VARIANT)) {
  26403. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26404. }
  26405. #endif /* HAVE_SPHINCS */
  26406. #endif /* HAVE_PQC */
  26407. else {
  26408. ret = BAD_FUNC_ARG;
  26409. }
  26410. }
  26411. if ((ret == 0) && (cert->serialSz == 0)) {
  26412. /* Generate random serial number. */
  26413. cert->serialSz = CTC_GEN_SERIAL_SZ;
  26414. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  26415. }
  26416. if (ret == 0) {
  26417. /* Determine issuer name size. */
  26418. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26419. defined(WOLFSSL_CERT_REQ)
  26420. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  26421. if (issRawLen > 0) {
  26422. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  26423. }
  26424. else
  26425. #endif
  26426. {
  26427. /* Calculate issuer name encoding size. If the cert is self-signed
  26428. * use the subject instead of the issuer. */
  26429. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  26430. &cert->subject : &cert->issuer, cert->heap);
  26431. issuerSz = (word32)ret;
  26432. }
  26433. }
  26434. if (ret >= 0) {
  26435. /* Determine subject name size. */
  26436. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26437. defined(WOLFSSL_CERT_REQ)
  26438. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26439. if (sbjRawLen > 0) {
  26440. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  26441. }
  26442. else
  26443. #endif
  26444. {
  26445. /* Calculate subject name encoding size. */
  26446. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  26447. cert->heap);
  26448. subjectSz = (word32)ret;
  26449. }
  26450. }
  26451. if (ret >= 0) {
  26452. /* Calculate public key encoding size. */
  26453. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26454. eccKey, ed25519Key, ed448Key, dsaKey);
  26455. publicKeySz = (word32)ret;
  26456. }
  26457. if (ret >= 0) {
  26458. /* Calculate extensions encoding size - may be 0. */
  26459. ret = EncodeExtensions(cert, NULL, 0, 0);
  26460. extSz = (word32)ret;
  26461. }
  26462. if (ret >= 0) {
  26463. /* Don't write out outer sequence - only doing body. */
  26464. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  26465. /* Set version, serial number and signature OID */
  26466. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  26467. (byte)cert->version);
  26468. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  26469. (word32)cert->serialSz);
  26470. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  26471. (word32)cert->sigType, oidSigType);
  26472. if (IsSigAlgoECC((word32)cert->sigType)) {
  26473. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  26474. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  26475. }
  26476. #ifdef WC_RSA_PSS
  26477. /* TODO: Encode RSA PSS parameters. */
  26478. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  26479. #endif
  26480. if (issRawLen > 0) {
  26481. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26482. defined(WOLFSSL_CERT_REQ)
  26483. /* Put in encoded issuer name. */
  26484. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  26485. cert->issRaw, issuerSz);
  26486. #endif
  26487. }
  26488. else {
  26489. /* Leave space for issuer name. */
  26490. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  26491. NULL, issuerSz);
  26492. }
  26493. if (cert->beforeDateSz && cert->afterDateSz) {
  26494. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  26495. /* Make space for before date data. */
  26496. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  26497. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  26498. /* Don't put out Generalized Time before data. */
  26499. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  26500. }
  26501. else {
  26502. /* Don't put out UTC before data. */
  26503. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  26504. /* Make space for before date data. */
  26505. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  26506. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  26507. }
  26508. if (cert->afterDate[0] == ASN_UTC_TIME) {
  26509. /* Make space for after date data. */
  26510. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  26511. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  26512. /* Don't put out UTC Generalized Time after data. */
  26513. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  26514. }
  26515. else {
  26516. /* Don't put out UTC after data. */
  26517. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  26518. /* Make space for after date data. */
  26519. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  26520. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  26521. }
  26522. }
  26523. else
  26524. {
  26525. /* Don't put out UTC before data. */
  26526. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  26527. /* Make space for before date data. */
  26528. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  26529. NULL, ASN_GEN_TIME_SZ);
  26530. /* Don't put out UTC after data. */
  26531. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  26532. /* Make space for after date data. */
  26533. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  26534. NULL, ASN_GEN_TIME_SZ);
  26535. }
  26536. if (sbjRawLen > 0) {
  26537. /* Put in encoded subject name. */
  26538. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26539. defined(WOLFSSL_CERT_REQ)
  26540. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  26541. cert->sbjRaw, subjectSz);
  26542. #endif
  26543. }
  26544. else {
  26545. /* Leave space for subject name. */
  26546. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  26547. NULL, subjectSz);
  26548. }
  26549. /* Leave space for public key. */
  26550. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  26551. NULL, publicKeySz);
  26552. /* Replacement buffer instead of algorithm identifier items. */
  26553. SetASNItem_NoOut(dataASN,
  26554. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  26555. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  26556. /* issuerUniqueID and subjectUniqueID not supported. */
  26557. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  26558. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  26559. /* Leave space for extensions if any set into certificate object. */
  26560. if (extSz > 0) {
  26561. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  26562. }
  26563. else {
  26564. SetASNItem_NoOutNode(dataASN, x509CertASN,
  26565. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  26566. }
  26567. /* No signature - added later. */
  26568. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  26569. X509CERTASN_IDX_SIGNATURE);
  26570. /* Calculate encoded certificate body size. */
  26571. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  26572. }
  26573. /* Check buffer is big enough for encoded data. */
  26574. if ((ret == 0) && (sz > (int)derSz)) {
  26575. ret = BUFFER_E;
  26576. }
  26577. if (ret == 0) {
  26578. /* Encode certificate body into buffer. */
  26579. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  26580. if (issRawLen == 0) {
  26581. /* Encode issuer name into buffer. Use the subject as the issuer
  26582. * if it is self-signed. Size will be correct because we did the
  26583. * same for size. */
  26584. ret = SetNameEx(
  26585. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  26586. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  26587. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  26588. }
  26589. }
  26590. if ((ret >= 0) && (sbjRawLen == 0)) {
  26591. /* Encode subject name into buffer. */
  26592. ret = SetNameEx(
  26593. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  26594. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  26595. &cert->subject, cert->heap);
  26596. }
  26597. if (ret >= 0) {
  26598. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  26599. {
  26600. /* Encode validity into buffer. */
  26601. ret = SetValidity(
  26602. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  26603. .data.buffer.data,
  26604. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  26605. .data.buffer.data, cert->daysValid);
  26606. }
  26607. }
  26608. if (ret >= 0) {
  26609. /* Encode public key into buffer. */
  26610. ret = EncodePublicKey(cert->keyType,
  26611. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  26612. .data.buffer.data,
  26613. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  26614. .data.buffer.length,
  26615. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26616. }
  26617. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  26618. /* Encode extensions into buffer. */
  26619. ret = EncodeExtensions(cert,
  26620. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  26621. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  26622. }
  26623. if (ret >= 0) {
  26624. /* Store encoded certificate body size. */
  26625. cert->bodySz = sz;
  26626. /* Return the encoding size. */
  26627. ret = sz;
  26628. }
  26629. FREE_ASNSETDATA(dataASN, cert->heap);
  26630. return ret;
  26631. #endif
  26632. }
  26633. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26634. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26635. void* key, WC_RNG* rng)
  26636. {
  26637. RsaKey* rsaKey = NULL;
  26638. DsaKey* dsaKey = NULL;
  26639. ecc_key* eccKey = NULL;
  26640. ed25519_key* ed25519Key = NULL;
  26641. ed448_key* ed448Key = NULL;
  26642. falcon_key* falconKey = NULL;
  26643. dilithium_key* dilithiumKey = NULL;
  26644. sphincs_key* sphincsKey = NULL;
  26645. if (keyType == RSA_TYPE)
  26646. rsaKey = (RsaKey*)key;
  26647. else if (keyType == DSA_TYPE)
  26648. dsaKey = (DsaKey*)key;
  26649. else if (keyType == ECC_TYPE)
  26650. eccKey = (ecc_key*)key;
  26651. else if (keyType == ED25519_TYPE)
  26652. ed25519Key = (ed25519_key*)key;
  26653. else if (keyType == ED448_TYPE)
  26654. ed448Key = (ed448_key*)key;
  26655. else if (keyType == FALCON_LEVEL1_TYPE)
  26656. falconKey = (falcon_key*)key;
  26657. else if (keyType == FALCON_LEVEL5_TYPE)
  26658. falconKey = (falcon_key*)key;
  26659. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26660. dilithiumKey = (dilithium_key*)key;
  26661. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26662. dilithiumKey = (dilithium_key*)key;
  26663. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26664. dilithiumKey = (dilithium_key*)key;
  26665. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26666. sphincsKey = (sphincs_key*)key;
  26667. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26668. sphincsKey = (sphincs_key*)key;
  26669. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26670. sphincsKey = (sphincs_key*)key;
  26671. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26672. sphincsKey = (sphincs_key*)key;
  26673. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26674. sphincsKey = (sphincs_key*)key;
  26675. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26676. sphincsKey = (sphincs_key*)key;
  26677. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  26678. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26679. sphincsKey);
  26680. }
  26681. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26682. WOLFSSL_ABI
  26683. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  26684. ecc_key* eccKey, WC_RNG* rng)
  26685. {
  26686. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  26687. NULL, NULL, NULL, NULL);
  26688. }
  26689. #ifdef WOLFSSL_CERT_REQ
  26690. #ifndef WOLFSSL_ASN_TEMPLATE
  26691. /* return size of data set on success
  26692. * if getting size only then attr and oid should be NULL
  26693. */
  26694. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  26695. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  26696. word32 extSz)
  26697. {
  26698. word32 totalSz = 0;
  26699. word32 seqSz = 0;
  26700. word32 setSz = 0;
  26701. word32 strSz = 0;
  26702. byte seq[MAX_SEQ_SZ];
  26703. byte set[MAX_SET_SZ];
  26704. byte str[MAX_PRSTR_SZ];
  26705. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  26706. totalSz += oidSz;
  26707. if (extSz > 0) {
  26708. totalSz += setSz = SetSet(extSz, set);
  26709. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26710. totalSz += extSz;
  26711. }
  26712. else {
  26713. if (printable) {
  26714. strSz = SetPrintableString(attrSz, str);
  26715. totalSz += strSz;
  26716. }
  26717. else {
  26718. totalSz += strSz = SetUTF8String(attrSz, str);
  26719. }
  26720. totalSz += setSz = SetSet(strSz + attrSz, set);
  26721. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26722. totalSz += attrSz;
  26723. }
  26724. if (oid) {
  26725. XMEMCPY(&output[*idx], seq, seqSz);
  26726. *idx += seqSz;
  26727. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  26728. XMEMCPY(&output[*idx], oid, oidSz);
  26729. *idx += oidSz;
  26730. XMEMCPY(&output[*idx], set, setSz);
  26731. *idx += setSz;
  26732. if (strSz > 0) {
  26733. XMEMCPY(&output[*idx], str, strSz);
  26734. *idx += strSz;
  26735. if (attrSz > 0) {
  26736. XMEMCPY(&output[*idx], attr, attrSz);
  26737. *idx += attrSz;
  26738. }
  26739. }
  26740. }
  26741. return totalSz;
  26742. }
  26743. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  26744. {
  26745. word32 sz = 0; /* overall size */
  26746. word32 setSz = 0;
  26747. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26748. sz++;
  26749. if (cert->challengePw[0]) {
  26750. setSz += SetReqAttribSingle(output, &sz, NULL,
  26751. (word32)XSTRLEN(cert->challengePw), NULL,
  26752. sizeof(attrChallengePasswordOid),
  26753. (byte)cert->challengePwPrintableString, 0);
  26754. }
  26755. if (cert->unstructuredName[0]) {
  26756. setSz += SetReqAttribSingle(output, &sz, NULL,
  26757. (word32)XSTRLEN(cert->unstructuredName), NULL,
  26758. sizeof(attrUnstructuredNameOid), 1, 0);
  26759. }
  26760. if (extSz) {
  26761. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26762. sizeof(attrExtensionRequestOid), 1, extSz);
  26763. }
  26764. /* Put the pieces together. */
  26765. sz += SetLength(setSz, &output[sz]);
  26766. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26767. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26768. return REQ_ATTRIBUTE_E;
  26769. }
  26770. if (cert->challengePw[0]) {
  26771. SetReqAttribSingle(output, &sz, cert->challengePw,
  26772. (word32)XSTRLEN(cert->challengePw),
  26773. &attrChallengePasswordOid[0],
  26774. sizeof(attrChallengePasswordOid),
  26775. (byte)cert->challengePwPrintableString, 0);
  26776. }
  26777. if (cert->unstructuredName[0]) {
  26778. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26779. (word32)XSTRLEN(cert->unstructuredName),
  26780. &attrUnstructuredNameOid[0],
  26781. sizeof(attrUnstructuredNameOid), 1, 0);
  26782. }
  26783. if (extSz) {
  26784. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26785. sizeof(attrExtensionRequestOid), 1, extSz);
  26786. /* The actual extension data will be tacked onto the output later. */
  26787. }
  26788. return (int)sz;
  26789. }
  26790. #ifdef WOLFSSL_CUSTOM_OID
  26791. /* encode a custom oid and value */
  26792. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26793. CertOidField* custom)
  26794. {
  26795. int idx = 0, cust_lenSz, cust_oidSz;
  26796. if (cert == NULL || output == NULL || custom == NULL) {
  26797. return BAD_FUNC_ARG;
  26798. }
  26799. if (custom->oid == NULL || custom->oidSz <= 0) {
  26800. return 0; /* none set */
  26801. }
  26802. /* Octet String header */
  26803. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26804. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26805. /* check for output buffer room */
  26806. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26807. outSz) {
  26808. return BUFFER_E;
  26809. }
  26810. /* put sequence with total */
  26811. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26812. output);
  26813. /* put oid header */
  26814. idx += SetObjectId(custom->oidSz, output+idx);
  26815. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26816. idx += custom->oidSz;
  26817. /* put value */
  26818. idx += SetOctetString(custom->valSz, output+idx);
  26819. XMEMCPY(output+idx, custom->val, custom->valSz);
  26820. idx += custom->valSz;
  26821. return idx;
  26822. }
  26823. #endif /* WOLFSSL_CUSTOM_OID */
  26824. /* encode info from cert into DER encoded format */
  26825. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26826. DsaKey* dsaKey, ecc_key* eccKey,
  26827. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26828. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26829. sphincs_key* sphincsKey)
  26830. {
  26831. int ret;
  26832. (void)eccKey;
  26833. (void)ed25519Key;
  26834. (void)ed448Key;
  26835. (void)falconKey;
  26836. (void)dilithiumKey;
  26837. (void)sphincsKey;
  26838. if (cert == NULL || der == NULL)
  26839. return BAD_FUNC_ARG;
  26840. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26841. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26842. falconKey == NULL) {
  26843. return PUBLIC_KEY_E;
  26844. }
  26845. /* init */
  26846. XMEMSET(der, 0, sizeof(DerCert));
  26847. /* version */
  26848. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  26849. /* subject name */
  26850. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26851. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26852. /* Use the raw subject */
  26853. int idx;
  26854. der->subjectSz = (int)min(sizeof(der->subject),
  26855. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26856. /* header */
  26857. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  26858. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26859. return SUBJECT_E;
  26860. }
  26861. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26862. (size_t)der->subjectSz);
  26863. der->subjectSz += idx;
  26864. }
  26865. else
  26866. #endif
  26867. {
  26868. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26869. &cert->subject, cert->heap);
  26870. }
  26871. if (der->subjectSz <= 0)
  26872. return SUBJECT_E;
  26873. /* public key */
  26874. #ifndef NO_RSA
  26875. if (cert->keyType == RSA_KEY) {
  26876. if (rsaKey == NULL)
  26877. return PUBLIC_KEY_E;
  26878. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26879. sizeof(der->publicKey), 1);
  26880. }
  26881. #endif
  26882. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26883. if (cert->keyType == DSA_KEY) {
  26884. if (dsaKey == NULL)
  26885. return PUBLIC_KEY_E;
  26886. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26887. sizeof(der->publicKey), 1);
  26888. }
  26889. #endif
  26890. #ifdef HAVE_ECC
  26891. if (cert->keyType == ECC_KEY) {
  26892. if (eccKey == NULL)
  26893. return PUBLIC_KEY_E;
  26894. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26895. sizeof(der->publicKey), 1, 0);
  26896. }
  26897. #endif
  26898. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26899. if (cert->keyType == ED25519_KEY) {
  26900. if (ed25519Key == NULL)
  26901. return PUBLIC_KEY_E;
  26902. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26903. (word32)sizeof(der->publicKey), 1);
  26904. }
  26905. #endif
  26906. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26907. if (cert->keyType == ED448_KEY) {
  26908. if (ed448Key == NULL)
  26909. return PUBLIC_KEY_E;
  26910. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26911. (word32)sizeof(der->publicKey), 1);
  26912. }
  26913. #endif
  26914. #if defined(HAVE_PQC)
  26915. #if defined(HAVE_FALCON)
  26916. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26917. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26918. if (falconKey == NULL)
  26919. return PUBLIC_KEY_E;
  26920. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26921. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26922. }
  26923. #endif
  26924. #if defined(HAVE_DILITHIUM)
  26925. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26926. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26927. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26928. if (dilithiumKey == NULL)
  26929. return PUBLIC_KEY_E;
  26930. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26931. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26932. }
  26933. #endif
  26934. #if defined(HAVE_SPHINCS)
  26935. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26936. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26937. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26938. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26939. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26940. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26941. if (sphincsKey == NULL)
  26942. return PUBLIC_KEY_E;
  26943. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26944. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26945. }
  26946. #endif
  26947. #endif /* HAVE_PQC */
  26948. if (der->publicKeySz <= 0)
  26949. return PUBLIC_KEY_E;
  26950. /* set the extensions */
  26951. der->extensionsSz = 0;
  26952. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26953. * The pathLenConstraint field is meaningful only if the CA boolean is
  26954. * asserted and the key usage extension, if present, asserts the
  26955. * keyCertSign bit */
  26956. /* Set CA and path length */
  26957. if ((cert->isCA) && (cert->pathLenSet)
  26958. #ifdef WOLFSSL_CERT_EXT
  26959. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26960. #endif
  26961. ) {
  26962. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26963. if (der->caSz <= 0)
  26964. return CA_TRUE_E;
  26965. der->extensionsSz += der->caSz;
  26966. }
  26967. /* Set CA */
  26968. else if (cert->isCA) {
  26969. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26970. if (der->caSz <= 0)
  26971. return CA_TRUE_E;
  26972. der->extensionsSz += der->caSz;
  26973. }
  26974. /* Set Basic Constraint */
  26975. else if (cert->basicConstSet) {
  26976. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26977. if (der->caSz <= 0)
  26978. return EXTENSIONS_E;
  26979. der->extensionsSz += der->caSz;
  26980. }
  26981. else
  26982. der->caSz = 0;
  26983. #ifdef WOLFSSL_ALT_NAMES
  26984. /* Alternative Name */
  26985. if (cert->altNamesSz) {
  26986. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26987. cert->altNames, (word32)cert->altNamesSz,
  26988. cert->altNamesCrit);
  26989. if (der->altNamesSz <= 0)
  26990. return ALT_NAME_E;
  26991. der->extensionsSz += der->altNamesSz;
  26992. }
  26993. else
  26994. der->altNamesSz = 0;
  26995. #endif
  26996. #ifdef WOLFSSL_CERT_EXT
  26997. /* SKID */
  26998. if (cert->skidSz) {
  26999. /* check the provided SKID size */
  27000. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  27001. return SKID_E;
  27002. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  27003. cert->skid, (word32)cert->skidSz);
  27004. if (der->skidSz <= 0)
  27005. return SKID_E;
  27006. der->extensionsSz += der->skidSz;
  27007. }
  27008. else
  27009. der->skidSz = 0;
  27010. /* Key Usage */
  27011. if (cert->keyUsage != 0) {
  27012. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  27013. cert->keyUsage);
  27014. if (der->keyUsageSz <= 0)
  27015. return KEYUSAGE_E;
  27016. der->extensionsSz += der->keyUsageSz;
  27017. }
  27018. else
  27019. der->keyUsageSz = 0;
  27020. /* Extended Key Usage */
  27021. if (cert->extKeyUsage != 0) {
  27022. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  27023. sizeof(der->extKeyUsage), cert->extKeyUsage);
  27024. if (der->extKeyUsageSz <= 0)
  27025. return EXTKEYUSAGE_E;
  27026. der->extensionsSz += der->extKeyUsageSz;
  27027. }
  27028. else
  27029. der->extKeyUsageSz = 0;
  27030. #endif /* WOLFSSL_CERT_EXT */
  27031. #ifdef WOLFSSL_CUSTOM_OID
  27032. /* encode a custom oid and value */
  27033. /* zero returns, means none set */
  27034. ret = SetCustomObjectId(cert, der->extCustom,
  27035. sizeof(der->extCustom), &cert->extCustom);
  27036. if (ret < 0)
  27037. return ret;
  27038. der->extCustomSz = ret;
  27039. der->extensionsSz += der->extCustomSz;
  27040. #endif
  27041. /* put extensions */
  27042. if (der->extensionsSz > 0) {
  27043. /* put the start of sequence (ID, Size) */
  27044. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  27045. der->extensions);
  27046. if (der->extensionsSz <= 0)
  27047. return EXTENSIONS_E;
  27048. /* put CA */
  27049. if (der->caSz) {
  27050. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27051. &der->extensionsSz,
  27052. der->ca, der->caSz);
  27053. if (ret <= 0)
  27054. return EXTENSIONS_E;
  27055. }
  27056. #ifdef WOLFSSL_ALT_NAMES
  27057. /* put Alternative Names */
  27058. if (der->altNamesSz) {
  27059. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27060. &der->extensionsSz,
  27061. der->altNames, der->altNamesSz);
  27062. if (ret <= 0)
  27063. return EXTENSIONS_E;
  27064. }
  27065. #endif
  27066. #ifdef WOLFSSL_CERT_EXT
  27067. /* put SKID */
  27068. if (der->skidSz) {
  27069. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27070. &der->extensionsSz,
  27071. der->skid, der->skidSz);
  27072. if (ret <= 0)
  27073. return EXTENSIONS_E;
  27074. }
  27075. /* put AKID */
  27076. if (der->akidSz) {
  27077. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27078. &der->extensionsSz,
  27079. der->akid, der->akidSz);
  27080. if (ret <= 0)
  27081. return EXTENSIONS_E;
  27082. }
  27083. /* put KeyUsage */
  27084. if (der->keyUsageSz) {
  27085. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27086. &der->extensionsSz,
  27087. der->keyUsage, der->keyUsageSz);
  27088. if (ret <= 0)
  27089. return EXTENSIONS_E;
  27090. }
  27091. /* put ExtendedKeyUsage */
  27092. if (der->extKeyUsageSz) {
  27093. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27094. &der->extensionsSz,
  27095. der->extKeyUsage, der->extKeyUsageSz);
  27096. if (ret <= 0)
  27097. return EXTENSIONS_E;
  27098. }
  27099. #ifdef WOLFSSL_CUSTOM_OID
  27100. if (der->extCustomSz) {
  27101. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  27102. &der->extensionsSz,
  27103. der->extCustom, der->extCustomSz);
  27104. if (ret <= 0)
  27105. return EXTENSIONS_E;
  27106. }
  27107. #endif
  27108. #endif /* WOLFSSL_CERT_EXT */
  27109. }
  27110. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  27111. if (der->attribSz <= 0)
  27112. return REQ_ATTRIBUTE_E;
  27113. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  27114. der->extensionsSz + der->attribSz;
  27115. return 0;
  27116. }
  27117. /* write DER encoded cert req to buffer, size already checked */
  27118. static int WriteCertReqBody(DerCert* der, byte* buf)
  27119. {
  27120. int idx;
  27121. /* signed part header */
  27122. idx = (int)SetSequence((word32)der->total, buf);
  27123. /* version */
  27124. if (buf)
  27125. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  27126. idx += der->versionSz;
  27127. /* subject */
  27128. if (buf)
  27129. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  27130. idx += der->subjectSz;
  27131. /* public key */
  27132. if (buf)
  27133. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  27134. idx += der->publicKeySz;
  27135. /* attributes */
  27136. if (buf)
  27137. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  27138. idx += der->attribSz;
  27139. /* extensions */
  27140. if (der->extensionsSz) {
  27141. if (buf)
  27142. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  27143. sizeof(der->extensions)));
  27144. idx += der->extensionsSz;
  27145. }
  27146. return idx;
  27147. }
  27148. #endif
  27149. #ifdef WOLFSSL_ASN_TEMPLATE
  27150. /* ASN.1 template for Certificate Request body.
  27151. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  27152. */
  27153. static const ASNItem certReqBodyASN[] = {
  27154. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  27155. /* version */
  27156. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  27157. /* subject */
  27158. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  27159. /* subjectPKInfo */
  27160. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  27161. /* attributes*/
  27162. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  27163. /* Challenge Password Attribute */
  27164. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  27165. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27166. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  27167. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  27168. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  27169. /* ATTRS_USN_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  27170. /* ATTRS_USN_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27171. /* ATTRS_USN_SET */ { 3, ASN_SET, 1, 1, 0 },
  27172. /* ATTRS_USN_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  27173. /* ATTRS_USN_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  27174. /* Extensions Attribute */
  27175. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  27176. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27177. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  27178. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  27179. };
  27180. enum {
  27181. CERTREQBODYASN_IDX_SEQ = 0,
  27182. CERTREQBODYASN_IDX_VER,
  27183. CERTREQBODYASN_IDX_SUBJ_SEQ,
  27184. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  27185. CERTREQBODYASN_IDX_ATTRS,
  27186. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  27187. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  27188. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  27189. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  27190. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  27191. CERTREQBODYASN_IDX_ATTRS_USN_SEQ,
  27192. CERTREQBODYASN_IDX_ATTRS_USN_OID,
  27193. CERTREQBODYASN_IDX_ATTRS_USN_SET,
  27194. CERTREQBODYASN_IDX_ATTRS_USN_PS,
  27195. CERTREQBODYASN_IDX_ATTRS_USN_UTF,
  27196. CERTREQBODYASN_IDX_EXT_SEQ,
  27197. CERTREQBODYASN_IDX_EXT_OID,
  27198. CERTREQBODYASN_IDX_EXT_SET,
  27199. CERTREQBODYASN_IDX_EXT_BODY
  27200. };
  27201. /* Number of items in ASN.1 template for Certificate Request body. */
  27202. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  27203. #endif
  27204. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  27205. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  27206. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27207. falcon_key* falconKey, dilithium_key* dilithiumKey,
  27208. sphincs_key* sphincsKey)
  27209. {
  27210. #ifndef WOLFSSL_ASN_TEMPLATE
  27211. int ret;
  27212. #ifdef WOLFSSL_SMALL_STACK
  27213. DerCert* der;
  27214. #else
  27215. DerCert der[1];
  27216. #endif
  27217. if (eccKey)
  27218. cert->keyType = ECC_KEY;
  27219. else if (rsaKey)
  27220. cert->keyType = RSA_KEY;
  27221. else if (dsaKey)
  27222. cert->keyType = DSA_KEY;
  27223. else if (ed25519Key)
  27224. cert->keyType = ED25519_KEY;
  27225. else if (ed448Key)
  27226. cert->keyType = ED448_KEY;
  27227. #ifdef HAVE_PQC
  27228. #ifdef HAVE_FALCON
  27229. else if ((falconKey != NULL) && (falconKey->level == 1))
  27230. cert->keyType = FALCON_LEVEL1_KEY;
  27231. else if ((falconKey != NULL) && (falconKey->level == 5))
  27232. cert->keyType = FALCON_LEVEL5_KEY;
  27233. #endif /* HAVE_FALCON */
  27234. #ifdef HAVE_DILITHIUM
  27235. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  27236. cert->keyType = DILITHIUM_LEVEL2_KEY;
  27237. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  27238. cert->keyType = DILITHIUM_LEVEL3_KEY;
  27239. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  27240. cert->keyType = DILITHIUM_LEVEL5_KEY;
  27241. #endif /* HAVE_DILITHIUM */
  27242. #ifdef HAVE_SPHINCS
  27243. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27244. && (sphincsKey->optim == FAST_VARIANT))
  27245. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  27246. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27247. && (sphincsKey->optim == FAST_VARIANT))
  27248. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  27249. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27250. && (sphincsKey->optim == FAST_VARIANT))
  27251. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  27252. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27253. && (sphincsKey->optim == SMALL_VARIANT))
  27254. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  27255. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27256. && (sphincsKey->optim == SMALL_VARIANT))
  27257. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  27258. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27259. && (sphincsKey->optim == SMALL_VARIANT))
  27260. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  27261. #endif /* HAVE_SPHINCS */
  27262. #endif /* HAVE_PQC */
  27263. else
  27264. return BAD_FUNC_ARG;
  27265. #ifdef WOLFSSL_SMALL_STACK
  27266. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  27267. DYNAMIC_TYPE_TMP_BUFFER);
  27268. if (der == NULL)
  27269. return MEMORY_E;
  27270. #endif
  27271. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  27272. falconKey, dilithiumKey, sphincsKey);
  27273. if (ret == 0) {
  27274. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  27275. ret = BUFFER_E;
  27276. else
  27277. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  27278. }
  27279. #ifdef WOLFSSL_SMALL_STACK
  27280. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27281. #endif
  27282. return ret;
  27283. #else
  27284. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  27285. word32 publicKeySz = 0;
  27286. word32 subjectSz = 0;
  27287. word32 extSz = 0;
  27288. int sz = 0;
  27289. int ret = 0;
  27290. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27291. word32 sbjRawSz = 0;
  27292. #endif
  27293. /* Unused without OQS */
  27294. (void)falconKey;
  27295. (void)dilithiumKey;
  27296. (void)sphincsKey;
  27297. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  27298. if (ret == 0) {
  27299. /* Set key type into certificate object based on key passed in. */
  27300. if (rsaKey != NULL) {
  27301. cert->keyType = RSA_KEY;
  27302. }
  27303. else if (eccKey != NULL) {
  27304. cert->keyType = ECC_KEY;
  27305. }
  27306. else if (dsaKey != NULL) {
  27307. cert->keyType = DSA_KEY;
  27308. }
  27309. else if (ed25519Key != NULL) {
  27310. cert->keyType = ED25519_KEY;
  27311. }
  27312. else if (ed448Key != NULL) {
  27313. cert->keyType = ED448_KEY;
  27314. }
  27315. #ifdef HAVE_PQC
  27316. #ifdef HAVE_FALCON
  27317. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  27318. cert->keyType = FALCON_LEVEL1_KEY;
  27319. }
  27320. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  27321. cert->keyType = FALCON_LEVEL5_KEY;
  27322. }
  27323. #endif /* HAVE_FALCON */
  27324. #ifdef HAVE_DILITHIUM
  27325. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  27326. cert->keyType = DILITHIUM_LEVEL2_KEY;
  27327. }
  27328. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  27329. cert->keyType = DILITHIUM_LEVEL3_KEY;
  27330. }
  27331. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  27332. cert->keyType = DILITHIUM_LEVEL5_KEY;
  27333. }
  27334. #endif /* HAVE_DILITHIUM */
  27335. #ifdef HAVE_SPHINCS
  27336. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27337. && (sphincsKey->optim == FAST_VARIANT)) {
  27338. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  27339. }
  27340. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27341. && (sphincsKey->optim == FAST_VARIANT)) {
  27342. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  27343. }
  27344. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27345. && (sphincsKey->optim == FAST_VARIANT)) {
  27346. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  27347. }
  27348. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  27349. && (sphincsKey->optim == SMALL_VARIANT)) {
  27350. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  27351. }
  27352. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  27353. && (sphincsKey->optim == SMALL_VARIANT)) {
  27354. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  27355. }
  27356. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  27357. && (sphincsKey->optim == SMALL_VARIANT)) {
  27358. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  27359. }
  27360. #endif /* HAVE_SPHINCS */
  27361. #endif /* HAVE_PQC */
  27362. else {
  27363. ret = BAD_FUNC_ARG;
  27364. }
  27365. }
  27366. if (ret == 0) {
  27367. /* Determine subject name size. */
  27368. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27369. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  27370. if (sbjRawSz > 0) {
  27371. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  27372. }
  27373. else
  27374. #endif
  27375. {
  27376. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  27377. subjectSz = (word32)ret;
  27378. }
  27379. }
  27380. if (ret >= 0) {
  27381. /* Determine encode public key size. */
  27382. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  27383. eccKey, ed25519Key, ed448Key, dsaKey);
  27384. publicKeySz = (word32)ret;
  27385. }
  27386. if (ret >= 0) {
  27387. /* Determine encode extensions size. */
  27388. ret = EncodeExtensions(cert, NULL, 0, 1);
  27389. extSz = (word32)ret;
  27390. }
  27391. if (ret >= 0) {
  27392. /* Set version. */
  27393. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  27394. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27395. if (sbjRawSz > 0) {
  27396. /* Put in encoded subject name. */
  27397. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  27398. subjectSz);
  27399. }
  27400. else
  27401. #endif
  27402. {
  27403. /* Leave space for subject name. */
  27404. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  27405. subjectSz);
  27406. }
  27407. /* Leave space for public key. */
  27408. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  27409. NULL, publicKeySz);
  27410. if (cert->challengePw[0] != '\0') {
  27411. /* Add challenge password attribute. */
  27412. /* Set challenge password OID. */
  27413. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  27414. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  27415. /* Enable the ASN template item with the appropriate tag. */
  27416. if (cert->challengePwPrintableString) {
  27417. /* PRINTABLE_STRING - set buffer */
  27418. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  27419. (byte*)cert->challengePw,
  27420. (word32)XSTRLEN(cert->challengePw));
  27421. /* UTF8STRING - don't encode */
  27422. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  27423. }
  27424. else {
  27425. /* PRINTABLE_STRING - don't encode */
  27426. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  27427. /* UTF8STRING - set buffer */
  27428. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  27429. (byte*)cert->challengePw,
  27430. (word32)XSTRLEN(cert->challengePw));
  27431. }
  27432. }
  27433. else {
  27434. /* Leave out challenge password attribute items. */
  27435. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  27436. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  27437. }
  27438. if (cert->unstructuredName[0] != '\0') {
  27439. /* Add unstructured name attribute. */
  27440. /* Set unstructured name OID. */
  27441. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_USN_OID],
  27442. attrUnstructuredNameOid, sizeof(attrUnstructuredNameOid));
  27443. /* PRINTABLE_STRING - set buffer */
  27444. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_USN_PS],
  27445. (byte*)cert->unstructuredName,
  27446. (word32)XSTRLEN(cert->unstructuredName));
  27447. /* UTF8STRING - don't encode */
  27448. dataASN[CERTREQBODYASN_IDX_ATTRS_USN_UTF].noOut = 1;
  27449. }
  27450. else {
  27451. /* Leave out unstructured name attribute item. */
  27452. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  27453. CERTREQBODYASN_IDX_ATTRS_USN_SEQ, certReqBodyASN_Length);
  27454. }
  27455. if (extSz > 0) {
  27456. /* Set extension attribute OID. */
  27457. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  27458. sizeof(attrExtensionRequestOid));
  27459. /* Leave space for data. */
  27460. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  27461. }
  27462. else {
  27463. /* Leave out extension attribute items. */
  27464. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  27465. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  27466. }
  27467. /* Calculate size of encoded certificate request body. */
  27468. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  27469. &sz);
  27470. }
  27471. /* Check buffer is big enough for encoded data. */
  27472. if ((ret == 0) && (sz > (int)derSz)) {
  27473. ret = BUFFER_E;
  27474. }
  27475. if (ret == 0 && derBuffer != NULL) {
  27476. /* Encode certificate request body into buffer. */
  27477. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  27478. /* Put in generated data */
  27479. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27480. if (sbjRawSz == 0)
  27481. #endif
  27482. {
  27483. /* Encode subject name into space in buffer. */
  27484. ret = SetNameEx(
  27485. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  27486. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  27487. &cert->subject, cert->heap);
  27488. }
  27489. }
  27490. if (ret >= 0 && derBuffer != NULL) {
  27491. /* Encode public key into space in buffer. */
  27492. ret = EncodePublicKey(cert->keyType,
  27493. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  27494. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  27495. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  27496. }
  27497. if ((ret >= 0 && derBuffer != NULL) &&
  27498. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  27499. /* Encode extensions into space in buffer. */
  27500. ret = EncodeExtensions(cert,
  27501. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  27502. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  27503. }
  27504. if (ret >= 0) {
  27505. /* Store encoded certificate request body size. */
  27506. cert->bodySz = sz;
  27507. /* Return the encoding size. */
  27508. ret = sz;
  27509. }
  27510. FREE_ASNSETDATA(dataASN, cert->heap);
  27511. return ret;
  27512. #endif /* WOLFSSL_ASN_TEMPLATE */
  27513. }
  27514. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  27515. void* key)
  27516. {
  27517. RsaKey* rsaKey = NULL;
  27518. DsaKey* dsaKey = NULL;
  27519. ecc_key* eccKey = NULL;
  27520. ed25519_key* ed25519Key = NULL;
  27521. ed448_key* ed448Key = NULL;
  27522. falcon_key* falconKey = NULL;
  27523. dilithium_key* dilithiumKey = NULL;
  27524. sphincs_key* sphincsKey = NULL;
  27525. if (keyType == RSA_TYPE)
  27526. rsaKey = (RsaKey*)key;
  27527. else if (keyType == DSA_TYPE)
  27528. dsaKey = (DsaKey*)key;
  27529. else if (keyType == ECC_TYPE)
  27530. eccKey = (ecc_key*)key;
  27531. else if (keyType == ED25519_TYPE)
  27532. ed25519Key = (ed25519_key*)key;
  27533. else if (keyType == ED448_TYPE)
  27534. ed448Key = (ed448_key*)key;
  27535. else if (keyType == FALCON_LEVEL1_TYPE)
  27536. falconKey = (falcon_key*)key;
  27537. else if (keyType == FALCON_LEVEL5_TYPE)
  27538. falconKey = (falcon_key*)key;
  27539. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27540. dilithiumKey = (dilithium_key*)key;
  27541. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27542. dilithiumKey = (dilithium_key*)key;
  27543. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27544. dilithiumKey = (dilithium_key*)key;
  27545. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27546. sphincsKey = (sphincs_key*)key;
  27547. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27548. sphincsKey = (sphincs_key*)key;
  27549. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27550. sphincsKey = (sphincs_key*)key;
  27551. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27552. sphincsKey = (sphincs_key*)key;
  27553. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27554. sphincsKey = (sphincs_key*)key;
  27555. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27556. sphincsKey = (sphincs_key*)key;
  27557. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  27558. ed25519Key, ed448Key, falconKey, dilithiumKey,
  27559. sphincsKey);
  27560. }
  27561. WOLFSSL_ABI
  27562. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  27563. RsaKey* rsaKey, ecc_key* eccKey)
  27564. {
  27565. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  27566. NULL, NULL, NULL, NULL);
  27567. }
  27568. #endif /* WOLFSSL_CERT_REQ */
  27569. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27570. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  27571. ed448_key* ed448Key, falcon_key* falconKey,
  27572. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  27573. WC_RNG* rng)
  27574. {
  27575. int sigSz = 0;
  27576. void* heap = NULL;
  27577. CertSignCtx certSignCtx_lcl;
  27578. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  27579. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  27580. if (requestSz < 0)
  27581. return requestSz;
  27582. /* locate ctx */
  27583. if (rsaKey) {
  27584. #ifndef NO_RSA
  27585. #ifdef WOLFSSL_ASYNC_CRYPT
  27586. certSignCtx = &rsaKey->certSignCtx;
  27587. #endif
  27588. heap = rsaKey->heap;
  27589. #else
  27590. return NOT_COMPILED_IN;
  27591. #endif /* NO_RSA */
  27592. }
  27593. else if (eccKey) {
  27594. #ifdef HAVE_ECC
  27595. #ifdef WOLFSSL_ASYNC_CRYPT
  27596. certSignCtx = &eccKey->certSignCtx;
  27597. #endif
  27598. heap = eccKey->heap;
  27599. #else
  27600. return NOT_COMPILED_IN;
  27601. #endif /* HAVE_ECC */
  27602. }
  27603. if (certSignCtx->sig == NULL) {
  27604. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  27605. DYNAMIC_TYPE_TMP_BUFFER);
  27606. if (certSignCtx->sig == NULL)
  27607. return MEMORY_E;
  27608. }
  27609. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  27610. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  27611. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  27612. #ifdef WOLFSSL_ASYNC_CRYPT
  27613. if (sigSz == WC_PENDING_E) {
  27614. /* Not free'ing certSignCtx->sig here because it could still be in use
  27615. * with async operations. */
  27616. return sigSz;
  27617. }
  27618. #endif
  27619. if (sigSz >= 0) {
  27620. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  27621. sigSz = BUFFER_E;
  27622. else
  27623. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  27624. sType);
  27625. }
  27626. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27627. certSignCtx->sig = NULL;
  27628. return sigSz;
  27629. }
  27630. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  27631. int keyType, void* key, WC_RNG* rng)
  27632. {
  27633. RsaKey* rsaKey = NULL;
  27634. ecc_key* eccKey = NULL;
  27635. ed25519_key* ed25519Key = NULL;
  27636. ed448_key* ed448Key = NULL;
  27637. falcon_key* falconKey = NULL;
  27638. dilithium_key* dilithiumKey = NULL;
  27639. sphincs_key* sphincsKey = NULL;
  27640. if (keyType == RSA_TYPE)
  27641. rsaKey = (RsaKey*)key;
  27642. else if (keyType == ECC_TYPE)
  27643. eccKey = (ecc_key*)key;
  27644. else if (keyType == ED25519_TYPE)
  27645. ed25519Key = (ed25519_key*)key;
  27646. else if (keyType == ED448_TYPE)
  27647. ed448Key = (ed448_key*)key;
  27648. else if (keyType == FALCON_LEVEL1_TYPE)
  27649. falconKey = (falcon_key*)key;
  27650. else if (keyType == FALCON_LEVEL5_TYPE)
  27651. falconKey = (falcon_key*)key;
  27652. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27653. dilithiumKey = (dilithium_key*)key;
  27654. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27655. dilithiumKey = (dilithium_key*)key;
  27656. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27657. dilithiumKey = (dilithium_key*)key;
  27658. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27659. sphincsKey = (sphincs_key*)key;
  27660. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27661. sphincsKey = (sphincs_key*)key;
  27662. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27663. sphincsKey = (sphincs_key*)key;
  27664. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27665. sphincsKey = (sphincs_key*)key;
  27666. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27667. sphincsKey = (sphincs_key*)key;
  27668. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27669. sphincsKey = (sphincs_key*)key;
  27670. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  27671. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  27672. }
  27673. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27674. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  27675. {
  27676. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  27677. NULL, NULL, NULL, rng);
  27678. }
  27679. WOLFSSL_ABI
  27680. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  27681. RsaKey* key, WC_RNG* rng)
  27682. {
  27683. int ret;
  27684. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  27685. if (ret < 0)
  27686. return ret;
  27687. return wc_SignCert(cert->bodySz, cert->sigType,
  27688. buf, buffSz, key, NULL, rng);
  27689. }
  27690. #ifdef WOLFSSL_CERT_EXT
  27691. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  27692. The raw subject pointer will only be valid while "cert" is valid. */
  27693. WOLFSSL_ABI
  27694. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  27695. {
  27696. int rc = BAD_FUNC_ARG;
  27697. if ((subjectRaw != NULL) && (cert != NULL)) {
  27698. *subjectRaw = cert->sbjRaw;
  27699. rc = 0;
  27700. }
  27701. return rc;
  27702. }
  27703. /* Set KID from public key */
  27704. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27705. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27706. falcon_key* falconKey,
  27707. dilithium_key* dilithiumKey,
  27708. sphincs_key *sphincsKey, int kid_type)
  27709. {
  27710. byte *buf;
  27711. int bufferSz, ret;
  27712. if (cert == NULL ||
  27713. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27714. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27715. sphincsKey == NULL) ||
  27716. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27717. return BAD_FUNC_ARG;
  27718. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27719. DYNAMIC_TYPE_TMP_BUFFER);
  27720. if (buf == NULL)
  27721. return MEMORY_E;
  27722. /* Public Key */
  27723. bufferSz = -1;
  27724. #ifndef NO_RSA
  27725. /* RSA public key */
  27726. if (rsakey != NULL)
  27727. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27728. #endif
  27729. #ifdef HAVE_ECC
  27730. /* ECC public key */
  27731. if (eckey != NULL)
  27732. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27733. #endif
  27734. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27735. /* ED25519 public key */
  27736. if (ed25519Key != NULL) {
  27737. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27738. }
  27739. #endif
  27740. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27741. /* ED448 public key */
  27742. if (ed448Key != NULL) {
  27743. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27744. }
  27745. #endif
  27746. #if defined(HAVE_PQC)
  27747. #if defined(HAVE_FALCON)
  27748. if (falconKey != NULL) {
  27749. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27750. 0);
  27751. }
  27752. #endif
  27753. #if defined(HAVE_DILITHIUM)
  27754. if (dilithiumKey != NULL) {
  27755. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27756. MAX_PUBLIC_KEY_SZ, 0);
  27757. }
  27758. #endif
  27759. #if defined(HAVE_SPHINCS)
  27760. if (sphincsKey != NULL) {
  27761. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27762. MAX_PUBLIC_KEY_SZ, 0);
  27763. }
  27764. #endif
  27765. #endif /* HAVE_PQC */
  27766. if (bufferSz <= 0) {
  27767. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27768. return PUBLIC_KEY_E;
  27769. }
  27770. /* Compute SKID by hashing public key */
  27771. if (kid_type == SKID_TYPE) {
  27772. int hashId = HashIdAlg((word32)cert->sigType);
  27773. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->skid, hashId);
  27774. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27775. cert->skidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  27776. #else
  27777. cert->skidSz = KEYID_SIZE;
  27778. #endif
  27779. }
  27780. else if (kid_type == AKID_TYPE) {
  27781. int hashId = HashIdAlg((word32)cert->sigType);
  27782. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->akid, hashId);
  27783. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27784. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  27785. #else
  27786. cert->akidSz = KEYID_SIZE;
  27787. #endif
  27788. }
  27789. else
  27790. ret = BAD_FUNC_ARG;
  27791. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27792. return ret;
  27793. }
  27794. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27795. {
  27796. RsaKey* rsaKey = NULL;
  27797. ecc_key* eccKey = NULL;
  27798. ed25519_key* ed25519Key = NULL;
  27799. ed448_key* ed448Key = NULL;
  27800. falcon_key* falconKey = NULL;
  27801. dilithium_key* dilithiumKey = NULL;
  27802. sphincs_key* sphincsKey = NULL;
  27803. if (keyType == RSA_TYPE)
  27804. rsaKey = (RsaKey*)key;
  27805. else if (keyType == ECC_TYPE)
  27806. eccKey = (ecc_key*)key;
  27807. else if (keyType == ED25519_TYPE)
  27808. ed25519Key = (ed25519_key*)key;
  27809. else if (keyType == ED448_TYPE)
  27810. ed448Key = (ed448_key*)key;
  27811. else if (keyType == FALCON_LEVEL1_TYPE)
  27812. falconKey = (falcon_key*)key;
  27813. else if (keyType == FALCON_LEVEL5_TYPE)
  27814. falconKey = (falcon_key*)key;
  27815. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27816. dilithiumKey = (dilithium_key*)key;
  27817. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27818. dilithiumKey = (dilithium_key*)key;
  27819. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27820. dilithiumKey = (dilithium_key*)key;
  27821. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27822. sphincsKey = (sphincs_key*)key;
  27823. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27824. sphincsKey = (sphincs_key*)key;
  27825. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27826. sphincsKey = (sphincs_key*)key;
  27827. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27828. sphincsKey = (sphincs_key*)key;
  27829. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27830. sphincsKey = (sphincs_key*)key;
  27831. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27832. sphincsKey = (sphincs_key*)key;
  27833. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27834. falconKey, dilithiumKey, sphincsKey,
  27835. SKID_TYPE);
  27836. }
  27837. /* Set SKID from RSA or ECC public key */
  27838. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27839. {
  27840. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27841. NULL, SKID_TYPE);
  27842. }
  27843. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27844. {
  27845. RsaKey* rsaKey = NULL;
  27846. ecc_key* eccKey = NULL;
  27847. ed25519_key* ed25519Key = NULL;
  27848. ed448_key* ed448Key = NULL;
  27849. falcon_key* falconKey = NULL;
  27850. dilithium_key* dilithiumKey = NULL;
  27851. sphincs_key* sphincsKey = NULL;
  27852. if (keyType == RSA_TYPE)
  27853. rsaKey = (RsaKey*)key;
  27854. else if (keyType == ECC_TYPE)
  27855. eccKey = (ecc_key*)key;
  27856. else if (keyType == ED25519_TYPE)
  27857. ed25519Key = (ed25519_key*)key;
  27858. else if (keyType == ED448_TYPE)
  27859. ed448Key = (ed448_key*)key;
  27860. else if (keyType == FALCON_LEVEL1_TYPE)
  27861. falconKey = (falcon_key*)key;
  27862. else if (keyType == FALCON_LEVEL5_TYPE)
  27863. falconKey = (falcon_key*)key;
  27864. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27865. dilithiumKey = (dilithium_key*)key;
  27866. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27867. dilithiumKey = (dilithium_key*)key;
  27868. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27869. dilithiumKey = (dilithium_key*)key;
  27870. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27871. sphincsKey = (sphincs_key*)key;
  27872. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27873. sphincsKey = (sphincs_key*)key;
  27874. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27875. sphincsKey = (sphincs_key*)key;
  27876. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27877. sphincsKey = (sphincs_key*)key;
  27878. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27879. sphincsKey = (sphincs_key*)key;
  27880. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27881. sphincsKey = (sphincs_key*)key;
  27882. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27883. falconKey, dilithiumKey, sphincsKey,
  27884. AKID_TYPE);
  27885. }
  27886. /* Set SKID from RSA or ECC public key */
  27887. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27888. {
  27889. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27890. NULL, AKID_TYPE);
  27891. }
  27892. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27893. /* Set SKID from public key file in PEM */
  27894. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27895. {
  27896. int ret, derSz;
  27897. byte* der;
  27898. word32 idx;
  27899. RsaKey *rsakey = NULL;
  27900. ecc_key *eckey = NULL;
  27901. if (cert == NULL || file == NULL)
  27902. return BAD_FUNC_ARG;
  27903. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27904. if (der == NULL) {
  27905. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27906. return MEMORY_E;
  27907. }
  27908. derSz = MAX_PUBLIC_KEY_SZ;
  27909. XMEMSET(der, 0, (size_t)derSz);
  27910. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27911. if (derSz <= 0) {
  27912. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27913. return derSz;
  27914. }
  27915. /* Load PubKey in internal structure */
  27916. #ifndef NO_RSA
  27917. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27918. if (rsakey == NULL) {
  27919. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27920. return MEMORY_E;
  27921. }
  27922. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27923. WOLFSSL_MSG("wc_InitRsaKey failure");
  27924. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27925. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27926. return MEMORY_E;
  27927. }
  27928. idx = 0;
  27929. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  27930. if (ret != 0)
  27931. #endif
  27932. {
  27933. #ifndef NO_RSA
  27934. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27935. wc_FreeRsaKey(rsakey);
  27936. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27937. rsakey = NULL;
  27938. #endif
  27939. #ifdef HAVE_ECC
  27940. /* Check to load ecc public key */
  27941. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27942. DYNAMIC_TYPE_ECC);
  27943. if (eckey == NULL) {
  27944. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27945. return MEMORY_E;
  27946. }
  27947. if (wc_ecc_init(eckey) != 0) {
  27948. WOLFSSL_MSG("wc_ecc_init failure");
  27949. wc_ecc_free(eckey);
  27950. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27951. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27952. return MEMORY_E;
  27953. }
  27954. idx = 0;
  27955. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  27956. if (ret != 0) {
  27957. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27958. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27959. wc_ecc_free(eckey);
  27960. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27961. return PUBLIC_KEY_E;
  27962. }
  27963. #else
  27964. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27965. return PUBLIC_KEY_E;
  27966. #endif /* HAVE_ECC */
  27967. }
  27968. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27969. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27970. #ifndef NO_RSA
  27971. wc_FreeRsaKey(rsakey);
  27972. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27973. #endif
  27974. #ifdef HAVE_ECC
  27975. wc_ecc_free(eckey);
  27976. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27977. #endif
  27978. return ret;
  27979. }
  27980. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27981. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27982. {
  27983. int ret = 0;
  27984. /* Subject Key Id not found !! */
  27985. if (decoded->extSubjKeyIdSet == 0) {
  27986. ret = ASN_NO_SKID;
  27987. }
  27988. /* SKID invalid size */
  27989. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27990. ret = MEMORY_E;
  27991. }
  27992. else {
  27993. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27994. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(HashIdAlg(
  27995. cert->sigType)));
  27996. #else
  27997. cert->akidSz = KEYID_SIZE;
  27998. #endif
  27999. /* Put the SKID of CA to AKID of certificate */
  28000. XMEMCPY(cert->akid, decoded->extSubjKeyId, (size_t)cert->akidSz);
  28001. }
  28002. return ret;
  28003. }
  28004. /* Set AKID from certificate contains in buffer (DER encoded) */
  28005. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  28006. {
  28007. int ret = 0;
  28008. if (cert == NULL) {
  28009. ret = BAD_FUNC_ARG;
  28010. }
  28011. else {
  28012. /* Check if decodedCert is cached */
  28013. if (cert->der != der) {
  28014. /* Allocate cache for the decoded cert */
  28015. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28016. }
  28017. if (ret >= 0) {
  28018. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28019. #ifndef WOLFSSL_CERT_GEN_CACHE
  28020. wc_SetCert_Free(cert);
  28021. #endif
  28022. }
  28023. }
  28024. return ret;
  28025. }
  28026. #ifndef NO_FILESYSTEM
  28027. /* Set AKID from certificate file in PEM */
  28028. int wc_SetAuthKeyId(Cert *cert, const char* file)
  28029. {
  28030. int ret;
  28031. DerBuffer* der = NULL;
  28032. if (cert == NULL || file == NULL)
  28033. return BAD_FUNC_ARG;
  28034. ret = wc_PemCertToDer_ex(file, &der);
  28035. if (ret == 0)
  28036. {
  28037. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  28038. FreeDer(&der);
  28039. }
  28040. return ret;
  28041. }
  28042. #endif /* !NO_FILESYSTEM */
  28043. /* Set KeyUsage from human readable string */
  28044. int wc_SetKeyUsage(Cert *cert, const char *value)
  28045. {
  28046. int ret = 0;
  28047. if (cert == NULL || value == NULL)
  28048. return BAD_FUNC_ARG;
  28049. cert->keyUsage = 0;
  28050. ret = ParseKeyUsageStr(value, &cert->keyUsage, cert->heap);
  28051. return ret;
  28052. }
  28053. /* Set ExtendedKeyUsage from human readable string */
  28054. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  28055. {
  28056. int ret = 0;
  28057. if (cert == NULL || value == NULL)
  28058. return BAD_FUNC_ARG;
  28059. cert->extKeyUsage = 0;
  28060. ret = ParseExtKeyUsageStr(value, &cert->extKeyUsage, cert->heap);
  28061. return ret;
  28062. }
  28063. #ifdef WOLFSSL_EKU_OID
  28064. /*
  28065. * cert structure to set EKU oid in
  28066. * oid the oid in byte representation
  28067. * sz size of oid buffer
  28068. * idx index of array to place oid
  28069. *
  28070. * returns 0 on success
  28071. */
  28072. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  28073. void* heap)
  28074. {
  28075. byte oid[MAX_OID_SZ];
  28076. word32 oidSz = MAX_OID_SZ;
  28077. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  28078. WOLFSSL_MSG("Either idx or sz was too large");
  28079. return BAD_FUNC_ARG;
  28080. }
  28081. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  28082. return BUFFER_E;
  28083. }
  28084. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  28085. cert->extKeyUsageOIDSz[idx] = oidSz;
  28086. cert->extKeyUsage |= EXTKEYUSE_USER;
  28087. return 0;
  28088. }
  28089. #endif /* WOLFSSL_EKU_OID */
  28090. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  28091. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  28092. defined(WOLFSSL_CERT_EXT)
  28093. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  28094. const byte *der, word32 derSz) {
  28095. CertExtension *ext;
  28096. byte encodedOid[MAX_OID_SZ];
  28097. word32 encodedOidSz = MAX_OID_SZ;
  28098. int ret;
  28099. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  28100. return BAD_FUNC_ARG;
  28101. }
  28102. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  28103. return MEMORY_E;
  28104. }
  28105. /* Make sure we can properly parse the OID. */
  28106. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  28107. if (ret != 0) {
  28108. return ret;
  28109. }
  28110. ext = &cert->customCertExt[cert->customCertExtCount];
  28111. ext->oid = (char*)oid;
  28112. ext->crit = (critical == 0) ? 0 : 1;
  28113. ext->val = (byte*)der;
  28114. ext->valSz = derSz;
  28115. cert->customCertExtCount++;
  28116. return 0;
  28117. }
  28118. #endif
  28119. #endif /* WOLFSSL_CERT_EXT */
  28120. #ifdef WOLFSSL_ALT_NAMES
  28121. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  28122. {
  28123. int ret = 0;
  28124. cert->altNamesSz = 0;
  28125. if (decoded->altNames) {
  28126. ret = FlattenAltNames(cert->altNames,
  28127. sizeof(cert->altNames), decoded->altNames);
  28128. if (ret >= 0) {
  28129. cert->altNamesSz = ret;
  28130. ret = 0;
  28131. }
  28132. }
  28133. return ret;
  28134. }
  28135. #ifndef NO_FILESYSTEM
  28136. /* Set Alt Names from der cert, return 0 on success */
  28137. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  28138. int devId)
  28139. {
  28140. int ret;
  28141. #ifdef WOLFSSL_SMALL_STACK
  28142. DecodedCert* decoded;
  28143. #else
  28144. DecodedCert decoded[1];
  28145. #endif
  28146. if (derSz < 0)
  28147. return derSz;
  28148. #ifdef WOLFSSL_SMALL_STACK
  28149. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  28150. DYNAMIC_TYPE_TMP_BUFFER);
  28151. if (decoded == NULL)
  28152. return MEMORY_E;
  28153. #endif
  28154. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  28155. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  28156. if (ret < 0) {
  28157. WOLFSSL_MSG("ParseCertRelative error");
  28158. }
  28159. else {
  28160. ret = SetAltNamesFromDcert(cert, decoded);
  28161. }
  28162. FreeDecodedCert(decoded);
  28163. #ifdef WOLFSSL_SMALL_STACK
  28164. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28165. #endif
  28166. return ret < 0 ? ret : 0;
  28167. }
  28168. #endif
  28169. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  28170. {
  28171. int ret = 0;
  28172. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  28173. WOLFSSL_MSG("Couldn't extract dates");
  28174. ret = -1;
  28175. }
  28176. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  28177. decoded->afterDateLen > MAX_DATE_SIZE) {
  28178. WOLFSSL_MSG("Bad date size");
  28179. ret = -1;
  28180. }
  28181. else {
  28182. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  28183. (size_t)decoded->beforeDateLen);
  28184. XMEMCPY(cert->afterDate, decoded->afterDate,
  28185. (size_t)decoded->afterDateLen);
  28186. cert->beforeDateSz = decoded->beforeDateLen;
  28187. cert->afterDateSz = decoded->afterDateLen;
  28188. }
  28189. return ret;
  28190. }
  28191. #endif /* WOLFSSL_ALT_NAMES */
  28192. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  28193. {
  28194. int sz;
  28195. if (decoded->subjectCN) {
  28196. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  28197. : CTC_NAME_SIZE - 1;
  28198. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  28199. cn->commonName[sz] = '\0';
  28200. cn->commonNameEnc = decoded->subjectCNEnc;
  28201. }
  28202. if (decoded->subjectC) {
  28203. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  28204. : CTC_NAME_SIZE - 1;
  28205. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  28206. cn->country[sz] = '\0';
  28207. cn->countryEnc = decoded->subjectCEnc;
  28208. }
  28209. if (decoded->subjectST) {
  28210. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  28211. : CTC_NAME_SIZE - 1;
  28212. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  28213. cn->state[sz] = '\0';
  28214. cn->stateEnc = decoded->subjectSTEnc;
  28215. }
  28216. if (decoded->subjectL) {
  28217. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  28218. : CTC_NAME_SIZE - 1;
  28219. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  28220. cn->locality[sz] = '\0';
  28221. cn->localityEnc = decoded->subjectLEnc;
  28222. }
  28223. if (decoded->subjectO) {
  28224. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  28225. : CTC_NAME_SIZE - 1;
  28226. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  28227. cn->org[sz] = '\0';
  28228. cn->orgEnc = decoded->subjectOEnc;
  28229. }
  28230. if (decoded->subjectOU) {
  28231. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  28232. : CTC_NAME_SIZE - 1;
  28233. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  28234. cn->unit[sz] = '\0';
  28235. cn->unitEnc = decoded->subjectOUEnc;
  28236. }
  28237. if (decoded->subjectSN) {
  28238. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  28239. : CTC_NAME_SIZE - 1;
  28240. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  28241. cn->sur[sz] = '\0';
  28242. cn->surEnc = decoded->subjectSNEnc;
  28243. }
  28244. if (decoded->subjectSND) {
  28245. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  28246. : CTC_NAME_SIZE - 1;
  28247. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  28248. cn->serialDev[sz] = '\0';
  28249. cn->serialDevEnc = decoded->subjectSNDEnc;
  28250. }
  28251. if (decoded->subjectUID) {
  28252. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  28253. : CTC_NAME_SIZE - 1;
  28254. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  28255. cn->userId[sz] = '\0';
  28256. cn->userIdEnc = decoded->subjectUIDEnc;
  28257. }
  28258. #ifdef WOLFSSL_CERT_EXT
  28259. if (decoded->subjectBC) {
  28260. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  28261. : CTC_NAME_SIZE - 1;
  28262. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  28263. cn->busCat[sz] = '\0';
  28264. cn->busCatEnc = decoded->subjectBCEnc;
  28265. }
  28266. if (decoded->subjectJC) {
  28267. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  28268. : CTC_NAME_SIZE - 1;
  28269. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  28270. cn->joiC[sz] = '\0';
  28271. cn->joiCEnc = decoded->subjectJCEnc;
  28272. }
  28273. if (decoded->subjectJS) {
  28274. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  28275. : CTC_NAME_SIZE - 1;
  28276. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  28277. cn->joiSt[sz] = '\0';
  28278. cn->joiStEnc = decoded->subjectJSEnc;
  28279. }
  28280. #endif
  28281. if (decoded->subjectEmail) {
  28282. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  28283. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  28284. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  28285. cn->email[sz] = '\0';
  28286. }
  28287. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  28288. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  28289. if (decoded->subjectN) {
  28290. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  28291. : CTC_NAME_SIZE - 1;
  28292. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  28293. cn->dnName[sz] = '\0';
  28294. cn->dnNameEnc = decoded->subjectNEnc;
  28295. }
  28296. if (decoded->subjectI) {
  28297. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  28298. : CTC_NAME_SIZE - 1;
  28299. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  28300. cn->initials[sz] = '\0';
  28301. cn->initialsEnc = decoded->subjectIEnc;
  28302. }
  28303. if (decoded->subjectGN) {
  28304. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  28305. : CTC_NAME_SIZE - 1;
  28306. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  28307. cn->givenName[sz] = '\0';
  28308. cn->givenNameEnc = decoded->subjectGNEnc;
  28309. }
  28310. if (decoded->subjectDNQ) {
  28311. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  28312. : CTC_NAME_SIZE - 1;
  28313. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  28314. cn->dnQualifier[sz] = '\0';
  28315. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  28316. }
  28317. #endif /* WOLFSSL_CERT_NAME_ALL */
  28318. }
  28319. #ifndef NO_FILESYSTEM
  28320. /* Set cn name from der buffer, return 0 on success */
  28321. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  28322. {
  28323. int ret;
  28324. #ifdef WOLFSSL_SMALL_STACK
  28325. DecodedCert* decoded;
  28326. #else
  28327. DecodedCert decoded[1];
  28328. #endif
  28329. if (derSz < 0)
  28330. return derSz;
  28331. #ifdef WOLFSSL_SMALL_STACK
  28332. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  28333. DYNAMIC_TYPE_TMP_BUFFER);
  28334. if (decoded == NULL)
  28335. return MEMORY_E;
  28336. #endif
  28337. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  28338. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  28339. if (ret < 0) {
  28340. WOLFSSL_MSG("ParseCertRelative error");
  28341. }
  28342. else {
  28343. SetNameFromDcert(cn, decoded);
  28344. }
  28345. FreeDecodedCert(decoded);
  28346. #ifdef WOLFSSL_SMALL_STACK
  28347. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  28348. #endif
  28349. return ret < 0 ? ret : 0;
  28350. }
  28351. /* Set cert issuer from issuerFile in PEM */
  28352. WOLFSSL_ABI
  28353. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  28354. {
  28355. int ret;
  28356. DerBuffer* der = NULL;
  28357. if (cert == NULL || issuerFile == NULL)
  28358. return BAD_FUNC_ARG;
  28359. ret = wc_PemCertToDer_ex(issuerFile, &der);
  28360. if (ret == 0) {
  28361. cert->selfSigned = 0;
  28362. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  28363. INVALID_DEVID);
  28364. FreeDer(&der);
  28365. }
  28366. return ret;
  28367. }
  28368. /* Set cert subject from subjectFile in PEM */
  28369. WOLFSSL_ABI
  28370. int wc_SetSubject(Cert* cert, const char* subjectFile)
  28371. {
  28372. int ret;
  28373. DerBuffer* der = NULL;
  28374. if (cert == NULL || subjectFile == NULL)
  28375. return BAD_FUNC_ARG;
  28376. ret = wc_PemCertToDer_ex(subjectFile, &der);
  28377. if (ret == 0) {
  28378. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  28379. INVALID_DEVID);
  28380. FreeDer(&der);
  28381. }
  28382. return ret;
  28383. }
  28384. #ifdef WOLFSSL_ALT_NAMES
  28385. /* Set alt names from file in PEM */
  28386. WOLFSSL_ABI
  28387. int wc_SetAltNames(Cert* cert, const char* file)
  28388. {
  28389. int ret;
  28390. DerBuffer* der = NULL;
  28391. if (cert == NULL) {
  28392. return BAD_FUNC_ARG;
  28393. }
  28394. ret = wc_PemCertToDer_ex(file, &der);
  28395. if (ret == 0) {
  28396. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  28397. INVALID_DEVID);
  28398. FreeDer(&der);
  28399. }
  28400. return ret;
  28401. }
  28402. #endif /* WOLFSSL_ALT_NAMES */
  28403. #endif /* !NO_FILESYSTEM */
  28404. /* Set cert issuer from DER buffer */
  28405. WOLFSSL_ABI
  28406. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  28407. {
  28408. int ret = 0;
  28409. if (cert == NULL) {
  28410. ret = BAD_FUNC_ARG;
  28411. }
  28412. else {
  28413. cert->selfSigned = 0;
  28414. /* Check if decodedCert is cached */
  28415. if (cert->der != der) {
  28416. /* Allocate cache for the decoded cert */
  28417. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28418. }
  28419. if (ret >= 0) {
  28420. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  28421. #ifndef WOLFSSL_CERT_GEN_CACHE
  28422. wc_SetCert_Free(cert);
  28423. #endif
  28424. }
  28425. }
  28426. return ret;
  28427. }
  28428. /* Set cert subject from DER buffer */
  28429. WOLFSSL_ABI
  28430. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  28431. {
  28432. int ret = 0;
  28433. if (cert == NULL) {
  28434. ret = BAD_FUNC_ARG;
  28435. }
  28436. else {
  28437. /* Check if decodedCert is cached */
  28438. if (cert->der != der) {
  28439. /* Allocate cache for the decoded cert */
  28440. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28441. }
  28442. if (ret >= 0) {
  28443. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  28444. #ifndef WOLFSSL_CERT_GEN_CACHE
  28445. wc_SetCert_Free(cert);
  28446. #endif
  28447. }
  28448. }
  28449. return ret;
  28450. }
  28451. #ifdef WOLFSSL_CERT_EXT
  28452. /* Set cert raw subject from DER buffer */
  28453. WOLFSSL_ABI
  28454. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  28455. {
  28456. int ret = 0;
  28457. if (cert == NULL) {
  28458. ret = BAD_FUNC_ARG;
  28459. }
  28460. else {
  28461. /* Check if decodedCert is cached */
  28462. if (cert->der != der) {
  28463. /* Allocate cache for the decoded cert */
  28464. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28465. }
  28466. if (ret >= 0) {
  28467. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  28468. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  28469. (int)sizeof(CertName))) {
  28470. XMEMCPY(cert->sbjRaw,
  28471. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  28472. (size_t)((DecodedCert*)cert->decodedCert)->
  28473. subjectRawLen);
  28474. }
  28475. #ifndef WOLFSSL_CERT_GEN_CACHE
  28476. wc_SetCert_Free(cert);
  28477. #endif
  28478. }
  28479. }
  28480. return ret;
  28481. }
  28482. /* Set cert raw issuer from DER buffer */
  28483. WOLFSSL_ABI
  28484. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  28485. {
  28486. int ret = 0;
  28487. if (cert == NULL) {
  28488. ret = BAD_FUNC_ARG;
  28489. }
  28490. else {
  28491. /* Check if decodedCert is cached */
  28492. if (cert->der != der) {
  28493. /* Allocate cache for the decoded cert */
  28494. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28495. }
  28496. if (ret >= 0) {
  28497. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  28498. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  28499. (int)sizeof(CertName))) {
  28500. /* Copy the subject to the issuer field */
  28501. XMEMCPY(cert->issRaw,
  28502. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  28503. (size_t)((DecodedCert*)cert->decodedCert)->
  28504. subjectRawLen);
  28505. }
  28506. #ifndef WOLFSSL_CERT_GEN_CACHE
  28507. wc_SetCert_Free(cert);
  28508. #endif
  28509. }
  28510. }
  28511. return ret;
  28512. }
  28513. #endif
  28514. #ifdef WOLFSSL_ALT_NAMES
  28515. /* Set cert alt names from DER buffer */
  28516. WOLFSSL_ABI
  28517. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  28518. {
  28519. int ret = 0;
  28520. if (cert == NULL) {
  28521. ret = BAD_FUNC_ARG;
  28522. }
  28523. else {
  28524. /* Check if decodedCert is cached */
  28525. if (cert->der != der) {
  28526. /* Allocate cache for the decoded cert */
  28527. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28528. }
  28529. if (ret >= 0) {
  28530. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28531. #ifndef WOLFSSL_CERT_GEN_CACHE
  28532. wc_SetCert_Free(cert);
  28533. #endif
  28534. }
  28535. }
  28536. return(ret);
  28537. }
  28538. /* Set cert dates from DER buffer */
  28539. WOLFSSL_ABI
  28540. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  28541. {
  28542. int ret = 0;
  28543. if (cert == NULL) {
  28544. ret = BAD_FUNC_ARG;
  28545. }
  28546. else {
  28547. /* Check if decodedCert is cached */
  28548. if (cert->der != der) {
  28549. /* Allocate cache for the decoded cert */
  28550. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28551. }
  28552. if (ret >= 0) {
  28553. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28554. #ifndef WOLFSSL_CERT_GEN_CACHE
  28555. wc_SetCert_Free(cert);
  28556. #endif
  28557. }
  28558. }
  28559. return(ret);
  28560. }
  28561. #endif /* WOLFSSL_ALT_NAMES */
  28562. #endif /* WOLFSSL_CERT_GEN */
  28563. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  28564. || defined(OPENSSL_EXTRA)
  28565. /* Encode OID string representation to ITU-T X.690 format */
  28566. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  28567. {
  28568. word32 idx = 0, nb_val;
  28569. char *token, *str, *ptr;
  28570. word32 len;
  28571. (void)heap;
  28572. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  28573. return BAD_FUNC_ARG;
  28574. /* duplicate string (including terminator) */
  28575. len = (word32)XSTRLEN(in);
  28576. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28577. if (str == NULL)
  28578. return MEMORY_E;
  28579. XMEMCPY(str, in, len+1);
  28580. nb_val = 0;
  28581. /* parse value, and set corresponding Policy OID value */
  28582. token = XSTRTOK(str, ".", &ptr);
  28583. while (token != NULL)
  28584. {
  28585. word32 val = (word32)XATOI(token);
  28586. if (nb_val == 0) {
  28587. if (val > 2) {
  28588. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28589. return ASN_OBJECT_ID_E;
  28590. }
  28591. out[idx] = (byte)(40 * val);
  28592. }
  28593. else if (nb_val == 1) {
  28594. if (val > 127) {
  28595. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28596. return ASN_OBJECT_ID_E;
  28597. }
  28598. if (idx > *outSz) {
  28599. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28600. return BUFFER_E;
  28601. }
  28602. out[idx++] += (byte)val;
  28603. }
  28604. else {
  28605. word32 tb = 0;
  28606. int i = 0;
  28607. byte oid[MAX_OID_SZ];
  28608. while (val >= 128) {
  28609. word32 x = val % 128;
  28610. val /= 128;
  28611. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  28612. }
  28613. if ((idx+(word32)i) >= *outSz) {
  28614. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28615. return BUFFER_E;
  28616. }
  28617. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  28618. /* push value in the right order */
  28619. while (i >= 0)
  28620. out[idx++] = oid[i--];
  28621. }
  28622. token = XSTRTOK(NULL, ".", &ptr);
  28623. nb_val++;
  28624. }
  28625. *outSz = idx;
  28626. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28627. return 0;
  28628. }
  28629. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  28630. #endif /* !NO_CERTS */
  28631. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  28632. /* Helper function for wolfSSL_i2d_DHparams */
  28633. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  28634. {
  28635. #ifndef WOLFSSL_ASN_TEMPLATE
  28636. word32 idx = 0;
  28637. word32 total;
  28638. WOLFSSL_ENTER("StoreDHparams");
  28639. if (out == NULL) {
  28640. WOLFSSL_MSG("Null buffer error");
  28641. return BUFFER_E;
  28642. }
  28643. /* determine size */
  28644. /* integer - g */
  28645. idx = SetASNIntMP(g, -1, NULL);
  28646. /* integer - p */
  28647. idx += SetASNIntMP(p, -1, NULL);
  28648. total = idx;
  28649. /* sequence */
  28650. idx += SetSequence(idx, NULL);
  28651. /* make sure output fits in buffer */
  28652. if (idx > *outLen) {
  28653. return BUFFER_E;
  28654. }
  28655. /* write DH parameters */
  28656. /* sequence - for P and G only */
  28657. idx = SetSequence(total, out);
  28658. /* integer - p */
  28659. idx += SetASNIntMP(p, -1, out + idx);
  28660. /* integer - g */
  28661. idx += SetASNIntMP(g, -1, out + idx);
  28662. *outLen = idx;
  28663. return 0;
  28664. #else
  28665. ASNSetData dataASN[dhParamASN_Length];
  28666. int ret = 0;
  28667. int sz = 0;
  28668. WOLFSSL_ENTER("StoreDHparams");
  28669. if (out == NULL) {
  28670. ret = BUFFER_E;
  28671. }
  28672. if (ret == 0) {
  28673. XMEMSET(dataASN, 0, sizeof(dataASN));
  28674. /* Set mp_int containing p and g. */
  28675. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28676. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28677. /* privateValueLength not encoded. */
  28678. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28679. /* Calculate the size of the DH parameters. */
  28680. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28681. }
  28682. /* Check buffer is big enough for encoding. */
  28683. if ((ret == 0) && ((int)*outLen < sz)) {
  28684. ret = BUFFER_E;
  28685. }
  28686. if (ret == 0) {
  28687. /* Encode the DH parameters into buffer. */
  28688. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28689. /* Set the actual encoding size. */
  28690. *outLen = (word32)sz;
  28691. }
  28692. return ret;
  28693. #endif /* WOLFSSL_ASN_TEMPLATE */
  28694. }
  28695. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28696. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28697. #ifdef WOLFSSL_ASN_TEMPLATE
  28698. /* ASN.1 template for DSA signature.
  28699. * RFC 5912, 6 - DSA-Sig-Value
  28700. */
  28701. static const ASNItem dsaSigASN[] = {
  28702. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28703. /* r */
  28704. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28705. /* s */
  28706. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28707. };
  28708. enum {
  28709. DSASIGASN_IDX_SEQ = 0,
  28710. DSASIGASN_IDX_R,
  28711. DSASIGASN_IDX_S
  28712. };
  28713. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28714. #endif
  28715. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28716. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28717. {
  28718. #ifndef WOLFSSL_ASN_TEMPLATE
  28719. word32 idx = 0;
  28720. int rSz; /* encoding size */
  28721. int sSz;
  28722. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28723. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28724. int rLeadingZero = mp_leading_bit(r);
  28725. int sLeadingZero = mp_leading_bit(s);
  28726. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28727. int sLen = mp_unsigned_bin_size(s);
  28728. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  28729. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  28730. return BUFFER_E;
  28731. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  28732. headerSz), out);
  28733. /* store r */
  28734. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  28735. if (rSz < 0)
  28736. return rSz;
  28737. idx += (word32)rSz;
  28738. /* store s */
  28739. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  28740. if (sSz < 0)
  28741. return sSz;
  28742. idx += (word32)sSz;
  28743. *outLen = idx;
  28744. return 0;
  28745. #else
  28746. ASNSetData dataASN[dsaSigASN_Length];
  28747. int ret;
  28748. int sz;
  28749. /* Clear dynamic data and set mp_ints r and s */
  28750. XMEMSET(dataASN, 0, sizeof(dataASN));
  28751. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28752. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28753. /* Calculate size of encoding. */
  28754. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28755. /* Check buffer is big enough for encoding. */
  28756. if ((ret == 0) && ((int)*outLen < sz)) {
  28757. ret = BUFFER_E;
  28758. }
  28759. if (ret == 0) {
  28760. /* Encode DSA signature into buffer. */
  28761. ret = SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28762. if (ret >= 0) {
  28763. if (ret == sz) {
  28764. /* Set the actual encoding size. */
  28765. *outLen = (word32)sz;
  28766. ret = 0;
  28767. } else {
  28768. ret = BAD_STATE_E;
  28769. }
  28770. }
  28771. }
  28772. return ret;
  28773. #endif /* WOLFSSL_ASN_TEMPLATE */
  28774. }
  28775. #ifndef WOLFSSL_ASN_TEMPLATE
  28776. /* determine if leading bit is set */
  28777. static word32 is_leading_bit_set(const byte* input, word32 sz)
  28778. {
  28779. byte c = 0;
  28780. if (sz > 0)
  28781. c = input[0];
  28782. return (c & 0x80) != 0;
  28783. }
  28784. static word32 trim_leading_zeros(const byte** input, word32 sz)
  28785. {
  28786. int i;
  28787. word32 leadingZeroCount = 0;
  28788. const byte* tmp = *input;
  28789. for (i=0; i<(int)sz; i++) {
  28790. if (tmp[i] != 0)
  28791. break;
  28792. leadingZeroCount++;
  28793. }
  28794. /* catch all zero case */
  28795. if (sz > 0 && leadingZeroCount == sz) {
  28796. leadingZeroCount--;
  28797. }
  28798. *input += leadingZeroCount;
  28799. sz -= leadingZeroCount;
  28800. return sz;
  28801. }
  28802. #endif
  28803. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28804. /* All input/outputs are assumed to be big-endian */
  28805. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28806. const byte* s, word32 sLen)
  28807. {
  28808. #ifndef WOLFSSL_ASN_TEMPLATE
  28809. int ret;
  28810. word32 idx;
  28811. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28812. word32 rAddLeadZero, sAddLeadZero;
  28813. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28814. return BAD_FUNC_ARG;
  28815. /* Trim leading zeros */
  28816. rLen = trim_leading_zeros(&r, rLen);
  28817. sLen = trim_leading_zeros(&s, sLen);
  28818. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28819. /* Add leading zero if MSB is set */
  28820. rAddLeadZero = is_leading_bit_set(r, rLen);
  28821. sAddLeadZero = is_leading_bit_set(s, sLen);
  28822. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28823. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28824. return BUFFER_E;
  28825. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28826. /* store r */
  28827. ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28828. if (ret < 0)
  28829. return ret;
  28830. idx += (word32)ret;
  28831. XMEMCPY(&out[idx], r, rLen);
  28832. idx += rLen;
  28833. /* store s */
  28834. ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28835. if (ret < 0)
  28836. return ret;
  28837. idx += (word32)ret;
  28838. XMEMCPY(&out[idx], s, sLen);
  28839. idx += sLen;
  28840. *outLen = idx;
  28841. return 0;
  28842. #else
  28843. ASNSetData dataASN[dsaSigASN_Length];
  28844. int ret;
  28845. int sz;
  28846. /* Clear dynamic data and set buffers for r and s */
  28847. XMEMSET(dataASN, 0, sizeof(dataASN));
  28848. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28849. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28850. /* Calculate size of encoding. */
  28851. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28852. /* Check buffer is big enough for encoding. */
  28853. if ((ret == 0) && ((int)*outLen < sz)) {
  28854. ret = BUFFER_E;
  28855. }
  28856. if (ret == 0) {
  28857. /* Encode DSA signature into buffer. */
  28858. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28859. /* Set the actual encoding size. */
  28860. *outLen = (word32)sz;
  28861. }
  28862. return ret;
  28863. #endif /* WOLFSSL_ASN_TEMPLATE */
  28864. }
  28865. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28866. /* All input/outputs are assumed to be big-endian */
  28867. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28868. byte* s, word32* sLen)
  28869. {
  28870. #ifndef WOLFSSL_ASN_TEMPLATE
  28871. int ret;
  28872. word32 idx = 0;
  28873. int len = 0;
  28874. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28875. return ASN_ECC_KEY_E;
  28876. }
  28877. #ifndef NO_STRICT_ECDSA_LEN
  28878. /* enable strict length checking for signature */
  28879. if (sigLen != idx + (word32)len) {
  28880. return ASN_ECC_KEY_E;
  28881. }
  28882. #else
  28883. /* allow extra signature bytes at end */
  28884. if ((word32)len > (sigLen - idx)) {
  28885. return ASN_ECC_KEY_E;
  28886. }
  28887. #endif
  28888. ret = GetASNInt(sig, &idx, &len, sigLen);
  28889. if (ret != 0)
  28890. return ret;
  28891. if (rLen)
  28892. *rLen = (word32)len;
  28893. if (r)
  28894. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  28895. idx += (word32)len;
  28896. ret = GetASNInt(sig, &idx, &len, sigLen);
  28897. if (ret != 0)
  28898. return ret;
  28899. if (sLen)
  28900. *sLen = (word32)len;
  28901. if (s)
  28902. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  28903. #ifndef NO_STRICT_ECDSA_LEN
  28904. /* sanity check that the index has been advanced all the way to the end of
  28905. * the buffer */
  28906. if (idx + (word32)len != sigLen) {
  28907. ret = ASN_ECC_KEY_E;
  28908. }
  28909. #endif
  28910. return ret;
  28911. #else
  28912. ASNGetData dataASN[dsaSigASN_Length];
  28913. word32 idx = 0;
  28914. /* Clear dynamic data and set buffers to put r and s into. */
  28915. XMEMSET(dataASN, 0, sizeof(dataASN));
  28916. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28917. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28918. /* Decode the DSA signature. */
  28919. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28920. sigLen);
  28921. #endif /* WOLFSSL_ASN_TEMPLATE */
  28922. }
  28923. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28924. {
  28925. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  28926. }
  28927. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  28928. int init)
  28929. {
  28930. #ifndef WOLFSSL_ASN_TEMPLATE
  28931. word32 idx = 0;
  28932. int len = 0;
  28933. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28934. return ASN_ECC_KEY_E;
  28935. }
  28936. #ifndef NO_STRICT_ECDSA_LEN
  28937. /* enable strict length checking for signature */
  28938. if (sigLen != idx + (word32)len) {
  28939. return ASN_ECC_KEY_E;
  28940. }
  28941. #else
  28942. /* allow extra signature bytes at end */
  28943. if ((word32)len > (sigLen - idx)) {
  28944. return ASN_ECC_KEY_E;
  28945. }
  28946. #endif
  28947. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  28948. return ASN_ECC_KEY_E;
  28949. }
  28950. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  28951. mp_clear(r);
  28952. return ASN_ECC_KEY_E;
  28953. }
  28954. #ifndef NO_STRICT_ECDSA_LEN
  28955. /* sanity check that the index has been advanced all the way to the end of
  28956. * the buffer */
  28957. if (idx != sigLen) {
  28958. mp_clear(r);
  28959. mp_clear(s);
  28960. return ASN_ECC_KEY_E;
  28961. }
  28962. #endif
  28963. return 0;
  28964. #else
  28965. ASNGetData dataASN[dsaSigASN_Length];
  28966. word32 idx = 0;
  28967. int ret;
  28968. /* Clear dynamic data and set mp_ints to put r and s into. */
  28969. XMEMSET(dataASN, 0, sizeof(dataASN));
  28970. if (init) {
  28971. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28972. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28973. }
  28974. else {
  28975. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  28976. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  28977. }
  28978. /* Decode the DSA signature. */
  28979. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  28980. sigLen);
  28981. #ifndef NO_STRICT_ECDSA_LEN
  28982. /* sanity check that the index has been advanced all the way to the end of
  28983. * the buffer */
  28984. if ((ret == 0) && (idx != sigLen)) {
  28985. ret = ASN_ECC_KEY_E;
  28986. }
  28987. #endif
  28988. if (ret != 0) {
  28989. mp_clear(r);
  28990. mp_clear(s);
  28991. }
  28992. return ret;
  28993. #endif /* WOLFSSL_ASN_TEMPLATE */
  28994. }
  28995. #endif
  28996. #ifdef WOLFSSL_ASN_TEMPLATE
  28997. #ifdef WOLFSSL_CUSTOM_CURVES
  28998. /* Convert data to hex string.
  28999. *
  29000. * Big-endian byte array is converted to big-endian hexadecimal string.
  29001. *
  29002. * @param [in] input Buffer containing data.
  29003. * @param [in] inSz Size of data in buffer.
  29004. * @param [out] out Buffer to hold hex string.
  29005. */
  29006. static void DataToHexString(const byte* input, word32 inSz, char* out)
  29007. {
  29008. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  29009. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  29010. word32 i;
  29011. /* Converting a byte of data at a time to two hex characters. */
  29012. for (i = 0; i < inSz; i++) {
  29013. out[i*2 + 0] = hexChar[input[i] >> 4];
  29014. out[i*2 + 1] = hexChar[input[i] & 0xf];
  29015. }
  29016. /* NUL terminate string. */
  29017. out[i * 2] = '\0';
  29018. }
  29019. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29020. /* Convert data to hex string and place in allocated buffer.
  29021. *
  29022. * Big-endian byte array is converted to big-endian hexadecimal string.
  29023. *
  29024. * @param [in] input Buffer containing data.
  29025. * @param [in] inSz Size of data in buffer.
  29026. * @param [out] out Allocated buffer holding hex string.
  29027. * @param [in] heap Dynamic memory allocation hint.
  29028. * @param [in] heapType Type of heap to use.
  29029. * @return 0 on success.
  29030. * @return MEMORY_E when dynamic memory allocation fails.
  29031. */
  29032. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  29033. void* heap, int heapType)
  29034. {
  29035. int ret = 0;
  29036. char* str;
  29037. /* Allocate for 2 string characters ber byte plus NUL. */
  29038. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  29039. if (str == NULL) {
  29040. ret = MEMORY_E;
  29041. }
  29042. else {
  29043. /* Convert to hex string. */
  29044. DataToHexString(input, inSz, str);
  29045. *out = str;
  29046. }
  29047. (void)heap;
  29048. (void)heapType;
  29049. return ret;
  29050. }
  29051. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  29052. /* ASN.1 template for SpecifiedECDomain.
  29053. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  29054. * NOTE: characteristic-two-field not supported. */
  29055. static const ASNItem eccSpecifiedASN[] = {
  29056. /* version */
  29057. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  29058. /* fieldID */
  29059. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29060. /* prime-field or characteristic-two-field */
  29061. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  29062. /* Prime-p */
  29063. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  29064. /* fieldID */
  29065. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29066. /* a */
  29067. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  29068. /* b */
  29069. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  29070. /* seed */
  29071. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  29072. /* base */
  29073. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  29074. /* order */
  29075. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  29076. /* cofactor */
  29077. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  29078. /* hash */
  29079. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  29080. };
  29081. enum {
  29082. ECCSPECIFIEDASN_IDX_VER = 0,
  29083. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  29084. ECCSPECIFIEDASN_IDX_PRIME_OID,
  29085. ECCSPECIFIEDASN_IDX_PRIME_P,
  29086. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  29087. ECCSPECIFIEDASN_IDX_PARAM_A,
  29088. ECCSPECIFIEDASN_IDX_PARAM_B,
  29089. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  29090. ECCSPECIFIEDASN_IDX_BASE,
  29091. ECCSPECIFIEDASN_IDX_ORDER,
  29092. ECCSPECIFIEDASN_IDX_COFACTOR,
  29093. ECCSPECIFIEDASN_IDX_HASH_SEQ
  29094. };
  29095. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  29096. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  29097. /* OID indicating the prime field is explicitly defined. */
  29098. static const byte primeFieldOID[] = {
  29099. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  29100. };
  29101. static const char ecSetCustomName[] = "Custom";
  29102. /* Explicit EC parameter values. */
  29103. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  29104. ecc_key* key)
  29105. {
  29106. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  29107. int ret = 0;
  29108. ecc_set_type* curve;
  29109. word32 idx = 0;
  29110. byte version;
  29111. byte cofactor;
  29112. const byte *base;
  29113. word32 baseLen;
  29114. /* Allocate a new parameter set. */
  29115. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  29116. DYNAMIC_TYPE_ECC_BUFFER);
  29117. if (curve == NULL) {
  29118. ret = MEMORY_E;
  29119. }
  29120. else {
  29121. /* Clear out parameters and set fields to indicate it is custom. */
  29122. XMEMSET(curve, 0, sizeof(*curve));
  29123. }
  29124. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  29125. if (ret == 0) {
  29126. /* Set name to be: "Custom" */
  29127. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29128. curve->name = ecSetCustomName;
  29129. #else
  29130. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  29131. #endif
  29132. curve->id = ECC_CURVE_CUSTOM;
  29133. /* Get version, must have prime field OID and get co-factor. */
  29134. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  29135. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  29136. primeFieldOID, sizeof(primeFieldOID));
  29137. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  29138. /* Decode the explicit parameters. */
  29139. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  29140. input, &idx, inSz);
  29141. }
  29142. /* Version must be 1 or 2 for supporting explicit parameters. */
  29143. if ((ret == 0) && (version < 1 || version > 3)) {
  29144. ret = ASN_PARSE_E;
  29145. }
  29146. #ifndef WOLFSSL_NO_ASN_STRICT
  29147. /* Only version 2 and above can have a seed. */
  29148. if (ret == 0) {
  29149. if ((dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  29150. (version < 2)) {
  29151. ret = ASN_PARSE_E;
  29152. }
  29153. }
  29154. #endif
  29155. /* Only version 2 and above can have a hash algorithm. */
  29156. if (ret == 0) {
  29157. if ((dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  29158. (version < 2)) {
  29159. ret = ASN_PARSE_E;
  29160. }
  29161. }
  29162. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  29163. /* Store optional co-factor. */
  29164. curve->cofactor = cofactor;
  29165. }
  29166. if (ret == 0) {
  29167. /* Length of the prime in bytes is the curve size. */
  29168. curve->size =
  29169. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  29170. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  29171. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  29172. &baseLen);
  29173. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  29174. ret = ASN_PARSE_E;
  29175. }
  29176. }
  29177. /* Put the curve parameters into the set.
  29178. * Convert the big-endian number byte array to a big-endian string.
  29179. */
  29180. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29181. /* Allocate buffer to put hex strings into. */
  29182. if (ret == 0) {
  29183. /* Base X-ordinate */
  29184. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  29185. (char**)&curve->Gx, key->heap,
  29186. DYNAMIC_TYPE_ECC_BUFFER);
  29187. }
  29188. if (ret == 0) {
  29189. /* Base Y-ordinate */
  29190. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  29191. (char**)&curve->Gy, key->heap,
  29192. DYNAMIC_TYPE_ECC_BUFFER);
  29193. }
  29194. if (ret == 0) {
  29195. /* Prime */
  29196. ret = DataToHexStringAlloc(
  29197. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  29198. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  29199. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29200. }
  29201. if (ret == 0) {
  29202. /* Parameter A */
  29203. ret = DataToHexStringAlloc(
  29204. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  29205. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  29206. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29207. }
  29208. if (ret == 0) {
  29209. /* Parameter B */
  29210. ret = DataToHexStringAlloc(
  29211. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  29212. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  29213. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29214. }
  29215. if (ret == 0) {
  29216. /* Order of curve */
  29217. ret = DataToHexStringAlloc(
  29218. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  29219. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  29220. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29221. }
  29222. #else
  29223. if (ret == 0) {
  29224. /* Base X-ordinate */
  29225. DataToHexString(base + 1, curve->size, curve->Gx);
  29226. /* Base Y-ordinate */
  29227. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  29228. /* Prime */
  29229. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  29230. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  29231. curve->prime);
  29232. /* Parameter A */
  29233. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  29234. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  29235. curve->Af);
  29236. /* Parameter B */
  29237. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  29238. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  29239. curve->Bf);
  29240. /* Order of curve */
  29241. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  29242. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  29243. curve->order);
  29244. }
  29245. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  29246. /* Store parameter set in key. */
  29247. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  29248. ret = ASN_PARSE_E;
  29249. }
  29250. if (ret == 0) {
  29251. /* The parameter set was allocated.. */
  29252. key->deallocSet = 1;
  29253. }
  29254. if ((ret != 0) && (curve != NULL)) {
  29255. /* Failed to set parameters so free parameter set. */
  29256. wc_ecc_free_curve(curve, key->heap);
  29257. }
  29258. FREE_ASNGETDATA(dataASN, key->heap);
  29259. return ret;
  29260. }
  29261. #endif /* WOLFSSL_CUSTOM_CURVES */
  29262. #endif /* WOLFSSL_ASN_TEMPLATE */
  29263. #ifdef HAVE_ECC
  29264. #ifdef WOLFSSL_ASN_TEMPLATE
  29265. /* ASN.1 template for ECC private key.
  29266. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  29267. */
  29268. static const ASNItem eccKeyASN[] = {
  29269. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29270. /* version */
  29271. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  29272. /* privateKey */
  29273. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  29274. /* parameters */
  29275. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  29276. /* named */
  29277. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  29278. /* specified */
  29279. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  29280. /* publicKey */
  29281. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  29282. /* Uncompressed point - X9.62. */
  29283. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  29284. };
  29285. enum {
  29286. ECCKEYASN_IDX_SEQ = 0,
  29287. ECCKEYASN_IDX_VER,
  29288. ECCKEYASN_IDX_PKEY,
  29289. ECCKEYASN_IDX_PARAMS,
  29290. ECCKEYASN_IDX_CURVEID,
  29291. ECCKEYASN_IDX_CURVEPARAMS,
  29292. ECCKEYASN_IDX_PUBKEY,
  29293. ECCKEYASN_IDX_PUBKEY_VAL
  29294. };
  29295. /* Number of items in ASN.1 template for ECC private key. */
  29296. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  29297. #endif
  29298. WOLFSSL_ABI
  29299. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  29300. word32 inSz)
  29301. {
  29302. #ifndef WOLFSSL_ASN_TEMPLATE
  29303. word32 oidSum;
  29304. int version, length;
  29305. int privSz, pubSz = 0;
  29306. byte b;
  29307. int ret = 0;
  29308. int curve_id = ECC_CURVE_DEF;
  29309. #ifdef WOLFSSL_SMALL_STACK
  29310. byte* priv;
  29311. byte* pub = NULL;
  29312. #else
  29313. byte priv[ECC_MAXSIZE+1];
  29314. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  29315. #endif
  29316. word32 algId = 0;
  29317. byte* pubData = NULL;
  29318. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  29319. return BAD_FUNC_ARG;
  29320. /* if has pkcs8 header skip it */
  29321. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  29322. /* ignore error, did not have pkcs8 header */
  29323. }
  29324. else {
  29325. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  29326. }
  29327. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29328. return ASN_PARSE_E;
  29329. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  29330. return ASN_PARSE_E;
  29331. if (*inOutIdx >= inSz)
  29332. return ASN_PARSE_E;
  29333. b = input[*inOutIdx];
  29334. *inOutIdx += 1;
  29335. /* priv type */
  29336. if (b != 4 && b != 6 && b != 7)
  29337. return ASN_PARSE_E;
  29338. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  29339. return ASN_PARSE_E;
  29340. privSz = length;
  29341. if (privSz > ECC_MAXSIZE)
  29342. return BUFFER_E;
  29343. #ifdef WOLFSSL_SMALL_STACK
  29344. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29345. if (priv == NULL)
  29346. return MEMORY_E;
  29347. #endif
  29348. /* priv key */
  29349. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  29350. *inOutIdx += (word32)length;
  29351. if ((*inOutIdx + 1) < inSz) {
  29352. /* prefix 0, may have */
  29353. b = input[*inOutIdx];
  29354. if (b == ECC_PREFIX_0) {
  29355. *inOutIdx += 1;
  29356. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29357. ret = ASN_PARSE_E;
  29358. else {
  29359. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  29360. inSz);
  29361. if (ret == 0) {
  29362. if ((ret = CheckCurve(oidSum)) < 0)
  29363. ret = ECC_CURVE_OID_E;
  29364. else {
  29365. curve_id = ret;
  29366. ret = 0;
  29367. }
  29368. }
  29369. }
  29370. }
  29371. }
  29372. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  29373. /* prefix 1 */
  29374. b = input[*inOutIdx];
  29375. *inOutIdx += 1;
  29376. if (b != ECC_PREFIX_1) {
  29377. ret = ASN_ECC_KEY_E;
  29378. }
  29379. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  29380. ret = ASN_PARSE_E;
  29381. }
  29382. else {
  29383. /* key header */
  29384. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  29385. if (ret == 0) {
  29386. /* pub key */
  29387. pubSz = length;
  29388. if (pubSz > 2*(ECC_MAXSIZE+1))
  29389. ret = BUFFER_E;
  29390. else {
  29391. #ifdef WOLFSSL_SMALL_STACK
  29392. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29393. if (pub == NULL)
  29394. ret = MEMORY_E;
  29395. else
  29396. #endif
  29397. {
  29398. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  29399. *inOutIdx += (word32)length;
  29400. pubData = pub;
  29401. }
  29402. }
  29403. }
  29404. }
  29405. }
  29406. if (ret == 0) {
  29407. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  29408. (word32)pubSz, key, curve_id);
  29409. }
  29410. #ifdef WOLFSSL_SMALL_STACK
  29411. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29412. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29413. #endif
  29414. return ret;
  29415. #else
  29416. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29417. byte version;
  29418. int ret = 0;
  29419. int curve_id = ECC_CURVE_DEF;
  29420. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  29421. word32 algId = 0;
  29422. #endif
  29423. /* Validate parameters. */
  29424. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29425. ret = BAD_FUNC_ARG;
  29426. }
  29427. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  29428. /* if has pkcs8 header skip it */
  29429. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  29430. /* ignore error, did not have pkcs8 header */
  29431. }
  29432. else {
  29433. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  29434. }
  29435. #endif
  29436. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29437. if (ret == 0) {
  29438. /* Get the version and set the expected OID type. */
  29439. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  29440. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  29441. /* Decode the private ECC key. */
  29442. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29443. inOutIdx, inSz);
  29444. }
  29445. /* Only version 1 supported. */
  29446. if (ret == 0) {
  29447. if (version != 1) {
  29448. ret = ASN_PARSE_E;
  29449. }
  29450. }
  29451. /* Curve Parameters are optional. */
  29452. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  29453. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  29454. /* Named curve - check and get id. */
  29455. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  29456. if (curve_id < 0) {
  29457. ret = ECC_CURVE_OID_E;
  29458. }
  29459. }
  29460. else {
  29461. #ifdef WOLFSSL_CUSTOM_CURVES
  29462. /* Parse explicit parameters. */
  29463. ret = EccSpecifiedECDomainDecode(
  29464. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  29465. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  29466. #else
  29467. /* Explicit parameters not supported in build configuration. */
  29468. ret = ASN_PARSE_E;
  29469. #endif
  29470. }
  29471. }
  29472. if (ret == 0) {
  29473. /* Import private key value and public point (may be NULL). */
  29474. ret = wc_ecc_import_private_key_ex(
  29475. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  29476. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  29477. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  29478. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  29479. key, curve_id);
  29480. }
  29481. FREE_ASNGETDATA(dataASN, key->heap);
  29482. return ret;
  29483. #endif
  29484. }
  29485. #ifdef WOLFSSL_CUSTOM_CURVES
  29486. #ifndef WOLFSSL_ASN_TEMPLATE
  29487. /* returns 0 on success */
  29488. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  29489. word32 inSz, void* heap, int heapType)
  29490. {
  29491. int len;
  29492. int i;
  29493. char* str;
  29494. word32 localIdx;
  29495. byte tag;
  29496. if (*inOutIdx >= inSz) {
  29497. return BUFFER_E;
  29498. }
  29499. localIdx = *inOutIdx;
  29500. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  29501. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  29502. return ASN_PARSE_E;
  29503. }
  29504. else {
  29505. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  29506. return ASN_PARSE_E;
  29507. }
  29508. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  29509. if (str == NULL) {
  29510. return MEMORY_E;
  29511. }
  29512. for (i=0; i<len; i++)
  29513. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  29514. str[len*2] = '\0';
  29515. *inOutIdx += (word32)len;
  29516. *out = str;
  29517. (void)heap;
  29518. (void)heapType;
  29519. return 0;
  29520. }
  29521. static int EccKeyParamCopy(char** dst, char* src)
  29522. {
  29523. int ret = 0;
  29524. #ifdef WOLFSSL_ECC_CURVE_STATIC
  29525. word32 length;
  29526. #endif
  29527. if (dst == NULL || src == NULL)
  29528. return BAD_FUNC_ARG;
  29529. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29530. *dst = src;
  29531. #else
  29532. length = (int)XSTRLEN(src) + 1;
  29533. if (length > MAX_ECC_STRING) {
  29534. WOLFSSL_MSG("ECC Param too large for buffer");
  29535. ret = BUFFER_E;
  29536. }
  29537. else {
  29538. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  29539. }
  29540. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29541. #endif
  29542. return ret;
  29543. }
  29544. #endif /* !WOLFSSL_ASN_TEMPLATE */
  29545. #endif /* WOLFSSL_CUSTOM_CURVES */
  29546. WOLFSSL_ABI
  29547. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  29548. ecc_key* key, word32 inSz)
  29549. {
  29550. #ifndef WOLFSSL_ASN_TEMPLATE
  29551. int ret;
  29552. int version, length;
  29553. int curve_id = ECC_CURVE_DEF;
  29554. word32 oidSum, localIdx;
  29555. byte tag, isPrivFormat = 0;
  29556. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  29557. return BAD_FUNC_ARG;
  29558. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29559. return ASN_PARSE_E;
  29560. /* Check if ECC private key is being used and skip private portion */
  29561. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  29562. isPrivFormat = 1;
  29563. /* Type private key */
  29564. if (*inOutIdx >= inSz)
  29565. return ASN_PARSE_E;
  29566. tag = input[*inOutIdx];
  29567. *inOutIdx += 1;
  29568. if (tag != 4 && tag != 6 && tag != 7)
  29569. return ASN_PARSE_E;
  29570. /* Skip Private Key */
  29571. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  29572. return ASN_PARSE_E;
  29573. if (length > ECC_MAXSIZE)
  29574. return BUFFER_E;
  29575. *inOutIdx += (word32)length;
  29576. /* Private Curve Header */
  29577. if (*inOutIdx >= inSz)
  29578. return ASN_PARSE_E;
  29579. tag = input[*inOutIdx];
  29580. *inOutIdx += 1;
  29581. if (tag != ECC_PREFIX_0)
  29582. return ASN_ECC_KEY_E;
  29583. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29584. return ASN_PARSE_E;
  29585. }
  29586. /* Standard ECC public key */
  29587. else {
  29588. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29589. return ASN_PARSE_E;
  29590. ret = SkipObjectId(input, inOutIdx, inSz);
  29591. if (ret != 0)
  29592. return ret;
  29593. }
  29594. if (*inOutIdx >= inSz) {
  29595. return BUFFER_E;
  29596. }
  29597. localIdx = *inOutIdx;
  29598. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  29599. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  29600. #ifdef WOLFSSL_CUSTOM_CURVES
  29601. ecc_set_type* curve;
  29602. int len;
  29603. char* point = NULL;
  29604. ret = 0;
  29605. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  29606. DYNAMIC_TYPE_ECC_BUFFER);
  29607. if (curve == NULL)
  29608. ret = MEMORY_E;
  29609. if (ret == 0) {
  29610. static const char customName[] = "Custom";
  29611. XMEMSET(curve, 0, sizeof(*curve));
  29612. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29613. curve->name = customName;
  29614. #else
  29615. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  29616. #endif
  29617. curve->id = ECC_CURVE_CUSTOM;
  29618. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29619. ret = ASN_PARSE_E;
  29620. }
  29621. if (ret == 0) {
  29622. GetInteger7Bit(input, inOutIdx, inSz);
  29623. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29624. ret = ASN_PARSE_E;
  29625. }
  29626. if (ret == 0) {
  29627. char* p = NULL;
  29628. SkipObjectId(input, inOutIdx, inSz);
  29629. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  29630. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29631. if (ret == 0) {
  29632. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29633. ret = EccKeyParamCopy((char**)&curve->prime, p);
  29634. #else
  29635. const char *_tmp_ptr = &curve->prime[0];
  29636. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  29637. #endif
  29638. }
  29639. }
  29640. if (ret == 0) {
  29641. curve->size = (int)XSTRLEN(curve->prime) / 2;
  29642. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29643. ret = ASN_PARSE_E;
  29644. }
  29645. if (ret == 0) {
  29646. char* af = NULL;
  29647. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  29648. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29649. if (ret == 0) {
  29650. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29651. ret = EccKeyParamCopy((char**)&curve->Af, af);
  29652. #else
  29653. const char *_tmp_ptr = &curve->Af[0];
  29654. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  29655. #endif
  29656. }
  29657. }
  29658. if (ret == 0) {
  29659. char* bf = NULL;
  29660. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  29661. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29662. if (ret == 0) {
  29663. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29664. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29665. #else
  29666. const char *_tmp_ptr = &curve->Bf[0];
  29667. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29668. #endif
  29669. }
  29670. }
  29671. if (ret == 0) {
  29672. localIdx = *inOutIdx;
  29673. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29674. == 0 && tag == ASN_BIT_STRING) {
  29675. len = 0;
  29676. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29677. if (ret > 0)
  29678. ret = 0; /* reset on success */
  29679. *inOutIdx += (word32)len;
  29680. }
  29681. }
  29682. if (ret == 0) {
  29683. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29684. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29685. /* sanity check that point buffer is not smaller than the expected
  29686. * size to hold ( 0 4 || Gx || Gy )
  29687. * where Gx and Gy are each the size of curve->size * 2 */
  29688. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29689. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29690. ret = BUFFER_E;
  29691. }
  29692. }
  29693. if (ret == 0) {
  29694. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29695. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29696. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29697. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29698. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29699. if (curve->Gx == NULL || curve->Gy == NULL) {
  29700. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29701. ret = MEMORY_E;
  29702. }
  29703. #else
  29704. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29705. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29706. ret = BUFFER_E;
  29707. }
  29708. #endif
  29709. }
  29710. if (ret == 0) {
  29711. char* o = NULL;
  29712. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  29713. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29714. (size_t)curve->size * 2);
  29715. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29716. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29717. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29718. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29719. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29720. if (ret == 0) {
  29721. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29722. ret = EccKeyParamCopy((char**)&curve->order, o);
  29723. #else
  29724. const char *_tmp_ptr = &curve->order[0];
  29725. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29726. #endif
  29727. }
  29728. }
  29729. if (ret == 0) {
  29730. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29731. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29732. curve->oid = NULL;
  29733. #else
  29734. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29735. #endif
  29736. curve->oidSz = 0;
  29737. curve->oidSum = 0;
  29738. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29739. ret = ASN_PARSE_E;
  29740. }
  29741. key->deallocSet = 1;
  29742. curve = NULL;
  29743. }
  29744. if (curve != NULL)
  29745. wc_ecc_free_curve(curve, key->heap);
  29746. if (ret < 0)
  29747. return ret;
  29748. #else
  29749. return ASN_PARSE_E;
  29750. #endif /* WOLFSSL_CUSTOM_CURVES */
  29751. }
  29752. else {
  29753. /* ecc params information */
  29754. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29755. if (ret != 0)
  29756. return ret;
  29757. /* get curve id */
  29758. if ((ret = CheckCurve(oidSum)) < 0)
  29759. return ECC_CURVE_OID_E;
  29760. else {
  29761. curve_id = ret;
  29762. }
  29763. }
  29764. if (isPrivFormat) {
  29765. /* Public Curve Header - skip */
  29766. if (*inOutIdx >= inSz)
  29767. return ASN_PARSE_E;
  29768. tag = input[*inOutIdx];
  29769. *inOutIdx += 1;
  29770. if (tag != ECC_PREFIX_1)
  29771. return ASN_ECC_KEY_E;
  29772. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29773. return ASN_PARSE_E;
  29774. }
  29775. /* key header */
  29776. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29777. if (ret != 0)
  29778. return ret;
  29779. /* This is the raw point data compressed or uncompressed. */
  29780. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  29781. curve_id) != 0) {
  29782. return ASN_ECC_KEY_E;
  29783. }
  29784. *inOutIdx += (word32)length;
  29785. return 0;
  29786. #else
  29787. /* eccKeyASN is longer than eccPublicKeyASN. */
  29788. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29789. int ret = 0;
  29790. int curve_id = ECC_CURVE_DEF;
  29791. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29792. #ifdef WOLFSSL_CUSTOM_CURVES
  29793. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29794. #endif
  29795. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29796. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29797. ret = BAD_FUNC_ARG;
  29798. }
  29799. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29800. if (ret == 0) {
  29801. /* Clear dynamic data for ECC public key. */
  29802. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29803. #if !defined(WOLFSSL_SM2) || !defined(WOLFSSL_SM3)
  29804. /* Set required ECDSA OID and ignore the curve OID type. */
  29805. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29806. sizeof(keyEcdsaOid));
  29807. #else
  29808. GetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  29809. #endif
  29810. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  29811. /* Decode the public ECC key. */
  29812. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29813. input, inOutIdx, inSz);
  29814. if (ret != 0) {
  29815. oidIdx = ECCKEYASN_IDX_CURVEID;
  29816. #ifdef WOLFSSL_CUSTOM_CURVES
  29817. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29818. #endif
  29819. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29820. /* Clear dynamic data for ECC private key. */
  29821. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29822. /* Check named curve OID type. */
  29823. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  29824. /* Try private key format .*/
  29825. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29826. inOutIdx, inSz);
  29827. if (ret != 0) {
  29828. ret = ASN_PARSE_E;
  29829. }
  29830. }
  29831. }
  29832. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  29833. if ((ret == 0) && (oidIdx == ECCPUBLICKEYASN_IDX_ALGOID_CURVEID)) {
  29834. int oidSum = dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  29835. if ((oidSum != ECDSAk) && (oidSum != SM2k)) {
  29836. ret = ASN_PARSE_E;
  29837. }
  29838. }
  29839. #endif
  29840. if (ret == 0) {
  29841. if (dataASN[oidIdx].tag != 0) {
  29842. /* Named curve - check and get id. */
  29843. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29844. if (curve_id < 0) {
  29845. ret = ASN_OBJECT_ID_E;
  29846. }
  29847. }
  29848. else {
  29849. #ifdef WOLFSSL_CUSTOM_CURVES
  29850. /* Parse explicit parameters. */
  29851. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29852. dataASN[specIdx].data.ref.length, key);
  29853. #else
  29854. /* Explicit parameters not supported in build configuration. */
  29855. ret = ASN_PARSE_E;
  29856. #endif
  29857. }
  29858. }
  29859. if (ret == 0) {
  29860. /* Import public point. */
  29861. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29862. dataASN[pubIdx].data.ref.length, key, curve_id);
  29863. if (ret != 0) {
  29864. ret = ASN_ECC_KEY_E;
  29865. }
  29866. }
  29867. FREE_ASNGETDATA(dataASN, key->heap);
  29868. return ret;
  29869. #endif /* WOLFSSL_ASN_TEMPLATE */
  29870. }
  29871. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29872. /* build DER formatted ECC key, include optional public key if requested,
  29873. * return length on success, negative on error */
  29874. int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29875. int pubIn, int curveIn)
  29876. {
  29877. #ifndef WOLFSSL_ASN_TEMPLATE
  29878. byte curve[MAX_ALGO_SZ+2];
  29879. byte ver[MAX_VERSION_SZ];
  29880. byte seq[MAX_SEQ_SZ];
  29881. int ret, curveSz, verSz;
  29882. word32 totalSz;
  29883. int privHdrSz = ASN_ECC_HEADER_SZ;
  29884. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29885. #ifdef WOLFSSL_NO_MALLOC
  29886. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29887. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29888. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29889. #else
  29890. byte *prv = NULL, *pub = NULL;
  29891. #endif
  29892. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29893. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29894. if (key == NULL || (output == NULL && inLen == NULL))
  29895. return BAD_FUNC_ARG;
  29896. if (curveIn) {
  29897. /* curve */
  29898. curve[curveidx++] = ECC_PREFIX_0;
  29899. curveidx++ /* to put the size after computation */;
  29900. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29901. if (curveSz < 0)
  29902. return curveSz;
  29903. /* set computed size */
  29904. curve[1] = (byte)curveSz;
  29905. curveidx += (word32)curveSz;
  29906. }
  29907. /* private */
  29908. privSz = (word32)key->dp->size;
  29909. #ifdef WOLFSSL_QNX_CAAM
  29910. /* check if is a black key, and add MAC size if needed */
  29911. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29912. privSz = privSz + WC_CAAM_MAC_SZ;
  29913. }
  29914. #endif
  29915. #ifndef WOLFSSL_NO_MALLOC
  29916. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  29917. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29918. if (prv == NULL) {
  29919. return MEMORY_E;
  29920. }
  29921. #else
  29922. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29923. return BUFFER_E;
  29924. }
  29925. #endif
  29926. if (privSz < ASN_LONG_LENGTH) {
  29927. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29928. }
  29929. else {
  29930. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29931. }
  29932. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29933. if (ret < 0) {
  29934. #ifndef WOLFSSL_NO_MALLOC
  29935. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29936. #endif
  29937. return ret;
  29938. }
  29939. prvidx += privSz;
  29940. /* pubIn */
  29941. if (pubIn) {
  29942. PRIVATE_KEY_UNLOCK();
  29943. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29944. PRIVATE_KEY_LOCK();
  29945. if (ret != LENGTH_ONLY_E) {
  29946. #ifndef WOLFSSL_NO_MALLOC
  29947. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29948. #endif
  29949. return ret;
  29950. }
  29951. #ifndef WOLFSSL_NO_MALLOC
  29952. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  29953. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29954. if (pub == NULL) {
  29955. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29956. return MEMORY_E;
  29957. }
  29958. #else
  29959. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29960. return BUFFER_E;
  29961. }
  29962. #endif
  29963. pub[pubidx++] = ECC_PREFIX_1;
  29964. if (pubSz > 128) /* leading zero + extra size byte */
  29965. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29966. else /* leading zero */
  29967. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29968. /* SetBitString adds leading zero */
  29969. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29970. PRIVATE_KEY_UNLOCK();
  29971. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29972. PRIVATE_KEY_LOCK();
  29973. if (ret != 0) {
  29974. #ifndef WOLFSSL_NO_MALLOC
  29975. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29976. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29977. #endif
  29978. return ret;
  29979. }
  29980. pubidx += pubSz;
  29981. }
  29982. /* make headers */
  29983. verSz = SetMyVersion(1, ver, FALSE);
  29984. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  29985. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  29986. if (output == NULL) {
  29987. *inLen = totalSz;
  29988. #ifndef WOLFSSL_NO_MALLOC
  29989. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29990. if (pubIn) {
  29991. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29992. }
  29993. #endif
  29994. return LENGTH_ONLY_E;
  29995. }
  29996. if (inLen != NULL && totalSz > *inLen) {
  29997. #ifndef WOLFSSL_NO_MALLOC
  29998. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29999. if (pubIn) {
  30000. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30001. }
  30002. #endif
  30003. return BAD_FUNC_ARG;
  30004. }
  30005. /* write out */
  30006. /* seq */
  30007. XMEMCPY(output + idx, seq, seqSz);
  30008. idx = seqSz;
  30009. /* ver */
  30010. XMEMCPY(output + idx, ver, (size_t)verSz);
  30011. idx += (word32)verSz;
  30012. /* private */
  30013. XMEMCPY(output + idx, prv, prvidx);
  30014. idx += prvidx;
  30015. #ifndef WOLFSSL_NO_MALLOC
  30016. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30017. #endif
  30018. /* curve */
  30019. XMEMCPY(output + idx, curve, curveidx);
  30020. idx += curveidx;
  30021. /* pubIn */
  30022. if (pubIn) {
  30023. XMEMCPY(output + idx, pub, pubidx);
  30024. /* idx += pubidx; not used after write, if more data remove comment */
  30025. #ifndef WOLFSSL_NO_MALLOC
  30026. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30027. #endif
  30028. }
  30029. return (int)totalSz;
  30030. #else
  30031. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  30032. word32 privSz, pubSz;
  30033. int sz = 0;
  30034. int ret = 0;
  30035. int curveIdSz = 0;
  30036. /* Check validity of parameters. */
  30037. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  30038. ret = BAD_FUNC_ARG;
  30039. }
  30040. /* Check key has parameters when encoding curve. */
  30041. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  30042. ret = BAD_FUNC_ARG;
  30043. }
  30044. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  30045. if (ret == 0) {
  30046. /* Private key size is the curve size. */
  30047. privSz = (word32)key->dp->size;
  30048. if (pubIn) {
  30049. /* Get the length of the public key. */
  30050. PRIVATE_KEY_UNLOCK();
  30051. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  30052. PRIVATE_KEY_LOCK();
  30053. if (ret == LENGTH_ONLY_E)
  30054. ret = 0;
  30055. }
  30056. }
  30057. if (ret == 0) {
  30058. /* Version: 1 */
  30059. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  30060. /* Leave space for private key. */
  30061. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  30062. if (curveIn) {
  30063. /* Get length of the named curve OID to put into the encoding. */
  30064. curveIdSz = SetCurve(key, NULL, 0);
  30065. if (curveIdSz < 0) {
  30066. ret = curveIdSz;
  30067. }
  30068. /* Curve OID */
  30069. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  30070. (word32)curveIdSz);
  30071. /* TODO: add support for SpecifiedECDomain curve. */
  30072. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  30073. }
  30074. else {
  30075. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  30076. eccKeyASN_Length);
  30077. }
  30078. if (ret == 0) {
  30079. if (pubIn) {
  30080. /* Leave space for public key. */
  30081. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  30082. }
  30083. else {
  30084. /* Don't write out public key. */
  30085. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  30086. eccKeyASN_Length);
  30087. }
  30088. /* Calculate size of the private key encoding. */
  30089. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  30090. }
  30091. }
  30092. /* Return the size if no buffer. */
  30093. if ((ret == 0) && (output == NULL)) {
  30094. *inLen = (word32)sz;
  30095. ret = LENGTH_ONLY_E;
  30096. }
  30097. /* Check the buffer is big enough. */
  30098. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  30099. ret = BAD_FUNC_ARG;
  30100. }
  30101. if ((ret == 0) && (output != NULL)) {
  30102. /* Encode the private key. */
  30103. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  30104. if (curveIn) {
  30105. /* Put named curve OID data into encoding. */
  30106. curveIdSz = SetCurve(key,
  30107. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  30108. (size_t)curveIdSz);
  30109. if (curveIdSz < 0) {
  30110. ret = curveIdSz;
  30111. }
  30112. }
  30113. if (ret == 0) {
  30114. /* Export the private value into the buffer. */
  30115. ret = wc_ecc_export_private_only(key,
  30116. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  30117. }
  30118. if ((ret == 0) && pubIn) {
  30119. /* Export the public point into the buffer. */
  30120. PRIVATE_KEY_UNLOCK();
  30121. ret = wc_ecc_export_x963(key,
  30122. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  30123. &pubSz);
  30124. PRIVATE_KEY_LOCK();
  30125. }
  30126. }
  30127. if (ret == 0) {
  30128. /* Return the encoding size. */
  30129. ret = sz;
  30130. }
  30131. FREE_ASNSETDATA(dataASN, key->heap);
  30132. return ret;
  30133. #endif
  30134. }
  30135. /* Write a Private ecc key, including public to DER format,
  30136. * length on success else < 0 */
  30137. WOLFSSL_ABI
  30138. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  30139. {
  30140. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  30141. }
  30142. /* Write only private ecc key to DER format,
  30143. * length on success else < 0 */
  30144. int wc_EccKeyDerSize(ecc_key* key, int pub)
  30145. {
  30146. word32 sz = 0;
  30147. int ret;
  30148. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  30149. if (ret != LENGTH_ONLY_E) {
  30150. return ret;
  30151. }
  30152. return (int)sz;
  30153. }
  30154. /* Write only private ecc key to DER format,
  30155. * length on success else < 0 */
  30156. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  30157. {
  30158. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  30159. }
  30160. #ifdef HAVE_PKCS8
  30161. /* Write only private ecc key or both private and public parts to unencrypted
  30162. * PKCS#8 format.
  30163. *
  30164. * If output is NULL, places required PKCS#8 buffer size in outLen and
  30165. * returns LENGTH_ONLY_E.
  30166. *
  30167. * return length on success else < 0 */
  30168. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  30169. int includePublic)
  30170. {
  30171. int ret;
  30172. word32 tmpDerSz;
  30173. int algoID = 0;
  30174. word32 oidSz = 0;
  30175. word32 pkcs8Sz = 0;
  30176. const byte* curveOID = NULL;
  30177. #ifdef WOLFSSL_NO_MALLOC
  30178. byte tmpDer[ECC_BUFSIZE];
  30179. #else
  30180. byte* tmpDer = NULL;
  30181. #endif
  30182. word32 sz = ECC_BUFSIZE;
  30183. if (key == NULL || key->dp == NULL || outLen == NULL)
  30184. return BAD_FUNC_ARG;
  30185. /* set algoID, get curve OID */
  30186. algoID = ECDSAk;
  30187. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  30188. if (ret < 0)
  30189. return ret;
  30190. #ifndef WOLFSSL_NO_MALLOC
  30191. /* temp buffer for plain DER key */
  30192. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30193. if (tmpDer == NULL)
  30194. return MEMORY_E;
  30195. #endif
  30196. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  30197. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  30198. if (ret < 0) {
  30199. #ifndef WOLFSSL_NO_MALLOC
  30200. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30201. #endif
  30202. return ret;
  30203. }
  30204. tmpDerSz = (word32)ret;
  30205. /* get pkcs8 expected output size */
  30206. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  30207. curveOID, oidSz);
  30208. if (ret != LENGTH_ONLY_E) {
  30209. #ifndef WOLFSSL_NO_MALLOC
  30210. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30211. #endif
  30212. return ret;
  30213. }
  30214. if (output == NULL) {
  30215. #ifndef WOLFSSL_NO_MALLOC
  30216. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30217. #endif
  30218. *outLen = pkcs8Sz;
  30219. return LENGTH_ONLY_E;
  30220. }
  30221. else if (*outLen < pkcs8Sz) {
  30222. #ifndef WOLFSSL_NO_MALLOC
  30223. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30224. #endif
  30225. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  30226. return BUFFER_E;
  30227. }
  30228. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  30229. algoID, curveOID, oidSz);
  30230. if (ret < 0) {
  30231. #ifndef WOLFSSL_NO_MALLOC
  30232. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30233. #endif
  30234. return ret;
  30235. }
  30236. #ifndef WOLFSSL_NO_MALLOC
  30237. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  30238. #endif
  30239. *outLen = (word32)ret;
  30240. return ret;
  30241. }
  30242. /* Write only private ecc key to unencrypted PKCS#8 format.
  30243. *
  30244. * return length on success else < 0 */
  30245. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  30246. {
  30247. return eccToPKCS8(key, output, outLen, 0);
  30248. }
  30249. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  30250. *
  30251. * return length on success else < 0 */
  30252. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  30253. word32* outLen)
  30254. {
  30255. return eccToPKCS8(key, output, outLen, 1);
  30256. }
  30257. #endif /* HAVE_PKCS8 */
  30258. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  30259. #endif /* HAVE_ECC */
  30260. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  30261. #ifdef WOLFSSL_ASN_TEMPLATE
  30262. /* ASN.1 template for Ed25519 and Ed448 private key.
  30263. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  30264. */
  30265. static const ASNItem edKeyASN[] = {
  30266. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30267. /* Version */
  30268. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  30269. /* privateKeyAlgorithm */
  30270. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30271. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  30272. /* privateKey */
  30273. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  30274. /* CurvePrivateKey */
  30275. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30276. /* attributes */
  30277. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  30278. /* publicKey */
  30279. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  30280. };
  30281. enum {
  30282. EDKEYASN_IDX_SEQ = 0,
  30283. EDKEYASN_IDX_VER,
  30284. EDKEYASN_IDX_PKEYALGO_SEQ,
  30285. EDKEYASN_IDX_PKEYALGO_OID,
  30286. EDKEYASN_IDX_PKEY,
  30287. EDKEYASN_IDX_PKEY_CURVEPKEY,
  30288. EDKEYASN_IDX_ATTRS,
  30289. EDKEYASN_IDX_PUBKEY
  30290. };
  30291. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  30292. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  30293. #endif
  30294. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  30295. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  30296. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  30297. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  30298. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  30299. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  30300. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  30301. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  30302. byte* privKey, word32* privKeyLen,
  30303. byte* pubKey, word32* pubKeyLen, int keyType)
  30304. {
  30305. #ifndef WOLFSSL_ASN_TEMPLATE
  30306. word32 oid;
  30307. int version, length, endKeyIdx, privSz, pubSz;
  30308. const byte* priv;
  30309. const byte* pub;
  30310. #else
  30311. int ret = 0;
  30312. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  30313. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  30314. #endif
  30315. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  30316. privKey == NULL || privKeyLen == NULL) {
  30317. #ifdef WOLFSSL_ASN_TEMPLATE
  30318. FREE_ASNGETDATA(dataASN, NULL);
  30319. #endif
  30320. return BAD_FUNC_ARG;
  30321. }
  30322. #ifndef WOLFSSL_ASN_TEMPLATE
  30323. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  30324. endKeyIdx = (int)*inOutIdx + length;
  30325. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  30326. return ASN_PARSE_E;
  30327. if (version != 0) {
  30328. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  30329. return ASN_PARSE_E;
  30330. }
  30331. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  30332. return ASN_PARSE_E;
  30333. if (oid != (word32)keyType)
  30334. return ASN_PARSE_E;
  30335. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  30336. return ASN_PARSE_E;
  30337. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  30338. return ASN_PARSE_E;
  30339. priv = input + *inOutIdx;
  30340. *inOutIdx += (word32)privSz;
  30341. }
  30342. else {
  30343. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  30344. return ASN_PARSE_E;
  30345. priv = input + *inOutIdx;
  30346. *inOutIdx += (word32)privSz;
  30347. endKeyIdx = (int)*inOutIdx;
  30348. }
  30349. if ((word32)privSz > *privKeyLen)
  30350. return BUFFER_E;
  30351. if (endKeyIdx == (int)*inOutIdx) {
  30352. *privKeyLen = (word32)privSz;
  30353. XMEMCPY(privKey, priv, *privKeyLen);
  30354. if (pubKeyLen != NULL)
  30355. *pubKeyLen = 0;
  30356. }
  30357. else {
  30358. if (pubKeyLen == NULL) {
  30359. return BAD_FUNC_ARG;
  30360. }
  30361. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  30362. inOutIdx, &pubSz, inSz) < 0) {
  30363. return ASN_PARSE_E;
  30364. }
  30365. if ((word32)pubSz > *pubKeyLen)
  30366. return BUFFER_E;
  30367. pub = input + *inOutIdx;
  30368. *inOutIdx += (word32)pubSz;
  30369. *privKeyLen = (word32)privSz;
  30370. XMEMCPY(privKey, priv, *privKeyLen);
  30371. *pubKeyLen = (word32)pubSz;
  30372. if (pubKey != NULL)
  30373. XMEMCPY(pubKey, pub, *pubKeyLen);
  30374. }
  30375. if (endKeyIdx != (int)*inOutIdx)
  30376. return ASN_PARSE_E;
  30377. return 0;
  30378. #else
  30379. if (ret == 0) {
  30380. /* Require OID. */
  30381. word32 oidSz;
  30382. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  30383. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  30384. /* Parse full private key. */
  30385. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  30386. inOutIdx, inSz);
  30387. if (ret != 0) {
  30388. /* Parse just the OCTET_STRING. */
  30389. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  30390. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  30391. inOutIdx, inSz);
  30392. if (ret != 0) {
  30393. ret = ASN_PARSE_E;
  30394. }
  30395. }
  30396. }
  30397. /* Check the private value length is correct. */
  30398. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  30399. > *privKeyLen) {
  30400. ret = ASN_PARSE_E;
  30401. }
  30402. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  30403. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  30404. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  30405. *privKeyLen);
  30406. if (pubKeyLen != NULL)
  30407. *pubKeyLen = 0;
  30408. }
  30409. else if ((ret == 0) &&
  30410. (pubKeyLen != NULL) &&
  30411. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  30412. ret = ASN_PARSE_E;
  30413. }
  30414. else if (ret == 0) {
  30415. /* Import private and public value. */
  30416. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  30417. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  30418. *privKeyLen);
  30419. if (pubKeyLen != NULL)
  30420. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  30421. if (pubKey != NULL && pubKeyLen != NULL)
  30422. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  30423. *pubKeyLen);
  30424. }
  30425. FREE_ASNGETDATA(dataASN, NULL);
  30426. return ret;
  30427. #endif /* WOLFSSL_ASN_TEMPLATE */
  30428. }
  30429. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  30430. byte* pubKey, word32* pubKeyLen, int keyType)
  30431. {
  30432. int ret = 0;
  30433. #ifndef WOLFSSL_ASN_TEMPLATE
  30434. int length;
  30435. word32 oid;
  30436. #else
  30437. word32 len;
  30438. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  30439. #endif
  30440. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  30441. pubKey == NULL || pubKeyLen == NULL) {
  30442. return BAD_FUNC_ARG;
  30443. }
  30444. #ifndef WOLFSSL_ASN_TEMPLATE
  30445. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30446. return ASN_PARSE_E;
  30447. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30448. return ASN_PARSE_E;
  30449. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  30450. return ASN_PARSE_E;
  30451. if (oid != (word32)keyType)
  30452. return ASN_PARSE_E;
  30453. /* key header */
  30454. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  30455. if (ret != 0)
  30456. return ret;
  30457. /* check that the value found is not too large for pubKey buffer */
  30458. if ((word32)length > *pubKeyLen)
  30459. return ASN_PARSE_E;
  30460. /* check that input buffer is exhausted */
  30461. if (*inOutIdx + (word32)length != inSz)
  30462. return ASN_PARSE_E;
  30463. /* This is the raw point data compressed or uncompressed. */
  30464. *pubKeyLen = (word32)length;
  30465. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  30466. #else
  30467. len = inSz - *inOutIdx;
  30468. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  30469. if (ret == 0) {
  30470. /* Require OID. */
  30471. word32 oidSz;
  30472. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  30473. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  30474. /* Decode Ed25519 private key. */
  30475. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  30476. inOutIdx, inSz);
  30477. if (ret != 0)
  30478. ret = ASN_PARSE_E;
  30479. /* check that input buffer is exhausted */
  30480. if (*inOutIdx != inSz)
  30481. ret = ASN_PARSE_E;
  30482. }
  30483. /* Check the public value length is correct. */
  30484. if ((ret == 0) &&
  30485. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  30486. ret = ASN_PARSE_E;
  30487. }
  30488. /* Check that the all the buffer was used. */
  30489. if ((ret == 0) &&
  30490. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  30491. ret = ASN_PARSE_E;
  30492. }
  30493. if (ret == 0) {
  30494. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  30495. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  30496. *pubKeyLen);
  30497. }
  30498. FREE_ASNGETDATA(dataASN, NULL);
  30499. #endif /* WOLFSSL_ASN_TEMPLATE */
  30500. return ret;
  30501. }
  30502. #endif
  30503. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  30504. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  30505. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30506. ed25519_key* key, word32 inSz)
  30507. {
  30508. int ret;
  30509. byte privKey[ED25519_KEY_SIZE], pubKey[2*ED25519_PUB_KEY_SIZE+1];
  30510. word32 privKeyLen = (word32)sizeof(privKey);
  30511. word32 pubKeyLen = (word32)sizeof(pubKey);
  30512. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30513. return BAD_FUNC_ARG;
  30514. }
  30515. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30516. pubKey, &pubKeyLen, ED25519k);
  30517. if (ret == 0) {
  30518. if (pubKeyLen == 0) {
  30519. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  30520. }
  30521. else {
  30522. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  30523. pubKey, pubKeyLen, key);
  30524. }
  30525. }
  30526. return ret;
  30527. }
  30528. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  30529. ed25519_key* key, word32 inSz)
  30530. {
  30531. int ret;
  30532. byte pubKey[2*ED25519_PUB_KEY_SIZE+1];
  30533. word32 pubKeyLen = (word32)sizeof(pubKey);
  30534. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30535. return BAD_FUNC_ARG;
  30536. }
  30537. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30538. pubKey, &pubKeyLen, ED25519k);
  30539. if (ret == 0) {
  30540. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  30541. }
  30542. return ret;
  30543. }
  30544. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  30545. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  30546. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30547. curve25519_key* key, word32 inSz)
  30548. {
  30549. int ret;
  30550. byte privKey[CURVE25519_KEYSIZE];
  30551. word32 privKeyLen = CURVE25519_KEYSIZE;
  30552. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30553. return BAD_FUNC_ARG;
  30554. }
  30555. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30556. NULL, NULL, X25519k);
  30557. if (ret == 0) {
  30558. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  30559. }
  30560. return ret;
  30561. }
  30562. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  30563. curve25519_key* key, word32 inSz)
  30564. {
  30565. int ret;
  30566. byte pubKey[CURVE25519_KEYSIZE];
  30567. word32 pubKeyLen = (word32)sizeof(pubKey);
  30568. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30569. return BAD_FUNC_ARG;
  30570. }
  30571. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30572. pubKey, &pubKeyLen, X25519k);
  30573. if (ret == 0) {
  30574. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  30575. }
  30576. return ret;
  30577. }
  30578. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  30579. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  30580. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  30581. *
  30582. * Pass NULL for output to get the size of the encoding.
  30583. *
  30584. * @param [in] privKey private key buffer
  30585. * @param [in] privKeyLen private key buffer length
  30586. * @param [in] pubKey public key buffer (optional)
  30587. * @param [in] pubKeyLen public key buffer length
  30588. * @param [out] output Buffer to put encoded data in (optional)
  30589. * @param [in] outLen Size of buffer in bytes
  30590. * @param [in] keyType is "enum Key_Sum" like ED25519k
  30591. * @return Size of encoded data in bytes on success
  30592. * @return BAD_FUNC_ARG when key is NULL.
  30593. * @return MEMORY_E when dynamic memory allocation failed.
  30594. */
  30595. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  30596. const byte* pubKey, word32 pubKeyLen,
  30597. byte* output, word32 outLen, int keyType)
  30598. {
  30599. int ret = 0;
  30600. #ifndef WOLFSSL_ASN_TEMPLATE
  30601. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  30602. #else
  30603. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  30604. int sz;
  30605. #endif
  30606. /* Validate parameters. */
  30607. if (privKey == NULL || outLen == 0) {
  30608. return BAD_FUNC_ARG;
  30609. }
  30610. #ifndef WOLFSSL_ASN_TEMPLATE
  30611. /* calculate size */
  30612. if (pubKey) {
  30613. pubSz = 2 + pubKeyLen;
  30614. }
  30615. privSz = 2 + 2 + privKeyLen;
  30616. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  30617. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  30618. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  30619. sz = seqSz + verSz + algoSz + privSz + pubSz;
  30620. /* checkout output size */
  30621. if (output != NULL && sz > outLen) {
  30622. ret = BAD_FUNC_ARG;
  30623. }
  30624. if (ret == 0 && output != NULL) {
  30625. /* write out */
  30626. /* seq */
  30627. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  30628. idx = seqSz;
  30629. /* ver */
  30630. SetMyVersion(0, output + idx, FALSE);
  30631. idx += verSz;
  30632. /* algo */
  30633. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  30634. idx += algoSz;
  30635. /* privKey */
  30636. idx += SetOctetString(2 + privKeyLen, output + idx);
  30637. idx += SetOctetString(privKeyLen, output + idx);
  30638. XMEMCPY(output + idx, privKey, privKeyLen);
  30639. idx += privKeyLen;
  30640. /* pubKey */
  30641. if (pubKey) {
  30642. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  30643. 1, pubKeyLen, output + idx);
  30644. XMEMCPY(output + idx, pubKey, pubKeyLen);
  30645. idx += pubKeyLen;
  30646. }
  30647. sz = idx;
  30648. }
  30649. if (ret == 0) {
  30650. /* Return size of encoding. */
  30651. ret = (int)sz;
  30652. }
  30653. #else
  30654. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  30655. if (ret == 0) {
  30656. /* Set version = 0 */
  30657. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  30658. /* Set OID. */
  30659. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
  30660. oidKeyType);
  30661. /* Leave space for private key. */
  30662. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  30663. /* Don't write out attributes. */
  30664. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  30665. if (pubKey) {
  30666. /* Leave space for public key. */
  30667. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  30668. }
  30669. else {
  30670. /* Don't put out public part. */
  30671. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  30672. edKeyASN_Length);
  30673. }
  30674. /* Calculate the size of encoding. */
  30675. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  30676. }
  30677. /* Check buffer is big enough. */
  30678. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30679. ret = BAD_FUNC_ARG;
  30680. }
  30681. if ((ret == 0) && (output != NULL)) {
  30682. /* Encode private key. */
  30683. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30684. /* Put private value into space provided. */
  30685. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30686. privKey, privKeyLen);
  30687. if (pubKey != NULL) {
  30688. /* Put public value into space provided. */
  30689. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30690. pubKey, pubKeyLen);
  30691. }
  30692. }
  30693. if (ret == 0) {
  30694. /* Return size of encoding. */
  30695. ret = sz;
  30696. }
  30697. FREE_ASNSETDATA(dataASN, NULL);
  30698. #endif
  30699. return ret;
  30700. }
  30701. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30702. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30703. /* Write a Private ED25519 key, including public to DER format,
  30704. * length on success else < 0 */
  30705. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30706. {
  30707. if (key == NULL) {
  30708. return BAD_FUNC_ARG;
  30709. }
  30710. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30711. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30712. }
  30713. /* Write only private ED25519 key to DER format,
  30714. * length on success else < 0 */
  30715. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30716. {
  30717. if (key == NULL) {
  30718. return BAD_FUNC_ARG;
  30719. }
  30720. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30721. NULL, 0, output, inLen, ED25519k);
  30722. }
  30723. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30724. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30725. /* Write only private Curve25519 key to DER format,
  30726. * length on success else < 0 */
  30727. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30728. {
  30729. int ret;
  30730. byte privKey[CURVE25519_KEYSIZE];
  30731. word32 privKeyLen = CURVE25519_KEYSIZE;
  30732. if (key == NULL) {
  30733. return BAD_FUNC_ARG;
  30734. }
  30735. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30736. if (ret == 0) {
  30737. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30738. X25519k);
  30739. }
  30740. return ret;
  30741. }
  30742. /* Write a public Curve25519 key to DER format,
  30743. * length on success else < 0 */
  30744. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30745. int withAlg)
  30746. {
  30747. int ret;
  30748. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30749. word32 pubKeyLen = (word32)sizeof(pubKey);
  30750. if (key == NULL || output == NULL) {
  30751. return BAD_FUNC_ARG;
  30752. }
  30753. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30754. if (ret == 0) {
  30755. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30756. X25519k, withAlg);
  30757. }
  30758. return ret;
  30759. }
  30760. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30761. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30762. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30763. ed448_key* key, word32 inSz)
  30764. {
  30765. int ret;
  30766. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30767. word32 privKeyLen = (word32)sizeof(privKey);
  30768. word32 pubKeyLen = (word32)sizeof(pubKey);
  30769. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30770. return BAD_FUNC_ARG;
  30771. }
  30772. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30773. pubKey, &pubKeyLen, ED448k);
  30774. if (ret == 0) {
  30775. if (pubKeyLen == 0) {
  30776. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30777. }
  30778. else {
  30779. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30780. pubKey, pubKeyLen, key);
  30781. }
  30782. }
  30783. return ret;
  30784. }
  30785. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30786. ed448_key* key, word32 inSz)
  30787. {
  30788. int ret;
  30789. byte pubKey[2 * ED448_PUB_KEY_SIZE + 1];
  30790. word32 pubKeyLen = (word32)sizeof(pubKey);
  30791. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30792. return BAD_FUNC_ARG;
  30793. }
  30794. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30795. pubKey, &pubKeyLen, ED448k);
  30796. if (ret == 0) {
  30797. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30798. }
  30799. return ret;
  30800. }
  30801. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30802. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30803. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30804. curve448_key* key, word32 inSz)
  30805. {
  30806. int ret;
  30807. byte privKey[CURVE448_KEY_SIZE];
  30808. word32 privKeyLen = CURVE448_KEY_SIZE;
  30809. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30810. return BAD_FUNC_ARG;
  30811. }
  30812. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30813. NULL, NULL, X448k);
  30814. if (ret == 0) {
  30815. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30816. }
  30817. return ret;
  30818. }
  30819. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30820. curve448_key* key, word32 inSz)
  30821. {
  30822. int ret;
  30823. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30824. word32 pubKeyLen = (word32)sizeof(pubKey);
  30825. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30826. return BAD_FUNC_ARG;
  30827. }
  30828. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30829. pubKey, &pubKeyLen, X448k);
  30830. if (ret == 0) {
  30831. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30832. }
  30833. return ret;
  30834. }
  30835. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30836. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30837. /* Write a Private ecc key, including public to DER format,
  30838. * length on success else < 0 */
  30839. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30840. {
  30841. if (key == NULL) {
  30842. return BAD_FUNC_ARG;
  30843. }
  30844. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30845. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30846. }
  30847. /* Write only private ecc key to DER format,
  30848. * length on success else < 0 */
  30849. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30850. {
  30851. if (key == NULL) {
  30852. return BAD_FUNC_ARG;
  30853. }
  30854. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30855. NULL, 0, output, inLen, ED448k);
  30856. }
  30857. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30858. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30859. /* Write private Curve448 key to DER format,
  30860. * length on success else < 0 */
  30861. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30862. {
  30863. int ret;
  30864. byte privKey[CURVE448_KEY_SIZE];
  30865. word32 privKeyLen = CURVE448_KEY_SIZE;
  30866. if (key == NULL) {
  30867. return BAD_FUNC_ARG;
  30868. }
  30869. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30870. if (ret == 0) {
  30871. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30872. X448k);
  30873. }
  30874. return ret;
  30875. }
  30876. /* Write a public Curve448 key to DER format,
  30877. * length on success else < 0 */
  30878. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30879. int withAlg)
  30880. {
  30881. int ret;
  30882. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30883. word32 pubKeyLen = (word32)sizeof(pubKey);
  30884. if (key == NULL || output == NULL) {
  30885. return BAD_FUNC_ARG;
  30886. }
  30887. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30888. if (ret == 0) {
  30889. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30890. X448k, withAlg);
  30891. }
  30892. return ret;
  30893. }
  30894. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30895. #ifndef WOLFSSL_ASN_TEMPLATE
  30896. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30897. /* Get raw Date only, no processing, 0 on success */
  30898. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30899. byte* format, int maxIdx)
  30900. {
  30901. int ret, length;
  30902. const byte *datePtr = NULL;
  30903. WOLFSSL_ENTER("GetBasicDate");
  30904. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30905. if (ret < 0)
  30906. return ret;
  30907. XMEMCPY(date, datePtr, length);
  30908. return 0;
  30909. }
  30910. #endif /* HAVE_OCSP || HAVE_CRL */
  30911. #endif /* WOLFSSL_ASN_TEMPLATE */
  30912. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30913. #ifndef WOLFSSL_ASN_TEMPLATE
  30914. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30915. int sz)
  30916. {
  30917. word32 idx = *inOutIdx;
  30918. word32 len;
  30919. byte tag;
  30920. WOLFSSL_ENTER("GetEnumerated");
  30921. *value = 0;
  30922. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30923. return ASN_PARSE_E;
  30924. if (tag != ASN_ENUMERATED)
  30925. return ASN_PARSE_E;
  30926. if ((int)idx >= sz)
  30927. return BUFFER_E;
  30928. len = input[idx++];
  30929. if (len > 4 || (int)(len + idx) > sz)
  30930. return ASN_PARSE_E;
  30931. while (len--) {
  30932. *value = *value << 8 | input[idx++];
  30933. }
  30934. *inOutIdx = idx;
  30935. return *value;
  30936. }
  30937. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30938. #ifdef WOLFSSL_ASN_TEMPLATE
  30939. /* ASN.1 template for OCSP single response.
  30940. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30941. */
  30942. static const ASNItem singleResponseASN[] = {
  30943. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30944. /* certId */
  30945. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30946. /* hashAlgorithm */
  30947. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30948. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30949. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30950. /* issuerNameHash */
  30951. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30952. /* issuerKeyHash */
  30953. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30954. /* serialNumber */
  30955. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30956. /* certStatus - CHOICE */
  30957. /* good [0] IMPLICIT NULL */
  30958. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30959. /* revoked [1] IMPLICIT RevokedInfo */
  30960. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30961. /* revocationTime */
  30962. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30963. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30964. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30965. /* crlReason */
  30966. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30967. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30968. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30969. /* thisUpdate */
  30970. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30971. /* nextUpdate */
  30972. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30973. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30974. /* singleExtensions */
  30975. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30976. };
  30977. enum {
  30978. SINGLERESPONSEASN_IDX_SEQ = 0,
  30979. SINGLERESPONSEASN_IDX_CID_SEQ,
  30980. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30981. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30982. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30983. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30984. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30985. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30986. SINGLERESPONSEASN_IDX_CS_GOOD,
  30987. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30988. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30989. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30990. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30991. SINGLERESPONSEASN_IDX_UNKNOWN,
  30992. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30993. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30994. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30995. SINGLERESPONSEASN_IDX_EXT,
  30996. };
  30997. /* Number of items in ASN.1 template for OCSP single response. */
  30998. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30999. #endif
  31000. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  31001. int wrapperSz, OcspEntry* single)
  31002. {
  31003. #ifndef WOLFSSL_ASN_TEMPLATE
  31004. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  31005. int length;
  31006. int ret;
  31007. byte tag;
  31008. WOLFSSL_ENTER("DecodeSingleResponse");
  31009. prevIndex = idx;
  31010. /* Wrapper around the Single Response */
  31011. if (GetSequence(source, &idx, &length, size) < 0)
  31012. return ASN_PARSE_E;
  31013. /* Wrapper around the CertID */
  31014. certIdIdx = idx;
  31015. if (GetSequence(source, &idx, &length, size) < 0)
  31016. return ASN_PARSE_E;
  31017. single->rawCertId = source + certIdIdx;
  31018. /* Hash algorithm */
  31019. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  31020. if (ret < 0)
  31021. return ret;
  31022. single->hashAlgoOID = oid;
  31023. /* Save reference to the hash of CN */
  31024. ret = GetOctetString(source, &idx, &length, size);
  31025. if (ret < 0)
  31026. return ret;
  31027. if (length > (int)sizeof(single->issuerHash))
  31028. return BUFFER_E;
  31029. XMEMCPY(single->issuerHash, source + idx, length);
  31030. idx += length;
  31031. /* Save reference to the hash of the issuer public key */
  31032. ret = GetOctetString(source, &idx, &length, size);
  31033. if (ret < 0)
  31034. return ret;
  31035. if (length > (int)sizeof(single->issuerKeyHash))
  31036. return BUFFER_E;
  31037. XMEMCPY(single->issuerKeyHash, source + idx, length);
  31038. idx += length;
  31039. /* Get serial number */
  31040. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  31041. &single->status->serialSz, size) < 0)
  31042. return ASN_PARSE_E;
  31043. single->rawCertIdSize = idx - certIdIdx;
  31044. if (idx >= size)
  31045. return BUFFER_E;
  31046. /* CertStatus */
  31047. switch (source[idx++])
  31048. {
  31049. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  31050. single->status->status = CERT_GOOD;
  31051. idx++;
  31052. break;
  31053. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  31054. single->status->status = CERT_REVOKED;
  31055. if (GetLength(source, &idx, &length, size) < 0)
  31056. return ASN_PARSE_E;
  31057. idx += length;
  31058. break;
  31059. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  31060. single->status->status = CERT_UNKNOWN;
  31061. idx++;
  31062. break;
  31063. default:
  31064. return ASN_PARSE_E;
  31065. }
  31066. if (idx >= size)
  31067. return BUFFER_E;
  31068. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  31069. single->status->thisDateAsn = source + idx;
  31070. localIdx = 0;
  31071. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  31072. (byte*)&single->status->thisDateParsed.type,
  31073. &single->status->thisDateParsed.length, size - idx) < 0)
  31074. return ASN_PARSE_E;
  31075. if (idx + localIdx >= size)
  31076. return BUFFER_E;
  31077. XMEMCPY(single->status->thisDateParsed.data,
  31078. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  31079. single->status->thisDateParsed.length);
  31080. #endif
  31081. if (GetBasicDate(source, &idx, single->status->thisDate,
  31082. &single->status->thisDateFormat, size) < 0)
  31083. return ASN_PARSE_E;
  31084. #ifndef NO_ASN_TIME_CHECK
  31085. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  31086. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  31087. return ASN_BEFORE_DATE_E;
  31088. #endif
  31089. #endif
  31090. /* The following items are optional. Only check for them if there is more
  31091. * unprocessed data in the singleResponse wrapper. */
  31092. localIdx = idx;
  31093. if (((int)(idx - prevIndex) < wrapperSz) &&
  31094. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31095. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  31096. {
  31097. idx++;
  31098. if (GetLength(source, &idx, &length, size) < 0)
  31099. return ASN_PARSE_E;
  31100. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  31101. single->status->nextDateAsn = source + idx;
  31102. localIdx = 0;
  31103. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  31104. (byte*)&single->status->nextDateParsed.type,
  31105. &single->status->nextDateParsed.length, size - idx) < 0)
  31106. return ASN_PARSE_E;
  31107. if (idx + localIdx >= size)
  31108. return BUFFER_E;
  31109. XMEMCPY(single->status->nextDateParsed.data,
  31110. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  31111. single->status->nextDateParsed.length);
  31112. #endif
  31113. if (GetBasicDate(source, &idx, single->status->nextDate,
  31114. &single->status->nextDateFormat, size) < 0)
  31115. return ASN_PARSE_E;
  31116. #ifndef NO_ASN_TIME_CHECK
  31117. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  31118. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  31119. return ASN_AFTER_DATE_E;
  31120. #endif
  31121. #endif
  31122. }
  31123. /* Skip the optional extensions in singleResponse. */
  31124. localIdx = idx;
  31125. if (((int)(idx - prevIndex) < wrapperSz) &&
  31126. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31127. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  31128. {
  31129. idx++;
  31130. if (GetLength(source, &idx, &length, size) < 0)
  31131. return ASN_PARSE_E;
  31132. idx += length;
  31133. }
  31134. *ioIndex = idx;
  31135. return 0;
  31136. #else
  31137. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  31138. int ret = 0;
  31139. word32 ocspDigestSize = OCSP_DIGEST_SIZE;
  31140. CertStatus* cs = NULL;
  31141. word32 serialSz;
  31142. word32 issuerHashLen;
  31143. word32 issuerKeyHashLen;
  31144. word32 thisDateLen;
  31145. word32 nextDateLen;
  31146. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  31147. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  31148. WOLFSSL_ASN1_TIME *at;
  31149. #endif
  31150. (void)wrapperSz;
  31151. WOLFSSL_ENTER("DecodeSingleResponse");
  31152. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  31153. if (ret == 0) {
  31154. /* Certificate Status field. */
  31155. cs = single->status;
  31156. /* Set maximum lengths for data. */
  31157. issuerHashLen = OCSP_DIGEST_SIZE;
  31158. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  31159. serialSz = EXTERNAL_SERIAL_SIZE;
  31160. thisDateLen = MAX_DATE_SIZE;
  31161. nextDateLen = MAX_DATE_SIZE;
  31162. /* Set OID type, buffers to hold data and variables to hold size. */
  31163. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  31164. oidHashType);
  31165. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  31166. single->issuerHash, &issuerHashLen);
  31167. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  31168. single->issuerKeyHash, &issuerKeyHashLen);
  31169. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  31170. &serialSz);
  31171. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  31172. cs->thisDate, &thisDateLen);
  31173. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  31174. cs->nextDate, &nextDateLen);
  31175. /* TODO: decode revoked time and reason. */
  31176. /* Decode OCSP single response. */
  31177. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  31178. 1, source, ioIndex, size);
  31179. }
  31180. if (ret == 0) {
  31181. single->hashAlgoOID =
  31182. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  31183. ocspDigestSize = (word32)wc_HashGetDigestSize(
  31184. wc_OidGetHash((int)single->hashAlgoOID));
  31185. }
  31186. /* Validate the issuer hash length is the size required. */
  31187. if ((ret == 0) && (issuerHashLen != ocspDigestSize)) {
  31188. ret = ASN_PARSE_E;
  31189. }
  31190. /* Validate the issuer key hash length is the size required. */
  31191. if (ret == 0) {
  31192. if (issuerKeyHashLen != ocspDigestSize) {
  31193. ret = ASN_PARSE_E;
  31194. }
  31195. }
  31196. if (ret == 0) {
  31197. /* Store serial size. */
  31198. cs->serialSz = (int)serialSz;
  31199. /* Set the hash algorithm OID */
  31200. single->hashAlgoOID =
  31201. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  31202. /* Determine status by which item was found. */
  31203. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  31204. cs->status = CERT_GOOD;
  31205. }
  31206. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  31207. cs->status = CERT_REVOKED;
  31208. }
  31209. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  31210. cs->status = CERT_UNKNOWN;
  31211. }
  31212. /* Store the thisDate format - only one possible. */
  31213. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  31214. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  31215. /* Check date is a valid string and BEFORE now. */
  31216. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  31217. ret = ASN_BEFORE_DATE_E;
  31218. }
  31219. }
  31220. if (ret == 0) {
  31221. #endif
  31222. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  31223. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  31224. /* Store ASN.1 version of thisDate. */
  31225. cs->thisDateAsn = GetASNItem_Addr(
  31226. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  31227. at = &cs->thisDateParsed;
  31228. at->type = ASN_GENERALIZED_TIME;
  31229. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  31230. at->length = (int)thisDateLen;
  31231. #endif
  31232. }
  31233. if ((ret == 0) &&
  31234. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  31235. /* Store the nextDate format - only one possible. */
  31236. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  31237. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  31238. /* Check date is a valid string and AFTER now. */
  31239. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  31240. ret = ASN_AFTER_DATE_E;
  31241. }
  31242. }
  31243. if ((ret == 0) &&
  31244. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  31245. #endif
  31246. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  31247. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  31248. /* Store ASN.1 version of thisDate. */
  31249. cs->nextDateAsn = GetASNItem_Addr(
  31250. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  31251. at = &cs->nextDateParsed;
  31252. at->type = ASN_GENERALIZED_TIME;
  31253. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  31254. at->length = (int)nextDateLen;
  31255. #endif
  31256. }
  31257. if (ret == 0) {
  31258. /* OcspEntry now used. */
  31259. single->used = 1;
  31260. }
  31261. FREE_ASNGETDATA(dataASN, NULL);
  31262. return ret;
  31263. #endif
  31264. }
  31265. #ifdef WOLFSSL_ASN_TEMPLATE
  31266. /* ASN.1 template for OCSP response extension header.
  31267. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31268. */
  31269. static const ASNItem respExtHdrASN[] = {
  31270. /* responseExtensions */
  31271. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  31272. /* extensions */
  31273. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31274. };
  31275. enum {
  31276. RESPEXTHDRASN_IDX_EXT = 0,
  31277. RESPEXTHDRASN_IDX_EXT_SEQ,
  31278. };
  31279. /* Number of items in ASN.1 template for OCSP response extension header. */
  31280. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  31281. #endif
  31282. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  31283. OcspResponse* resp, word32 sz)
  31284. {
  31285. #ifndef WOLFSSL_ASN_TEMPLATE
  31286. word32 idx = *ioIndex;
  31287. int length;
  31288. int ext_bound; /* boundary index for the sequence of extensions */
  31289. word32 oid;
  31290. int ret;
  31291. byte tag;
  31292. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  31293. if ((idx + 1) > sz)
  31294. return BUFFER_E;
  31295. if (GetASNTag(source, &idx, &tag, sz) < 0)
  31296. return ASN_PARSE_E;
  31297. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  31298. return ASN_PARSE_E;
  31299. if (GetLength(source, &idx, &length, sz) < 0)
  31300. return ASN_PARSE_E;
  31301. if (GetSequence(source, &idx, &length, sz) < 0)
  31302. return ASN_PARSE_E;
  31303. ext_bound = idx + length;
  31304. while (idx < (word32)ext_bound) {
  31305. word32 localIdx;
  31306. if (GetSequence(source, &idx, &length, sz) < 0) {
  31307. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  31308. return ASN_PARSE_E;
  31309. }
  31310. oid = 0;
  31311. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  31312. WOLFSSL_MSG("\tfail: OBJECT ID");
  31313. return ASN_PARSE_E;
  31314. }
  31315. /* check for critical flag */
  31316. if ((idx + 1) > (word32)sz) {
  31317. WOLFSSL_MSG("\tfail: malformed buffer");
  31318. return BUFFER_E;
  31319. }
  31320. localIdx = idx;
  31321. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  31322. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  31323. ret = GetBoolean(source, &idx, sz);
  31324. if (ret < 0)
  31325. return ret;
  31326. }
  31327. ret = GetOctetString(source, &idx, &length, sz);
  31328. if (ret < 0)
  31329. return ret;
  31330. if (oid == OCSP_NONCE_OID) {
  31331. /* get data inside extra OCTET_STRING */
  31332. ret = GetOctetString(source, &idx, &length, sz);
  31333. if (ret < 0)
  31334. return ret;
  31335. resp->nonce = source + idx;
  31336. resp->nonceSz = length;
  31337. }
  31338. idx += length;
  31339. }
  31340. *ioIndex = idx;
  31341. return 0;
  31342. #else
  31343. /* certExtASN_Length is greater than respExtHdrASN_Length */
  31344. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  31345. int ret = 0;
  31346. word32 idx = *ioIndex;
  31347. word32 maxIdx = 0;
  31348. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  31349. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  31350. if (ret == 0) {
  31351. /* Check for header and move past. */
  31352. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  31353. source, &idx, sz);
  31354. }
  31355. if (ret == 0) {
  31356. /* Keep end extensions index for total length check. */
  31357. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  31358. }
  31359. /* Step through all extensions. */
  31360. while ((ret == 0) && (idx < maxIdx)) {
  31361. /* Clear dynamic data, set OID type to expect. */
  31362. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  31363. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  31364. /* TODO: check criticality. */
  31365. /* Decode OCSP response extension. */
  31366. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  31367. source, &idx, sz);
  31368. if (ret == 0) {
  31369. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  31370. int length = (int)dataASN[CERTEXTASN_IDX_VAL].length;
  31371. if (oid == OCSP_NONCE_OID) {
  31372. /* Extract nonce data. */
  31373. ret = GetOctetString(source, &idx, &length, sz);
  31374. if (ret >= 0) {
  31375. ret = 0;
  31376. /* get data inside extra OCTET_STRING */
  31377. resp->nonce = source + idx;
  31378. resp->nonceSz = length;
  31379. }
  31380. }
  31381. /* Ignore all other extension types. */
  31382. /* Skip over rest of extension. */
  31383. idx += (word32)length;
  31384. }
  31385. }
  31386. /* Return index after extensions. */
  31387. *ioIndex = idx;
  31388. FREE_ASNGETDATA(dataASN, resp->heap);
  31389. return ret;
  31390. #endif
  31391. }
  31392. #ifdef WOLFSSL_ASN_TEMPLATE
  31393. /* ASN.1 template for OCSP ResponseData.
  31394. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31395. */
  31396. static const ASNItem ocspRespDataASN[] = {
  31397. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31398. /* version DEFAULT v1 */
  31399. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31400. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  31401. /* byName */
  31402. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  31403. /* byKey */
  31404. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  31405. /* producedAt */
  31406. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  31407. /* responses */
  31408. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  31409. /* responseExtensions */
  31410. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  31411. };
  31412. enum {
  31413. OCSPRESPDATAASN_IDX_SEQ = 0,
  31414. OCSPRESPDATAASN_IDX_VER_PRESENT,
  31415. OCSPRESPDATAASN_IDX_VER,
  31416. OCSPRESPDATAASN_IDX_BYNAME,
  31417. OCSPRESPDATAASN_IDX_BYKEY,
  31418. OCSPRESPDATAASN_IDX_PA,
  31419. OCSPRESPDATAASN_IDX_RESP,
  31420. OCSPRESPDATAASN_IDX_RESPEXT,
  31421. };
  31422. /* Number of items in ASN.1 template for OCSP ResponseData. */
  31423. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  31424. #endif
  31425. static int DecodeResponseData(byte* source, word32* ioIndex,
  31426. OcspResponse* resp, word32 size)
  31427. {
  31428. #ifndef WOLFSSL_ASN_TEMPLATE
  31429. word32 idx = *ioIndex, prev_idx, localIdx;
  31430. int length;
  31431. int version;
  31432. int ret;
  31433. byte tag;
  31434. int wrapperSz;
  31435. OcspEntry* single;
  31436. WOLFSSL_ENTER("DecodeResponseData");
  31437. resp->response = source + idx;
  31438. prev_idx = idx;
  31439. if (GetSequence(source, &idx, &length, size) < 0)
  31440. return ASN_PARSE_E;
  31441. resp->responseSz = length + idx - prev_idx;
  31442. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  31443. * item isn't an EXPLICIT[0], then set version to zero and move
  31444. * onto the next item.
  31445. */
  31446. localIdx = idx;
  31447. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31448. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  31449. {
  31450. idx += 2; /* Eat the value and length */
  31451. if (GetMyVersion(source, &idx, &version, size) < 0)
  31452. return ASN_PARSE_E;
  31453. } else
  31454. version = 0;
  31455. localIdx = idx;
  31456. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31457. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  31458. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  31459. {
  31460. idx++; /* advance past ASN tag */
  31461. if (GetLength(source, &idx, &length, size) < 0)
  31462. return ASN_PARSE_E;
  31463. idx += length;
  31464. }
  31465. else
  31466. return ASN_PARSE_E;
  31467. /* save pointer to the producedAt time */
  31468. if (GetBasicDate(source, &idx, resp->producedDate,
  31469. &resp->producedDateFormat, size) < 0)
  31470. return ASN_PARSE_E;
  31471. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  31472. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  31473. return ASN_PARSE_E;
  31474. localIdx = idx;
  31475. single = resp->single;
  31476. while (idx - localIdx < (word32)wrapperSz) {
  31477. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  31478. if (ret < 0)
  31479. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31480. if (idx - localIdx < (word32)wrapperSz) {
  31481. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  31482. DYNAMIC_TYPE_OCSP_ENTRY);
  31483. if (single->next == NULL) {
  31484. return MEMORY_E;
  31485. }
  31486. XMEMSET(single->next, 0, sizeof(OcspEntry));
  31487. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  31488. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31489. if (single->next->status == NULL) {
  31490. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31491. single->next = NULL;
  31492. return MEMORY_E;
  31493. }
  31494. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  31495. single->next->isDynamic = 1;
  31496. single = single->next;
  31497. }
  31498. }
  31499. /*
  31500. * Check the length of the ResponseData against the current index to
  31501. * see if there are extensions, they are optional.
  31502. */
  31503. if (idx - prev_idx < resp->responseSz)
  31504. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  31505. return ASN_PARSE_E;
  31506. *ioIndex = idx;
  31507. return 0;
  31508. #else
  31509. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  31510. int ret = 0;
  31511. byte version;
  31512. word32 dateSz, idx = *ioIndex;
  31513. OcspEntry* single = NULL;
  31514. WOLFSSL_ENTER("DecodeResponseData");
  31515. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  31516. if (ret == 0) {
  31517. resp->response = source + idx;
  31518. /* Default, not present, is v1 = 0. */
  31519. version = 0;
  31520. /* Max size of date supported. */
  31521. dateSz = MAX_DATE_SIZE;
  31522. /* Set the where to put version an produced date. */
  31523. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  31524. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  31525. &dateSz);
  31526. /* Decode the ResponseData. */
  31527. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  31528. 1, source, ioIndex, size);
  31529. }
  31530. /* Only support v1 == 0 */
  31531. if (ret == 0) {
  31532. if (version != 0) {
  31533. ret = ASN_PARSE_E;
  31534. }
  31535. }
  31536. /* Ensure date is a minimal size. */
  31537. if (ret == 0) {
  31538. if (dateSz < MIN_DATE_SIZE) {
  31539. ret = ASN_PARSE_E;
  31540. }
  31541. }
  31542. if (ret == 0) {
  31543. /* TODO: use byName/byKey fields. */
  31544. /* Store size of response. */
  31545. resp->responseSz = *ioIndex - idx;
  31546. /* Store date format/tag. */
  31547. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  31548. /* Get the index of the responses SEQUENCE. */
  31549. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  31550. /* Start with the pre-existing OcspEntry. */
  31551. single = resp->single;
  31552. }
  31553. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  31554. /* Allocate and use a new OCSP entry if this is used. */
  31555. if (single->used) {
  31556. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  31557. DYNAMIC_TYPE_OCSP_ENTRY);
  31558. if (single->next == NULL) {
  31559. ret = MEMORY_E;
  31560. }
  31561. else {
  31562. XMEMSET(single->next, 0, sizeof(OcspEntry));
  31563. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  31564. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31565. if (single->next->status == NULL) {
  31566. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31567. single->next = NULL;
  31568. ret = MEMORY_E;
  31569. }
  31570. else {
  31571. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  31572. /* Entry to be freed. */
  31573. single->next->isDynamic = 1;
  31574. /* used will be 0 (false) */
  31575. single = single->next;
  31576. }
  31577. }
  31578. }
  31579. if (ret == 0) {
  31580. /* Decode SingleResponse into OcspEntry. */
  31581. ret = DecodeSingleResponse(source, &idx,
  31582. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  31583. (int)dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  31584. /* single->used set on successful decode. */
  31585. }
  31586. }
  31587. /* Check if there were extensions. */
  31588. if ((ret == 0) &&
  31589. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  31590. /* Get index of [1] */
  31591. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  31592. /* Decode the response extensions. */
  31593. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  31594. ret = ASN_PARSE_E;
  31595. }
  31596. }
  31597. FREE_ASNGETDATA(dataASN, resp->heap);
  31598. return ret;
  31599. #endif
  31600. }
  31601. #ifndef WOLFSSL_ASN_TEMPLATE
  31602. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31603. static int DecodeCerts(byte* source,
  31604. word32* ioIndex, OcspResponse* resp, word32 size)
  31605. {
  31606. word32 idx = *ioIndex;
  31607. byte tag;
  31608. WOLFSSL_ENTER("DecodeCerts");
  31609. if (GetASNTag(source, &idx, &tag, size) < 0)
  31610. return ASN_PARSE_E;
  31611. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  31612. {
  31613. int length;
  31614. if (GetLength(source, &idx, &length, size) < 0)
  31615. return ASN_PARSE_E;
  31616. if (GetSequence(source, &idx, &length, size) < 0)
  31617. return ASN_PARSE_E;
  31618. resp->cert = source + idx;
  31619. resp->certSz = length;
  31620. idx += length;
  31621. }
  31622. *ioIndex = idx;
  31623. return 0;
  31624. }
  31625. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31626. #endif /* !WOLFSSL_ASN_TEMPLATE */
  31627. #ifdef WOLFSSL_ASN_TEMPLATE
  31628. /* ASN.1 template for BasicOCSPResponse.
  31629. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31630. */
  31631. static const ASNItem ocspBasicRespASN[] = {
  31632. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31633. /* tbsResponseData */
  31634. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  31635. /* signatureAlgorithm */
  31636. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  31637. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  31638. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  31639. /* parameters */
  31640. #ifdef WC_RSA_PSS
  31641. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  31642. #endif
  31643. /* signature */
  31644. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  31645. /* certs */
  31646. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31647. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  31648. };
  31649. enum {
  31650. OCSPBASICRESPASN_IDX_SEQ = 0,
  31651. OCSPBASICRESPASN_IDX_TBS_SEQ,
  31652. OCSPBASICRESPASN_IDX_SIGALGO,
  31653. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  31654. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  31655. #ifdef WC_RSA_PSS
  31656. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  31657. #endif
  31658. OCSPBASICRESPASN_IDX_SIGNATURE,
  31659. OCSPBASICRESPASN_IDX_CERTS,
  31660. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  31661. };
  31662. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  31663. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  31664. #endif /* WOLFSSL_ASN_TEMPLATE */
  31665. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  31666. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  31667. {
  31668. #ifndef WOLFSSL_ASN_TEMPLATE
  31669. int length;
  31670. word32 idx = *ioIndex;
  31671. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31672. word32 end_index;
  31673. #endif
  31674. int ret;
  31675. int sigLength;
  31676. const byte* sigParams = NULL;
  31677. word32 sigParamsSz = 0;
  31678. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31679. (void)heap;
  31680. if (GetSequence(source, &idx, &length, size) < 0)
  31681. return ASN_PARSE_E;
  31682. if (idx + length > size)
  31683. return ASN_INPUT_E;
  31684. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31685. end_index = idx + length;
  31686. #endif
  31687. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  31688. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31689. /* Get the signature algorithm */
  31690. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  31691. return ASN_PARSE_E;
  31692. }
  31693. #ifdef WC_RSA_PSS
  31694. else if (resp->sigOID == CTC_RSASSAPSS) {
  31695. word32 sz;
  31696. int len;
  31697. const byte* params;
  31698. sz = idx;
  31699. params = source + idx;
  31700. if (GetSequence(source, &idx, &len, size) < 0)
  31701. ret = ASN_PARSE_E;
  31702. if (ret == 0) {
  31703. idx += len;
  31704. sigParams = params;
  31705. sigParamsSz = idx - sz;
  31706. }
  31707. }
  31708. #endif
  31709. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31710. if (ret != 0)
  31711. return ret;
  31712. resp->sigSz = sigLength;
  31713. resp->sig = source + idx;
  31714. idx += sigLength;
  31715. /*
  31716. * Check the length of the BasicOcspResponse against the current index to
  31717. * see if there are certificates, they are optional.
  31718. */
  31719. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31720. if (idx < end_index)
  31721. {
  31722. int cert_inited = 0;
  31723. #ifdef WOLFSSL_SMALL_STACK
  31724. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31725. DYNAMIC_TYPE_TMP_BUFFER);
  31726. if (cert == NULL)
  31727. return MEMORY_E;
  31728. #else
  31729. DecodedCert cert[1];
  31730. #endif
  31731. do {
  31732. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31733. ret = ASN_PARSE_E;
  31734. break;
  31735. }
  31736. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31737. cert_inited = 1;
  31738. /* Don't verify if we don't have access to Cert Manager. */
  31739. ret = ParseCertRelative(cert, CERT_TYPE,
  31740. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31741. cm);
  31742. if (ret < 0) {
  31743. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31744. break;
  31745. }
  31746. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31747. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31748. if (XMEMCMP(cert->subjectHash,
  31749. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31750. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31751. }
  31752. else {
  31753. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31754. #ifdef OPENSSL_EXTRA
  31755. resp->verifyError = OCSP_BAD_ISSUER;
  31756. #else
  31757. ret = BAD_OCSP_RESPONDER;
  31758. break;
  31759. #endif
  31760. }
  31761. }
  31762. #endif
  31763. /* ConfirmSignature is blocking here */
  31764. ret = ConfirmSignature(
  31765. &cert->sigCtx,
  31766. resp->response, resp->responseSz,
  31767. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31768. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31769. NULL);
  31770. if (ret != 0) {
  31771. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31772. ret = ASN_OCSP_CONFIRM_E;
  31773. break;
  31774. }
  31775. } while(0);
  31776. if (cert_inited)
  31777. FreeDecodedCert(cert);
  31778. #ifdef WOLFSSL_SMALL_STACK
  31779. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31780. #endif
  31781. if (ret != 0)
  31782. return ret;
  31783. }
  31784. else
  31785. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31786. {
  31787. Signer* ca;
  31788. int sigValid = -1;
  31789. #ifndef NO_SKID
  31790. ca = GetCA(cm, resp->single->issuerKeyHash);
  31791. #else
  31792. ca = GetCA(cm, resp->single->issuerHash);
  31793. #endif
  31794. if (ca) {
  31795. SignatureCtx sigCtx;
  31796. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31797. /* ConfirmSignature is blocking here */
  31798. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31799. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31800. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31801. NULL);
  31802. }
  31803. if (ca == NULL || sigValid != 0) {
  31804. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31805. return ASN_OCSP_CONFIRM_E;
  31806. }
  31807. (void)noVerify;
  31808. }
  31809. *ioIndex = idx;
  31810. return 0;
  31811. #else
  31812. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31813. int ret = 0;
  31814. word32 idx = *ioIndex;
  31815. const byte* sigParams = NULL;
  31816. word32 sigParamsSz = 0;
  31817. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31818. #ifdef WOLFSSL_SMALL_STACK
  31819. DecodedCert* cert = NULL;
  31820. #else
  31821. DecodedCert cert[1];
  31822. #endif
  31823. int certInit = 0;
  31824. #endif
  31825. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31826. (void)heap;
  31827. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31828. if (ret == 0) {
  31829. /* Set expecting signature OID. */
  31830. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31831. /* Decode BasicOCSPResponse. */
  31832. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31833. 1, source, &idx, size);
  31834. }
  31835. if (ret == 0) {
  31836. word32 dataIdx = 0;
  31837. /* Decode the response data. */
  31838. if (DecodeResponseData(
  31839. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31840. &dataIdx, resp,
  31841. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31842. ) < 0) {
  31843. ret = ASN_PARSE_E;
  31844. }
  31845. }
  31846. #ifdef WC_RSA_PSS
  31847. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31848. sigParams = GetASNItem_Addr(
  31849. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31850. source);
  31851. sigParamsSz =
  31852. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31853. source);
  31854. }
  31855. #endif
  31856. if (ret == 0) {
  31857. /* Get the signature OID and signature. */
  31858. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31859. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31860. &resp->sigSz);
  31861. }
  31862. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31863. if ((ret == 0) &&
  31864. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31865. /* TODO: support more than one certificate. */
  31866. /* Store reference to certificate BER data. */
  31867. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31868. &resp->certSz);
  31869. /* Allocate a certificate object to decode cert into. */
  31870. #ifdef WOLFSSL_SMALL_STACK
  31871. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31872. DYNAMIC_TYPE_TMP_BUFFER);
  31873. if (cert == NULL) {
  31874. ret = MEMORY_E;
  31875. }
  31876. }
  31877. if ((ret == 0) &&
  31878. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31879. #endif
  31880. /* Initialize the certificate object. */
  31881. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31882. certInit = 1;
  31883. /* Parse the certificate and don't verify if we don't have access to
  31884. * Cert Manager. */
  31885. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31886. cm);
  31887. if (ret < 0) {
  31888. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31889. }
  31890. }
  31891. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31892. if ((ret == 0) &&
  31893. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL) &&
  31894. !noVerify) {
  31895. ret = CheckOcspResponder(resp, cert, cm);
  31896. }
  31897. #endif /* WOLFSSL_NO_OCSP_ISSUER_CHECK */
  31898. if ((ret == 0) &&
  31899. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31900. /* TODO: ConfirmSignature is blocking here */
  31901. /* Check the signature of the response. */
  31902. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31903. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31904. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31905. if (ret != 0) {
  31906. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31907. ret = ASN_OCSP_CONFIRM_E;
  31908. }
  31909. }
  31910. if ((ret == 0) &&
  31911. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31912. #else
  31913. if (ret == 0)
  31914. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31915. {
  31916. Signer* ca;
  31917. int sigValid = -1;
  31918. /* Response didn't have a certificate - lookup CA. */
  31919. #ifndef NO_SKID
  31920. ca = GetCA(cm, resp->single->issuerKeyHash);
  31921. #else
  31922. ca = GetCA(cm, resp->single->issuerHash);
  31923. #endif
  31924. if (ca) {
  31925. SignatureCtx sigCtx;
  31926. /* Initialize he signature context. */
  31927. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31928. /* TODO: ConfirmSignature is blocking here */
  31929. /* Check the signature of the response CA public key. */
  31930. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31931. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31932. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31933. NULL);
  31934. }
  31935. if ((ca == NULL) || (sigValid != 0)) {
  31936. /* Didn't find certificate or signature verificate failed. */
  31937. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31938. ret = ASN_OCSP_CONFIRM_E;
  31939. }
  31940. }
  31941. if (ret == 0) {
  31942. /* Update the position to after response data. */
  31943. *ioIndex = idx;
  31944. }
  31945. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31946. if (certInit) {
  31947. FreeDecodedCert(cert);
  31948. }
  31949. #ifdef WOLFSSL_SMALL_STACK
  31950. if (cert != NULL) {
  31951. /* Dispose of certificate object. */
  31952. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31953. }
  31954. #endif
  31955. #endif
  31956. FREE_ASNGETDATA(dataASN, heap);
  31957. return ret;
  31958. #endif /* WOLFSSL_ASN_TEMPLATE */
  31959. }
  31960. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31961. byte* source, word32 inSz, void* heap)
  31962. {
  31963. WOLFSSL_ENTER("InitOcspResponse");
  31964. XMEMSET(status, 0, sizeof(CertStatus));
  31965. XMEMSET(single, 0, sizeof(OcspEntry));
  31966. XMEMSET(resp, 0, sizeof(OcspResponse));
  31967. single->status = status;
  31968. resp->responseStatus = -1;
  31969. resp->single = single;
  31970. resp->source = source;
  31971. resp->maxIdx = inSz;
  31972. resp->heap = heap;
  31973. }
  31974. void FreeOcspResponse(OcspResponse* resp)
  31975. {
  31976. OcspEntry *single, *next;
  31977. if (resp != NULL) {
  31978. for (single = resp->single; single; single = next) {
  31979. next = single->next;
  31980. if (single->isDynamic) {
  31981. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31982. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31983. }
  31984. }
  31985. }
  31986. }
  31987. #ifdef WOLFSSL_ASN_TEMPLATE
  31988. /* ASN.1 template for OCSPResponse.
  31989. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31990. */
  31991. static const ASNItem ocspResponseASN[] = {
  31992. /* OCSPResponse ::= SEQUENCE */
  31993. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31994. /* responseStatus OCSPResponseStatus */
  31995. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31996. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31997. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31998. /* ResponseBytes ::= SEQUENCE */
  31999. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32000. /* responseType OBJECT IDENTIFIER */
  32001. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32002. /* response OCTET STRING */
  32003. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  32004. };
  32005. enum {
  32006. OCSPRESPONSEASN_IDX_SEQ = 0,
  32007. OCSPRESPONSEASN_IDX_STATUS,
  32008. OCSPRESPONSEASN_IDX_BYTES,
  32009. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  32010. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  32011. OCSPRESPONSEASN_IDX_BYTES_VAL,
  32012. };
  32013. /* Number of items in ASN.1 template for OCSPResponse. */
  32014. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  32015. #endif /* WOLFSSL_ASN_TEMPLATE */
  32016. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  32017. {
  32018. #ifndef WOLFSSL_ASN_TEMPLATE
  32019. int ret;
  32020. int length = 0;
  32021. word32 idx = 0;
  32022. byte* source = resp->source;
  32023. word32 size = resp->maxIdx;
  32024. word32 oid;
  32025. byte tag;
  32026. WOLFSSL_ENTER("OcspResponseDecode");
  32027. /* peel the outer SEQUENCE wrapper */
  32028. if (GetSequence(source, &idx, &length, size) < 0) {
  32029. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32030. return ASN_PARSE_E;
  32031. }
  32032. /* First get the responseStatus, an ENUMERATED */
  32033. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  32034. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32035. return ASN_PARSE_E;
  32036. }
  32037. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  32038. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  32039. return 0;
  32040. }
  32041. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  32042. if (idx >= size) {
  32043. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32044. return ASN_PARSE_E;
  32045. }
  32046. if (GetASNTag(source, &idx, &tag, size) < 0) {
  32047. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32048. return ASN_PARSE_E;
  32049. }
  32050. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  32051. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32052. return ASN_PARSE_E;
  32053. }
  32054. if (GetLength(source, &idx, &length, size) < 0) {
  32055. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32056. return ASN_PARSE_E;
  32057. }
  32058. /* Get the responseBytes SEQUENCE */
  32059. if (GetSequence(source, &idx, &length, size) < 0) {
  32060. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32061. return ASN_PARSE_E;
  32062. }
  32063. /* Check ObjectID for the resposeBytes */
  32064. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  32065. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32066. return ASN_PARSE_E;
  32067. }
  32068. if (oid != OCSP_BASIC_OID) {
  32069. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  32070. return ASN_PARSE_E;
  32071. }
  32072. ret = GetOctetString(source, &idx, &length, size);
  32073. if (ret < 0) {
  32074. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  32075. return ret;
  32076. }
  32077. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  32078. if (ret < 0) {
  32079. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  32080. return ret;
  32081. }
  32082. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  32083. return 0;
  32084. #else
  32085. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  32086. int ret = 0;
  32087. word32 idx = 0, size = resp->maxIdx;
  32088. byte* source = resp->source;
  32089. byte status;
  32090. byte* basic;
  32091. word32 basicSz;
  32092. WOLFSSL_ENTER("OcspResponseDecode");
  32093. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  32094. if (ret == 0) {
  32095. /* Set variable to put status in and expect OCSP OID. */
  32096. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  32097. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  32098. /* Decode OCSPResponse (and ResponseBytes). */
  32099. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  32100. source, &idx, size);
  32101. }
  32102. if (ret == 0) {
  32103. /* Get response. */
  32104. resp->responseStatus = status;
  32105. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  32106. == OCSP_BASIC_OID) {
  32107. /* Get reference to BasicOCSPResponse. */
  32108. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  32109. &basicSz);
  32110. idx = 0;
  32111. /* Decode BasicOCSPResponse. */
  32112. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  32113. noVerify);
  32114. }
  32115. /* Only support BasicOCSPResponse. */
  32116. else {
  32117. ret = ASN_PARSE_E;
  32118. }
  32119. }
  32120. FREE_ASNGETDATA(dataASN, resp->heap);
  32121. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  32122. return ret;
  32123. #endif /* WOLFSSL_ASN_TEMPLATE */
  32124. }
  32125. #ifdef WOLFSSL_ASN_TEMPLATE
  32126. /* ASN.1 template for OCSP nonce extension.
  32127. * RFC 6960, 4.4.1 - Nonce
  32128. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  32129. */
  32130. static const ASNItem ocspNonceExtASN[] = {
  32131. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32132. /* Extension */
  32133. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32134. /* extnId */
  32135. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  32136. /* critical not encoded. */
  32137. /* extnValue */
  32138. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  32139. /* nonce */
  32140. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  32141. };
  32142. enum {
  32143. OCSPNONCEEXTASN_IDX_SEQ = 0,
  32144. OCSPNONCEEXTASN_IDX_EXT,
  32145. OCSPNONCEEXTASN_IDX_EXT_OID,
  32146. OCSPNONCEEXTASN_IDX_EXT_VAL,
  32147. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  32148. };
  32149. /* Number of items in ASN.1 template for OCSP nonce extension. */
  32150. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  32151. #endif /* WOLFSSL_ASN_TEMPLATE */
  32152. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  32153. {
  32154. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  32155. 0x30, 0x01, 0x02 };
  32156. #ifndef WOLFSSL_ASN_TEMPLATE
  32157. byte seqArray[5][MAX_SEQ_SZ];
  32158. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  32159. WOLFSSL_ENTER("SetOcspReqExtensions");
  32160. if (!req || !output || !req->nonceSz)
  32161. return 0;
  32162. totalSz += req->nonceSz;
  32163. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  32164. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  32165. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  32166. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  32167. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  32168. if (totalSz > size)
  32169. return 0;
  32170. totalSz = 0;
  32171. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  32172. totalSz += seqSz[4];
  32173. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  32174. totalSz += seqSz[3];
  32175. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  32176. totalSz += seqSz[2];
  32177. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  32178. totalSz += (word32)sizeof(NonceObjId);
  32179. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  32180. totalSz += seqSz[1];
  32181. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  32182. totalSz += seqSz[0];
  32183. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  32184. totalSz += req->nonceSz;
  32185. return totalSz;
  32186. #else
  32187. int ret = 0;
  32188. WOLFSSL_ENTER("SetOcspReqExtensions");
  32189. /* Check request has nonce to write in extension. */
  32190. if (req != NULL && req->nonceSz != 0) {
  32191. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  32192. int sz;
  32193. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  32194. /* Set nonce extension OID and nonce. */
  32195. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  32196. sizeof(NonceObjId));
  32197. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  32198. (word32)req->nonceSz);
  32199. /* Calculate size of nonce extension. */
  32200. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  32201. &sz);
  32202. /* Check buffer big enough for encoding if supplied. */
  32203. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  32204. ret = BUFFER_E;
  32205. }
  32206. if ((ret == 0) && (output != NULL)) {
  32207. /* Encode nonce extension. */
  32208. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  32209. output);
  32210. }
  32211. if (ret == 0) {
  32212. /* Return size of encoding. */
  32213. ret = sz;
  32214. }
  32215. FREE_ASNSETDATA(dataASN, req->heap);
  32216. }
  32217. return (word32)ret;
  32218. #endif /* WOLFSSL_ASN_TEMPLATE */
  32219. }
  32220. #ifdef WOLFSSL_ASN_TEMPLATE
  32221. /* ASN.1 template for OCSPRequest.
  32222. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  32223. */
  32224. static const ASNItem ocspRequestASN[] = {
  32225. /* OCSPRequest */
  32226. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32227. /* tbsRequest */
  32228. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32229. /* version not written - v1 */
  32230. /* requestorName not written */
  32231. /* requestList */
  32232. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32233. /* Request */
  32234. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  32235. /* reqCert */
  32236. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  32237. /* hashAlgorithm */
  32238. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  32239. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  32240. /* issuerNameHash */
  32241. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  32242. /* issuerKeyHash */
  32243. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  32244. /* serialNumber */
  32245. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  32246. /* requestExtensions */
  32247. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  32248. /* optionalSignature not written. */
  32249. };
  32250. enum {
  32251. OCSPREQUESTASN_IDX_SEQ = 0,
  32252. OCSPREQUESTASN_IDX_TBS,
  32253. OCSPREQUESTASN_IDX_TBS_SEQ,
  32254. OCSPREQUESTASN_IDX_TBS_LIST,
  32255. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  32256. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  32257. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  32258. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  32259. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  32260. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  32261. OCSPREQUESTASN_IDX_TBS_REQEXT,
  32262. };
  32263. /* Number of items in ASN.1 template for OCSPRequest. */
  32264. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  32265. #endif
  32266. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  32267. {
  32268. #ifndef WOLFSSL_ASN_TEMPLATE
  32269. byte seqArray[5][MAX_SEQ_SZ];
  32270. /* The ASN.1 of the OCSP Request is an onion of sequences */
  32271. byte algoArray[MAX_ALGO_SZ];
  32272. byte issuerArray[MAX_ENCODED_DIG_SZ];
  32273. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  32274. byte snArray[MAX_SN_SZ];
  32275. byte extArray[MAX_OCSP_EXT_SZ];
  32276. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  32277. int i, snSz;
  32278. int keyIdSz;
  32279. WOLFSSL_ENTER("EncodeOcspRequest");
  32280. #ifdef NO_SHA
  32281. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  32282. keyIdSz = WC_SHA256_DIGEST_SIZE;
  32283. #else
  32284. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  32285. keyIdSz = WC_SHA_DIGEST_SIZE;
  32286. #endif
  32287. issuerSz = SetDigest(req->issuerHash, keyIdSz, issuerArray);
  32288. issuerKeySz = SetDigest(req->issuerKeyHash, keyIdSz, issuerKeyArray);
  32289. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  32290. MAX_SN_SZ, MAX_SN_SZ);
  32291. extSz = 0;
  32292. if (snSz < 0)
  32293. return snSz;
  32294. if (req->nonceSz) {
  32295. /* TLS Extensions use this function too - put extensions after
  32296. * ASN.1: Context Specific [2].
  32297. */
  32298. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  32299. OCSP_NONCE_EXT_SZ);
  32300. extSz += SetExplicit(2, extSz, extArray);
  32301. }
  32302. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  32303. for (i = 4; i >= 0; i--) {
  32304. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  32305. totalSz += seqSz[i];
  32306. if (i == 2) totalSz += extSz;
  32307. }
  32308. if (output == NULL)
  32309. return totalSz;
  32310. if (totalSz > size)
  32311. return BUFFER_E;
  32312. totalSz = 0;
  32313. for (i = 0; i < 5; i++) {
  32314. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  32315. totalSz += seqSz[i];
  32316. }
  32317. XMEMCPY(output + totalSz, algoArray, algoSz);
  32318. totalSz += algoSz;
  32319. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  32320. totalSz += issuerSz;
  32321. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  32322. totalSz += issuerKeySz;
  32323. XMEMCPY(output + totalSz, snArray, snSz);
  32324. totalSz += snSz;
  32325. if (extSz != 0) {
  32326. XMEMCPY(output + totalSz, extArray, extSz);
  32327. totalSz += extSz;
  32328. }
  32329. return totalSz;
  32330. #else
  32331. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  32332. word32 extSz = 0;
  32333. int sz = 0;
  32334. int ret = 0;
  32335. word32 keyIdSz;
  32336. WOLFSSL_ENTER("EncodeOcspRequest");
  32337. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  32338. if (ret == 0) {
  32339. /* Set OID of hash algorithm use on issuer and key. */
  32340. #ifdef NO_SHA
  32341. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  32342. oidHashType);
  32343. keyIdSz = WC_SHA256_DIGEST_SIZE;
  32344. #else
  32345. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  32346. oidHashType);
  32347. keyIdSz = WC_SHA_DIGEST_SIZE;
  32348. #endif
  32349. /* Set issuer, issuer key hash and serial number of certificate being
  32350. * checked. */
  32351. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  32352. req->issuerHash, keyIdSz);
  32353. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  32354. req->issuerKeyHash, keyIdSz);
  32355. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  32356. req->serial, (word32)req->serialSz);
  32357. /* Only extension to write is nonce - check if one to encode. */
  32358. if (req->nonceSz) {
  32359. /* Get size of extensions and leave space for them in encoding. */
  32360. ret = (int)(extSz = EncodeOcspRequestExtensions(req, NULL, 0));
  32361. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  32362. if (ret > 0) {
  32363. ret = 0;
  32364. }
  32365. }
  32366. else {
  32367. /* Don't write out extensions. */
  32368. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  32369. }
  32370. }
  32371. if (ret == 0) {
  32372. /* Calculate size of encoding. */
  32373. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  32374. &sz);
  32375. }
  32376. /* Check buffer big enough for encoding if supplied. */
  32377. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  32378. ret = BUFFER_E;
  32379. }
  32380. if ((ret == 0) && (output != NULL)) {
  32381. /* Encode OCSPRequest. */
  32382. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  32383. if (req->nonceSz) {
  32384. /* Encode extensions into space provided. */
  32385. ret = (int)EncodeOcspRequestExtensions(req,
  32386. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  32387. extSz);
  32388. if (ret > 0) {
  32389. ret = 0;
  32390. }
  32391. }
  32392. }
  32393. if (ret == 0) {
  32394. /* Return size of encoding. */
  32395. ret = sz;
  32396. }
  32397. FREE_ASNSETDATA(dataASN, req->heap);
  32398. return ret;
  32399. #endif /* WOLFSSL_ASN_TEMPLATE */
  32400. }
  32401. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  32402. void* heap)
  32403. {
  32404. int ret;
  32405. WOLFSSL_ENTER("InitOcspRequest");
  32406. if (req == NULL)
  32407. return BAD_FUNC_ARG;
  32408. XMEMSET(req, 0, sizeof(OcspRequest));
  32409. req->heap = heap;
  32410. if (cert) {
  32411. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  32412. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  32413. req->serial = (byte*)XMALLOC((size_t)cert->serialSz, req->heap,
  32414. DYNAMIC_TYPE_OCSP_REQUEST);
  32415. if (req->serial == NULL)
  32416. return MEMORY_E;
  32417. XMEMCPY(req->serial, cert->serial, (size_t)cert->serialSz);
  32418. req->serialSz = cert->serialSz;
  32419. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  32420. req->url = (byte*)XMALLOC((size_t)cert->extAuthInfoSz + 1,
  32421. req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32422. if (req->url == NULL) {
  32423. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  32424. req->serial = NULL;
  32425. return MEMORY_E;
  32426. }
  32427. XMEMCPY(req->url, cert->extAuthInfo, (size_t)cert->extAuthInfoSz);
  32428. req->urlSz = cert->extAuthInfoSz;
  32429. req->url[req->urlSz] = 0;
  32430. }
  32431. }
  32432. if (useNonce) {
  32433. WC_RNG rng;
  32434. #ifndef HAVE_FIPS
  32435. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  32436. #else
  32437. ret = wc_InitRng(&rng);
  32438. #endif
  32439. if (ret != 0) {
  32440. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  32441. } else {
  32442. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  32443. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  32444. else
  32445. req->nonceSz = MAX_OCSP_NONCE_SZ;
  32446. wc_FreeRng(&rng);
  32447. }
  32448. }
  32449. return 0;
  32450. }
  32451. void FreeOcspRequest(OcspRequest* req)
  32452. {
  32453. WOLFSSL_ENTER("FreeOcspRequest");
  32454. if (req) {
  32455. if (req->serial)
  32456. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32457. req->serial = NULL;
  32458. #ifdef OPENSSL_EXTRA
  32459. if (req->serialInt) {
  32460. if (req->serialInt->isDynamic) {
  32461. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  32462. }
  32463. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  32464. }
  32465. req->serialInt = NULL;
  32466. #endif
  32467. if (req->url)
  32468. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32469. req->url = NULL;
  32470. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  32471. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_APACHE_HTTPD) || \
  32472. defined(HAVE_LIGHTY)
  32473. if (req->cid != NULL)
  32474. wolfSSL_OCSP_CERTID_free((WOLFSSL_OCSP_CERTID*)req->cid);
  32475. req->cid = NULL;
  32476. #endif
  32477. }
  32478. }
  32479. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  32480. {
  32481. int cmp = -1; /* default as not matching, cmp gets set on each check */
  32482. int ocspDigestSize;
  32483. OcspEntry *single, *next, *prev = NULL, *top;
  32484. WOLFSSL_ENTER("CompareOcspReqResp");
  32485. if (req == NULL) {
  32486. WOLFSSL_MSG("\tReq missing");
  32487. return -1;
  32488. }
  32489. if (resp == NULL || resp->single == NULL) {
  32490. WOLFSSL_MSG("\tResp missing");
  32491. return 1;
  32492. }
  32493. /* Nonces are not critical. The responder may not necessarily add
  32494. * the nonce to the response. */
  32495. if (req->nonceSz && resp->nonce != NULL
  32496. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  32497. && resp->nonceSz != 0
  32498. #endif
  32499. ) {
  32500. cmp = req->nonceSz - resp->nonceSz;
  32501. if (cmp != 0) {
  32502. WOLFSSL_MSG("\tnonceSz mismatch");
  32503. return cmp;
  32504. }
  32505. cmp = XMEMCMP(req->nonce, resp->nonce, (size_t)req->nonceSz);
  32506. if (cmp != 0) {
  32507. WOLFSSL_MSG("\tnonce mismatch");
  32508. return cmp;
  32509. }
  32510. }
  32511. /* match based on found status and return */
  32512. for (single = resp->single; single; single = next) {
  32513. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  32514. ocspDigestSize = wc_HashGetDigestSize(
  32515. wc_OidGetHash(single->hashAlgoOID));
  32516. #else
  32517. ocspDigestSize = OCSP_DIGEST_SIZE;
  32518. #endif
  32519. cmp = req->serialSz - single->status->serialSz;
  32520. if (cmp == 0) {
  32521. cmp = XMEMCMP(req->serial, single->status->serial,
  32522. (size_t)req->serialSz)
  32523. || XMEMCMP(req->issuerHash, single->issuerHash,
  32524. (size_t)ocspDigestSize)
  32525. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash,
  32526. (size_t)ocspDigestSize);
  32527. if (cmp == 0) {
  32528. /* match found */
  32529. if (resp->single != single && prev) {
  32530. /* move to top of list */
  32531. top = resp->single;
  32532. resp->single = single;
  32533. prev->next = single->next;
  32534. single->next = top;
  32535. }
  32536. break;
  32537. }
  32538. }
  32539. next = single->next;
  32540. prev = single;
  32541. }
  32542. if (cmp != 0) {
  32543. WOLFSSL_MSG("\trequest and response mismatch");
  32544. return cmp;
  32545. }
  32546. return 0;
  32547. }
  32548. #endif /* HAVE_OCSP */
  32549. #ifdef WOLFSSL_ASN_TEMPLATE
  32550. /* ASN.1 template for certificate name hash. */
  32551. static const ASNItem nameHashASN[] = {
  32552. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  32553. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  32554. };
  32555. enum {
  32556. NAMEHASHASN_IDX_OID = 0,
  32557. NAMEHASHASN_IDX_NAME
  32558. };
  32559. /* Number of items in ASN.1 template for certificate name hash. */
  32560. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  32561. #endif /* WOLFSSL_ASN_TEMPLATE */
  32562. /* store WC_SHA hash of NAME */
  32563. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  32564. {
  32565. /* Use summy signature OID. */
  32566. return GetNameHash_ex(source, idx, hash, maxIdx, 0);
  32567. }
  32568. /* store WC_SHA hash of NAME */
  32569. int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx,
  32570. word32 sigOID)
  32571. {
  32572. #ifndef WOLFSSL_ASN_TEMPLATE
  32573. int length; /* length of all distinguished names */
  32574. int ret;
  32575. word32 dummy;
  32576. byte tag;
  32577. WOLFSSL_ENTER("GetNameHash");
  32578. dummy = *idx;
  32579. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  32580. tag == ASN_OBJECT_ID) {
  32581. WOLFSSL_MSG("Trying optional prefix...");
  32582. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  32583. return ASN_PARSE_E;
  32584. *idx += (word32)length;
  32585. WOLFSSL_MSG("Got optional prefix");
  32586. }
  32587. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  32588. * calculated over the entire DER encoding of the Name field, including
  32589. * the tag and length. */
  32590. dummy = *idx;
  32591. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  32592. return ASN_PARSE_E;
  32593. ret = CalcHashId_ex(source + dummy, (word32)length + *idx - dummy, hash,
  32594. HashIdAlg(sigOID));
  32595. *idx += (word32)length;
  32596. return ret;
  32597. #else
  32598. ASNGetData dataASN[nameHashASN_Length];
  32599. int ret;
  32600. XMEMSET(dataASN, 0, sizeof(dataASN));
  32601. /* Ignore the OID even when present. */
  32602. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  32603. /* Decode certificate name. */
  32604. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  32605. (word32)maxIdx);
  32606. if (ret == 0) {
  32607. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  32608. * calculated over the entire DER encoding of the Name field, including
  32609. * the tag and length. */
  32610. /* Calculate hash of complete name including SEQUENCE. */
  32611. ret = CalcHashId_ex(
  32612. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  32613. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  32614. hash, HashIdAlg(sigOID));
  32615. }
  32616. return ret;
  32617. #endif /* WOLFSSL_ASN_TEMPLATE */
  32618. }
  32619. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  32620. #ifdef OPENSSL_EXTRA
  32621. static char* GetNameFromDer(const byte* source, int sz)
  32622. {
  32623. char* out;
  32624. out = (char*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_OPENSSL);
  32625. if (out == NULL) {
  32626. WOLFSSL_MSG("Name malloc failed");
  32627. return NULL;
  32628. }
  32629. XMEMCPY(out, source, (size_t)sz);
  32630. return out;
  32631. }
  32632. #endif
  32633. /* initialize decoded CRL */
  32634. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  32635. {
  32636. WOLFSSL_MSG("InitDecodedCRL");
  32637. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  32638. dcrl->heap = heap;
  32639. #ifdef WOLFSSL_HEAP_TEST
  32640. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  32641. #endif
  32642. }
  32643. /* free decoded CRL resources */
  32644. void FreeDecodedCRL(DecodedCRL* dcrl)
  32645. {
  32646. RevokedCert* tmp = dcrl->certs;
  32647. WOLFSSL_MSG("FreeDecodedCRL");
  32648. while(tmp) {
  32649. RevokedCert* next = tmp->next;
  32650. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32651. tmp = next;
  32652. }
  32653. #ifdef OPENSSL_EXTRA
  32654. if (dcrl->issuer != NULL)
  32655. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  32656. #endif
  32657. }
  32658. #ifdef WOLFSSL_ASN_TEMPLATE
  32659. /* ASN.1 template for revoked certificates.
  32660. * X.509: RFC 5280, 5.1 - CRL Fields
  32661. */
  32662. static const ASNItem revokedASN[] = {
  32663. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32664. /* userCertificate CertificateSerialNumber */
  32665. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  32666. /* revocationDate Time */
  32667. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  32668. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32669. /* crlEntryExensions Extensions */
  32670. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  32671. };
  32672. enum {
  32673. REVOKEDASN_IDX_SEQ = 0,
  32674. REVOKEDASN_IDX_CERT,
  32675. REVOKEDASN_IDX_TIME_UTC,
  32676. REVOKEDASN_IDX_TIME_GT,
  32677. REVOKEDASN_IDX_TIME_EXT,
  32678. };
  32679. /* Number of items in ASN.1 template for revoked certificates. */
  32680. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  32681. #endif
  32682. /* Get Revoked Cert list, 0 on success */
  32683. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  32684. DecodedCRL* dcrl, word32 maxIdx)
  32685. {
  32686. #ifndef WOLFSSL_ASN_TEMPLATE
  32687. int ret;
  32688. int len;
  32689. word32 end;
  32690. RevokedCert* rc;
  32691. #ifdef CRL_STATIC_REVOKED_LIST
  32692. int totalCerts = 0;
  32693. #endif
  32694. WOLFSSL_ENTER("GetRevoked");
  32695. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  32696. return ASN_PARSE_E;
  32697. end = *idx + len;
  32698. #ifdef CRL_STATIC_REVOKED_LIST
  32699. totalCerts = dcrl->totalCerts;
  32700. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32701. return MEMORY_E;
  32702. }
  32703. rc = &rcert[totalCerts];
  32704. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32705. if (ret < 0) {
  32706. WOLFSSL_MSG("wc_GetSerialNumber error");
  32707. return ret;
  32708. }
  32709. #else
  32710. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32711. DYNAMIC_TYPE_REVOKED);
  32712. if (rc == NULL) {
  32713. WOLFSSL_MSG("Alloc Revoked Cert failed");
  32714. return MEMORY_E;
  32715. }
  32716. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32717. if (ret < 0) {
  32718. WOLFSSL_MSG("wc_GetSerialNumber error");
  32719. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32720. return ret;
  32721. }
  32722. /* add to list */
  32723. rc->next = dcrl->certs;
  32724. dcrl->certs = rc;
  32725. (void)rcert;
  32726. #endif /* CRL_STATIC_REVOKED_LIST */
  32727. dcrl->totalCerts++;
  32728. /* get date */
  32729. #ifndef NO_ASN_TIME
  32730. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  32731. if (ret < 0) {
  32732. WOLFSSL_MSG("Expecting Date");
  32733. return ret;
  32734. }
  32735. #endif
  32736. /* skip extensions */
  32737. *idx = end;
  32738. return 0;
  32739. #else
  32740. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32741. int ret = 0;
  32742. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32743. word32 revDateSz = MAX_DATE_SIZE;
  32744. RevokedCert* rc;
  32745. #ifdef CRL_STATIC_REVOKED_LIST
  32746. int totalCerts = dcrl->totalCerts;
  32747. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32748. return MEMORY_E;
  32749. }
  32750. rc = &rcert[totalCerts];
  32751. #else
  32752. /* Allocate a new revoked certificate object. */
  32753. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32754. DYNAMIC_TYPE_CRL);
  32755. if (rc == NULL) {
  32756. ret = MEMORY_E;
  32757. }
  32758. #endif /* CRL_STATIC_REVOKED_LIST */
  32759. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32760. if (ret == 0) {
  32761. /* Set buffer to place serial number into. */
  32762. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32763. &serialSz);
  32764. /* Set buffer to store revocation date. */
  32765. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32766. &revDateSz);
  32767. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32768. &revDateSz);
  32769. /* Decode the Revoked */
  32770. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32771. maxIdx);
  32772. }
  32773. if (ret == 0) {
  32774. /* Store size of serial number. */
  32775. rc->serialSz = (int)serialSz;
  32776. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32777. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32778. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32779. /* TODO: use extensions, only v2 */
  32780. /* Add revoked certificate to chain. */
  32781. #ifndef CRL_STATIC_REVOKED_LIST
  32782. rc->next = dcrl->certs;
  32783. dcrl->certs = rc;
  32784. #endif
  32785. dcrl->totalCerts++;
  32786. }
  32787. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32788. #ifndef CRL_STATIC_REVOKED_LIST
  32789. if ((ret != 0) && (rc != NULL)) {
  32790. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32791. }
  32792. (void)rcert;
  32793. #endif
  32794. return ret;
  32795. #endif /* WOLFSSL_ASN_TEMPLATE */
  32796. }
  32797. #ifdef WOLFSSL_ASN_TEMPLATE
  32798. /* Parse the revoked certificates of a CRL.
  32799. *
  32800. * @param [in] dcrl Decoded CRL object.
  32801. * @param [in] buff Buffer holding CRL.
  32802. * @param [in] idx Index into buffer of revoked certificates.
  32803. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32804. * @return 0 on success.
  32805. * @return ASN_PARSE_E on failure.
  32806. */
  32807. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32808. const byte* buff, word32 idx, word32 maxIdx)
  32809. {
  32810. int ret = 0;
  32811. /* Parse each revoked certificate. */
  32812. while ((ret == 0) && (idx < maxIdx)) {
  32813. /* Parse a revoked certificate. */
  32814. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32815. ret = ASN_PARSE_E;
  32816. }
  32817. }
  32818. return ret;
  32819. }
  32820. #endif /* WOLFSSL_ASN_TEMPLATE */
  32821. #ifndef WOLFSSL_ASN_TEMPLATE
  32822. /* Get CRL Signature, 0 on success */
  32823. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32824. int maxIdx)
  32825. {
  32826. int length;
  32827. int ret;
  32828. WOLFSSL_ENTER("GetCRL_Signature");
  32829. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32830. if (ret != 0)
  32831. return ret;
  32832. dcrl->sigLength = length;
  32833. dcrl->signature = (byte*)&source[*idx];
  32834. *idx += dcrl->sigLength;
  32835. return 0;
  32836. }
  32837. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32838. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32839. word32 tbsSz, const byte* signature, word32 sigSz,
  32840. word32 signatureOID, Signer *ca, void* heap)
  32841. {
  32842. /* try to confirm/verify signature */
  32843. #ifndef IGNORE_KEY_EXTENSIONS
  32844. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32845. WOLFSSL_MSG("CA cannot sign CRLs");
  32846. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32847. return ASN_CRL_NO_SIGNER_E;
  32848. }
  32849. #endif /* IGNORE_KEY_EXTENSIONS */
  32850. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32851. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32852. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32853. signatureOID, NULL, 0, NULL) != 0) {
  32854. WOLFSSL_MSG("CRL Confirm signature failed");
  32855. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32856. return ASN_CRL_CONFIRM_E;
  32857. }
  32858. return 0;
  32859. }
  32860. #ifdef WOLFSSL_ASN_TEMPLATE
  32861. /* Find the signer for the CRL and verify the signature.
  32862. *
  32863. * @param [in] dcrl Decoded CRL object.
  32864. * @param [in] buff Buffer holding CRL.
  32865. * @param [in] cm Certificate manager object.
  32866. * @return 0 on success.
  32867. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32868. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32869. */
  32870. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32871. {
  32872. int ret = 0;
  32873. Signer* ca = NULL;
  32874. SignatureCtx sigCtx;
  32875. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32876. * If experiencing issues uncomment NO_SKID define in CRL section of
  32877. * wolfssl/wolfcrypt/settings.h */
  32878. #ifndef NO_SKID
  32879. if (dcrl->extAuthKeyIdSet) {
  32880. /* more unique than issuerHash */
  32881. ca = GetCA(cm, dcrl->extAuthKeyId);
  32882. }
  32883. /* Check issuerHash matched CA's subjectNameHash. */
  32884. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32885. KEYID_SIZE) != 0)) {
  32886. ca = NULL;
  32887. }
  32888. if (ca == NULL) {
  32889. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32890. /* If AKID is available then this CA doesn't have the public
  32891. * key required */
  32892. if (ca && dcrl->extAuthKeyIdSet) {
  32893. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32894. ca = NULL;
  32895. }
  32896. }
  32897. #else
  32898. ca = GetCA(cm, dcrl->issuerHash);
  32899. #endif /* !NO_SKID */
  32900. WOLFSSL_MSG("About to verify CRL signature");
  32901. if (ca == NULL) {
  32902. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32903. ret = ASN_CRL_NO_SIGNER_E;
  32904. WOLFSSL_ERROR_VERBOSE(ret);
  32905. }
  32906. if (ret == 0) {
  32907. WOLFSSL_MSG("Found CRL issuer CA");
  32908. /* Verify CRL signature with CA. */
  32909. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32910. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32911. dcrl->signatureOID, ca, dcrl->heap);
  32912. }
  32913. return ret;
  32914. }
  32915. #endif
  32916. #ifndef WOLFSSL_ASN_TEMPLATE
  32917. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32918. const byte* buf,word32* inOutIdx, int sz, int verify)
  32919. {
  32920. word32 oid, dateIdx, idx, checkIdx;
  32921. int length;
  32922. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32923. int doNextDate = 1;
  32924. #endif
  32925. byte tag;
  32926. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32927. return BAD_FUNC_ARG;
  32928. }
  32929. /* may have version */
  32930. idx = *inOutIdx;
  32931. checkIdx = idx;
  32932. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32933. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32934. return ASN_PARSE_E;
  32935. dcrl->version++;
  32936. }
  32937. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32938. return ASN_PARSE_E;
  32939. checkIdx = idx;
  32940. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32941. return ASN_PARSE_E;
  32942. }
  32943. #ifdef OPENSSL_EXTRA
  32944. dcrl->issuerSz = length + (checkIdx - idx);
  32945. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32946. #endif
  32947. if (GetNameHash_ex(buf, &idx, dcrl->issuerHash, sz, oid) < 0)
  32948. return ASN_PARSE_E;
  32949. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32950. return ASN_PARSE_E;
  32951. dateIdx = idx;
  32952. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32953. {
  32954. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32955. (void)dateIdx;
  32956. return ASN_PARSE_E;
  32957. #else
  32958. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32959. doNextDate = 0;
  32960. idx = dateIdx;
  32961. #endif
  32962. }
  32963. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32964. if (doNextDate)
  32965. #endif
  32966. {
  32967. #ifndef NO_ASN_TIME
  32968. if (verify != NO_VERIFY &&
  32969. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32970. WOLFSSL_MSG("CRL after date is no longer valid");
  32971. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32972. return CRL_CERT_DATE_ERR;
  32973. }
  32974. #else
  32975. (void)verify;
  32976. #endif
  32977. }
  32978. checkIdx = idx;
  32979. if (idx != dcrl->sigIndex &&
  32980. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32981. int len;
  32982. if (GetSequence(buf, &idx, &len, sz) < 0)
  32983. return ASN_PARSE_E;
  32984. len += idx;
  32985. while (idx < (word32)len) {
  32986. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32987. return ASN_PARSE_E;
  32988. }
  32989. }
  32990. *inOutIdx = idx;
  32991. return 0;
  32992. }
  32993. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32994. #ifndef NO_SKID
  32995. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32996. {
  32997. #ifndef WOLFSSL_ASN_TEMPLATE
  32998. word32 idx = 0;
  32999. int length = 0, ret = 0;
  33000. byte tag;
  33001. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  33002. if (GetSequence(input, &idx, &length, sz) < 0) {
  33003. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  33004. return ASN_PARSE_E;
  33005. }
  33006. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  33007. return ASN_PARSE_E;
  33008. }
  33009. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  33010. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  33011. return 0;
  33012. }
  33013. if (GetLength(input, &idx, &length, sz) <= 0) {
  33014. WOLFSSL_MSG("\tfail: extension data length");
  33015. return ASN_PARSE_E;
  33016. }
  33017. dcrl->extAuthKeyIdSet = 1;
  33018. /* Get the hash or hash of the hash if wrong size. */
  33019. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId,
  33020. HashIdAlg(dcrl->signatureOID));
  33021. return ret;
  33022. #else
  33023. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  33024. int ret = 0;
  33025. word32 idx = 0;
  33026. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  33027. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  33028. if (ret == 0) {
  33029. /* Parse an authority key identifier. */
  33030. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  33031. &idx, (word32)sz);
  33032. }
  33033. if (ret == 0) {
  33034. /* Key id is optional. */
  33035. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  33036. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  33037. }
  33038. else {
  33039. /* Get the hash or hash of the hash if wrong size. */
  33040. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  33041. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  33042. dcrl->extAuthKeyId, HashIdAlg(dcrl->signatureOID));
  33043. }
  33044. }
  33045. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33046. return ret;
  33047. #endif /* WOLFSSL_ASN_TEMPLATE */
  33048. }
  33049. #endif
  33050. #ifndef WOLFSSL_ASN_TEMPLATE
  33051. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  33052. word32* inOutIdx, word32 sz)
  33053. {
  33054. int length;
  33055. word32 idx;
  33056. word32 ext_bound; /* boundary index for the sequence of extensions */
  33057. word32 oid;
  33058. byte tag;
  33059. WOLFSSL_ENTER("ParseCRL_Extensions");
  33060. (void)dcrl;
  33061. if (inOutIdx == NULL)
  33062. return BAD_FUNC_ARG;
  33063. idx = *inOutIdx;
  33064. /* CRL Extensions are optional */
  33065. if ((idx + 1) > sz)
  33066. return 0;
  33067. /* CRL Extensions are optional */
  33068. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  33069. return 0;
  33070. /* CRL Extensions are optional */
  33071. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  33072. return 0;
  33073. if (GetLength(buf, &idx, &length, sz) < 0)
  33074. return ASN_PARSE_E;
  33075. if (GetSequence(buf, &idx, &length, sz) < 0)
  33076. return ASN_PARSE_E;
  33077. ext_bound = idx + length;
  33078. while (idx < (word32)ext_bound) {
  33079. word32 localIdx;
  33080. int ret;
  33081. if (GetSequence(buf, &idx, &length, sz) < 0) {
  33082. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  33083. return ASN_PARSE_E;
  33084. }
  33085. oid = 0;
  33086. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  33087. WOLFSSL_MSG("\tfail: OBJECT ID");
  33088. return ASN_PARSE_E;
  33089. }
  33090. /* check for critical flag */
  33091. if ((idx + 1) > (word32)sz) {
  33092. WOLFSSL_MSG("\tfail: malformed buffer");
  33093. return BUFFER_E;
  33094. }
  33095. localIdx = idx;
  33096. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  33097. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  33098. ret = GetBoolean(buf, &idx, sz);
  33099. if (ret < 0)
  33100. return ret;
  33101. }
  33102. ret = GetOctetString(buf, &idx, &length, sz);
  33103. if (ret < 0)
  33104. return ret;
  33105. if (oid == AUTH_KEY_OID) {
  33106. #ifndef NO_SKID
  33107. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  33108. if (ret < 0) {
  33109. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  33110. return ret;
  33111. }
  33112. #endif
  33113. }
  33114. else if (oid == CRL_NUMBER_OID) {
  33115. localIdx = idx;
  33116. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  33117. tag == ASN_INTEGER) {
  33118. ret = GetASNInt(buf, &idx, &length, sz);
  33119. if (ret < 0) {
  33120. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  33121. return ret;
  33122. }
  33123. else {
  33124. if (length > 1) {
  33125. int i;
  33126. #ifdef WOLFSSL_SMALL_STACK
  33127. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  33128. DYNAMIC_TYPE_BIGINT);
  33129. if (m == NULL) {
  33130. return MEMORY_E;
  33131. }
  33132. #else
  33133. mp_int m[1];
  33134. #endif
  33135. if (mp_init(m) != MP_OKAY) {
  33136. ret = MP_INIT_E;
  33137. }
  33138. if (ret == 0)
  33139. ret = mp_read_unsigned_bin(m, buf + idx, length);
  33140. if (ret != MP_OKAY)
  33141. ret = BUFFER_E;
  33142. if (ret == 0) {
  33143. dcrl->crlNumber = 0;
  33144. for (i = 0; i < (int)(*m).used; ++i) {
  33145. if (i > (CHAR_BIT *
  33146. (int)sizeof(word32) / DIGIT_BIT)) {
  33147. break;
  33148. }
  33149. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  33150. (DIGIT_BIT * i);
  33151. }
  33152. }
  33153. mp_free(m);
  33154. #ifdef WOLFSSL_SMALL_STACK
  33155. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  33156. #endif
  33157. if (ret != 0)
  33158. return ret;
  33159. }
  33160. else if (length == 1) {
  33161. dcrl->crlNumber = buf[idx];
  33162. }
  33163. }
  33164. }
  33165. }
  33166. idx += length;
  33167. }
  33168. *inOutIdx = idx;
  33169. return 0;
  33170. }
  33171. #else
  33172. /* Parse the extensions of a CRL.
  33173. *
  33174. * @param [in] dcrl Decoded CRL object.
  33175. * @param [in] buff Buffer holding CRL.
  33176. * @param [in] idx Index into buffer of extensions.
  33177. * @param [in] maxIdx Maximum index of extension data.
  33178. * @return 0 on success.
  33179. * @return ASN_PARSE_E on failure.
  33180. */
  33181. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  33182. word32 maxIdx)
  33183. {
  33184. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  33185. int ret = 0;
  33186. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  33187. while ((ret == 0) && (idx < maxIdx)) {
  33188. byte critical = 0;
  33189. /* Clear dynamic data. */
  33190. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  33191. /* Ensure OID is an extension type. */
  33192. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  33193. /* Set criticality variable. */
  33194. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  33195. /* Parse extension wrapper. */
  33196. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  33197. maxIdx);
  33198. if (ret == 0) {
  33199. /* OID in extension. */
  33200. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  33201. /* Length of extension data. */
  33202. int length = (int)dataASN[CERTEXTASN_IDX_VAL].length;
  33203. if (oid == AUTH_KEY_OID) {
  33204. #ifndef NO_SKID
  33205. /* Parse Authority Key Id extension.
  33206. * idx is at start of OCTET_STRING data. */
  33207. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  33208. if (ret != 0) {
  33209. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  33210. }
  33211. #endif
  33212. }
  33213. /* TODO: Parse CRL Number extension */
  33214. /* TODO: check criticality */
  33215. /* Move index on to next extension. */
  33216. idx += (word32)length;
  33217. }
  33218. }
  33219. if (ret < 0) {
  33220. ret = ASN_PARSE_E;
  33221. }
  33222. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33223. return ret;
  33224. }
  33225. #endif /* !WOLFSSL_ASN_TEMPLATE */
  33226. #ifdef WOLFSSL_ASN_TEMPLATE
  33227. /* ASN.1 template for a CRL- CertificateList.
  33228. * X.509: RFC 5280, 5.1 - CRL Fields
  33229. */
  33230. static const ASNItem crlASN[] = {
  33231. /* CertificateList */
  33232. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  33233. /* tbsCertList */
  33234. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  33235. /* version Version OPTIONAL if present must be v2 */
  33236. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  33237. /* signature */
  33238. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  33239. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  33240. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  33241. /* issuer */
  33242. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  33243. /* thisUpdate */
  33244. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  33245. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  33246. /* nextUpdate */
  33247. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  33248. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  33249. /* revokedCertificates */
  33250. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  33251. /* crlExtensions */
  33252. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  33253. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  33254. /* signatureAlgorithm */
  33255. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  33256. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  33257. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  33258. /* signatureValue */
  33259. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  33260. };
  33261. enum {
  33262. CRLASN_IDX_SEQ = 0,
  33263. CRLASN_IDX_TBS,
  33264. CRLASN_IDX_TBS_VER,
  33265. CRLASN_IDX_TBS_SIGALGO,
  33266. CRLASN_IDX_TBS_SIGALGO_OID,
  33267. CRLASN_IDX_TBS_SIGALGO_NULL,
  33268. CRLASN_IDX_TBS_ISSUER,
  33269. CRLASN_IDX_TBS_THISUPDATE_UTC,
  33270. CRLASN_IDX_TBS_THISUPDATE_GT,
  33271. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  33272. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  33273. CRLASN_IDX_TBS_REVOKEDCERTS,
  33274. CRLASN_IDX_TBS_EXT,
  33275. CRLASN_IDX_TBS_EXT_SEQ,
  33276. CRLASN_IDX_SIGALGO,
  33277. CRLASN_IDX_SIGALGO_OID,
  33278. CRLASN_IDX_SIGALGO_NULL,
  33279. CRLASN_IDX_SIGNATURE,
  33280. };
  33281. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  33282. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  33283. #endif
  33284. /* parse crl buffer into decoded state, 0 on success */
  33285. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  33286. int verify, void* cm)
  33287. {
  33288. #ifndef WOLFSSL_ASN_TEMPLATE
  33289. Signer* ca = NULL;
  33290. SignatureCtx sigCtx;
  33291. int ret = 0;
  33292. int len;
  33293. word32 idx = 0;
  33294. WOLFSSL_MSG("ParseCRL");
  33295. /* raw crl hash */
  33296. /* hash here if needed for optimized comparisons
  33297. * wc_Sha sha;
  33298. * wc_InitSha(&sha);
  33299. * wc_ShaUpdate(&sha, buff, sz);
  33300. * wc_ShaFinal(&sha, dcrl->crlHash); */
  33301. if (GetSequence(buff, &idx, &len, sz) < 0)
  33302. return ASN_PARSE_E;
  33303. dcrl->certBegin = idx;
  33304. /* Normalize sz for the length inside the outer sequence. */
  33305. sz = len + idx;
  33306. if (GetSequence(buff, &idx, &len, sz) < 0)
  33307. return ASN_PARSE_E;
  33308. dcrl->sigIndex = len + idx;
  33309. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  33310. return ASN_PARSE_E;
  33311. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  33312. return ASN_PARSE_E;
  33313. idx = dcrl->sigIndex;
  33314. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  33315. return ASN_PARSE_E;
  33316. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  33317. return ASN_PARSE_E;
  33318. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  33319. if experiencing issues uncomment NO_SKID define in CRL section of
  33320. wolfssl/wolfcrypt/settings.h */
  33321. #ifndef NO_SKID
  33322. if (dcrl->extAuthKeyIdSet) {
  33323. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  33324. }
  33325. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  33326. KEYID_SIZE) != 0) {
  33327. ca = NULL;
  33328. }
  33329. if (ca == NULL) {
  33330. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  33331. /* If AKID is available then this CA doesn't have the public
  33332. * key required */
  33333. if (ca && dcrl->extAuthKeyIdSet) {
  33334. WOLFSSL_MSG("CA SKID doesn't match AKID");
  33335. ca = NULL;
  33336. }
  33337. }
  33338. #else
  33339. ca = GetCA(cm, dcrl->issuerHash);
  33340. #endif /* !NO_SKID */
  33341. WOLFSSL_MSG("About to verify CRL signature");
  33342. if (ca == NULL) {
  33343. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  33344. ret = ASN_CRL_NO_SIGNER_E;
  33345. WOLFSSL_ERROR_VERBOSE(ret);
  33346. goto end;
  33347. }
  33348. WOLFSSL_MSG("Found CRL issuer CA");
  33349. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  33350. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  33351. dcrl->signatureOID, ca, dcrl->heap);
  33352. end:
  33353. return ret;
  33354. #else
  33355. DECL_ASNGETDATA(dataASN, crlASN_Length);
  33356. int ret = 0;
  33357. /* Default version - v1 = 0 */
  33358. byte version = 0;
  33359. word32 idx = 0;
  33360. /* Size of buffer for date. */
  33361. word32 lastDateSz = MAX_DATE_SIZE;
  33362. word32 nextDateSz = MAX_DATE_SIZE;
  33363. /* When NO_ASN_TIME is defined, verify not used. */
  33364. (void)verify;
  33365. WOLFSSL_MSG("ParseCRL");
  33366. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  33367. if (ret == 0) {
  33368. /* Set variable to store version. */
  33369. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  33370. /* Set expecting signature OID. */
  33371. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  33372. /* Set buffer to put last and next date into. */
  33373. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  33374. &lastDateSz);
  33375. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  33376. &lastDateSz);
  33377. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  33378. &nextDateSz);
  33379. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  33380. &nextDateSz);
  33381. /* Set expecting signature OID. */
  33382. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  33383. /* Decode the CRL. */
  33384. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  33385. }
  33386. /* Version must be v2 = 1 if present. */
  33387. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  33388. (version != 1)) {
  33389. ret = ASN_PARSE_E;
  33390. }
  33391. /* Check minimum size of last date. */
  33392. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  33393. ret = ASN_PARSE_E;
  33394. }
  33395. /* Check minimum size of next date. */
  33396. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  33397. ret = ASN_PARSE_E;
  33398. }
  33399. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  33400. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  33401. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  33402. ret = ASN_PARSE_E;
  33403. }
  33404. if (ret == 0) {
  33405. /* Store version */
  33406. dcrl->version = ++version;
  33407. /* Store offset of to be signed part. */
  33408. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  33409. /* Store index of signature. */
  33410. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  33411. /* Store address and length of signature data. */
  33412. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  33413. &dcrl->sigLength);
  33414. /* Get the signature OID. */
  33415. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  33416. /* Get the format/tag of the last and next date. */
  33417. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  33418. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  33419. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  33420. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  33421. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  33422. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  33423. #ifndef NO_ASN_TIME
  33424. if (dcrl->nextDateFormat != 0) {
  33425. /* Next date was set, so validate it. */
  33426. if (verify != NO_VERIFY &&
  33427. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  33428. WOLFSSL_MSG("CRL after date is no longer valid");
  33429. ret = CRL_CERT_DATE_ERR;
  33430. WOLFSSL_ERROR_VERBOSE(ret);
  33431. }
  33432. }
  33433. }
  33434. if (ret == 0) {
  33435. #endif
  33436. #ifdef OPENSSL_EXTRA
  33437. /* Parse and store the issuer name. */
  33438. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  33439. buff);
  33440. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  33441. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  33442. (int)dcrl->issuerSz);
  33443. #endif
  33444. /* Calculate the Hash id from the issuer name. */
  33445. ret = CalcHashId_ex(
  33446. GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  33447. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  33448. dcrl->issuerHash, HashIdAlg(dcrl->signatureOID));
  33449. if (ret < 0) {
  33450. ret = ASN_PARSE_E;
  33451. }
  33452. }
  33453. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  33454. /* Parse revoked certificates - starting after SEQUENCE OF. */
  33455. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  33456. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  33457. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  33458. }
  33459. if (ret == 0) {
  33460. /* Parse the extensions - starting after SEQUENCE OF. */
  33461. ret = ParseCRL_Extensions(dcrl, buff,
  33462. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  33463. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  33464. }
  33465. if (ret == 0) {
  33466. /* Find signer and verify signature. */
  33467. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  33468. }
  33469. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33470. return ret;
  33471. #endif /* WOLFSSL_ASN_TEMPLATE */
  33472. }
  33473. #endif /* HAVE_CRL */
  33474. #ifdef WOLFSSL_CERT_PIV
  33475. #ifdef WOLFSSL_ASN_TEMPLATE
  33476. /* Template for PIV. */
  33477. static const ASNItem pivASN[] = {
  33478. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  33479. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  33480. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  33481. };
  33482. enum {
  33483. PIVASN_IDX_CERT = 0,
  33484. PIVASN_IDX_NONCE,
  33485. PIVASN_IDX_SIGNEDNONCE,
  33486. };
  33487. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  33488. static const ASNItem pivCertASN[] = {
  33489. /* 0x53 = 0x40 | 0x13 */
  33490. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  33491. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  33492. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  33493. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  33494. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  33495. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  33496. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  33497. };
  33498. enum {
  33499. PIVCERTASN_IDX_CERT,
  33500. PIVCERTASN_IDX_X509,
  33501. PIVCERTASN_IDX_INFO,
  33502. PIVCERTASN_IDX_ERR,
  33503. };
  33504. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  33505. #endif
  33506. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  33507. {
  33508. #ifndef WOLFSSL_ASN_TEMPLATE
  33509. int length = 0;
  33510. word32 idx = 0;
  33511. WOLFSSL_ENTER("wc_ParseCertPIV");
  33512. if (piv == NULL || buf == NULL || totalSz == 0)
  33513. return BAD_FUNC_ARG;
  33514. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  33515. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  33516. /* Certificate (0A 82 05FA) */
  33517. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  33518. /* Identiv Type PIV card */
  33519. piv->isIdentiv = 1;
  33520. piv->cert = &buf[idx];
  33521. piv->certSz = length;
  33522. idx += length;
  33523. /* Nonce (0B 14) */
  33524. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  33525. piv->nonce = &buf[idx];
  33526. piv->nonceSz = length;
  33527. idx += length;
  33528. }
  33529. /* Signed Nonce (0C 82 0100) */
  33530. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  33531. piv->signedNonce = &buf[idx];
  33532. piv->signedNonceSz = length;
  33533. }
  33534. idx = 0;
  33535. buf = piv->cert;
  33536. totalSz = piv->certSz;
  33537. }
  33538. /* Certificate Buffer Total Size (53 82 05F6) */
  33539. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  33540. &length, totalSz) < 0) {
  33541. return ASN_PARSE_E;
  33542. }
  33543. /* PIV Certificate (70 82 05ED) */
  33544. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  33545. totalSz) < 0) {
  33546. return ASN_PARSE_E;
  33547. }
  33548. /* Capture certificate buffer pointer and length */
  33549. piv->cert = &buf[idx];
  33550. piv->certSz = length;
  33551. idx += length;
  33552. /* PIV Certificate Info (71 01 00) */
  33553. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  33554. totalSz) >= 0) {
  33555. if (length >= 1) {
  33556. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  33557. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  33558. }
  33559. idx += length;
  33560. }
  33561. /* PIV Error Detection (FE 00) */
  33562. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  33563. totalSz) >= 0) {
  33564. piv->certErrDet = &buf[idx];
  33565. piv->certErrDetSz = length;
  33566. idx += length;
  33567. }
  33568. return 0;
  33569. #else
  33570. /* pivCertASN_Length is longer than pivASN_Length */
  33571. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  33572. int ret = 0;
  33573. word32 idx;
  33574. byte info;
  33575. WOLFSSL_ENTER("wc_ParseCertPIV");
  33576. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  33577. if (ret == 0) {
  33578. /* Clear dynamic data. */
  33579. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  33580. /* Start parsing from start of buffer. */
  33581. idx = 0;
  33582. /* Parse Identiv wrapper. */
  33583. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  33584. totalSz);
  33585. if (ret == 0) {
  33586. /* Identiv wrapper found. */
  33587. piv->isIdentiv = 1;
  33588. /* Get nonce reference. */
  33589. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  33590. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  33591. &piv->nonceSz);
  33592. }
  33593. /* Get signedNonce reference. */
  33594. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  33595. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  33596. &piv->signedNonce, &piv->signedNonceSz);
  33597. }
  33598. /* Get the certificate data for parsing. */
  33599. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  33600. }
  33601. ret = 0;
  33602. }
  33603. if (ret == 0) {
  33604. /* Clear dynamic data and set variable to put cert info into. */
  33605. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  33606. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  33607. /* Start parsing from start of buffer. */
  33608. idx = 0;
  33609. /* Parse PIV certificate data. */
  33610. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  33611. totalSz);
  33612. if (ret == 0) {
  33613. /* Get X.509 certificate reference. */
  33614. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  33615. &piv->certSz);
  33616. /* Set the certificate info if available. */
  33617. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  33618. /* Bits 1 and 2 are compression. */
  33619. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  33620. /* Bits 3 is X509 flag. */
  33621. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  33622. }
  33623. /* Get X.509 certificate error detection reference. */
  33624. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  33625. &piv->certErrDetSz);
  33626. }
  33627. ret = 0;
  33628. }
  33629. FREE_ASNGETDATA(dataASN, NULL);
  33630. return ret;
  33631. #endif /* WOLFSSL_ASN_TEMPLATE */
  33632. }
  33633. #endif /* WOLFSSL_CERT_PIV */
  33634. #ifdef HAVE_SMIME
  33635. /*****************************************************************************
  33636. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  33637. * and parameters into headers. Will continue until in has no more content.
  33638. *
  33639. * RETURNS:
  33640. * returns zero on success, non-zero on error.
  33641. */
  33642. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  33643. {
  33644. MimeHdr* nextHdr = NULL;
  33645. MimeHdr* curHdr = NULL;
  33646. MimeParam* nextParam = NULL;
  33647. size_t start = 0;
  33648. size_t end = 0;
  33649. char* nameAttr = NULL;
  33650. char* bodyVal = NULL;
  33651. MimeTypes mimeType = MIME_HDR;
  33652. MimeStatus mimeStatus = MIME_NAMEATTR;
  33653. int ret = -1;
  33654. size_t pos = 0;
  33655. size_t lineLen = 0;
  33656. char* curLine = NULL;
  33657. char* ptr = NULL;
  33658. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  33659. ret = BAD_FUNC_ARG;
  33660. goto error;
  33661. }
  33662. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  33663. if (nextHdr == NULL) {
  33664. ret = MEMORY_E;
  33665. goto error;
  33666. }
  33667. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33668. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33669. DYNAMIC_TYPE_PKCS7);
  33670. if (nextParam == NULL) {
  33671. ret = MEMORY_E;
  33672. goto error;
  33673. }
  33674. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33675. curLine = XSTRTOK(in, "\r\n", &ptr);
  33676. if (curLine == NULL) {
  33677. ret = ASN_PARSE_E;
  33678. goto error;
  33679. }
  33680. while (curLine != NULL) {
  33681. /* Leftover from previous line, add params to previous header. */
  33682. if (curLine[0] == ' ' && curHdr) {
  33683. mimeType = MIME_PARAM;
  33684. }
  33685. else {
  33686. mimeType = MIME_HDR;
  33687. }
  33688. start = 0;
  33689. lineLen = XSTRLEN(curLine);
  33690. if (lineLen == 0) {
  33691. ret = BAD_FUNC_ARG;
  33692. goto error;
  33693. }
  33694. for (pos = 0; pos < lineLen; pos++) {
  33695. char cur = curLine[pos];
  33696. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  33697. mimeType == MIME_HDR) || (cur == '=' &&
  33698. mimeType == MIME_PARAM)) && pos >= 1) {
  33699. mimeStatus = MIME_BODYVAL;
  33700. end = pos-1;
  33701. if (nameAttr != NULL)
  33702. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33703. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  33704. if (ret) {
  33705. goto error;
  33706. }
  33707. start = pos+1;
  33708. }
  33709. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  33710. end = pos-1;
  33711. if (bodyVal != NULL)
  33712. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33713. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33714. if (ret) {
  33715. goto error;
  33716. }
  33717. if (mimeType == MIME_HDR) {
  33718. nextHdr->name = nameAttr;
  33719. nameAttr = NULL;
  33720. nextHdr->body = bodyVal;
  33721. bodyVal = NULL;
  33722. nextHdr->next = curHdr;
  33723. curHdr = nextHdr;
  33724. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33725. DYNAMIC_TYPE_PKCS7);
  33726. if (nextHdr == NULL) {
  33727. ret = MEMORY_E;
  33728. goto error;
  33729. }
  33730. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33731. }
  33732. else {
  33733. nextParam->attribute = nameAttr;
  33734. nameAttr = NULL;
  33735. nextParam->value = bodyVal;
  33736. bodyVal = NULL;
  33737. nextParam->next = curHdr->params;
  33738. curHdr->params = nextParam;
  33739. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33740. DYNAMIC_TYPE_PKCS7);
  33741. if (nextParam == NULL) {
  33742. ret = MEMORY_E;
  33743. goto error;
  33744. }
  33745. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33746. }
  33747. mimeType = MIME_PARAM;
  33748. mimeStatus = MIME_NAMEATTR;
  33749. start = pos+1;
  33750. }
  33751. }
  33752. end = lineLen-1;
  33753. /* Omit newline characters. */
  33754. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33755. end--;
  33756. }
  33757. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33758. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33759. if (ret) {
  33760. goto error;
  33761. }
  33762. if (mimeType == MIME_HDR) {
  33763. nextHdr->name = nameAttr;
  33764. nameAttr = NULL;
  33765. nextHdr->body = bodyVal;
  33766. bodyVal = NULL;
  33767. nextHdr->next = curHdr;
  33768. curHdr = nextHdr;
  33769. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33770. DYNAMIC_TYPE_PKCS7);
  33771. if (nextHdr == NULL) {
  33772. ret = MEMORY_E;
  33773. goto error;
  33774. }
  33775. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33776. } else {
  33777. nextParam->attribute = nameAttr;
  33778. nameAttr = NULL;
  33779. nextParam->value = bodyVal;
  33780. bodyVal = NULL;
  33781. nextParam->next = curHdr->params;
  33782. curHdr->params = nextParam;
  33783. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33784. DYNAMIC_TYPE_PKCS7);
  33785. if (nextParam == NULL) {
  33786. ret = MEMORY_E;
  33787. goto error;
  33788. }
  33789. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33790. }
  33791. }
  33792. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33793. mimeStatus = MIME_NAMEATTR;
  33794. }
  33795. *headers = curHdr;
  33796. ret = 0; /* success if at this point */
  33797. error:
  33798. if (ret != 0)
  33799. wc_MIME_free_hdrs(curHdr);
  33800. wc_MIME_free_hdrs(nextHdr);
  33801. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33802. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33803. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33804. return ret;
  33805. }
  33806. /*****************************************************************************
  33807. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33808. * out disallowed/separator characters and places the rest into *out.
  33809. *
  33810. * RETURNS:
  33811. * returns zero on success, non-zero on error.
  33812. */
  33813. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33814. {
  33815. size_t inPos = start;
  33816. size_t outPos = 0;
  33817. size_t inLen = 0;
  33818. if (end < start || in == NULL || out == NULL) {
  33819. return BAD_FUNC_ARG;
  33820. }
  33821. inLen = XSTRLEN(in);
  33822. if (start > inLen || end > inLen) {
  33823. return BAD_FUNC_ARG;
  33824. }
  33825. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33826. DYNAMIC_TYPE_PKCS7);
  33827. if (*out == NULL) {
  33828. return MEMORY_E;
  33829. }
  33830. while (inPos <= end) {
  33831. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33832. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33833. (*out)[outPos] = in[inPos];
  33834. outPos++;
  33835. }
  33836. inPos++;
  33837. }
  33838. (*out)[outPos] = '\0';
  33839. return 0;
  33840. }
  33841. /*****************************************************************************
  33842. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33843. * a name matching the provided name is found.
  33844. *
  33845. * RETURNS:
  33846. * returns a pointer to the found header, if no match was found, returns NULL.
  33847. */
  33848. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33849. {
  33850. while (header) {
  33851. if (!XSTRCMP(name, header->name)) {
  33852. return header;
  33853. }
  33854. header = header->next;
  33855. }
  33856. return header;
  33857. }
  33858. /*****************************************************************************
  33859. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33860. * with a attribute matching the provided attribute is found.
  33861. *
  33862. * RETURNS:
  33863. * returns a pointer to the found parameter, if no match was found,
  33864. * returns NULL.
  33865. */
  33866. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33867. MimeParam* param)
  33868. {
  33869. while (param) {
  33870. if (!XSTRCMP(attribute, param->attribute)) {
  33871. return param;
  33872. }
  33873. param = param->next;
  33874. }
  33875. return param;
  33876. }
  33877. /*****************************************************************************
  33878. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33879. * line ending to CRLF.
  33880. *
  33881. * line - input line to canonicalize
  33882. * len - length of line in chars on input, length of output array on return
  33883. *
  33884. * RETURNS:
  33885. * returns a pointer to a canonicalized line on success, NULL on error.
  33886. */
  33887. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33888. {
  33889. size_t end = 0;
  33890. char* canonLine = NULL;
  33891. if (line == NULL || len == NULL || *len == 0) {
  33892. return NULL;
  33893. }
  33894. end = *len;
  33895. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33896. end--;
  33897. }
  33898. /* Need 2 chars for \r\n and 1 for EOL */
  33899. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33900. if (canonLine == NULL) {
  33901. return NULL;
  33902. }
  33903. XMEMCPY(canonLine, line, end);
  33904. canonLine[end] = '\r';
  33905. canonLine[end+1] = '\n';
  33906. canonLine[end+2] = '\0';
  33907. *len = (word32)(end + 3);
  33908. return canonLine;
  33909. }
  33910. /*****************************************************************************
  33911. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33912. * the provided header pointer.
  33913. *
  33914. * RETURNS:
  33915. * returns zero on success, non-zero on error.
  33916. */
  33917. int wc_MIME_free_hdrs(MimeHdr* head)
  33918. {
  33919. MimeHdr* curHdr = NULL;
  33920. MimeParam* curParam = NULL;
  33921. while (head) {
  33922. while (head->params) {
  33923. curParam = head->params;
  33924. head->params = head->params->next;
  33925. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33926. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33927. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33928. }
  33929. curHdr = head;
  33930. head = head->next;
  33931. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33932. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33933. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33934. }
  33935. return 0;
  33936. }
  33937. #endif /* HAVE_SMIME */
  33938. #undef ERROR_OUT
  33939. #ifdef WOLFSSL_ASN_PRINT
  33940. /*******************************************************************************
  33941. * ASN.1 Parsing and Printing Implementation
  33942. ******************************************************************************/
  33943. /* Initialize ASN.1 print options.
  33944. *
  33945. * @param [in, out] opts ASN.1 options for printing.
  33946. * @return 0 on success.
  33947. * @return BAD_FUNC_ARG when asn1 is NULL.
  33948. */
  33949. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  33950. {
  33951. int ret = 0;
  33952. if (opts == NULL) {
  33953. ret = BAD_FUNC_ARG;
  33954. }
  33955. else {
  33956. XMEMSET(opts, 0, sizeof(*opts));
  33957. }
  33958. return ret;
  33959. }
  33960. /* Set a print option into Asn1PrintOptions object.
  33961. *
  33962. * @param [in, out] opts ASN.1 options for printing.
  33963. * @param [in] opt Option to set value of.
  33964. * @param [in] val Value to set for option.
  33965. * @return 0 on success.
  33966. * @return BAD_FUNC_ARG when asn1 is NULL.
  33967. * @return BAD_FUNC_ARG when val is out of range for option.
  33968. */
  33969. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  33970. word32 val)
  33971. {
  33972. int ret = 0;
  33973. /* Validate parameters. */
  33974. if (opts == NULL) {
  33975. ret = BAD_FUNC_ARG;
  33976. }
  33977. if (ret == 0) {
  33978. switch (opt) {
  33979. /* Offset into DER/BER data to start decoding from. */
  33980. case ASN1_PRINT_OPT_OFFSET:
  33981. opts->offset = val;
  33982. break;
  33983. /* Length of DER/BER encoding to parse. */
  33984. case ASN1_PRINT_OPT_LENGTH:
  33985. opts->length = val;
  33986. break;
  33987. /* Number of spaces to indent for each change in depth. */
  33988. case ASN1_PRINT_OPT_INDENT:
  33989. /* Only 4 bits allowed for value. */
  33990. if (val >= (1 << 4)) {
  33991. ret = BAD_FUNC_ARG;
  33992. }
  33993. else {
  33994. opts->indent = (word8)val;
  33995. }
  33996. break;
  33997. /* Draw branches instead of indenting. */
  33998. case ASN1_PRINT_OPT_DRAW_BRANCH:
  33999. /* Boolean value. */
  34000. opts->draw_branch = (val > 0);
  34001. break;
  34002. /* Show raw data of primitive types as octets. */
  34003. case ASN1_PRINT_OPT_SHOW_DATA:
  34004. /* Boolean value. */
  34005. opts->show_data = (val > 0);
  34006. break;
  34007. /* Show header data as octets. */
  34008. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  34009. /* Boolean value. */
  34010. opts->show_header_data = (val > 0);
  34011. break;
  34012. /* Show the wolfSSL OID value for OBJECT_ID. */
  34013. case ASN1_PRINT_OPT_SHOW_OID:
  34014. /* Boolean value. */
  34015. opts->show_oid = (val > 0);
  34016. break;
  34017. /* Don't show text representations of primitive types. */
  34018. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  34019. /* Boolean value. */
  34020. opts->show_no_text = (val > 0);
  34021. break;
  34022. /* Don't show dump text representations of primitive types. */
  34023. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  34024. /* Boolean value. */
  34025. opts->show_no_dump_text = (val > 0);
  34026. break;
  34027. }
  34028. }
  34029. return ret;
  34030. }
  34031. /* Initialize an ASN.1 parse object.
  34032. *
  34033. * @param [in, out] asn1 ASN.1 parse object.
  34034. * @return 0 on success.
  34035. * @return BAD_FUNC_ARG when asn1 is NULL.
  34036. */
  34037. int wc_Asn1_Init(Asn1* asn1)
  34038. {
  34039. int ret = 0;
  34040. if (asn1 == NULL) {
  34041. ret = BAD_FUNC_ARG;
  34042. }
  34043. else {
  34044. XMEMSET(asn1, 0, sizeof(*asn1));
  34045. asn1->file = XBADFILE;
  34046. }
  34047. return ret;
  34048. }
  34049. /* Set the file to use when printing.
  34050. *
  34051. * @param [in, out] asn1 ASN.1 parse object.
  34052. * @param [in] file File to print to.
  34053. * @return 0 on success.
  34054. * @return BAD_FUNC_ARG when asn1 is NULL.
  34055. * @return BAD_FUNC_ARG when file is XBADFILE.
  34056. */
  34057. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  34058. {
  34059. int ret = 0;
  34060. if ((asn1 == NULL) || (file == XBADFILE)) {
  34061. ret = BAD_FUNC_ARG;
  34062. }
  34063. else {
  34064. asn1->file = file;
  34065. }
  34066. return ret;
  34067. }
  34068. /* Print OID in dotted form or as hex bytes.
  34069. *
  34070. * @param [in] file File pointer to write to.
  34071. * @param [in] oid OBJECT_ID data.
  34072. * @param [in] oid_len Length of OBJECT_ID data.
  34073. */
  34074. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  34075. {
  34076. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  34077. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  34078. word32 i;
  34079. /* Decode OBJECT_ID into dotted form array. */
  34080. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  34081. /* Print out each number of dotted form. */
  34082. for (i = 0; i < num; i++) {
  34083. XFPRINTF(file, "%d", dotted_nums[i]);
  34084. /* Add separator. */
  34085. if (i < num - 1) {
  34086. XFPRINTF(file, ".");
  34087. }
  34088. }
  34089. }
  34090. else {
  34091. /* Print out bytes as we couldn't decode. */
  34092. for (i = 0; i < len; i++) {
  34093. XFPRINTF(file, "%02x", oid[i]);
  34094. /* Add separator. */
  34095. if (i < len - 1) {
  34096. XFPRINTF(file, ":");
  34097. }
  34098. }
  34099. }
  34100. }
  34101. /* OID value to name mapping. */
  34102. typedef struct OidName {
  34103. /* wolfSSL OID value. */
  34104. word32 oid;
  34105. /* Long name to print when OID seen. */
  34106. const char* name;
  34107. } OidName;
  34108. /* Extra OID to name mappings. */
  34109. static const OidName extraOids[] = {
  34110. { 0x005c, "commonName" },
  34111. { 0x005d, "surname" },
  34112. { 0x005e, "serialNumber" },
  34113. { 0x005f, "countryName" },
  34114. { 0x0060, "localityName" },
  34115. { 0x0061, "stateOrProvinceName" },
  34116. { 0x0062, "streetAddress" },
  34117. { 0x0063, "organizationName" },
  34118. { 0x0064, "organizationUnitName" },
  34119. { 0x0065, "title" },
  34120. { 0x0086, "certificateExtension" },
  34121. { 0x028d, "emailAddress" },
  34122. { 0x0293, "challengePassword" },
  34123. { 0x029a, "extensionReq" },
  34124. };
  34125. /* Length of table of extra OID to name mappings. */
  34126. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  34127. /* Convert OID value to long name.
  34128. *
  34129. * @param [in] oid OID value.
  34130. * @param [out] name Long name for OID when known.
  34131. * @return 1 when OID known.
  34132. * @return 0 when OID not known.
  34133. */
  34134. static int Oid2LongName(word32 oid, const char** name)
  34135. {
  34136. int ret = 0;
  34137. int i;
  34138. /* Step through each entry in table. */
  34139. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  34140. if (extraOids[i].oid == oid) {
  34141. /* Return the name associated with the OID value. */
  34142. *name = extraOids[i].name;
  34143. ret = 1;
  34144. break;
  34145. }
  34146. }
  34147. return ret;
  34148. }
  34149. /* Print the text version of the OBJECT_ID.
  34150. *
  34151. * @param [in] asn1 ASN.1 parse object.
  34152. * @param [in] opts ASN.1 options for printing.
  34153. */
  34154. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  34155. {
  34156. word32 oid = (word32)-1;
  34157. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  34158. int nid;
  34159. #endif
  34160. const char* ln = NULL;
  34161. word32 i = 0;
  34162. int known = 1;
  34163. /* Get the OID value for the OBJECT_ID. */
  34164. if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  34165. asn1->item.len + 2) == ASN_PARSE_E) {
  34166. known = 0;
  34167. }
  34168. else
  34169. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  34170. /* Lookup NID for OID value. */
  34171. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  34172. /* Lookup long name for NID. */
  34173. ln = wolfSSL_OBJ_nid2ln(nid);
  34174. }
  34175. else
  34176. #endif
  34177. /* Lookup long name for extra known OID values. */
  34178. if (!Oid2LongName(oid, &ln)) {
  34179. /* Unknown OID value. */
  34180. ln = NULL;
  34181. known = 0;
  34182. }
  34183. XFPRINTF(asn1->file, ":");
  34184. /* Show OID value if not known or asked to. */
  34185. if ((!known) || opts->show_oid) {
  34186. XFPRINTF(asn1->file, "(0x%x) ", oid);
  34187. }
  34188. if (ln != NULL) {
  34189. /* Print long name. */
  34190. XFPRINTF(asn1->file, "%s", ln);
  34191. }
  34192. else {
  34193. /* Print out as numbers - either dotted or hex values. */
  34194. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  34195. asn1->item.len);
  34196. }
  34197. }
  34198. /* Print ASN.1 data as a character string.
  34199. *
  34200. * @param [in] asn1 ASN.1 parse object.
  34201. */
  34202. static void PrintText(Asn1* asn1)
  34203. {
  34204. word32 i;
  34205. XFPRINTF(asn1->file, ":");
  34206. /* Print all data bytes as characters. */
  34207. for (i = 0; i < asn1->item.len; i++) {
  34208. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  34209. }
  34210. }
  34211. /* Print data as a hex bytes.
  34212. *
  34213. * @param [in] file File pointer to write to.
  34214. * @param [in] data Data to print.
  34215. * @param [in] len Number of bytes to print.
  34216. */
  34217. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  34218. {
  34219. word32 i;
  34220. /* Print data bytes as hex numbers. */
  34221. for (i = 0; i < len; i++) {
  34222. XFPRINTF(file, "%02x", data[i]);
  34223. }
  34224. }
  34225. /* Print ASN.1 data as a hex bytes.
  34226. *
  34227. * @param [in] asn1 ASN.1 parse object.
  34228. */
  34229. static void PrintHexText(Asn1* asn1)
  34230. {
  34231. XFPRINTF(asn1->file, ":");
  34232. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  34233. }
  34234. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  34235. *
  34236. * @param [in] asn1 ASN.1 parse object.
  34237. */
  34238. static void PrintBitStringText(Asn1* asn1)
  34239. {
  34240. if (asn1->item.len > 0) {
  34241. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  34242. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  34243. asn1->item.len - 1);
  34244. }
  34245. }
  34246. /* Print ASN.1 BOOLEAN data as text with value.
  34247. *
  34248. * @param [in] asn1 ASN.1 parse object.
  34249. */
  34250. static void PrintBooleanText(Asn1* asn1)
  34251. {
  34252. /* Booleans should be 1 byte of data. */
  34253. if (asn1->item.len == 1) {
  34254. XFPRINTF(asn1->file, ":%s (%d)",
  34255. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  34256. asn1->data[asn1->item.data_idx]);
  34257. }
  34258. }
  34259. /* Print ASN.1 data as single byte +/- number.
  34260. *
  34261. * @param [in] asn1 ASN.1 parse object.
  34262. */
  34263. static void PrintNumberText(Asn1* asn1)
  34264. {
  34265. /* Only supporting 1 byte of data for now. */
  34266. if (asn1->item.len == 1) {
  34267. int num = asn1->data[asn1->item.data_idx];
  34268. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  34269. }
  34270. }
  34271. /* Print ASN.1 data as a text based on the tag.
  34272. *
  34273. * TODO: handle more tags.
  34274. *
  34275. * @param [in] asn1 ASN.1 parse object.
  34276. * @param [in] opts ASN.1 options for printing.
  34277. */
  34278. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  34279. {
  34280. /* Get the long name for OBJECT_ID where possible. */
  34281. if (asn1->item.tag == ASN_OBJECT_ID) {
  34282. PrintObjectIdText(asn1, opts);
  34283. }
  34284. /* Data is an array of printable characters. */
  34285. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  34286. (asn1->item.tag == ASN_IA5_STRING) ||
  34287. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  34288. (asn1->item.tag == ASN_T61STRING) ||
  34289. (asn1->item.tag == ASN_BMPSTRING) ||
  34290. (asn1->item.tag == ASN_UTC_TIME) ||
  34291. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  34292. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  34293. (asn1->item.tag == ASN_OBJECT_DESC) ||
  34294. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  34295. PrintText(asn1);
  34296. }
  34297. /* Show TRUE and FALSE with number. */
  34298. else if (asn1->item.tag == ASN_BOOLEAN) {
  34299. PrintBooleanText(asn1);
  34300. }
  34301. /* Show number. */
  34302. else if (asn1->item.tag == ASN_ENUMERATED) {
  34303. PrintNumberText(asn1);
  34304. }
  34305. /* Dumping potentially long string of hex digites. */
  34306. else if (!opts->show_no_dump_text) {
  34307. /* Dump all bytes. */
  34308. if ((asn1->item.tag == ASN_INTEGER) ||
  34309. (asn1->item.tag == ASN_OCTET_STRING) ||
  34310. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  34311. PrintHexText(asn1);
  34312. }
  34313. /* First byte is number of unused bits in last byte.
  34314. * Print first specially and dump rest of the bytes. */
  34315. else if (asn1->item.tag == ASN_BIT_STRING) {
  34316. PrintBitStringText(asn1);
  34317. }
  34318. }
  34319. }
  34320. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  34321. /* Dump data as hex bytes.
  34322. *
  34323. * @param [in] file File pointer to write to.
  34324. * @param [in] data Data to print.
  34325. * @param [in] len Number of bytes to print.
  34326. */
  34327. static void DumpData(XFILE file, unsigned char* data, word32 len)
  34328. {
  34329. word32 i;
  34330. word32 j;
  34331. for (i = 0; i < len; i += j) {
  34332. /* Print offset. */
  34333. XFPRINTF(file, " %04x:", i);
  34334. for (j = 0; (j < 16) && (i + j < len); j++) {
  34335. /* Print byte as hex number. */
  34336. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  34337. }
  34338. /* Print spaces between hex and characters. */
  34339. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  34340. for (j = 0; (j < 16) && (i + j < len); j++) {
  34341. /* Print byte as hex number. */
  34342. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  34343. }
  34344. XFPRINTF(file, "\n");
  34345. }
  34346. }
  34347. /* Update current depth based on the current position.
  34348. *
  34349. * @param [in, out] asn1 ASN.1 parse object.
  34350. */
  34351. static void UpdateDepth(Asn1* asn1)
  34352. {
  34353. /* If current index is greater than or equal end index then it is done. */
  34354. while ((asn1->depth > 0) &&
  34355. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  34356. /* Move up a depth. */
  34357. asn1->depth--;
  34358. }
  34359. }
  34360. /* Check validity of end index of constructed ASN.1 items.
  34361. *
  34362. * @param [in, out] asn1 ASN.1 parse object.
  34363. * @return 0 on success.
  34364. * @return ASN_DEPTH_E when end offset invalid.
  34365. */
  34366. static int CheckDepth(Asn1* asn1)
  34367. {
  34368. int ret = 0;
  34369. int i;
  34370. word32 curr_end = asn1->curr + asn1->item.len;
  34371. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  34372. /* Each end index must be at least as large as the current one. */
  34373. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  34374. ret = ASN_DEPTH_E;
  34375. }
  34376. /* Each end index must be at least as large as current index. */
  34377. if (asn1->end_idx[i] < curr_end) {
  34378. ret = ASN_DEPTH_E;
  34379. }
  34380. }
  34381. return ret;
  34382. }
  34383. /* Draw branching based on depth for an ASN.1 item.
  34384. *
  34385. * @param [in] asn1 ASN.1 parse object.
  34386. */
  34387. static void DrawBranch(Asn1* asn1)
  34388. {
  34389. int i;
  34390. word32 end = asn1->curr + asn1->item.len;
  34391. /* Write out the character for all depths but current. */
  34392. for (i = 0; i < asn1->depth; i++) {
  34393. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  34394. if (i < asn1->depth - 1) {
  34395. /* Constructed or not end index and not current depth: | */
  34396. XFPRINTF(asn1->file, "\xe2\x94\x82");
  34397. }
  34398. else {
  34399. /* Constructed or not end index and current depth: |- */
  34400. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  34401. }
  34402. }
  34403. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  34404. /* End index for previous: _|_ (in top half) */
  34405. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  34406. }
  34407. else {
  34408. /* End index but not for previous: L (in top half) */
  34409. XFPRINTF(asn1->file, "\xe2\x94\x94");
  34410. }
  34411. }
  34412. /* Prefix to tag name. */
  34413. if (asn1->item.cons) {
  34414. if (asn1->depth > 0) {
  34415. /* Have other line to connect to: T (in bottom half) */
  34416. XFPRINTF(asn1->file, "\xe2\x94\xac");
  34417. }
  34418. else {
  34419. /* Have no other line to connect to: r */
  34420. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  34421. }
  34422. }
  34423. else {
  34424. /* In a sequence: - */
  34425. XFPRINTF(asn1->file, "\xe2\x94\x80");
  34426. }
  34427. }
  34428. /* Print data as hex bytes separated by space.
  34429. *
  34430. * @param [in] file File pointer to write to.
  34431. * @param [in] data Data to print.
  34432. * @param [in] len Number of bytes to print.
  34433. */
  34434. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  34435. {
  34436. word32 i;
  34437. for (i = 0; i < len; i++) {
  34438. XFPRINTF(file, " %02x", data[i]);
  34439. }
  34440. }
  34441. /* Dump header data.
  34442. *
  34443. * @param [in] asn1 ASN.1 parse object.
  34444. * @param [in] opts ASN.1 options for printing.
  34445. */
  34446. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  34447. {
  34448. /* Put on same line when not showing data too and not showing text data. */
  34449. if ((!opts->show_data) && opts->show_no_text) {
  34450. XFPRINTF(asn1->file, "%10s", "");
  34451. }
  34452. else {
  34453. /* Align with start of data. */
  34454. XFPRINTF(asn1->file, "\n%12s", "");
  34455. }
  34456. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  34457. if (asn1->curr >= asn1->offset + 1) {
  34458. /* Print the header bytes as hex bytes separated by a space. */
  34459. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  34460. asn1->curr - (asn1->offset + 1));
  34461. }
  34462. }
  34463. /* Print ASN.1 item info based on header and indices.
  34464. *
  34465. * @param [in] asn1 ASN.1 parse object.
  34466. * @param [in] opts ASN.1 options for printing.
  34467. */
  34468. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  34469. {
  34470. /* Print offset of this ASN.1 item. */
  34471. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  34472. /* Print length of header. */
  34473. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  34474. /* Print data length. */
  34475. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  34476. asn1->item.cons ? ']' : ' ');
  34477. /* Print depth. */
  34478. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  34479. if (!opts->draw_branch) {
  34480. /* Indent to depth as required. */
  34481. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  34482. if (!opts->indent) {
  34483. /* Indicate constructed if no indent. */
  34484. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  34485. }
  34486. }
  34487. else {
  34488. /* Draw branch structure for ASN.1 item. */
  34489. XFPRINTF(asn1->file, " ");
  34490. DrawBranch(asn1);
  34491. }
  34492. /* Print tag name. */
  34493. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  34494. }
  34495. /* Expecting tag part of ASN.1 item. */
  34496. #define ASN_PART_TAG 0
  34497. /* Expecting length part of ASN.1 item. */
  34498. #define ASN_PART_LENGTH 1
  34499. /* Expecting data part of ASN.1 item. */
  34500. #define ASN_PART_DATA 2
  34501. /* Print next ASN.1 item.
  34502. *
  34503. * @param [in, out] asn1 ASN.1 parse object.
  34504. * @param [in] opts ASN.1 print options.
  34505. * @return 0 on success.
  34506. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  34507. * @return ASN_LEN_E when ASN.1 item's length too long.
  34508. * @return ASN_DEPTH_E when end offset invalid.
  34509. */
  34510. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  34511. {
  34512. int ret = 0;
  34513. /* Process tag. */
  34514. if (asn1->part == ASN_PART_TAG) {
  34515. /* Recalculate which depth we are at. */
  34516. UpdateDepth(asn1);
  34517. /* Get tag. */
  34518. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  34519. /* Store whether tag indicates constructed. */
  34520. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  34521. ASN_CONSTRUCTED;
  34522. /* Start of ASN.1 item is current index. */
  34523. asn1->offset = asn1->curr;
  34524. /* Step over tag. */
  34525. asn1->curr++;
  34526. /* Next part is length. */
  34527. asn1->part = ASN_PART_LENGTH;
  34528. }
  34529. /* Process length. */
  34530. if (asn1->part == ASN_PART_LENGTH) {
  34531. int len;
  34532. /* Decode length and step over it. */
  34533. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  34534. ret = ASN_LEN_E;
  34535. }
  34536. else {
  34537. /* Store ASN.1 item data offset. */
  34538. asn1->item.data_idx = asn1->curr;
  34539. /* Store ASN.1 item data length. */
  34540. asn1->item.len = (word32)len;
  34541. /* Print info about ASN.1 item. */
  34542. PrintInfo(asn1, opts);
  34543. if (!asn1->item.cons) {
  34544. /* Move on to print data. */
  34545. asn1->part = ASN_PART_DATA;
  34546. }
  34547. else {
  34548. /* Print header now if not printing data. */
  34549. if (opts->show_header_data) {
  34550. DumpHeader(asn1, opts);
  34551. }
  34552. XFPRINTF(asn1->file, "\n");
  34553. /* Record end offset for this depth. */
  34554. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  34555. /* Done with this ASN.1 item. */
  34556. asn1->part = ASN_PART_TAG;
  34557. }
  34558. /* Check end indices are valid. */
  34559. ret = CheckDepth(asn1);
  34560. }
  34561. }
  34562. /* Process data. */
  34563. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  34564. if (!opts->show_no_text) {
  34565. /* Print text representation of data. */
  34566. PrintAsn1Text(asn1, opts);
  34567. }
  34568. if (opts->show_header_data) {
  34569. /* Dump header bytes. */
  34570. DumpHeader(asn1, opts);
  34571. }
  34572. XFPRINTF(asn1->file, "\n");
  34573. if (opts->show_data) {
  34574. /* Dump data bytes. */
  34575. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  34576. asn1->item.len);
  34577. }
  34578. /* Step past data to next ASN.1 item. */
  34579. asn1->curr += asn1->item.len;
  34580. /* Update the depth based on end indices. */
  34581. UpdateDepth(asn1);
  34582. /* Done with this ASN.1 item. */
  34583. asn1->part = ASN_PART_TAG;
  34584. }
  34585. /* Make ASN.1 item printing go out. */
  34586. fflush(asn1->file);
  34587. return ret;
  34588. }
  34589. /* Print all ASN.1 items.
  34590. *
  34591. * @param [in, out] asn1 ASN.1 parse object.
  34592. * @param [in] opts ASN.1 print options.
  34593. * @param [in] data BER/DER data to print.
  34594. * @param [in] len Length of data to print in bytes.
  34595. * @return 0 on success.
  34596. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  34597. * @return ASN_LEN_E when ASN.1 item's length too long.
  34598. * @return ASN_DEPTH_E when end offset invalid.
  34599. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  34600. */
  34601. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  34602. word32 len)
  34603. {
  34604. int ret = 0;
  34605. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  34606. ret = BAD_FUNC_ARG;
  34607. }
  34608. if (ret == 0) {
  34609. /* Initialize start position. */
  34610. asn1->curr = 0;
  34611. /* Start parsing at tag. */
  34612. asn1->part = ASN_PART_TAG;
  34613. /* Start depth at 0. */
  34614. asn1->depth = 0;
  34615. /* Store the starting point of the data to parse. */
  34616. asn1->data = data + opts->offset;
  34617. if (opts->length > 0) {
  34618. /* Use user specified maximum length. */
  34619. asn1->max = opts->length;
  34620. }
  34621. else {
  34622. /* Maximum length is up to end from offset. */
  34623. asn1->max = len - opts->offset;
  34624. }
  34625. /* Keep going while no error and have data to parse. */
  34626. while ((ret == 0) && (asn1->curr < asn1->max)) {
  34627. /* Print an ASN.1 item. */
  34628. ret = wc_Asn1_Print(asn1, opts);
  34629. }
  34630. }
  34631. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  34632. /* Stopped before finishing ASN.1 item. */
  34633. ret = ASN_PARSE_E;
  34634. }
  34635. if ((ret == 0) && (asn1->depth != 0)) {
  34636. /* Stopped without seeing all items in a constructed item. */
  34637. ret = ASN_DEPTH_E;
  34638. }
  34639. return ret;
  34640. }
  34641. #endif /* WOLFSSL_ASN_PRINT */
  34642. #endif /* !NO_ASN */
  34643. /* Functions that parse, but are not using ASN.1 */
  34644. #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  34645. (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  34646. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  34647. /* this function does not use any ASN.1 parsing */
  34648. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  34649. word32 eSz, RsaKey* key)
  34650. {
  34651. if (n == NULL || e == NULL || key == NULL)
  34652. return BAD_FUNC_ARG;
  34653. key->type = RSA_PUBLIC;
  34654. if (mp_init(&key->n) != MP_OKAY)
  34655. return MP_INIT_E;
  34656. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  34657. mp_clear(&key->n);
  34658. return ASN_GETINT_E;
  34659. }
  34660. #ifdef HAVE_WOLF_BIGINT
  34661. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  34662. mp_clear(&key->n);
  34663. return ASN_GETINT_E;
  34664. }
  34665. #endif /* HAVE_WOLF_BIGINT */
  34666. if (mp_init(&key->e) != MP_OKAY) {
  34667. mp_clear(&key->n);
  34668. return MP_INIT_E;
  34669. }
  34670. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  34671. mp_clear(&key->n);
  34672. mp_clear(&key->e);
  34673. return ASN_GETINT_E;
  34674. }
  34675. #ifdef HAVE_WOLF_BIGINT
  34676. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  34677. mp_clear(&key->n);
  34678. mp_clear(&key->e);
  34679. return ASN_GETINT_E;
  34680. }
  34681. #endif /* HAVE_WOLF_BIGINT */
  34682. #ifdef WOLFSSL_XILINX_CRYPT
  34683. if (wc_InitRsaHw(key) != 0) {
  34684. return BAD_STATE_E;
  34685. }
  34686. #endif
  34687. return 0;
  34688. }
  34689. #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  34690. #ifdef WOLFSSL_SEP
  34691. #endif /* WOLFSSL_SEP */