asn.c 1.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163
  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_SCEPROTECT) || 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. * @erturn 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 max)
  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 < max; 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 Maximim 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. #ifndef WOLFSSL_ASN_TEMPLATE
  2338. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2339. *
  2340. * Removes the leading zero byte when found.
  2341. *
  2342. * input Buffer holding DER/BER encoded data.
  2343. * inOutIdx Current index into buffer to parse.
  2344. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2345. * maxIdx Length of data in buffer.
  2346. * returns BUFFER_E when there is not enough data to parse.
  2347. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2348. * or invalid use of or missing leading zero.
  2349. * Otherwise, 0 to indicate success.
  2350. */
  2351. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2352. word32 maxIdx)
  2353. {
  2354. int ret;
  2355. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2356. if (ret < 0)
  2357. return ret;
  2358. if (*len > 0) {
  2359. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2360. /* check for invalid padding on negative integer.
  2361. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2362. */
  2363. if (*len > 1) {
  2364. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2365. return ASN_PARSE_E;
  2366. }
  2367. #endif
  2368. /* remove leading zero, unless there is only one 0x00 byte */
  2369. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2370. (*inOutIdx)++;
  2371. (*len)--;
  2372. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2373. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2374. return ASN_PARSE_E;
  2375. #endif
  2376. }
  2377. }
  2378. return 0;
  2379. }
  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 pre-pended 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. if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
  2995. return MP_INIT_E;
  2996. if (initNum) {
  2997. if (mp_init(mpi) != MP_OKAY)
  2998. return MP_INIT_E;
  2999. }
  3000. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  3001. mp_clear(mpi);
  3002. return ASN_GETINT_E;
  3003. }
  3004. #ifdef HAVE_WOLF_BIGINT
  3005. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3006. mp_clear(mpi);
  3007. return ASN_GETINT_E;
  3008. }
  3009. #endif /* HAVE_WOLF_BIGINT */
  3010. *inOutIdx = idx + (word32)length;
  3011. return 0;
  3012. }
  3013. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  3014. #ifndef WOLFSSL_ASN_TEMPLATE
  3015. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  3016. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  3017. {
  3018. word32 idx = *inOutIdx;
  3019. int ret;
  3020. int length;
  3021. ret = GetASNInt(input, &idx, &length, maxIdx);
  3022. if (ret != 0)
  3023. return ret;
  3024. *inOutIdx = idx + (word32)length;
  3025. return 0;
  3026. }
  3027. #endif
  3028. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3029. #ifdef WOLFSSL_ASN_TEMPLATE
  3030. /* ASN.1 template for a BIT_STRING. */
  3031. static const ASNItem bitStringASN[] = {
  3032. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  3033. };
  3034. enum {
  3035. BITSTRINGASN_IDX_BIT_STR = 0
  3036. };
  3037. /* Number of items in ASN.1 template for a BIT_STRING. */
  3038. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  3039. #endif
  3040. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  3041. *
  3042. * @param [in] input Buffer holding BER encoding.
  3043. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3044. * On out, start of ASN.1 item after BIT_STRING.
  3045. * @param [out] len Length of BIT_STRING data.
  3046. * @param [in] maxIdx Maximum index of data in buffer.
  3047. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3048. * @param [in] unusedBits Number of unused bits in last byte.
  3049. * @return 0 on success.
  3050. * @return ASN_PARSE_E when encoding is invalid.
  3051. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3052. * @return BUFFER_E when data in buffer is too small.
  3053. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3054. */
  3055. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3056. word32 maxIdx, int zeroBits, byte* unusedBits)
  3057. {
  3058. #ifndef WOLFSSL_ASN_TEMPLATE
  3059. word32 idx = *inOutIdx;
  3060. int length;
  3061. byte b;
  3062. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3063. return ASN_BITSTR_E;
  3064. }
  3065. if (b != ASN_BIT_STRING) {
  3066. return ASN_BITSTR_E;
  3067. }
  3068. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3069. return ASN_PARSE_E;
  3070. /* extra sanity check that length is greater than 0 */
  3071. if (length <= 0) {
  3072. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3073. return BUFFER_E;
  3074. }
  3075. if (idx + 1 > maxIdx) {
  3076. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3077. return BUFFER_E;
  3078. }
  3079. b = input[idx];
  3080. if (zeroBits && b != 0x00)
  3081. return ASN_EXPECT_0_E;
  3082. if (b >= 0x08)
  3083. return ASN_PARSE_E;
  3084. if (b != 0) {
  3085. if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
  3086. return ASN_PARSE_E;
  3087. }
  3088. idx++;
  3089. length--; /* length has been checked for greater than 0 */
  3090. *inOutIdx = idx;
  3091. if (len != NULL)
  3092. *len = length;
  3093. if (unusedBits != NULL)
  3094. *unusedBits = b;
  3095. return 0;
  3096. #else
  3097. ASNGetData dataASN[bitStringASN_Length];
  3098. int ret;
  3099. int bits;
  3100. /* Parse BIT_STRING and check validity of unused bits. */
  3101. XMEMSET(dataASN, 0, sizeof(dataASN));
  3102. /* Decode BIT_STRING. */
  3103. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3104. inOutIdx, maxIdx);
  3105. if (ret == 0) {
  3106. /* Get unused bits from dynamic ASN.1 data. */
  3107. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3108. /* Check unused bits is 0 when expected. */
  3109. if (zeroBits && (bits != 0)) {
  3110. ret = ASN_EXPECT_0_E;
  3111. }
  3112. }
  3113. if (ret == 0) {
  3114. /* Return length of data and unused bits if required. */
  3115. if (len != NULL) {
  3116. *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3117. }
  3118. if (unusedBits != NULL) {
  3119. *unusedBits = (byte)bits;
  3120. }
  3121. }
  3122. return ret;
  3123. #endif
  3124. }
  3125. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3126. * KeyGen) */
  3127. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  3128. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3129. defined(OPENSSL_EXTRA))) || \
  3130. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3131. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3132. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3133. defined(OPENSSL_EXTRA))) || \
  3134. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3135. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3136. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3137. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3138. *
  3139. * When output is NULL, calculate the header length only.
  3140. *
  3141. * @param [in] len Length of BIT STRING data.
  3142. * That is, the number of least significant zero bits
  3143. * before a one.
  3144. * The last byte is the most-significant non-zero byte
  3145. * of a number.
  3146. * @param [out] output Buffer to write into.
  3147. * @return Number of bytes added to the buffer.
  3148. */
  3149. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3150. {
  3151. word32 idx = 0;
  3152. if (output) {
  3153. /* Write out tag. */
  3154. output[idx] = ASN_BIT_STRING;
  3155. }
  3156. /* Step over tag. */
  3157. idx += ASN_TAG_SZ;
  3158. /* Encode length - passing NULL for output will not encode.
  3159. * Add one to length for unused bits. */
  3160. idx += SetLength(len + 1, output ? output + idx : NULL);
  3161. if (output) {
  3162. /* Write out unused bits. */
  3163. output[idx] = unusedBits;
  3164. }
  3165. /* Skip over unused bits. */
  3166. idx++;
  3167. /* Return index after header. */
  3168. return idx;
  3169. }
  3170. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3171. #ifdef ASN_BER_TO_DER
  3172. /* Convert BER to DER */
  3173. /* Pull informtation from the ASN.1 BER encoded item header */
  3174. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3175. byte* pTag, word32* pLen, int* indef)
  3176. {
  3177. int len = 0;
  3178. byte tag;
  3179. word32 i = *idx;
  3180. *indef = 0;
  3181. /* Check there is enough data for a minimal header */
  3182. if (i + 2 > maxIdx) {
  3183. return ASN_PARSE_E;
  3184. }
  3185. /* Retrieve tag */
  3186. tag = data[i++];
  3187. /* Indefinite length handled specially */
  3188. if (data[i] == ASN_INDEF_LENGTH) {
  3189. /* Check valid tag for indefinite */
  3190. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3191. return ASN_PARSE_E;
  3192. }
  3193. i++;
  3194. *indef = 1;
  3195. }
  3196. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3197. return ASN_PARSE_E;
  3198. }
  3199. /* Return tag, length and index after BER item header */
  3200. *pTag = tag;
  3201. *pLen = (word32)len;
  3202. *idx = i;
  3203. return 0;
  3204. }
  3205. #ifndef INDEF_ITEMS_MAX
  3206. #define INDEF_ITEMS_MAX 20
  3207. #endif
  3208. /* Indef length item data */
  3209. typedef struct Indef {
  3210. word32 start;
  3211. int depth;
  3212. int headerLen;
  3213. word32 len;
  3214. } Indef;
  3215. /* Indef length items */
  3216. typedef struct IndefItems
  3217. {
  3218. Indef len[INDEF_ITEMS_MAX];
  3219. int cnt;
  3220. int idx;
  3221. int depth;
  3222. } IndefItems;
  3223. /* Get header length of current item */
  3224. static int IndefItems_HeaderLen(IndefItems* items)
  3225. {
  3226. return items->len[items->idx].headerLen;
  3227. }
  3228. /* Get data length of current item */
  3229. static word32 IndefItems_Len(IndefItems* items)
  3230. {
  3231. return items->len[items->idx].len;
  3232. }
  3233. /* Add a indefinite length item */
  3234. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3235. {
  3236. int ret = 0;
  3237. int i;
  3238. if (items->cnt == INDEF_ITEMS_MAX) {
  3239. ret = MEMORY_E;
  3240. }
  3241. else {
  3242. i = items->cnt++;
  3243. items->len[i].start = start;
  3244. items->len[i].depth = items->depth++;
  3245. items->len[i].headerLen = 1;
  3246. items->len[i].len = 0;
  3247. items->idx = i;
  3248. }
  3249. return ret;
  3250. }
  3251. /* Increase data length of current item */
  3252. static void IndefItems_AddData(IndefItems* items, word32 length)
  3253. {
  3254. items->len[items->idx].len += length;
  3255. }
  3256. /* Update header length of current item to reflect data length */
  3257. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3258. {
  3259. items->len[items->idx].headerLen +=
  3260. (int)SetLength(items->len[items->idx].len, NULL);
  3261. }
  3262. /* Go to indefinite parent of current item */
  3263. static void IndefItems_Up(IndefItems* items)
  3264. {
  3265. int i;
  3266. int depth = items->len[items->idx].depth - 1;
  3267. for (i = items->cnt - 1; i >= 0; i--) {
  3268. if (items->len[i].depth == depth) {
  3269. break;
  3270. }
  3271. }
  3272. items->idx = i;
  3273. items->depth = depth + 1;
  3274. }
  3275. /* Calculate final length by adding length of indefinite child items */
  3276. static void IndefItems_CalcLength(IndefItems* items)
  3277. {
  3278. int i;
  3279. int idx = items->idx;
  3280. for (i = idx + 1; i < items->cnt; i++) {
  3281. if (items->len[i].depth == items->depth) {
  3282. items->len[idx].len += (word32)items->len[i].headerLen;
  3283. items->len[idx].len += items->len[i].len;
  3284. }
  3285. }
  3286. items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
  3287. }
  3288. /* Add more data to indefinite length item */
  3289. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3290. {
  3291. if (items->cnt > 0 && items->idx >= 0) {
  3292. items->len[items->idx].len += length;
  3293. }
  3294. }
  3295. /* Convert a BER encoding with indefinite length items to DER.
  3296. *
  3297. * ber BER encoded data.
  3298. * berSz Length of BER encoded data.
  3299. * der Buffer to hold DER encoded version of data.
  3300. * NULL indicates only the length is required.
  3301. * derSz The size of the buffer to hold the DER encoded data.
  3302. * Will be set if der is NULL, otherwise the value is checked as der is
  3303. * filled.
  3304. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3305. * derSz are NULL.
  3306. */
  3307. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3308. {
  3309. int ret = 0;
  3310. word32 i, j;
  3311. #ifdef WOLFSSL_SMALL_STACK
  3312. IndefItems* indefItems = NULL;
  3313. #else
  3314. IndefItems indefItems[1];
  3315. #endif
  3316. byte tag, basic;
  3317. word32 length;
  3318. int indef;
  3319. if (ber == NULL || derSz == NULL)
  3320. return BAD_FUNC_ARG;
  3321. #ifdef WOLFSSL_SMALL_STACK
  3322. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3323. DYNAMIC_TYPE_TMP_BUFFER);
  3324. if (indefItems == NULL) {
  3325. ret = MEMORY_E;
  3326. goto end;
  3327. }
  3328. #endif
  3329. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3330. /* Calculate indefinite item lengths */
  3331. for (i = 0; i < berSz; ) {
  3332. word32 start = i;
  3333. /* Get next BER item */
  3334. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3335. if (ret != 0) {
  3336. goto end;
  3337. }
  3338. if (indef) {
  3339. /* Indefinite item - add to list */
  3340. ret = IndefItems_AddItem(indefItems, i);
  3341. if (ret != 0) {
  3342. goto end;
  3343. }
  3344. if ((tag & 0xC0) == 0 &&
  3345. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3346. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3347. /* Constructed basic type - get repeating tag */
  3348. basic = (byte)(tag & (~ASN_CONSTRUCTED));
  3349. /* Add up lengths of each item below */
  3350. for (; i < berSz; ) {
  3351. /* Get next BER_item */
  3352. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3353. if (ret != 0) {
  3354. goto end;
  3355. }
  3356. /* End of content closes item */
  3357. if (tag == ASN_EOC) {
  3358. /* Must be zero length */
  3359. if (length != 0) {
  3360. ret = ASN_PARSE_E;
  3361. goto end;
  3362. }
  3363. break;
  3364. }
  3365. /* Must not be indefinite and tag must match parent */
  3366. if (indef || tag != basic) {
  3367. ret = ASN_PARSE_E;
  3368. goto end;
  3369. }
  3370. /* Add to length */
  3371. IndefItems_AddData(indefItems, length);
  3372. /* Skip data */
  3373. i += length;
  3374. }
  3375. /* Ensure we got an EOC and not end of data */
  3376. if (tag != ASN_EOC) {
  3377. ret = ASN_PARSE_E;
  3378. goto end;
  3379. }
  3380. /* Set the header length to include the length field */
  3381. IndefItems_UpdateHeaderLen(indefItems);
  3382. /* Go to indefinite parent item */
  3383. IndefItems_Up(indefItems);
  3384. }
  3385. }
  3386. else if (tag == ASN_EOC) {
  3387. /* End-of-content must be 0 length */
  3388. if (length != 0) {
  3389. ret = ASN_PARSE_E;
  3390. goto end;
  3391. }
  3392. /* Check there is an item to close - missing EOC */
  3393. if (indefItems->depth == 0) {
  3394. ret = ASN_PARSE_E;
  3395. goto end;
  3396. }
  3397. /* Finish calculation of data length for indefinite item */
  3398. IndefItems_CalcLength(indefItems);
  3399. /* Go to indefinite parent item */
  3400. IndefItems_Up(indefItems);
  3401. }
  3402. else {
  3403. /* Known length item to add in - make sure enough data for it */
  3404. if (i + length > berSz) {
  3405. ret = ASN_PARSE_E;
  3406. goto end;
  3407. }
  3408. /* Include all data - can't have indefinite inside definite */
  3409. i += length;
  3410. /* Add entire item to current indefinite item */
  3411. IndefItems_MoreData(indefItems, i - start);
  3412. }
  3413. }
  3414. /* Check we had a EOC for each indefinite item */
  3415. if (indefItems->depth != 0) {
  3416. ret = ASN_PARSE_E;
  3417. goto end;
  3418. }
  3419. /* Write out DER */
  3420. j = 0;
  3421. /* Reset index */
  3422. indefItems->idx = 0;
  3423. for (i = 0; i < berSz; ) {
  3424. word32 start = i;
  3425. /* Get item - checked above */
  3426. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3427. if (indef) {
  3428. if (der != NULL) {
  3429. /* Check enough space for header */
  3430. if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
  3431. ret = BUFFER_E;
  3432. goto end;
  3433. }
  3434. if ((tag & 0xC0) == 0 &&
  3435. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3436. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3437. /* Remove constructed tag for basic types */
  3438. tag &= (byte)~ASN_CONSTRUCTED;
  3439. }
  3440. /* Add tag and length */
  3441. der[j] = tag;
  3442. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3443. }
  3444. /* Add header length of indefinite item */
  3445. j += (word32)IndefItems_HeaderLen(indefItems);
  3446. if ((tag & 0xC0) == 0 &&
  3447. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3448. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3449. /* For basic type - get each child item and add data */
  3450. for (; i < berSz; ) {
  3451. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3452. if (tag == ASN_EOC) {
  3453. break;
  3454. }
  3455. if (der != NULL) {
  3456. if (j + length > *derSz) {
  3457. ret = BUFFER_E;
  3458. goto end;
  3459. }
  3460. XMEMCPY(der + j, ber + i, length);
  3461. }
  3462. j += length;
  3463. i += length;
  3464. }
  3465. }
  3466. /* Move to next indef item in list */
  3467. indefItems->idx++;
  3468. }
  3469. else if (tag == ASN_EOC) {
  3470. /* End-Of-Content is not written out in DER */
  3471. }
  3472. else {
  3473. /* Write out definite length item as is. */
  3474. i += length;
  3475. if (der != NULL) {
  3476. /* Ensure space for item */
  3477. if (j + i - start > *derSz) {
  3478. ret = BUFFER_E;
  3479. goto end;
  3480. }
  3481. /* Copy item as is */
  3482. XMEMCPY(der + j, ber + start, i - start);
  3483. }
  3484. j += i - start;
  3485. }
  3486. }
  3487. /* Return the length of the DER encoded ASN.1 */
  3488. *derSz = j;
  3489. if (der == NULL) {
  3490. ret = LENGTH_ONLY_E;
  3491. }
  3492. end:
  3493. #ifdef WOLFSSL_SMALL_STACK
  3494. if (indefItems != NULL) {
  3495. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3496. }
  3497. #endif
  3498. return ret;
  3499. }
  3500. #endif
  3501. #ifndef WOLFSSL_ASN_TEMPLATE
  3502. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3503. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3504. *
  3505. * val 16-bit value to encode.
  3506. * output Buffer to write into.
  3507. * returns the number of bytes added to the buffer.
  3508. */
  3509. static word32 SetBitString16Bit(word16 val, byte* output)
  3510. {
  3511. word32 idx;
  3512. int len;
  3513. byte lastByte;
  3514. byte unusedBits = 0;
  3515. if ((val >> 8) != 0) {
  3516. len = 2;
  3517. lastByte = (byte)(val >> 8);
  3518. }
  3519. else {
  3520. len = 1;
  3521. lastByte = (byte)val;
  3522. }
  3523. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3524. unusedBits++;
  3525. idx = SetBitString((word32)len, unusedBits, output);
  3526. output[idx++] = (byte)val;
  3527. if (len > 1)
  3528. output[idx++] = (byte)(val >> 8);
  3529. return idx;
  3530. }
  3531. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3532. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3533. /* hashType */
  3534. #ifdef WOLFSSL_MD2
  3535. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3536. #endif
  3537. #ifndef NO_MD5
  3538. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3539. #endif
  3540. #ifndef NO_SHA
  3541. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3542. #endif
  3543. #ifdef WOLFSSL_SHA224
  3544. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3545. #endif
  3546. #ifndef NO_SHA256
  3547. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3548. #endif
  3549. #ifdef WOLFSSL_SHA384
  3550. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3551. #endif
  3552. #ifdef WOLFSSL_SHA512
  3553. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3554. #ifndef WOLFSSL_NOSHA512_224
  3555. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3556. #endif
  3557. #ifndef WOLFSSL_NOSHA512_256
  3558. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3559. #endif
  3560. #endif
  3561. #ifdef WOLFSSL_SHA3
  3562. #ifndef WOLFSSL_NOSHA3_224
  3563. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3564. #endif /* WOLFSSL_NOSHA3_224 */
  3565. #ifndef WOLFSSL_NOSHA3_256
  3566. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3567. #endif /* WOLFSSL_NOSHA3_256 */
  3568. #ifndef WOLFSSL_NOSHA3_384
  3569. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3570. #endif /* WOLFSSL_NOSHA3_384 */
  3571. #ifndef WOLFSSL_NOSHA3_512
  3572. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3573. #endif /* WOLFSSL_NOSHA3_512 */
  3574. #endif /* WOLFSSL_SHA3 */
  3575. /* hmacType */
  3576. #ifndef NO_HMAC
  3577. #ifdef WOLFSSL_SHA224
  3578. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3579. #endif
  3580. #ifndef NO_SHA256
  3581. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3582. #endif
  3583. #ifdef WOLFSSL_SHA384
  3584. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3585. #endif
  3586. #ifdef WOLFSSL_SHA512
  3587. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3588. #endif
  3589. #endif
  3590. /* sigType */
  3591. #if !defined(NO_DSA) && !defined(NO_SHA)
  3592. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3593. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3594. #endif /* NO_DSA */
  3595. #ifndef NO_RSA
  3596. #ifdef WOLFSSL_MD2
  3597. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3598. #endif
  3599. #ifndef NO_MD5
  3600. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3601. #endif
  3602. #ifndef NO_SHA
  3603. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3604. #endif
  3605. #ifdef WOLFSSL_SHA224
  3606. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3607. #endif
  3608. #ifndef NO_SHA256
  3609. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3610. #endif
  3611. #ifdef WOLFSSL_SHA384
  3612. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3613. #endif
  3614. #ifdef WOLFSSL_SHA512
  3615. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3616. #endif
  3617. #ifdef WOLFSSL_SHA3
  3618. #ifndef WOLFSSL_NOSHA3_224
  3619. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3620. #endif
  3621. #ifndef WOLFSSL_NOSHA3_256
  3622. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3623. #endif
  3624. #ifndef WOLFSSL_NOSHA3_384
  3625. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3626. #endif
  3627. #ifndef WOLFSSL_NOSHA3_512
  3628. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3629. #endif
  3630. #endif
  3631. #ifdef WC_RSA_PSS
  3632. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3633. #endif
  3634. #endif /* NO_RSA */
  3635. #ifdef HAVE_ECC
  3636. #ifndef NO_SHA
  3637. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3638. #endif
  3639. #ifdef WOLFSSL_SHA224
  3640. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3641. #endif
  3642. #ifndef NO_SHA256
  3643. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3644. #endif
  3645. #ifdef WOLFSSL_SHA384
  3646. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3647. #endif
  3648. #ifdef WOLFSSL_SHA512
  3649. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3650. #endif
  3651. #ifdef WOLFSSL_SHA3
  3652. #ifndef WOLFSSL_NOSHA3_224
  3653. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3654. #endif
  3655. #ifndef WOLFSSL_NOSHA3_256
  3656. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3657. #endif
  3658. #ifndef WOLFSSL_NOSHA3_384
  3659. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3660. #endif
  3661. #ifndef WOLFSSL_NOSHA3_512
  3662. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3663. #endif
  3664. #endif
  3665. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  3666. /* 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x75 */
  3667. static const byte sigSm3wSm2Oid[] = {42, 129, 28, 207, 85, 1, 131, 117};
  3668. #endif
  3669. #endif /* HAVE_ECC */
  3670. #ifdef HAVE_ED25519
  3671. static const byte sigEd25519Oid[] = {43, 101, 112};
  3672. #endif /* HAVE_ED25519 */
  3673. #ifdef HAVE_ED448
  3674. static const byte sigEd448Oid[] = {43, 101, 113};
  3675. #endif /* HAVE_ED448 */
  3676. #ifdef HAVE_PQC
  3677. #ifdef HAVE_FALCON
  3678. /* Falcon Level 1: 1 3 9999 3 1 */
  3679. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3680. /* Falcon Level 5: 1 3 9999 3 4 */
  3681. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3682. #endif /* HAVE_FACON */
  3683. #ifdef HAVE_DILITHIUM
  3684. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3685. static const byte sigDilithium_Level2Oid[] =
  3686. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3687. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3688. static const byte sigDilithium_Level3Oid[] =
  3689. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3690. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3691. static const byte sigDilithium_Level5Oid[] =
  3692. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3693. #endif /* HAVE_DILITHIUM */
  3694. #ifdef HAVE_SPHINCS
  3695. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3696. static const byte sigSphincsFast_Level1Oid[] =
  3697. {43, 206, 15, 6, 7, 4};
  3698. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3699. static const byte sigSphincsFast_Level3Oid[] =
  3700. {43, 206, 15, 6, 8, 3};
  3701. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3702. static const byte sigSphincsFast_Level5Oid[] =
  3703. {43, 206, 15, 6, 9, 3};
  3704. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3705. static const byte sigSphincsSmall_Level1Oid[] =
  3706. {43, 206, 15, 6, 7, 10};
  3707. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3708. static const byte sigSphincsSmall_Level3Oid[] =
  3709. {43, 206, 15, 6, 8, 7};
  3710. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3711. static const byte sigSphincsSmall_Level5Oid[] =
  3712. {43, 206, 15, 6, 9, 7};
  3713. #endif /* HAVE_SPHINCS */
  3714. #endif /* HAVE_PQC */
  3715. /* keyType */
  3716. #ifndef NO_DSA
  3717. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3718. #endif /* NO_DSA */
  3719. #ifndef NO_RSA
  3720. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3721. #ifdef WC_RSA_PSS
  3722. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3723. #endif
  3724. #endif /* NO_RSA */
  3725. #ifdef HAVE_ECC
  3726. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3727. #endif /* HAVE_ECC */
  3728. #ifdef HAVE_ED25519
  3729. static const byte keyEd25519Oid[] = {43, 101, 112};
  3730. #endif /* HAVE_ED25519 */
  3731. #ifdef HAVE_CURVE25519
  3732. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3733. #endif
  3734. #ifdef HAVE_ED448
  3735. static const byte keyEd448Oid[] = {43, 101, 113};
  3736. #endif /* HAVE_ED448 */
  3737. #ifdef HAVE_CURVE448
  3738. static const byte keyCurve448Oid[] = {43, 101, 111};
  3739. #endif /* HAVE_CURVE448 */
  3740. #ifndef NO_DH
  3741. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3742. #endif /* !NO_DH */
  3743. #ifdef HAVE_PQC
  3744. #ifdef HAVE_FALCON
  3745. /* Falcon Level 1: 1 3 9999 3 1 */
  3746. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3747. /* Falcon Level 5: 1 3 9999 3 4 */
  3748. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3749. #endif /* HAVE_FALCON */
  3750. #ifdef HAVE_DILITHIUM
  3751. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3752. static const byte keyDilithium_Level2Oid[] =
  3753. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3754. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3755. static const byte keyDilithium_Level3Oid[] =
  3756. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3757. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3758. static const byte keyDilithium_Level5Oid[] =
  3759. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3760. #endif /* HAVE_DILITHIUM */
  3761. #ifdef HAVE_SPHINCS
  3762. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3763. static const byte keySphincsFast_Level1Oid[] =
  3764. {43, 206, 15, 6, 7, 4};
  3765. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3766. static const byte keySphincsFast_Level3Oid[] =
  3767. {43, 206, 15, 6, 8, 3};
  3768. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3769. static const byte keySphincsFast_Level5Oid[] =
  3770. {43, 206, 15, 6, 9, 3};
  3771. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3772. static const byte keySphincsSmall_Level1Oid[] =
  3773. {43, 206, 15, 6, 7, 10};
  3774. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3775. static const byte keySphincsSmall_Level3Oid[] =
  3776. {43, 206, 15, 6, 8, 7};
  3777. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3778. static const byte keySphincsSmall_Level5Oid[] =
  3779. {43, 206, 15, 6, 9, 7};
  3780. #endif /* HAVE_SPHINCS */
  3781. #endif /* HAVE_PQC */
  3782. /* curveType */
  3783. #ifdef HAVE_ECC
  3784. /* See "ecc_sets" table in ecc.c */
  3785. #endif /* HAVE_ECC */
  3786. #ifdef HAVE_AES_CBC
  3787. /* blkType */
  3788. #ifdef WOLFSSL_AES_128
  3789. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3790. #endif
  3791. #ifdef WOLFSSL_AES_192
  3792. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3793. #endif
  3794. #ifdef WOLFSSL_AES_256
  3795. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3796. #endif
  3797. #endif /* HAVE_AES_CBC */
  3798. #ifdef HAVE_AESGCM
  3799. #ifdef WOLFSSL_AES_128
  3800. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3801. #endif
  3802. #ifdef WOLFSSL_AES_192
  3803. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3804. #endif
  3805. #ifdef WOLFSSL_AES_256
  3806. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3807. #endif
  3808. #endif /* HAVE_AESGCM */
  3809. #ifdef HAVE_AESCCM
  3810. #ifdef WOLFSSL_AES_128
  3811. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3812. #endif
  3813. #ifdef WOLFSSL_AES_192
  3814. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3815. #endif
  3816. #ifdef WOLFSSL_AES_256
  3817. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3818. #endif
  3819. #endif /* HAVE_AESCCM */
  3820. #ifndef NO_DES3
  3821. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3822. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3823. #endif
  3824. /* keyWrapType */
  3825. #ifdef WOLFSSL_AES_128
  3826. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3827. #endif
  3828. #ifdef WOLFSSL_AES_192
  3829. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3830. #endif
  3831. #ifdef WOLFSSL_AES_256
  3832. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3833. #endif
  3834. #ifdef HAVE_PKCS7
  3835. /* From RFC 3211 */
  3836. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3837. #endif
  3838. /* cmsKeyAgreeType */
  3839. #ifndef NO_SHA
  3840. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3841. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3842. #endif
  3843. #ifdef WOLFSSL_SHA224
  3844. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3845. #endif
  3846. #ifndef NO_SHA256
  3847. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3848. #endif
  3849. #ifdef WOLFSSL_SHA384
  3850. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3851. #endif
  3852. #ifdef WOLFSSL_SHA512
  3853. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3854. #endif
  3855. /* ocspType */
  3856. #ifdef HAVE_OCSP
  3857. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3858. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3859. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3860. #endif /* HAVE_OCSP */
  3861. /* certExtType */
  3862. static const byte extBasicCaOid[] = {85, 29, 19};
  3863. static const byte extAltNamesOid[] = {85, 29, 17};
  3864. static const byte extCrlDistOid[] = {85, 29, 31};
  3865. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3866. static const byte extAuthKeyOid[] = {85, 29, 35};
  3867. static const byte extSubjKeyOid[] = {85, 29, 14};
  3868. static const byte extCertPolicyOid[] = {85, 29, 32};
  3869. static const byte extKeyUsageOid[] = {85, 29, 15};
  3870. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3871. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3872. #ifndef IGNORE_NAME_CONSTRAINTS
  3873. static const byte extNameConsOid[] = {85, 29, 30};
  3874. #endif
  3875. #ifdef HAVE_CRL
  3876. static const byte extCrlNumberOid[] = {85, 29, 20};
  3877. #endif
  3878. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3879. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  3880. #endif
  3881. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3882. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  3883. #endif
  3884. /* certAuthInfoType */
  3885. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3886. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3887. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3888. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  3889. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  3890. /* certPolicyType */
  3891. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3892. #ifdef WOLFSSL_FPKI
  3893. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  3894. static const byte extCertPolicyFpkiCommonAuthOid[] =
  3895. CERT_POLICY_TYPE_OID_BASE(13);
  3896. static const byte extCertPolicyFpkiPivAuthOid[] =
  3897. CERT_POLICY_TYPE_OID_BASE(40);
  3898. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  3899. CERT_POLICY_TYPE_OID_BASE(41);
  3900. static const byte extCertPolicyFpkiPiviAuthOid[] =
  3901. CERT_POLICY_TYPE_OID_BASE(45);
  3902. #endif /* WOLFSSL_FPKI */
  3903. /* certAltNameType */
  3904. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3905. /* certKeyUseType */
  3906. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3907. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3908. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3909. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3910. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3911. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3912. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3913. #ifdef WOLFSSL_WOLFSSH
  3914. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  3915. static const byte extExtKeyUsageSshClientAuthOid[] =
  3916. EXT_KEY_USAGE_OID_BASE(21);
  3917. static const byte extExtKeyUsageSshMSCLOid[] =
  3918. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  3919. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  3920. {43, 6, 1, 5, 2, 3, 4};
  3921. #endif /* WOLFSSL_WOLFSSH */
  3922. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3923. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  3924. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  3925. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  3926. static const byte extSubjDirAttrGenderOid[] =
  3927. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  3928. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  3929. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  3930. #endif
  3931. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3932. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  3933. defined(OPENSSL_EXTRA_X509_SMALL)
  3934. /* csrAttrType */
  3935. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  3936. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3937. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3938. defined(WOLFSSL_ASN_TEMPLATE)
  3939. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  3940. #endif
  3941. #ifdef WOLFSSL_CERT_REQ
  3942. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  3943. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  3944. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  3945. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  3946. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3947. static const byte attrDnQualifier[] = {85, 4, 46};
  3948. static const byte attrInitals[] = {85, 4, 43};
  3949. static const byte attrSurname[] = {85, 4, 4};
  3950. static const byte attrGivenName[] = {85, 4, 42};
  3951. #endif
  3952. #endif
  3953. /* kdfType */
  3954. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3955. /* PKCS5 */
  3956. #if !defined(NO_DES3) && !defined(NO_MD5)
  3957. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3958. #endif
  3959. #if !defined(NO_DES3) && !defined(NO_SHA)
  3960. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3961. #endif
  3962. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3963. /* PKCS12 */
  3964. #if !defined(NO_RC4) && !defined(NO_SHA)
  3965. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3966. #endif
  3967. #if !defined(NO_DES3) && !defined(NO_SHA)
  3968. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3969. #endif
  3970. #if defined(WC_RC2) && !defined(NO_SHA)
  3971. static const byte pbe40Rc2Cbc[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 6};
  3972. #endif
  3973. #ifdef HAVE_LIBZ
  3974. /* zlib compression */
  3975. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3976. #endif
  3977. #ifdef WOLFSSL_APACHE_HTTPD
  3978. /* tlsExtType */
  3979. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3980. /* certNameType */
  3981. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3982. #endif
  3983. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3984. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3985. defined(WOLFSSL_ASN_TEMPLATE)
  3986. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  3987. #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
  3988. static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
  3989. static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
  3990. #endif
  3991. #if defined(WOLFSSL_CERT_GEN) || \
  3992. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3993. defined(WOLFSSL_ASN_TEMPLATE)
  3994. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  3995. #endif
  3996. /* Looks up the ID/type of an OID.
  3997. *
  3998. * When known returns the OID as a byte array and its length.
  3999. * ID-type are unique.
  4000. *
  4001. * Use oidIgnoreType to autofail.
  4002. *
  4003. * @param [in] id OID id.
  4004. * @param [in] type Type of OID (enum Oid_Types).
  4005. * @param [out] oidSz Length of OID byte array returned.
  4006. * @return Array of bytes for the OID.
  4007. * @return NULL when ID/type not recognized.
  4008. */
  4009. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  4010. {
  4011. const byte* oid = NULL;
  4012. *oidSz = 0;
  4013. switch (type) {
  4014. case oidHashType:
  4015. switch (id) {
  4016. #ifdef WOLFSSL_MD2
  4017. case MD2h:
  4018. oid = hashMd2hOid;
  4019. *oidSz = sizeof(hashMd2hOid);
  4020. break;
  4021. #endif
  4022. #ifndef NO_MD5
  4023. case MD5h:
  4024. oid = hashMd5hOid;
  4025. *oidSz = sizeof(hashMd5hOid);
  4026. break;
  4027. #endif
  4028. #ifndef NO_SHA
  4029. case SHAh:
  4030. oid = hashSha1hOid;
  4031. *oidSz = sizeof(hashSha1hOid);
  4032. break;
  4033. #endif
  4034. #ifdef WOLFSSL_SHA224
  4035. case SHA224h:
  4036. oid = hashSha224hOid;
  4037. *oidSz = sizeof(hashSha224hOid);
  4038. break;
  4039. #endif
  4040. #ifndef NO_SHA256
  4041. case SHA256h:
  4042. oid = hashSha256hOid;
  4043. *oidSz = sizeof(hashSha256hOid);
  4044. break;
  4045. #endif
  4046. #ifdef WOLFSSL_SHA384
  4047. case SHA384h:
  4048. oid = hashSha384hOid;
  4049. *oidSz = sizeof(hashSha384hOid);
  4050. break;
  4051. #endif
  4052. #ifdef WOLFSSL_SHA512
  4053. #ifndef WOLFSSL_NOSHA512_224
  4054. case SHA512_224h:
  4055. oid = hashSha512_224hOid;
  4056. *oidSz = sizeof(hashSha512_224hOid);
  4057. break;
  4058. #endif
  4059. #ifndef WOLFSSL_NOSHA512_256
  4060. case SHA512_256h:
  4061. oid = hashSha512_256hOid;
  4062. *oidSz = sizeof(hashSha512_256hOid);
  4063. break;
  4064. #endif
  4065. case SHA512h:
  4066. oid = hashSha512hOid;
  4067. *oidSz = sizeof(hashSha512hOid);
  4068. break;
  4069. #endif
  4070. #ifdef WOLFSSL_SHA3
  4071. #ifndef WOLFSSL_NOSHA3_224
  4072. case SHA3_224h:
  4073. oid = hashSha3_224hOid;
  4074. *oidSz = sizeof(hashSha3_224hOid);
  4075. break;
  4076. #endif /* WOLFSSL_NOSHA3_224 */
  4077. #ifndef WOLFSSL_NOSHA3_256
  4078. case SHA3_256h:
  4079. oid = hashSha3_256hOid;
  4080. *oidSz = sizeof(hashSha3_256hOid);
  4081. break;
  4082. #endif /* WOLFSSL_NOSHA3_256 */
  4083. #ifndef WOLFSSL_NOSHA3_384
  4084. case SHA3_384h:
  4085. oid = hashSha3_384hOid;
  4086. *oidSz = sizeof(hashSha3_384hOid);
  4087. break;
  4088. #endif /* WOLFSSL_NOSHA3_384 */
  4089. #ifndef WOLFSSL_NOSHA3_512
  4090. case SHA3_512h:
  4091. oid = hashSha3_512hOid;
  4092. *oidSz = sizeof(hashSha3_512hOid);
  4093. break;
  4094. #endif /* WOLFSSL_NOSHA3_512 */
  4095. #endif /* WOLFSSL_SHA3 */
  4096. default:
  4097. break;
  4098. }
  4099. break;
  4100. case oidSigType:
  4101. switch (id) {
  4102. #if !defined(NO_DSA) && !defined(NO_SHA)
  4103. case CTC_SHAwDSA:
  4104. oid = sigSha1wDsaOid;
  4105. *oidSz = sizeof(sigSha1wDsaOid);
  4106. break;
  4107. case CTC_SHA256wDSA:
  4108. oid = sigSha256wDsaOid;
  4109. *oidSz = sizeof(sigSha256wDsaOid);
  4110. break;
  4111. #endif /* NO_DSA */
  4112. #ifndef NO_RSA
  4113. #ifdef WOLFSSL_MD2
  4114. case CTC_MD2wRSA:
  4115. oid = sigMd2wRsaOid;
  4116. *oidSz = sizeof(sigMd2wRsaOid);
  4117. break;
  4118. #endif
  4119. #ifndef NO_MD5
  4120. case CTC_MD5wRSA:
  4121. oid = sigMd5wRsaOid;
  4122. *oidSz = sizeof(sigMd5wRsaOid);
  4123. break;
  4124. #endif
  4125. #ifndef NO_SHA
  4126. case CTC_SHAwRSA:
  4127. oid = sigSha1wRsaOid;
  4128. *oidSz = sizeof(sigSha1wRsaOid);
  4129. break;
  4130. #endif
  4131. #ifdef WOLFSSL_SHA224
  4132. case CTC_SHA224wRSA:
  4133. oid = sigSha224wRsaOid;
  4134. *oidSz = sizeof(sigSha224wRsaOid);
  4135. break;
  4136. #endif
  4137. #ifndef NO_SHA256
  4138. case CTC_SHA256wRSA:
  4139. oid = sigSha256wRsaOid;
  4140. *oidSz = sizeof(sigSha256wRsaOid);
  4141. break;
  4142. #endif
  4143. #ifdef WOLFSSL_SHA384
  4144. case CTC_SHA384wRSA:
  4145. oid = sigSha384wRsaOid;
  4146. *oidSz = sizeof(sigSha384wRsaOid);
  4147. break;
  4148. #endif
  4149. #ifdef WOLFSSL_SHA512
  4150. case CTC_SHA512wRSA:
  4151. oid = sigSha512wRsaOid;
  4152. *oidSz = sizeof(sigSha512wRsaOid);
  4153. break;
  4154. #endif /* WOLFSSL_SHA512 */
  4155. #ifdef WOLFSSL_SHA3
  4156. #ifndef WOLFSSL_NOSHA3_224
  4157. case CTC_SHA3_224wRSA:
  4158. oid = sigSha3_224wRsaOid;
  4159. *oidSz = sizeof(sigSha3_224wRsaOid);
  4160. break;
  4161. #endif
  4162. #ifndef WOLFSSL_NOSHA3_256
  4163. case CTC_SHA3_256wRSA:
  4164. oid = sigSha3_256wRsaOid;
  4165. *oidSz = sizeof(sigSha3_256wRsaOid);
  4166. break;
  4167. #endif
  4168. #ifndef WOLFSSL_NOSHA3_384
  4169. case CTC_SHA3_384wRSA:
  4170. oid = sigSha3_384wRsaOid;
  4171. *oidSz = sizeof(sigSha3_384wRsaOid);
  4172. break;
  4173. #endif
  4174. #ifndef WOLFSSL_NOSHA3_512
  4175. case CTC_SHA3_512wRSA:
  4176. oid = sigSha3_512wRsaOid;
  4177. *oidSz = sizeof(sigSha3_512wRsaOid);
  4178. break;
  4179. #endif
  4180. #endif
  4181. #ifdef WC_RSA_PSS
  4182. case CTC_RSASSAPSS:
  4183. oid = sigRsaSsaPssOid;
  4184. *oidSz = sizeof(sigRsaSsaPssOid);
  4185. break;
  4186. #endif
  4187. #endif /* NO_RSA */
  4188. #ifdef HAVE_ECC
  4189. #ifndef NO_SHA
  4190. case CTC_SHAwECDSA:
  4191. oid = sigSha1wEcdsaOid;
  4192. *oidSz = sizeof(sigSha1wEcdsaOid);
  4193. break;
  4194. #endif
  4195. #ifdef WOLFSSL_SHA224
  4196. case CTC_SHA224wECDSA:
  4197. oid = sigSha224wEcdsaOid;
  4198. *oidSz = sizeof(sigSha224wEcdsaOid);
  4199. break;
  4200. #endif
  4201. #ifndef NO_SHA256
  4202. case CTC_SHA256wECDSA:
  4203. oid = sigSha256wEcdsaOid;
  4204. *oidSz = sizeof(sigSha256wEcdsaOid);
  4205. break;
  4206. #endif
  4207. #ifdef WOLFSSL_SHA384
  4208. case CTC_SHA384wECDSA:
  4209. oid = sigSha384wEcdsaOid;
  4210. *oidSz = sizeof(sigSha384wEcdsaOid);
  4211. break;
  4212. #endif
  4213. #ifdef WOLFSSL_SHA512
  4214. case CTC_SHA512wECDSA:
  4215. oid = sigSha512wEcdsaOid;
  4216. *oidSz = sizeof(sigSha512wEcdsaOid);
  4217. break;
  4218. #endif
  4219. #ifdef WOLFSSL_SHA3
  4220. #ifndef WOLFSSL_NOSHA3_224
  4221. case CTC_SHA3_224wECDSA:
  4222. oid = sigSha3_224wEcdsaOid;
  4223. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4224. break;
  4225. #endif
  4226. #ifndef WOLFSSL_NOSHA3_256
  4227. case CTC_SHA3_256wECDSA:
  4228. oid = sigSha3_256wEcdsaOid;
  4229. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4230. break;
  4231. #endif
  4232. #ifndef WOLFSSL_NOSHA3_384
  4233. case CTC_SHA3_384wECDSA:
  4234. oid = sigSha3_384wEcdsaOid;
  4235. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4236. break;
  4237. #endif
  4238. #ifndef WOLFSSL_NOSHA3_512
  4239. case CTC_SHA3_512wECDSA:
  4240. oid = sigSha3_512wEcdsaOid;
  4241. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4242. break;
  4243. #endif
  4244. #endif
  4245. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  4246. case CTC_SM3wSM2:
  4247. oid = sigSm3wSm2Oid;
  4248. *oidSz = sizeof(sigSm3wSm2Oid);
  4249. break;
  4250. #endif
  4251. #endif /* HAVE_ECC */
  4252. #ifdef HAVE_ED25519
  4253. case CTC_ED25519:
  4254. oid = sigEd25519Oid;
  4255. *oidSz = sizeof(sigEd25519Oid);
  4256. break;
  4257. #endif
  4258. #ifdef HAVE_ED448
  4259. case CTC_ED448:
  4260. oid = sigEd448Oid;
  4261. *oidSz = sizeof(sigEd448Oid);
  4262. break;
  4263. #endif
  4264. #ifdef HAVE_PQC
  4265. #ifdef HAVE_FALCON
  4266. case CTC_FALCON_LEVEL1:
  4267. oid = sigFalcon_Level1Oid;
  4268. *oidSz = sizeof(sigFalcon_Level1Oid);
  4269. break;
  4270. case CTC_FALCON_LEVEL5:
  4271. oid = sigFalcon_Level5Oid;
  4272. *oidSz = sizeof(sigFalcon_Level5Oid);
  4273. break;
  4274. #endif /* HAVE_FALCON */
  4275. #ifdef HAVE_DILITHIUM
  4276. case CTC_DILITHIUM_LEVEL2:
  4277. oid = sigDilithium_Level2Oid;
  4278. *oidSz = sizeof(sigDilithium_Level2Oid);
  4279. break;
  4280. case CTC_DILITHIUM_LEVEL3:
  4281. oid = sigDilithium_Level3Oid;
  4282. *oidSz = sizeof(sigDilithium_Level3Oid);
  4283. break;
  4284. case CTC_DILITHIUM_LEVEL5:
  4285. oid = sigDilithium_Level5Oid;
  4286. *oidSz = sizeof(sigDilithium_Level5Oid);
  4287. break;
  4288. #endif /* HAVE_DILITHIUM */
  4289. #ifdef HAVE_SPHINCS
  4290. case CTC_SPHINCS_FAST_LEVEL1:
  4291. oid = sigSphincsFast_Level1Oid;
  4292. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4293. break;
  4294. case CTC_SPHINCS_FAST_LEVEL3:
  4295. oid = sigSphincsFast_Level3Oid;
  4296. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4297. break;
  4298. case CTC_SPHINCS_FAST_LEVEL5:
  4299. oid = sigSphincsFast_Level5Oid;
  4300. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4301. break;
  4302. case CTC_SPHINCS_SMALL_LEVEL1:
  4303. oid = sigSphincsSmall_Level1Oid;
  4304. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4305. break;
  4306. case CTC_SPHINCS_SMALL_LEVEL3:
  4307. oid = sigSphincsSmall_Level3Oid;
  4308. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4309. break;
  4310. case CTC_SPHINCS_SMALL_LEVEL5:
  4311. oid = sigSphincsSmall_Level5Oid;
  4312. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4313. break;
  4314. #endif /* HAVE_SPHINCS */
  4315. #endif /* HAVE_PQC */
  4316. default:
  4317. break;
  4318. }
  4319. break;
  4320. case oidKeyType:
  4321. switch (id) {
  4322. #ifndef NO_DSA
  4323. case DSAk:
  4324. oid = keyDsaOid;
  4325. *oidSz = sizeof(keyDsaOid);
  4326. break;
  4327. #endif /* NO_DSA */
  4328. #ifndef NO_RSA
  4329. case RSAk:
  4330. oid = keyRsaOid;
  4331. *oidSz = sizeof(keyRsaOid);
  4332. break;
  4333. #ifdef WC_RSA_PSS
  4334. case RSAPSSk:
  4335. oid = keyRsaPssOid;
  4336. *oidSz = sizeof(keyRsaPssOid);
  4337. break;
  4338. #endif
  4339. #endif /* NO_RSA */
  4340. #ifdef HAVE_ECC
  4341. case ECDSAk:
  4342. oid = keyEcdsaOid;
  4343. *oidSz = sizeof(keyEcdsaOid);
  4344. break;
  4345. #endif /* HAVE_ECC */
  4346. #ifdef HAVE_ED25519
  4347. case ED25519k:
  4348. oid = keyEd25519Oid;
  4349. *oidSz = sizeof(keyEd25519Oid);
  4350. break;
  4351. #endif /* HAVE_ED25519 */
  4352. #ifdef HAVE_CURVE25519
  4353. case X25519k:
  4354. oid = keyCurve25519Oid;
  4355. *oidSz = sizeof(keyCurve25519Oid);
  4356. break;
  4357. #endif /* HAVE_CURVE25519 */
  4358. #ifdef HAVE_ED448
  4359. case ED448k:
  4360. oid = keyEd448Oid;
  4361. *oidSz = sizeof(keyEd448Oid);
  4362. break;
  4363. #endif /* HAVE_ED448 */
  4364. #ifdef HAVE_CURVE448
  4365. case X448k:
  4366. oid = keyCurve448Oid;
  4367. *oidSz = sizeof(keyCurve448Oid);
  4368. break;
  4369. #endif /* HAVE_CURVE448 */
  4370. #ifndef NO_DH
  4371. case DHk:
  4372. oid = keyDhOid;
  4373. *oidSz = sizeof(keyDhOid);
  4374. break;
  4375. #endif /* !NO_DH */
  4376. #ifdef HAVE_PQC
  4377. #ifdef HAVE_FALCON
  4378. case FALCON_LEVEL1k:
  4379. oid = keyFalcon_Level1Oid;
  4380. *oidSz = sizeof(keyFalcon_Level1Oid);
  4381. break;
  4382. case FALCON_LEVEL5k:
  4383. oid = keyFalcon_Level5Oid;
  4384. *oidSz = sizeof(keyFalcon_Level5Oid);
  4385. break;
  4386. #endif /* HAVE_FALCON */
  4387. #ifdef HAVE_DILITHIUM
  4388. case DILITHIUM_LEVEL2k:
  4389. oid = keyDilithium_Level2Oid;
  4390. *oidSz = sizeof(keyDilithium_Level2Oid);
  4391. break;
  4392. case DILITHIUM_LEVEL3k:
  4393. oid = keyDilithium_Level3Oid;
  4394. *oidSz = sizeof(keyDilithium_Level3Oid);
  4395. break;
  4396. case DILITHIUM_LEVEL5k:
  4397. oid = keyDilithium_Level5Oid;
  4398. *oidSz = sizeof(keyDilithium_Level5Oid);
  4399. break;
  4400. #endif /* HAVE_DILITHIUM */
  4401. #ifdef HAVE_SPHINCS
  4402. case SPHINCS_FAST_LEVEL1k:
  4403. oid = keySphincsFast_Level1Oid;
  4404. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4405. break;
  4406. case SPHINCS_FAST_LEVEL3k:
  4407. oid = keySphincsFast_Level3Oid;
  4408. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4409. break;
  4410. case SPHINCS_FAST_LEVEL5k:
  4411. oid = keySphincsFast_Level5Oid;
  4412. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4413. break;
  4414. case SPHINCS_SMALL_LEVEL1k:
  4415. oid = keySphincsSmall_Level1Oid;
  4416. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4417. break;
  4418. case SPHINCS_SMALL_LEVEL3k:
  4419. oid = keySphincsSmall_Level3Oid;
  4420. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4421. break;
  4422. case SPHINCS_SMALL_LEVEL5k:
  4423. oid = keySphincsSmall_Level5Oid;
  4424. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4425. break;
  4426. #endif /* HAVE_SPHINCS */
  4427. #endif /* HAVE_PQC */
  4428. default:
  4429. break;
  4430. }
  4431. break;
  4432. #ifdef HAVE_ECC
  4433. case oidCurveType:
  4434. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4435. WOLFSSL_MSG("ECC OID not found");
  4436. }
  4437. break;
  4438. #endif /* HAVE_ECC */
  4439. case oidBlkType:
  4440. switch (id) {
  4441. #ifdef HAVE_AES_CBC
  4442. #ifdef WOLFSSL_AES_128
  4443. case AES128CBCb:
  4444. oid = blkAes128CbcOid;
  4445. *oidSz = sizeof(blkAes128CbcOid);
  4446. break;
  4447. #endif
  4448. #ifdef WOLFSSL_AES_192
  4449. case AES192CBCb:
  4450. oid = blkAes192CbcOid;
  4451. *oidSz = sizeof(blkAes192CbcOid);
  4452. break;
  4453. #endif
  4454. #ifdef WOLFSSL_AES_256
  4455. case AES256CBCb:
  4456. oid = blkAes256CbcOid;
  4457. *oidSz = sizeof(blkAes256CbcOid);
  4458. break;
  4459. #endif
  4460. #endif /* HAVE_AES_CBC */
  4461. #ifdef HAVE_AESGCM
  4462. #ifdef WOLFSSL_AES_128
  4463. case AES128GCMb:
  4464. oid = blkAes128GcmOid;
  4465. *oidSz = sizeof(blkAes128GcmOid);
  4466. break;
  4467. #endif
  4468. #ifdef WOLFSSL_AES_192
  4469. case AES192GCMb:
  4470. oid = blkAes192GcmOid;
  4471. *oidSz = sizeof(blkAes192GcmOid);
  4472. break;
  4473. #endif
  4474. #ifdef WOLFSSL_AES_256
  4475. case AES256GCMb:
  4476. oid = blkAes256GcmOid;
  4477. *oidSz = sizeof(blkAes256GcmOid);
  4478. break;
  4479. #endif
  4480. #endif /* HAVE_AESGCM */
  4481. #ifdef HAVE_AESCCM
  4482. #ifdef WOLFSSL_AES_128
  4483. case AES128CCMb:
  4484. oid = blkAes128CcmOid;
  4485. *oidSz = sizeof(blkAes128CcmOid);
  4486. break;
  4487. #endif
  4488. #ifdef WOLFSSL_AES_192
  4489. case AES192CCMb:
  4490. oid = blkAes192CcmOid;
  4491. *oidSz = sizeof(blkAes192CcmOid);
  4492. break;
  4493. #endif
  4494. #ifdef WOLFSSL_AES_256
  4495. case AES256CCMb:
  4496. oid = blkAes256CcmOid;
  4497. *oidSz = sizeof(blkAes256CcmOid);
  4498. break;
  4499. #endif
  4500. #endif /* HAVE_AESCCM */
  4501. #ifndef NO_DES3
  4502. case DESb:
  4503. oid = blkDesCbcOid;
  4504. *oidSz = sizeof(blkDesCbcOid);
  4505. break;
  4506. case DES3b:
  4507. oid = blkDes3CbcOid;
  4508. *oidSz = sizeof(blkDes3CbcOid);
  4509. break;
  4510. #endif /* !NO_DES3 */
  4511. default:
  4512. break;
  4513. }
  4514. break;
  4515. #ifdef HAVE_OCSP
  4516. case oidOcspType:
  4517. switch (id) {
  4518. case OCSP_BASIC_OID:
  4519. oid = ocspBasicOid;
  4520. *oidSz = sizeof(ocspBasicOid);
  4521. break;
  4522. case OCSP_NONCE_OID:
  4523. oid = ocspNonceOid;
  4524. *oidSz = sizeof(ocspNonceOid);
  4525. break;
  4526. default:
  4527. break;
  4528. }
  4529. break;
  4530. #endif /* HAVE_OCSP */
  4531. case oidCertExtType:
  4532. switch (id) {
  4533. case BASIC_CA_OID:
  4534. oid = extBasicCaOid;
  4535. *oidSz = sizeof(extBasicCaOid);
  4536. break;
  4537. case ALT_NAMES_OID:
  4538. oid = extAltNamesOid;
  4539. *oidSz = sizeof(extAltNamesOid);
  4540. break;
  4541. case CRL_DIST_OID:
  4542. oid = extCrlDistOid;
  4543. *oidSz = sizeof(extCrlDistOid);
  4544. break;
  4545. case AUTH_INFO_OID:
  4546. oid = extAuthInfoOid;
  4547. *oidSz = sizeof(extAuthInfoOid);
  4548. break;
  4549. case AUTH_KEY_OID:
  4550. oid = extAuthKeyOid;
  4551. *oidSz = sizeof(extAuthKeyOid);
  4552. break;
  4553. case SUBJ_KEY_OID:
  4554. oid = extSubjKeyOid;
  4555. *oidSz = sizeof(extSubjKeyOid);
  4556. break;
  4557. case CERT_POLICY_OID:
  4558. oid = extCertPolicyOid;
  4559. *oidSz = sizeof(extCertPolicyOid);
  4560. break;
  4561. case KEY_USAGE_OID:
  4562. oid = extKeyUsageOid;
  4563. *oidSz = sizeof(extKeyUsageOid);
  4564. break;
  4565. case INHIBIT_ANY_OID:
  4566. oid = extInhibitAnyOid;
  4567. *oidSz = sizeof(extInhibitAnyOid);
  4568. break;
  4569. case EXT_KEY_USAGE_OID:
  4570. oid = extExtKeyUsageOid;
  4571. *oidSz = sizeof(extExtKeyUsageOid);
  4572. break;
  4573. #ifndef IGNORE_NAME_CONSTRAINTS
  4574. case NAME_CONS_OID:
  4575. oid = extNameConsOid;
  4576. *oidSz = sizeof(extNameConsOid);
  4577. break;
  4578. #endif
  4579. #ifdef HAVE_OCSP
  4580. case OCSP_NOCHECK_OID:
  4581. oid = ocspNoCheckOid;
  4582. *oidSz = sizeof(ocspNoCheckOid);
  4583. break;
  4584. #endif
  4585. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4586. case SUBJ_DIR_ATTR_OID:
  4587. oid = extSubjDirAttrOid;
  4588. *oidSz = sizeof(extSubjDirAttrOid);
  4589. break;
  4590. #endif
  4591. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4592. case SUBJ_INFO_ACC_OID:
  4593. oid = extSubjInfoAccessOid;
  4594. *oidSz = sizeof(extSubjInfoAccessOid);
  4595. break;
  4596. #endif
  4597. default:
  4598. break;
  4599. }
  4600. break;
  4601. case oidCrlExtType:
  4602. #ifdef HAVE_CRL
  4603. switch (id) {
  4604. case AUTH_KEY_OID:
  4605. oid = extAuthKeyOid;
  4606. *oidSz = sizeof(extAuthKeyOid);
  4607. break;
  4608. case CRL_NUMBER_OID:
  4609. oid = extCrlNumberOid;
  4610. *oidSz = sizeof(extCrlNumberOid);
  4611. break;
  4612. default:
  4613. break;
  4614. }
  4615. #endif
  4616. break;
  4617. case oidCertAuthInfoType:
  4618. switch (id) {
  4619. case AIA_OCSP_OID:
  4620. oid = extAuthInfoOcspOid;
  4621. *oidSz = sizeof(extAuthInfoOcspOid);
  4622. break;
  4623. case AIA_CA_ISSUER_OID:
  4624. oid = extAuthInfoCaIssuerOid;
  4625. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4626. break;
  4627. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4628. case AIA_CA_REPO_OID:
  4629. oid = extAuthInfoCaRespOid;
  4630. *oidSz = sizeof(extAuthInfoCaRespOid);
  4631. break;
  4632. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4633. default:
  4634. break;
  4635. }
  4636. break;
  4637. case oidCertPolicyType:
  4638. switch (id) {
  4639. case CP_ANY_OID:
  4640. oid = extCertPolicyAnyOid;
  4641. *oidSz = sizeof(extCertPolicyAnyOid);
  4642. break;
  4643. #if defined(WOLFSSL_FPKI)
  4644. case CP_FPKI_COMMON_AUTH_OID:
  4645. oid = extCertPolicyFpkiCommonAuthOid;
  4646. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4647. break;
  4648. case CP_FPKI_PIV_AUTH_OID:
  4649. oid = extCertPolicyFpkiPivAuthOid;
  4650. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4651. break;
  4652. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4653. oid = extCertPolicyFpkiPivAuthHwOid;
  4654. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4655. break;
  4656. case CP_FPKI_PIVI_AUTH_OID:
  4657. oid = extCertPolicyFpkiPiviAuthOid;
  4658. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4659. break;
  4660. #endif /* WOLFSSL_FPKI */
  4661. default:
  4662. break;
  4663. }
  4664. break;
  4665. case oidCertAltNameType:
  4666. switch (id) {
  4667. case HW_NAME_OID:
  4668. oid = extAltNamesHwNameOid;
  4669. *oidSz = sizeof(extAltNamesHwNameOid);
  4670. break;
  4671. default:
  4672. break;
  4673. }
  4674. break;
  4675. case oidCertKeyUseType:
  4676. switch (id) {
  4677. case EKU_ANY_OID:
  4678. oid = extExtKeyUsageAnyOid;
  4679. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4680. break;
  4681. case EKU_SERVER_AUTH_OID:
  4682. oid = extExtKeyUsageServerAuthOid;
  4683. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4684. break;
  4685. case EKU_CLIENT_AUTH_OID:
  4686. oid = extExtKeyUsageClientAuthOid;
  4687. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4688. break;
  4689. case EKU_CODESIGNING_OID:
  4690. oid = extExtKeyUsageCodeSigningOid;
  4691. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4692. break;
  4693. case EKU_EMAILPROTECT_OID:
  4694. oid = extExtKeyUsageEmailProtectOid;
  4695. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4696. break;
  4697. case EKU_TIMESTAMP_OID:
  4698. oid = extExtKeyUsageTimestampOid;
  4699. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4700. break;
  4701. case EKU_OCSP_SIGN_OID:
  4702. oid = extExtKeyUsageOcspSignOid;
  4703. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4704. break;
  4705. #ifdef WOLFSSL_WOLFSSH
  4706. case EKU_SSH_CLIENT_AUTH_OID:
  4707. oid = extExtKeyUsageSshClientAuthOid;
  4708. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4709. break;
  4710. case EKU_SSH_MSCL_OID:
  4711. oid = extExtKeyUsageSshMSCLOid;
  4712. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4713. break;
  4714. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4715. oid = extExtKeyUsageSshKpClientAuthOid;
  4716. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4717. break;
  4718. #endif /* WOLFSSL_WOLFSSH */
  4719. default:
  4720. break;
  4721. }
  4722. break;
  4723. case oidKdfType:
  4724. switch (id) {
  4725. case PBKDF2_OID:
  4726. oid = pbkdf2Oid;
  4727. *oidSz = sizeof(pbkdf2Oid);
  4728. break;
  4729. default:
  4730. break;
  4731. }
  4732. break;
  4733. case oidPBEType:
  4734. switch (id) {
  4735. #if !defined(NO_SHA) && !defined(NO_RC4)
  4736. case PBE_SHA1_RC4_128_SUM:
  4737. case PBE_SHA1_RC4_128:
  4738. oid = pbeSha1RC4128;
  4739. *oidSz = sizeof(pbeSha1RC4128);
  4740. break;
  4741. #endif
  4742. #if !defined(NO_MD5) && !defined(NO_DES3)
  4743. case PBE_MD5_DES_SUM:
  4744. case PBE_MD5_DES:
  4745. oid = pbeMd5Des;
  4746. *oidSz = sizeof(pbeMd5Des);
  4747. break;
  4748. #endif
  4749. #if !defined(NO_SHA) && !defined(NO_DES3)
  4750. case PBE_SHA1_DES_SUM:
  4751. case PBE_SHA1_DES:
  4752. oid = pbeSha1Des;
  4753. *oidSz = sizeof(pbeSha1Des);
  4754. break;
  4755. #endif
  4756. #if !defined(NO_SHA) && !defined(NO_DES3)
  4757. case PBE_SHA1_DES3_SUM:
  4758. case PBE_SHA1_DES3:
  4759. oid = pbeSha1Des3;
  4760. *oidSz = sizeof(pbeSha1Des3);
  4761. break;
  4762. #endif
  4763. #if !defined(NO_SHA) && defined(WC_RC2)
  4764. case PBE_SHA1_40RC2_CBC_SUM:
  4765. case PBE_SHA1_40RC2_CBC:
  4766. oid = pbe40Rc2Cbc;
  4767. *oidSz = sizeof(pbe40Rc2Cbc);
  4768. break;
  4769. #endif
  4770. case PBES2_SUM:
  4771. case PBES2:
  4772. oid = pbes2;
  4773. *oidSz = sizeof(pbes2);
  4774. break;
  4775. default:
  4776. break;
  4777. }
  4778. break;
  4779. case oidKeyWrapType:
  4780. switch (id) {
  4781. #ifdef WOLFSSL_AES_128
  4782. case AES128_WRAP:
  4783. oid = wrapAes128Oid;
  4784. *oidSz = sizeof(wrapAes128Oid);
  4785. break;
  4786. #endif
  4787. #ifdef WOLFSSL_AES_192
  4788. case AES192_WRAP:
  4789. oid = wrapAes192Oid;
  4790. *oidSz = sizeof(wrapAes192Oid);
  4791. break;
  4792. #endif
  4793. #ifdef WOLFSSL_AES_256
  4794. case AES256_WRAP:
  4795. oid = wrapAes256Oid;
  4796. *oidSz = sizeof(wrapAes256Oid);
  4797. break;
  4798. #endif
  4799. #ifdef HAVE_PKCS7
  4800. case PWRI_KEK_WRAP:
  4801. oid = wrapPwriKekOid;
  4802. *oidSz = sizeof(wrapPwriKekOid);
  4803. break;
  4804. #endif
  4805. default:
  4806. break;
  4807. }
  4808. break;
  4809. case oidCmsKeyAgreeType:
  4810. switch (id) {
  4811. #ifndef NO_SHA
  4812. case dhSinglePass_stdDH_sha1kdf_scheme:
  4813. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4814. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4815. break;
  4816. #endif
  4817. #ifdef WOLFSSL_SHA224
  4818. case dhSinglePass_stdDH_sha224kdf_scheme:
  4819. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4820. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4821. break;
  4822. #endif
  4823. #ifndef NO_SHA256
  4824. case dhSinglePass_stdDH_sha256kdf_scheme:
  4825. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4826. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4827. break;
  4828. #endif
  4829. #ifdef WOLFSSL_SHA384
  4830. case dhSinglePass_stdDH_sha384kdf_scheme:
  4831. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4832. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4833. break;
  4834. #endif
  4835. #ifdef WOLFSSL_SHA512
  4836. case dhSinglePass_stdDH_sha512kdf_scheme:
  4837. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4838. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4839. break;
  4840. #endif
  4841. default:
  4842. break;
  4843. }
  4844. break;
  4845. #ifndef NO_HMAC
  4846. case oidHmacType:
  4847. switch (id) {
  4848. #ifdef WOLFSSL_SHA224
  4849. case HMAC_SHA224_OID:
  4850. oid = hmacSha224Oid;
  4851. *oidSz = sizeof(hmacSha224Oid);
  4852. break;
  4853. #endif
  4854. #ifndef NO_SHA256
  4855. case HMAC_SHA256_OID:
  4856. oid = hmacSha256Oid;
  4857. *oidSz = sizeof(hmacSha256Oid);
  4858. break;
  4859. #endif
  4860. #ifdef WOLFSSL_SHA384
  4861. case HMAC_SHA384_OID:
  4862. oid = hmacSha384Oid;
  4863. *oidSz = sizeof(hmacSha384Oid);
  4864. break;
  4865. #endif
  4866. #ifdef WOLFSSL_SHA512
  4867. case HMAC_SHA512_OID:
  4868. oid = hmacSha512Oid;
  4869. *oidSz = sizeof(hmacSha512Oid);
  4870. break;
  4871. #endif
  4872. default:
  4873. break;
  4874. }
  4875. break;
  4876. #endif /* !NO_HMAC */
  4877. #ifdef HAVE_LIBZ
  4878. case oidCompressType:
  4879. switch (id) {
  4880. case ZLIBc:
  4881. oid = zlibCompress;
  4882. *oidSz = sizeof(zlibCompress);
  4883. break;
  4884. default:
  4885. break;
  4886. }
  4887. break;
  4888. #endif /* HAVE_LIBZ */
  4889. #ifdef WOLFSSL_APACHE_HTTPD
  4890. case oidCertNameType:
  4891. switch (id) {
  4892. case NID_id_on_dnsSRV:
  4893. oid = dnsSRVOid;
  4894. *oidSz = sizeof(dnsSRVOid);
  4895. break;
  4896. default:
  4897. break;
  4898. }
  4899. break;
  4900. case oidTlsExtType:
  4901. switch (id) {
  4902. case TLS_FEATURE_OID:
  4903. oid = tlsFeatureOid;
  4904. *oidSz = sizeof(tlsFeatureOid);
  4905. break;
  4906. default:
  4907. break;
  4908. }
  4909. break;
  4910. #endif /* WOLFSSL_APACHE_HTTPD */
  4911. #ifdef WOLFSSL_CERT_REQ
  4912. case oidCsrAttrType:
  4913. switch (id) {
  4914. case GIVEN_NAME_OID:
  4915. oid = attrGivenName;
  4916. *oidSz = sizeof(attrGivenName);
  4917. break;
  4918. case SURNAME_OID:
  4919. oid = attrSurname;
  4920. *oidSz = sizeof(attrSurname);
  4921. break;
  4922. case INITIALS_OID:
  4923. oid = attrInitals;
  4924. *oidSz = sizeof(attrInitals);
  4925. break;
  4926. case DNQUALIFIER_OID:
  4927. oid = attrDnQualifier;
  4928. *oidSz = sizeof(attrDnQualifier);
  4929. break;
  4930. case UNSTRUCTURED_NAME_OID:
  4931. oid = attrUnstructuredNameOid;
  4932. *oidSz = sizeof(attrUnstructuredNameOid);
  4933. break;
  4934. case PKCS9_CONTENT_TYPE_OID:
  4935. oid = attrPkcs9ContentTypeOid;
  4936. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4937. break;
  4938. case CHALLENGE_PASSWORD_OID:
  4939. oid = attrChallengePasswordOid;
  4940. *oidSz = sizeof(attrChallengePasswordOid);
  4941. break;
  4942. case SERIAL_NUMBER_OID:
  4943. oid = attrSerialNumberOid;
  4944. *oidSz = sizeof(attrSerialNumberOid);
  4945. break;
  4946. case USER_ID_OID:
  4947. oid = uidOid;
  4948. *oidSz = sizeof(uidOid);
  4949. break;
  4950. case EXTENSION_REQUEST_OID:
  4951. oid = attrExtensionRequestOid;
  4952. *oidSz = sizeof(attrExtensionRequestOid);
  4953. break;
  4954. default:
  4955. break;
  4956. }
  4957. break;
  4958. #endif
  4959. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4960. case oidSubjDirAttrType:
  4961. switch (id) {
  4962. case SDA_DOB_OID:
  4963. oid = extSubjDirAttrDobOid;
  4964. *oidSz = sizeof(extSubjDirAttrDobOid);
  4965. break;
  4966. case SDA_POB_OID:
  4967. oid = extSubjDirAttrPobOid;
  4968. *oidSz = sizeof(extSubjDirAttrPobOid);
  4969. break;
  4970. case SDA_GENDER_OID:
  4971. oid = extSubjDirAttrGenderOid;
  4972. *oidSz = sizeof(extSubjDirAttrGenderOid);
  4973. break;
  4974. case SDA_COC_OID:
  4975. oid = extSubjDirAttrCocOid;
  4976. *oidSz = sizeof(extSubjDirAttrCocOid);
  4977. break;
  4978. case SDA_COR_OID:
  4979. oid = extSubjDirAttrCorOid;
  4980. *oidSz = sizeof(extSubjDirAttrCorOid);
  4981. break;
  4982. default:
  4983. break;
  4984. }
  4985. break;
  4986. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  4987. case oidIgnoreType:
  4988. default:
  4989. break;
  4990. }
  4991. return oid;
  4992. }
  4993. #ifdef HAVE_ECC
  4994. /* Check the OID id is for a known elliptic curve.
  4995. *
  4996. * @param [in] oid OID id.
  4997. * @return ECC set id on success.
  4998. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  4999. */
  5000. static int CheckCurve(word32 oid)
  5001. {
  5002. int ret;
  5003. word32 oidSz;
  5004. /* Lookup OID id. */
  5005. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  5006. /* Check for error or zero length OID size (can't get OID for encoding). */
  5007. if ((ret < 0) || (oidSz == 0)) {
  5008. WOLFSSL_MSG("CheckCurve not found");
  5009. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  5010. ret = ECC_CURVE_OID_E;
  5011. }
  5012. /* Return ECC set id or error code. */
  5013. return ret;
  5014. }
  5015. #endif
  5016. #ifdef HAVE_OID_ENCODING
  5017. /* Encode dotted form of OID into byte array version.
  5018. *
  5019. * @param [in] in Dotted form of OID.
  5020. * @param [in] inSz Count of numbers in dotted form.
  5021. * @param [in] out Buffer to hold OID.
  5022. * @param [in, out] outSz On in, size of buffer.
  5023. * On out, number of bytes in buffer.
  5024. * @return 0 on success
  5025. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5026. * @return BUFFER_E when buffer too small.
  5027. */
  5028. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5029. {
  5030. int i, x, len;
  5031. word32 d, t;
  5032. /* check args */
  5033. if (in == NULL || outSz == NULL) {
  5034. return BAD_FUNC_ARG;
  5035. }
  5036. /* compute length of encoded OID */
  5037. d = (in[0] * 40) + in[1];
  5038. len = 0;
  5039. for (i = 1; i < (int)inSz; i++) {
  5040. x = 0;
  5041. t = d;
  5042. while (t) {
  5043. x++;
  5044. t >>= 1;
  5045. }
  5046. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5047. if (i < (int)inSz - 1) {
  5048. d = in[i + 1];
  5049. }
  5050. }
  5051. if (out) {
  5052. /* verify length */
  5053. if ((int)*outSz < len) {
  5054. return BUFFER_E; /* buffer provided is not large enough */
  5055. }
  5056. /* calc first byte */
  5057. d = (in[0] * 40) + in[1];
  5058. /* encode bytes */
  5059. x = 0;
  5060. for (i = 1; i < (int)inSz; i++) {
  5061. if (d) {
  5062. int y = x, z;
  5063. byte mask = 0;
  5064. while (d) {
  5065. out[x++] = (byte)((d & 0x7F) | mask);
  5066. d >>= 7;
  5067. mask |= 0x80; /* upper bit is set on all but the last byte */
  5068. }
  5069. /* now swap bytes y...x-1 */
  5070. z = x - 1;
  5071. while (y < z) {
  5072. mask = out[y];
  5073. out[y] = out[z];
  5074. out[z] = mask;
  5075. ++y;
  5076. --z;
  5077. }
  5078. }
  5079. else {
  5080. out[x++] = 0x00; /* zero value */
  5081. }
  5082. /* next word */
  5083. if (i < (int)inSz - 1) {
  5084. d = in[i + 1];
  5085. }
  5086. }
  5087. }
  5088. /* return length */
  5089. *outSz = len;
  5090. return 0;
  5091. }
  5092. #endif /* HAVE_OID_ENCODING */
  5093. #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT)
  5094. /* Encode dotted form of OID into byte array version.
  5095. *
  5096. * @param [in] in Byte array containing OID.
  5097. * @param [in] inSz Size of OID in bytes.
  5098. * @param [in] out Array to hold dotted form of OID.
  5099. * @param [in, out] outSz On in, number of elements in array.
  5100. * On out, count of numbers in dotted form.
  5101. * @return 0 on success
  5102. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5103. * @return BUFFER_E when dotted form buffer too small.
  5104. */
  5105. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5106. {
  5107. int x = 0, y = 0;
  5108. word32 t = 0;
  5109. /* check args */
  5110. if (in == NULL || outSz == NULL) {
  5111. return BAD_FUNC_ARG;
  5112. }
  5113. /* decode bytes */
  5114. while (inSz--) {
  5115. t = (t << 7) | (in[x] & 0x7F);
  5116. if (!(in[x] & 0x80)) {
  5117. if (y >= (int)*outSz) {
  5118. return BUFFER_E;
  5119. }
  5120. if (y == 0) {
  5121. out[0] = (word16)(t / 40);
  5122. out[1] = (word16)(t % 40);
  5123. y = 2;
  5124. }
  5125. else {
  5126. out[y++] = (word16)t;
  5127. }
  5128. t = 0; /* reset tmp */
  5129. }
  5130. x++;
  5131. }
  5132. /* return length */
  5133. *outSz = (word32)y;
  5134. return 0;
  5135. }
  5136. #endif /* HAVE_OID_DECODING */
  5137. /* Decode the header of a BER/DER encoded OBJECT ID.
  5138. *
  5139. * @param [in] input Buffer holding DER/BER encoded data.
  5140. * @param [in, out] inOutIdx On in, starting index of header.
  5141. * On out, end of parsed header.
  5142. * @param [out] len Number of bytes in the ASN.1 data.
  5143. * @param [in] maxIdx Length of data in buffer.
  5144. * @return 0 on success.
  5145. * @return BUFFER_E when there is not enough data to parse.
  5146. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5147. */
  5148. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5149. {
  5150. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5151. if (ret > 0) {
  5152. /* Only return 0 on success. */
  5153. ret = 0;
  5154. }
  5155. return ret;
  5156. }
  5157. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5158. *
  5159. * When output is NULL, calculate the header length only.
  5160. *
  5161. * @param [in] len Length of OBJECT ID data in bytes.
  5162. * @param [out] output Buffer to write into.
  5163. * @return Number of bytes added to the buffer.
  5164. */
  5165. int SetObjectId(int len, byte* output)
  5166. {
  5167. int idx = 0;
  5168. if (output) {
  5169. /* Write out tag. */
  5170. output[idx] = ASN_OBJECT_ID;
  5171. }
  5172. /* Skip tag. */
  5173. idx += ASN_TAG_SZ;
  5174. /* Encode length - passing NULL for output will not encode. */
  5175. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  5176. /* Return index after header. */
  5177. return idx;
  5178. }
  5179. #ifdef ASN_DUMP_OID
  5180. /* Dump the OID information.
  5181. *
  5182. * Decode the OID too if function available.
  5183. *
  5184. * @param [in] oidData OID data from buffer.
  5185. * @param [in] oidSz Size of OID data in buffer.
  5186. * @param [in] oid OID id.
  5187. * @param [in] oidType Type of OID.
  5188. * @return 0 on success.
  5189. * @return BUFFER_E when not enough bytes for proper decode.
  5190. * (HAVE_OID_DECODING)
  5191. */
  5192. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5193. word32 oidType)
  5194. {
  5195. int ret = 0;
  5196. word32 i;
  5197. /* support for dumping OID information */
  5198. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5199. /* Dump bytes in decimal. */
  5200. for (i = 0; i < oidSz; i++) {
  5201. printf("%d, ", oidData[i]);
  5202. }
  5203. printf("\n");
  5204. /* Dump bytes in hexadecimal. */
  5205. for (i = 0; i < oidSz; i++) {
  5206. printf("%02x, ", oidData[i]);
  5207. }
  5208. printf("\n");
  5209. #ifdef HAVE_OID_DECODING
  5210. {
  5211. word16 decOid[MAX_OID_SZ];
  5212. word32 decOidSz = sizeof(decOid);
  5213. /* Decode the OID into dotted form. */
  5214. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5215. if (ret == 0) {
  5216. printf(" Decoded (Sz %d): ", decOidSz);
  5217. for (i=0; i<decOidSz; i++) {
  5218. printf("%d.", decOid[i]);
  5219. }
  5220. printf("\n");
  5221. }
  5222. else {
  5223. printf("DecodeObjectId failed: %d\n", ret);
  5224. }
  5225. }
  5226. #endif /* HAVE_OID_DECODING */
  5227. return ret;
  5228. }
  5229. #endif /* ASN_DUMP_OID */
  5230. /* Get the OID data and verify it is of the type specified when compiled in.
  5231. *
  5232. * @param [in] input Buffer holding OID.
  5233. * @param [in, out] inOutIdx On in, starting index of OID.
  5234. * On out, end of parsed OID.
  5235. * @param [out] oid OID id.
  5236. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5237. * not compile in check.
  5238. * @param [in] length Length of OID data in buffer.
  5239. * @return 0 on success.
  5240. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5241. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5242. * HAVE_OID_DECODING)
  5243. */
  5244. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5245. word32 oidType, int length)
  5246. {
  5247. int ret = 0;
  5248. word32 idx = *inOutIdx;
  5249. #ifndef NO_VERIFY_OID
  5250. word32 actualOidSz;
  5251. const byte* actualOid;
  5252. const byte* checkOid = NULL;
  5253. word32 checkOidSz;
  5254. #endif /* NO_VERIFY_OID */
  5255. #ifdef HAVE_PQC
  5256. word32 found_collision = 0;
  5257. #endif
  5258. (void)oidType;
  5259. *oid = 0;
  5260. #ifndef NO_VERIFY_OID
  5261. /* Keep references to OID data and length for check. */
  5262. actualOid = &input[idx];
  5263. actualOidSz = (word32)length;
  5264. #endif /* NO_VERIFY_OID */
  5265. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  5266. /* Since we are summing it up, there could be collisions...and indeed there
  5267. * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
  5268. *
  5269. * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
  5270. * 283 instead of 281; 282 is taken.
  5271. *
  5272. * These hacks will hopefully disappear when new standardized OIDs appear.
  5273. */
  5274. if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
  5275. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5276. found_collision = SPHINCS_FAST_LEVEL3k;
  5277. }
  5278. #endif /* HAVE_PQC */
  5279. /* Sum it up for now. */
  5280. while (length--) {
  5281. /* odd HC08 compiler behavior here when input[idx++] */
  5282. *oid += (word32)input[idx];
  5283. idx++;
  5284. }
  5285. #ifdef HAVE_PQC
  5286. if (found_collision) {
  5287. *oid = found_collision;
  5288. }
  5289. #endif /* HAVE_PQC */
  5290. /* Return the index after the OID data. */
  5291. *inOutIdx = idx;
  5292. #ifndef NO_VERIFY_OID
  5293. /* 'Ignore' type means we don't care which OID it is. */
  5294. if (oidType != oidIgnoreType) {
  5295. /* Get the OID data for the id-type. */
  5296. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5297. #if defined(WOLFSSL_FPKI)
  5298. /* Handle OID sum collision of
  5299. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5300. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5301. */
  5302. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5303. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5304. (XMEMCMP(actualOid, blkAes256CbcOid,
  5305. sizeof(blkAes256CbcOid)) == 0)) {
  5306. checkOid = blkAes256CbcOid;
  5307. checkOidSz = sizeof(blkAes256CbcOid);
  5308. }
  5309. #endif /* HAVE_AES_CBC */
  5310. #endif /* WOLFSSL_FPKI */
  5311. #ifdef ASN_DUMP_OID
  5312. /* Dump out the data for debug. */
  5313. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5314. #endif
  5315. /* TODO: Want to fail when checkOid is NULL.
  5316. * Can't as too many situations where unknown OID is to be
  5317. * supported. Extra parameter for must not be NULL?
  5318. */
  5319. /* Check that the OID data matches what we found for the OID id. */
  5320. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5321. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5322. WOLFSSL_MSG("OID Check Failed");
  5323. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5324. ret = ASN_UNKNOWN_OID_E;
  5325. }
  5326. }
  5327. #endif /* NO_VERIFY_OID */
  5328. return ret;
  5329. }
  5330. #ifdef WOLFSSL_ASN_TEMPLATE
  5331. /* ASN.1 template for an OBJECT_ID. */
  5332. static const ASNItem objectIdASN[] = {
  5333. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5334. };
  5335. enum {
  5336. OBJECTIDASN_IDX_OID = 0
  5337. };
  5338. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5339. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5340. #endif
  5341. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5342. *
  5343. * @param [in] input Buffer holding BER encoded data.
  5344. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5345. * On out, start of ASN.1 item after OBJECT_ID.
  5346. * @param [out] oid Id of OID in OBJECT_ID data.
  5347. * @param [in] oidType Type of OID to expect.
  5348. * @param [in] maxIdx Maximum index of data in buffer.
  5349. * @return 0 on success.
  5350. * @return ASN_PARSE_E when encoding is invalid.
  5351. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5352. */
  5353. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5354. word32 oidType, word32 maxIdx)
  5355. {
  5356. #ifndef WOLFSSL_ASN_TEMPLATE
  5357. int ret, length;
  5358. WOLFSSL_ENTER("GetObjectId");
  5359. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5360. if (ret != 0)
  5361. return ret;
  5362. return GetOID(input, inOutIdx, oid, oidType, length);
  5363. #else
  5364. ASNGetData dataASN[objectIdASN_Length];
  5365. int ret;
  5366. WOLFSSL_ENTER("GetObjectId");
  5367. /* Clear dynamic data and set OID type expected. */
  5368. XMEMSET(dataASN, 0, sizeof(dataASN));
  5369. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5370. /* Decode OBJECT_ID. */
  5371. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5372. inOutIdx, maxIdx);
  5373. if (ret == 0) {
  5374. /* Return the id/sum. */
  5375. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5376. }
  5377. return ret;
  5378. #endif /* WOLFSSL_ASN_TEMPLATE */
  5379. }
  5380. #ifndef WOLFSSL_ASN_TEMPLATE
  5381. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5382. {
  5383. word32 idx = *inOutIdx;
  5384. int length;
  5385. int ret;
  5386. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5387. if (ret != 0)
  5388. return ret;
  5389. idx += (word32)length;
  5390. *inOutIdx = idx;
  5391. return 0;
  5392. }
  5393. #endif
  5394. #ifdef WOLFSSL_ASN_TEMPLATE
  5395. /* ASN.1 template for an algorithm identifier. */
  5396. static const ASNItem algoIdASN[] = {
  5397. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5398. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5399. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5400. };
  5401. enum {
  5402. ALGOIDASN_IDX_SEQ = 0,
  5403. ALGOIDASN_IDX_OID,
  5404. ALGOIDASN_IDX_NULL
  5405. };
  5406. /* Number of items in ASN.1 template for an algorithm identifier. */
  5407. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5408. #endif
  5409. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5410. *
  5411. * NULL tag is skipped if present.
  5412. *
  5413. * @param [in] input Buffer holding BER encoded data.
  5414. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5415. * On out, start of ASN.1 item after algorithm id.
  5416. * @param [out] oid Id of OID in algorithm identifier data.
  5417. * @param [in] oidType Type of OID to expect.
  5418. * @param [in] maxIdx Maximum index of data in buffer.
  5419. * @return 0 on success.
  5420. * @return ASN_PARSE_E when encoding is invalid.
  5421. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5422. */
  5423. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5424. word32 oidType, word32 maxIdx)
  5425. {
  5426. #ifndef WOLFSSL_ASN_TEMPLATE
  5427. int length;
  5428. word32 idx = *inOutIdx;
  5429. int ret;
  5430. *oid = 0;
  5431. WOLFSSL_ENTER("GetAlgoId");
  5432. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5433. return ASN_PARSE_E;
  5434. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5435. return ASN_OBJECT_ID_E;
  5436. /* could have NULL tag and 0 terminator, but may not */
  5437. if (idx < maxIdx) {
  5438. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5439. byte tag;
  5440. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5441. if (tag == ASN_TAG_NULL) {
  5442. ret = GetASNNull(input, &idx, maxIdx);
  5443. if (ret != 0)
  5444. return ret;
  5445. }
  5446. }
  5447. }
  5448. *inOutIdx = idx;
  5449. return 0;
  5450. #else
  5451. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5452. int ret = 0;
  5453. WOLFSSL_ENTER("GetAlgoId");
  5454. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5455. if (ret == 0) {
  5456. /* Set OID type expected. */
  5457. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5458. /* Decode the algorithm identifier. */
  5459. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5460. inOutIdx, maxIdx);
  5461. }
  5462. if (ret == 0) {
  5463. /* Return the OID id/sum. */
  5464. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5465. }
  5466. FREE_ASNGETDATA(dataASN, NULL);
  5467. return ret;
  5468. #endif /* WOLFSSL_ASN_TEMPLATE */
  5469. }
  5470. #ifndef NO_RSA
  5471. #ifdef WC_RSA_PSS
  5472. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5473. /* Convert a hash OID to a hash type.
  5474. *
  5475. * @param [in] oid Hash OID.
  5476. * @param [out] type Hash type.
  5477. * @return 0 on success.
  5478. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5479. */
  5480. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5481. {
  5482. int ret = 0;
  5483. switch (oid) {
  5484. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5485. #ifdef WOLFSSL_SHA224
  5486. case SHA224h:
  5487. *type = WC_HASH_TYPE_SHA224;
  5488. break;
  5489. #endif
  5490. #ifndef NO_SHA256
  5491. case SHA256h:
  5492. *type = WC_HASH_TYPE_SHA256;
  5493. break;
  5494. #endif
  5495. #ifdef WOLFSSL_SHA384
  5496. case SHA384h:
  5497. *type = WC_HASH_TYPE_SHA384;
  5498. break;
  5499. #endif
  5500. #ifdef WOLFSSL_SHA512
  5501. case SHA512h:
  5502. *type = WC_HASH_TYPE_SHA512;
  5503. break;
  5504. /* TODO: SHA512_224h */
  5505. /* TODO: SHA512_256h */
  5506. #endif
  5507. default:
  5508. ret = ASN_PARSE_E;
  5509. break;
  5510. }
  5511. return ret;
  5512. }
  5513. /* Convert a hash OID to a MGF1 type.
  5514. *
  5515. * @param [in] oid Hash OID.
  5516. * @param [out] mgf MGF type.
  5517. * @return 0 on success.
  5518. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5519. */
  5520. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5521. {
  5522. int ret = 0;
  5523. switch (oid) {
  5524. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5525. #ifdef WOLFSSL_SHA224
  5526. case SHA224h:
  5527. *mgf = WC_MGF1SHA224;
  5528. break;
  5529. #endif
  5530. #ifndef NO_SHA256
  5531. case SHA256h:
  5532. *mgf = WC_MGF1SHA256;
  5533. break;
  5534. #endif
  5535. #ifdef WOLFSSL_SHA384
  5536. case SHA384h:
  5537. *mgf = WC_MGF1SHA384;
  5538. break;
  5539. #endif
  5540. #ifdef WOLFSSL_SHA512
  5541. case SHA512h:
  5542. *mgf = WC_MGF1SHA512;
  5543. break;
  5544. /* TODO: SHA512_224h */
  5545. /* TODO: SHA512_256h */
  5546. #endif
  5547. default:
  5548. ret = ASN_PARSE_E;
  5549. break;
  5550. }
  5551. return ret;
  5552. }
  5553. #ifndef NO_CERTS
  5554. /* Convert a hash OID to a fake signature OID.
  5555. *
  5556. * @param [in] oid Hash OID.
  5557. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5558. * @return 0 on success.
  5559. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5560. */
  5561. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5562. {
  5563. int ret = 0;
  5564. switch (oid) {
  5565. #ifndef NO_SHA
  5566. case WC_HASH_TYPE_SHA:
  5567. *sigOid = CTC_SHAwRSA;
  5568. break;
  5569. #endif
  5570. #ifdef WOLFSSL_SHA224
  5571. case WC_HASH_TYPE_SHA224:
  5572. *sigOid = CTC_SHA224wRSA;
  5573. break;
  5574. #endif
  5575. #ifndef NO_SHA256
  5576. case WC_HASH_TYPE_SHA256:
  5577. *sigOid = CTC_SHA256wRSA;
  5578. break;
  5579. #endif
  5580. #ifdef WOLFSSL_SHA384
  5581. case WC_HASH_TYPE_SHA384:
  5582. *sigOid = CTC_SHA384wRSA;
  5583. break;
  5584. #endif
  5585. #ifdef WOLFSSL_SHA512
  5586. case WC_HASH_TYPE_SHA512:
  5587. *sigOid = CTC_SHA512wRSA;
  5588. break;
  5589. #endif
  5590. /* TODO: SHA512_224h */
  5591. /* TODO: SHA512_256h */
  5592. /* Not supported by HashForSignature() */
  5593. default:
  5594. ret = ASN_PARSE_E;
  5595. break;
  5596. }
  5597. return ret;
  5598. }
  5599. #endif
  5600. #ifdef WOLFSSL_ASN_TEMPLATE
  5601. /* ASN tag for hashAlgorigthm. */
  5602. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5603. /* ASN tag for maskGenAlgorithm. */
  5604. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5605. /* ASN tag for saltLength. */
  5606. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5607. /* ASN tag for trailerField. */
  5608. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5609. /* ASN.1 template for RSA PSS parameters. */
  5610. static const ASNItem rsaPssParamsASN[] = {
  5611. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5612. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5613. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5614. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5615. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5616. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5617. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5618. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5619. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5620. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5621. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5622. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5623. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5624. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5625. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5626. };
  5627. enum {
  5628. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5629. RSAPSSPARAMSASN_IDX_HASH,
  5630. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5631. RSAPSSPARAMSASN_IDX_HASHOID,
  5632. RSAPSSPARAMSASN_IDX_HASHNULL,
  5633. RSAPSSPARAMSASN_IDX_MGF,
  5634. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5635. RSAPSSPARAMSASN_IDX_MGFOID,
  5636. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5637. RSAPSSPARAMSASN_IDX_MGFHOID,
  5638. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5639. RSAPSSPARAMSASN_IDX_SALTLEN,
  5640. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5641. RSAPSSPARAMSASN_IDX_TRAILER,
  5642. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5643. };
  5644. /* Number of items in ASN.1 template for an algorithm identifier. */
  5645. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5646. #else
  5647. /* ASN tag for hashAlgorigthm. */
  5648. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5649. /* ASN tag for maskGenAlgorithm. */
  5650. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5651. /* ASN tag for saltLength. */
  5652. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5653. /* ASN tag for trailerField. */
  5654. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5655. #endif
  5656. /* Decode the RSA PSS parameters.
  5657. *
  5658. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5659. * @param [in] sz Size of data in buffer in bytes.
  5660. * @param [out] hash Hash algorithm to use on message.
  5661. * @param [out] mgf MGF algorithm to use with PSS padding.
  5662. * @param [out] saltLen Length of salt in PSS padding.
  5663. * @return BAD_FUNC_ARG when the params is NULL.
  5664. * @return ASN_PARSE_E when the decoding fails.
  5665. * @return 0 on success.
  5666. */
  5667. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5668. enum wc_HashType* hash, int* mgf, int* saltLen)
  5669. {
  5670. #ifndef WOLFSSL_ASN_TEMPLATE
  5671. int ret = 0;
  5672. word32 idx = 0;
  5673. int len = 0;
  5674. word32 oid = 0;
  5675. byte tag;
  5676. int length;
  5677. if (params == NULL) {
  5678. ret = BAD_FUNC_ARG;
  5679. }
  5680. if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
  5681. ret = ASN_PARSE_E;
  5682. }
  5683. if (ret == 0) {
  5684. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5685. /* Hash algorithm to use on message. */
  5686. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5687. ret = ASN_PARSE_E;
  5688. }
  5689. if (ret == 0) {
  5690. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5691. ret = ASN_PARSE_E;
  5692. }
  5693. }
  5694. if (ret == 0) {
  5695. ret = RsaPssHashOidToType(oid, hash);
  5696. }
  5697. }
  5698. else {
  5699. /* Default hash algorithm. */
  5700. *hash = WC_HASH_TYPE_SHA;
  5701. }
  5702. }
  5703. if (ret == 0) {
  5704. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5705. /* MGF and hash algorithm to use with padding. */
  5706. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5707. ret = ASN_PARSE_E;
  5708. }
  5709. if (ret == 0) {
  5710. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5711. ret = ASN_PARSE_E;
  5712. }
  5713. }
  5714. if ((ret == 0) && (oid != MGF1_OID)) {
  5715. ret = ASN_PARSE_E;
  5716. }
  5717. if (ret == 0) {
  5718. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5719. if (ret == 0) {
  5720. ret = RsaPssHashOidToMgf1(oid, mgf);
  5721. }
  5722. }
  5723. }
  5724. else {
  5725. /* Default MGF/Hash algorithm. */
  5726. *mgf = WC_MGF1SHA1;
  5727. }
  5728. }
  5729. if (ret == 0) {
  5730. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5731. /* Salt length to use with padding. */
  5732. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5733. ret = ASN_PARSE_E;
  5734. }
  5735. if (ret == 0) {
  5736. ret = GetInteger16Bit(params, &idx, sz);
  5737. if (ret >= 0) {
  5738. *saltLen = ret;
  5739. ret = 0;
  5740. }
  5741. }
  5742. }
  5743. else {
  5744. /* Default salt length. */
  5745. *saltLen = 20;
  5746. }
  5747. }
  5748. if (ret == 0) {
  5749. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5750. /* Unused - trialerField. */
  5751. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5752. ret = ASN_PARSE_E;
  5753. }
  5754. if (ret == 0) {
  5755. ret = GetInteger16Bit(params, &idx, sz);
  5756. if (ret > 0) {
  5757. ret = 0;
  5758. }
  5759. }
  5760. }
  5761. }
  5762. if ((ret == 0) && (idx != sz)) {
  5763. ret = ASN_PARSE_E;
  5764. }
  5765. return ret;
  5766. #else
  5767. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5768. int ret = 0;
  5769. word16 sLen = 20;
  5770. if (params == NULL) {
  5771. ret = BAD_FUNC_ARG;
  5772. }
  5773. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5774. if (ret == 0) {
  5775. word32 inOutIdx = 0;
  5776. /* Default values. */
  5777. *hash = WC_HASH_TYPE_SHA;
  5778. *mgf = WC_MGF1SHA1;
  5779. /* Set OID type expected. */
  5780. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5781. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5782. /* Place the salt length into 16-bit var sLen. */
  5783. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5784. /* Decode the algorithm identifier. */
  5785. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5786. params, &inOutIdx, sz);
  5787. }
  5788. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5789. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5790. ret = RsaPssHashOidToType(oid, hash);
  5791. }
  5792. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5793. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5794. ret = RsaPssHashOidToMgf1(oid, mgf);
  5795. }
  5796. if (ret == 0) {
  5797. *saltLen = sLen;
  5798. }
  5799. FREE_ASNGETDATA(dataASN, NULL);
  5800. return ret;
  5801. #endif /* WOLFSSL_ASN_TEMPLATE */
  5802. }
  5803. #endif /* WC_RSA_PSS */
  5804. #ifndef HAVE_USER_RSA
  5805. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5806. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5807. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5808. /* Byte offset of numbers in RSA key. */
  5809. size_t rsaIntOffset[] = {
  5810. OFFSETOF(RsaKey, n),
  5811. OFFSETOF(RsaKey, e),
  5812. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5813. OFFSETOF(RsaKey, d),
  5814. OFFSETOF(RsaKey, p),
  5815. OFFSETOF(RsaKey, q),
  5816. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5817. OFFSETOF(RsaKey, dP),
  5818. OFFSETOF(RsaKey, dQ),
  5819. OFFSETOF(RsaKey, u)
  5820. #endif
  5821. #endif
  5822. };
  5823. /* Get a number from the RSA key based on an index.
  5824. *
  5825. * Order: { n, e, d, p, q, dP, dQ, u }
  5826. *
  5827. * Caller must ensure index is not invalid!
  5828. *
  5829. * @param [in] key RSA key object.
  5830. * @param [in] idx Index of number.
  5831. * @return A pointer to an mp_int when valid index.
  5832. * @return NULL when invalid index.
  5833. */
  5834. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5835. {
  5836. /* Cast key to byte array to and use offset to get to mp_int field. */
  5837. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5838. }
  5839. #endif
  5840. #ifdef WOLFSSL_ASN_TEMPLATE
  5841. /* ASN.1 template for an RSA private key.
  5842. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5843. */
  5844. static const ASNItem rsaKeyASN[] = {
  5845. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5846. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5847. /* Integers need to be in this specific order
  5848. * as asn code depends on this. */
  5849. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5850. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5851. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5852. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5853. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5854. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5855. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5856. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5857. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5858. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5859. * v2 - multiprime */
  5860. #endif
  5861. };
  5862. enum {
  5863. RSAKEYASN_IDX_SEQ = 0,
  5864. RSAKEYASN_IDX_VER,
  5865. /* Integers need to be in this specific order
  5866. * as asn code depends on this. */
  5867. RSAKEYASN_IDX_N,
  5868. RSAKEYASN_IDX_E,
  5869. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5870. RSAKEYASN_IDX_D,
  5871. RSAKEYASN_IDX_P,
  5872. RSAKEYASN_IDX_Q,
  5873. RSAKEYASN_IDX_DP,
  5874. RSAKEYASN_IDX_DQ,
  5875. RSAKEYASN_IDX_U,
  5876. #endif
  5877. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  5878. };
  5879. /* Number of items in ASN.1 template for an RSA private key. */
  5880. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5881. #endif
  5882. /* Decode RSA private key.
  5883. *
  5884. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5885. *
  5886. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5887. * being extracted.
  5888. *
  5889. * @param [in] input Buffer holding BER encoded data.
  5890. * @param [in, out] inOutIdx On in, start of RSA private key.
  5891. * On out, start of ASN.1 item after RSA private key.
  5892. * @param [in, out] key RSA key object. May be NULL.
  5893. * @param [out] keySz Size of key in bytes. May be NULL.
  5894. * @param [in] inSz Number of bytes in buffer.
  5895. * @return 0 on success.
  5896. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  5897. * @return BAD_FUNC_ARG when key and keySz are NULL.
  5898. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5899. * is invalid.
  5900. * @return BUFFER_E when data in buffer is too small.
  5901. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5902. * non-zero length.
  5903. * @return MP_INIT_E when the unable to initialize an mp_int.
  5904. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5905. */
  5906. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  5907. RsaKey* key, int* keySz, word32 inSz)
  5908. {
  5909. #ifndef WOLFSSL_ASN_TEMPLATE
  5910. int version, length;
  5911. word32 algId = 0;
  5912. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  5913. return BAD_FUNC_ARG;
  5914. }
  5915. /* if has pkcs8 header skip it */
  5916. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5917. /* ignore error, did not have pkcs8 header */
  5918. }
  5919. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5920. return ASN_PARSE_E;
  5921. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5922. return ASN_PARSE_E;
  5923. if (key == NULL) {
  5924. int i;
  5925. /* Modulus */
  5926. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  5927. return ASN_PARSE_E;
  5928. }
  5929. *inOutIdx += (word32)*keySz;
  5930. for (i = 1; i < RSA_INTS; i++) {
  5931. if (SkipInt(input, inOutIdx, inSz) < 0) {
  5932. return ASN_RSA_KEY_E;
  5933. }
  5934. }
  5935. }
  5936. else {
  5937. key->type = RSA_PRIVATE;
  5938. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5939. mp_memzero_add("Decode RSA key d", &key->d);
  5940. mp_memzero_add("Decode RSA key p", &key->p);
  5941. mp_memzero_add("Decode RSA key q", &key->q);
  5942. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5943. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5944. mp_memzero_add("Decode RSA key dP", &key->dP);
  5945. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  5946. mp_memzero_add("Decode RSA key u", &key->u);
  5947. #endif
  5948. #endif
  5949. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  5950. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  5951. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5952. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  5953. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  5954. GetInt(&key->q, input, inOutIdx, inSz) < 0
  5955. #else
  5956. SkipInt(input, inOutIdx, inSz) < 0 ||
  5957. SkipInt(input, inOutIdx, inSz) < 0 ||
  5958. SkipInt(input, inOutIdx, inSz) < 0
  5959. #endif
  5960. ) {
  5961. return ASN_RSA_KEY_E;
  5962. }
  5963. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  5964. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5965. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  5966. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  5967. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5968. #else
  5969. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  5970. SkipInt(input, inOutIdx, inSz) < 0 ||
  5971. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5972. #endif
  5973. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  5974. if (wc_InitRsaHw(key) != 0) {
  5975. return BAD_STATE_E;
  5976. }
  5977. #endif
  5978. }
  5979. return 0;
  5980. #else
  5981. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5982. int ret = 0;
  5983. byte version = (byte)-1;
  5984. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5985. word32 algId = 0;
  5986. #endif
  5987. void* heap = NULL;
  5988. /* Check validity of parameters. */
  5989. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  5990. (keySz == NULL))) {
  5991. ret = BAD_FUNC_ARG;
  5992. }
  5993. if ((ret == 0) && (key != NULL)) {
  5994. heap = key->heap;
  5995. }
  5996. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5997. if (ret == 0) {
  5998. /* if has pkcs8 header skip it */
  5999. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  6000. /* ignore error, did not have pkcs8 header */
  6001. }
  6002. }
  6003. #endif
  6004. (void)heap;
  6005. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  6006. if (ret == 0) {
  6007. /* Register variable to hold version field. */
  6008. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  6009. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  6010. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6011. #define RSA_ASN_INTS RSA_PUB_INTS
  6012. /* Not extracting all data from BER encoding. */
  6013. #define RSA_ASN_COMPLETE 0
  6014. #else
  6015. #define RSA_ASN_INTS RSA_INTS
  6016. /* Extracting all data from BER encoding. */
  6017. #define RSA_ASN_COMPLETE 1
  6018. #endif
  6019. if (key != NULL) {
  6020. int i;
  6021. /* Extract all public fields. */
  6022. for (i = 0; i < RSA_ASN_INTS; i++) {
  6023. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  6024. GetRsaInt(key, i));
  6025. }
  6026. }
  6027. /* Parse BER encoding for RSA private key. */
  6028. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  6029. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  6030. }
  6031. /* Check version: 0 - two prime, 1 - multi-prime
  6032. * Multi-prime has optional sequence after coefficient for extra primes.
  6033. * If extra primes, parsing will fail as not all the buffer was used.
  6034. */
  6035. if ((ret == 0) && (version > PKCS1v1)) {
  6036. ret = ASN_PARSE_E;
  6037. }
  6038. if ((ret == 0) && (key != NULL)) {
  6039. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6040. /* RSA key object has all private key values. */
  6041. key->type = RSA_PRIVATE;
  6042. #else
  6043. /* RSA key object has all public key values. */
  6044. key->type = RSA_PUBLIC;
  6045. #endif
  6046. #ifdef WOLFSSL_XILINX_CRYPT
  6047. if (wc_InitRsaHw(key) != 0)
  6048. ret = BAD_STATE_E;
  6049. #endif
  6050. }
  6051. else if (ret == 0) {
  6052. /* Not filling in key but do want key size. */
  6053. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6054. /* Check whether first byte of data is 0x00 and drop it. */
  6055. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6056. (*keySz)--;
  6057. }
  6058. }
  6059. FREE_ASNGETDATA(dataASN, heap);
  6060. return ret;
  6061. #endif /* WOLFSSL_ASN_TEMPLATE */
  6062. }
  6063. /* Decode RSA private key.
  6064. *
  6065. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6066. *
  6067. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6068. * being extracted.
  6069. *
  6070. * @param [in] input Buffer holding BER encoded data.
  6071. * @param [in, out] inOutIdx On in, start of RSA private key.
  6072. * On out, start of ASN.1 item after RSA private key.
  6073. * @param [in, out] key RSA key object.
  6074. * @param [in] inSz Number of bytes in buffer.
  6075. * @return 0 on success.
  6076. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6077. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6078. * is invalid.
  6079. * @return BUFFER_E when data in buffer is too small.
  6080. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6081. * non-zero length.
  6082. * @return MP_INIT_E when the unable to initialize an mp_int.
  6083. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6084. */
  6085. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6086. word32 inSz)
  6087. {
  6088. if (key == NULL) {
  6089. return BAD_FUNC_ARG;
  6090. }
  6091. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6092. }
  6093. /* Valdidate RSA private key ASN.1 encoding.
  6094. *
  6095. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6096. *
  6097. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6098. * being extracted.
  6099. *
  6100. * @param [in] input Buffer holding BER encoded data.
  6101. * @param [in, out] inOutIdx On in, start of RSA private key.
  6102. * On out, start of ASN.1 item after RSA private key.
  6103. * @param [in] inSz Number of bytes in buffer.
  6104. * @return 0 on success.
  6105. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6106. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6107. * is invalid.
  6108. * @return BUFFER_E when data in buffer is too small.
  6109. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6110. * non-zero length.
  6111. * @return MP_INIT_E when the unable to initialize an mp_int.
  6112. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6113. */
  6114. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6115. word32 inSz)
  6116. {
  6117. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6118. }
  6119. #endif /* HAVE_USER_RSA */
  6120. #endif /* NO_RSA */
  6121. #ifdef WOLFSSL_ASN_TEMPLATE
  6122. /* ASN.1 template for a PKCS #8 key.
  6123. * Ignoring optional attributes and public key.
  6124. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6125. */
  6126. static const ASNItem pkcs8KeyASN[] = {
  6127. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6128. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6129. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6130. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6131. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6132. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6133. #ifdef WC_RSA_PSS
  6134. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6135. #endif
  6136. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6137. /* attributes [0] Attributes OPTIONAL */
  6138. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6139. };
  6140. enum {
  6141. PKCS8KEYASN_IDX_SEQ = 0,
  6142. PKCS8KEYASN_IDX_VER,
  6143. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6144. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6145. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6146. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6147. #ifdef WC_RSA_PSS
  6148. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6149. #endif
  6150. PKCS8KEYASN_IDX_PKEY_DATA,
  6151. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6152. };
  6153. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6154. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6155. #endif
  6156. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6157. *
  6158. * @param [in] input Buffer holding BER data.
  6159. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6160. * On out, start of encoded key.
  6161. * @param [in] sz Size of data in buffer.
  6162. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6163. * @return Length of key data on success.
  6164. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6165. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6166. * is invalid.
  6167. * @return BUFFER_E when data in buffer is too small.
  6168. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6169. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6170. * non-zero length.
  6171. */
  6172. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6173. word32* algId)
  6174. {
  6175. #ifndef WOLFSSL_ASN_TEMPLATE
  6176. word32 idx;
  6177. int version, length;
  6178. int ret;
  6179. byte tag;
  6180. if (input == NULL || inOutIdx == NULL)
  6181. return BAD_FUNC_ARG;
  6182. idx = *inOutIdx;
  6183. if (GetSequence(input, &idx, &length, sz) < 0)
  6184. return ASN_PARSE_E;
  6185. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6186. return ASN_PARSE_E;
  6187. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6188. return ASN_PARSE_E;
  6189. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6190. return ASN_PARSE_E;
  6191. idx = idx - 1; /* reset idx after finding tag */
  6192. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6193. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6194. word32 seqIdx = idx;
  6195. int seqLen;
  6196. /* Not set when -1. */
  6197. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6198. int mgf = -1;
  6199. int saltLen = 0;
  6200. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6201. return ASN_PARSE_E;
  6202. }
  6203. /* Get the private key parameters. */
  6204. ret = DecodeRsaPssParams(input + seqIdx,
  6205. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6206. if (ret != 0) {
  6207. return ASN_PARSE_E;
  6208. }
  6209. /* TODO: store parameters so that usage can be checked. */
  6210. idx += seqLen;
  6211. }
  6212. #endif /* WC_RSA_PSS && !NO_RSA */
  6213. if (tag == ASN_OBJECT_ID) {
  6214. if (SkipObjectId(input, &idx, sz) < 0)
  6215. return ASN_PARSE_E;
  6216. }
  6217. ret = GetOctetString(input, &idx, &length, sz);
  6218. if (ret < 0) {
  6219. if (ret == BUFFER_E)
  6220. return ASN_PARSE_E;
  6221. /* Some private keys don't expect an octet string */
  6222. WOLFSSL_MSG("Couldn't find Octet string");
  6223. }
  6224. *inOutIdx = idx;
  6225. return length;
  6226. #else
  6227. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6228. int ret = 0;
  6229. word32 oid = 9;
  6230. byte version;
  6231. word32 idx;
  6232. /* Check validity of parameters. */
  6233. if (input == NULL || inOutIdx == NULL) {
  6234. return BAD_FUNC_ARG;
  6235. }
  6236. idx = *inOutIdx;
  6237. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6238. if (ret == 0) {
  6239. /* Get version, check key type and curve type. */
  6240. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6241. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6242. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6243. /* Parse data. */
  6244. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6245. &idx, sz);
  6246. }
  6247. if (ret == 0) {
  6248. /* Key type OID. */
  6249. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6250. /* Version 1 includes an optional public key.
  6251. * If public key is included then the parsing will fail as it did not
  6252. * use all the data.
  6253. */
  6254. if (version > PKCS8v1) {
  6255. ret = ASN_PARSE_E;
  6256. }
  6257. }
  6258. if (ret == 0) {
  6259. switch (oid) {
  6260. #ifndef NO_RSA
  6261. case RSAk:
  6262. /* Must have NULL item but not OBJECT_ID item. */
  6263. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6264. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6265. ret = ASN_PARSE_E;
  6266. }
  6267. break;
  6268. #ifdef WC_RSA_PSS
  6269. case RSAPSSk:
  6270. /* Must not have NULL item. */
  6271. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6272. ret = ASN_PARSE_E;
  6273. }
  6274. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6275. enum wc_HashType hash;
  6276. int mgf;
  6277. int saltLen;
  6278. const byte* params = GetASNItem_Addr(
  6279. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6280. word32 paramsSz = GetASNItem_Length(
  6281. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6282. /* Validate the private key parameters. */
  6283. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6284. &saltLen);
  6285. if (ret != 0) {
  6286. return ASN_PARSE_E;
  6287. }
  6288. /* TODO: store parameters so that usage can be checked. */
  6289. }
  6290. break;
  6291. #endif
  6292. #endif
  6293. #ifdef HAVE_ECC
  6294. case ECDSAk:
  6295. /* Must not have NULL item. */
  6296. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6297. ret = ASN_PARSE_E;
  6298. }
  6299. break;
  6300. #endif
  6301. #ifdef HAVE_ED25519
  6302. case ED25519k:
  6303. /* Neither NULL item nor OBJECT_ID item allowed. */
  6304. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6305. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6306. ret = ASN_PARSE_E;
  6307. }
  6308. break;
  6309. #endif
  6310. #ifdef HAVE_CURVE25519
  6311. case X25519k:
  6312. /* Neither NULL item nor OBJECT_ID item allowed. */
  6313. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6314. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6315. ret = ASN_PARSE_E;
  6316. }
  6317. break;
  6318. #endif
  6319. #ifdef HAVE_ED448
  6320. case ED448k:
  6321. /* Neither NULL item nor OBJECT_ID item allowed. */
  6322. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6323. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6324. ret = ASN_PARSE_E;
  6325. }
  6326. break;
  6327. #endif
  6328. #ifdef HAVE_CURVE448
  6329. case X448k:
  6330. /* Neither NULL item nor OBJECT_ID item allowed. */
  6331. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6332. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6333. ret = ASN_PARSE_E;
  6334. }
  6335. break;
  6336. #endif
  6337. /* DSAk not supported. */
  6338. /* Falcon, Dilithium and Sphincs not supported. */
  6339. /* Ignore OID lookup failures. */
  6340. default:
  6341. break;
  6342. }
  6343. }
  6344. if (ret == 0) {
  6345. /* Return algorithm id of internal key. */
  6346. *algId = oid;
  6347. /* Return index to start of internal key. */
  6348. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6349. /* Return value is length of internal key. */
  6350. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6351. }
  6352. FREE_ASNGETDATA(dataASN, NULL);
  6353. return ret;
  6354. #endif
  6355. }
  6356. /* TODO: test case */
  6357. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6358. {
  6359. word32 oid;
  6360. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6361. }
  6362. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6363. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6364. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6365. {
  6366. word32 inOutIdx = 0;
  6367. int length;
  6368. if (input == NULL)
  6369. return BAD_FUNC_ARG;
  6370. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6371. if (length < 0)
  6372. return length;
  6373. if ((word32)length + inOutIdx > sz)
  6374. return BUFFER_E;
  6375. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6376. return length;
  6377. }
  6378. int ToTraditional(byte* input, word32 sz)
  6379. {
  6380. word32 oid;
  6381. return ToTraditional_ex(input, sz, &oid);
  6382. }
  6383. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6384. #if defined(HAVE_PKCS8)
  6385. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6386. {
  6387. int length;
  6388. word32 algId;
  6389. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6390. return BAD_FUNC_ARG;
  6391. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6392. return length;
  6393. }
  6394. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6395. int algoID, const byte* curveOID, word32 oidSz)
  6396. {
  6397. #ifndef WOLFSSL_ASN_TEMPLATE
  6398. word32 keyIdx = 0;
  6399. word32 tmpSz = 0;
  6400. word32 sz;
  6401. word32 tmpAlgId = 0;
  6402. /* If out is NULL then return the max size needed
  6403. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6404. if (out == NULL && outSz != NULL) {
  6405. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6406. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6407. if (curveOID != NULL)
  6408. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6409. WOLFSSL_MSG("Checking size of PKCS8");
  6410. return LENGTH_ONLY_E;
  6411. }
  6412. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6413. if (key == NULL || out == NULL || outSz == NULL) {
  6414. return BAD_FUNC_ARG;
  6415. }
  6416. /* check the buffer has enough room for largest possible size */
  6417. if (curveOID != NULL) {
  6418. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6419. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6420. return BUFFER_E;
  6421. }
  6422. else {
  6423. oidSz = 0; /* with no curveOID oid size must be 0 */
  6424. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6425. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6426. return BUFFER_E;
  6427. }
  6428. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6429. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6430. (void)tmpAlgId;
  6431. return ASN_PARSE_E;
  6432. }
  6433. /* PrivateKeyInfo ::= SEQUENCE */
  6434. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6435. /* version Version
  6436. * no header information just INTEGER */
  6437. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6438. tmpSz += sz; keyIdx += sz;
  6439. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6440. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6441. if (curveOID != NULL && oidSz > 0) {
  6442. byte buf[MAX_LENGTH_SZ];
  6443. sz = SetLength(oidSz, buf);
  6444. sz += 1; /* plus one for ASN object id */
  6445. }
  6446. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6447. tmpSz += sz; keyIdx += sz;
  6448. /* privateKey PrivateKey *
  6449. * pkcs8 ecc uses slightly different format. Places curve oid in
  6450. * buffer */
  6451. if (curveOID != NULL && oidSz > 0) {
  6452. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6453. keyIdx += sz; tmpSz += sz;
  6454. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6455. keyIdx += oidSz; tmpSz += oidSz;
  6456. }
  6457. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6458. keyIdx += sz; tmpSz += sz;
  6459. XMEMCPY(out + keyIdx, key, keySz);
  6460. tmpSz += keySz;
  6461. /* attributes optional
  6462. * No attributes currently added */
  6463. /* rewind and add sequence */
  6464. sz = SetSequence(tmpSz, out);
  6465. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6466. *outSz = tmpSz + sz;
  6467. return (int)(tmpSz + sz);
  6468. #else
  6469. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6470. int sz;
  6471. int ret = 0;
  6472. word32 keyIdx = 0;
  6473. word32 tmpAlgId = 0;
  6474. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6475. /* Check validity of parameters. */
  6476. if (out == NULL && outSz != NULL) {
  6477. }
  6478. else if (key == NULL || out == NULL || outSz == NULL) {
  6479. ret = BAD_FUNC_ARG;
  6480. }
  6481. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6482. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6483. (void)tmpAlgId;
  6484. ret = ASN_PARSE_E;
  6485. }
  6486. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6487. if (ret == 0) {
  6488. /* Only support default PKCS #8 format - v0. */
  6489. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6490. /* Set key OID that corresponds to key data. */
  6491. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6492. oidKeyType);
  6493. if (curveOID != NULL && oidSz > 0) {
  6494. /* ECC key and curveOID set to write. */
  6495. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE],
  6496. curveOID, oidSz);
  6497. }
  6498. else {
  6499. /* EC curve OID to encode. */
  6500. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6501. }
  6502. /* Only RSA keys have NULL tagged item after OID. */
  6503. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6504. #ifdef WC_RSA_PSS
  6505. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6506. #endif
  6507. /* Set key data to encode. */
  6508. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6509. /* Get the size of the DER encoding. */
  6510. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6511. }
  6512. if (ret == 0) {
  6513. /* Always return the calculated size. */
  6514. *outSz = (word32)sz;
  6515. }
  6516. /* Check for buffer to encoded into. */
  6517. if ((ret == 0) && (out == NULL)) {
  6518. WOLFSSL_MSG("Checking size of PKCS8");
  6519. ret = LENGTH_ONLY_E;
  6520. }
  6521. if (ret == 0) {
  6522. /* Encode PKCS #8 key into buffer. */
  6523. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6524. ret = sz;
  6525. }
  6526. FREE_ASNSETDATA(dataASN, NULL);
  6527. return ret;
  6528. #endif /* WOLFSSL_ASN_TEMPLATE */
  6529. }
  6530. #endif /* HAVE_PKCS8 */
  6531. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6532. /* check that the private key is a pair for the public key
  6533. * return 1 (true) on match
  6534. * return 0 or negative value on failure/error
  6535. *
  6536. * privKey : buffer holding DER format private key
  6537. * privKeySz : size of private key buffer
  6538. * pubKey : buffer holding DER format public key
  6539. * pubKeySz : size of public key buffer
  6540. * ks : type of key */
  6541. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6542. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6543. {
  6544. int ret;
  6545. (void)privKeySz;
  6546. (void)pubKeySz;
  6547. (void)ks;
  6548. if (privKey == NULL || pubKey == NULL) {
  6549. return BAD_FUNC_ARG;
  6550. }
  6551. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6552. /* test if RSA key */
  6553. if (ks == RSAk
  6554. #ifdef WC_RSA_PSS
  6555. || ks == RSAPSSk
  6556. #endif
  6557. ) {
  6558. #ifdef WOLFSSL_SMALL_STACK
  6559. RsaKey* a;
  6560. RsaKey* b = NULL;
  6561. #else
  6562. RsaKey a[1], b[1];
  6563. #endif
  6564. word32 keyIdx = 0;
  6565. #ifdef WOLFSSL_SMALL_STACK
  6566. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6567. if (a == NULL)
  6568. return MEMORY_E;
  6569. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6570. if (b == NULL) {
  6571. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6572. return MEMORY_E;
  6573. }
  6574. #endif
  6575. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6576. #ifdef WOLFSSL_SMALL_STACK
  6577. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6578. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6579. #endif
  6580. return ret;
  6581. }
  6582. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6583. wc_FreeRsaKey(a);
  6584. #ifdef WOLFSSL_SMALL_STACK
  6585. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6586. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6587. #endif
  6588. return ret;
  6589. }
  6590. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6591. WOLFSSL_MSG("Checking RSA key pair");
  6592. keyIdx = 0; /* reset to 0 for parsing public key */
  6593. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6594. pubKeySz)) == 0) {
  6595. /* limit for user RSA crypto because of RsaKey
  6596. * dereference. */
  6597. #if defined(HAVE_USER_RSA)
  6598. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6599. ret = 1; /* return first RSA cert as match */
  6600. #else
  6601. /* both keys extracted successfully now check n and e
  6602. * values are the same. This is dereferencing RsaKey */
  6603. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6604. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6605. ret = MP_CMP_E;
  6606. WOLFSSL_ERROR_VERBOSE(ret);
  6607. }
  6608. else
  6609. ret = 1;
  6610. #endif
  6611. }
  6612. else {
  6613. WOLFSSL_ERROR_VERBOSE(ret);
  6614. }
  6615. }
  6616. wc_FreeRsaKey(b);
  6617. wc_FreeRsaKey(a);
  6618. #ifdef WOLFSSL_SMALL_STACK
  6619. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6620. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6621. #endif
  6622. }
  6623. else
  6624. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6625. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6626. if (ks == ECDSAk) {
  6627. #ifdef WOLFSSL_SMALL_STACK
  6628. ecc_key* key_pair;
  6629. byte* privDer;
  6630. #else
  6631. ecc_key key_pair[1];
  6632. byte privDer[MAX_ECC_BYTES];
  6633. #endif
  6634. word32 privSz = MAX_ECC_BYTES;
  6635. word32 keyIdx = 0;
  6636. #ifdef WOLFSSL_SMALL_STACK
  6637. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6638. if (key_pair == NULL)
  6639. return MEMORY_E;
  6640. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6641. if (privDer == NULL) {
  6642. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6643. return MEMORY_E;
  6644. }
  6645. #endif
  6646. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6647. #ifdef WOLFSSL_SMALL_STACK
  6648. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6649. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6650. #endif
  6651. return ret;
  6652. }
  6653. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6654. privKeySz)) == 0) {
  6655. WOLFSSL_MSG("Checking ECC key pair");
  6656. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6657. == 0) {
  6658. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6659. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6660. #endif
  6661. wc_ecc_free(key_pair);
  6662. ret = wc_ecc_init(key_pair);
  6663. if (ret == 0) {
  6664. ret = wc_ecc_import_private_key(privDer,
  6665. privSz, pubKey,
  6666. pubKeySz, key_pair);
  6667. }
  6668. /* public and private extracted successfully now check if is
  6669. * a pair and also do sanity checks on key. wc_ecc_check_key
  6670. * checks that private * base generator equals pubkey */
  6671. if (ret == 0) {
  6672. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6673. ret = 1;
  6674. }
  6675. else {
  6676. WOLFSSL_ERROR_VERBOSE(ret);
  6677. }
  6678. }
  6679. ForceZero(privDer, privSz);
  6680. }
  6681. }
  6682. else {
  6683. WOLFSSL_ERROR_VERBOSE(ret);
  6684. }
  6685. wc_ecc_free(key_pair);
  6686. #ifdef WOLFSSL_SMALL_STACK
  6687. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6688. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6689. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6690. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6691. #endif
  6692. }
  6693. else
  6694. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6695. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6696. if (ks == ED25519k) {
  6697. #ifdef WOLFSSL_SMALL_STACK
  6698. ed25519_key* key_pair;
  6699. #else
  6700. ed25519_key key_pair[1];
  6701. #endif
  6702. word32 keyIdx = 0;
  6703. #ifdef WOLFSSL_SMALL_STACK
  6704. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6705. DYNAMIC_TYPE_ED25519);
  6706. if (key_pair == NULL)
  6707. return MEMORY_E;
  6708. #endif
  6709. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6710. #ifdef WOLFSSL_SMALL_STACK
  6711. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6712. #endif
  6713. return ret;
  6714. }
  6715. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6716. privKeySz)) == 0) {
  6717. WOLFSSL_MSG("Checking ED25519 key pair");
  6718. keyIdx = 0;
  6719. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6720. key_pair)) == 0) {
  6721. /* public and private extracted successfully no check if is
  6722. * a pair and also do sanity checks on key. wc_ecc_check_key
  6723. * checks that private * base generator equals pubkey */
  6724. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6725. ret = 1;
  6726. }
  6727. else {
  6728. WOLFSSL_ERROR_VERBOSE(ret);
  6729. }
  6730. }
  6731. }
  6732. else {
  6733. WOLFSSL_ERROR_VERBOSE(ret);
  6734. }
  6735. wc_ed25519_free(key_pair);
  6736. #ifdef WOLFSSL_SMALL_STACK
  6737. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6738. #endif
  6739. }
  6740. else
  6741. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6742. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6743. if (ks == ED448k) {
  6744. #ifdef WOLFSSL_SMALL_STACK
  6745. ed448_key* key_pair = NULL;
  6746. #else
  6747. ed448_key key_pair[1];
  6748. #endif
  6749. word32 keyIdx = 0;
  6750. #ifdef WOLFSSL_SMALL_STACK
  6751. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6752. DYNAMIC_TYPE_ED448);
  6753. if (key_pair == NULL)
  6754. return MEMORY_E;
  6755. #endif
  6756. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6757. #ifdef WOLFSSL_SMALL_STACK
  6758. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6759. #endif
  6760. return ret;
  6761. }
  6762. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6763. privKeySz)) == 0) {
  6764. WOLFSSL_MSG("Checking ED448 key pair");
  6765. keyIdx = 0;
  6766. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6767. key_pair)) == 0) {
  6768. /* public and private extracted successfully no check if is
  6769. * a pair and also do sanity checks on key. wc_ecc_check_key
  6770. * checks that private * base generator equals pubkey */
  6771. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6772. ret = 1;
  6773. }
  6774. else {
  6775. WOLFSSL_ERROR_VERBOSE(ret);
  6776. }
  6777. }
  6778. }
  6779. else {
  6780. WOLFSSL_ERROR_VERBOSE(ret);
  6781. }
  6782. wc_ed448_free(key_pair);
  6783. #ifdef WOLFSSL_SMALL_STACK
  6784. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6785. #endif
  6786. }
  6787. else
  6788. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6789. #if defined(HAVE_PQC)
  6790. #if defined(HAVE_FALCON)
  6791. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6792. #ifdef WOLFSSL_SMALL_STACK
  6793. falcon_key* key_pair = NULL;
  6794. #else
  6795. falcon_key key_pair[1];
  6796. #endif
  6797. word32 keyIdx = 0;
  6798. #ifdef WOLFSSL_SMALL_STACK
  6799. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6800. DYNAMIC_TYPE_FALCON);
  6801. if (key_pair == NULL)
  6802. return MEMORY_E;
  6803. #endif
  6804. ret = wc_falcon_init(key_pair);
  6805. if (ret < 0) {
  6806. #ifdef WOLFSSL_SMALL_STACK
  6807. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6808. #endif
  6809. return ret;
  6810. }
  6811. if (ks == FALCON_LEVEL1k) {
  6812. ret = wc_falcon_set_level(key_pair, 1);
  6813. }
  6814. else if (ks == FALCON_LEVEL5k) {
  6815. ret = wc_falcon_set_level(key_pair, 5);
  6816. }
  6817. if (ret < 0) {
  6818. #ifdef WOLFSSL_SMALL_STACK
  6819. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6820. #endif
  6821. return ret;
  6822. }
  6823. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6824. privKeySz)) == 0) {
  6825. WOLFSSL_MSG("Checking Falcon key pair");
  6826. keyIdx = 0;
  6827. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6828. key_pair)) == 0) {
  6829. /* Public and private extracted successfully. Sanity check. */
  6830. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6831. ret = 1;
  6832. }
  6833. else {
  6834. WOLFSSL_ERROR_VERBOSE(ret);
  6835. }
  6836. }
  6837. }
  6838. else {
  6839. WOLFSSL_ERROR_VERBOSE(ret);
  6840. }
  6841. wc_falcon_free(key_pair);
  6842. #ifdef WOLFSSL_SMALL_STACK
  6843. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6844. #endif
  6845. }
  6846. else
  6847. #endif /* HAVE_FALCON */
  6848. #if defined(HAVE_DILITHIUM)
  6849. if ((ks == DILITHIUM_LEVEL2k) ||
  6850. (ks == DILITHIUM_LEVEL3k) ||
  6851. (ks == DILITHIUM_LEVEL5k)) {
  6852. #ifdef WOLFSSL_SMALL_STACK
  6853. dilithium_key* key_pair = NULL;
  6854. #else
  6855. dilithium_key key_pair[1];
  6856. #endif
  6857. word32 keyIdx = 0;
  6858. #ifdef WOLFSSL_SMALL_STACK
  6859. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6860. DYNAMIC_TYPE_DILITHIUM);
  6861. if (key_pair == NULL)
  6862. return MEMORY_E;
  6863. #endif
  6864. ret = wc_dilithium_init(key_pair);
  6865. if (ret < 0) {
  6866. #ifdef WOLFSSL_SMALL_STACK
  6867. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6868. #endif
  6869. return ret;
  6870. }
  6871. if (ks == DILITHIUM_LEVEL2k) {
  6872. ret = wc_dilithium_set_level(key_pair, 2);
  6873. }
  6874. else if (ks == DILITHIUM_LEVEL3k) {
  6875. ret = wc_dilithium_set_level(key_pair, 3);
  6876. }
  6877. else if (ks == DILITHIUM_LEVEL5k) {
  6878. ret = wc_dilithium_set_level(key_pair, 5);
  6879. }
  6880. if (ret < 0) {
  6881. #ifdef WOLFSSL_SMALL_STACK
  6882. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6883. #endif
  6884. return ret;
  6885. }
  6886. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6887. privKeySz)) == 0) {
  6888. WOLFSSL_MSG("Checking Dilithium key pair");
  6889. keyIdx = 0;
  6890. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6891. key_pair)) == 0) {
  6892. /* Public and private extracted successfully. Sanity check. */
  6893. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6894. ret = 1;
  6895. }
  6896. }
  6897. wc_dilithium_free(key_pair);
  6898. #ifdef WOLFSSL_SMALL_STACK
  6899. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6900. #endif
  6901. }
  6902. else
  6903. #endif /* HAVE_DILITHIUM */
  6904. #if defined(HAVE_SPHINCS)
  6905. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6906. (ks == SPHINCS_FAST_LEVEL3k) ||
  6907. (ks == SPHINCS_FAST_LEVEL5k) ||
  6908. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6909. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6910. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6911. #ifdef WOLFSSL_SMALL_STACK
  6912. sphincs_key* key_pair = NULL;
  6913. #else
  6914. sphincs_key key_pair[1];
  6915. #endif
  6916. word32 keyIdx = 0;
  6917. #ifdef WOLFSSL_SMALL_STACK
  6918. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6919. DYNAMIC_TYPE_SPHINCS);
  6920. if (key_pair == NULL)
  6921. return MEMORY_E;
  6922. #endif
  6923. ret = wc_sphincs_init(key_pair);
  6924. if (ret < 0) {
  6925. #ifdef WOLFSSL_SMALL_STACK
  6926. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6927. #endif
  6928. return ret;
  6929. }
  6930. if (ks == SPHINCS_FAST_LEVEL1k) {
  6931. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6932. }
  6933. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6934. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6935. }
  6936. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6937. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6938. }
  6939. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6940. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6941. }
  6942. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6943. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6944. }
  6945. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6946. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6947. }
  6948. if (ret < 0) {
  6949. #ifdef WOLFSSL_SMALL_STACK
  6950. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6951. #endif
  6952. return ret;
  6953. }
  6954. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6955. privKeySz)) == 0) {
  6956. WOLFSSL_MSG("Checking Sphincs key pair");
  6957. keyIdx = 0;
  6958. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6959. key_pair)) == 0) {
  6960. /* Public and private extracted successfully. Sanity check. */
  6961. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6962. ret = 1;
  6963. }
  6964. }
  6965. wc_sphincs_free(key_pair);
  6966. #ifdef WOLFSSL_SMALL_STACK
  6967. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6968. #endif
  6969. }
  6970. else
  6971. #endif /* HAVE_SPHINCS */
  6972. #endif /* HAVE_PQC */
  6973. {
  6974. ret = 0;
  6975. }
  6976. (void)ks;
  6977. return ret;
  6978. }
  6979. /* check that the private key is a pair for the public key in certificate
  6980. * return 1 (true) on match
  6981. * return 0 or negative value on failure/error
  6982. *
  6983. * key : buffer holding DER format key
  6984. * keySz : size of key buffer
  6985. * der : a initialized and parsed DecodedCert holding a certificate */
  6986. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  6987. {
  6988. if (key == NULL || der == NULL) {
  6989. return BAD_FUNC_ARG;
  6990. }
  6991. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  6992. der->pubKeySize, (enum Key_Sum) der->keyOID);
  6993. }
  6994. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  6995. #ifndef NO_PWDBASED
  6996. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6997. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  6998. * size of encryption algorithm.
  6999. *
  7000. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  7001. * blockSz based on encryption algorithm.
  7002. *
  7003. * @param [in] first First byte of OID to use in check.
  7004. * @param [in] second Second byte of OID to use in check.
  7005. * @param [out] id wolfSSL id for PBE algorithm.
  7006. * @param [out] version Version of PBE OID:
  7007. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7008. * @param [out] blockSz Block size of encryption algorithm.
  7009. * @return 0 on success.
  7010. * @return ALGO_ID_E when OID not supported.
  7011. * @return ASN_INPUT_E when first byte is invalid.
  7012. */
  7013. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  7014. {
  7015. int ret = 0;
  7016. (void)id;
  7017. (void)blockSz;
  7018. *version = -1;
  7019. /* pkcs-12 1 = pkcs-12PbeIds */
  7020. if (first == 1) {
  7021. /* PKCS #12: Appendix C */
  7022. switch (second) {
  7023. #if !defined(NO_SHA)
  7024. #ifndef NO_RC4
  7025. case PBE_SHA1_RC4_128:
  7026. *id = PBE_SHA1_RC4_128;
  7027. *version = PKCS12v1;
  7028. if (blockSz != NULL) {
  7029. *blockSz = 1;
  7030. }
  7031. break;
  7032. #endif
  7033. #ifndef NO_DES3
  7034. case PBE_SHA1_DES3:
  7035. *id = PBE_SHA1_DES3;
  7036. *version = PKCS12v1;
  7037. if (blockSz != NULL) {
  7038. *blockSz = DES_BLOCK_SIZE;
  7039. }
  7040. break;
  7041. #endif
  7042. #ifdef WC_RC2
  7043. case PBE_SHA1_40RC2_CBC:
  7044. *id = PBE_SHA1_40RC2_CBC;
  7045. *version = PKCS12v1;
  7046. if (blockSz != NULL) {
  7047. *blockSz = RC2_BLOCK_SIZE;
  7048. }
  7049. break;
  7050. #endif
  7051. #endif /* !NO_SHA */
  7052. default:
  7053. ret = ALGO_ID_E;
  7054. break;
  7055. }
  7056. }
  7057. else if (first != PKCS5) {
  7058. /* Bad OID. */
  7059. ret = ASN_INPUT_E;
  7060. }
  7061. /* PKCS #5 PBES2: Appendix A.4
  7062. * pkcs-5 13 = id-PBES2 */
  7063. else if (second == PBES2) {
  7064. *version = PKCS5v2;
  7065. /* Id and block size come from CheckAlgoV2() */
  7066. }
  7067. else {
  7068. /* PKCS #5 PBES1: Appendix A.3 */
  7069. /* see RFC 2898 for ids */
  7070. switch (second) {
  7071. #ifndef NO_DES3
  7072. #ifndef NO_MD5
  7073. case PBES1_MD5_DES:
  7074. *id = PBE_MD5_DES;
  7075. *version = PKCS5;
  7076. if (blockSz != NULL) {
  7077. *blockSz = DES_BLOCK_SIZE;
  7078. }
  7079. break;
  7080. #endif
  7081. #ifndef NO_SHA
  7082. case PBES1_SHA1_DES:
  7083. *id = PBE_SHA1_DES;
  7084. *version = PKCS5;
  7085. if (blockSz != NULL) {
  7086. *blockSz = DES_BLOCK_SIZE;
  7087. }
  7088. break;
  7089. #endif
  7090. #endif /* !NO_DES3 */
  7091. default:
  7092. ret = ALGO_ID_E;
  7093. break;
  7094. }
  7095. }
  7096. /* Return error code. */
  7097. return ret;
  7098. }
  7099. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7100. #ifdef HAVE_PKCS8
  7101. /* Check the encryption algorithm with PBES2 is supported and return block size
  7102. * and wolfSSL id for the PBE.
  7103. *
  7104. * @param [in] oid Encryption algorithm OID id.
  7105. * @param [out] id wolfSSL id for PBE algorithm.
  7106. * @param [out] version Version of PBE OID:
  7107. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7108. * @return 0 on success.
  7109. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7110. */
  7111. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7112. {
  7113. int ret = 0;
  7114. (void)id;
  7115. (void)blockSz;
  7116. switch (oid) {
  7117. #if !defined(NO_DES3) && !defined(NO_SHA)
  7118. case DESb:
  7119. *id = PBE_SHA1_DES;
  7120. if (blockSz != NULL) {
  7121. *blockSz = DES_BLOCK_SIZE;
  7122. }
  7123. break;
  7124. case DES3b:
  7125. *id = PBE_SHA1_DES3;
  7126. if (blockSz != NULL) {
  7127. *blockSz = DES_BLOCK_SIZE;
  7128. }
  7129. break;
  7130. #endif
  7131. #ifdef WOLFSSL_AES_256
  7132. case AES256CBCb:
  7133. *id = PBE_AES256_CBC;
  7134. if (blockSz != NULL) {
  7135. *blockSz = AES_BLOCK_SIZE;
  7136. }
  7137. break;
  7138. #endif
  7139. #ifdef WOLFSSL_AES_128
  7140. case AES128CBCb:
  7141. *id = PBE_AES128_CBC;
  7142. if (blockSz != NULL) {
  7143. *blockSz = AES_BLOCK_SIZE;
  7144. }
  7145. break;
  7146. #endif
  7147. default:
  7148. WOLFSSL_MSG("No PKCS v2 algo found");
  7149. ret = ALGO_ID_E;
  7150. break;
  7151. }
  7152. /* Return error code. */
  7153. return ret;
  7154. }
  7155. #endif /* HAVE_PKCS8 */
  7156. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7157. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7158. int* algoID, void* heap)
  7159. {
  7160. word32 tmpIdx = 0;
  7161. if (key == NULL || algoID == NULL)
  7162. return BAD_FUNC_ARG;
  7163. *algoID = 0;
  7164. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7165. {
  7166. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7167. if (rsa == NULL)
  7168. return MEMORY_E;
  7169. wc_InitRsaKey(rsa, heap);
  7170. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7171. *algoID = RSAk;
  7172. }
  7173. else {
  7174. WOLFSSL_MSG("Not RSA DER key");
  7175. }
  7176. wc_FreeRsaKey(rsa);
  7177. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7178. }
  7179. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7180. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7181. if (*algoID == 0) {
  7182. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7183. if (ecc == NULL)
  7184. return MEMORY_E;
  7185. tmpIdx = 0;
  7186. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7187. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7188. *algoID = ECDSAk;
  7189. /* now find oid */
  7190. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7191. WOLFSSL_MSG("Error getting ECC curve OID");
  7192. wc_ecc_free(ecc);
  7193. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7194. return BAD_FUNC_ARG;
  7195. }
  7196. }
  7197. else {
  7198. WOLFSSL_MSG("Not ECC DER key either");
  7199. }
  7200. wc_ecc_free(ecc);
  7201. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7202. }
  7203. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7204. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7205. if (*algoID == 0) {
  7206. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7207. DYNAMIC_TYPE_TMP_BUFFER);
  7208. if (ed25519 == NULL)
  7209. return MEMORY_E;
  7210. tmpIdx = 0;
  7211. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7212. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7213. *algoID = ED25519k;
  7214. }
  7215. else {
  7216. WOLFSSL_MSG("Not ED25519 DER key");
  7217. }
  7218. wc_ed25519_free(ed25519);
  7219. }
  7220. else {
  7221. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7222. }
  7223. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7224. }
  7225. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7226. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7227. if (*algoID == 0) {
  7228. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7229. DYNAMIC_TYPE_TMP_BUFFER);
  7230. if (ed448 == NULL)
  7231. return MEMORY_E;
  7232. tmpIdx = 0;
  7233. if (wc_ed448_init(ed448) == 0) {
  7234. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7235. *algoID = ED448k;
  7236. }
  7237. else {
  7238. WOLFSSL_MSG("Not ED448 DER key");
  7239. }
  7240. wc_ed448_free(ed448);
  7241. }
  7242. else {
  7243. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7244. }
  7245. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7246. }
  7247. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7248. #if defined(HAVE_PQC)
  7249. #if defined(HAVE_FALCON)
  7250. if (*algoID == 0) {
  7251. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7252. DYNAMIC_TYPE_TMP_BUFFER);
  7253. if (falcon == NULL)
  7254. return MEMORY_E;
  7255. if (wc_falcon_init(falcon) != 0) {
  7256. tmpIdx = 0;
  7257. if (wc_falcon_set_level(falcon, 1) == 0) {
  7258. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7259. == 0) {
  7260. *algoID = FALCON_LEVEL1k;
  7261. }
  7262. else {
  7263. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7264. }
  7265. }
  7266. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7267. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7268. == 0) {
  7269. *algoID = FALCON_LEVEL5k;
  7270. }
  7271. else {
  7272. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7273. }
  7274. }
  7275. else {
  7276. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7277. }
  7278. wc_falcon_free(falcon);
  7279. }
  7280. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7281. }
  7282. #endif /* HAVE_FALCON */
  7283. #if defined(HAVE_DILITHIUM)
  7284. if (*algoID == 0) {
  7285. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7286. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7287. if (dilithium == NULL)
  7288. return MEMORY_E;
  7289. if (wc_dilithium_init(dilithium) != 0) {
  7290. tmpIdx = 0;
  7291. if (wc_dilithium_set_level(dilithium, 2)
  7292. == 0) {
  7293. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7294. keySz) == 0) {
  7295. *algoID = DILITHIUM_LEVEL2k;
  7296. }
  7297. else {
  7298. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7299. }
  7300. }
  7301. else if (wc_dilithium_set_level(dilithium, 3)
  7302. == 0) {
  7303. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7304. keySz) == 0) {
  7305. *algoID = DILITHIUM_LEVEL3k;
  7306. }
  7307. else {
  7308. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7309. }
  7310. }
  7311. else if (wc_dilithium_set_level(dilithium, 5)
  7312. == 0) {
  7313. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7314. keySz) == 0) {
  7315. *algoID = DILITHIUM_LEVEL5k;
  7316. }
  7317. else {
  7318. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7319. }
  7320. }
  7321. else {
  7322. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7323. }
  7324. wc_dilithium_free(dilithium);
  7325. }
  7326. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7327. }
  7328. #endif /* HAVE_DILITHIUM */
  7329. #if defined(HAVE_SPHINCS)
  7330. if (*algoID == 0) {
  7331. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7332. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7333. if (sphincs == NULL)
  7334. return MEMORY_E;
  7335. if (wc_sphincs_init(sphincs) != 0) {
  7336. tmpIdx = 0;
  7337. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7338. == 0) {
  7339. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7340. keySz) == 0) {
  7341. *algoID = SPHINCS_FAST_LEVEL1k;
  7342. }
  7343. else {
  7344. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7345. }
  7346. }
  7347. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7348. == 0) {
  7349. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7350. keySz) == 0) {
  7351. *algoID = SPHINCS_FAST_LEVEL3k;
  7352. }
  7353. else {
  7354. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7355. }
  7356. }
  7357. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7358. == 0) {
  7359. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7360. keySz) == 0) {
  7361. *algoID = SPHINCS_FAST_LEVEL5k;
  7362. }
  7363. else {
  7364. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7365. }
  7366. }
  7367. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7368. == 0) {
  7369. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7370. keySz) == 0) {
  7371. *algoID = SPHINCS_SMALL_LEVEL1k;
  7372. }
  7373. else {
  7374. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7375. }
  7376. }
  7377. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7378. == 0) {
  7379. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7380. keySz) == 0) {
  7381. *algoID = SPHINCS_SMALL_LEVEL3k;
  7382. }
  7383. else {
  7384. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7385. }
  7386. }
  7387. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7388. == 0) {
  7389. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7390. keySz) == 0) {
  7391. *algoID = SPHINCS_SMALL_LEVEL5k;
  7392. }
  7393. else {
  7394. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7395. }
  7396. }
  7397. else {
  7398. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7399. }
  7400. wc_sphincs_free(sphincs);
  7401. }
  7402. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7403. }
  7404. #endif /* HAVE_SPHINCS */
  7405. #endif /* HAVE_PQC */
  7406. /* if flag is not set then this is not a key that we understand. */
  7407. if (*algoID == 0) {
  7408. WOLFSSL_MSG("Bad key DER or compile options");
  7409. return BAD_FUNC_ARG;
  7410. }
  7411. (void)tmpIdx;
  7412. (void)curveOID;
  7413. (void)oidSz;
  7414. (void)keySz;
  7415. (void)heap;
  7416. return 1;
  7417. }
  7418. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7419. #ifdef WOLFSSL_ASN_TEMPLATE
  7420. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7421. /* ASN.1 template for PBES2 parameters.
  7422. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7423. * A.2 - PBKDF2-params
  7424. * B.2 - Encryption schemes
  7425. * C - AlgorithmIdentifier
  7426. */
  7427. static const ASNItem pbes2ParamsASN[] = {
  7428. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7429. /* PBKDF2 */
  7430. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7431. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7432. /* Salt */
  7433. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7434. /* Iteration count */
  7435. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7436. /* Key length */
  7437. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7438. /* PRF - default is HMAC-SHA1 */
  7439. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7440. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7441. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7442. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7443. /* Encryption algorithm */
  7444. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7445. /* IV for CBC */
  7446. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7447. };
  7448. enum {
  7449. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7450. PBES2PARAMSASN_IDX_KDF_OID,
  7451. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7452. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7453. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7454. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7455. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7456. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7457. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7458. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7459. PBES2PARAMSASN_IDX_ENCS_OID,
  7460. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7461. };
  7462. /* Number of items in ASN.1 template for PBES2 parameters. */
  7463. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7464. /* ASN.1 template for PBES1 parameters.
  7465. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7466. */
  7467. static const ASNItem pbes1ParamsASN[] = {
  7468. /* Salt */
  7469. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7470. /* Iteration count */
  7471. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7472. };
  7473. enum {
  7474. PBES1PARAMSASN_IDX_SALT = 0,
  7475. PBES1PARAMSASN_IDX_ITER
  7476. };
  7477. /* Number of items in ASN.1 template for PBES1 parameters. */
  7478. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7479. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7480. #endif /* WOLFSSL_ASN_TEMPLATE */
  7481. #ifdef HAVE_PKCS8
  7482. /*
  7483. * Equivalent to calling TraditionalEnc with the same parameters but with
  7484. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7485. * part of the API (WOLFSSL_ASN_API).
  7486. */
  7487. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7488. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7489. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7490. {
  7491. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7492. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7493. }
  7494. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7495. int *blkSz)
  7496. {
  7497. int ret = 0;
  7498. switch (encAlgId) {
  7499. #if !defined(NO_DES3) && !defined(NO_SHA)
  7500. case DESb:
  7501. *len = sizeof(blkDesCbcOid);
  7502. *oid = blkDesCbcOid;
  7503. *id = PBE_SHA1_DES;
  7504. *blkSz = 8;
  7505. break;
  7506. case DES3b:
  7507. *len = sizeof(blkDes3CbcOid);
  7508. *oid = blkDes3CbcOid;
  7509. *id = PBE_SHA1_DES3;
  7510. *blkSz = 8;
  7511. break;
  7512. #endif
  7513. #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
  7514. case AES128CBCb:
  7515. *len = sizeof(blkAes128CbcOid);
  7516. *oid = blkAes128CbcOid;
  7517. *id = PBE_AES128_CBC;
  7518. *blkSz = 16;
  7519. break;
  7520. #endif
  7521. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7522. case AES256CBCb:
  7523. *len = sizeof(blkAes256CbcOid);
  7524. *oid = blkAes256CbcOid;
  7525. *id = PBE_AES256_CBC;
  7526. *blkSz = 16;
  7527. break;
  7528. #endif
  7529. default:
  7530. (void)len;
  7531. (void)oid;
  7532. (void)id;
  7533. (void)blkSz;
  7534. ret = ALGO_ID_E;
  7535. }
  7536. return ret;
  7537. }
  7538. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7539. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7540. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7541. void* heap)
  7542. {
  7543. #ifdef WOLFSSL_SMALL_STACK
  7544. byte* saltTmp = NULL;
  7545. #else
  7546. byte saltTmp[MAX_SALT_SIZE];
  7547. #endif
  7548. int genSalt = 0;
  7549. int ret = 0;
  7550. int version = 0;
  7551. int pbeId = 0;
  7552. int blockSz = 0;
  7553. const byte* encOid = NULL;
  7554. int encOidSz = 0;
  7555. word32 padSz = 0;
  7556. word32 innerLen = 0;
  7557. const byte* pbeOidBuf = NULL;
  7558. word32 pbeOidBufSz = 0;
  7559. word32 pbeLen = 0;
  7560. word32 kdfLen = 0;
  7561. word32 encLen = 0;
  7562. byte cbcIv[MAX_IV_SIZE];
  7563. word32 idx = 0;
  7564. word32 encIdx = 0;
  7565. (void)heap;
  7566. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7567. if (key == NULL || outSz == NULL || password == NULL) {
  7568. ret = BAD_FUNC_ARG;
  7569. }
  7570. if (ret == 0) {
  7571. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7572. }
  7573. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7574. genSalt = 1;
  7575. saltSz = 8;
  7576. }
  7577. if (ret == 0 && version == PKCS5v2) {
  7578. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7579. }
  7580. if (ret == 0) {
  7581. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7582. (blockSz - 1));
  7583. /* inner = OCT salt INT itt */
  7584. innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
  7585. if (version != PKCS5v2) {
  7586. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7587. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7588. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7589. }
  7590. else {
  7591. pbeOidBuf = pbes2;
  7592. pbeOidBufSz = sizeof(pbes2);
  7593. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7594. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7595. /* enc = OBJ enc_alg OCT iv */
  7596. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7597. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7598. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7599. (size_t)encLen);
  7600. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7601. }
  7602. }
  7603. if (ret == 0) {
  7604. /* outerLen = length of PBE encoding + octet string data */
  7605. /* Plus 2 for tag and length for pbe */
  7606. word32 outerLen = 2 + pbeLen;
  7607. /* Octet string tag, length */
  7608. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7609. /* Octet string bytes */
  7610. outerLen += keySz + padSz;
  7611. if (out == NULL) {
  7612. /* Sequence tag, length */
  7613. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7614. return LENGTH_ONLY_E;
  7615. }
  7616. SetOctetString(keySz + padSz, out);
  7617. idx += SetSequence(outerLen, out + idx);
  7618. encIdx = idx + outerLen - keySz - padSz;
  7619. /* Put Encrypted content in place. */
  7620. XMEMCPY(out + encIdx, key, keySz);
  7621. if (padSz > 0) {
  7622. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7623. keySz += padSz;
  7624. }
  7625. if (genSalt == 1) {
  7626. #ifdef WOLFSSL_SMALL_STACK
  7627. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7628. if (saltTmp == NULL) {
  7629. ret = MEMORY_E;
  7630. }
  7631. else
  7632. #endif
  7633. {
  7634. salt = saltTmp;
  7635. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7636. WOLFSSL_MSG("Error generating random salt");
  7637. }
  7638. }
  7639. }
  7640. }
  7641. if (ret == 0) {
  7642. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7643. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7644. }
  7645. if (ret == 0) {
  7646. if (version != PKCS5v2) {
  7647. /* PBE algorithm */
  7648. idx += SetSequence(pbeLen, out + idx);
  7649. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7650. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7651. idx += pbeOidBufSz;
  7652. }
  7653. else {
  7654. /* PBES2 algorithm identifier */
  7655. idx += SetSequence(pbeLen, out + idx);
  7656. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7657. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7658. idx += pbeOidBufSz;
  7659. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7660. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7661. /* KDF Algorithm Identifier */
  7662. idx += SetSequence(kdfLen, out + idx);
  7663. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7664. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7665. idx += sizeof(pbkdf2Oid);
  7666. }
  7667. idx += SetSequence(innerLen, out + idx);
  7668. idx += SetOctetString(saltSz, out + idx);
  7669. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7670. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7671. if (ret > 0)
  7672. ret = 0;
  7673. }
  7674. if (ret == 0) {
  7675. if (version == PKCS5v2) {
  7676. /* Encryption Algorithm Identifier */
  7677. idx += SetSequence(encLen, out + idx);
  7678. idx += (word32)SetObjectId(encOidSz, out + idx);
  7679. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7680. idx += (word32)encOidSz;
  7681. /* Encryption Algorithm Parameter: CBC IV */
  7682. idx += SetOctetString((word32)blockSz, out + idx);
  7683. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7684. idx += (word32)blockSz;
  7685. }
  7686. idx += SetOctetString(keySz, out + idx);
  7687. /* Default PRF - no need to write out OID */
  7688. idx += keySz;
  7689. ret = (int)idx;
  7690. }
  7691. #ifdef WOLFSSL_SMALL_STACK
  7692. if (saltTmp != NULL) {
  7693. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7694. }
  7695. #endif
  7696. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7697. return ret;
  7698. }
  7699. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7700. int passwordSz)
  7701. {
  7702. int ret;
  7703. int length;
  7704. word32 inOutIdx = 0;
  7705. if (input == NULL || password == NULL) {
  7706. return BAD_FUNC_ARG;
  7707. }
  7708. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7709. ret = ASN_PARSE_E;
  7710. }
  7711. else {
  7712. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7713. passwordSz);
  7714. if (ret > 0) {
  7715. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7716. }
  7717. }
  7718. if (ret > 0) {
  7719. /* DecryptContent will decrypt the data, but it will leave any padding
  7720. * bytes intact. This code calculates the length without the padding
  7721. * and we return that to the user. */
  7722. inOutIdx = 0;
  7723. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7724. ret = ASN_PARSE_E;
  7725. }
  7726. else {
  7727. ret = (int)inOutIdx + length;
  7728. }
  7729. }
  7730. return ret;
  7731. }
  7732. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7733. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7734. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7735. * buffer size. */
  7736. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7737. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7738. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7739. void* heap)
  7740. {
  7741. int ret = 0;
  7742. byte *pkcs8Key = NULL;
  7743. word32 pkcs8KeySz = 0;
  7744. int algId = 0;
  7745. const byte* curveOid = NULL;
  7746. word32 curveOidSz = 0;
  7747. if (ret == 0) {
  7748. /* check key type and get OID if ECC */
  7749. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7750. if (ret == 1)
  7751. ret = 0;
  7752. }
  7753. if (ret == 0) {
  7754. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7755. curveOidSz);
  7756. if (ret == LENGTH_ONLY_E)
  7757. ret = 0;
  7758. }
  7759. if (ret == 0) {
  7760. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7761. if (pkcs8Key == NULL)
  7762. ret = MEMORY_E;
  7763. }
  7764. if (ret == 0) {
  7765. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7766. curveOid, curveOidSz);
  7767. if (ret >= 0) {
  7768. pkcs8KeySz = (word32)ret;
  7769. ret = 0;
  7770. }
  7771. }
  7772. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7773. if (ret == 0) {
  7774. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7775. }
  7776. #endif
  7777. if (ret == 0) {
  7778. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7779. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7780. }
  7781. if (pkcs8Key != NULL) {
  7782. ForceZero(pkcs8Key, pkcs8KeySz);
  7783. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7784. }
  7785. (void)rng;
  7786. return ret;
  7787. }
  7788. /* Same as TraditionalEnc, but in the public API. */
  7789. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7790. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7791. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7792. WC_RNG* rng, void* heap)
  7793. {
  7794. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7795. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7796. }
  7797. #ifdef WOLFSSL_ASN_TEMPLATE
  7798. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7799. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7800. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7801. */
  7802. static const ASNItem pkcs8DecASN[] = {
  7803. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7804. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7805. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7806. /* PKCS #7 */
  7807. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7808. 0, 0, 2 },
  7809. /* PKCS #8 */
  7810. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7811. };
  7812. enum {
  7813. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7814. PKCS8DECASN_IDX_ENCALGO_OID,
  7815. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7816. PKCS8DECASN_IDX_ENCCONTENT,
  7817. PKCS8DECASN_IDX_ENCDATA
  7818. };
  7819. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7820. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7821. #endif
  7822. /* Decrypt data using PBE algorithm.
  7823. *
  7824. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7825. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7826. *
  7827. * Note: input buffer is overwritten with decrypted data!
  7828. *
  7829. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7830. *
  7831. * @param [in] input Data to decrypt and unwrap.
  7832. * @param [in] sz Size of encrypted data.
  7833. * @param [in] password Password to derive encryption key with.
  7834. * @param [in] passwordSz Size of password in bytes.
  7835. * @return Length of decrypted data on success.
  7836. * @return MEMORY_E when dynamic memory allocation fails.
  7837. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7838. * is invalid.
  7839. * @return BUFFER_E when data in buffer is too small.
  7840. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7841. * @return Other when decryption fails.
  7842. */
  7843. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7844. {
  7845. #ifndef WOLFSSL_ASN_TEMPLATE
  7846. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7847. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7848. int iterations = 0, keySz = 0;
  7849. #ifdef WOLFSSL_SMALL_STACK
  7850. byte* salt = NULL;
  7851. byte* cbcIv = NULL;
  7852. #else
  7853. byte salt[MAX_SALT_SIZE];
  7854. byte cbcIv[MAX_IV_SIZE];
  7855. #endif
  7856. byte tag;
  7857. if (passwordSz < 0) {
  7858. WOLFSSL_MSG("Bad password size");
  7859. return BAD_FUNC_ARG;
  7860. }
  7861. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7862. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7863. }
  7864. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7865. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7866. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7867. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7868. }
  7869. if (version == PKCS5v2) {
  7870. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7871. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7872. }
  7873. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7874. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7875. }
  7876. if (oid != PBKDF2_OID) {
  7877. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7878. }
  7879. }
  7880. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7881. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7882. }
  7883. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7884. * DEFAULT items. */
  7885. seqEnd = inOutIdx + (word32)length;
  7886. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7887. if (ret < 0)
  7888. goto exit_dc;
  7889. if (saltSz > MAX_SALT_SIZE) {
  7890. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7891. }
  7892. #ifdef WOLFSSL_SMALL_STACK
  7893. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7894. if (salt == NULL) {
  7895. ERROR_OUT(MEMORY_E, exit_dc);
  7896. }
  7897. #endif
  7898. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  7899. inOutIdx += (word32)saltSz;
  7900. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7901. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7902. }
  7903. /* OPTIONAL key length */
  7904. if (seqEnd > inOutIdx) {
  7905. word32 localIdx = inOutIdx;
  7906. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7907. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7908. }
  7909. if (tag == ASN_INTEGER &&
  7910. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7911. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7912. }
  7913. }
  7914. /* DEFAULT HMAC is SHA-1 */
  7915. if (seqEnd > inOutIdx) {
  7916. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7917. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7918. }
  7919. shaOid = oid;
  7920. }
  7921. #ifdef WOLFSSL_SMALL_STACK
  7922. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7923. if (cbcIv == NULL) {
  7924. ERROR_OUT(MEMORY_E, exit_dc);
  7925. }
  7926. #endif
  7927. if (version == PKCS5v2) {
  7928. /* get encryption algo */
  7929. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7930. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7931. }
  7932. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  7933. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7934. }
  7935. if (shaOid == 0)
  7936. shaOid = oid;
  7937. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7938. if (ret < 0)
  7939. goto exit_dc;
  7940. if (length > MAX_IV_SIZE) {
  7941. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7942. }
  7943. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  7944. inOutIdx += (word32)length;
  7945. }
  7946. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7947. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7948. }
  7949. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7950. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7951. }
  7952. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7953. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7954. }
  7955. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7956. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  7957. exit_dc:
  7958. #ifdef WOLFSSL_SMALL_STACK
  7959. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7960. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7961. #endif
  7962. if (ret == 0) {
  7963. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  7964. ret = length;
  7965. }
  7966. return ret;
  7967. #else
  7968. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7969. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7970. int ret = 0;
  7971. int id = 0;
  7972. int version;
  7973. word32 idx = 0;
  7974. word32 pIdx = 0;
  7975. word32 iterations;
  7976. word32 keySz = 0;
  7977. word32 saltSz = 0;
  7978. word32 shaOid = 0;
  7979. byte* salt = NULL;
  7980. byte* key = NULL;
  7981. byte cbcIv[MAX_IV_SIZE];
  7982. byte* params = NULL;
  7983. WOLFSSL_ENTER("DecryptContent");
  7984. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  7985. if (ret == 0) {
  7986. /* Check OID is a PBE Type */
  7987. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  7988. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  7989. &idx, sz);
  7990. }
  7991. if (ret == 0) {
  7992. /* Check the PBE algorithm and get the version and id. */
  7993. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  7994. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  7995. * Last byte: Alg or PBES2 */
  7996. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  7997. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  7998. &id, &version, NULL);
  7999. }
  8000. if (ret == 0) {
  8001. /* Get the parameters data. */
  8002. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  8003. /* Having a numbered choice means none or both will have errored out. */
  8004. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  8005. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  8006. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  8007. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  8008. else
  8009. ret = ASN_RSA_KEY_E;
  8010. }
  8011. if (ret == 0) {
  8012. if (version != PKCS5v2) {
  8013. /* Initialize for PBES1 parameters and put iterations in var. */
  8014. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  8015. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  8016. /* Parse the PBES1 parameters. */
  8017. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  8018. 0, params, &pIdx, sz);
  8019. if (ret == 0) {
  8020. /* Get the salt data. */
  8021. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  8022. }
  8023. }
  8024. else {
  8025. word32 ivSz = MAX_IV_SIZE;
  8026. /* Initialize for PBES2 parameters. Put iterations in var; match
  8027. * KDF, HMAC and cipher, and copy CBC into buffer. */
  8028. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  8029. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  8030. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  8031. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  8032. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  8033. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  8034. /* Parse the PBES2 parameters */
  8035. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  8036. 0, params, &pIdx, sz);
  8037. if (ret == 0) {
  8038. /* Get the salt data. */
  8039. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  8040. /* Get the digest and encryption algorithm id. */
  8041. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  8042. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8043. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8044. CheckAlgoV2(id, &id, NULL);
  8045. }
  8046. }
  8047. }
  8048. if (ret == 0) {
  8049. /* Decrypt the key. */
  8050. ret = wc_CryptKey(
  8051. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8052. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8053. }
  8054. if (ret == 0) {
  8055. /* Copy the decrypted key into the input (inline). */
  8056. XMEMMOVE(input, key, keySz);
  8057. ret = (int)keySz;
  8058. }
  8059. FREE_ASNGETDATA(dataASN, NULL);
  8060. return ret;
  8061. #endif
  8062. }
  8063. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8064. *
  8065. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8066. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8067. *
  8068. * Note: input buffer is overwritten with decrypted key!
  8069. *
  8070. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8071. *
  8072. * @param [in] input Data to decrypt and unwrap.
  8073. * @param [in] sz Size of encrypted data.
  8074. * @param [in] password Password to derive encryption key with.
  8075. * @param [in] passwordSz Size of password in bytes.
  8076. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8077. * @return Length of decrypted data on success.
  8078. * @return MEMORY_E when dynamic memory allocation fails.
  8079. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8080. * is invalid.
  8081. * @return BUFFER_E when data in buffer is too small.
  8082. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8083. * @return Other when decryption fails.
  8084. */
  8085. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8086. int passwordSz, word32* algId)
  8087. {
  8088. int ret;
  8089. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8090. if (ret > 0) {
  8091. ret = ToTraditional_ex(input, (word32)ret, algId);
  8092. }
  8093. return ret;
  8094. }
  8095. #endif /* HAVE_PKCS8 */
  8096. #ifdef HAVE_PKCS12
  8097. #define PKCS8_MIN_BLOCK_SIZE 8
  8098. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8099. {
  8100. int padSz;
  8101. /* calculate pad size */
  8102. padSz = blockSz - (sz & (blockSz - 1));
  8103. /* pad with padSz value */
  8104. if (buf) {
  8105. int i;
  8106. for (i = 0; i < padSz; i++) {
  8107. buf[sz+i] = (byte)(padSz & 0xFF);
  8108. }
  8109. }
  8110. /* return adjusted length */
  8111. return sz + padSz;
  8112. }
  8113. #ifdef WOLFSSL_ASN_TEMPLATE
  8114. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8115. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8116. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8117. */
  8118. static const ASNItem p8EncPbes1ASN[] = {
  8119. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8120. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8121. /* PBE algorithm */
  8122. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8123. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8124. /* Salt */
  8125. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8126. /* Iteration Count */
  8127. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8128. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8129. };
  8130. enum {
  8131. P8ENCPBES1ASN_IDX_SEQ = 0,
  8132. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8133. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8134. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8135. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8136. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8137. P8ENCPBES1ASN_IDX_ENCDATA
  8138. };
  8139. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8140. #endif
  8141. /* Wrap a private key in PKCS#8 and encrypt.
  8142. *
  8143. * Used for PKCS#12 and PKCS#7.
  8144. * vPKCS is the version of PKCS to use.
  8145. * vAlgo is the algorithm version to use.
  8146. *
  8147. * When salt is NULL, a random number is generated.
  8148. *
  8149. * data returned is :
  8150. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8151. *
  8152. * @param [in] input Data to encrypt.
  8153. * @param [in] inputSz Length of data in bytes.
  8154. * @param [out] out Buffer to write wrapped encrypted data into.
  8155. * @param [out] outSz Length of encrypted data in bytes.
  8156. * @param [in] password Password used to create encryption key.
  8157. * @param [in] passwordSz Length of password in bytes.
  8158. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8159. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8160. * @param [in] salt Salt to use with KDF.
  8161. * @param [in] saltSz Length of salt in bytes.
  8162. * @param [in] itt Number of iterations to use in KDF.
  8163. * @param [in] rng Random number generator to use to generate salt.
  8164. * @param [in] heap Dynamic memory allocator hint.
  8165. * @return The size of encrypted data on success
  8166. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8167. * @return ASN_PARSE_E when the salt size is too large.
  8168. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8169. * TraditionalEnc).
  8170. * @return MEMORY_E when dynamic memory allocation fails.
  8171. * @return Other when encryption or random number generation fails.
  8172. */
  8173. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8174. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8175. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8176. {
  8177. #ifndef WOLFSSL_ASN_TEMPLATE
  8178. word32 sz;
  8179. word32 inOutIdx = 0;
  8180. word32 tmpIdx = 0;
  8181. word32 totalSz = 0;
  8182. word32 seqSz;
  8183. word32 innerSz;
  8184. int ret;
  8185. int version, id, blockSz = 0;
  8186. #ifdef WOLFSSL_SMALL_STACK
  8187. byte* saltTmp = NULL;
  8188. byte* cbcIv = NULL;
  8189. #else
  8190. byte saltTmp[MAX_SALT_SIZE];
  8191. byte cbcIv[MAX_IV_SIZE];
  8192. #endif
  8193. byte seq[MAX_SEQ_SZ];
  8194. byte shr[MAX_SHORT_SZ];
  8195. word32 maxShr = MAX_SHORT_SZ;
  8196. word32 algoSz;
  8197. const byte* algoName;
  8198. (void)heap;
  8199. WOLFSSL_ENTER("EncryptContent");
  8200. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8201. return ASN_INPUT_E; /* Algo ID error */
  8202. if (version == PKCS5v2) {
  8203. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8204. return BAD_FUNC_ARG;
  8205. }
  8206. if (saltSz > MAX_SALT_SIZE)
  8207. return ASN_PARSE_E;
  8208. if (outSz == NULL) {
  8209. return BAD_FUNC_ARG;
  8210. }
  8211. /* calculate size */
  8212. /* size of constructed string at end */
  8213. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8214. totalSz = ASN_TAG_SZ;
  8215. totalSz += SetLength(sz, seq);
  8216. totalSz += sz;
  8217. /* size of sequence holding object id and sub sequence of salt and itt */
  8218. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8219. if (algoName == NULL) {
  8220. WOLFSSL_MSG("Unknown Algorithm");
  8221. return 0;
  8222. }
  8223. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8224. innerSz += algoSz;
  8225. /* get subsequence of salt and itt */
  8226. if (salt == NULL || saltSz == 0) {
  8227. sz = 8;
  8228. }
  8229. else {
  8230. sz = saltSz;
  8231. }
  8232. seqSz = SetOctetString(sz, seq);
  8233. seqSz += sz;
  8234. tmpIdx = 0;
  8235. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8236. if (ret >= 0) {
  8237. seqSz += (word32)ret;
  8238. }
  8239. else {
  8240. return ret;
  8241. }
  8242. innerSz += seqSz + SetSequence(seqSz, seq);
  8243. totalSz += innerSz + SetSequence(innerSz, seq);
  8244. if (out == NULL) {
  8245. *outSz = totalSz;
  8246. return LENGTH_ONLY_E;
  8247. }
  8248. inOutIdx = 0;
  8249. if (totalSz > *outSz)
  8250. return BUFFER_E;
  8251. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8252. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8253. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8254. inOutIdx += algoSz;
  8255. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8256. /* create random salt if one not provided */
  8257. if (salt == NULL || saltSz == 0) {
  8258. saltSz = 8;
  8259. #ifdef WOLFSSL_SMALL_STACK
  8260. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8261. if (saltTmp == NULL)
  8262. return MEMORY_E;
  8263. #endif
  8264. salt = saltTmp;
  8265. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8266. WOLFSSL_MSG("Error generating random salt");
  8267. #ifdef WOLFSSL_SMALL_STACK
  8268. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8269. #endif
  8270. return ret;
  8271. }
  8272. }
  8273. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8274. if (saltSz + inOutIdx > *outSz) {
  8275. #ifdef WOLFSSL_SMALL_STACK
  8276. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8277. #endif
  8278. return BUFFER_E;
  8279. }
  8280. XMEMCPY(out + inOutIdx, salt, saltSz);
  8281. inOutIdx += saltSz;
  8282. /* place iteration setting in buffer */
  8283. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8284. if (ret < 0) {
  8285. #ifdef WOLFSSL_SMALL_STACK
  8286. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8287. #endif
  8288. return ret;
  8289. }
  8290. if (inOutIdx + 1 > *outSz) {
  8291. #ifdef WOLFSSL_SMALL_STACK
  8292. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8293. #endif
  8294. return BUFFER_E;
  8295. }
  8296. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8297. /* get pad size and verify buffer room */
  8298. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8299. if (sz + inOutIdx > *outSz) {
  8300. #ifdef WOLFSSL_SMALL_STACK
  8301. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8302. #endif
  8303. return BUFFER_E;
  8304. }
  8305. inOutIdx += SetLength(sz, out + inOutIdx);
  8306. /* copy input to output buffer and pad end */
  8307. XMEMCPY(out + inOutIdx, input, inputSz);
  8308. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8309. #ifdef WOLFSSL_SMALL_STACK
  8310. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8311. if (cbcIv == NULL) {
  8312. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8313. return MEMORY_E;
  8314. }
  8315. #endif
  8316. /* encrypt */
  8317. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8318. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8319. #ifdef WOLFSSL_SMALL_STACK
  8320. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8321. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8322. #endif
  8323. return ret; /* encrypt failure */
  8324. }
  8325. #ifdef WOLFSSL_SMALL_STACK
  8326. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8327. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8328. #endif
  8329. (void)rng;
  8330. return (int)(inOutIdx + sz);
  8331. #else
  8332. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8333. int ret = 0;
  8334. int sz = 0;
  8335. int version = 0;
  8336. int id = -1;
  8337. int blockSz = 0;
  8338. word32 pkcs8Sz = 0;
  8339. (void)heap;
  8340. WOLFSSL_ENTER("EncryptContent");
  8341. /* Must have a output size to return or check. */
  8342. if (outSz == NULL) {
  8343. ret = BAD_FUNC_ARG;
  8344. }
  8345. /* Check salt size is valid. */
  8346. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8347. ret = ASN_PARSE_E;
  8348. }
  8349. /* Get algorithm parameters for algorithm identifier. */
  8350. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8351. ret = ASN_INPUT_E;
  8352. }
  8353. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8354. if ((ret == 0) && (version == PKCS5v2)) {
  8355. ret = BAD_FUNC_ARG;
  8356. }
  8357. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8358. if (ret == 0) {
  8359. /* Setup data to go into encoding including PBE algorithm, salt,
  8360. * iteration count, and padded key length. */
  8361. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8362. oidPBEType);
  8363. if (salt == NULL || saltSz == 0) {
  8364. salt = NULL;
  8365. saltSz = PKCS5_SALT_SZ;
  8366. /* Salt generated into encoding below. */
  8367. }
  8368. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8369. salt, saltSz);
  8370. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8371. (word16)itt);
  8372. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8373. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8374. /* Calculate size of encoding. */
  8375. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8376. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8377. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8378. &sz);
  8379. }
  8380. /* Return size when no output buffer. */
  8381. if ((ret == 0) && (out == NULL)) {
  8382. *outSz = (word32)sz;
  8383. ret = LENGTH_ONLY_E;
  8384. }
  8385. /* Check output buffer is big enough for encoded data. */
  8386. if ((ret == 0) && (sz > (int)*outSz)) {
  8387. ret = BAD_FUNC_ARG;
  8388. }
  8389. if (ret == 0) {
  8390. /* Encode PKCS#8 key. */
  8391. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8392. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8393. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8394. out);
  8395. if (salt == NULL) {
  8396. /* Generate salt into encoding. */
  8397. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8398. data.buffer.data;
  8399. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8400. }
  8401. }
  8402. if (ret == 0) {
  8403. byte cbcIv[MAX_IV_SIZE];
  8404. /* Store PKCS#8 key in output buffer. */
  8405. byte* pkcs8 =
  8406. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8407. XMEMCPY(pkcs8, input, inputSz);
  8408. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8409. /* Encrypt PKCS#8 key inline. */
  8410. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8411. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8412. }
  8413. if (ret == 0) {
  8414. /* Returning size on success. */
  8415. ret = sz;
  8416. }
  8417. FREE_ASNSETDATA(dataASN, heap);
  8418. return ret;
  8419. #endif /* WOLFSSL_ASN_TEMPLATE */
  8420. }
  8421. #endif /* HAVE_PKCS12 */
  8422. #endif /* NO_PWDBASED */
  8423. #ifndef NO_RSA
  8424. #ifndef HAVE_USER_RSA
  8425. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  8426. /* This function is to retrieve key position information in a cert.*
  8427. * The information will be used to call TSIP TLS-linked API for *
  8428. * certificate verification. */
  8429. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8430. word32 inSz, word32* key_n,
  8431. word32* key_n_len, word32* key_e,
  8432. word32* key_e_len)
  8433. {
  8434. int ret = 0;
  8435. int length = 0;
  8436. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8437. byte b;
  8438. #endif
  8439. if (input == NULL || inOutIdx == NULL)
  8440. return BAD_FUNC_ARG;
  8441. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8442. return ASN_PARSE_E;
  8443. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8444. if ((*inOutIdx + 1) > inSz)
  8445. return BUFFER_E;
  8446. b = input[*inOutIdx];
  8447. if (b != ASN_INTEGER) {
  8448. /* not from decoded cert, will have algo id, skip past */
  8449. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8450. return ASN_PARSE_E;
  8451. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8452. return ASN_PARSE_E;
  8453. /* Option NULL ASN.1 tag */
  8454. if (*inOutIdx >= inSz) {
  8455. return BUFFER_E;
  8456. }
  8457. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8458. ret = GetASNNull(input, inOutIdx, inSz);
  8459. if (ret != 0)
  8460. return ret;
  8461. }
  8462. /* TODO: support RSA PSS */
  8463. /* should have bit tag length and seq next */
  8464. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8465. if (ret != 0)
  8466. return ret;
  8467. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8468. return ASN_PARSE_E;
  8469. }
  8470. #endif /* OPENSSL_EXTRA */
  8471. /* Get modulus */
  8472. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8473. *key_n += *inOutIdx;
  8474. if (ret < 0) {
  8475. return ASN_RSA_KEY_E;
  8476. }
  8477. if (key_n_len)
  8478. *key_n_len = length;
  8479. *inOutIdx += length;
  8480. /* Get exponent */
  8481. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8482. *key_e += *inOutIdx;
  8483. if (ret < 0) {
  8484. return ASN_RSA_KEY_E;
  8485. }
  8486. if (key_e_len)
  8487. *key_e_len = length;
  8488. return ret;
  8489. }
  8490. #endif /* WOLFSSL_RENESAS_TSIP */
  8491. #ifdef WOLFSSL_ASN_TEMPLATE
  8492. /* ASN.1 template for an RSA public key.
  8493. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8494. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8495. */
  8496. static const ASNItem rsaPublicKeyASN[] = {
  8497. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8498. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8499. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8500. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8501. #ifdef WC_RSA_PSS
  8502. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8503. #endif
  8504. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8505. /* RSAPublicKey */
  8506. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8507. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8508. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8509. };
  8510. enum {
  8511. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8512. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8513. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8514. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8515. #ifdef WC_RSA_PSS
  8516. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8517. #endif
  8518. RSAPUBLICKEYASN_IDX_PUBKEY,
  8519. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8520. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8521. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8522. };
  8523. /* Number of items in ASN.1 template for an RSA public key. */
  8524. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8525. #endif
  8526. /* Decode RSA public key.
  8527. *
  8528. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8529. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8530. *
  8531. * @param [in] input Buffer holding BER encoded data.
  8532. * @param [in, out] inOutIdx On in, start of RSA public key.
  8533. * On out, start of ASN.1 item after RSA public key.
  8534. * @param [in] inSz Number of bytes in buffer.
  8535. * @param [out] n Pointer to modulus in buffer.
  8536. * @param [out] nSz Size of modulus in bytes.
  8537. * @param [out] e Pointer to exponent in buffer.
  8538. * @param [out] eSz Size of exponent in bytes.
  8539. * @return 0 on success.
  8540. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8541. * is invalid.
  8542. * @return BUFFER_E when data in buffer is too small.
  8543. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8544. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8545. * non-zero length.
  8546. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8547. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8548. */
  8549. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8550. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8551. {
  8552. #ifndef WOLFSSL_ASN_TEMPLATE
  8553. int ret = 0;
  8554. int length = 0;
  8555. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8556. word32 localIdx;
  8557. byte tag;
  8558. #endif
  8559. if (input == NULL || inOutIdx == NULL)
  8560. return BAD_FUNC_ARG;
  8561. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8562. return ASN_PARSE_E;
  8563. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8564. localIdx = *inOutIdx;
  8565. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8566. return BUFFER_E;
  8567. if (tag != ASN_INTEGER) {
  8568. /* not from decoded cert, will have algo id, skip past */
  8569. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8570. return ASN_PARSE_E;
  8571. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8572. return ASN_PARSE_E;
  8573. /* Option NULL ASN.1 tag */
  8574. if (*inOutIdx >= inSz) {
  8575. return BUFFER_E;
  8576. }
  8577. localIdx = *inOutIdx;
  8578. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8579. return ASN_PARSE_E;
  8580. if (tag == ASN_TAG_NULL) {
  8581. ret = GetASNNull(input, inOutIdx, inSz);
  8582. if (ret != 0)
  8583. return ret;
  8584. }
  8585. #ifdef WC_RSA_PSS
  8586. /* Skip RSA PSS parameters. */
  8587. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8588. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8589. return ASN_PARSE_E;
  8590. *inOutIdx += length;
  8591. }
  8592. #endif
  8593. /* should have bit tag length and seq next */
  8594. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8595. if (ret != 0)
  8596. return ret;
  8597. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8598. return ASN_PARSE_E;
  8599. }
  8600. #endif /* OPENSSL_EXTRA */
  8601. /* Get modulus */
  8602. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8603. if (ret < 0) {
  8604. return ASN_RSA_KEY_E;
  8605. }
  8606. if (nSz)
  8607. *nSz = (word32)length;
  8608. if (n)
  8609. *n = &input[*inOutIdx];
  8610. *inOutIdx += (word32)length;
  8611. /* Get exponent */
  8612. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8613. if (ret < 0) {
  8614. return ASN_RSA_KEY_E;
  8615. }
  8616. if (eSz)
  8617. *eSz = (word32)length;
  8618. if (e)
  8619. *e = &input[*inOutIdx];
  8620. *inOutIdx += (word32)length;
  8621. return ret;
  8622. #else
  8623. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8624. int ret = 0;
  8625. #ifdef WC_RSA_PSS
  8626. word32 oid = RSAk;
  8627. #endif
  8628. /* Check validity of parameters. */
  8629. if (input == NULL || inOutIdx == NULL) {
  8630. ret = BAD_FUNC_ARG;
  8631. }
  8632. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8633. if (ret == 0) {
  8634. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8635. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8636. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8637. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8638. 0, input, inOutIdx, inSz);
  8639. if (ret != 0) {
  8640. /* Didn't work - try whole SubjectKeyInfo instead. */
  8641. #ifdef WC_RSA_PSS
  8642. /* Could be RSA or RSA PSS key. */
  8643. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8644. #else
  8645. /* Set the OID to expect. */
  8646. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8647. keyRsaOid, sizeof(keyRsaOid));
  8648. #endif
  8649. /* Decode SubjectKeyInfo. */
  8650. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8651. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8652. inSz);
  8653. }
  8654. }
  8655. #ifdef WC_RSA_PSS
  8656. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8657. /* Two possible OIDs supported - RSA and RSA PSS. */
  8658. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8659. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8660. ret = ASN_PARSE_E;
  8661. }
  8662. }
  8663. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8664. /* Can't have NULL and SEQ. */
  8665. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8666. ret = ASN_PARSE_E;
  8667. }
  8668. /* SEQ present only with RSA PSS. */
  8669. if ((ret == 0) && (oid != RSAPSSk)) {
  8670. ret = ASN_PARSE_E;
  8671. }
  8672. if (ret == 0) {
  8673. enum wc_HashType hash;
  8674. int mgf;
  8675. int saltLen;
  8676. const byte* params = GetASNItem_Addr(
  8677. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8678. word32 paramsSz = GetASNItem_Length(
  8679. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8680. /* Validate the private key parameters. */
  8681. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8682. /* TODO: store parameters so that usage can be checked. */
  8683. }
  8684. }
  8685. #endif
  8686. if (ret == 0) {
  8687. /* Return the buffers and lengths asked for. */
  8688. if (n != NULL) {
  8689. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8690. }
  8691. if (nSz != NULL) {
  8692. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8693. }
  8694. if (e != NULL) {
  8695. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8696. }
  8697. if (eSz != NULL) {
  8698. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8699. }
  8700. }
  8701. FREE_ASNGETDATA(dataASN, NULL);
  8702. return ret;
  8703. #endif /* WOLFSSL_ASN_TEMPLATE */
  8704. }
  8705. /* Decode RSA public key.
  8706. *
  8707. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8708. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8709. *
  8710. * @param [in] input Buffer holding BER encoded data.
  8711. * @param [in, out] inOutIdx On in, start of RSA public key.
  8712. * On out, start of ASN.1 item after RSA public key.
  8713. * @param [in, out] key RSA key object.
  8714. * @param [in] inSz Number of bytes in buffer.
  8715. * @return 0 on success.
  8716. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8717. * is invalid.
  8718. * @return BUFFER_E when data in buffer is too small.
  8719. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8720. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8721. * non-zero length.
  8722. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8723. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8724. */
  8725. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8726. word32 inSz)
  8727. {
  8728. int ret;
  8729. const byte *n = NULL, *e = NULL;
  8730. word32 nSz = 0, eSz = 0;
  8731. if (key == NULL)
  8732. return BAD_FUNC_ARG;
  8733. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8734. if (ret == 0) {
  8735. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8736. }
  8737. return ret;
  8738. }
  8739. #endif /* HAVE_USER_RSA */
  8740. #endif /* !NO_RSA */
  8741. #ifndef NO_DH
  8742. #if defined(WOLFSSL_DH_EXTRA)
  8743. /*
  8744. * Decodes DH public key to fill specified DhKey.
  8745. *
  8746. * return 0 on success, negative on failure
  8747. */
  8748. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8749. DhKey* key, word32 inSz)
  8750. {
  8751. int ret = 0;
  8752. int length;
  8753. word32 oid = 0;
  8754. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8755. return BAD_FUNC_ARG;
  8756. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8757. return ASN_PARSE_E;
  8758. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8759. return ASN_PARSE_E;
  8760. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8761. if (oid != DHk || ret < 0)
  8762. return ASN_DH_KEY_E;
  8763. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8764. return ASN_PARSE_E;
  8765. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8766. return ASN_DH_KEY_E;
  8767. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8768. mp_clear(&key->p);
  8769. return ASN_DH_KEY_E;
  8770. }
  8771. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8772. if (ret > 0) {
  8773. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8774. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8775. mp_clear(&key->p);
  8776. mp_clear(&key->g);
  8777. return ASN_DH_KEY_E;
  8778. }
  8779. }
  8780. else {
  8781. mp_clear(&key->p);
  8782. mp_clear(&key->g);
  8783. return ASN_DH_KEY_E;
  8784. }
  8785. return 0;
  8786. }
  8787. #endif /* WOLFSSL_DH_EXTRA */
  8788. #ifdef WOLFSSL_ASN_TEMPLATE
  8789. /* ASN.1 template for DH key.
  8790. * PKCS #3, 9 - DHParameter.
  8791. * (Also in: RFC 2786, 3)
  8792. */
  8793. static const ASNItem dhParamASN[] = {
  8794. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8795. /* prime */
  8796. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8797. /* base */
  8798. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8799. /* privateValueLength */
  8800. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8801. };
  8802. enum {
  8803. DHPARAMASN_IDX_SEQ = 0,
  8804. DHPARAMASN_IDX_PRIME,
  8805. DHPARAMASN_IDX_BASE,
  8806. DHPARAMASN_IDX_PRIVLEN
  8807. };
  8808. /* Number of items in ASN.1 template for DH key. */
  8809. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8810. #ifdef WOLFSSL_DH_EXTRA
  8811. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8812. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8813. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8814. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8815. */
  8816. static const ASNItem dhKeyPkcs8ASN[] = {
  8817. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8818. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8819. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8820. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8821. /* DHParameter */
  8822. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8823. /* p */
  8824. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8825. /* g */
  8826. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8827. /* q - factor of p-1 */
  8828. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8829. /* j - subgroup factor */
  8830. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8831. /* ValidationParms */
  8832. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8833. /* PrivateKey - PKCS #8 */
  8834. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8835. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8836. /* PublicKey - SubjectPublicKeyInfo. */
  8837. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8838. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8839. };
  8840. enum {
  8841. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8842. DHKEYPKCS8ASN_IDX_VER,
  8843. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8844. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8845. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8846. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8847. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8848. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8849. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8850. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8851. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8852. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8853. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8854. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8855. };
  8856. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8857. #endif
  8858. #endif
  8859. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8860. *
  8861. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8862. * object.
  8863. *
  8864. * @param [in] input BER/DER encoded data.
  8865. * @param [in, out] inOutIdx On in, start of DH key data.
  8866. * On out, end of DH key data.
  8867. * @param [in, out] key DH key object.
  8868. * @param [in] inSz Size of data in bytes.
  8869. * @return 0 on success.
  8870. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8871. * @return MEMORY_E when dynamic memory allocation fails.
  8872. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8873. * is invalid.
  8874. * @return BUFFER_E when data in buffer is too small.
  8875. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8876. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8877. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8878. * non-zero length.
  8879. * @return MP_INIT_E when the unable to initialize an mp_int.
  8880. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8881. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8882. */
  8883. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8884. {
  8885. #ifndef WOLFSSL_ASN_TEMPLATE
  8886. int ret = 0;
  8887. int length;
  8888. #ifdef WOLFSSL_DH_EXTRA
  8889. #if !defined(HAVE_FIPS) || \
  8890. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8891. word32 oid = 0, temp = 0;
  8892. #endif
  8893. #endif
  8894. WOLFSSL_ENTER("wc_DhKeyDecode");
  8895. if (inOutIdx == NULL)
  8896. return BAD_FUNC_ARG;
  8897. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8898. return ASN_PARSE_E;
  8899. #ifdef WOLFSSL_DH_EXTRA
  8900. #if !defined(HAVE_FIPS) || \
  8901. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8902. temp = *inOutIdx;
  8903. #endif
  8904. #endif
  8905. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8906. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8907. ret = ASN_DH_KEY_E;
  8908. }
  8909. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8910. mp_clear(&key->p);
  8911. ret = ASN_DH_KEY_E;
  8912. }
  8913. #ifdef WOLFSSL_DH_EXTRA
  8914. #if !defined(HAVE_FIPS) || \
  8915. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8916. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8917. if (ret == ASN_DH_KEY_E) {
  8918. *inOutIdx = temp;
  8919. /* the version (0) - private only (for public skip) */
  8920. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8921. *inOutIdx += (word32)length;
  8922. }
  8923. /* Size of dhKeyAgreement section */
  8924. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8925. return ASN_PARSE_E;
  8926. /* Check for dhKeyAgreement */
  8927. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8928. if (oid != DHk || ret < 0)
  8929. return ASN_DH_KEY_E;
  8930. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8931. return ASN_PARSE_E;
  8932. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8933. return ASN_DH_KEY_E;
  8934. }
  8935. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8936. mp_clear(&key->p);
  8937. return ASN_DH_KEY_E;
  8938. }
  8939. }
  8940. temp = *inOutIdx;
  8941. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8942. if (ret > 0) {
  8943. /* Found Bit String */
  8944. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8945. WOLFSSL_MSG("Found Public Key");
  8946. ret = 0;
  8947. }
  8948. } else {
  8949. *inOutIdx = temp;
  8950. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8951. if (ret > 0) {
  8952. /* Found Octet String */
  8953. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8954. WOLFSSL_MSG("Found Private Key");
  8955. /* Compute public */
  8956. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8957. }
  8958. } else {
  8959. /* Don't use length from failed CheckBitString/GetOctetString */
  8960. *inOutIdx = temp;
  8961. ret = 0;
  8962. }
  8963. }
  8964. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8965. #endif /* WOLFSSL_DH_EXTRA */
  8966. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8967. return ret;
  8968. #else
  8969. #ifdef WOLFSSL_DH_EXTRA
  8970. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8971. #else
  8972. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8973. #endif
  8974. int ret = 0;
  8975. /* Check input parameters are valid. */
  8976. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8977. ret = BAD_FUNC_ARG;
  8978. }
  8979. #ifdef WOLFSSL_DH_EXTRA
  8980. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8981. #else
  8982. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8983. #endif
  8984. if (ret == 0) {
  8985. /* Initialize data and set mp_ints to hold p and g. */
  8986. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  8987. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  8988. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  8989. /* Try simple PKCS #3 template. */
  8990. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  8991. inOutIdx, inSz);
  8992. #ifdef WOLFSSL_DH_EXTRA
  8993. if (ret != 0) {
  8994. mp_free(&key->p);
  8995. mp_free(&key->g);
  8996. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  8997. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  8998. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  8999. keyDhOid, sizeof(keyDhOid));
  9000. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9001. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9002. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  9003. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9004. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9005. /* Try PKCS #8 wrapped template. */
  9006. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  9007. input, inOutIdx, inSz);
  9008. if (ret == 0) {
  9009. /* VERSION only present in PKCS #8 private key structure */
  9010. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  9011. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  9012. ret = ASN_PARSE_E;
  9013. }
  9014. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  9015. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  9016. ret = ASN_PARSE_E;
  9017. }
  9018. }
  9019. if ((ret == 0) && mp_iszero(&key->pub)) {
  9020. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  9021. }
  9022. }
  9023. #endif
  9024. }
  9025. FREE_ASNGETDATA(dataASN, key->heap);
  9026. return ret;
  9027. #endif /* WOLFSSL_ASN_TEMPLATE */
  9028. }
  9029. #ifdef WOLFSSL_DH_EXTRA
  9030. /* Export DH Key (private or public) */
  9031. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  9032. {
  9033. #ifndef WOLFSSL_ASN_TEMPLATE
  9034. int ret, privSz = 0, pubSz = 0;
  9035. word32 keySz, idx, len, total;
  9036. if (key == NULL || outSz == NULL) {
  9037. return BAD_FUNC_ARG;
  9038. }
  9039. /* determine size */
  9040. if (exportPriv) {
  9041. /* octect string: priv */
  9042. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9043. if (privSz < 0)
  9044. return privSz;
  9045. idx = 1 + SetLength((word32)privSz, NULL) +
  9046. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9047. }
  9048. else {
  9049. /* bit string: public */
  9050. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9051. if (pubSz < 0)
  9052. return pubSz;
  9053. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9054. }
  9055. keySz = idx;
  9056. /* DH Parameters sequence with P and G */
  9057. total = 0;
  9058. ret = wc_DhParamsToDer(key, NULL, &total);
  9059. if (ret != LENGTH_ONLY_E)
  9060. return ret;
  9061. idx += total;
  9062. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9063. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9064. idx += (word32)sizeof(keyDhOid);
  9065. len = idx - keySz;
  9066. /* sequence - all but pub/priv */
  9067. idx += SetSequence(len, NULL);
  9068. if (exportPriv) {
  9069. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9070. idx += 3;
  9071. }
  9072. /* sequence */
  9073. total = idx + SetSequence(idx, NULL);
  9074. /* if no output, then just getting size */
  9075. if (output == NULL) {
  9076. *outSz = total;
  9077. return LENGTH_ONLY_E;
  9078. }
  9079. /* make sure output fits in buffer */
  9080. if (total > *outSz) {
  9081. return BUFFER_E;
  9082. }
  9083. total = idx;
  9084. /* sequence */
  9085. idx = SetSequence(total, output);
  9086. if (exportPriv) {
  9087. /* version: 0 */
  9088. idx += (word32)SetMyVersion(0, output + idx, 0);
  9089. }
  9090. /* sequence - all but pub/priv */
  9091. idx += SetSequence(len, output + idx);
  9092. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9093. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9094. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9095. idx += sizeof(keyDhOid);
  9096. /* DH Parameters sequence with P and G */
  9097. total = *outSz - idx;
  9098. ret = wc_DhParamsToDer(key, output + idx, &total);
  9099. if (ret < 0)
  9100. return ret;
  9101. idx += total;
  9102. /* octect string: priv */
  9103. if (exportPriv) {
  9104. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9105. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9106. }
  9107. else {
  9108. /* bit string: public */
  9109. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9110. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9111. }
  9112. *outSz = idx;
  9113. return (int)idx;
  9114. #else
  9115. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9116. int ret = 0;
  9117. int sz;
  9118. WOLFSSL_ENTER("wc_DhKeyToDer");
  9119. XMEMSET(dataASN, 0, sizeof(dataASN));
  9120. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9121. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9122. /* Set mp_int containing p and g. */
  9123. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9124. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9125. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9126. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9127. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9128. if (exportPriv) {
  9129. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9130. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9131. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9132. }
  9133. else {
  9134. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9135. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9136. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9137. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9138. }
  9139. /* Calculate the size of the DH parameters. */
  9140. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9141. if (output == NULL) {
  9142. *outSz = (word32)sz;
  9143. ret = LENGTH_ONLY_E;
  9144. }
  9145. /* Check buffer is big enough for encoding. */
  9146. if ((ret == 0) && ((int)*outSz < sz)) {
  9147. ret = BUFFER_E;
  9148. }
  9149. if (ret == 0) {
  9150. /* Encode the DH parameters into buffer. */
  9151. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9152. /* Set the actual encoding size. */
  9153. *outSz = (word32)sz;
  9154. /* Return the actual encoding size. */
  9155. ret = sz;
  9156. }
  9157. return ret;
  9158. #endif
  9159. }
  9160. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9161. {
  9162. return wc_DhKeyToDer(key, out, outSz, 0);
  9163. }
  9164. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9165. {
  9166. return wc_DhKeyToDer(key, out, outSz, 1);
  9167. }
  9168. /* Convert DH key parameters to DER format, write to output (outSz)
  9169. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9170. * returned.
  9171. *
  9172. * Note : static function due to redefinition complications with DhKey and FIPS
  9173. * version 2 build.
  9174. *
  9175. * return bytes written on success */
  9176. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9177. {
  9178. #ifndef WOLFSSL_ASN_TEMPLATE
  9179. int ret;
  9180. word32 idx, total;
  9181. if (key == NULL || outSz == NULL) {
  9182. return BAD_FUNC_ARG;
  9183. }
  9184. /* determine size */
  9185. /* integer - g */
  9186. ret = SetASNIntMP(&key->g, -1, NULL);
  9187. if (ret < 0)
  9188. return ret;
  9189. idx = (word32)ret;
  9190. /* integer - p */
  9191. ret = SetASNIntMP(&key->p, -1, NULL);
  9192. if (ret < 0)
  9193. return ret;
  9194. idx += (word32)ret;
  9195. total = idx;
  9196. /* sequence */
  9197. idx += SetSequence(idx, NULL);
  9198. if (output == NULL) {
  9199. *outSz = idx;
  9200. return LENGTH_ONLY_E;
  9201. }
  9202. /* make sure output fits in buffer */
  9203. if (idx > *outSz) {
  9204. return BUFFER_E;
  9205. }
  9206. /* write DH parameters */
  9207. /* sequence - for P and G only */
  9208. idx = SetSequence(total, output);
  9209. /* integer - p */
  9210. ret = SetASNIntMP(&key->p, -1, output + idx);
  9211. if (ret < 0)
  9212. return ret;
  9213. idx += (word32)ret;
  9214. /* integer - g */
  9215. ret = SetASNIntMP(&key->g, -1, output + idx);
  9216. if (ret < 0)
  9217. return ret;
  9218. idx += (word32)ret;
  9219. *outSz = idx;
  9220. return (int)idx;
  9221. #else
  9222. ASNSetData dataASN[dhParamASN_Length];
  9223. int ret = 0;
  9224. int sz = 0;
  9225. WOLFSSL_ENTER("wc_DhParamsToDer");
  9226. if (key == NULL || outSz == NULL) {
  9227. ret = BAD_FUNC_ARG;
  9228. }
  9229. if (ret == 0) {
  9230. XMEMSET(dataASN, 0, sizeof(dataASN));
  9231. /* Set mp_int containing p and g. */
  9232. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9233. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9234. /* privateValueLength not encoded. */
  9235. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9236. /* Calculate the size of the DH parameters. */
  9237. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9238. }
  9239. if ((ret == 0) && (output == NULL)) {
  9240. *outSz = (word32)sz;
  9241. ret = LENGTH_ONLY_E;
  9242. }
  9243. /* Check buffer is big enough for encoding. */
  9244. if ((ret == 0) && (*outSz < (word32)sz)) {
  9245. ret = BUFFER_E;
  9246. }
  9247. if (ret == 0) {
  9248. /* Encode the DH parameters into buffer. */
  9249. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9250. /* Set the actual encoding size. */
  9251. *outSz = (word32)sz;
  9252. /* Return count of bytes written. */
  9253. ret = sz;
  9254. }
  9255. return ret;
  9256. #endif
  9257. }
  9258. #endif /* WOLFSSL_DH_EXTRA */
  9259. /* Decode DH parameters.
  9260. *
  9261. * PKCS #3, 9 - DHParameter.
  9262. * (Also in: RFC 2786, 3)
  9263. *
  9264. * @param [in] input Buffer holding BER encoded data.
  9265. * @param [in, out] inOutIdx On in, start of RSA public key.
  9266. * On out, start of ASN.1 item after RSA public key.
  9267. * @param [in] inSz Number of bytes in buffer.
  9268. * @param [in, out] p Buffer to hold prime.
  9269. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9270. * On out, size of prime in bytes.
  9271. * @param [in, out] g Buffer to hold base.
  9272. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9273. * On out, size of base in bytes.
  9274. * @return 0 on success.
  9275. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9276. * is invalid.
  9277. * @return BUFFER_E when data in buffer is too small.
  9278. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9279. */
  9280. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9281. byte* g, word32* gInOutSz)
  9282. {
  9283. #ifndef WOLFSSL_ASN_TEMPLATE
  9284. word32 idx = 0;
  9285. int ret;
  9286. int length;
  9287. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9288. return ASN_PARSE_E;
  9289. ret = GetASNInt(input, &idx, &length, inSz);
  9290. if (ret != 0)
  9291. return ret;
  9292. if (length <= (int)*pInOutSz) {
  9293. XMEMCPY(p, &input[idx], (size_t)length);
  9294. *pInOutSz = (word32)length;
  9295. }
  9296. else {
  9297. return BUFFER_E;
  9298. }
  9299. idx += (word32)length;
  9300. ret = GetASNInt(input, &idx, &length, inSz);
  9301. if (ret != 0)
  9302. return ret;
  9303. if (length <= (int)*gInOutSz) {
  9304. XMEMCPY(g, &input[idx], (size_t)length);
  9305. *gInOutSz = (word32)length;
  9306. }
  9307. else {
  9308. return BUFFER_E;
  9309. }
  9310. return 0;
  9311. #else
  9312. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9313. word32 idx = 0;
  9314. int ret = 0;
  9315. /* Make sure pointers are valid before use. */
  9316. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9317. (gInOutSz == NULL)) {
  9318. ret = BAD_FUNC_ARG;
  9319. }
  9320. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9321. if (ret == 0) {
  9322. /* Set the buffers to copy p and g into. */
  9323. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9324. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9325. /* Decode the DH Parameters. */
  9326. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9327. &idx, inSz);
  9328. }
  9329. FREE_ASNGETDATA(dataASN, NULL);
  9330. return ret;
  9331. #endif /* WOLFSSL_ASN_TEMPLATE */
  9332. }
  9333. #endif /* !NO_DH */
  9334. #ifndef NO_DSA
  9335. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9336. {
  9337. if (idx == 0)
  9338. return &key->p;
  9339. if (idx == 1)
  9340. return &key->q;
  9341. if (idx == 2)
  9342. return &key->g;
  9343. if (idx == 3)
  9344. return &key->y;
  9345. if (idx == 4)
  9346. return &key->x;
  9347. return NULL;
  9348. }
  9349. #ifdef WOLFSSL_ASN_TEMPLATE
  9350. /* ASN.1 template for DSA public and private keys.
  9351. * Public key: seq, p, q, g, y
  9352. * Private key: seq, version, p, q, g, y, x
  9353. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9354. */
  9355. static const ASNItem dsaKeyASN[] = {
  9356. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9357. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9358. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9359. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9360. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9361. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9362. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9363. };
  9364. enum {
  9365. DSAKEYASN_IDX_SEQ = 0,
  9366. DSAKEYASN_IDX_VER,
  9367. DSAKEYASN_IDX_P,
  9368. DSAKEYASN_IDX_Q,
  9369. DSAKEYASN_IDX_G,
  9370. DSAKEYASN_IDX_Y,
  9371. DSAKEYASN_IDX_X
  9372. };
  9373. /* Number of items in ASN.1 template for DSA private key. */
  9374. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9375. /* Number of items in ASN.1 template for DSA public key. */
  9376. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9377. /* ASN.1 template for PublicKeyInfo with DSA.
  9378. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9379. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9380. */
  9381. static const ASNItem dsaPubKeyASN[] = {
  9382. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9383. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9384. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9385. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9386. /* p */
  9387. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9388. /* q */
  9389. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9390. /* g */
  9391. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9392. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9393. /* y */
  9394. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9395. };
  9396. enum {
  9397. DSAPUBKEYASN_IDX_SEQ = 0,
  9398. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9399. DSAPUBKEYASN_IDX_ALGOID_OID,
  9400. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9401. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9402. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9403. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9404. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9405. DSAPUBKEYASN_IDX_PUBKEY_Y
  9406. };
  9407. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9408. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9409. #endif /* WOLFSSL_ASN_TEMPLATE */
  9410. /* Decode DSA public key.
  9411. *
  9412. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9413. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9414. *
  9415. * @param [in] input Buffer holding BER encoded data.
  9416. * @param [in, out] inOutIdx On in, start of DSA public key.
  9417. * On out, start of ASN.1 item after DSA public key.
  9418. * @param [in, out] key DSA key object.
  9419. * @param [in] inSz Number of bytes in buffer.
  9420. * @return 0 on success.
  9421. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9422. * is invalid.
  9423. * @return BUFFER_E when data in buffer is too small.
  9424. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9425. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9426. * non-zero length.
  9427. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9428. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9429. */
  9430. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9431. word32 inSz)
  9432. {
  9433. #ifndef WOLFSSL_ASN_TEMPLATE
  9434. int length;
  9435. int ret = 0;
  9436. word32 oid;
  9437. word32 maxIdx;
  9438. if (input == NULL || inOutIdx == NULL || key == NULL)
  9439. return BAD_FUNC_ARG;
  9440. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9441. return ASN_PARSE_E;
  9442. maxIdx = (word32)(*inOutIdx + (word32)length);
  9443. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9444. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9445. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9446. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9447. ret = ASN_DH_KEY_E;
  9448. if (ret != 0) {
  9449. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9450. return ASN_PARSE_E;
  9451. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9452. if (ret != 0)
  9453. return ret;
  9454. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9455. return ASN_PARSE_E;
  9456. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9457. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9458. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9459. return ASN_DH_KEY_E;
  9460. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9461. return ASN_PARSE_E;
  9462. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9463. return ASN_DH_KEY_E;
  9464. ret = 0;
  9465. }
  9466. key->type = DSA_PUBLIC;
  9467. return ret;
  9468. #else
  9469. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9470. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9471. int ret = 0;
  9472. /* Validated parameters. */
  9473. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9474. ret = BAD_FUNC_ARG;
  9475. }
  9476. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9477. if (ret == 0) {
  9478. int i;
  9479. /* Clear dynamic data items. */
  9480. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9481. /* seq
  9482. * p, q, g, y
  9483. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9484. for (i = 0; i < DSA_INTS - 1; i++)
  9485. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9486. /* Parse as simple form. */
  9487. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9488. inOutIdx, inSz);
  9489. if (ret != 0) {
  9490. /* Clear dynamic data items. */
  9491. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9492. /* Set DSA OID to expect. */
  9493. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9494. keyDsaOid, sizeof(keyDsaOid));
  9495. /* p, q, g */
  9496. for (i = 0; i < DSA_INTS - 2; i++)
  9497. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9498. GetDsaInt(key, i));
  9499. /* y */
  9500. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9501. /* Parse as SubjectPublicKeyInfo. */
  9502. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9503. input, inOutIdx, inSz);
  9504. }
  9505. }
  9506. if (ret == 0) {
  9507. /* Data parsed - set type of key parsed. */
  9508. key->type = DSA_PUBLIC;
  9509. }
  9510. FREE_ASNGETDATA(dataASN, key->heap);
  9511. return ret;
  9512. #endif
  9513. }
  9514. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9515. word32 inSz)
  9516. {
  9517. int length;
  9518. word32 maxIdx;
  9519. if (input == NULL || inOutIdx == NULL || key == NULL)
  9520. return BAD_FUNC_ARG;
  9521. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9522. return ASN_PARSE_E;
  9523. maxIdx = (word32)(*inOutIdx + (word32)length);
  9524. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9525. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9526. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9527. return ASN_DH_KEY_E;
  9528. return 0;
  9529. }
  9530. #ifdef WOLFSSL_ASN_TEMPLATE
  9531. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9532. static const ASNItem dsaKeyOctASN[] = {
  9533. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9534. /* p */
  9535. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9536. /* q */
  9537. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9538. /* g */
  9539. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9540. /* Private key */
  9541. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9542. /* x */
  9543. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9544. };
  9545. enum {
  9546. DSAKEYOCTASN_IDX_SEQ = 0,
  9547. DSAKEYOCTASN_IDX_P,
  9548. DSAKEYOCTASN_IDX_Q,
  9549. DSAKEYOCTASN_IDX_G,
  9550. DSAKEYOCTASN_IDX_PKEY_STR,
  9551. DSAKEYOCTASN_IDX_X
  9552. };
  9553. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9554. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9555. #endif
  9556. /* Decode DSA private key.
  9557. *
  9558. * @param [in] input Buffer holding BER encoded data.
  9559. * @param [in, out] inOutIdx On in, start of DSA public key.
  9560. * On out, start of ASN.1 item after DSA public key.
  9561. * @param [in, out] key DSA key object.
  9562. * @param [in] inSz Number of bytes in buffer.
  9563. * @return 0 on success.
  9564. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9565. * is invalid.
  9566. * @return BUFFER_E when data in buffer is too small.
  9567. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9568. * non-zero length.
  9569. */
  9570. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9571. word32 inSz)
  9572. {
  9573. #ifndef WOLFSSL_ASN_TEMPLATE
  9574. int length, version, ret = 0, temp = 0;
  9575. word32 algId = 0;
  9576. /* Sanity checks on input */
  9577. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9578. return BAD_FUNC_ARG;
  9579. }
  9580. /* if has pkcs8 header skip it */
  9581. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9582. /* ignore error, did not have pkcs8 header */
  9583. }
  9584. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9585. return ASN_PARSE_E;
  9586. temp = (int)*inOutIdx;
  9587. /* Default case expects a certificate with OctetString but no version ID */
  9588. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9589. if (ret < 0) {
  9590. mp_clear(&key->p);
  9591. ret = ASN_PARSE_E;
  9592. }
  9593. else {
  9594. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9595. if (ret < 0) {
  9596. mp_clear(&key->p);
  9597. mp_clear(&key->q);
  9598. ret = ASN_PARSE_E;
  9599. }
  9600. else {
  9601. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9602. if (ret < 0) {
  9603. mp_clear(&key->p);
  9604. mp_clear(&key->q);
  9605. mp_clear(&key->g);
  9606. ret = ASN_PARSE_E;
  9607. }
  9608. else {
  9609. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9610. if (ret < 0) {
  9611. mp_clear(&key->p);
  9612. mp_clear(&key->q);
  9613. mp_clear(&key->g);
  9614. ret = ASN_PARSE_E;
  9615. }
  9616. else {
  9617. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9618. if (ret < 0) {
  9619. mp_clear(&key->p);
  9620. mp_clear(&key->q);
  9621. mp_clear(&key->g);
  9622. mp_clear(&key->y);
  9623. ret = ASN_PARSE_E;
  9624. }
  9625. }
  9626. }
  9627. }
  9628. }
  9629. /* An alternate pass if default certificate fails parsing */
  9630. if (ret == ASN_PARSE_E) {
  9631. *inOutIdx = (word32)temp;
  9632. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9633. return ASN_PARSE_E;
  9634. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9635. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9636. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9637. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9638. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9639. return ASN_DH_KEY_E;
  9640. }
  9641. key->type = DSA_PRIVATE;
  9642. return 0;
  9643. #else
  9644. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9645. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9646. int ret = 0;
  9647. byte version = 0;
  9648. /* Sanity checks on input */
  9649. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9650. ret = BAD_FUNC_ARG;
  9651. }
  9652. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9653. if (ret == 0) {
  9654. int i;
  9655. /* Try dsaKeyOctASN */
  9656. /* Initialize key data and set mp_ints for params */
  9657. for (i = 0; i < DSA_INTS - 2; i++) {
  9658. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9659. }
  9660. /* and priv */
  9661. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9662. /* Try simple form. */
  9663. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9664. inOutIdx, inSz);
  9665. if (ret != 0) {
  9666. /* Try dsaKeyASN */
  9667. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9668. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9669. for (i = 0; i < DSA_INTS; i++) {
  9670. mp_int* n = GetDsaInt(key, i);
  9671. mp_clear(n);
  9672. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9673. }
  9674. /* Try simple OCTET_STRING form. */
  9675. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9676. inOutIdx, inSz);
  9677. }
  9678. }
  9679. if (ret == 0) {
  9680. /* Set the contents to be a private key. */
  9681. key->type = DSA_PRIVATE;
  9682. }
  9683. FREE_ASNGETDATA(dataASN, key->heap);
  9684. return ret;
  9685. #endif
  9686. }
  9687. #ifndef WOLFSSL_ASN_TEMPLATE
  9688. /* Release Tmp DSA resources */
  9689. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9690. {
  9691. int i;
  9692. for (i = 0; i < ints; i++)
  9693. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9694. (void)heap;
  9695. }
  9696. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9697. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9698. defined(WOLFSSL_CERT_GEN))
  9699. /* Encode a DSA public key into buffer.
  9700. *
  9701. * @param [out] output Buffer to hold encoded data.
  9702. * @param [in] key DSA key object.
  9703. * @param [out] outLen Length of buffer.
  9704. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9705. * @return Size of encoded data in bytes on success.
  9706. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9707. * than a minimal size (5 bytes), or buffer size is smaller than
  9708. * encoding size.
  9709. * @return MEMORY_E when dynamic memory allocation fails.
  9710. */
  9711. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9712. {
  9713. #ifndef WOLFSSL_ASN_TEMPLATE
  9714. /* p, g, q = DSA params, y = public exponent */
  9715. #ifdef WOLFSSL_SMALL_STACK
  9716. byte* p = NULL;
  9717. byte* g = NULL;
  9718. byte* q = NULL;
  9719. byte* y = NULL;
  9720. #else
  9721. byte p[MAX_DSA_INT_SZ];
  9722. byte g[MAX_DSA_INT_SZ];
  9723. byte q[MAX_DSA_INT_SZ];
  9724. byte y[MAX_DSA_INT_SZ];
  9725. #endif
  9726. byte innerSeq[MAX_SEQ_SZ];
  9727. byte outerSeq[MAX_SEQ_SZ];
  9728. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9729. int pSz, gSz, qSz, ySz;
  9730. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9731. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9732. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9733. return BAD_FUNC_ARG;
  9734. }
  9735. /* p */
  9736. #ifdef WOLFSSL_SMALL_STACK
  9737. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9738. if (p == NULL)
  9739. return MEMORY_E;
  9740. #endif
  9741. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9742. WOLFSSL_MSG("SetASNIntMP Error with p");
  9743. #ifdef WOLFSSL_SMALL_STACK
  9744. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9745. #endif
  9746. return pSz;
  9747. }
  9748. /* q */
  9749. #ifdef WOLFSSL_SMALL_STACK
  9750. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9751. if (q == NULL)
  9752. return MEMORY_E;
  9753. #endif
  9754. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9755. WOLFSSL_MSG("SetASNIntMP Error with q");
  9756. #ifdef WOLFSSL_SMALL_STACK
  9757. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9758. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9759. #endif
  9760. return qSz;
  9761. }
  9762. /* g */
  9763. #ifdef WOLFSSL_SMALL_STACK
  9764. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9765. if (g == NULL)
  9766. return MEMORY_E;
  9767. #endif
  9768. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9769. WOLFSSL_MSG("SetASNIntMP Error with g");
  9770. #ifdef WOLFSSL_SMALL_STACK
  9771. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9772. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9773. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9774. #endif
  9775. return gSz;
  9776. }
  9777. /* y */
  9778. #ifdef WOLFSSL_SMALL_STACK
  9779. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9780. if (y == NULL)
  9781. return MEMORY_E;
  9782. #endif
  9783. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9784. WOLFSSL_MSG("SetASNIntMP Error with y");
  9785. #ifdef WOLFSSL_SMALL_STACK
  9786. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9787. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9788. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9789. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9790. #endif
  9791. return ySz;
  9792. }
  9793. if (with_header) {
  9794. word32 algoSz;
  9795. #ifdef WOLFSSL_SMALL_STACK
  9796. byte* algo = NULL;
  9797. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9798. if (algo == NULL) {
  9799. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9800. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9801. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9802. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9803. return MEMORY_E;
  9804. }
  9805. #else
  9806. byte algo[MAX_ALGO_SZ];
  9807. #endif
  9808. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9809. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9810. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9811. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9812. (word32)(pSz + qSz + gSz), outerSeq);
  9813. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9814. bitStringSz + (word32)ySz + outerSeqSz, output);
  9815. /* check output size */
  9816. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9817. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9818. {
  9819. #ifdef WOLFSSL_SMALL_STACK
  9820. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9821. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9822. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9823. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9824. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9825. #endif
  9826. WOLFSSL_MSG("Error, output size smaller than outlen");
  9827. return BUFFER_E;
  9828. }
  9829. /* outerSeq */
  9830. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9831. idx += outerSeqSz;
  9832. /* algo */
  9833. XMEMCPY(output + idx, algo, algoSz);
  9834. idx += algoSz;
  9835. #ifdef WOLFSSL_SMALL_STACK
  9836. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9837. #endif
  9838. } else {
  9839. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9840. /* check output size */
  9841. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9842. #ifdef WOLFSSL_SMALL_STACK
  9843. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9844. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9845. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9846. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9847. #endif
  9848. WOLFSSL_MSG("Error, output size smaller than outlen");
  9849. return BUFFER_E;
  9850. }
  9851. idx = 0;
  9852. }
  9853. /* innerSeq */
  9854. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9855. idx += innerSeqSz;
  9856. /* p */
  9857. XMEMCPY(output + idx, p, (size_t)pSz);
  9858. idx += (word32)pSz;
  9859. /* q */
  9860. XMEMCPY(output + idx, q, (size_t)qSz);
  9861. idx += (word32)qSz;
  9862. /* g */
  9863. XMEMCPY(output + idx, g, (size_t)gSz);
  9864. idx += (word32)gSz;
  9865. /* bit string */
  9866. if (bitStringSz > 0) {
  9867. XMEMCPY(output + idx, bitString, bitStringSz);
  9868. idx += bitStringSz;
  9869. }
  9870. /* y */
  9871. XMEMCPY(output + idx, y, (size_t)ySz);
  9872. idx += (word32)ySz;
  9873. #ifdef WOLFSSL_SMALL_STACK
  9874. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9875. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9876. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9877. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9878. #endif
  9879. return (int)idx;
  9880. #else
  9881. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9882. int ret = 0;
  9883. int i;
  9884. int sz = 0;
  9885. const ASNItem *data = NULL;
  9886. int count = 0;
  9887. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9888. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9889. ret = BAD_FUNC_ARG;
  9890. }
  9891. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9892. if (ret == 0) {
  9893. if (with_header) {
  9894. /* Using dsaPubKeyASN */
  9895. data = dsaPubKeyASN;
  9896. count = dsaPubKeyASN_Length;
  9897. /* Set the algorithm OID to write out. */
  9898. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9899. /* Set the mp_ints to encode - parameters and public value. */
  9900. for (i = 0; i < DSA_INTS - 2; i++) {
  9901. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9902. GetDsaInt(key, i));
  9903. }
  9904. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9905. }
  9906. else {
  9907. /* Using dsaKeyASN */
  9908. data = dsaKeyASN;
  9909. count = dsaPublicKeyASN_Length;
  9910. /* Set the mp_ints to encode - parameters and public value. */
  9911. for (i = 0; i < DSA_INTS - 1; i++) {
  9912. /* Move all DSA ints up one slot (ignore VERSION so now
  9913. * it means P) */
  9914. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9915. GetDsaInt(key, i));
  9916. }
  9917. }
  9918. ret = SizeASN_Items(data, dataASN, count, &sz);
  9919. }
  9920. /* Check buffer is big enough for encoding. */
  9921. if ((ret == 0) && (sz > (int)outLen)) {
  9922. ret = BAD_FUNC_ARG;
  9923. }
  9924. /* Encode the DSA public key into output buffer. */
  9925. if (ret == 0) {
  9926. ret = SetASN_Items(data, dataASN, count, output);
  9927. }
  9928. FREE_ASNSETDATA(dataASN, key->heap);
  9929. return ret;
  9930. #endif /* WOLFSSL_ASN_TEMPLATE */
  9931. }
  9932. /* Encode a DSA public key into buffer.
  9933. *
  9934. * @param [out] output Buffer to hold encoded data.
  9935. * @param [in] key DSA key object.
  9936. * @param [out] outLen Length of buffer.
  9937. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9938. * @return Size of encoded data in bytes on success.
  9939. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9940. * than a minimal size (5 bytes), or buffer size is smaller than
  9941. * encoding size.
  9942. * @return MEMORY_E when dynamic memory allocation fails.
  9943. */
  9944. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9945. {
  9946. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  9947. }
  9948. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9949. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9950. int ints, int includeVersion)
  9951. {
  9952. #ifndef WOLFSSL_ASN_TEMPLATE
  9953. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  9954. word32 sizes[DSA_INTS];
  9955. int i, ret = 0;
  9956. byte seq[MAX_SEQ_SZ];
  9957. byte ver[MAX_VERSION_SZ];
  9958. byte* tmps[DSA_INTS];
  9959. if (ints > DSA_INTS || inLen == NULL)
  9960. return BAD_FUNC_ARG;
  9961. XMEMSET(sizes, 0, sizeof(sizes));
  9962. for (i = 0; i < ints; i++)
  9963. tmps[i] = NULL;
  9964. /* write all big ints from key to DER tmps */
  9965. for (i = 0; i < ints; i++) {
  9966. int mpSz;
  9967. mp_int* keyInt = GetDsaInt(key, i);
  9968. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  9969. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9970. DYNAMIC_TYPE_DSA);
  9971. if (tmps[i] == NULL) {
  9972. ret = MEMORY_E;
  9973. break;
  9974. }
  9975. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9976. if (mpSz < 0) {
  9977. ret = mpSz;
  9978. break;
  9979. }
  9980. sizes[i] = (word32)mpSz;
  9981. intTotalLen += (word32)mpSz;
  9982. }
  9983. if (ret != 0) {
  9984. FreeTmpDsas(tmps, key->heap, ints);
  9985. return ret;
  9986. }
  9987. /* make headers */
  9988. if (includeVersion)
  9989. verSz = (word32)SetMyVersion(0, ver, FALSE);
  9990. seqSz = SetSequence(verSz + intTotalLen, seq);
  9991. outLen = seqSz + verSz + intTotalLen;
  9992. *inLen = outLen;
  9993. if (output == NULL) {
  9994. FreeTmpDsas(tmps, key->heap, ints);
  9995. return LENGTH_ONLY_E;
  9996. }
  9997. if (outLen > *inLen) {
  9998. FreeTmpDsas(tmps, key->heap, ints);
  9999. return BAD_FUNC_ARG;
  10000. }
  10001. /* write to output */
  10002. XMEMCPY(output, seq, seqSz);
  10003. j = seqSz;
  10004. if (includeVersion) {
  10005. XMEMCPY(output + j, ver, verSz);
  10006. j += verSz;
  10007. }
  10008. for (i = 0; i < ints; i++) {
  10009. XMEMCPY(output + j, tmps[i], sizes[i]);
  10010. j += sizes[i];
  10011. }
  10012. FreeTmpDsas(tmps, key->heap, ints);
  10013. return (int)outLen;
  10014. #else
  10015. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  10016. int ret = 0;
  10017. int sz = 0;
  10018. (void)ints;
  10019. if ((key == NULL) || (inLen == NULL)) {
  10020. ret = BAD_FUNC_ARG;
  10021. }
  10022. if ((ret == 0) && (ints > DSA_INTS)) {
  10023. ret = BAD_FUNC_ARG;
  10024. }
  10025. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  10026. if (ret == 0) {
  10027. int i;
  10028. if (includeVersion) {
  10029. /* Set the version. */
  10030. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  10031. }
  10032. else {
  10033. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  10034. }
  10035. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10036. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10037. /* Set the mp_ints to encode - params, public and private value. */
  10038. for (i = 0; i < DSA_INTS; i++) {
  10039. if (i < ints)
  10040. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10041. else
  10042. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10043. }
  10044. /* Calculate size of the encoding. */
  10045. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10046. }
  10047. if ((ret == 0) && (output == NULL)) {
  10048. *inLen = (word32)sz;
  10049. ret = LENGTH_ONLY_E;
  10050. }
  10051. /* Check buffer is big enough for encoding. */
  10052. if ((ret == 0) && (sz > (int)*inLen)) {
  10053. ret = BAD_FUNC_ARG;
  10054. }
  10055. if (ret == 0) {
  10056. /* Encode the DSA private key into output buffer. */
  10057. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10058. /* Return the size of the encoding. */
  10059. ret = sz;
  10060. }
  10061. FREE_ASNSETDATA(dataASN, key->heap);
  10062. return ret;
  10063. #endif /* WOLFSSL_ASN_TEMPLATE */
  10064. }
  10065. /* Encode a DSA private key into buffer.
  10066. *
  10067. * @param [in] key DSA key object.
  10068. * @param [out] output Buffer to hold encoded data.
  10069. * @param [out] inLen Length of buffer.
  10070. * @return Size of encoded data in bytes on success.
  10071. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10072. * or, buffer size is smaller than encoding size.
  10073. * @return MEMORY_E when dynamic memory allocation fails.
  10074. */
  10075. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10076. {
  10077. if (!key || !output)
  10078. return BAD_FUNC_ARG;
  10079. if (key->type != DSA_PRIVATE)
  10080. return BAD_FUNC_ARG;
  10081. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10082. }
  10083. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10084. return bytes written. Version is excluded to be compatible with
  10085. OpenSSL d2i_DSAparams */
  10086. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10087. {
  10088. if (!key || !output)
  10089. return BAD_FUNC_ARG;
  10090. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10091. }
  10092. /* This version of the function allows output to be NULL. In that case, the
  10093. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10094. size will be pointed to by inLen. */
  10095. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10096. {
  10097. if (!key || !inLen)
  10098. return BAD_FUNC_ARG;
  10099. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10100. }
  10101. #endif /* NO_DSA */
  10102. #ifndef NO_CERTS
  10103. /* Initialize decoded certificate object with buffer of DER encoding.
  10104. *
  10105. * @param [in, out] cert Decoded certificate object.
  10106. * @param [in] source Buffer containing DER encoded certificate.
  10107. * @param [in] inSz Size of DER data in buffer in bytes.
  10108. * @param [in] heap Dynamic memory hint.
  10109. */
  10110. void InitDecodedCert(DecodedCert* cert,
  10111. const byte* source, word32 inSz, void* heap)
  10112. {
  10113. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10114. }
  10115. /* Initialize decoded certificate object with buffer of DER encoding.
  10116. *
  10117. * @param [in, out] cert Decoded certificate object.
  10118. * @param [in] source Buffer containing DER encoded certificate.
  10119. * @param [in] inSz Size of DER data in buffer in bytes.
  10120. * @param [in] heap Dynamic memory hint.
  10121. * @param [in] devId Crypto callback ID to use.
  10122. */
  10123. void InitDecodedCert_ex(DecodedCert* cert,
  10124. const byte* source, word32 inSz, void* heap, int devId)
  10125. {
  10126. if (cert != NULL) {
  10127. XMEMSET(cert, 0, sizeof(DecodedCert));
  10128. cert->subjectCNEnc = CTC_UTF8;
  10129. cert->issuer[0] = '\0';
  10130. cert->subject[0] = '\0';
  10131. cert->source = source; /* don't own */
  10132. cert->maxIdx = inSz; /* can't go over this index */
  10133. cert->heap = heap;
  10134. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10135. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10136. #ifdef WOLFSSL_CERT_NAME_ALL
  10137. cert->subjectNEnc = CTC_UTF8;
  10138. cert->subjectIEnc = CTC_UTF8;
  10139. cert->subjectDNQEnc = CTC_UTF8;
  10140. cert->subjectGNEnc = CTC_UTF8;
  10141. #endif
  10142. cert->subjectSNEnc = CTC_UTF8;
  10143. cert->subjectCEnc = CTC_PRINTABLE;
  10144. cert->subjectLEnc = CTC_UTF8;
  10145. cert->subjectSTEnc = CTC_UTF8;
  10146. cert->subjectOEnc = CTC_UTF8;
  10147. cert->subjectOUEnc = CTC_UTF8;
  10148. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10149. cert->issuerSNEnc = CTC_UTF8;
  10150. cert->issuerCEnc = CTC_PRINTABLE;
  10151. cert->issuerLEnc = CTC_UTF8;
  10152. cert->issuerSTEnc = CTC_UTF8;
  10153. cert->issuerOEnc = CTC_UTF8;
  10154. cert->issuerOUEnc = CTC_UTF8;
  10155. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10156. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10157. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10158. }
  10159. }
  10160. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10161. void* heap)
  10162. {
  10163. InitDecodedCert(cert, source, inSz, heap);
  10164. }
  10165. /* Free the alternative names object.
  10166. *
  10167. * Frees each linked list items and its name.
  10168. *
  10169. * @param [in, out] altNames Alternative names.
  10170. * @param [in] heap Dynamic memory hint.
  10171. */
  10172. void FreeAltNames(DNS_entry* altNames, void* heap)
  10173. {
  10174. (void)heap;
  10175. while (altNames) {
  10176. DNS_entry* tmp = altNames->next;
  10177. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10178. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10179. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10180. #endif
  10181. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10182. altNames = tmp;
  10183. }
  10184. }
  10185. /* malloc and initialize a new alt name structure */
  10186. DNS_entry* AltNameNew(void* heap)
  10187. {
  10188. DNS_entry* ret;
  10189. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10190. if (ret != NULL) {
  10191. XMEMSET(ret, 0, sizeof(DNS_entry));
  10192. }
  10193. (void)heap;
  10194. return ret;
  10195. }
  10196. #ifndef IGNORE_NAME_CONSTRAINTS
  10197. /* Free the subtree names object.
  10198. *
  10199. * Frees each linked list items and its name.
  10200. *
  10201. * @param [in, out] names Subtree names.
  10202. * @param [in] heap Dynamic memory hint.
  10203. */
  10204. void FreeNameSubtrees(Base_entry* names, void* heap)
  10205. {
  10206. (void)heap;
  10207. while (names) {
  10208. Base_entry* tmp = names->next;
  10209. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10210. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10211. names = tmp;
  10212. }
  10213. }
  10214. #endif /* IGNORE_NAME_CONSTRAINTS */
  10215. /* Free the decoded cert object's dynamic data.
  10216. *
  10217. * @param [in, out] cert Decoded certificate object.
  10218. */
  10219. void FreeDecodedCert(DecodedCert* cert)
  10220. {
  10221. if (cert == NULL)
  10222. return;
  10223. if (cert->subjectCNStored == 1) {
  10224. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10225. }
  10226. if (cert->pubKeyStored == 1) {
  10227. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10228. }
  10229. if (cert->weOwnAltNames && cert->altNames)
  10230. FreeAltNames(cert->altNames, cert->heap);
  10231. #ifndef IGNORE_NAME_CONSTRAINTS
  10232. if (cert->altEmailNames)
  10233. FreeAltNames(cert->altEmailNames, cert->heap);
  10234. if (cert->altDirNames)
  10235. FreeAltNames(cert->altDirNames, cert->heap);
  10236. if (cert->permittedNames)
  10237. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10238. if (cert->excludedNames)
  10239. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10240. #endif /* IGNORE_NAME_CONSTRAINTS */
  10241. #ifdef WOLFSSL_SEP
  10242. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10243. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10244. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10245. #endif /* WOLFSSL_SEP */
  10246. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10247. if (cert->issuerName != NULL)
  10248. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10249. if (cert->subjectName != NULL)
  10250. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10251. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10252. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10253. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10254. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10255. #endif
  10256. FreeSignatureCtx(&cert->sigCtx);
  10257. }
  10258. void wc_FreeDecodedCert(DecodedCert* cert)
  10259. {
  10260. FreeDecodedCert(cert);
  10261. }
  10262. #ifndef WOLFSSL_ASN_TEMPLATE
  10263. static int GetCertHeader(DecodedCert* cert)
  10264. {
  10265. int ret = 0, len;
  10266. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10267. return ASN_PARSE_E;
  10268. /* Reset the max index for the size indicated in the outer wrapper. */
  10269. cert->maxIdx = (word32)len + cert->srcIdx;
  10270. cert->certBegin = cert->srcIdx;
  10271. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10272. return ASN_PARSE_E;
  10273. cert->sigIndex = (word32)len + cert->srcIdx;
  10274. if (cert->sigIndex > cert->maxIdx)
  10275. return ASN_PARSE_E;
  10276. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10277. cert->sigIndex) < 0)
  10278. return ASN_PARSE_E;
  10279. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10280. &cert->serialSz, cert->sigIndex) < 0)
  10281. return ASN_PARSE_E;
  10282. return ret;
  10283. }
  10284. #endif
  10285. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10286. defined(HAVE_LIBOQS))
  10287. /* Store the key data under the BIT_STRING in dynamicly allocated data.
  10288. *
  10289. * @param [in, out] cert Certificate object.
  10290. * @param [in] source Buffer containing encoded key.
  10291. * @param [in, out] srcIdx On in, start of key data.
  10292. * On out, start of element after key data.
  10293. * @param [in] maxIdx Maximum index of certificate data.
  10294. */
  10295. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10296. word32 maxIdx)
  10297. {
  10298. int ret;
  10299. int length;
  10300. byte* publicKey;
  10301. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10302. if (ret == 0) {
  10303. #ifdef HAVE_OCSP
  10304. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10305. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10306. }
  10307. if (ret == 0) {
  10308. #endif
  10309. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10310. DYNAMIC_TYPE_PUBLIC_KEY);
  10311. if (publicKey == NULL) {
  10312. ret = MEMORY_E;
  10313. }
  10314. else {
  10315. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10316. cert->publicKey = publicKey;
  10317. cert->pubKeyStored = 1;
  10318. cert->pubKeySize = (word32)length;
  10319. *srcIdx += (word32)length;
  10320. }
  10321. }
  10322. return ret;
  10323. }
  10324. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10325. #endif
  10326. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10327. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  10328. {
  10329. #ifdef HAVE_OID_ENCODING
  10330. int ret;
  10331. #endif
  10332. int idx;
  10333. word32 oidSz = 0;
  10334. /* validate key */
  10335. if (key == NULL || key->dp == NULL) {
  10336. return BAD_FUNC_ARG;
  10337. }
  10338. #ifdef HAVE_OID_ENCODING
  10339. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  10340. if (ret != 0) {
  10341. return ret;
  10342. }
  10343. #else
  10344. oidSz = key->dp->oidSz;
  10345. #endif
  10346. idx = SetObjectId((int)oidSz, output);
  10347. /* length only */
  10348. if (output == NULL) {
  10349. return idx + (int)oidSz;
  10350. }
  10351. /* verify output buffer has room */
  10352. if (oidSz > outSz)
  10353. return BUFFER_E;
  10354. #ifdef HAVE_OID_ENCODING
  10355. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  10356. if (ret != 0) {
  10357. return ret;
  10358. }
  10359. #else
  10360. XMEMCPY(output+idx, key->dp->oid, oidSz);
  10361. #endif
  10362. idx += (int)oidSz;
  10363. return idx;
  10364. }
  10365. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10366. #ifdef HAVE_ECC
  10367. #ifdef WOLFSSL_ASN_TEMPLATE
  10368. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  10369. * RFC 5480, 2 - Subject Public Key Information Fields
  10370. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10371. * X9.62 ECC point format.
  10372. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  10373. */
  10374. static const ASNItem eccPublicKeyASN[] = {
  10375. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10376. /* AlgorithmIdentifier */
  10377. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10378. /* algorithm */
  10379. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  10380. /* namedCurve */
  10381. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  10382. /* specifiedCurve - explicit parameters */
  10383. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  10384. /* Public Key */
  10385. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10386. };
  10387. enum {
  10388. ECCPUBLICKEYASN_IDX_SEQ = 0,
  10389. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  10390. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  10391. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  10392. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  10393. ECCPUBLICKEYASN_IDX_PUBKEY
  10394. };
  10395. /* Number of items in ASN.1 template for ECC public key. */
  10396. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  10397. #endif /* WOLFSSL_ASN_TEMPLATE */
  10398. #endif /* HAVE_ECC */
  10399. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10400. /* Encode public ECC key in DER format.
  10401. *
  10402. * RFC 5480, 2 - Subject Public Key Information Fields
  10403. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10404. * X9.62 ECC point format.
  10405. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  10406. *
  10407. * @param [out] output Buffer to put encoded data in.
  10408. * @param [in] key ECC key object.
  10409. * @param [in] outLen Size of buffer in bytes.
  10410. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  10411. * @return Size of encoded data in bytes on success.
  10412. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10413. * @return MEMORY_E when dynamic memory allocation failed.
  10414. */
  10415. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  10416. int with_header, int comp)
  10417. {
  10418. #ifndef WOLFSSL_ASN_TEMPLATE
  10419. int ret;
  10420. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  10421. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  10422. byte algo[MAX_ALGO_SZ]; /* 20 */
  10423. /* public size */
  10424. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  10425. if (comp)
  10426. pubSz = 1 + pubSz;
  10427. else
  10428. pubSz = 1 + 2 * pubSz;
  10429. /* check for buffer overflow */
  10430. if (output != NULL && pubSz > (word32)outLen) {
  10431. return BUFFER_E;
  10432. }
  10433. /* headers */
  10434. if (with_header) {
  10435. ret = SetCurve(key, NULL, 0);
  10436. if (ret <= 0) {
  10437. return ret;
  10438. }
  10439. curveSz = (word32)ret;
  10440. ret = 0;
  10441. /* calculate size */
  10442. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  10443. bitStringSz = SetBitString(pubSz, 0, bitString);
  10444. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  10445. /* check for buffer overflow */
  10446. if (output != NULL &&
  10447. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  10448. return BUFFER_E;
  10449. }
  10450. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  10451. output);
  10452. /* algo */
  10453. if (output)
  10454. XMEMCPY(output + idx, algo, algoSz);
  10455. idx += algoSz;
  10456. /* curve */
  10457. if (output)
  10458. (void)SetCurve(key, output + idx, curveSz);
  10459. idx += curveSz;
  10460. /* bit string */
  10461. if (output)
  10462. XMEMCPY(output + idx, bitString, bitStringSz);
  10463. idx += bitStringSz;
  10464. }
  10465. /* pub */
  10466. if (output) {
  10467. PRIVATE_KEY_UNLOCK();
  10468. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  10469. PRIVATE_KEY_LOCK();
  10470. if (ret != 0) {
  10471. return ret;
  10472. }
  10473. }
  10474. idx += pubSz;
  10475. return (int)idx;
  10476. #else
  10477. word32 pubSz = 0;
  10478. int sz = 0;
  10479. int ret = 0;
  10480. int curveIdSz = 0;
  10481. byte* curveOid = NULL;
  10482. /* Check key validity. */
  10483. if ((key == NULL) || (key->dp == NULL)) {
  10484. ret = BAD_FUNC_ARG;
  10485. }
  10486. if (ret == 0) {
  10487. /* Calculate the size of the encoded public point. */
  10488. PRIVATE_KEY_UNLOCK();
  10489. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  10490. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  10491. /* in earlier versions of FIPS the get length functionality is not
  10492. * available with compressed keys */
  10493. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  10494. if (comp)
  10495. pubSz = 1 + pubSz;
  10496. else
  10497. pubSz = 1 + 2 * pubSz;
  10498. ret = LENGTH_ONLY_E;
  10499. #else
  10500. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  10501. #endif
  10502. PRIVATE_KEY_LOCK();
  10503. /* LENGTH_ONLY_E on success. */
  10504. if (ret == LENGTH_ONLY_E) {
  10505. ret = 0;
  10506. }
  10507. }
  10508. if ((ret == 0) && with_header) {
  10509. /* Including SubjectPublicKeyInfo header. */
  10510. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  10511. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  10512. /* Get the length of the named curve OID to put into the encoding. */
  10513. curveIdSz = SetCurve(key, NULL, 0);
  10514. if (curveIdSz < 0) {
  10515. ret = curveIdSz;
  10516. }
  10517. if (ret == 0) {
  10518. /* Set the key type OID. */
  10519. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  10520. oidKeyType);
  10521. /* Set the curve OID. */
  10522. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  10523. NULL, (word32)curveIdSz);
  10524. /* Don't try to write out explicit parameters. */
  10525. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  10526. /* Set size of public point to ensure space is made for it. */
  10527. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  10528. /* Calculate size of ECC public key. */
  10529. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  10530. eccPublicKeyASN_Length, &sz);
  10531. }
  10532. /* Check buffer, if passed in, is big enough for encoded data. */
  10533. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  10534. ret = BUFFER_E;
  10535. }
  10536. if ((ret == 0) && (output != NULL)) {
  10537. /* Encode ECC public key. */
  10538. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  10539. output);
  10540. /* Skip to where public point is to be encoded. */
  10541. output += sz - (int)pubSz;
  10542. /* Cache the location to place the name curve OID. */
  10543. curveOid = (byte*)
  10544. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  10545. }
  10546. FREE_ASNSETDATA(dataASN, key->heap);
  10547. }
  10548. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  10549. ret = BUFFER_E;
  10550. }
  10551. else {
  10552. /* Total size is the public point size. */
  10553. sz = (int)pubSz;
  10554. }
  10555. if ((ret == 0) && (output != NULL)) {
  10556. /* Put named curve OID data into encoding. */
  10557. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  10558. if (curveIdSz < 0) {
  10559. ret = curveIdSz;
  10560. }
  10561. }
  10562. if ((ret == 0) && (output != NULL)) {
  10563. /* Encode public point. */
  10564. PRIVATE_KEY_UNLOCK();
  10565. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  10566. PRIVATE_KEY_LOCK();
  10567. }
  10568. if (ret == 0) {
  10569. /* Return the size of the encoding. */
  10570. ret = sz;
  10571. }
  10572. return ret;
  10573. #endif
  10574. }
  10575. /* Encode the public part of an ECC key in a DER.
  10576. *
  10577. * Pass NULL for output to get the size of the encoding.
  10578. *
  10579. * @param [in] key ECC key object.
  10580. * @param [out] output Buffer to hold DER encoding.
  10581. * @param [in] inLen Size of buffer in bytes.
  10582. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  10583. * @return Size of encoded data in bytes on success.
  10584. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10585. * @return MEMORY_E when dynamic memory allocation failed.
  10586. */
  10587. WOLFSSL_ABI
  10588. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  10589. int with_AlgCurve)
  10590. {
  10591. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  10592. }
  10593. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  10594. int with_AlgCurve, int comp)
  10595. {
  10596. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  10597. }
  10598. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  10599. {
  10600. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  10601. }
  10602. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10603. #ifdef WOLFSSL_ASN_TEMPLATE
  10604. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  10605. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  10606. * RFC 8410, 4 - Subject Public Key Fields
  10607. */
  10608. static const ASNItem edPubKeyASN[] = {
  10609. /* SubjectPublicKeyInfo */
  10610. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10611. /* AlgorithmIdentifier */
  10612. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10613. /* Ed25519/Ed448 OID */
  10614. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  10615. /* Public key stream */
  10616. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10617. };
  10618. enum {
  10619. EDPUBKEYASN_IDX_SEQ = 0,
  10620. EDPUBKEYASN_IDX_ALGOID_SEQ,
  10621. EDPUBKEYASN_IDX_ALGOID_OID,
  10622. EDPUBKEYASN_IDX_PUBKEY
  10623. };
  10624. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  10625. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  10626. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  10627. #endif /* WOLFSSL_ASN_TEMPLATE */
  10628. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  10629. /* Build ASN.1 formatted public key based on RFC 8410
  10630. *
  10631. * Pass NULL for output to get the size of the encoding.
  10632. *
  10633. * @param [in] pubKey public key buffer
  10634. * @param [in] pubKeyLen public ket buffer length
  10635. * @param [out] output Buffer to put encoded data in (optional)
  10636. * @param [in] outLen Size of buffer in bytes
  10637. * @param [in] keyType is "enum Key_Sum" like ED25519k
  10638. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  10639. * @return Size of encoded data in bytes on success
  10640. * @return BAD_FUNC_ARG when key is NULL.
  10641. * @return MEMORY_E when dynamic memory allocation failed.
  10642. */
  10643. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  10644. byte* output, word32 outLen, int keyType, int withHeader)
  10645. {
  10646. int ret = 0;
  10647. #ifndef WOLFSSL_ASN_TEMPLATE
  10648. word32 idx = 0;
  10649. word32 seqDataSz = 0;
  10650. word32 sz;
  10651. #else
  10652. int sz = 0;
  10653. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  10654. #endif
  10655. if (pubKey == NULL) {
  10656. return BAD_FUNC_ARG;
  10657. }
  10658. #ifndef WOLFSSL_ASN_TEMPLATE
  10659. /* calculate size */
  10660. if (withHeader) {
  10661. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  10662. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  10663. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  10664. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  10665. }
  10666. else {
  10667. sz = pubKeyLen;
  10668. }
  10669. /* checkout output size */
  10670. if (output != NULL && sz > outLen) {
  10671. ret = BUFFER_E;
  10672. }
  10673. /* headers */
  10674. if (ret == 0 && output != NULL && withHeader) {
  10675. /* sequence */
  10676. idx = SetSequence(seqDataSz, output);
  10677. /* algo */
  10678. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  10679. /* bit string */
  10680. idx += SetBitString(pubKeyLen, 0, output + idx);
  10681. }
  10682. if (ret == 0 && output != NULL) {
  10683. /* pub */
  10684. XMEMCPY(output + idx, pubKey, pubKeyLen);
  10685. idx += pubKeyLen;
  10686. sz = idx;
  10687. }
  10688. if (ret == 0) {
  10689. ret = (int)sz;
  10690. }
  10691. #else
  10692. if (withHeader) {
  10693. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  10694. if (ret == 0) {
  10695. /* Set the OID. */
  10696. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  10697. oidKeyType);
  10698. /* Leave space for public point. */
  10699. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  10700. /* Calculate size of public key encoding. */
  10701. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  10702. }
  10703. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  10704. ret = BUFFER_E;
  10705. }
  10706. if ((ret == 0) && (output != NULL)) {
  10707. /* Encode public key. */
  10708. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  10709. /* Set location to encode public point. */
  10710. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  10711. }
  10712. FREE_ASNSETDATA(dataASN, NULL);
  10713. }
  10714. else if ((output != NULL) && (pubKeyLen > outLen)) {
  10715. ret = BUFFER_E;
  10716. }
  10717. else if (ret == 0) {
  10718. sz = (int)pubKeyLen;
  10719. }
  10720. if ((ret == 0) && (output != NULL)) {
  10721. /* Put public key into space provided. */
  10722. XMEMCPY(output, pubKey, pubKeyLen);
  10723. }
  10724. if (ret == 0) {
  10725. ret = sz;
  10726. }
  10727. #endif /* WOLFSSL_ASN_TEMPLATE */
  10728. return ret;
  10729. }
  10730. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  10731. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  10732. /* Encode the public part of an Ed25519 key in DER.
  10733. *
  10734. * Pass NULL for output to get the size of the encoding.
  10735. *
  10736. * @param [in] key Ed25519 key object.
  10737. * @param [out] output Buffer to put encoded data in.
  10738. * @param [in] outLen Size of buffer in bytes.
  10739. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10740. * @return Size of encoded data in bytes on success.
  10741. * @return BAD_FUNC_ARG when key is NULL.
  10742. * @return MEMORY_E when dynamic memory allocation failed.
  10743. */
  10744. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  10745. int withAlg)
  10746. {
  10747. int ret;
  10748. byte pubKey[ED25519_PUB_KEY_SIZE];
  10749. word32 pubKeyLen = (word32)sizeof(pubKey);
  10750. if (key == NULL) {
  10751. return BAD_FUNC_ARG;
  10752. }
  10753. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  10754. if (ret == 0) {
  10755. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10756. ED25519k, withAlg);
  10757. }
  10758. return ret;
  10759. }
  10760. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  10761. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  10762. /* Encode the public part of an Ed448 key in DER.
  10763. *
  10764. * Pass NULL for output to get the size of the encoding.
  10765. *
  10766. * @param [in] key Ed448 key object.
  10767. * @param [out] output Buffer to put encoded data in.
  10768. * @param [in] outLen Size of buffer in bytes.
  10769. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10770. * @return Size of encoded data in bytes on success.
  10771. * @return BAD_FUNC_ARG when key is NULL.
  10772. * @return MEMORY_E when dynamic memory allocation failed.
  10773. */
  10774. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  10775. int withAlg)
  10776. {
  10777. int ret;
  10778. byte pubKey[ED448_PUB_KEY_SIZE];
  10779. word32 pubKeyLen = (word32)sizeof(pubKey);
  10780. if (key == NULL) {
  10781. return BAD_FUNC_ARG;
  10782. }
  10783. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  10784. if (ret == 0) {
  10785. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10786. ED448k, withAlg);
  10787. }
  10788. return ret;
  10789. }
  10790. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  10791. #if !defined(NO_RSA) && !defined(NO_CERTS)
  10792. #ifdef WOLFSSL_ASN_TEMPLATE
  10793. /* ASN.1 template for header before RSA key in certificate. */
  10794. static const ASNItem rsaCertKeyASN[] = {
  10795. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10796. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10797. };
  10798. enum {
  10799. RSACERTKEYASN_IDX_STR = 0,
  10800. RSACERTKEYASN_IDX_SEQ
  10801. };
  10802. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10803. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10804. #endif
  10805. /* Store RSA key pointer and length in certificate object.
  10806. *
  10807. * @param [in, out] cert Certificate object.
  10808. * @param [in] source Buffer containing encoded key.
  10809. * @param [in, out] srcIdx On in, start of RSA key data.
  10810. * On out, start of element after RSA key data.
  10811. * @param [in] maxIdx Maximum index of key data.
  10812. * @return 0 on success.
  10813. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10814. * is invalid.
  10815. * @return BUFFER_E when data in buffer is too small.
  10816. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10817. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10818. * non-zero length.
  10819. */
  10820. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10821. word32 maxIdx)
  10822. {
  10823. #ifndef WOLFSSL_ASN_TEMPLATE
  10824. int length;
  10825. int pubLen;
  10826. word32 pubIdx;
  10827. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10828. return ASN_PARSE_E;
  10829. pubIdx = *srcIdx;
  10830. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10831. return ASN_PARSE_E;
  10832. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10833. cert->sigCtx.CertAtt.pubkey_n_start =
  10834. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10835. #endif
  10836. cert->pubKeySize = (word32)pubLen;
  10837. cert->publicKey = source + pubIdx;
  10838. #ifdef WOLFSSL_MAXQ10XX_TLS
  10839. cert->publicKeyIndex = pubIdx;
  10840. #endif
  10841. *srcIdx += (word32)length;
  10842. #ifdef HAVE_OCSP
  10843. return CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10844. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10845. #else
  10846. return 0;
  10847. #endif
  10848. #else
  10849. ASNGetData dataASN[rsaCertKeyASN_Length];
  10850. int ret;
  10851. /* No dynamic data. */
  10852. XMEMSET(dataASN, 0, sizeof(dataASN));
  10853. /* Decode the header before the key data. */
  10854. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10855. srcIdx, maxIdx);
  10856. if (ret == 0) {
  10857. /* Store the pointer and length in certificate object starting at
  10858. * SEQUENCE. */
  10859. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10860. &cert->publicKey, &cert->pubKeySize);
  10861. #ifdef WOLFSSL_MAXQ10XX_TLS
  10862. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10863. #endif
  10864. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10865. /* Start of SEQUENCE. */
  10866. cert->sigCtx.CertAtt.pubkey_n_start =
  10867. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10868. #endif
  10869. #ifdef HAVE_OCSP
  10870. /* Calculate the hash of the public key for OCSP. */
  10871. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10872. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10873. #endif
  10874. }
  10875. return ret;
  10876. #endif /* WOLFSSL_ASN_TEMPLATE */
  10877. }
  10878. #endif /* !NO_RSA && !NO_CERTS */
  10879. #if defined(HAVE_ECC) && !defined(NO_CERTS)
  10880. #ifdef WOLFSSL_ASN_TEMPLATE
  10881. /* ASN.1 template for header before ECC key in certificate. */
  10882. static const ASNItem eccCertKeyASN[] = {
  10883. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10884. /* Algo parameters */
  10885. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10886. /* Subject public key */
  10887. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10888. };
  10889. enum {
  10890. ECCCERTKEYASN_IDX_OID = 0,
  10891. ECCCERTKEYASN_IDX_PARAMS,
  10892. ECCCERTKEYASN_IDX_SUBJPUBKEY
  10893. };
  10894. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10895. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10896. #endif /* WOLFSSL_ASN_TEMPLATE */
  10897. /* Store public ECC key in certificate object.
  10898. *
  10899. * Parse parameters and store public key data.
  10900. *
  10901. * @param [in, out] cert Certificate object.
  10902. * @param [in] source Buffer containing encoded key.
  10903. * @param [in, out] srcIdx On in, start of ECC key data.
  10904. * On out, start of element after ECC key data.
  10905. * @param [in] maxIdx Maximum index of key data.
  10906. * @param [in] pubKey Buffer holding encoded public key.
  10907. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10908. * @return 0 on success.
  10909. * @return BAD_FUNC_ARG when pubKey is NULL.
  10910. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10911. * is invalid.
  10912. * @return BUFFER_E when data in buffer is too small.
  10913. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10914. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10915. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10916. * non-zero length.
  10917. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10918. */
  10919. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10920. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10921. {
  10922. #ifndef WOLFSSL_ASN_TEMPLATE
  10923. int ret;
  10924. word32 localIdx;
  10925. byte* publicKey;
  10926. byte tag;
  10927. int length;
  10928. if (pubKey == NULL) {
  10929. return BAD_FUNC_ARG;
  10930. }
  10931. localIdx = *srcIdx;
  10932. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10933. return ASN_PARSE_E;
  10934. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10935. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10936. maxIdx) < 0)
  10937. return ASN_PARSE_E;
  10938. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10939. return ECC_CURVE_OID_E;
  10940. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10941. cert->sigCtx.CertAtt.curve_id = ret;
  10942. #else
  10943. (void)ret;
  10944. #endif
  10945. /* key header */
  10946. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10947. if (ret != 0)
  10948. return ret;
  10949. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10950. cert->sigCtx.CertAtt.pubkey_n_start =
  10951. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10952. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10953. cert->sigCtx.CertAtt.pubkey_e_start +=
  10954. cert->sigCtx.CertAtt.pubkey_n_len;
  10955. cert->sigCtx.CertAtt.pubkey_e_len =
  10956. cert->sigCtx.CertAtt.pubkey_n_len;
  10957. #endif
  10958. #ifdef WOLFSSL_MAXQ10XX_TLS
  10959. cert->publicKeyIndex = *srcIdx + 1;
  10960. #endif
  10961. #ifdef HAVE_OCSP
  10962. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10963. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10964. if (ret != 0)
  10965. return ret;
  10966. #endif
  10967. *srcIdx += (word32)length;
  10968. }
  10969. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10970. if (publicKey == NULL)
  10971. return MEMORY_E;
  10972. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10973. cert->publicKey = publicKey;
  10974. cert->pubKeyStored = 1;
  10975. cert->pubKeySize = pubKeyLen;
  10976. return 0;
  10977. #else
  10978. int ret = 0;
  10979. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10980. byte* publicKey;
  10981. /* Validate parameters. */
  10982. if (pubKey == NULL) {
  10983. ret = BAD_FUNC_ARG;
  10984. }
  10985. /* Clear dynamic data and check OID is a curve. */
  10986. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  10987. if (ret == 0) {
  10988. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  10989. /* Parse ECC public key header. */
  10990. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  10991. source, srcIdx, maxIdx);
  10992. }
  10993. if (ret == 0) {
  10994. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  10995. /* Store curve OID. */
  10996. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  10997. }
  10998. /* Ignore explicit parameters. */
  10999. #ifdef WOLFSSL_MAXQ10XX_TLS
  11000. cert->publicKeyIndex =
  11001. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  11002. + 1;
  11003. #endif
  11004. #ifdef HAVE_OCSP
  11005. /* Calculate the hash of the subject public key for OCSP. */
  11006. ret = CalcHashId_ex(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  11007. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  11008. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  11009. }
  11010. if (ret == 0) {
  11011. #endif
  11012. /* Store public key data length. */
  11013. cert->pubKeySize = pubKeyLen;
  11014. /* Must allocated space for key.
  11015. * Don't memcpy into constant pointer so use temp. */
  11016. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  11017. DYNAMIC_TYPE_PUBLIC_KEY);
  11018. if (publicKey == NULL) {
  11019. ret = MEMORY_E;
  11020. }
  11021. else {
  11022. /* Copy in whole public key and store pointer. */
  11023. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  11024. cert->publicKey = publicKey;
  11025. /* Indicate publicKey needs to be freed. */
  11026. cert->pubKeyStored = 1;
  11027. }
  11028. }
  11029. FREE_ASNGETDATA(dataASN, cert->heap);
  11030. return ret;
  11031. #endif /* WOLFSSL_ASN_TEMPLATE */
  11032. }
  11033. #endif /* HAVE_ECC && !NO_CERTS */
  11034. #ifndef NO_CERTS
  11035. #if !defined(NO_DSA)
  11036. #ifdef WOLFSSL_ASN_TEMPLATE
  11037. /* ASN.1 template for DSA key in certificate.
  11038. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  11039. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  11040. */
  11041. static const ASNItem dsaCertKeyASN[] = {
  11042. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  11043. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11044. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11045. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11046. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  11047. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  11048. };
  11049. /* Number of items in ASN.1 template for DSA key in certificate. */
  11050. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  11051. #endif /* WOLFSSL_ASN_TEMPLATE */
  11052. /* Parse DSA parameters to ensure valid.
  11053. *
  11054. * @param [in] source Buffer containing encoded key.
  11055. * @param [in, out] srcIdx On in, start of DSA key data.
  11056. * On out, start of element after DSA key data.
  11057. * @param [in] maxIdx Maximum index of key data.
  11058. * @param [in] heap Dynamic memory hint.
  11059. * @return 0 on success.
  11060. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11061. * is invalid.
  11062. * @return BUFFER_E when data in buffer is too small.
  11063. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11064. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  11065. * non-zero length.
  11066. */
  11067. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  11068. void* heap)
  11069. {
  11070. #ifndef WOLFSSL_ASN_TEMPLATE
  11071. int ret;
  11072. int length;
  11073. (void)heap;
  11074. ret = GetSequence(source, srcIdx, &length, maxIdx);
  11075. if (ret < 0)
  11076. return ret;
  11077. ret = SkipInt(source, srcIdx, maxIdx);
  11078. if (ret != 0)
  11079. return ret;
  11080. ret = SkipInt(source, srcIdx, maxIdx);
  11081. if (ret != 0)
  11082. return ret;
  11083. ret = SkipInt(source, srcIdx, maxIdx);
  11084. if (ret != 0)
  11085. return ret;
  11086. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  11087. if (ret != 0)
  11088. return ret;
  11089. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  11090. if (ret != 0)
  11091. return ASN_PARSE_E;
  11092. *srcIdx += (word32)length;
  11093. return 0;
  11094. #else
  11095. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  11096. int ret = 0;
  11097. (void)heap;
  11098. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  11099. if (ret == 0) {
  11100. /* Parse the DSA key data to ensure valid. */
  11101. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  11102. source, srcIdx, maxIdx);
  11103. }
  11104. FREE_ASNGETDATA(dataASN, heap);
  11105. return ret;
  11106. #endif /* WOLFSSL_ASN_TEMPLATE */
  11107. }
  11108. #endif /* !NO_DSA */
  11109. /* Decode the SubjectPublicKeyInfo block in a certificate.
  11110. *
  11111. * Stores the public key in fields of the certificate object.
  11112. * Validates the BER/DER items and does not store in a key object.
  11113. *
  11114. * @param [in, out] cert Decoded certificate oject.
  11115. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  11116. * @param [in, out] inOutIdx On in, start of public key.
  11117. * On out, start of ASN.1 item after public key.
  11118. * @param [in] maxIdx Maximum index of key data.
  11119. * @return 0 on success.
  11120. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11121. * is invalid.
  11122. * @return BUFFER_E when data in buffer is too small.
  11123. */
  11124. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  11125. word32 maxIdx)
  11126. {
  11127. word32 srcIdx = *inOutIdx;
  11128. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11129. int pubLen;
  11130. #endif
  11131. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11132. int pubIdx = (int)srcIdx;
  11133. #endif
  11134. int ret = 0;
  11135. int length;
  11136. /* Validate paramaters. */
  11137. if (source == NULL) {
  11138. return ASN_PARSE_E;
  11139. }
  11140. #ifndef WOLFSSL_ASN_TEMPLATE
  11141. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  11142. #else
  11143. /* Get SEQUENCE and expect all data to be accounted for. */
  11144. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  11145. #endif
  11146. {
  11147. return ASN_PARSE_E;
  11148. }
  11149. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11150. pubLen = (int)srcIdx - pubIdx + length;
  11151. #endif
  11152. maxIdx = srcIdx + (word32)length;
  11153. /* Decode the algorithm identifier for the key. */
  11154. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  11155. return ASN_PARSE_E;
  11156. }
  11157. (void)length;
  11158. /* Parse each type of public key. */
  11159. switch (cert->keyOID) {
  11160. #ifndef NO_RSA
  11161. #ifdef WC_RSA_PSS
  11162. case RSAPSSk:
  11163. if (srcIdx != maxIdx &&
  11164. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  11165. word32 seqIdx = srcIdx;
  11166. int seqLen;
  11167. /* Not set when -1. */
  11168. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  11169. int mgf = -1;
  11170. int saltLen = 0;
  11171. /* Defaults for sig algorithm parameters. */
  11172. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  11173. int sigMgf = WC_MGF1SHA1;
  11174. int sigSaltLen = 20;
  11175. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  11176. return ASN_PARSE_E;
  11177. }
  11178. /* Get the pubic key parameters. */
  11179. ret = DecodeRsaPssParams(source + seqIdx,
  11180. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  11181. if (ret != 0) {
  11182. return ASN_PARSE_E;
  11183. }
  11184. /* Get the signature parameters. */
  11185. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  11186. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  11187. if (ret != 0) {
  11188. return ASN_PARSE_E;
  11189. }
  11190. /* Validated signature params match public key params. */
  11191. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  11192. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  11193. return ASN_PARSE_E;
  11194. }
  11195. if (mgf != -1 && mgf != sigMgf) {
  11196. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  11197. return ASN_PARSE_E;
  11198. }
  11199. if (saltLen > sigSaltLen) {
  11200. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  11201. return ASN_PARSE_E;
  11202. }
  11203. srcIdx += (word32)seqLen;
  11204. }
  11205. FALL_THROUGH;
  11206. #endif /* WC_RSA_PSS */
  11207. case RSAk:
  11208. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  11209. break;
  11210. #endif /* NO_RSA */
  11211. #ifdef HAVE_ECC
  11212. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11213. case SM2k:
  11214. #endif
  11215. case ECDSAk:
  11216. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  11217. (word32)pubLen);
  11218. break;
  11219. #endif /* HAVE_ECC */
  11220. #ifdef HAVE_ED25519
  11221. case ED25519k:
  11222. cert->pkCurveOID = ED25519k;
  11223. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11224. break;
  11225. #endif /* HAVE_ED25519 */
  11226. #ifdef HAVE_ED448
  11227. case ED448k:
  11228. cert->pkCurveOID = ED448k;
  11229. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11230. break;
  11231. #endif /* HAVE_ED448 */
  11232. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  11233. #ifdef HAVE_FALCON
  11234. case FALCON_LEVEL1k:
  11235. cert->pkCurveOID = FALCON_LEVEL1k;
  11236. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11237. break;
  11238. case FALCON_LEVEL5k:
  11239. cert->pkCurveOID = FALCON_LEVEL5k;
  11240. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11241. break;
  11242. #endif /* HAVE_FALCON */
  11243. #ifdef HAVE_DILITHIUM
  11244. case DILITHIUM_LEVEL2k:
  11245. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  11246. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11247. break;
  11248. case DILITHIUM_LEVEL3k:
  11249. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  11250. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11251. break;
  11252. case DILITHIUM_LEVEL5k:
  11253. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  11254. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11255. break;
  11256. #endif /* HAVE_DILITHIUM */
  11257. #ifdef HAVE_SPHINCS
  11258. case SPHINCS_FAST_LEVEL1k:
  11259. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  11260. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11261. break;
  11262. case SPHINCS_FAST_LEVEL3k:
  11263. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  11264. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11265. break;
  11266. case SPHINCS_FAST_LEVEL5k:
  11267. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  11268. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11269. break;
  11270. case SPHINCS_SMALL_LEVEL1k:
  11271. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  11272. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11273. break;
  11274. case SPHINCS_SMALL_LEVEL3k:
  11275. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  11276. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11277. break;
  11278. case SPHINCS_SMALL_LEVEL5k:
  11279. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  11280. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11281. break;
  11282. #endif /* HAVE_SPHINCS */
  11283. #endif /* HAVE_PQC */
  11284. #ifndef NO_DSA
  11285. case DSAk:
  11286. cert->publicKey = source + pubIdx;
  11287. cert->pubKeySize = (word32)pubLen;
  11288. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  11289. break;
  11290. #endif /* NO_DSA */
  11291. default:
  11292. WOLFSSL_MSG("Unknown or not compiled in key OID");
  11293. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  11294. ret = ASN_UNKNOWN_OID_E;
  11295. }
  11296. /* Return index after public key. */
  11297. *inOutIdx = srcIdx;
  11298. /* Return error code. */
  11299. return ret;
  11300. }
  11301. #endif
  11302. /* Return the hash algorithm to use with the signature algorithm.
  11303. *
  11304. * @param [in] oidSum Signature id.
  11305. * @return Hash algorithm id.
  11306. */
  11307. int HashIdAlg(word32 oidSum)
  11308. {
  11309. (void)oidSum;
  11310. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11311. if (oidSum == CTC_SM3wSM2) {
  11312. return WC_SM3;
  11313. }
  11314. if (oidSum == SM2k) {
  11315. return WC_SM3;
  11316. }
  11317. #endif
  11318. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11319. return WC_SHA256;
  11320. #else
  11321. return WC_SHA;
  11322. #endif
  11323. }
  11324. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11325. *
  11326. * @param [in] data Data to hash.
  11327. * @param [in] len Length of data to hash.
  11328. * @param [out] hash Buffer to hold hash.
  11329. * @return 0 on success.
  11330. * @return MEMORY_E when dynamic memory allocation fails.
  11331. */
  11332. int CalcHashId(const byte* data, word32 len, byte* hash)
  11333. {
  11334. /* Use default hash algorithm. */
  11335. return CalcHashId_ex(data, len, hash,
  11336. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11337. WC_SHA256
  11338. #else
  11339. WC_SHA
  11340. #endif
  11341. );
  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_ex(const byte* data, word32 len, byte* hash, int hashAlg)
  11352. {
  11353. int ret;
  11354. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11355. if (hashAlg == WC_SM3) {
  11356. ret = wc_Sm3Hash(data, len, hash);
  11357. }
  11358. else
  11359. #endif
  11360. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11361. if (hashAlg == WC_SHA256) {
  11362. ret = wc_Sha256Hash(data, len, hash);
  11363. }
  11364. else
  11365. #elif !defined(NO_SHA)
  11366. if (hashAlg == WC_SHA) {
  11367. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11368. XMEMSET(hash + WC_SHA_DIGEST_SIZE, 0, KEYID_SIZE - WC_SHA_DIGEST_SIZE);
  11369. #endif
  11370. ret = wc_ShaHash(data, len, hash);
  11371. }
  11372. else
  11373. #else
  11374. (void)data;
  11375. (void)len;
  11376. (void)hash;
  11377. #endif
  11378. {
  11379. ret = NOT_COMPILED_IN;
  11380. }
  11381. return ret;
  11382. }
  11383. #ifndef NO_CERTS
  11384. /* Get the hash of the id using the SHA-1 or SHA-256.
  11385. *
  11386. * If the id is not the length of the hash, then hash it.
  11387. *
  11388. * @param [in] id Id to get hash for.
  11389. * @param [in] len Length of id in bytes.
  11390. * @param [out] hash Buffer to hold hash.
  11391. * @return 0 on success.
  11392. * @return MEMORY_E when dynamic memory allocation fails.
  11393. */
  11394. static int GetHashId(const byte* id, int length, byte* hash, int hashAlg)
  11395. {
  11396. int ret;
  11397. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11398. if (length == wc_HashGetDigestSize(wc_HashTypeConvert(hashAlg)))
  11399. #else
  11400. if (length == KEYID_SIZE)
  11401. #endif
  11402. {
  11403. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11404. XMEMSET(hash + length, 0, KEYID_SIZE - length);
  11405. #endif
  11406. XMEMCPY(hash, id, (size_t)length);
  11407. ret = 0;
  11408. }
  11409. else {
  11410. ret = CalcHashId_ex(id, (word32)length, hash, hashAlg);
  11411. }
  11412. return ret;
  11413. }
  11414. #endif /* !NO_CERTS */
  11415. #ifdef WOLFSSL_ASN_TEMPLATE
  11416. /* Id for email address. */
  11417. #define ASN_EMAIL 0x100
  11418. /* Id for domain component. */
  11419. #define ASN_DC 0x102
  11420. /* Id for jurisdiction country. */
  11421. #define ASN_JURIS_C 0x203
  11422. /* Id for jurisdiction state. */
  11423. #define ASN_JURIS_ST 0x202
  11424. /* Set the string for a name component into the subject name. */
  11425. #define SetCertNameSubject(cert, id, val) \
  11426. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  11427. /* Set the string length for a name component into the subject name. */
  11428. #define SetCertNameSubjectLen(cert, id, val) \
  11429. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  11430. /* Set the encoding for a name component into the subject name. */
  11431. #define SetCertNameSubjectEnc(cert, id, val) \
  11432. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  11433. /* Get the string of a name component from the subject name. */
  11434. #define GetCertNameSubjectStr(id) \
  11435. (certNameSubject[(id) - 3].str)
  11436. /* Get the string length of a name component from the subject name. */
  11437. #define GetCertNameSubjectStrLen(id) \
  11438. (certNameSubject[(id) - 3].strLen)
  11439. /* Get the NID of a name component from the subject name. */
  11440. #define GetCertNameSubjectNID(id) \
  11441. (certNameSubject[(id) - 3].nid)
  11442. #define ValidCertNameSubject(id) \
  11443. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  11444. (certNameSubject[(id) - 3].strLen > 0))
  11445. /* Mapping of certificate name component to useful information. */
  11446. typedef struct CertNameData {
  11447. /* Type string of name component. */
  11448. const char* str;
  11449. /* Length of type string of name component. */
  11450. byte strLen;
  11451. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11452. /* Offset of data in subject name component. */
  11453. size_t data;
  11454. /* Offset of length in subject name component. */
  11455. size_t len;
  11456. /* Offset of encoding in subject name component. */
  11457. size_t enc;
  11458. #endif
  11459. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11460. /* NID of type for subject name component. */
  11461. int nid;
  11462. #endif
  11463. } CertNameData;
  11464. /* List of data for common name components. */
  11465. static const CertNameData certNameSubject[] = {
  11466. /* Common Name */
  11467. {
  11468. "/CN=", 4,
  11469. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11470. OFFSETOF(DecodedCert, subjectCN),
  11471. OFFSETOF(DecodedCert, subjectCNLen),
  11472. OFFSETOF(DecodedCert, subjectCNEnc),
  11473. #endif
  11474. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11475. NID_commonName
  11476. #endif
  11477. },
  11478. /* Surname */
  11479. {
  11480. "/SN=", 4,
  11481. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11482. OFFSETOF(DecodedCert, subjectSN),
  11483. OFFSETOF(DecodedCert, subjectSNLen),
  11484. OFFSETOF(DecodedCert, subjectSNEnc),
  11485. #endif
  11486. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11487. NID_surname
  11488. #endif
  11489. },
  11490. /* Serial Number */
  11491. {
  11492. "/serialNumber=", 14,
  11493. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11494. OFFSETOF(DecodedCert, subjectSND),
  11495. OFFSETOF(DecodedCert, subjectSNDLen),
  11496. OFFSETOF(DecodedCert, subjectSNDEnc),
  11497. #endif
  11498. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11499. NID_serialNumber
  11500. #endif
  11501. },
  11502. /* Country Name */
  11503. {
  11504. "/C=", 3,
  11505. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11506. OFFSETOF(DecodedCert, subjectC),
  11507. OFFSETOF(DecodedCert, subjectCLen),
  11508. OFFSETOF(DecodedCert, subjectCEnc),
  11509. #endif
  11510. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11511. NID_countryName
  11512. #endif
  11513. },
  11514. /* Locality Name */
  11515. {
  11516. "/L=", 3,
  11517. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11518. OFFSETOF(DecodedCert, subjectL),
  11519. OFFSETOF(DecodedCert, subjectLLen),
  11520. OFFSETOF(DecodedCert, subjectLEnc),
  11521. #endif
  11522. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11523. NID_localityName
  11524. #endif
  11525. },
  11526. /* State Name */
  11527. {
  11528. "/ST=", 4,
  11529. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11530. OFFSETOF(DecodedCert, subjectST),
  11531. OFFSETOF(DecodedCert, subjectSTLen),
  11532. OFFSETOF(DecodedCert, subjectSTEnc),
  11533. #endif
  11534. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11535. NID_stateOrProvinceName
  11536. #endif
  11537. },
  11538. /* Street Address */
  11539. {
  11540. "/street=", 8,
  11541. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11542. OFFSETOF(DecodedCert, subjectStreet),
  11543. OFFSETOF(DecodedCert, subjectStreetLen),
  11544. OFFSETOF(DecodedCert, subjectStreetEnc),
  11545. #endif
  11546. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11547. NID_streetAddress
  11548. #endif
  11549. },
  11550. /* Organization Name */
  11551. {
  11552. "/O=", 3,
  11553. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11554. OFFSETOF(DecodedCert, subjectO),
  11555. OFFSETOF(DecodedCert, subjectOLen),
  11556. OFFSETOF(DecodedCert, subjectOEnc),
  11557. #endif
  11558. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11559. NID_organizationName
  11560. #endif
  11561. },
  11562. /* Organization Unit Name */
  11563. {
  11564. "/OU=", 4,
  11565. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11566. OFFSETOF(DecodedCert, subjectOU),
  11567. OFFSETOF(DecodedCert, subjectOULen),
  11568. OFFSETOF(DecodedCert, subjectOUEnc),
  11569. #endif
  11570. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11571. NID_organizationalUnitName
  11572. #endif
  11573. },
  11574. /* Title */
  11575. {
  11576. NULL, 0,
  11577. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11578. 0,
  11579. 0,
  11580. 0,
  11581. #endif
  11582. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11583. 0,
  11584. #endif
  11585. },
  11586. /* Undefined */
  11587. {
  11588. NULL, 0,
  11589. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11590. 0,
  11591. 0,
  11592. 0,
  11593. #endif
  11594. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11595. 0,
  11596. #endif
  11597. },
  11598. /* Undefined */
  11599. {
  11600. NULL, 0,
  11601. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11602. 0,
  11603. 0,
  11604. 0,
  11605. #endif
  11606. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11607. 0,
  11608. #endif
  11609. },
  11610. /* Business Category */
  11611. {
  11612. "/businessCategory=", 18,
  11613. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11614. OFFSETOF(DecodedCert, subjectBC),
  11615. OFFSETOF(DecodedCert, subjectBCLen),
  11616. OFFSETOF(DecodedCert, subjectBCEnc),
  11617. #endif
  11618. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11619. NID_businessCategory
  11620. #endif
  11621. },
  11622. /* Undefined */
  11623. {
  11624. NULL, 0,
  11625. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11626. 0,
  11627. 0,
  11628. 0,
  11629. #endif
  11630. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11631. 0,
  11632. #endif
  11633. },
  11634. /* Postal Code */
  11635. {
  11636. "/postalCode=", 12,
  11637. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11638. OFFSETOF(DecodedCert, subjectPC),
  11639. OFFSETOF(DecodedCert, subjectPCLen),
  11640. OFFSETOF(DecodedCert, subjectPCEnc),
  11641. #endif
  11642. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11643. NID_postalCode
  11644. #endif
  11645. },
  11646. /* User Id */
  11647. {
  11648. "/userid=", 8,
  11649. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11650. OFFSETOF(DecodedCert, subjectUID),
  11651. OFFSETOF(DecodedCert, subjectUIDLen),
  11652. OFFSETOF(DecodedCert, subjectUIDEnc),
  11653. #endif
  11654. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11655. NID_userId
  11656. #endif
  11657. },
  11658. #ifdef WOLFSSL_CERT_NAME_ALL
  11659. /* Name, id 41 */
  11660. {
  11661. "/N=", 3,
  11662. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11663. OFFSETOF(DecodedCert, subjectN),
  11664. OFFSETOF(DecodedCert, subjectNLen),
  11665. OFFSETOF(DecodedCert, subjectNEnc),
  11666. #endif
  11667. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11668. NID_name
  11669. #endif
  11670. },
  11671. /* Given Name, id 42 */
  11672. {
  11673. "/GN=", 4,
  11674. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11675. OFFSETOF(DecodedCert, subjectGN),
  11676. OFFSETOF(DecodedCert, subjectGNLen),
  11677. OFFSETOF(DecodedCert, subjectGNEnc),
  11678. #endif
  11679. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11680. NID_givenName
  11681. #endif
  11682. },
  11683. /* initials, id 43 */
  11684. {
  11685. "/initials=", 10,
  11686. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11687. OFFSETOF(DecodedCert, subjectI),
  11688. OFFSETOF(DecodedCert, subjectILen),
  11689. OFFSETOF(DecodedCert, subjectIEnc),
  11690. #endif
  11691. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11692. NID_initials
  11693. #endif
  11694. },
  11695. /* DN Qualifier Name, id 46 */
  11696. {
  11697. "/dnQualifier=", 13,
  11698. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11699. OFFSETOF(DecodedCert, subjectDNQ),
  11700. OFFSETOF(DecodedCert, subjectDNQLen),
  11701. OFFSETOF(DecodedCert, subjectDNQEnc),
  11702. #endif
  11703. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11704. NID_dnQualifier
  11705. #endif
  11706. },
  11707. #endif /* WOLFSSL_CERT_NAME_ALL */
  11708. };
  11709. static const int certNameSubjectSz =
  11710. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11711. /* ASN.1 template for an RDN.
  11712. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11713. */
  11714. static const ASNItem rdnASN[] = {
  11715. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11716. /* AttributeTypeAndValue */
  11717. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11718. /* AttributeType */
  11719. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11720. /* AttributeValue: Choice of tags - rdnChoice. */
  11721. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11722. };
  11723. enum {
  11724. RDNASN_IDX_SET = 0,
  11725. RDNASN_IDX_ATTR_SEQ,
  11726. RDNASN_IDX_ATTR_TYPE,
  11727. RDNASN_IDX_ATTR_VAL
  11728. };
  11729. /* Number of items in ASN.1 template for an RDN. */
  11730. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11731. /* Supported types of encodings (tags) for RDN strings.
  11732. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11733. * (IA5 String not listed in RFC but required for alternative types)
  11734. */
  11735. static const byte rdnChoice[] = {
  11736. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11737. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11738. };
  11739. #endif
  11740. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11741. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11742. * DNS entry
  11743. * return 0 on success
  11744. */
  11745. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11746. {
  11747. int ret = 0;
  11748. size_t nameSz;
  11749. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11750. unsigned char* ip;
  11751. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11752. return BAD_FUNC_ARG;
  11753. }
  11754. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11755. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11756. WOLFSSL_MSG("Unexpected IP size");
  11757. return BAD_FUNC_ARG;
  11758. }
  11759. ip = (unsigned char*)entry->name;
  11760. /* store IP addresses as a string */
  11761. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11762. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11763. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11764. >= (int)sizeof(tmpName))
  11765. {
  11766. WOLFSSL_MSG("IP buffer overrun");
  11767. return BUFFER_E;
  11768. }
  11769. }
  11770. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11771. size_t i;
  11772. for (i = 0; i < 8; i++) {
  11773. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11774. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11775. (i < 7) ? ":" : "")
  11776. >= (int)sizeof(tmpName))
  11777. {
  11778. WOLFSSL_MSG("IPv6 buffer overrun");
  11779. return BUFFER_E;
  11780. }
  11781. }
  11782. }
  11783. nameSz = XSTRLEN(tmpName);
  11784. entry->ipString = (char*)XMALLOC(nameSz + 1, heap,
  11785. DYNAMIC_TYPE_ALTNAME);
  11786. if (entry->ipString == NULL) {
  11787. ret = MEMORY_E;
  11788. }
  11789. if (ret == 0) {
  11790. XMEMCPY(entry->ipString, tmpName, nameSz);
  11791. entry->ipString[nameSz] = '\0';
  11792. }
  11793. (void)heap;
  11794. return ret;
  11795. }
  11796. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11797. #ifdef WOLFSSL_ASN_TEMPLATE
  11798. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11799. /* Adds a DNS entry to a list of DNS entries
  11800. *
  11801. * @param [in, out] lst Linked list of DNS name entries.
  11802. * @param [in] entry Entry to add to the list
  11803. * @return 0 on success.
  11804. */
  11805. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11806. {
  11807. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11808. entry->next = NULL;
  11809. if (*lst == NULL) {
  11810. /* First on list */
  11811. *lst = entry;
  11812. }
  11813. else {
  11814. DNS_entry* temp = *lst;
  11815. /* Find end */
  11816. for (; (temp->next != NULL); temp = temp->next);
  11817. /* Add to end */
  11818. temp->next = entry;
  11819. }
  11820. #else
  11821. /* Prepend entry to linked list. */
  11822. entry->next = *lst;
  11823. *lst = entry;
  11824. #endif
  11825. return 0;
  11826. }
  11827. /* Allocate a DNS entry and set the fields.
  11828. *
  11829. * @param [in] cert Certificate object.
  11830. * @param [in] str DNS name string.
  11831. * @param [in] strLen Length of DNS name string.
  11832. * @param [in] type Type of DNS name string.
  11833. * @param [in, out] entries Linked list of DNS name entries.
  11834. * @return 0 on success.
  11835. * @return MEMORY_E when dynamic memory allocation fails.
  11836. */
  11837. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11838. int type, DNS_entry** entries)
  11839. {
  11840. DNS_entry* dnsEntry;
  11841. int ret = 0;
  11842. /* Only used for heap. */
  11843. (void)cert;
  11844. /* TODO: consider one malloc. */
  11845. /* Allocate DNS Entry object. */
  11846. dnsEntry = AltNameNew(cert->heap);
  11847. if (dnsEntry == NULL) {
  11848. ret = MEMORY_E;
  11849. }
  11850. if (ret == 0) {
  11851. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11852. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  11853. DYNAMIC_TYPE_ALTNAME);
  11854. if (dnsEntry->name == NULL) {
  11855. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11856. ret = MEMORY_E;
  11857. }
  11858. }
  11859. if (ret == 0) {
  11860. /* Set tag type, name length, name and NUL terminate name. */
  11861. dnsEntry->type = type;
  11862. dnsEntry->len = strLen;
  11863. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  11864. dnsEntry->name[strLen] = '\0';
  11865. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11866. /* store IP addresses as a string */
  11867. if (type == ASN_IP_TYPE) {
  11868. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11869. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11870. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11871. }
  11872. }
  11873. }
  11874. if (ret == 0) {
  11875. #endif
  11876. ret = AddDNSEntryToList(entries, dnsEntry);
  11877. }
  11878. return ret;
  11879. }
  11880. #endif
  11881. /* Set the details of a subject name component into a certificate.
  11882. *
  11883. * @param [in, out] cert Certificate object.
  11884. * @param [in] id Id of component.
  11885. * @param [in] str String for component.
  11886. * @param [in] strLen Length of string.
  11887. * @param [in] tag BER tag representing encoding of string.
  11888. * @return 0 on success, negative values on failure.
  11889. */
  11890. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  11891. byte tag)
  11892. {
  11893. int ret = 0;
  11894. /* Put string and encoding into certificate. */
  11895. if (id == ASN_COMMON_NAME) {
  11896. cert->subjectCN = (char *)str;
  11897. cert->subjectCNLen = (int)strLen;
  11898. cert->subjectCNEnc = (char)tag;
  11899. }
  11900. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11901. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  11902. /* Use table and offsets to put data into appropriate fields. */
  11903. SetCertNameSubject(cert, id, (char*)str);
  11904. SetCertNameSubjectLen(cert, id, strLen);
  11905. SetCertNameSubjectEnc(cert, id, tag);
  11906. }
  11907. #endif
  11908. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11909. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11910. else if (id == ASN_EMAIL) {
  11911. cert->subjectEmail = (char*)str;
  11912. cert->subjectEmailLen = strLen;
  11913. }
  11914. #endif
  11915. #ifdef WOLFSSL_CERT_EXT
  11916. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  11917. else if (id == ASN_JURIS_C) {
  11918. cert->subjectJC = (char*)str;
  11919. cert->subjectJCLen = strLen;
  11920. cert->subjectJCEnc = (char)tag;
  11921. }
  11922. else if (id == ASN_JURIS_ST) {
  11923. cert->subjectJS = (char*)str;
  11924. cert->subjectJSLen = strLen;
  11925. cert->subjectJSEnc = (char)tag;
  11926. }
  11927. #endif
  11928. return ret;
  11929. }
  11930. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  11931. *
  11932. * @param [in, out] cert Certificate object.
  11933. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  11934. * @param [in, out] idx Index int full name to place next component.
  11935. * @param [in, out] nid NID of component type.
  11936. * @param [in] isSubject Whether this data is for a subject name.
  11937. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  11938. * @return 0 on success.
  11939. * @return MEMORY_E when dynamic memory allocation fails.
  11940. * @return ASN_PARSE_E when type not supported.
  11941. */
  11942. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  11943. int isSubject, ASNGetData* dataASN)
  11944. {
  11945. int ret = 0;
  11946. const char* typeStr = NULL;
  11947. byte typeStrLen = 0;
  11948. byte* oid;
  11949. word32 oidSz;
  11950. int id = 0;
  11951. (void)nid;
  11952. /* Get name type OID from data items. */
  11953. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  11954. /* v1 name types */
  11955. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  11956. id = oid[2];
  11957. /* Check range of supported ids in table. */
  11958. if (ValidCertNameSubject(id)) {
  11959. /* Get the type string, length and NID from table. */
  11960. typeStr = GetCertNameSubjectStr(id);
  11961. typeStrLen = GetCertNameSubjectStrLen(id);
  11962. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11963. *nid = GetCertNameSubjectNID(id);
  11964. #endif
  11965. }
  11966. }
  11967. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  11968. /* Set the email id, type string, length and NID. */
  11969. id = ASN_EMAIL;
  11970. typeStr = WOLFSSL_EMAIL_ADDR;
  11971. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11972. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11973. *nid = NID_emailAddress;
  11974. #endif
  11975. }
  11976. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  11977. /* Set the user id, type string, length and NID. */
  11978. id = ASN_USER_ID;
  11979. typeStr = WOLFSSL_USER_ID;
  11980. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  11981. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11982. *nid = NID_userId;
  11983. #endif
  11984. }
  11985. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  11986. /* Set the domain component, type string, length and NID. */
  11987. id = ASN_DC;
  11988. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  11989. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  11990. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11991. *nid = NID_domainComponent;
  11992. #endif
  11993. }
  11994. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  11995. /* Set the favourite drink, type string, length and NID. */
  11996. id = ASN_FAVOURITE_DRINK;
  11997. typeStr = WOLFSSL_FAVOURITE_DRINK;
  11998. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  11999. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12000. *nid = NID_favouriteDrink;
  12001. #endif
  12002. }
  12003. /* Other OIDs that start with the same values. */
  12004. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  12005. WOLFSSL_MSG("Unknown pilot attribute type");
  12006. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  12007. ret = ASN_PARSE_E;
  12008. }
  12009. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  12010. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  12011. /* Set the jurisdiction id. */
  12012. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  12013. /* Set the jurisdiction type string, length and NID if known. */
  12014. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  12015. typeStr = WOLFSSL_JOI_C;
  12016. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  12017. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12018. *nid = NID_jurisdictionCountryName;
  12019. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12020. }
  12021. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  12022. typeStr = WOLFSSL_JOI_ST;
  12023. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12024. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12025. *nid = NID_jurisdictionStateOrProvinceName;
  12026. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12027. }
  12028. else {
  12029. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  12030. }
  12031. }
  12032. if ((ret == 0) && (typeStr != NULL)) {
  12033. /* OID type to store for subject name and add to full string. */
  12034. byte* str;
  12035. word32 strLen;
  12036. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12037. /* Get the string reference and length. */
  12038. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12039. if (isSubject) {
  12040. /* Store subject field components. */
  12041. ret = SetSubject(cert, id, str, (int)strLen, tag);
  12042. }
  12043. if (ret == 0) {
  12044. /* Check there is space for this in the full name string and
  12045. * terminating NUL character. */
  12046. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  12047. {
  12048. /* Add RDN to full string. */
  12049. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  12050. *idx += typeStrLen;
  12051. XMEMCPY(&full[*idx], str, strLen);
  12052. *idx += strLen;
  12053. }
  12054. else {
  12055. WOLFSSL_MSG("ASN Name too big, skipping");
  12056. }
  12057. }
  12058. }
  12059. return ret;
  12060. }
  12061. #endif /* WOLFSSL_ASN_TEMPLATE */
  12062. /* Get a certificate name into the certificate object.
  12063. *
  12064. * @param [in, out] cert Decoded certificate object.
  12065. * @param [out] full Buffer to hold full name as a string.
  12066. * @param [out] hash Buffer to hold hash of name.
  12067. * @param [in] nameType ISSUER or SUBJECT.
  12068. * @param [in] input Buffer holding certificate name.
  12069. * @param [in, out] inOutIdx On in, start of certificate name.
  12070. * On out, start of ASN.1 item after cert name.
  12071. * @param [in] maxIdx Index of next item after certificate name.
  12072. * @return 0 on success.
  12073. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12074. * is invalid.
  12075. * @return BUFFER_E when data in buffer is too small.
  12076. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12077. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12078. * @return MEMORY_E when dynamic memory allocation fails.
  12079. */
  12080. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  12081. const byte* input, word32* inOutIdx, word32 maxIdx)
  12082. {
  12083. #ifndef WOLFSSL_ASN_TEMPLATE
  12084. int length; /* length of all distinguished names */
  12085. int dummy;
  12086. int ret;
  12087. word32 idx;
  12088. word32 srcIdx = *inOutIdx;
  12089. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12090. !defined(WOLFCRYPT_ONLY)
  12091. WOLFSSL_X509_NAME* dName = NULL;
  12092. #endif
  12093. WOLFSSL_MSG("Getting Cert Name");
  12094. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12095. * calculated over the entire DER encoding of the Name field, including
  12096. * the tag and length. */
  12097. if (CalcHashId_ex(input + *inOutIdx, maxIdx - *inOutIdx, hash,
  12098. HashIdAlg(cert->signatureOID)) != 0) {
  12099. return ASN_PARSE_E;
  12100. }
  12101. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12102. !defined(WOLFCRYPT_ONLY)
  12103. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12104. if (dName == NULL) {
  12105. return MEMORY_E;
  12106. }
  12107. #endif /* OPENSSL_EXTRA */
  12108. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  12109. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12110. !defined(WOLFCRYPT_ONLY)
  12111. wolfSSL_X509_NAME_free(dName);
  12112. #endif /* OPENSSL_EXTRA */
  12113. return ASN_PARSE_E;
  12114. }
  12115. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12116. /* store pointer to raw issuer */
  12117. if (nameType == ISSUER) {
  12118. cert->issuerRaw = &input[srcIdx];
  12119. cert->issuerRawLen = length;
  12120. }
  12121. #endif
  12122. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12123. if (nameType == SUBJECT) {
  12124. cert->subjectRaw = &input[srcIdx];
  12125. cert->subjectRawLen = length;
  12126. }
  12127. #endif
  12128. length += (int)srcIdx;
  12129. idx = 0;
  12130. while (srcIdx < (word32)length) {
  12131. byte b = 0;
  12132. byte joint[3];
  12133. byte tooBig = FALSE;
  12134. int oidSz;
  12135. const char* copy = NULL;
  12136. int copyLen = 0;
  12137. int strLen = 0;
  12138. byte id = 0;
  12139. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12140. && !defined(WOLFCRYPT_ONLY)
  12141. int nid = NID_undef;
  12142. int enc;
  12143. #endif /* OPENSSL_EXTRA */
  12144. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  12145. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  12146. }
  12147. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  12148. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12149. !defined(WOLFCRYPT_ONLY)
  12150. wolfSSL_X509_NAME_free(dName);
  12151. #endif /* OPENSSL_EXTRA */
  12152. return ASN_PARSE_E;
  12153. }
  12154. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  12155. if (ret != 0) {
  12156. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12157. !defined(WOLFCRYPT_ONLY)
  12158. wolfSSL_X509_NAME_free(dName);
  12159. #endif /* OPENSSL_EXTRA */
  12160. return ret;
  12161. }
  12162. /* make sure there is room for joint */
  12163. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  12164. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12165. !defined(WOLFCRYPT_ONLY)
  12166. wolfSSL_X509_NAME_free(dName);
  12167. #endif /* OPENSSL_EXTRA */
  12168. return ASN_PARSE_E;
  12169. }
  12170. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  12171. /* v1 name types */
  12172. if (joint[0] == 0x55 && joint[1] == 0x04) {
  12173. srcIdx += 3;
  12174. id = joint[2];
  12175. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  12176. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12177. !defined(WOLFCRYPT_ONLY)
  12178. wolfSSL_X509_NAME_free(dName);
  12179. #endif /* OPENSSL_EXTRA */
  12180. return ASN_PARSE_E;
  12181. }
  12182. if (id == ASN_COMMON_NAME) {
  12183. if (nameType == SUBJECT) {
  12184. cert->subjectCN = (char *)&input[srcIdx];
  12185. cert->subjectCNLen = strLen;
  12186. cert->subjectCNEnc = (char)b;
  12187. }
  12188. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12189. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12190. else if (nameType == ISSUER) {
  12191. cert->issuerCN = (char*)&input[srcIdx];
  12192. cert->issuerCNLen = strLen;
  12193. cert->issuerCNEnc = (char)b;
  12194. }
  12195. #endif
  12196. copy = WOLFSSL_COMMON_NAME;
  12197. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  12198. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12199. && !defined(WOLFCRYPT_ONLY)
  12200. nid = NID_commonName;
  12201. #endif /* OPENSSL_EXTRA */
  12202. }
  12203. #ifdef WOLFSSL_CERT_NAME_ALL
  12204. else if (id == ASN_NAME) {
  12205. copy = WOLFSSL_NAME;
  12206. copyLen = sizeof(WOLFSSL_NAME) - 1;
  12207. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12208. if (nameType == SUBJECT) {
  12209. cert->subjectN = (char*)&input[srcIdx];
  12210. cert->subjectNLen = strLen;
  12211. cert->subjectNEnc = b;
  12212. }
  12213. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12214. #if (defined(OPENSSL_EXTRA) || \
  12215. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12216. && !defined(WOLFCRYPT_ONLY)
  12217. nid = NID_name;
  12218. #endif /* OPENSSL_EXTRA */
  12219. }
  12220. else if (id == ASN_INITIALS) {
  12221. copy = WOLFSSL_INITIALS;
  12222. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  12223. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12224. if (nameType == SUBJECT) {
  12225. cert->subjectI = (char*)&input[srcIdx];
  12226. cert->subjectILen = strLen;
  12227. cert->subjectIEnc = b;
  12228. }
  12229. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12230. #if (defined(OPENSSL_EXTRA) || \
  12231. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12232. && !defined(WOLFCRYPT_ONLY)
  12233. nid = NID_initials;
  12234. #endif /* OPENSSL_EXTRA */
  12235. }
  12236. else if (id == ASN_GIVEN_NAME) {
  12237. copy = WOLFSSL_GIVEN_NAME;
  12238. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  12239. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12240. if (nameType == SUBJECT) {
  12241. cert->subjectGN = (char*)&input[srcIdx];
  12242. cert->subjectGNLen = strLen;
  12243. cert->subjectGNEnc = b;
  12244. }
  12245. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12246. #if (defined(OPENSSL_EXTRA) || \
  12247. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12248. && !defined(WOLFCRYPT_ONLY)
  12249. nid = NID_givenName;
  12250. #endif /* OPENSSL_EXTRA */
  12251. }
  12252. else if (id == ASN_DNQUALIFIER) {
  12253. copy = WOLFSSL_DNQUALIFIER;
  12254. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  12255. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12256. if (nameType == SUBJECT) {
  12257. cert->subjectDNQ = (char*)&input[srcIdx];
  12258. cert->subjectDNQLen = strLen;
  12259. cert->subjectDNQEnc = b;
  12260. }
  12261. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12262. #if (defined(OPENSSL_EXTRA) || \
  12263. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12264. && !defined(WOLFCRYPT_ONLY)
  12265. nid = NID_dnQualifier;
  12266. #endif /* OPENSSL_EXTRA */
  12267. }
  12268. #endif /* WOLFSSL_CERT_NAME_ALL */
  12269. else if (id == ASN_SUR_NAME) {
  12270. copy = WOLFSSL_SUR_NAME;
  12271. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  12272. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12273. if (nameType == SUBJECT) {
  12274. cert->subjectSN = (char*)&input[srcIdx];
  12275. cert->subjectSNLen = strLen;
  12276. cert->subjectSNEnc = (char)b;
  12277. }
  12278. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12279. else if (nameType == ISSUER) {
  12280. cert->issuerSN = (char*)&input[srcIdx];
  12281. cert->issuerSNLen = strLen;
  12282. cert->issuerSNEnc = (char)b;
  12283. }
  12284. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12285. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12286. #if (defined(OPENSSL_EXTRA) || \
  12287. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12288. && !defined(WOLFCRYPT_ONLY)
  12289. nid = NID_surname;
  12290. #endif /* OPENSSL_EXTRA */
  12291. }
  12292. else if (id == ASN_COUNTRY_NAME) {
  12293. copy = WOLFSSL_COUNTRY_NAME;
  12294. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  12295. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12296. if (nameType == SUBJECT) {
  12297. cert->subjectC = (char*)&input[srcIdx];
  12298. cert->subjectCLen = strLen;
  12299. cert->subjectCEnc = (char)b;
  12300. }
  12301. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12302. else if (nameType == ISSUER) {
  12303. cert->issuerC = (char*)&input[srcIdx];
  12304. cert->issuerCLen = strLen;
  12305. cert->issuerCEnc = (char)b;
  12306. }
  12307. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12308. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12309. #if (defined(OPENSSL_EXTRA) || \
  12310. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12311. && !defined(WOLFCRYPT_ONLY)
  12312. nid = NID_countryName;
  12313. #endif /* OPENSSL_EXTRA */
  12314. }
  12315. else if (id == ASN_LOCALITY_NAME) {
  12316. copy = WOLFSSL_LOCALITY_NAME;
  12317. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  12318. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12319. if (nameType == SUBJECT) {
  12320. cert->subjectL = (char*)&input[srcIdx];
  12321. cert->subjectLLen = strLen;
  12322. cert->subjectLEnc = (char)b;
  12323. }
  12324. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12325. else if (nameType == ISSUER) {
  12326. cert->issuerL = (char*)&input[srcIdx];
  12327. cert->issuerLLen = strLen;
  12328. cert->issuerLEnc = (char)b;
  12329. }
  12330. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12331. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12332. #if (defined(OPENSSL_EXTRA) || \
  12333. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12334. && !defined(WOLFCRYPT_ONLY)
  12335. nid = NID_localityName;
  12336. #endif /* OPENSSL_EXTRA */
  12337. }
  12338. else if (id == ASN_STATE_NAME) {
  12339. copy = WOLFSSL_STATE_NAME;
  12340. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  12341. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12342. if (nameType == SUBJECT) {
  12343. cert->subjectST = (char*)&input[srcIdx];
  12344. cert->subjectSTLen = strLen;
  12345. cert->subjectSTEnc = (char)b;
  12346. }
  12347. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12348. else if (nameType == ISSUER) {
  12349. cert->issuerST = (char*)&input[srcIdx];
  12350. cert->issuerSTLen = strLen;
  12351. cert->issuerSTEnc = (char)b;
  12352. }
  12353. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12354. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12355. #if (defined(OPENSSL_EXTRA) || \
  12356. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12357. && !defined(WOLFCRYPT_ONLY)
  12358. nid = NID_stateOrProvinceName;
  12359. #endif /* OPENSSL_EXTRA */
  12360. }
  12361. else if (id == ASN_ORG_NAME) {
  12362. copy = WOLFSSL_ORG_NAME;
  12363. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  12364. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12365. if (nameType == SUBJECT) {
  12366. cert->subjectO = (char*)&input[srcIdx];
  12367. cert->subjectOLen = strLen;
  12368. cert->subjectOEnc = (char)b;
  12369. }
  12370. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12371. else if (nameType == ISSUER) {
  12372. cert->issuerO = (char*)&input[srcIdx];
  12373. cert->issuerOLen = strLen;
  12374. cert->issuerOEnc = (char)b;
  12375. }
  12376. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12377. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12378. #if (defined(OPENSSL_EXTRA) || \
  12379. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12380. && !defined(WOLFCRYPT_ONLY)
  12381. nid = NID_organizationName;
  12382. #endif /* OPENSSL_EXTRA */
  12383. }
  12384. else if (id == ASN_ORGUNIT_NAME) {
  12385. copy = WOLFSSL_ORGUNIT_NAME;
  12386. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  12387. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12388. if (nameType == SUBJECT) {
  12389. cert->subjectOU = (char*)&input[srcIdx];
  12390. cert->subjectOULen = strLen;
  12391. cert->subjectOUEnc = (char)b;
  12392. }
  12393. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12394. else if (nameType == ISSUER) {
  12395. cert->issuerOU = (char*)&input[srcIdx];
  12396. cert->issuerOULen = strLen;
  12397. cert->issuerOUEnc = (char)b;
  12398. }
  12399. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12400. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12401. #if (defined(OPENSSL_EXTRA) || \
  12402. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12403. && !defined(WOLFCRYPT_ONLY)
  12404. nid = NID_organizationalUnitName;
  12405. #endif /* OPENSSL_EXTRA */
  12406. }
  12407. else if (id == ASN_SERIAL_NUMBER) {
  12408. copy = WOLFSSL_SERIAL_NUMBER;
  12409. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  12410. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12411. if (nameType == SUBJECT) {
  12412. cert->subjectSND = (char*)&input[srcIdx];
  12413. cert->subjectSNDLen = strLen;
  12414. cert->subjectSNDEnc = (char)b;
  12415. }
  12416. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12417. else if (nameType == ISSUER) {
  12418. cert->issuerSND = (char*)&input[srcIdx];
  12419. cert->issuerSNDLen = strLen;
  12420. cert->issuerSNDEnc = (char)b;
  12421. }
  12422. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12423. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12424. #if (defined(OPENSSL_EXTRA) || \
  12425. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12426. && !defined(WOLFCRYPT_ONLY)
  12427. nid = NID_serialNumber;
  12428. #endif /* OPENSSL_EXTRA */
  12429. }
  12430. else if (id == ASN_USER_ID) {
  12431. copy = WOLFSSL_USER_ID;
  12432. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12433. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12434. if (nameType == SUBJECT) {
  12435. cert->subjectUID = (char*)&input[srcIdx];
  12436. cert->subjectUIDLen = strLen;
  12437. cert->subjectUIDEnc = (char)b;
  12438. }
  12439. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12440. #if (defined(OPENSSL_EXTRA) || \
  12441. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12442. && !defined(WOLFCRYPT_ONLY)
  12443. nid = NID_userId;
  12444. #endif /* OPENSSL_EXTRA */
  12445. }
  12446. #ifdef WOLFSSL_CERT_EXT
  12447. else if (id == ASN_STREET_ADDR) {
  12448. copy = WOLFSSL_STREET_ADDR_NAME;
  12449. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  12450. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12451. if (nameType == SUBJECT) {
  12452. cert->subjectStreet = (char*)&input[srcIdx];
  12453. cert->subjectStreetLen = strLen;
  12454. cert->subjectStreetEnc = (char)b;
  12455. }
  12456. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12457. #if (defined(OPENSSL_EXTRA) || \
  12458. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12459. && !defined(WOLFCRYPT_ONLY)
  12460. nid = NID_streetAddress;
  12461. #endif /* OPENSSL_EXTRA */
  12462. }
  12463. else if (id == ASN_BUS_CAT) {
  12464. copy = WOLFSSL_BUS_CAT;
  12465. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  12466. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12467. if (nameType == SUBJECT) {
  12468. cert->subjectBC = (char*)&input[srcIdx];
  12469. cert->subjectBCLen = strLen;
  12470. cert->subjectBCEnc = (char)b;
  12471. }
  12472. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12473. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12474. && !defined(WOLFCRYPT_ONLY)
  12475. nid = NID_businessCategory;
  12476. #endif /* OPENSSL_EXTRA */
  12477. }
  12478. else if (id == ASN_POSTAL_CODE) {
  12479. copy = WOLFSSL_POSTAL_NAME;
  12480. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  12481. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12482. if (nameType == SUBJECT) {
  12483. cert->subjectPC = (char*)&input[srcIdx];
  12484. cert->subjectPCLen = strLen;
  12485. cert->subjectPCEnc = (char)b;
  12486. }
  12487. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12488. #if (defined(OPENSSL_EXTRA) || \
  12489. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12490. && !defined(WOLFCRYPT_ONLY)
  12491. nid = NID_postalCode;
  12492. #endif /* OPENSSL_EXTRA */
  12493. }
  12494. #endif /* WOLFSSL_CERT_EXT */
  12495. }
  12496. #ifdef WOLFSSL_CERT_EXT
  12497. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  12498. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  12499. ASN_JOI_PREFIX_SZ)) &&
  12500. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  12501. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  12502. {
  12503. srcIdx += ASN_JOI_PREFIX_SZ;
  12504. id = input[srcIdx++];
  12505. b = input[srcIdx++]; /* encoding */
  12506. if (GetLength(input, &srcIdx, &strLen,
  12507. maxIdx) < 0) {
  12508. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12509. !defined(WOLFCRYPT_ONLY)
  12510. wolfSSL_X509_NAME_free(dName);
  12511. #endif /* OPENSSL_EXTRA */
  12512. return ASN_PARSE_E;
  12513. }
  12514. /* Check for jurisdiction of incorporation country name */
  12515. if (id == ASN_JOI_C) {
  12516. copy = WOLFSSL_JOI_C;
  12517. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  12518. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12519. if (nameType == SUBJECT) {
  12520. cert->subjectJC = (char*)&input[srcIdx];
  12521. cert->subjectJCLen = strLen;
  12522. cert->subjectJCEnc = (char)b;
  12523. }
  12524. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12525. #if (defined(OPENSSL_EXTRA) || \
  12526. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12527. && !defined(WOLFCRYPT_ONLY)
  12528. nid = NID_jurisdictionCountryName;
  12529. #endif /* OPENSSL_EXTRA */
  12530. }
  12531. /* Check for jurisdiction of incorporation state name */
  12532. else if (id == ASN_JOI_ST) {
  12533. copy = WOLFSSL_JOI_ST;
  12534. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12535. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12536. if (nameType == SUBJECT) {
  12537. cert->subjectJS = (char*)&input[srcIdx];
  12538. cert->subjectJSLen = strLen;
  12539. cert->subjectJSEnc = (char)b;
  12540. }
  12541. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12542. #if (defined(OPENSSL_EXTRA) || \
  12543. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12544. && !defined(WOLFCRYPT_ONLY)
  12545. nid = NID_jurisdictionStateOrProvinceName;
  12546. #endif /* OPENSSL_EXTRA */
  12547. }
  12548. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12549. WOLFSSL_MSG("ASN Name too big, skipping");
  12550. tooBig = TRUE;
  12551. }
  12552. }
  12553. #endif /* WOLFSSL_CERT_EXT */
  12554. else {
  12555. /* skip */
  12556. byte email = FALSE;
  12557. byte pilot = FALSE;
  12558. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  12559. id = ASN_EMAIL_NAME;
  12560. email = TRUE;
  12561. }
  12562. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  12563. /* last value of OID is the type of pilot attribute */
  12564. id = input[srcIdx + (word32)oidSz - 1];
  12565. if (id == 0x01)
  12566. id = ASN_USER_ID;
  12567. pilot = TRUE;
  12568. }
  12569. srcIdx += (word32)oidSz + 1;
  12570. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  12571. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12572. !defined(WOLFCRYPT_ONLY)
  12573. wolfSSL_X509_NAME_free(dName);
  12574. #endif /* OPENSSL_EXTRA */
  12575. return ASN_PARSE_E;
  12576. }
  12577. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12578. WOLFSSL_MSG("ASN name too big, skipping");
  12579. tooBig = TRUE;
  12580. }
  12581. if (email) {
  12582. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12583. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12584. WOLFSSL_MSG("ASN name too big, skipping");
  12585. tooBig = TRUE;
  12586. }
  12587. else {
  12588. copy = WOLFSSL_EMAIL_ADDR;
  12589. }
  12590. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12591. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12592. if (nameType == SUBJECT) {
  12593. cert->subjectEmail = (char*)&input[srcIdx];
  12594. cert->subjectEmailLen = strLen;
  12595. }
  12596. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12597. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12598. else if (nameType == ISSUER) {
  12599. cert->issuerEmail = (char*)&input[srcIdx];
  12600. cert->issuerEmailLen = strLen;
  12601. }
  12602. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12603. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12604. #if (defined(OPENSSL_EXTRA) || \
  12605. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12606. && !defined(WOLFCRYPT_ONLY)
  12607. nid = NID_emailAddress;
  12608. #endif /* OPENSSL_EXTRA */
  12609. }
  12610. if (pilot) {
  12611. switch (id) {
  12612. case ASN_USER_ID:
  12613. copy = WOLFSSL_USER_ID;
  12614. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12615. #if (defined(OPENSSL_EXTRA) || \
  12616. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12617. && !defined(WOLFCRYPT_ONLY)
  12618. nid = NID_userId;
  12619. #endif /* OPENSSL_EXTRA */
  12620. break;
  12621. case ASN_DOMAIN_COMPONENT:
  12622. copy = WOLFSSL_DOMAIN_COMPONENT;
  12623. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12624. #if (defined(OPENSSL_EXTRA) || \
  12625. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12626. && !defined(WOLFCRYPT_ONLY)
  12627. nid = NID_domainComponent;
  12628. #endif /* OPENSSL_EXTRA */
  12629. break;
  12630. case ASN_FAVOURITE_DRINK:
  12631. copy = WOLFSSL_FAVOURITE_DRINK;
  12632. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12633. #if (defined(OPENSSL_EXTRA) || \
  12634. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12635. && !defined(WOLFCRYPT_ONLY)
  12636. nid = NID_favouriteDrink;
  12637. #endif /* OPENSSL_EXTRA */
  12638. break;
  12639. default:
  12640. WOLFSSL_MSG("Unknown pilot attribute type");
  12641. #if (defined(OPENSSL_EXTRA) || \
  12642. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12643. !defined(WOLFCRYPT_ONLY)
  12644. wolfSSL_X509_NAME_free(dName);
  12645. #endif /* OPENSSL_EXTRA */
  12646. return ASN_PARSE_E;
  12647. }
  12648. }
  12649. }
  12650. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12651. {
  12652. WOLFSSL_MSG("ASN Name too big, skipping");
  12653. tooBig = TRUE;
  12654. }
  12655. if ((copy != NULL) && !tooBig) {
  12656. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  12657. idx += (word32)copyLen;
  12658. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  12659. idx += (word32)strLen;
  12660. }
  12661. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12662. !defined(WOLFCRYPT_ONLY)
  12663. switch (b) {
  12664. case CTC_UTF8:
  12665. enc = MBSTRING_UTF8;
  12666. break;
  12667. case CTC_PRINTABLE:
  12668. enc = V_ASN1_PRINTABLESTRING;
  12669. break;
  12670. default:
  12671. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12672. enc = MBSTRING_UTF8;
  12673. }
  12674. if (nid != NID_undef) {
  12675. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12676. &input[srcIdx], strLen, -1, -1) !=
  12677. WOLFSSL_SUCCESS) {
  12678. wolfSSL_X509_NAME_free(dName);
  12679. return ASN_PARSE_E;
  12680. }
  12681. }
  12682. #endif /* OPENSSL_EXTRA */
  12683. srcIdx += (word32)strLen;
  12684. }
  12685. full[idx++] = 0;
  12686. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12687. !defined(WOLFCRYPT_ONLY)
  12688. if (nameType == ISSUER) {
  12689. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12690. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12691. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12692. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12693. #endif
  12694. cert->issuerName = dName;
  12695. }
  12696. else {
  12697. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12698. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12699. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12700. #endif
  12701. cert->subjectName = dName;
  12702. }
  12703. #endif
  12704. *inOutIdx = srcIdx;
  12705. return 0;
  12706. #else
  12707. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12708. int ret = 0;
  12709. word32 idx = 0;
  12710. int len;
  12711. word32 srcIdx = *inOutIdx;
  12712. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12713. WOLFSSL_X509_NAME* dName = NULL;
  12714. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12715. WOLFSSL_MSG("Getting Cert Name");
  12716. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12717. * calculated over the entire DER encoding of the Name field, including
  12718. * the tag and length. */
  12719. if (CalcHashId_ex(input + srcIdx, maxIdx - srcIdx, hash,
  12720. HashIdAlg(cert->signatureOID)) != 0) {
  12721. ret = ASN_PARSE_E;
  12722. }
  12723. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12724. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12725. if (ret == 0) {
  12726. /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
  12727. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12728. if (dName == NULL) {
  12729. ret = MEMORY_E;
  12730. }
  12731. }
  12732. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12733. if (ret == 0) {
  12734. /* Expecting a SEQUENCE using up all data. */
  12735. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12736. }
  12737. if (ret == 0) {
  12738. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12739. /* Store pointer and length to raw issuer. */
  12740. if (nameType == ISSUER) {
  12741. cert->issuerRaw = &input[srcIdx];
  12742. cert->issuerRawLen = len;
  12743. }
  12744. #endif
  12745. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12746. /* Store pointer and length to raw subject. */
  12747. if (nameType == SUBJECT) {
  12748. cert->subjectRaw = &input[srcIdx];
  12749. cert->subjectRawLen = len;
  12750. }
  12751. #endif
  12752. /* Process all RDNs in name. */
  12753. while ((ret == 0) && (srcIdx < maxIdx)) {
  12754. int nid = 0;
  12755. /* Initialize for data and setup RDN choice. */
  12756. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12757. /* Ignore type OID as too many to store in table. */
  12758. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12759. /* Parse RDN. */
  12760. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12761. &srcIdx, maxIdx);
  12762. if (ret == 0) {
  12763. /* Put RDN data into certificate. */
  12764. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12765. dataASN);
  12766. }
  12767. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12768. /* TODO: push this back up to ssl.c
  12769. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12770. if (ret == 0) {
  12771. int enc;
  12772. byte* str;
  12773. word32 strLen;
  12774. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12775. /* Get string reference. */
  12776. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12777. /* Convert BER tag to a OpenSSL type. */
  12778. switch (tag) {
  12779. case CTC_UTF8:
  12780. enc = MBSTRING_UTF8;
  12781. break;
  12782. case CTC_PRINTABLE:
  12783. enc = V_ASN1_PRINTABLESTRING;
  12784. break;
  12785. default:
  12786. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12787. enc = MBSTRING_UTF8;
  12788. }
  12789. if (nid != 0) {
  12790. /* Add an entry to the X509_NAME. */
  12791. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12792. (int)strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12793. ret = ASN_PARSE_E;
  12794. }
  12795. }
  12796. }
  12797. #endif
  12798. }
  12799. }
  12800. if (ret == 0) {
  12801. /* Terminate string. */
  12802. full[idx] = 0;
  12803. /* Return index into encoding after name. */
  12804. *inOutIdx = srcIdx;
  12805. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12806. /* Store X509_NAME in certificate. */
  12807. if (nameType == ISSUER) {
  12808. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12809. defined(HAVE_LIGHTY)) && \
  12810. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12811. dName->rawLen = (int)min((word32)cert->issuerRawLen,
  12812. WC_ASN_NAME_MAX);
  12813. XMEMCPY(dName->raw, cert->issuerRaw, (size_t)dName->rawLen);
  12814. #endif
  12815. cert->issuerName = dName;
  12816. }
  12817. else {
  12818. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12819. dName->rawLen = (int)min((word32)cert->subjectRawLen,
  12820. WC_ASN_NAME_MAX);
  12821. XMEMCPY(dName->raw, cert->subjectRaw, (size_t)dName->rawLen);
  12822. #endif
  12823. cert->subjectName = dName;
  12824. }
  12825. }
  12826. else {
  12827. /* Dispose of unused X509_NAME. */
  12828. wolfSSL_X509_NAME_free(dName);
  12829. #endif
  12830. }
  12831. FREE_ASNGETDATA(dataASN, cert->heap);
  12832. return ret;
  12833. #endif /* WOLFSSL_ASN_TEMPLATE */
  12834. }
  12835. #ifdef WOLFSSL_ASN_TEMPLATE
  12836. /* ASN.1 template for certificate name. */
  12837. static const ASNItem certNameASN[] = {
  12838. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12839. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12840. };
  12841. enum {
  12842. CERTNAMEASN_IDX_OID = 0,
  12843. CERTNAMEASN_IDX_NAME
  12844. };
  12845. /* Number of items in ASN.1 template for certificate name. */
  12846. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12847. #endif
  12848. /* Get a certificate name into the certificate object.
  12849. *
  12850. * Either the issuer or subject name.
  12851. *
  12852. * @param [in, out] cert Decoded certificate object.
  12853. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12854. * @param [in] maxIdx Index of next item after certificate name.
  12855. * @return 0 on success.
  12856. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12857. * is invalid.
  12858. * @return BUFFER_E when data in buffer is too small.
  12859. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12860. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12861. * @return MEMORY_E when dynamic memory allocation fails.
  12862. */
  12863. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12864. {
  12865. #ifndef WOLFSSL_ASN_TEMPLATE
  12866. char* full;
  12867. byte* hash;
  12868. int length;
  12869. word32 localIdx;
  12870. byte tag;
  12871. WOLFSSL_MSG("Getting Name");
  12872. if (nameType == ISSUER) {
  12873. full = cert->issuer;
  12874. hash = cert->issuerHash;
  12875. }
  12876. else {
  12877. full = cert->subject;
  12878. hash = cert->subjectHash;
  12879. }
  12880. if (cert->srcIdx >= (word32)maxIdx) {
  12881. return BUFFER_E;
  12882. }
  12883. localIdx = cert->srcIdx;
  12884. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12885. return ASN_PARSE_E;
  12886. }
  12887. if (tag == ASN_OBJECT_ID) {
  12888. WOLFSSL_MSG("Trying optional prefix...");
  12889. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  12890. return ASN_PARSE_E;
  12891. WOLFSSL_MSG("Got optional prefix");
  12892. }
  12893. localIdx = cert->srcIdx;
  12894. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12895. return ASN_PARSE_E;
  12896. }
  12897. localIdx = cert->srcIdx + 1;
  12898. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  12899. return ASN_PARSE_E;
  12900. }
  12901. length += (int)(localIdx - cert->srcIdx);
  12902. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  12903. cert->srcIdx + (word32)length);
  12904. #else
  12905. ASNGetData dataASN[certNameASN_Length];
  12906. word32 idx = cert->srcIdx;
  12907. int ret = 0;
  12908. WOLFSSL_MSG("Getting Name");
  12909. XMEMSET(dataASN, 0, sizeof(dataASN));
  12910. /* Initialize for data and don't check optional prefix OID. */
  12911. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  12912. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  12913. cert->source, &idx, (word32)maxIdx);
  12914. if (ret == 0) {
  12915. char* full;
  12916. byte* hash;
  12917. /* Store offset of SEQUENCE that is start of name. */
  12918. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  12919. /* Get fields to fill in based on name type. */
  12920. if (nameType == ISSUER) {
  12921. full = cert->issuer;
  12922. hash = cert->issuerHash;
  12923. }
  12924. else {
  12925. full = cert->subject;
  12926. hash = cert->subjectHash;
  12927. }
  12928. /* Parse certificate name. */
  12929. ret = GetCertName(cert, full, hash, nameType, cert->source,
  12930. &cert->srcIdx, idx);
  12931. }
  12932. return ret;
  12933. #endif
  12934. }
  12935. #ifndef NO_ASN_TIME
  12936. /* two byte date/time, add to value */
  12937. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  12938. {
  12939. int i = *idx;
  12940. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12941. date[i+1] > 0x39) {
  12942. return ASN_PARSE_E;
  12943. }
  12944. *value += (int)btoi(date[i++]) * 10;
  12945. *value += (int)btoi(date[i++]);
  12946. *idx = i;
  12947. return 0;
  12948. }
  12949. #ifdef WOLFSSL_LINUXKM
  12950. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  12951. {
  12952. int i = *idx;
  12953. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12954. date[i+1] > 0x39) {
  12955. return ASN_PARSE_E;
  12956. }
  12957. *value += (long)btoi(date[i++]) * 10;
  12958. *value += (long)btoi(date[i++]);
  12959. *idx = i;
  12960. return 0;
  12961. }
  12962. #endif
  12963. int ExtractDate(const unsigned char* date, unsigned char format,
  12964. struct tm* certTime, int* idx)
  12965. {
  12966. XMEMSET(certTime, 0, sizeof(struct tm));
  12967. if (format == ASN_UTC_TIME) {
  12968. if (btoi(date[*idx]) >= 5)
  12969. certTime->tm_year = 1900;
  12970. else
  12971. certTime->tm_year = 2000;
  12972. }
  12973. else { /* format == GENERALIZED_TIME */
  12974. #ifdef WOLFSSL_LINUXKM
  12975. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12976. #else
  12977. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12978. #endif
  12979. certTime->tm_year *= 100;
  12980. }
  12981. #ifdef AVR
  12982. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  12983. /* AVR libc stores these as uint8_t instead of int */
  12984. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  12985. int tm_year = certTime->tm_year - 2000;
  12986. int tm_mon = certTime->tm_mon - 1;
  12987. int tm_mday = certTime->tm_mday;
  12988. int tm_hour = certTime->tm_hour;
  12989. int tm_min = certTime->tm_min;
  12990. int tm_sec = certTime->tm_sec;
  12991. #ifdef WOLFSSL_LINUXKM
  12992. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  12993. #else
  12994. if (GetTime(&tm_year, date, idx) != 0) return 0;
  12995. #endif
  12996. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  12997. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  12998. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  12999. if (GetTime(&tm_min , date, idx) != 0) return 0;
  13000. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  13001. /* Re-populate certTime with computed values */
  13002. certTime->tm_year = tm_year;
  13003. certTime->tm_mon = tm_mon;
  13004. certTime->tm_mday = tm_mday;
  13005. certTime->tm_hour = tm_hour;
  13006. certTime->tm_min = tm_min;
  13007. certTime->tm_sec = tm_sec;
  13008. #else
  13009. /* adjust tm_year, tm_mon */
  13010. #ifdef WOLFSSL_LINUXKM
  13011. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  13012. #else
  13013. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  13014. #endif
  13015. certTime->tm_year -= 1900;
  13016. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  13017. certTime->tm_mon -= 1;
  13018. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  13019. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  13020. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  13021. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  13022. #endif
  13023. return 1;
  13024. }
  13025. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  13026. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  13027. int GetTimeString(byte* date, int format, char* buf, int len)
  13028. {
  13029. struct tm t;
  13030. int idx = 0;
  13031. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  13032. return 0;
  13033. }
  13034. if (date[idx] != 'Z') {
  13035. WOLFSSL_MSG("UTCtime, not Zulu") ;
  13036. return 0;
  13037. }
  13038. /* place month in buffer */
  13039. buf[0] = '\0';
  13040. switch(t.tm_mon) {
  13041. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  13042. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  13043. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  13044. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  13045. case 4: XSTRNCAT(buf, "May ", 5); break;
  13046. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  13047. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  13048. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  13049. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  13050. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  13051. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  13052. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  13053. default:
  13054. return 0;
  13055. }
  13056. idx = 4; /* use idx now for char buffer */
  13057. if (XSNPRINTF(buf + idx, (size_t)(len - idx), "%2d %02d:%02d:%02d %d GMT",
  13058. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  13059. >= len - idx)
  13060. {
  13061. WOLFSSL_MSG("buffer overrun in GetTimeString");
  13062. return 0;
  13063. }
  13064. return 1;
  13065. }
  13066. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  13067. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  13068. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  13069. /* Set current time string, either UTC or GeneralizedTime.
  13070. * (void*) tm should be a pointer to time_t, output is placed in buf.
  13071. *
  13072. * Return time string length placed in buf on success, negative on error */
  13073. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  13074. {
  13075. byte* data_ptr = buf;
  13076. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  13077. int data_len = 0;
  13078. WOLFSSL_ENTER("GetAsnTimeString");
  13079. if (buf == NULL || len == 0)
  13080. return BAD_FUNC_ARG;
  13081. XMEMSET(uf_time, 0, sizeof(uf_time));
  13082. /* GetFormattedTime returns length with null terminator */
  13083. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  13084. if (data_len <= 0) {
  13085. return ASN_TIME_E;
  13086. }
  13087. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  13088. else if (len < (word32)data_len + 2) {
  13089. return BUFFER_E;
  13090. }
  13091. if (data_len == ASN_UTC_TIME_SIZE-1) {
  13092. /* increment data_len for ASN length byte after adding the data_ptr */
  13093. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  13094. /* -1 below excludes null terminator */
  13095. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  13096. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  13097. data_ptr += ASN_UTC_TIME_SIZE - 1;
  13098. }
  13099. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  13100. /* increment data_len for ASN length byte after adding the data_ptr */
  13101. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  13102. /* -1 below excludes null terminator */
  13103. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  13104. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  13105. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  13106. }
  13107. else {
  13108. WOLFSSL_MSG("Invalid time size returned");
  13109. return ASN_TIME_E;
  13110. }
  13111. /* append null terminator */
  13112. *data_ptr = 0;
  13113. /* return length without null terminator */
  13114. return data_len;
  13115. }
  13116. /* return just the time string as either UTC or Generalized Time*/
  13117. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  13118. {
  13119. struct tm* ts = NULL;
  13120. struct tm* tmpTime = NULL;
  13121. int year, mon, day, hour, mini, sec;
  13122. int ret;
  13123. #if defined(NEED_TMP_TIME)
  13124. struct tm tmpTimeStorage;
  13125. tmpTime = &tmpTimeStorage;
  13126. #endif
  13127. /* Needed in case XGMTIME does not use the tmpTime argument. */
  13128. (void)tmpTime;
  13129. WOLFSSL_ENTER("GetFormattedTime");
  13130. if (buf == NULL || len == 0)
  13131. return BAD_FUNC_ARG;
  13132. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  13133. if (ts == NULL) {
  13134. WOLFSSL_MSG("failed to get time data.");
  13135. return ASN_TIME_E;
  13136. }
  13137. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  13138. * the null terminator. ASN encoded values leave off the terminator. */
  13139. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  13140. /* UTC Time */
  13141. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  13142. year = ts->tm_year;
  13143. }
  13144. else {
  13145. year = ts->tm_year - 100;
  13146. }
  13147. mon = ts->tm_mon + 1;
  13148. day = ts->tm_mday;
  13149. hour = ts->tm_hour;
  13150. mini = ts->tm_min;
  13151. sec = ts->tm_sec;
  13152. #if defined(WOLF_C89)
  13153. if (len < ASN_UTC_TIME_SIZE) {
  13154. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13155. return BUFFER_E;
  13156. }
  13157. ret = XSPRINTF((char*)buf,
  13158. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13159. hour, mini, sec);
  13160. #else
  13161. ret = XSNPRINTF((char*)buf, len,
  13162. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13163. hour, mini, sec);
  13164. #endif
  13165. }
  13166. else {
  13167. /* GeneralizedTime */
  13168. year = ts->tm_year + 1900;
  13169. mon = ts->tm_mon + 1;
  13170. day = ts->tm_mday;
  13171. hour = ts->tm_hour;
  13172. mini = ts->tm_min;
  13173. sec = ts->tm_sec;
  13174. #if defined(WOLF_C89)
  13175. if (len < ASN_GENERALIZED_TIME_SIZE) {
  13176. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13177. return BUFFER_E;
  13178. }
  13179. ret = XSPRINTF((char*)buf,
  13180. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13181. hour, mini, sec);
  13182. #else
  13183. ret = XSNPRINTF((char*)buf, len,
  13184. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13185. hour, mini, sec);
  13186. #endif
  13187. }
  13188. return ret;
  13189. }
  13190. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  13191. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  13192. #if defined(USE_WOLF_VALIDDATE)
  13193. /* to the second */
  13194. int DateGreaterThan(const struct tm* a, const struct tm* b)
  13195. {
  13196. if (a->tm_year > b->tm_year)
  13197. return 1;
  13198. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  13199. return 1;
  13200. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13201. a->tm_mday > b->tm_mday)
  13202. return 1;
  13203. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13204. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  13205. return 1;
  13206. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13207. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13208. a->tm_min > b->tm_min)
  13209. return 1;
  13210. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13211. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13212. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  13213. return 1;
  13214. return 0; /* false */
  13215. }
  13216. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  13217. {
  13218. return DateGreaterThan(b,a);
  13219. }
  13220. /* like atoi but only use first byte */
  13221. /* Make sure before and after dates are valid */
  13222. int wc_ValidateDate(const byte* date, byte format, int dateType)
  13223. {
  13224. time_t ltime;
  13225. struct tm certTime;
  13226. struct tm* localTime;
  13227. struct tm* tmpTime;
  13228. int i = 0;
  13229. int timeDiff = 0;
  13230. int diffHH = 0, diffMM = 0;
  13231. #if defined(NEED_TMP_TIME)
  13232. struct tm tmpTimeStorage;
  13233. tmpTime = &tmpTimeStorage;
  13234. #else
  13235. tmpTime = NULL;
  13236. #endif
  13237. (void)tmpTime;
  13238. ltime = wc_Time(0);
  13239. if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
  13240. /* A negative response here could be due to a 32-bit time_t
  13241. * where the year is 2038 or later. */
  13242. WOLFSSL_MSG("wc_Time failed to return a valid value");
  13243. return 0;
  13244. }
  13245. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  13246. if (dateType == BEFORE) {
  13247. WOLFSSL_MSG("Skewing local time for before date check");
  13248. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  13249. }
  13250. #endif
  13251. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  13252. if (dateType == AFTER) {
  13253. WOLFSSL_MSG("Skewing local time for after date check");
  13254. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  13255. }
  13256. #endif
  13257. if (!ExtractDate(date, format, &certTime, &i)) {
  13258. WOLFSSL_MSG("Error extracting the date");
  13259. return 0;
  13260. }
  13261. if ((date[i] == '+') || (date[i] == '-')) {
  13262. int diffSign;
  13263. WOLFSSL_MSG("Using time differential, not Zulu") ;
  13264. diffSign = date[i++] == '+' ? 1 : -1 ;
  13265. if (GetTime(&diffHH, date, &i) != 0)
  13266. return 0;
  13267. if (GetTime(&diffMM, date, &i) != 0)
  13268. return 0;
  13269. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  13270. } else if (date[i] != 'Z') {
  13271. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  13272. return 0;
  13273. }
  13274. ltime -= (time_t)timeDiff;
  13275. localTime = XGMTIME(&ltime, tmpTime);
  13276. if (localTime == NULL) {
  13277. WOLFSSL_MSG("XGMTIME failed");
  13278. return 0;
  13279. }
  13280. if (dateType == BEFORE) {
  13281. if (DateLessThan(localTime, &certTime)) {
  13282. WOLFSSL_MSG("Date BEFORE check failed");
  13283. return 0;
  13284. }
  13285. }
  13286. else { /* dateType == AFTER */
  13287. if (DateGreaterThan(localTime, &certTime)) {
  13288. WOLFSSL_MSG("Date AFTER check failed");
  13289. return 0;
  13290. }
  13291. }
  13292. return 1;
  13293. }
  13294. #endif /* USE_WOLF_VALIDDATE */
  13295. int wc_GetTime(void* timePtr, word32 timeSize)
  13296. {
  13297. time_t* ltime = (time_t*)timePtr;
  13298. if (timePtr == NULL) {
  13299. return BAD_FUNC_ARG;
  13300. }
  13301. if ((word32)sizeof(time_t) > timeSize) {
  13302. return BUFFER_E;
  13303. }
  13304. *ltime = wc_Time(0);
  13305. return 0;
  13306. }
  13307. #ifdef TIME_OVERRIDES
  13308. #ifndef HAVE_TIME_T_TYPE
  13309. typedef long time_t;
  13310. #endif
  13311. extern time_t XTIME(time_t* t);
  13312. #endif
  13313. static wc_time_cb timeFunc = NULL;
  13314. int wc_SetTimeCb(wc_time_cb f)
  13315. {
  13316. timeFunc = f;
  13317. return 0;
  13318. }
  13319. time_t wc_Time(time_t* t)
  13320. {
  13321. if (timeFunc != NULL) {
  13322. return timeFunc(t);
  13323. }
  13324. return XTIME(t);
  13325. }
  13326. #endif /* !NO_ASN_TIME */
  13327. #ifdef WOLFSSL_ASN_TEMPLATE
  13328. /* TODO: use a CHOICE instead of two items? */
  13329. /* ASN.1 template for a date - either UTC or Generalized Time. */
  13330. static const ASNItem dateASN[] = {
  13331. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  13332. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  13333. };
  13334. enum {
  13335. DATEASN_IDX_UTC = 0,
  13336. DATEASN_IDX_GT
  13337. };
  13338. /* Number of items in ASN.1 template for a date. */
  13339. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  13340. #endif /* WOLFSSL_ASN_TEMPLATE */
  13341. /* Get date buffer, format and length. Returns 0=success or error */
  13342. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  13343. *
  13344. * @param [in] source Buffer containing encoded date.
  13345. * @param [in, out] idx On in, the index of the date.
  13346. * On out, index after date.
  13347. * @param [out] pDate Pointer into buffer of data bytes.
  13348. * @param [out] pFormat Format of date - BER/DER tag.
  13349. * @param [out] pLength Length of date bytes.
  13350. * @param [in] maxIdx Index of next item after date.
  13351. * @return 0 on success.
  13352. * @return BAD_FUNC_ARG when source or idx is NULL.
  13353. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13354. * is invalid.
  13355. * @return BUFFER_E when data in buffer is too small.
  13356. */
  13357. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  13358. byte* pFormat, int* pLength, word32 maxIdx)
  13359. {
  13360. #ifndef WOLFSSL_ASN_TEMPLATE
  13361. int length;
  13362. byte format;
  13363. if (source == NULL || idx == NULL)
  13364. return BAD_FUNC_ARG;
  13365. /* get ASN format header */
  13366. if (*idx+1 > maxIdx)
  13367. return BUFFER_E;
  13368. format = source[*idx];
  13369. *idx += 1;
  13370. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  13371. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  13372. return ASN_TIME_E;
  13373. }
  13374. /* get length */
  13375. if (GetLength(source, idx, &length, maxIdx) < 0)
  13376. return ASN_PARSE_E;
  13377. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  13378. return ASN_DATE_SZ_E;
  13379. /* return format, date and length */
  13380. if (pFormat)
  13381. *pFormat = format;
  13382. if (pDate)
  13383. *pDate = &source[*idx];
  13384. if (pLength)
  13385. *pLength = length;
  13386. *idx += (word32)length;
  13387. return 0;
  13388. #else
  13389. ASNGetData dataASN[dateASN_Length];
  13390. int ret = 0;
  13391. if ((source == NULL) || (idx == NULL)) {
  13392. ret = BAD_FUNC_ARG;
  13393. }
  13394. if (ret == 0) {
  13395. /* Initialize data. */
  13396. XMEMSET(dataASN, 0, sizeof(dataASN));
  13397. /* Parse date. */
  13398. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  13399. maxIdx);
  13400. }
  13401. if (ret == 0) {
  13402. /* Determine which tag was seen. */
  13403. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  13404. : DATEASN_IDX_GT;
  13405. /* Return data from seen item. */
  13406. if (pFormat != NULL) {
  13407. *pFormat = dataASN[i].tag;
  13408. }
  13409. if (pDate != NULL) {
  13410. *pDate = dataASN[i].data.ref.data;
  13411. }
  13412. if (pLength != NULL) {
  13413. *pLength = (int)dataASN[i].data.ref.length;
  13414. }
  13415. }
  13416. return ret;
  13417. #endif
  13418. }
  13419. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13420. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  13421. {
  13422. int ret, length;
  13423. const byte *datePtr = NULL;
  13424. byte date[MAX_DATE_SIZE];
  13425. byte format;
  13426. word32 startIdx = 0;
  13427. if (dateType == BEFORE)
  13428. cert->beforeDate = &cert->source[cert->srcIdx];
  13429. else
  13430. cert->afterDate = &cert->source[cert->srcIdx];
  13431. startIdx = cert->srcIdx;
  13432. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  13433. &length, (word32)maxIdx);
  13434. if (ret < 0)
  13435. return ret;
  13436. XMEMSET(date, 0, MAX_DATE_SIZE);
  13437. XMEMCPY(date, datePtr, (size_t)length);
  13438. if (dateType == BEFORE)
  13439. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  13440. else
  13441. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  13442. #ifndef NO_ASN_TIME_CHECK
  13443. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  13444. !XVALIDATE_DATE(date, format, dateType)) {
  13445. if (dateType == BEFORE) {
  13446. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  13447. return ASN_BEFORE_DATE_E;
  13448. }
  13449. else {
  13450. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  13451. return ASN_AFTER_DATE_E;
  13452. }
  13453. }
  13454. #else
  13455. (void)verify;
  13456. #endif
  13457. return 0;
  13458. }
  13459. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  13460. {
  13461. int length;
  13462. int badDate = 0;
  13463. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  13464. return ASN_PARSE_E;
  13465. maxIdx = (int)cert->srcIdx + length;
  13466. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  13467. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  13468. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  13469. return ASN_AFTER_DATE_E;
  13470. if (badDate != 0)
  13471. return badDate;
  13472. return 0;
  13473. }
  13474. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13475. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  13476. byte* format, int* length)
  13477. {
  13478. int ret;
  13479. word32 idx = 0;
  13480. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  13481. return ret;
  13482. }
  13483. #ifndef NO_ASN_TIME
  13484. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  13485. struct tm* timearg)
  13486. {
  13487. int idx = 0;
  13488. (void)length;
  13489. if (!ExtractDate(date, format, timearg, &idx))
  13490. return ASN_TIME_E;
  13491. return 0;
  13492. }
  13493. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  13494. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  13495. {
  13496. int ret = 0;
  13497. const byte* date;
  13498. byte format;
  13499. int length;
  13500. if (cert == NULL)
  13501. return BAD_FUNC_ARG;
  13502. if (before && cert->beforeDateSz > 0) {
  13503. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  13504. &format, &length);
  13505. if (ret == 0)
  13506. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  13507. }
  13508. if (after && cert->afterDateSz > 0) {
  13509. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  13510. &format, &length);
  13511. if (ret == 0)
  13512. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  13513. }
  13514. return ret;
  13515. }
  13516. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  13517. #endif /* !NO_ASN_TIME */
  13518. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  13519. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  13520. {
  13521. int length;
  13522. word32 endSeqIdx;
  13523. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13524. return ASN_PARSE_E;
  13525. endSeqIdx = cert->srcIdx + (word32)length;
  13526. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  13527. maxIdx) < 0) {
  13528. return ASN_OBJECT_ID_E;
  13529. }
  13530. if (cert->srcIdx != endSeqIdx) {
  13531. #ifdef WC_RSA_PSS
  13532. if (*sigOid == CTC_RSASSAPSS) {
  13533. cert->sigParamsIndex = cert->srcIdx;
  13534. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  13535. }
  13536. else
  13537. #endif
  13538. /* Only allowed a ASN NULL header with zero length. */
  13539. if (endSeqIdx - cert->srcIdx != 2)
  13540. return ASN_PARSE_E;
  13541. else {
  13542. byte tag;
  13543. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  13544. return ASN_PARSE_E;
  13545. if (tag != ASN_TAG_NULL)
  13546. return ASN_PARSE_E;
  13547. }
  13548. }
  13549. cert->srcIdx = endSeqIdx;
  13550. return 0;
  13551. }
  13552. #endif
  13553. #ifndef NO_CERTS
  13554. #ifdef WOLFSSL_ASN_TEMPLATE
  13555. /* TODO: move code around to not require this. */
  13556. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  13557. int* badDateRet, int stopAtPubKey,
  13558. int stopAfterPubKey);
  13559. #endif
  13560. /* Parse the certificate up to the X.509 public key.
  13561. *
  13562. * If cert data is invalid then badDate get set to error value.
  13563. *
  13564. * @param [in, out] cert Decoded certificate object.
  13565. * @param [in] verify Whether to verify dates.
  13566. * @param [out] badDate Error code when verify dates.
  13567. * @return 0 on success.
  13568. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  13569. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13570. * @return ASN_DATE_SZ_E when time data is not supported.
  13571. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13572. * is invalid.
  13573. * @return BUFFER_E when data in buffer is too small.
  13574. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13575. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13576. */
  13577. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  13578. {
  13579. #ifndef WOLFSSL_ASN_TEMPLATE
  13580. int ret;
  13581. if (cert == NULL || badDate == NULL)
  13582. return BAD_FUNC_ARG;
  13583. *badDate = 0;
  13584. if ( (ret = GetCertHeader(cert)) < 0)
  13585. return ret;
  13586. WOLFSSL_MSG("Got Cert Header");
  13587. #ifdef WOLFSSL_CERT_REQ
  13588. if (!cert->isCSR) {
  13589. #endif
  13590. /* Using the sigIndex as the upper bound because that's where the
  13591. * actual certificate data ends. */
  13592. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  13593. return ret;
  13594. WOLFSSL_MSG("Got Algo ID");
  13595. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  13596. return ret;
  13597. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  13598. *badDate = ret;
  13599. #ifdef WOLFSSL_CERT_REQ
  13600. }
  13601. #endif
  13602. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  13603. return ret;
  13604. WOLFSSL_MSG("Got Subject Name");
  13605. return ret;
  13606. #else
  13607. /* Use common decode routine and stop at public key. */
  13608. int ret;
  13609. *badDate = 0;
  13610. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13611. if (ret >= 0) {
  13612. /* Store current index: public key. */
  13613. cert->srcIdx = (word32)ret;
  13614. }
  13615. return ret;
  13616. #endif /* WOLFSSL_ASN_TEMPLATE */
  13617. }
  13618. /* Parse the certificate up to and including X.509 public key.
  13619. *
  13620. * @param [in, out] cert Decoded certificate object.
  13621. * @param [in] verify Whether to verify dates.
  13622. * @return 0 on success.
  13623. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13624. * @return ASN_DATE_SZ_E when time data is not supported.
  13625. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13626. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13627. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13628. * is invalid.
  13629. * @return BUFFER_E when data in buffer is too small.
  13630. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13631. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13632. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13633. */
  13634. int DecodeToKey(DecodedCert* cert, int verify)
  13635. {
  13636. #ifndef WOLFSSL_ASN_TEMPLATE
  13637. int badDate = 0;
  13638. int ret;
  13639. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13640. return ret;
  13641. /* Determine if self signed */
  13642. #ifdef WOLFSSL_CERT_REQ
  13643. if (cert->isCSR)
  13644. cert->selfSigned = 1;
  13645. else
  13646. #endif
  13647. {
  13648. cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
  13649. KEYID_SIZE) == 0 ? 1 : 0;
  13650. }
  13651. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13652. if (ret != 0)
  13653. return ret;
  13654. WOLFSSL_MSG("Got Key");
  13655. if (badDate != 0)
  13656. return badDate;
  13657. return ret;
  13658. #else
  13659. int ret;
  13660. int badDate = 0;
  13661. /* Call internal version and stop after public key. */
  13662. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13663. /* Always return date errors. */
  13664. if (ret == 0) {
  13665. ret = badDate;
  13666. }
  13667. return ret;
  13668. #endif /* WOLFSSL_ASN_TEMPLATE */
  13669. }
  13670. #if !defined(WOLFSSL_ASN_TEMPLATE)
  13671. static int GetSignature(DecodedCert* cert)
  13672. {
  13673. int length;
  13674. int ret;
  13675. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13676. NULL);
  13677. if (ret != 0)
  13678. return ret;
  13679. cert->sigLength = (word32)length;
  13680. cert->signature = &cert->source[cert->srcIdx];
  13681. cert->srcIdx += cert->sigLength;
  13682. if (cert->srcIdx != cert->maxIdx)
  13683. return ASN_PARSE_E;
  13684. return 0;
  13685. }
  13686. #endif /* !WOLFSSL_ASN_TEMPLATE */
  13687. #endif /* !NO_CERTS */
  13688. #ifndef WOLFSSL_ASN_TEMPLATE
  13689. static word32 SetOctetString8Bit(word32 len, byte* output)
  13690. {
  13691. output[0] = ASN_OCTET_STRING;
  13692. output[1] = (byte)len;
  13693. return 2;
  13694. }
  13695. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13696. {
  13697. word32 idx = SetOctetString8Bit(digSz, output);
  13698. XMEMCPY(&output[idx], digest, digSz);
  13699. return idx + digSz;
  13700. }
  13701. #endif
  13702. /* Encode a length for DER.
  13703. *
  13704. * @param [in] length Value to encode.
  13705. * @param [out] output Buffer to encode into.
  13706. * @return Number of bytes encoded.
  13707. */
  13708. word32 SetLength(word32 length, byte* output)
  13709. {
  13710. /* Start encoding at start of buffer. */
  13711. word32 i = 0;
  13712. if (length < ASN_LONG_LENGTH) {
  13713. /* Only one byte needed to encode. */
  13714. if (output) {
  13715. /* Write out length value. */
  13716. output[i] = (byte)length;
  13717. }
  13718. /* Skip over length. */
  13719. i++;
  13720. }
  13721. else {
  13722. /* Calculate the number of bytes required to encode value. */
  13723. byte j = (byte)BytePrecision(length);
  13724. if (output) {
  13725. /* Encode count byte. */
  13726. output[i] = (byte)(j | ASN_LONG_LENGTH);
  13727. }
  13728. /* Skip over count byte. */
  13729. i++;
  13730. /* Encode value as a big-endian byte array. */
  13731. for (; j > 0; --j) {
  13732. if (output) {
  13733. /* Encode next most-significant byte. */
  13734. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13735. }
  13736. /* Skip over byte. */
  13737. i++;
  13738. }
  13739. }
  13740. /* Return number of bytes in encoded length. */
  13741. return i;
  13742. }
  13743. /* Encode a DER header - type/tag and length.
  13744. *
  13745. * @param [in] tag DER tag of ASN.1 item.
  13746. * @param [in] len Length of data in ASN.1 item.
  13747. * @param [out] output Buffer to encode into.
  13748. * @return Number of bytes encoded.
  13749. */
  13750. static word32 SetHeader(byte tag, word32 len, byte* output)
  13751. {
  13752. if (output) {
  13753. /* Encode tag first. */
  13754. output[0] = tag;
  13755. }
  13756. /* Encode the length. */
  13757. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13758. }
  13759. /* Encode a SEQUENCE header in DER.
  13760. *
  13761. * @param [in] len Length of data in SEQUENCE.
  13762. * @param [out] output Buffer to encode into.
  13763. * @return Number of bytes encoded.
  13764. */
  13765. word32 SetSequence(word32 len, byte* output)
  13766. {
  13767. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13768. }
  13769. /* Encode an OCTET STRING header in DER.
  13770. *
  13771. * @param [in] len Length of data in OCTET STRING.
  13772. * @param [out] output Buffer to encode into.
  13773. * @return Number of bytes encoded.
  13774. */
  13775. word32 SetOctetString(word32 len, byte* output)
  13776. {
  13777. return SetHeader(ASN_OCTET_STRING, len, output);
  13778. }
  13779. /* Encode a SET header in DER.
  13780. *
  13781. * @param [in] len Length of data in SET.
  13782. * @param [out] output Buffer to encode into.
  13783. * @return Number of bytes encoded.
  13784. */
  13785. word32 SetSet(word32 len, byte* output)
  13786. {
  13787. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13788. }
  13789. /* Encode an implicit context specific header in DER.
  13790. *
  13791. * Implicit means that it is constructed only if the included ASN.1 item is.
  13792. *
  13793. * @param [in] tag Tag for the implicit ASN.1 item.
  13794. * @param [in] number Context specific number.
  13795. * @param [in] len Length of data in SET.
  13796. * @param [out] output Buffer to encode into.
  13797. * @return Number of bytes encoded.
  13798. */
  13799. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13800. {
  13801. tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13802. | ASN_CONTEXT_SPECIFIC | number);
  13803. return SetHeader(tag, len, output);
  13804. }
  13805. /* Encode an explicit context specific header in DER.
  13806. *
  13807. * Explicit means that there will be an ASN.1 item underneath.
  13808. *
  13809. * @param [in] number Context specific number.
  13810. * @param [in] len Length of data in SET.
  13811. * @param [out] output Buffer to encode into.
  13812. * @return Number of bytes encoded.
  13813. */
  13814. word32 SetExplicit(byte number, word32 len, byte* output)
  13815. {
  13816. return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
  13817. len, output);
  13818. }
  13819. #if defined(OPENSSL_EXTRA)
  13820. /* Encode an Othername into DER.
  13821. *
  13822. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  13823. * @param [out] output Buffer to encode into. If NULL, don't encode.
  13824. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  13825. */
  13826. word32 SetOthername(void *name, byte *output)
  13827. {
  13828. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  13829. char *nameStr = NULL;
  13830. word32 nameSz = 0;
  13831. word32 len = 0;
  13832. if ((nm == NULL) || (nm->value == NULL)) {
  13833. WOLFSSL_MSG("otherName value is NULL");
  13834. return WOLFSSL_FAILURE;
  13835. }
  13836. nameStr = nm->value->value.utf8string->data;
  13837. nameSz = (word32)nm->value->value.utf8string->length;
  13838. len = nm->type_id->objSz +
  13839. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
  13840. SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
  13841. if (output != NULL) {
  13842. /* otherName OID */
  13843. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  13844. output += nm->type_id->objSz;
  13845. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  13846. output);
  13847. output += SetHeader(CTC_UTF8, nameSz, output);
  13848. XMEMCPY(output, nameStr, nameSz);
  13849. }
  13850. return len;
  13851. }
  13852. #endif /* OPENSSL_EXTRA */
  13853. #ifdef HAVE_ECC
  13854. /* Determines whether the signature algorithm is using ECDSA.
  13855. *
  13856. * @param [in] algoOID Signature algorithm identifier.
  13857. * @return 1 when algorithm is using ECDSA.
  13858. * @return 0 otherwise.
  13859. */
  13860. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  13861. {
  13862. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  13863. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  13864. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  13865. return 1;
  13866. }
  13867. return 0;
  13868. }
  13869. #endif
  13870. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  13871. * and post-quantum algorithms.
  13872. *
  13873. * @param [in] algoOID Algorithm OID.
  13874. * @return 1 when is EC signing algorithm.
  13875. * @return 0 otherwise.
  13876. */
  13877. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  13878. {
  13879. (void)algoOID;
  13880. return (0
  13881. #ifdef HAVE_ECC
  13882. || IsSigAlgoECDSA(algoOID)
  13883. #endif
  13884. #ifdef WOLFSSL_SM2
  13885. || (algoOID == SM2k)
  13886. #endif
  13887. #ifdef HAVE_ED25519
  13888. || (algoOID == ED25519k)
  13889. #endif
  13890. #ifdef HAVE_CURVE25519
  13891. || (algoOID == X25519k)
  13892. #endif
  13893. #ifdef HAVE_ED448
  13894. || (algoOID == ED448k)
  13895. #endif
  13896. #ifdef HAVE_CURVE448
  13897. || (algoOID == X448k)
  13898. #endif
  13899. #ifdef HAVE_PQC
  13900. #ifdef HAVE_FACON
  13901. || (algoOID == FALCON_LEVEL1k)
  13902. || (algoOID == FALCON_LEVEL5k)
  13903. #endif
  13904. #ifdef HAVE_DILITHIUM
  13905. || (algoOID == DILITHIUM_LEVEL2k)
  13906. || (algoOID == DILITHIUM_LEVEL3k)
  13907. || (algoOID == DILITHIUM_LEVEL5k)
  13908. #endif
  13909. #ifdef HAVE_SPHINCS
  13910. || (algoOID == SPHINCS_FAST_LEVEL1k)
  13911. || (algoOID == SPHINCS_FAST_LEVEL3k)
  13912. || (algoOID == SPHINCS_FAST_LEVEL5k)
  13913. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  13914. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  13915. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  13916. #endif
  13917. #endif /* HAVE_PQC */
  13918. );
  13919. }
  13920. /* Encode an algorithm identifier.
  13921. *
  13922. * [algoOID, type] is unique.
  13923. *
  13924. * @param [in] algoOID Algorithm identifier.
  13925. * @param [out] output Buffer to hold encoding.
  13926. * @param [in] type Type of OID being encoded.
  13927. * @param [in] curveSz Add extra space for curve data.
  13928. * @return Encoded data size on success.
  13929. * @return 0 when dynamic memory allocation fails.
  13930. */
  13931. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  13932. {
  13933. #ifndef WOLFSSL_ASN_TEMPLATE
  13934. word32 tagSz, idSz, seqSz, algoSz = 0;
  13935. const byte* algoName = 0;
  13936. byte ID_Length[1 + MAX_LENGTH_SZ];
  13937. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  13938. word32 length = 0;
  13939. tagSz = (type == oidHashType ||
  13940. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13941. (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
  13942. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13943. if (algoName == NULL) {
  13944. WOLFSSL_MSG("Unknown Algorithm");
  13945. return 0;
  13946. }
  13947. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  13948. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  13949. /* Copy only algo to output for DSA keys */
  13950. if (algoOID == DSAk && output) {
  13951. XMEMCPY(output, ID_Length, idSz);
  13952. XMEMCPY(output + idSz, algoName, algoSz);
  13953. if (tagSz == 2)
  13954. SetASNNull(&output[seqSz + idSz + algoSz]);
  13955. }
  13956. else if (output) {
  13957. XMEMCPY(output, seqArray, seqSz);
  13958. XMEMCPY(output + seqSz, ID_Length, idSz);
  13959. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  13960. if (tagSz == 2)
  13961. SetASNNull(&output[seqSz + idSz + algoSz]);
  13962. }
  13963. if (algoOID == DSAk)
  13964. length = idSz + algoSz + tagSz;
  13965. else
  13966. length = seqSz + idSz + algoSz + tagSz;
  13967. return length;
  13968. #else
  13969. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  13970. int ret = 0;
  13971. const byte* algoName = 0;
  13972. word32 algoSz = 0;
  13973. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  13974. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13975. if (algoName == NULL) {
  13976. WOLFSSL_MSG("Unknown Algorithm");
  13977. }
  13978. else {
  13979. int sz;
  13980. int o = 0;
  13981. /* Set the OID and OID type to encode. */
  13982. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  13983. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  13984. if (!(type == oidHashType ||
  13985. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13986. (type == oidKeyType && algoOID == RSAk))) {
  13987. /* Don't put out NULL DER item. */
  13988. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  13989. }
  13990. if (algoOID == DSAk) {
  13991. /* Don't include SEQUENCE for DSA keys. */
  13992. o = 1;
  13993. }
  13994. else if (curveSz > 0) {
  13995. /* Don't put out NULL DER item. */
  13996. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  13997. /* Include space for extra data of length curveSz.
  13998. * Subtract 1 for sequence and 1 for length encoding. */
  13999. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  14000. (word32)curveSz - 2);
  14001. }
  14002. /* Calculate size of encoding. */
  14003. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  14004. (int)algoIdASN_Length - (int)o, &sz);
  14005. if (ret == 0 && output != NULL) {
  14006. /* Encode into buffer. */
  14007. SetASN_Items(algoIdASN + o, dataASN + o,
  14008. (int)algoIdASN_Length - (int)o, output);
  14009. if (curveSz > 0) {
  14010. /* Return size excluding curve data. */
  14011. sz = (int)(dataASN[o].offset -
  14012. dataASN[ALGOIDASN_IDX_NULL].offset);
  14013. }
  14014. }
  14015. if (ret == 0) {
  14016. /* Return encoded size. */
  14017. ret = sz;
  14018. }
  14019. else {
  14020. /* Unsigned return type so 0 indicates error. */
  14021. ret = 0;
  14022. }
  14023. }
  14024. FREE_ASNSETDATA(dataASN, NULL);
  14025. return (word32)ret;
  14026. #endif /* WOLFSSL_ASN_TEMPLATE */
  14027. }
  14028. #ifdef WOLFSSL_ASN_TEMPLATE
  14029. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  14030. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  14031. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  14032. */
  14033. static const ASNItem digestInfoASN[] = {
  14034. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14035. /* digestAlgorithm */
  14036. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14037. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  14038. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  14039. /* digest */
  14040. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  14041. };
  14042. enum {
  14043. DIGESTINFOASN_IDX_SEQ = 0,
  14044. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  14045. DIGESTINFOASN_IDX_DIGALGO_OID,
  14046. DIGESTINFOASN_IDX_DIGALGO_NULL,
  14047. DIGESTINFOASN_IDX_DIGEST
  14048. };
  14049. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  14050. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  14051. #endif
  14052. /* Encode signature.
  14053. *
  14054. * @param [out] out Buffer to hold encoding.
  14055. * @param [in] digest Buffer holding digest.
  14056. * @param [in] digSz Length of digest in bytes.
  14057. * @return Encoded data size on success.
  14058. * @return 0 when dynamic memory allocation fails.
  14059. */
  14060. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  14061. int hashOID)
  14062. {
  14063. #ifndef WOLFSSL_ASN_TEMPLATE
  14064. byte digArray[MAX_ENCODED_DIG_SZ];
  14065. byte algoArray[MAX_ALGO_SZ];
  14066. byte seqArray[MAX_SEQ_SZ];
  14067. word32 encDigSz, algoSz, seqSz;
  14068. encDigSz = SetDigest(digest, digSz, digArray);
  14069. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  14070. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  14071. XMEMCPY(out, seqArray, seqSz);
  14072. XMEMCPY(out + seqSz, algoArray, algoSz);
  14073. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  14074. return encDigSz + algoSz + seqSz;
  14075. #else
  14076. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  14077. int ret = 0;
  14078. int sz;
  14079. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  14080. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  14081. if (ret == 0) {
  14082. /* Set hash OID and type. */
  14083. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  14084. oidHashType);
  14085. /* Set digest. */
  14086. if (digest == out) {
  14087. XMEMCPY(dgst, digest, digSz);
  14088. digest = dgst;
  14089. }
  14090. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  14091. /* Calculate size of encoding. */
  14092. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  14093. }
  14094. if (ret == 0) {
  14095. /* Encode PKCS#1 v1.5 RSA signature. */
  14096. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  14097. ret = sz;
  14098. }
  14099. else {
  14100. /* Unsigned return type so 0 indicates error. */
  14101. ret = 0;
  14102. }
  14103. FREE_ASNSETDATA(dataASN, NULL);
  14104. return (word32)ret;
  14105. #endif
  14106. }
  14107. #ifndef NO_CERTS
  14108. int wc_GetCTC_HashOID(int type)
  14109. {
  14110. int ret;
  14111. enum wc_HashType hType;
  14112. hType = wc_HashTypeConvert(type);
  14113. ret = wc_HashGetOID(hType);
  14114. if (ret < 0) {
  14115. ret = 0; /* backwards compatibility */
  14116. }
  14117. return ret;
  14118. }
  14119. /* Initialize a signature context object.
  14120. *
  14121. * Object used for signing and verifying a certificate signature.
  14122. *
  14123. * @param [in, out] sigCtx Signature context object.
  14124. * @param [in] heap Dynamic memory hint.
  14125. * @param [in] devId Hardware device identifier.
  14126. */
  14127. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  14128. {
  14129. if (sigCtx) {
  14130. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  14131. sigCtx->devId = devId;
  14132. sigCtx->heap = heap;
  14133. }
  14134. }
  14135. /* Free dynamic data in a signature context object.
  14136. *
  14137. * @param [in, out] sigCtx Signature context object.
  14138. */
  14139. void FreeSignatureCtx(SignatureCtx* sigCtx)
  14140. {
  14141. if (sigCtx == NULL)
  14142. return;
  14143. if (sigCtx->digest) {
  14144. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  14145. sigCtx->digest = NULL;
  14146. }
  14147. #if !(defined(NO_RSA) && defined(NO_DSA))
  14148. if (sigCtx->sigCpy) {
  14149. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14150. sigCtx->sigCpy = NULL;
  14151. }
  14152. #endif
  14153. #ifndef NO_ASN_CRYPT
  14154. if (sigCtx->key.ptr) {
  14155. switch (sigCtx->keyOID) {
  14156. #ifndef NO_RSA
  14157. #ifdef WC_RSA_PSS
  14158. case RSAPSSk:
  14159. #endif
  14160. case RSAk:
  14161. wc_FreeRsaKey(sigCtx->key.rsa);
  14162. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  14163. sigCtx->key.rsa = NULL;
  14164. break;
  14165. #endif /* !NO_RSA */
  14166. #ifndef NO_DSA
  14167. case DSAk:
  14168. wc_FreeDsaKey(sigCtx->key.dsa);
  14169. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  14170. sigCtx->key.dsa = NULL;
  14171. break;
  14172. #endif
  14173. #ifdef HAVE_ECC
  14174. case ECDSAk:
  14175. #ifdef WOLFSSL_SM2
  14176. case SM2k:
  14177. #endif
  14178. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14179. defined(WC_ASYNC_ENABLE_ECC)
  14180. if (sigCtx->key.ecc->nb_ctx != NULL) {
  14181. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  14182. DYNAMIC_TYPE_TMP_BUFFER);
  14183. }
  14184. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14185. WC_ASYNC_ENABLE_ECC */
  14186. wc_ecc_free(sigCtx->key.ecc);
  14187. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  14188. sigCtx->key.ecc = NULL;
  14189. break;
  14190. #endif /* HAVE_ECC */
  14191. #ifdef HAVE_ED25519
  14192. case ED25519k:
  14193. wc_ed25519_free(sigCtx->key.ed25519);
  14194. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  14195. sigCtx->key.ed25519 = NULL;
  14196. break;
  14197. #endif /* HAVE_ED25519 */
  14198. #ifdef HAVE_ED448
  14199. case ED448k:
  14200. wc_ed448_free(sigCtx->key.ed448);
  14201. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  14202. sigCtx->key.ed448 = NULL;
  14203. break;
  14204. #endif /* HAVE_ED448 */
  14205. #if defined(HAVE_PQC)
  14206. #if defined(HAVE_FALCON)
  14207. case FALCON_LEVEL1k:
  14208. case FALCON_LEVEL5k:
  14209. wc_falcon_free(sigCtx->key.falcon);
  14210. XFREE(sigCtx->key.falcon, sigCtx->heap,
  14211. DYNAMIC_TYPE_FALCON);
  14212. sigCtx->key.falcon = NULL;
  14213. break;
  14214. #endif /* HAVE_FALCON */
  14215. #if defined(HAVE_DILITHIUM)
  14216. case DILITHIUM_LEVEL2k:
  14217. case DILITHIUM_LEVEL3k:
  14218. case DILITHIUM_LEVEL5k:
  14219. wc_dilithium_free(sigCtx->key.dilithium);
  14220. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  14221. DYNAMIC_TYPE_DILITHIUM);
  14222. sigCtx->key.dilithium = NULL;
  14223. break;
  14224. #endif /* HAVE_DILITHIUM */
  14225. #if defined(HAVE_SPHINCS)
  14226. case SPHINCS_FAST_LEVEL1k:
  14227. case SPHINCS_FAST_LEVEL3k:
  14228. case SPHINCS_FAST_LEVEL5k:
  14229. case SPHINCS_SMALL_LEVEL1k:
  14230. case SPHINCS_SMALL_LEVEL3k:
  14231. case SPHINCS_SMALL_LEVEL5k:
  14232. wc_sphincs_free(sigCtx->key.sphincs);
  14233. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  14234. DYNAMIC_TYPE_SPHINCS);
  14235. sigCtx->key.sphincs = NULL;
  14236. break;
  14237. #endif /* HAVE_SPHINCS */
  14238. #endif /* HAVE_PQC */
  14239. default:
  14240. break;
  14241. } /* switch (keyOID) */
  14242. sigCtx->key.ptr = NULL;
  14243. }
  14244. #endif
  14245. /* reset state, we are done */
  14246. sigCtx->state = SIG_STATE_BEGIN;
  14247. }
  14248. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  14249. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  14250. byte* digest, int* typeH, int* digestSz, int verify)
  14251. {
  14252. int ret = 0;
  14253. switch (sigOID) {
  14254. #if defined(WOLFSSL_MD2)
  14255. case CTC_MD2wRSA:
  14256. if (!verify) {
  14257. ret = HASH_TYPE_E;
  14258. WOLFSSL_MSG("MD2 not supported for signing");
  14259. }
  14260. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  14261. *typeH = MD2h;
  14262. *digestSz = MD2_DIGEST_SIZE;
  14263. }
  14264. break;
  14265. #endif
  14266. #ifndef NO_MD5
  14267. case CTC_MD5wRSA:
  14268. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  14269. *typeH = MD5h;
  14270. *digestSz = WC_MD5_DIGEST_SIZE;
  14271. }
  14272. break;
  14273. #endif
  14274. #ifndef NO_SHA
  14275. case CTC_SHAwRSA:
  14276. case CTC_SHAwDSA:
  14277. case CTC_SHAwECDSA:
  14278. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  14279. *typeH = SHAh;
  14280. *digestSz = WC_SHA_DIGEST_SIZE;
  14281. }
  14282. break;
  14283. #endif
  14284. #ifdef WOLFSSL_SHA224
  14285. case CTC_SHA224wRSA:
  14286. case CTC_SHA224wECDSA:
  14287. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  14288. *typeH = SHA224h;
  14289. *digestSz = WC_SHA224_DIGEST_SIZE;
  14290. }
  14291. break;
  14292. #endif
  14293. #ifndef NO_SHA256
  14294. case CTC_SHA256wRSA:
  14295. case CTC_SHA256wECDSA:
  14296. case CTC_SHA256wDSA:
  14297. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  14298. *typeH = SHA256h;
  14299. *digestSz = WC_SHA256_DIGEST_SIZE;
  14300. }
  14301. break;
  14302. #endif
  14303. #ifdef WOLFSSL_SHA384
  14304. case CTC_SHA384wRSA:
  14305. case CTC_SHA384wECDSA:
  14306. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  14307. *typeH = SHA384h;
  14308. *digestSz = WC_SHA384_DIGEST_SIZE;
  14309. }
  14310. break;
  14311. #endif
  14312. #ifdef WOLFSSL_SHA512
  14313. case CTC_SHA512wRSA:
  14314. case CTC_SHA512wECDSA:
  14315. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  14316. *typeH = SHA512h;
  14317. *digestSz = WC_SHA512_DIGEST_SIZE;
  14318. }
  14319. break;
  14320. #endif
  14321. #ifdef WOLFSSL_SHA3
  14322. #ifndef WOLFSSL_NOSHA3_224
  14323. case CTC_SHA3_224wRSA:
  14324. case CTC_SHA3_224wECDSA:
  14325. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  14326. *typeH = SHA3_224h;
  14327. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  14328. }
  14329. break;
  14330. #endif
  14331. #ifndef WOLFSSL_NOSHA3_256
  14332. case CTC_SHA3_256wRSA:
  14333. case CTC_SHA3_256wECDSA:
  14334. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  14335. *typeH = SHA3_256h;
  14336. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  14337. }
  14338. break;
  14339. #endif
  14340. #ifndef WOLFSSL_NOSHA3_384
  14341. case CTC_SHA3_384wRSA:
  14342. case CTC_SHA3_384wECDSA:
  14343. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  14344. *typeH = SHA3_384h;
  14345. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  14346. }
  14347. break;
  14348. #endif
  14349. #ifndef WOLFSSL_NOSHA3_512
  14350. case CTC_SHA3_512wRSA:
  14351. case CTC_SHA3_512wECDSA:
  14352. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  14353. *typeH = SHA3_512h;
  14354. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  14355. }
  14356. break;
  14357. #endif
  14358. #endif
  14359. #if defined(WOLFSSL_SM2) & defined(WOLFSSL_SM3)
  14360. case CTC_SM3wSM2:
  14361. if ((ret = wc_Sm3Hash(buf, bufSz, digest)) == 0) {
  14362. *typeH = SM3h;
  14363. *digestSz = WC_SM3_DIGEST_SIZE;
  14364. }
  14365. break;
  14366. #endif
  14367. #ifdef HAVE_ED25519
  14368. case CTC_ED25519:
  14369. /* Hashes done in signing operation.
  14370. * Two dependent hashes with prefixes performed.
  14371. */
  14372. break;
  14373. #endif
  14374. #ifdef HAVE_ED448
  14375. case CTC_ED448:
  14376. /* Hashes done in signing operation.
  14377. * Two dependent hashes with prefixes performed.
  14378. */
  14379. break;
  14380. #endif
  14381. #ifdef HAVE_PQC
  14382. #ifdef HAVE_FALCON
  14383. case CTC_FALCON_LEVEL1:
  14384. case CTC_FALCON_LEVEL5:
  14385. /* Hashes done in signing operation. */
  14386. break;
  14387. #endif
  14388. #ifdef HAVE_DILITHIUM
  14389. case CTC_DILITHIUM_LEVEL2:
  14390. case CTC_DILITHIUM_LEVEL3:
  14391. case CTC_DILITHIUM_LEVEL5:
  14392. /* Hashes done in signing operation. */
  14393. break;
  14394. #endif
  14395. #ifdef HAVE_SPHINCS
  14396. case CTC_SPHINCS_FAST_LEVEL1:
  14397. case CTC_SPHINCS_FAST_LEVEL3:
  14398. case CTC_SPHINCS_FAST_LEVEL5:
  14399. case CTC_SPHINCS_SMALL_LEVEL1:
  14400. case CTC_SPHINCS_SMALL_LEVEL3:
  14401. case CTC_SPHINCS_SMALL_LEVEL5:
  14402. /* Hashes done in signing operation. */
  14403. break;
  14404. #endif
  14405. #endif /* HAVE_PQC */
  14406. default:
  14407. ret = HASH_TYPE_E;
  14408. WOLFSSL_MSG("Hash for Signature has unsupported type");
  14409. }
  14410. (void)buf;
  14411. (void)bufSz;
  14412. (void)sigOID;
  14413. (void)digest;
  14414. (void)digestSz;
  14415. (void)typeH;
  14416. (void)verify;
  14417. return ret;
  14418. }
  14419. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  14420. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  14421. static int ConfirmSignature(SignatureCtx* sigCtx,
  14422. const byte* buf, word32 bufSz,
  14423. const byte* key, word32 keySz, word32 keyOID,
  14424. const byte* sig, word32 sigSz, word32 sigOID,
  14425. const byte* sigParams, word32 sigParamsSz,
  14426. byte* rsaKeyIdx)
  14427. {
  14428. int ret = 0;
  14429. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  14430. CertAttribute* certatt = NULL;
  14431. #endif
  14432. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  14433. keySz == 0 || sig == NULL || sigSz == 0) {
  14434. return BAD_FUNC_ARG;
  14435. }
  14436. (void)key;
  14437. (void)keySz;
  14438. (void)sig;
  14439. (void)sigSz;
  14440. (void)sigParams;
  14441. (void)sigParamsSz;
  14442. WOLFSSL_ENTER("ConfirmSignature");
  14443. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
  14444. (void)rsaKeyIdx;
  14445. #else
  14446. #if !defined(NO_RSA) || defined(HAVE_ECC)
  14447. certatt = (CertAttribute*)&sigCtx->CertAtt;
  14448. #endif
  14449. if (certatt) {
  14450. certatt->keyIndex = rsaKeyIdx;
  14451. certatt->cert = buf;
  14452. certatt->certSz = bufSz;
  14453. }
  14454. #endif
  14455. #ifndef NO_ASN_CRYPT
  14456. switch (sigCtx->state) {
  14457. case SIG_STATE_BEGIN:
  14458. {
  14459. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  14460. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  14461. DYNAMIC_TYPE_DIGEST);
  14462. if (sigCtx->digest == NULL) {
  14463. ERROR_OUT(MEMORY_E, exit_cs);
  14464. }
  14465. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14466. /* RSA PSS Defaults */
  14467. sigCtx->hash = WC_HASH_TYPE_SHA;
  14468. sigCtx->mgf = WC_MGF1SHA1;
  14469. sigCtx->saltLen = 20;
  14470. #endif
  14471. sigCtx->state = SIG_STATE_HASH;
  14472. } /* SIG_STATE_BEGIN */
  14473. FALL_THROUGH;
  14474. case SIG_STATE_HASH:
  14475. {
  14476. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14477. if (sigOID == RSAPSSk) {
  14478. word32 fakeSigOID = 0;
  14479. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  14480. &sigCtx->mgf, &sigCtx->saltLen);
  14481. if (ret != 0) {
  14482. goto exit_cs;
  14483. }
  14484. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  14485. if (ret != 0) {
  14486. goto exit_cs;
  14487. }
  14488. /* Decode parameters. */
  14489. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  14490. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14491. if (ret != 0) {
  14492. goto exit_cs;
  14493. }
  14494. }
  14495. else
  14496. #endif
  14497. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14498. if (sigOID == CTC_SM3wSM2) {
  14499. ; /* SM2 hash requires public key. Done later. */
  14500. }
  14501. else
  14502. #endif
  14503. {
  14504. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  14505. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14506. if (ret != 0) {
  14507. goto exit_cs;
  14508. }
  14509. }
  14510. sigCtx->state = SIG_STATE_KEY;
  14511. } /* SIG_STATE_HASH */
  14512. FALL_THROUGH;
  14513. case SIG_STATE_KEY:
  14514. {
  14515. switch (keyOID) {
  14516. #ifndef NO_RSA
  14517. #ifdef WC_RSA_PSS
  14518. case RSAPSSk:
  14519. #endif
  14520. case RSAk:
  14521. {
  14522. word32 idx = 0;
  14523. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  14524. sigCtx->heap, DYNAMIC_TYPE_RSA);
  14525. if (sigCtx->key.rsa == NULL) {
  14526. ERROR_OUT(MEMORY_E, exit_cs);
  14527. }
  14528. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  14529. sigCtx->devId)) != 0) {
  14530. goto exit_cs;
  14531. }
  14532. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  14533. DYNAMIC_TYPE_SIGNATURE);
  14534. if (sigCtx->sigCpy == NULL) {
  14535. ERROR_OUT(MEMORY_E, exit_cs);
  14536. }
  14537. if (sigSz > MAX_ENCODED_SIG_SZ) {
  14538. WOLFSSL_MSG("Verify Signature is too big");
  14539. ERROR_OUT(BUFFER_E, exit_cs);
  14540. }
  14541. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  14542. keySz)) != 0) {
  14543. WOLFSSL_MSG("ASN Key decode error RSA");
  14544. WOLFSSL_ERROR_VERBOSE(ret);
  14545. goto exit_cs;
  14546. }
  14547. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14548. sigCtx->out = NULL;
  14549. #ifdef WOLFSSL_ASYNC_CRYPT
  14550. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  14551. #endif
  14552. break;
  14553. }
  14554. #endif /* !NO_RSA */
  14555. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14556. case DSAk:
  14557. {
  14558. word32 idx = 0;
  14559. if (sigSz < DSA_MIN_SIG_SIZE) {
  14560. WOLFSSL_MSG("Verify Signature is too small");
  14561. ERROR_OUT(BUFFER_E, exit_cs);
  14562. }
  14563. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  14564. sigCtx->heap, DYNAMIC_TYPE_DSA);
  14565. if (sigCtx->key.dsa == NULL) {
  14566. ERROR_OUT(MEMORY_E, exit_cs);
  14567. }
  14568. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  14569. WOLFSSL_MSG("wc_InitDsaKey_h error");
  14570. goto exit_cs;
  14571. }
  14572. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  14573. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14574. if (sigCtx->sigCpy == NULL) {
  14575. ERROR_OUT(MEMORY_E, exit_cs);
  14576. }
  14577. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  14578. keySz)) != 0) {
  14579. WOLFSSL_MSG("ASN Key decode error DSA");
  14580. WOLFSSL_ERROR_VERBOSE(ret);
  14581. goto exit_cs;
  14582. }
  14583. if (sigSz != DSA_160_SIG_SIZE &&
  14584. sigSz != DSA_256_SIG_SIZE) {
  14585. /* Try to parse it as the contents of a bitstring */
  14586. #ifdef WOLFSSL_SMALL_STACK
  14587. mp_int* r;
  14588. mp_int* s;
  14589. #else
  14590. mp_int r[1];
  14591. mp_int s[1];
  14592. #endif
  14593. int rSz;
  14594. int sSz;
  14595. #ifdef WOLFSSL_SMALL_STACK
  14596. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14597. DYNAMIC_TYPE_TMP_BUFFER);
  14598. if (r == NULL) {
  14599. ERROR_OUT(MEMORY_E, exit_cs);
  14600. }
  14601. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14602. DYNAMIC_TYPE_TMP_BUFFER);
  14603. if (s == NULL) {
  14604. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14605. ERROR_OUT(MEMORY_E, exit_cs);
  14606. }
  14607. #endif
  14608. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  14609. goto exit_cs;
  14610. }
  14611. idx = 0;
  14612. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14613. != 0) {
  14614. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14615. "incorrect format");
  14616. mp_free(r);
  14617. mp_free(s);
  14618. #ifdef WOLFSSL_SMALL_STACK
  14619. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14620. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14621. #endif
  14622. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14623. }
  14624. rSz = mp_unsigned_bin_size(r);
  14625. sSz = mp_unsigned_bin_size(s);
  14626. if (rSz + sSz > (int)sigSz) {
  14627. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14628. "incorrect format");
  14629. mp_free(r);
  14630. mp_free(s);
  14631. #ifdef WOLFSSL_SMALL_STACK
  14632. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14633. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14634. #endif
  14635. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14636. }
  14637. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14638. mp_to_unsigned_bin(s,
  14639. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14640. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14641. "incorrect format");
  14642. mp_free(r);
  14643. mp_free(s);
  14644. #ifdef WOLFSSL_SMALL_STACK
  14645. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14646. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14647. #endif
  14648. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14649. }
  14650. mp_free(r);
  14651. mp_free(s);
  14652. #ifdef WOLFSSL_SMALL_STACK
  14653. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14654. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14655. #endif
  14656. }
  14657. else {
  14658. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14659. }
  14660. break;
  14661. }
  14662. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14663. #ifdef HAVE_ECC
  14664. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14665. case SM2k:
  14666. #endif
  14667. case ECDSAk:
  14668. {
  14669. word32 idx = 0;
  14670. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14671. defined(WC_ASYNC_ENABLE_ECC)
  14672. ecc_nb_ctx_t* nbCtx;
  14673. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14674. WC_ASYNC_ENABLE_ECC */
  14675. sigCtx->verify = 0;
  14676. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14677. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14678. if (sigCtx->key.ecc == NULL) {
  14679. ERROR_OUT(MEMORY_E, exit_cs);
  14680. }
  14681. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14682. sigCtx->devId)) < 0) {
  14683. goto exit_cs;
  14684. }
  14685. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14686. defined(WC_ASYNC_ENABLE_ECC)
  14687. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14688. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14689. if (nbCtx == NULL) {
  14690. ERROR_OUT(MEMORY_E, exit_cs);
  14691. }
  14692. else {
  14693. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14694. if (ret != 0) {
  14695. goto exit_cs;
  14696. }
  14697. }
  14698. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14699. WC_ASYNC_ENABLE_ECC */
  14700. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14701. keySz);
  14702. if (ret < 0) {
  14703. WOLFSSL_MSG("ASN Key import error ECC");
  14704. WOLFSSL_ERROR_VERBOSE(ret);
  14705. goto exit_cs;
  14706. }
  14707. #ifdef WOLFSSL_ASYNC_CRYPT
  14708. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14709. #endif
  14710. break;
  14711. }
  14712. #endif /* HAVE_ECC */
  14713. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14714. case ED25519k:
  14715. {
  14716. sigCtx->verify = 0;
  14717. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14718. sizeof(ed25519_key), sigCtx->heap,
  14719. DYNAMIC_TYPE_ED25519);
  14720. if (sigCtx->key.ed25519 == NULL) {
  14721. ERROR_OUT(MEMORY_E, exit_cs);
  14722. }
  14723. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14724. sigCtx->heap, sigCtx->devId)) < 0) {
  14725. goto exit_cs;
  14726. }
  14727. if ((ret = wc_ed25519_import_public(key, keySz,
  14728. sigCtx->key.ed25519)) < 0) {
  14729. WOLFSSL_MSG("ASN Key import error ED25519");
  14730. WOLFSSL_ERROR_VERBOSE(ret);
  14731. goto exit_cs;
  14732. }
  14733. #ifdef WOLFSSL_ASYNC_CRYPT
  14734. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14735. #endif
  14736. break;
  14737. }
  14738. #endif
  14739. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14740. case ED448k:
  14741. {
  14742. sigCtx->verify = 0;
  14743. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14744. sizeof(ed448_key), sigCtx->heap,
  14745. DYNAMIC_TYPE_ED448);
  14746. if (sigCtx->key.ed448 == NULL) {
  14747. ERROR_OUT(MEMORY_E, exit_cs);
  14748. }
  14749. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14750. goto exit_cs;
  14751. }
  14752. if ((ret = wc_ed448_import_public(key, keySz,
  14753. sigCtx->key.ed448)) < 0) {
  14754. WOLFSSL_MSG("ASN Key import error ED448");
  14755. WOLFSSL_ERROR_VERBOSE(ret);
  14756. goto exit_cs;
  14757. }
  14758. #ifdef WOLFSSL_ASYNC_CRYPT
  14759. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14760. #endif
  14761. break;
  14762. }
  14763. #endif
  14764. #if defined(HAVE_PQC)
  14765. #if defined(HAVE_FALCON)
  14766. case FALCON_LEVEL1k:
  14767. {
  14768. sigCtx->verify = 0;
  14769. sigCtx->key.falcon =
  14770. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14771. sigCtx->heap,
  14772. DYNAMIC_TYPE_FALCON);
  14773. if (sigCtx->key.falcon == NULL) {
  14774. ERROR_OUT(MEMORY_E, exit_cs);
  14775. }
  14776. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14777. goto exit_cs;
  14778. }
  14779. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14780. < 0) {
  14781. goto exit_cs;
  14782. }
  14783. if ((ret = wc_falcon_import_public(key, keySz,
  14784. sigCtx->key.falcon)) < 0) {
  14785. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14786. WOLFSSL_ERROR_VERBOSE(ret);
  14787. goto exit_cs;
  14788. }
  14789. break;
  14790. }
  14791. case FALCON_LEVEL5k:
  14792. {
  14793. sigCtx->verify = 0;
  14794. sigCtx->key.falcon =
  14795. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14796. sigCtx->heap,
  14797. DYNAMIC_TYPE_FALCON);
  14798. if (sigCtx->key.falcon == NULL) {
  14799. ERROR_OUT(MEMORY_E, exit_cs);
  14800. }
  14801. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14802. goto exit_cs;
  14803. }
  14804. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14805. < 0) {
  14806. goto exit_cs;
  14807. }
  14808. if ((ret = wc_falcon_import_public(key, keySz,
  14809. sigCtx->key.falcon)) < 0) {
  14810. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14811. WOLFSSL_ERROR_VERBOSE(ret);
  14812. goto exit_cs;
  14813. }
  14814. break;
  14815. }
  14816. #endif /* HAVE_FALCON */
  14817. #if defined(HAVE_DILITHIUM)
  14818. case DILITHIUM_LEVEL2k:
  14819. {
  14820. sigCtx->verify = 0;
  14821. sigCtx->key.dilithium =
  14822. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14823. sigCtx->heap,
  14824. DYNAMIC_TYPE_DILITHIUM);
  14825. if (sigCtx->key.dilithium == NULL) {
  14826. ERROR_OUT(MEMORY_E, exit_cs);
  14827. }
  14828. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14829. goto exit_cs;
  14830. }
  14831. if ((ret = wc_dilithium_set_level(
  14832. sigCtx->key.dilithium, 2))
  14833. < 0) {
  14834. goto exit_cs;
  14835. }
  14836. if ((ret = wc_dilithium_import_public(key, keySz,
  14837. sigCtx->key.dilithium)) < 0) {
  14838. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14839. goto exit_cs;
  14840. }
  14841. break;
  14842. }
  14843. case DILITHIUM_LEVEL3k:
  14844. {
  14845. sigCtx->verify = 0;
  14846. sigCtx->key.dilithium =
  14847. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14848. sigCtx->heap,
  14849. DYNAMIC_TYPE_DILITHIUM);
  14850. if (sigCtx->key.dilithium == NULL) {
  14851. ERROR_OUT(MEMORY_E, exit_cs);
  14852. }
  14853. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14854. goto exit_cs;
  14855. }
  14856. if ((ret = wc_dilithium_set_level(
  14857. sigCtx->key.dilithium, 3))
  14858. < 0) {
  14859. goto exit_cs;
  14860. }
  14861. if ((ret = wc_dilithium_import_public(key, keySz,
  14862. sigCtx->key.dilithium)) < 0) {
  14863. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14864. goto exit_cs;
  14865. }
  14866. break;
  14867. }
  14868. case DILITHIUM_LEVEL5k:
  14869. {
  14870. sigCtx->verify = 0;
  14871. sigCtx->key.dilithium =
  14872. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14873. sigCtx->heap,
  14874. DYNAMIC_TYPE_DILITHIUM);
  14875. if (sigCtx->key.dilithium == NULL) {
  14876. ERROR_OUT(MEMORY_E, exit_cs);
  14877. }
  14878. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14879. goto exit_cs;
  14880. }
  14881. if ((ret = wc_dilithium_set_level(
  14882. sigCtx->key.dilithium, 5))
  14883. < 0) {
  14884. goto exit_cs;
  14885. }
  14886. if ((ret = wc_dilithium_import_public(key, keySz,
  14887. sigCtx->key.dilithium)) < 0) {
  14888. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14889. goto exit_cs;
  14890. }
  14891. break;
  14892. }
  14893. #endif /* HAVE_DILITHIUM */
  14894. #if defined(HAVE_SPHINCS)
  14895. case SPHINCS_FAST_LEVEL1k:
  14896. {
  14897. sigCtx->verify = 0;
  14898. sigCtx->key.sphincs =
  14899. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14900. sigCtx->heap,
  14901. DYNAMIC_TYPE_SPHINCS);
  14902. if (sigCtx->key.sphincs == NULL) {
  14903. ERROR_OUT(MEMORY_E, exit_cs);
  14904. }
  14905. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14906. goto exit_cs;
  14907. }
  14908. if ((ret = wc_sphincs_set_level_and_optim(
  14909. sigCtx->key.sphincs, 1, FAST_VARIANT))
  14910. < 0) {
  14911. goto exit_cs;
  14912. }
  14913. if ((ret = wc_sphincs_import_public(key, keySz,
  14914. sigCtx->key.sphincs)) < 0) {
  14915. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14916. goto exit_cs;
  14917. }
  14918. break;
  14919. }
  14920. case SPHINCS_FAST_LEVEL3k:
  14921. {
  14922. sigCtx->verify = 0;
  14923. sigCtx->key.sphincs =
  14924. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14925. sigCtx->heap,
  14926. DYNAMIC_TYPE_SPHINCS);
  14927. if (sigCtx->key.sphincs == NULL) {
  14928. ERROR_OUT(MEMORY_E, exit_cs);
  14929. }
  14930. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14931. goto exit_cs;
  14932. }
  14933. if ((ret = wc_sphincs_set_level_and_optim(
  14934. sigCtx->key.sphincs, 3, FAST_VARIANT))
  14935. < 0) {
  14936. goto exit_cs;
  14937. }
  14938. if ((ret = wc_sphincs_import_public(key, keySz,
  14939. sigCtx->key.sphincs)) < 0) {
  14940. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14941. goto exit_cs;
  14942. }
  14943. break;
  14944. }
  14945. case SPHINCS_FAST_LEVEL5k:
  14946. {
  14947. sigCtx->verify = 0;
  14948. sigCtx->key.sphincs =
  14949. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14950. sigCtx->heap,
  14951. DYNAMIC_TYPE_SPHINCS);
  14952. if (sigCtx->key.sphincs == NULL) {
  14953. ERROR_OUT(MEMORY_E, exit_cs);
  14954. }
  14955. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14956. goto exit_cs;
  14957. }
  14958. if ((ret = wc_sphincs_set_level_and_optim(
  14959. sigCtx->key.sphincs, 5, FAST_VARIANT))
  14960. < 0) {
  14961. goto exit_cs;
  14962. }
  14963. if ((ret = wc_sphincs_import_public(key, keySz,
  14964. sigCtx->key.sphincs)) < 0) {
  14965. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14966. goto exit_cs;
  14967. }
  14968. break;
  14969. }
  14970. case SPHINCS_SMALL_LEVEL1k:
  14971. {
  14972. sigCtx->verify = 0;
  14973. sigCtx->key.sphincs =
  14974. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14975. sigCtx->heap,
  14976. DYNAMIC_TYPE_SPHINCS);
  14977. if (sigCtx->key.sphincs == NULL) {
  14978. ERROR_OUT(MEMORY_E, exit_cs);
  14979. }
  14980. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14981. goto exit_cs;
  14982. }
  14983. if ((ret = wc_sphincs_set_level_and_optim(
  14984. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  14985. < 0) {
  14986. goto exit_cs;
  14987. }
  14988. if ((ret = wc_sphincs_import_public(key, keySz,
  14989. sigCtx->key.sphincs)) < 0) {
  14990. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14991. goto exit_cs;
  14992. }
  14993. break;
  14994. }
  14995. case SPHINCS_SMALL_LEVEL3k:
  14996. {
  14997. sigCtx->verify = 0;
  14998. sigCtx->key.sphincs =
  14999. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15000. sigCtx->heap,
  15001. DYNAMIC_TYPE_SPHINCS);
  15002. if (sigCtx->key.sphincs == NULL) {
  15003. ERROR_OUT(MEMORY_E, exit_cs);
  15004. }
  15005. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15006. goto exit_cs;
  15007. }
  15008. if ((ret = wc_sphincs_set_level_and_optim(
  15009. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  15010. < 0) {
  15011. goto exit_cs;
  15012. }
  15013. if ((ret = wc_sphincs_import_public(key, keySz,
  15014. sigCtx->key.sphincs)) < 0) {
  15015. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  15016. goto exit_cs;
  15017. }
  15018. break;
  15019. }
  15020. case SPHINCS_SMALL_LEVEL5k:
  15021. {
  15022. sigCtx->verify = 0;
  15023. sigCtx->key.sphincs =
  15024. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15025. sigCtx->heap,
  15026. DYNAMIC_TYPE_SPHINCS);
  15027. if (sigCtx->key.sphincs == NULL) {
  15028. ERROR_OUT(MEMORY_E, exit_cs);
  15029. }
  15030. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15031. goto exit_cs;
  15032. }
  15033. if ((ret = wc_sphincs_set_level_and_optim(
  15034. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  15035. < 0) {
  15036. goto exit_cs;
  15037. }
  15038. if ((ret = wc_sphincs_import_public(key, keySz,
  15039. sigCtx->key.sphincs)) < 0) {
  15040. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  15041. goto exit_cs;
  15042. }
  15043. break;
  15044. }
  15045. #endif /* HAVE_SPHINCS */
  15046. #endif /* HAVE_PQC */
  15047. default:
  15048. WOLFSSL_MSG("Verify Key type unknown");
  15049. ret = ASN_UNKNOWN_OID_E;
  15050. WOLFSSL_ERROR_VERBOSE(ret);
  15051. break;
  15052. } /* switch (keyOID) */
  15053. if (ret != 0) {
  15054. goto exit_cs;
  15055. }
  15056. sigCtx->state = SIG_STATE_DO;
  15057. #ifdef WOLFSSL_ASYNC_CRYPT
  15058. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  15059. /* make sure event is initialized */
  15060. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  15061. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  15062. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  15063. }
  15064. #endif
  15065. } /* SIG_STATE_KEY */
  15066. FALL_THROUGH;
  15067. case SIG_STATE_DO:
  15068. {
  15069. switch (keyOID) {
  15070. #ifndef NO_RSA
  15071. case RSAk:
  15072. #ifdef WC_RSA_PSS
  15073. case RSAPSSk:
  15074. if (sigOID == RSAPSSk) {
  15075. /* TODO: pkCbRsaPss - RSA PSS callback. */
  15076. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  15077. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  15078. sigCtx->saltLen, sigCtx->key.rsa);
  15079. }
  15080. else
  15081. #endif
  15082. {
  15083. #if defined(HAVE_PK_CALLBACKS)
  15084. if (sigCtx->pkCbRsa) {
  15085. ret = sigCtx->pkCbRsa(
  15086. sigCtx->sigCpy, sigSz, &sigCtx->out,
  15087. key, keySz,
  15088. sigCtx->pkCtxRsa);
  15089. }
  15090. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  15091. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15092. else
  15093. #else
  15094. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  15095. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  15096. #endif /* HAVE_PK_CALLBACKS */
  15097. {
  15098. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  15099. &sigCtx->out, sigCtx->key.rsa);
  15100. }
  15101. }
  15102. break;
  15103. #endif /* !NO_RSA */
  15104. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15105. case DSAk:
  15106. {
  15107. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  15108. sigCtx->key.dsa, &sigCtx->verify);
  15109. break;
  15110. }
  15111. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15112. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15113. case SM2k:
  15114. {
  15115. /* OpenSSL creates signature without CERT_SIG_ID. */
  15116. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID, 0, buf, bufSz,
  15117. WC_HASH_TYPE_SM3, sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15118. sigCtx->key.ecc);
  15119. if (ret == 0) {
  15120. sigCtx->typeH = SM3h;
  15121. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15122. }
  15123. else {
  15124. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15125. WOLFSSL_ERROR_VERBOSE(ret);
  15126. goto exit_cs;
  15127. }
  15128. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15129. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15130. break;
  15131. }
  15132. #endif
  15133. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  15134. case ECDSAk:
  15135. {
  15136. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15137. if (sigOID == CTC_SM3wSM2) {
  15138. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID,
  15139. CERT_SIG_ID_SZ, buf, bufSz, WC_HASH_TYPE_SM3,
  15140. sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15141. sigCtx->key.ecc);
  15142. if (ret == 0) {
  15143. sigCtx->typeH = SM3h;
  15144. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15145. }
  15146. else {
  15147. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15148. WOLFSSL_ERROR_VERBOSE(ret);
  15149. goto exit_cs;
  15150. }
  15151. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15152. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15153. }
  15154. else
  15155. #endif
  15156. #if defined(HAVE_PK_CALLBACKS)
  15157. if (sigCtx->pkCbEcc) {
  15158. ret = sigCtx->pkCbEcc(
  15159. sig, sigSz,
  15160. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  15161. key, keySz, &sigCtx->verify,
  15162. sigCtx->pkCtxEcc);
  15163. }
  15164. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  15165. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15166. else
  15167. #else
  15168. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  15169. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  15170. #endif /* HAVE_PK_CALLBACKS */
  15171. {
  15172. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  15173. (word32)sigCtx->digestSz, &sigCtx->verify,
  15174. sigCtx->key.ecc);
  15175. }
  15176. break;
  15177. }
  15178. #endif /* HAVE_ECC */
  15179. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  15180. case ED25519k:
  15181. {
  15182. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  15183. &sigCtx->verify, sigCtx->key.ed25519);
  15184. break;
  15185. }
  15186. #endif
  15187. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  15188. case ED448k:
  15189. {
  15190. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  15191. &sigCtx->verify, sigCtx->key.ed448,
  15192. NULL, 0);
  15193. break;
  15194. }
  15195. #endif
  15196. #if defined(HAVE_PQC)
  15197. #if defined(HAVE_FALCON)
  15198. case FALCON_LEVEL1k:
  15199. case FALCON_LEVEL5k:
  15200. {
  15201. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  15202. &sigCtx->verify,
  15203. sigCtx->key.falcon);
  15204. break;
  15205. }
  15206. #endif /* HAVE_FALCON */
  15207. #if defined(HAVE_DILITHIUM)
  15208. case DILITHIUM_LEVEL2k:
  15209. case DILITHIUM_LEVEL3k:
  15210. case DILITHIUM_LEVEL5k:
  15211. {
  15212. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  15213. &sigCtx->verify,
  15214. sigCtx->key.dilithium);
  15215. break;
  15216. }
  15217. #endif /* HAVE_DILITHIUM */
  15218. #if defined(HAVE_SPHINCS)
  15219. case SPHINCS_FAST_LEVEL1k:
  15220. case SPHINCS_FAST_LEVEL3k:
  15221. case SPHINCS_FAST_LEVEL5k:
  15222. case SPHINCS_SMALL_LEVEL1k:
  15223. case SPHINCS_SMALL_LEVEL3k:
  15224. case SPHINCS_SMALL_LEVEL5k:
  15225. {
  15226. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  15227. &sigCtx->verify,
  15228. sigCtx->key.sphincs);
  15229. break;
  15230. }
  15231. #endif /* HAVE_SPHINCS */
  15232. #endif /* HAVE_PQC */
  15233. default:
  15234. break;
  15235. } /* switch (keyOID) */
  15236. #ifdef WOLFSSL_ASYNC_CRYPT
  15237. if (ret == WC_PENDING_E) {
  15238. goto exit_cs;
  15239. }
  15240. #endif
  15241. if (ret < 0) {
  15242. /* treat all errors as ASN_SIG_CONFIRM_E */
  15243. ret = ASN_SIG_CONFIRM_E;
  15244. WOLFSSL_ERROR_VERBOSE(ret);
  15245. goto exit_cs;
  15246. }
  15247. sigCtx->state = SIG_STATE_CHECK;
  15248. } /* SIG_STATE_DO */
  15249. FALL_THROUGH;
  15250. case SIG_STATE_CHECK:
  15251. {
  15252. switch (keyOID) {
  15253. #ifndef NO_RSA
  15254. case RSAk:
  15255. #ifdef WC_RSA_PSS
  15256. case RSAPSSk:
  15257. if (sigOID == RSAPSSk) {
  15258. #if (defined(HAVE_SELFTEST) && \
  15259. (!defined(HAVE_SELFTEST_VERSION) || \
  15260. (HAVE_SELFTEST_VERSION < 2))) || \
  15261. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15262. (HAVE_FIPS_VERSION < 2))
  15263. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15264. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15265. sigCtx->saltLen);
  15266. #elif (defined(HAVE_SELFTEST) && \
  15267. (HAVE_SELFTEST_VERSION == 2)) || \
  15268. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15269. (HAVE_FIPS_VERSION == 2))
  15270. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15271. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15272. sigCtx->saltLen, 0);
  15273. #else
  15274. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  15275. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  15276. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  15277. sigCtx->heap);
  15278. #endif
  15279. break;
  15280. }
  15281. else
  15282. #endif
  15283. {
  15284. int encodedSigSz, verifySz;
  15285. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  15286. defined(WOLFSSL_RENESAS_SCEPROTECT)
  15287. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  15288. #endif
  15289. #ifdef WOLFSSL_SMALL_STACK
  15290. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  15291. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15292. if (encodedSig == NULL) {
  15293. ERROR_OUT(MEMORY_E, exit_cs);
  15294. }
  15295. #else
  15296. byte encodedSig[MAX_ENCODED_SIG_SZ];
  15297. #endif
  15298. verifySz = ret;
  15299. /* make sure we're right justified */
  15300. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  15301. sigCtx->digest, (word32)sigCtx->digestSz,
  15302. sigCtx->typeH);
  15303. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  15304. XMEMCMP(sigCtx->out, encodedSig,
  15305. (size_t)encodedSigSz) == 0) {
  15306. ret = 0;
  15307. }
  15308. else {
  15309. WOLFSSL_MSG("RSA SSL verify match encode error");
  15310. ret = ASN_SIG_CONFIRM_E;
  15311. WOLFSSL_ERROR_VERBOSE(ret);
  15312. }
  15313. #ifdef WOLFSSL_SMALL_STACK
  15314. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15315. #endif
  15316. break;
  15317. }
  15318. #endif /* NO_RSA */
  15319. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15320. case DSAk:
  15321. {
  15322. if (sigCtx->verify == 1) {
  15323. ret = 0;
  15324. }
  15325. else {
  15326. WOLFSSL_MSG("DSA Verify didn't match");
  15327. ret = ASN_SIG_CONFIRM_E;
  15328. WOLFSSL_ERROR_VERBOSE(ret);
  15329. }
  15330. break;
  15331. }
  15332. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15333. #ifdef HAVE_ECC
  15334. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15335. case SM2k:
  15336. #endif
  15337. case ECDSAk:
  15338. {
  15339. if (sigCtx->verify == 1) {
  15340. ret = 0;
  15341. }
  15342. else {
  15343. WOLFSSL_MSG("ECC Verify didn't match");
  15344. ret = ASN_SIG_CONFIRM_E;
  15345. WOLFSSL_ERROR_VERBOSE(ret);
  15346. }
  15347. break;
  15348. }
  15349. #endif /* HAVE_ECC */
  15350. #ifdef HAVE_ED25519
  15351. case ED25519k:
  15352. {
  15353. if (sigCtx->verify == 1) {
  15354. ret = 0;
  15355. }
  15356. else {
  15357. WOLFSSL_MSG("ED25519 Verify didn't match");
  15358. ret = ASN_SIG_CONFIRM_E;
  15359. WOLFSSL_ERROR_VERBOSE(ret);
  15360. }
  15361. break;
  15362. }
  15363. #endif /* HAVE_ED25519 */
  15364. #ifdef HAVE_ED448
  15365. case ED448k:
  15366. {
  15367. if (sigCtx->verify == 1) {
  15368. ret = 0;
  15369. }
  15370. else {
  15371. WOLFSSL_MSG("ED448 Verify didn't match");
  15372. ret = ASN_SIG_CONFIRM_E;
  15373. WOLFSSL_ERROR_VERBOSE(ret);
  15374. }
  15375. break;
  15376. }
  15377. #endif /* HAVE_ED448 */
  15378. #ifdef HAVE_PQC
  15379. #ifdef HAVE_FALCON
  15380. case FALCON_LEVEL1k:
  15381. {
  15382. if (sigCtx->verify == 1) {
  15383. ret = 0;
  15384. }
  15385. else {
  15386. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  15387. ret = ASN_SIG_CONFIRM_E;
  15388. WOLFSSL_ERROR_VERBOSE(ret);
  15389. }
  15390. break;
  15391. }
  15392. case FALCON_LEVEL5k:
  15393. {
  15394. if (sigCtx->verify == 1) {
  15395. ret = 0;
  15396. }
  15397. else {
  15398. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  15399. ret = ASN_SIG_CONFIRM_E;
  15400. WOLFSSL_ERROR_VERBOSE(ret);
  15401. }
  15402. break;
  15403. }
  15404. #endif /* HAVE_FALCON */
  15405. #ifdef HAVE_DILITHIUM
  15406. case DILITHIUM_LEVEL2k:
  15407. {
  15408. if (sigCtx->verify == 1) {
  15409. ret = 0;
  15410. }
  15411. else {
  15412. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  15413. ret = ASN_SIG_CONFIRM_E;
  15414. }
  15415. break;
  15416. }
  15417. case DILITHIUM_LEVEL3k:
  15418. {
  15419. if (sigCtx->verify == 1) {
  15420. ret = 0;
  15421. }
  15422. else {
  15423. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  15424. ret = ASN_SIG_CONFIRM_E;
  15425. }
  15426. break;
  15427. }
  15428. case DILITHIUM_LEVEL5k:
  15429. {
  15430. if (sigCtx->verify == 1) {
  15431. ret = 0;
  15432. }
  15433. else {
  15434. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  15435. ret = ASN_SIG_CONFIRM_E;
  15436. }
  15437. break;
  15438. }
  15439. #endif /* HAVE_DILITHIUM */
  15440. #ifdef HAVE_SPHINCS
  15441. case SPHINCS_FAST_LEVEL1k:
  15442. {
  15443. if (sigCtx->verify == 1) {
  15444. ret = 0;
  15445. }
  15446. else {
  15447. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  15448. ret = ASN_SIG_CONFIRM_E;
  15449. }
  15450. break;
  15451. }
  15452. case SPHINCS_FAST_LEVEL3k:
  15453. {
  15454. if (sigCtx->verify == 1) {
  15455. ret = 0;
  15456. }
  15457. else {
  15458. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  15459. ret = ASN_SIG_CONFIRM_E;
  15460. }
  15461. break;
  15462. }
  15463. case SPHINCS_FAST_LEVEL5k:
  15464. {
  15465. if (sigCtx->verify == 1) {
  15466. ret = 0;
  15467. }
  15468. else {
  15469. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  15470. ret = ASN_SIG_CONFIRM_E;
  15471. }
  15472. break;
  15473. }
  15474. case SPHINCS_SMALL_LEVEL1k:
  15475. {
  15476. if (sigCtx->verify == 1) {
  15477. ret = 0;
  15478. }
  15479. else {
  15480. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  15481. ret = ASN_SIG_CONFIRM_E;
  15482. }
  15483. break;
  15484. }
  15485. case SPHINCS_SMALL_LEVEL3k:
  15486. {
  15487. if (sigCtx->verify == 1) {
  15488. ret = 0;
  15489. }
  15490. else {
  15491. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  15492. ret = ASN_SIG_CONFIRM_E;
  15493. }
  15494. break;
  15495. }
  15496. case SPHINCS_SMALL_LEVEL5k:
  15497. {
  15498. if (sigCtx->verify == 1) {
  15499. ret = 0;
  15500. }
  15501. else {
  15502. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  15503. ret = ASN_SIG_CONFIRM_E;
  15504. }
  15505. break;
  15506. }
  15507. #endif /* HAVE_SPHINCS */
  15508. #endif /* HAVE_PQC */
  15509. default:
  15510. break;
  15511. } /* switch (keyOID) */
  15512. break;
  15513. } /* SIG_STATE_CHECK */
  15514. default:
  15515. break;
  15516. } /* switch (sigCtx->state) */
  15517. exit_cs:
  15518. #endif /* !NO_ASN_CRYPT */
  15519. (void)keyOID;
  15520. (void)sigOID;
  15521. WOLFSSL_LEAVE("ConfirmSignature", ret);
  15522. #ifdef WOLFSSL_ASYNC_CRYPT
  15523. if (ret == WC_PENDING_E)
  15524. return ret;
  15525. #endif
  15526. FreeSignatureCtx(sigCtx);
  15527. return ret;
  15528. }
  15529. #ifndef IGNORE_NAME_CONSTRAINTS
  15530. static int MatchBaseName(int type, const char* name, int nameSz,
  15531. const char* base, int baseSz)
  15532. {
  15533. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  15534. name[0] == '.' || nameSz < baseSz ||
  15535. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  15536. type != ASN_DIR_TYPE)) {
  15537. return 0;
  15538. }
  15539. if (type == ASN_DIR_TYPE)
  15540. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  15541. /* If an email type, handle special cases where the base is only
  15542. * a domain, or is an email address itself. */
  15543. if (type == ASN_RFC822_TYPE) {
  15544. const char* p = NULL;
  15545. int count = 0;
  15546. if (base[0] != '.') {
  15547. p = base;
  15548. count = 0;
  15549. /* find the '@' in the base */
  15550. while (*p != '@' && count < baseSz) {
  15551. count++;
  15552. p++;
  15553. }
  15554. /* No '@' in base, reset p to NULL */
  15555. if (count >= baseSz)
  15556. p = NULL;
  15557. }
  15558. if (p == NULL) {
  15559. /* Base isn't an email address, it is a domain name,
  15560. * wind the name forward one character past its '@'. */
  15561. p = name;
  15562. count = 0;
  15563. while (*p != '@' && count < baseSz) {
  15564. count++;
  15565. p++;
  15566. }
  15567. if (count < baseSz && *p == '@') {
  15568. name = p + 1;
  15569. nameSz -= count + 1;
  15570. }
  15571. }
  15572. }
  15573. /* RFC 5280 section 4.2.1.10
  15574. * "...Any DNS name that can be constructed by simply adding zero or more
  15575. * labels to the left-hand side of the name satisfies the name constraint."
  15576. * i.e www.host.example.com works for host.example.com name constraint and
  15577. * host1.example.com does not. */
  15578. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  15579. int szAdjust = nameSz - baseSz;
  15580. name += szAdjust;
  15581. nameSz -= szAdjust;
  15582. }
  15583. while (nameSz > 0) {
  15584. if (XTOLOWER((unsigned char)*name++) !=
  15585. XTOLOWER((unsigned char)*base++))
  15586. return 0;
  15587. nameSz--;
  15588. }
  15589. return 1;
  15590. }
  15591. /* Search through the list to find if the name is permitted.
  15592. * name The DNS name to search for
  15593. * dnsList The list to search through
  15594. * nameType Type of DNS name to currently searching
  15595. * return 1 if found in list or if not needed
  15596. * return 0 if not found in the list but is needed
  15597. */
  15598. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15599. {
  15600. Base_entry* current = dnsList;
  15601. int match = 0;
  15602. int need = 0;
  15603. int ret = 1; /* is ok unless needed and no match found */
  15604. while (current != NULL) {
  15605. if (current->type == nameType) {
  15606. need = 1; /* restriction on permitted names is set for this type */
  15607. if (name->len >= current->nameSz &&
  15608. MatchBaseName(nameType, name->name, name->len,
  15609. current->name, current->nameSz)) {
  15610. match = 1; /* found the current name in the permitted list*/
  15611. break;
  15612. }
  15613. }
  15614. current = current->next;
  15615. }
  15616. /* check if permitted name restriction was set and no matching name found */
  15617. if (need && !match)
  15618. ret = 0;
  15619. return ret;
  15620. }
  15621. /* Search through the list to find if the name is excluded.
  15622. * name The DNS name to search for
  15623. * dnsList The list to search through
  15624. * nameType Type of DNS name to currently searching
  15625. * return 1 if found in list and 0 if not found in the list
  15626. */
  15627. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15628. {
  15629. int ret = 0; /* default of not found in the list */
  15630. Base_entry* current = dnsList;
  15631. while (current != NULL) {
  15632. if (current->type == nameType) {
  15633. if (name->len >= current->nameSz &&
  15634. MatchBaseName(nameType, name->name, name->len,
  15635. current->name, current->nameSz)) {
  15636. ret = 1;
  15637. break;
  15638. }
  15639. }
  15640. current = current->next;
  15641. }
  15642. return ret;
  15643. }
  15644. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15645. {
  15646. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15647. int i;
  15648. if (signer == NULL || cert == NULL)
  15649. return 0;
  15650. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15651. return 1;
  15652. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15653. byte nameType = nameTypes[i];
  15654. DNS_entry* name = NULL;
  15655. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15656. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15657. switch (nameType) {
  15658. case ASN_DNS_TYPE:
  15659. /* Should it also consider CN in subject? It could use
  15660. * subjectDnsName too */
  15661. name = cert->altNames;
  15662. break;
  15663. case ASN_RFC822_TYPE:
  15664. /* Shouldn't it validade E= in subject as well? */
  15665. name = cert->altEmailNames;
  15666. /* Add subject email for checking. */
  15667. if (cert->subjectEmail != NULL) {
  15668. /* RFC 5280 section 4.2.1.10
  15669. * "When constraints are imposed on the rfc822Name name
  15670. * form, but the certificate does not include a subject
  15671. * alternative name, the rfc822Name constraint MUST be
  15672. * applied to the attribute of type emailAddress in the
  15673. * subject distinguished name" */
  15674. subjectDnsName.next = NULL;
  15675. subjectDnsName.type = ASN_RFC822_TYPE;
  15676. subjectDnsName.len = cert->subjectEmailLen;
  15677. subjectDnsName.name = (char *)cert->subjectEmail;
  15678. }
  15679. break;
  15680. case ASN_DIR_TYPE:
  15681. #ifndef WOLFSSL_NO_ASN_STRICT
  15682. name = cert->altDirNames;
  15683. #endif
  15684. /* RFC 5280 section 4.2.1.10
  15685. "Restrictions of the form directoryName MUST be
  15686. applied to the subject field .... and to any names
  15687. of type directoryName in the subjectAltName
  15688. extension"
  15689. */
  15690. if (cert->subjectRaw != NULL) {
  15691. subjectDnsName.next = NULL;
  15692. subjectDnsName.type = ASN_DIR_TYPE;
  15693. subjectDnsName.len = cert->subjectRawLen;
  15694. subjectDnsName.name = (char *)cert->subjectRaw;
  15695. }
  15696. break;
  15697. default:
  15698. /* Other types of names are ignored for now.
  15699. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15700. * and signer->extNameConstraintCrit is set? */
  15701. return 0;
  15702. }
  15703. while (name != NULL) {
  15704. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15705. WOLFSSL_MSG("Excluded name was found!");
  15706. return 0;
  15707. }
  15708. /* Check against the permitted list */
  15709. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15710. WOLFSSL_MSG("Permitted name was not found!");
  15711. return 0;
  15712. }
  15713. name = name->next;
  15714. }
  15715. /* handle comparing against subject name too */
  15716. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15717. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15718. nameType) == 1) {
  15719. WOLFSSL_MSG("Excluded name was found!");
  15720. return 0;
  15721. }
  15722. /* Check against the permitted list */
  15723. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15724. nameType) != 1) {
  15725. WOLFSSL_MSG("Permitted name was not found!");
  15726. return 0;
  15727. }
  15728. }
  15729. }
  15730. return 1;
  15731. }
  15732. #endif /* IGNORE_NAME_CONSTRAINTS */
  15733. #ifndef WOLFSSL_ASN_TEMPLATE
  15734. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15735. {
  15736. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15737. dnsEntry->next = NULL;
  15738. if (cert->altNames == NULL) {
  15739. /* First on list */
  15740. cert->altNames = dnsEntry;
  15741. }
  15742. else {
  15743. DNS_entry* temp = cert->altNames;
  15744. /* Find end */
  15745. for (; (temp->next != NULL); temp = temp->next);
  15746. /* Add to end */
  15747. temp->next = dnsEntry;
  15748. }
  15749. #else
  15750. dnsEntry->next = cert->altNames;
  15751. cert->altNames = dnsEntry;
  15752. #endif
  15753. }
  15754. #endif
  15755. #ifdef WOLFSSL_ASN_TEMPLATE
  15756. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15757. /* ASN.1 template for OtherName of an X.509 certificate.
  15758. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15759. * HW Name: RFC 4108, 5 - Hardware Module Name
  15760. * Only support HW Name where the type is a HW serial number.
  15761. *
  15762. * Other Names handled for FPKI (Federal PKI) use:
  15763. * UPN (Universal Principal Name), a non-standard Other Name
  15764. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15765. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15766. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15767. */
  15768. static const ASNItem otherNameASN[] = {
  15769. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15770. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15771. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15772. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15773. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15774. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15775. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15776. };
  15777. enum {
  15778. OTHERNAMEASN_IDX_TYPEID = 0,
  15779. OTHERNAMEASN_IDX_VALUE,
  15780. OTHERNAMEASN_IDX_UPN,
  15781. OTHERNAMEASN_IDX_FASCN,
  15782. OTHERNAMEASN_IDX_HWN_SEQ,
  15783. OTHERNAMEASN_IDX_HWN_TYPE,
  15784. OTHERNAMEASN_IDX_HWN_NUM
  15785. };
  15786. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15787. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15788. #ifdef WOLFSSL_SEP
  15789. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15790. {
  15791. int ret = 0;
  15792. word32 oidLen, serialLen;
  15793. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15794. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15795. /* Allocate space for HW type OID. */
  15796. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15797. DYNAMIC_TYPE_X509_EXT);
  15798. if (cert->hwType == NULL)
  15799. ret = MEMORY_E;
  15800. if (ret == 0) {
  15801. /* Copy, into cert HW type OID */
  15802. XMEMCPY(cert->hwType,
  15803. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15804. cert->hwTypeSz = (int)oidLen;
  15805. /* TODO: check this is the HW serial number OID - no test data. */
  15806. /* Allocate space for HW serial number, +1 for null terminator. */
  15807. cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
  15808. DYNAMIC_TYPE_X509_EXT);
  15809. if (cert->hwSerialNum == NULL) {
  15810. WOLFSSL_MSG("\tOut of Memory");
  15811. ret = MEMORY_E;
  15812. }
  15813. }
  15814. if (ret == 0) {
  15815. /* Copy into cert HW serial number. */
  15816. XMEMCPY(cert->hwSerialNum,
  15817. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15818. cert->hwSerialNum[serialLen] = '\0';
  15819. cert->hwSerialNumSz = (int)serialLen;
  15820. }
  15821. return ret;
  15822. }
  15823. #endif /* WOLFSSL_SEP */
  15824. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  15825. {
  15826. DNS_entry* entry = NULL;
  15827. int ret = 0;
  15828. word32 bufLen = 0;
  15829. const char* buf = NULL;
  15830. switch (oid) {
  15831. #ifdef WOLFSSL_FPKI
  15832. case FASCN_OID:
  15833. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  15834. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  15835. break;
  15836. #endif /* WOLFSSL_FPKI */
  15837. case UPN_OID:
  15838. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  15839. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  15840. break;
  15841. default:
  15842. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  15843. ret = ASN_UNKNOWN_OID_E;
  15844. break;
  15845. }
  15846. if (ret == 0) {
  15847. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  15848. if (ret == 0) {
  15849. #ifdef WOLFSSL_FPKI
  15850. entry->oidSum = oid;
  15851. #endif
  15852. AddDNSEntryToList(&cert->altNames, entry);
  15853. }
  15854. }
  15855. return ret;
  15856. }
  15857. /* Decode data with OtherName format from after implicit SEQUENCE.
  15858. *
  15859. * @param [in, out] cert Certificate object.
  15860. * @param [in] input Buffer containing encoded OtherName.
  15861. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15862. * On out, index after OtherName.
  15863. * @param [in] maxIdx Maximum index of data in buffer.
  15864. * @return 0 on success.
  15865. * @return MEMORY_E on dynamic memory allocation failure.
  15866. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15867. * is invalid.
  15868. * @return ASN_PARSE_E when OID does is not HW Name.
  15869. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15870. * @return BUFFER_E when data in buffer is too small.
  15871. */
  15872. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  15873. word32* inOutIdx, word32 maxIdx)
  15874. {
  15875. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  15876. int ret = 0;
  15877. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  15878. if (ret == 0) {
  15879. /* Check the first OID is a recognized Alt Cert Name type. */
  15880. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  15881. /* Parse OtherName. */
  15882. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  15883. inOutIdx, maxIdx);
  15884. }
  15885. if (ret == 0) {
  15886. /* Ensure expected OID. */
  15887. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  15888. #ifdef WOLFSSL_SEP
  15889. case HW_NAME_OID:
  15890. /* Only support HW serial number. */
  15891. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  15892. ret = DecodeSEP(dataASN, cert);
  15893. break;
  15894. #endif /* WOLFSSL_SEP */
  15895. #ifdef WOLFSSL_FPKI
  15896. case FASCN_OID:
  15897. #endif /* WOLFSSL_FPKI */
  15898. case UPN_OID:
  15899. ret = DecodeOtherHelper(dataASN, cert,
  15900. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  15901. break;
  15902. default:
  15903. WOLFSSL_MSG("\tunsupported OID skipping");
  15904. break;
  15905. }
  15906. }
  15907. FREE_ASNGETDATA(dataASN, cert->heap);
  15908. return ret;
  15909. }
  15910. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  15911. /* Decode a GeneralName.
  15912. *
  15913. * @param [in] input Buffer containing encoded OtherName.
  15914. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15915. * On out, index after OtherName.
  15916. * @param [in] len Length of data in buffer.
  15917. * @param [in] cert Decoded certificate object.
  15918. * @return 0 on success.
  15919. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15920. * is invalid.
  15921. * @return BUFFER_E when data in buffer is too small.
  15922. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15923. * @return MEMORY_E when dynamic memory allocation fails.
  15924. */
  15925. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  15926. int len, DecodedCert* cert)
  15927. {
  15928. int ret = 0;
  15929. word32 idx = *inOutIdx;
  15930. /* GeneralName choice: dnsName */
  15931. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15932. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  15933. &cert->altNames);
  15934. if (ret == 0) {
  15935. idx += (word32)len;
  15936. }
  15937. }
  15938. #ifndef IGNORE_NAME_CONSTRAINTS
  15939. /* GeneralName choice: directoryName */
  15940. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15941. int strLen;
  15942. word32 idxDir = idx;
  15943. /* Expecting a SEQUENCE using up all data. */
  15944. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  15945. {
  15946. WOLFSSL_MSG("\tfail: seq length");
  15947. return ASN_PARSE_E;
  15948. }
  15949. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  15950. ASN_DIR_TYPE, &cert->altDirNames);
  15951. if (ret == 0) {
  15952. idx += (word32)len;
  15953. }
  15954. }
  15955. /* GeneralName choice: rfc822Name */
  15956. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15957. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  15958. ASN_RFC822_TYPE, &cert->altEmailNames);
  15959. if (ret == 0) {
  15960. idx += (word32)len;
  15961. }
  15962. }
  15963. /* GeneralName choice: uniformResourceIdentifier */
  15964. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15965. WOLFSSL_MSG("\tPutting URI into list but not using");
  15966. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15967. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15968. "The name MUST NOT be a relative URI"
  15969. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15970. a scheme and hier-part. So the only strict requirement is a ':'
  15971. being present after the scheme. If a '/' is present as part of the
  15972. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15973. {
  15974. int i;
  15975. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15976. for (i = 0; i < len; i++) {
  15977. if (input[idx + (word32)i] == ':') {
  15978. break;
  15979. }
  15980. if (input[idx + (word32)i] == '/') {
  15981. i = len; /* error, found relative path since '/' was
  15982. * encountered before ':'. Returning error
  15983. * value in next if statement. */
  15984. }
  15985. }
  15986. /* test hier-part is empty */
  15987. if (i == 0 || i == len) {
  15988. WOLFSSL_MSG("\tEmpty or malformed URI");
  15989. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15990. return ASN_ALT_NAME_E;
  15991. }
  15992. /* test if scheme is missing */
  15993. if (input[idx + (word32)i] != ':') {
  15994. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15995. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15996. return ASN_ALT_NAME_E;
  15997. }
  15998. }
  15999. #endif
  16000. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  16001. &cert->altNames);
  16002. if (ret == 0) {
  16003. idx += (word32)len;
  16004. }
  16005. }
  16006. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  16007. defined(WOLFSSL_IP_ALT_NAME)
  16008. /* GeneralName choice: iPAddress */
  16009. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16010. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  16011. &cert->altNames);
  16012. if (ret == 0) {
  16013. idx += (word32)len;
  16014. }
  16015. }
  16016. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16017. #endif /* IGNORE_NAME_CONSTRAINTS */
  16018. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  16019. /* GeneralName choice: otherName */
  16020. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16021. /* TODO: test data for code path */
  16022. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  16023. }
  16024. #endif
  16025. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  16026. * registeredID */
  16027. else {
  16028. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16029. idx += (word32)len;
  16030. }
  16031. if (ret == 0) {
  16032. /* Return index of next encoded byte. */
  16033. *inOutIdx = idx;
  16034. }
  16035. return ret;
  16036. }
  16037. /* ASN.1 choices for GeneralName.
  16038. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16039. */
  16040. static const byte generalNameChoice[] = {
  16041. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  16042. ASN_CONTEXT_SPECIFIC | 1,
  16043. ASN_CONTEXT_SPECIFIC | 2,
  16044. ASN_CONTEXT_SPECIFIC | 3,
  16045. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  16046. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  16047. ASN_CONTEXT_SPECIFIC | 6,
  16048. ASN_CONTEXT_SPECIFIC | 7,
  16049. ASN_CONTEXT_SPECIFIC | 8,
  16050. 0
  16051. };
  16052. /* ASN.1 template for GeneralName.
  16053. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16054. */
  16055. static const ASNItem altNameASN[] = {
  16056. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  16057. };
  16058. enum {
  16059. ALTNAMEASN_IDX_GN = 0
  16060. };
  16061. /* Number of items in ASN.1 template for GeneralName. */
  16062. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  16063. #endif /* WOLFSSL_ASN_TEMPLATE */
  16064. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  16065. /* return 0 on success */
  16066. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  16067. word32* idxIn, word32 sz)
  16068. {
  16069. word32 idx = *idxIn;
  16070. int strLen;
  16071. int ret;
  16072. byte tag;
  16073. /* Certificates issued with this OID in the subject alt name are for
  16074. * verifying signatures created on a module.
  16075. * RFC 4108 Section 5. */
  16076. if (cert->hwType != NULL) {
  16077. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  16078. return ASN_PARSE_E;
  16079. }
  16080. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16081. return ASN_PARSE_E;
  16082. }
  16083. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  16084. WOLFSSL_MSG("\twrong type");
  16085. return ASN_PARSE_E;
  16086. }
  16087. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16088. WOLFSSL_MSG("\tfail: str len");
  16089. return ASN_PARSE_E;
  16090. }
  16091. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16092. WOLFSSL_MSG("\tBad Sequence");
  16093. return ASN_PARSE_E;
  16094. }
  16095. ret = GetASNObjectId(input, &idx, &strLen, sz);
  16096. if (ret != 0) {
  16097. WOLFSSL_MSG("\tbad OID");
  16098. return ret;
  16099. }
  16100. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  16101. DYNAMIC_TYPE_X509_EXT);
  16102. if (cert->hwType == NULL) {
  16103. WOLFSSL_MSG("\tOut of Memory");
  16104. return MEMORY_E;
  16105. }
  16106. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  16107. cert->hwTypeSz = strLen;
  16108. idx += (word32)strLen;
  16109. ret = GetOctetString(input, &idx, &strLen, sz);
  16110. if (ret < 0) {
  16111. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16112. cert->hwType = NULL;
  16113. return ret;
  16114. }
  16115. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  16116. DYNAMIC_TYPE_X509_EXT);
  16117. if (cert->hwSerialNum == NULL) {
  16118. WOLFSSL_MSG("\tOut of Memory");
  16119. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16120. cert->hwType = NULL;
  16121. return MEMORY_E;
  16122. }
  16123. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  16124. cert->hwSerialNum[strLen] = '\0';
  16125. cert->hwSerialNumSz = strLen;
  16126. idx += (word32)strLen;
  16127. *idxIn = idx;
  16128. return 0;
  16129. }
  16130. #endif /* WOLFSSL_SEP */
  16131. #if !defined(WOLFSSL_ASN_TEMPLATE)
  16132. /* return 0 on success */
  16133. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  16134. word32* idx, word32 sz, int oid)
  16135. {
  16136. int ret = 0;
  16137. int strLen = 0;
  16138. byte tag;
  16139. DNS_entry* dnsEntry = NULL;
  16140. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16141. ret = ASN_PARSE_E;
  16142. }
  16143. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  16144. ret = ASN_PARSE_E;
  16145. }
  16146. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16147. ret = ASN_PARSE_E;
  16148. }
  16149. if (ret == 0) {
  16150. dnsEntry = AltNameNew(cert->heap);
  16151. if (dnsEntry == NULL) {
  16152. WOLFSSL_MSG("\tOut of Memory");
  16153. return MEMORY_E;
  16154. }
  16155. switch (oid) {
  16156. #ifdef WOLFSSL_FPKI
  16157. case FASCN_OID:
  16158. ret = GetOctetString(input, idx, &strLen, sz);
  16159. if (ret > 0) {
  16160. ret = 0;
  16161. }
  16162. break;
  16163. #endif /* WOLFSSL_FPKI */
  16164. case UPN_OID:
  16165. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16166. ret = ASN_PARSE_E;
  16167. }
  16168. if (ret == 0 &&
  16169. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16170. tag != ASN_IA5_STRING) {
  16171. WOLFSSL_MSG("Was expecting a string for UPN");
  16172. ret = ASN_PARSE_E;
  16173. }
  16174. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16175. WOLFSSL_MSG("Was expecting a string for UPN");
  16176. ret = ASN_PARSE_E;
  16177. }
  16178. break;
  16179. default:
  16180. WOLFSSL_MSG("Unknown constructed other name, skipping");
  16181. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16182. dnsEntry = NULL;
  16183. }
  16184. }
  16185. if (ret == 0 && dnsEntry != NULL) {
  16186. dnsEntry->type = ASN_OTHER_TYPE;
  16187. dnsEntry->len = strLen;
  16188. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16189. DYNAMIC_TYPE_ALTNAME);
  16190. #ifdef WOLFSSL_FPKI
  16191. dnsEntry->oidSum = oid;
  16192. #endif /* WOLFSSL_FPKI */
  16193. if (dnsEntry->name == NULL) {
  16194. WOLFSSL_MSG("\tOut of Memory");
  16195. ret = MEMORY_E;
  16196. }
  16197. else {
  16198. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  16199. dnsEntry->name[strLen] = '\0';
  16200. AddAltName(cert, dnsEntry);
  16201. }
  16202. }
  16203. if (ret == 0) {
  16204. *idx += (word32)strLen;
  16205. }
  16206. else {
  16207. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16208. }
  16209. return ret;
  16210. }
  16211. #endif
  16212. /* Decode subject alternative names extension.
  16213. *
  16214. * RFC 5280 4.2.1.6. Subject Alternative Name
  16215. *
  16216. * @param [in] input Buffer holding encoded data.
  16217. * @param [in] sz Size of encoded data in bytes.
  16218. * @param [in, out] cert Decoded certificate object.
  16219. * @return 0 on success.
  16220. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16221. * is invalid.
  16222. * @return BUFFER_E when data in buffer is too small.
  16223. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16224. * @return MEMORY_E when dynamic memory allocation fails.
  16225. */
  16226. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  16227. {
  16228. #ifndef WOLFSSL_ASN_TEMPLATE
  16229. word32 idx = 0;
  16230. int length = 0;
  16231. WOLFSSL_ENTER("DecodeAltNames");
  16232. if (GetSequence(input, &idx, &length, sz) < 0) {
  16233. WOLFSSL_MSG("\tBad Sequence");
  16234. return ASN_PARSE_E;
  16235. }
  16236. if (length == 0) {
  16237. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16238. If the subjectAltName extension is present, the sequence MUST
  16239. contain at least one entry. */
  16240. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16241. return ASN_PARSE_E;
  16242. }
  16243. #ifdef OPENSSL_ALL
  16244. cert->extSubjAltNameSrc = input;
  16245. cert->extSubjAltNameSz = sz;
  16246. #endif
  16247. cert->weOwnAltNames = 1;
  16248. while (length > 0) {
  16249. byte current_byte;
  16250. /* Verify idx can't overflow input buffer */
  16251. if (idx >= (word32)sz) {
  16252. WOLFSSL_MSG("\tBad Index");
  16253. return BUFFER_E;
  16254. }
  16255. current_byte = input[idx++];
  16256. length--;
  16257. /* Save DNS Type names in the altNames list. */
  16258. /* Save Other Type names in the cert's OidMap */
  16259. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16260. DNS_entry* dnsEntry;
  16261. int strLen;
  16262. word32 lenStartIdx = idx;
  16263. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16264. WOLFSSL_MSG("\tfail: str length");
  16265. return ASN_PARSE_E;
  16266. }
  16267. length -= (int)(idx - lenStartIdx);
  16268. dnsEntry = AltNameNew(cert->heap);
  16269. if (dnsEntry == NULL) {
  16270. WOLFSSL_MSG("\tOut of Memory");
  16271. return MEMORY_E;
  16272. }
  16273. dnsEntry->type = ASN_DNS_TYPE;
  16274. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16275. DYNAMIC_TYPE_ALTNAME);
  16276. if (dnsEntry->name == NULL) {
  16277. WOLFSSL_MSG("\tOut of Memory");
  16278. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16279. return MEMORY_E;
  16280. }
  16281. dnsEntry->len = strLen;
  16282. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  16283. dnsEntry->name[strLen] = '\0';
  16284. AddAltName(cert, dnsEntry);
  16285. length -= strLen;
  16286. idx += (word32)strLen;
  16287. }
  16288. #ifndef IGNORE_NAME_CONSTRAINTS
  16289. else if (current_byte ==
  16290. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16291. DNS_entry* dirEntry;
  16292. int strLen;
  16293. word32 lenStartIdx = idx;
  16294. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16295. WOLFSSL_MSG("\tfail: str length");
  16296. return ASN_PARSE_E;
  16297. }
  16298. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16299. WOLFSSL_MSG("\tfail: seq length");
  16300. return ASN_PARSE_E;
  16301. }
  16302. length -= (int)(idx - lenStartIdx);
  16303. dirEntry = AltNameNew(cert->heap);
  16304. if (dirEntry == NULL) {
  16305. WOLFSSL_MSG("\tOut of Memory");
  16306. return MEMORY_E;
  16307. }
  16308. dirEntry->type = ASN_DIR_TYPE;
  16309. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16310. DYNAMIC_TYPE_ALTNAME);
  16311. if (dirEntry->name == NULL) {
  16312. WOLFSSL_MSG("\tOut of Memory");
  16313. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16314. return MEMORY_E;
  16315. }
  16316. dirEntry->len = strLen;
  16317. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  16318. dirEntry->name[strLen] = '\0';
  16319. dirEntry->next = cert->altDirNames;
  16320. cert->altDirNames = dirEntry;
  16321. length -= strLen;
  16322. idx += (word32)strLen;
  16323. }
  16324. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16325. DNS_entry* emailEntry;
  16326. int strLen;
  16327. word32 lenStartIdx = idx;
  16328. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16329. WOLFSSL_MSG("\tfail: str length");
  16330. return ASN_PARSE_E;
  16331. }
  16332. length -= (int)(idx - lenStartIdx);
  16333. emailEntry = AltNameNew(cert->heap);
  16334. if (emailEntry == NULL) {
  16335. WOLFSSL_MSG("\tOut of Memory");
  16336. return MEMORY_E;
  16337. }
  16338. emailEntry->type = ASN_RFC822_TYPE;
  16339. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16340. DYNAMIC_TYPE_ALTNAME);
  16341. if (emailEntry->name == NULL) {
  16342. WOLFSSL_MSG("\tOut of Memory");
  16343. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16344. return MEMORY_E;
  16345. }
  16346. emailEntry->len = strLen;
  16347. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  16348. emailEntry->name[strLen] = '\0';
  16349. emailEntry->next = cert->altEmailNames;
  16350. cert->altEmailNames = emailEntry;
  16351. length -= strLen;
  16352. idx += (word32)strLen;
  16353. }
  16354. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16355. DNS_entry* uriEntry;
  16356. int strLen;
  16357. word32 lenStartIdx = idx;
  16358. WOLFSSL_MSG("\tPutting URI into list but not using");
  16359. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16360. WOLFSSL_MSG("\tfail: str length");
  16361. return ASN_PARSE_E;
  16362. }
  16363. length -= (int)(idx - lenStartIdx);
  16364. /* check that strLen at index is not past input buffer */
  16365. if ((word32)strLen + idx > sz) {
  16366. return BUFFER_E;
  16367. }
  16368. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16369. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16370. "The name MUST NOT be a relative URI"
  16371. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16372. a scheme and hier-part. So the only strict requirement is a ':'
  16373. being present after the scheme. If a '/' is present as part of the
  16374. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16375. {
  16376. word32 i;
  16377. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16378. for (i = 0; i < (word32)strLen; i++) {
  16379. if (input[idx + i] == ':') {
  16380. break;
  16381. }
  16382. if (input[idx + i] == '/') {
  16383. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16384. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16385. return ASN_ALT_NAME_E;
  16386. }
  16387. }
  16388. /* test hier-part is empty */
  16389. if (i == 0 || i == (word32)strLen) {
  16390. WOLFSSL_MSG("\tEmpty or malformed URI");
  16391. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16392. return ASN_ALT_NAME_E;
  16393. }
  16394. /* test if scheme is missing */
  16395. if (input[idx + i] != ':') {
  16396. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16397. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16398. return ASN_ALT_NAME_E;
  16399. }
  16400. }
  16401. #endif
  16402. uriEntry = AltNameNew(cert->heap);
  16403. if (uriEntry == NULL) {
  16404. WOLFSSL_MSG("\tOut of Memory");
  16405. return MEMORY_E;
  16406. }
  16407. uriEntry->type = ASN_URI_TYPE;
  16408. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16409. DYNAMIC_TYPE_ALTNAME);
  16410. if (uriEntry->name == NULL) {
  16411. WOLFSSL_MSG("\tOut of Memory");
  16412. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16413. return MEMORY_E;
  16414. }
  16415. uriEntry->len = strLen;
  16416. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  16417. uriEntry->name[strLen] = '\0';
  16418. AddAltName(cert, uriEntry);
  16419. length -= strLen;
  16420. idx += (word32)strLen;
  16421. }
  16422. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16423. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16424. DNS_entry* ipAddr;
  16425. int strLen;
  16426. word32 lenStartIdx = idx;
  16427. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  16428. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16429. WOLFSSL_MSG("\tfail: str length");
  16430. return ASN_PARSE_E;
  16431. }
  16432. length -= (idx - lenStartIdx);
  16433. /* check that strLen at index is not past input buffer */
  16434. if (strLen + idx > sz) {
  16435. return BUFFER_E;
  16436. }
  16437. ipAddr = AltNameNew(cert->heap);
  16438. if (ipAddr == NULL) {
  16439. WOLFSSL_MSG("\tOut of Memory");
  16440. return MEMORY_E;
  16441. }
  16442. ipAddr->type = ASN_IP_TYPE;
  16443. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16444. DYNAMIC_TYPE_ALTNAME);
  16445. if (ipAddr->name == NULL) {
  16446. WOLFSSL_MSG("\tOut of Memory");
  16447. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16448. return MEMORY_E;
  16449. }
  16450. ipAddr->len = strLen;
  16451. XMEMCPY(ipAddr->name, &input[idx], strLen);
  16452. ipAddr->name[strLen] = '\0';
  16453. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16454. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  16455. WOLFSSL_MSG("\tOut of Memory for IP string");
  16456. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16457. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16458. return MEMORY_E;
  16459. }
  16460. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  16461. AddAltName(cert, ipAddr);
  16462. length -= strLen;
  16463. idx += (word32)strLen;
  16464. }
  16465. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16466. #endif /* IGNORE_NAME_CONSTRAINTS */
  16467. else if (current_byte ==
  16468. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16469. int strLen;
  16470. word32 lenStartIdx = idx;
  16471. word32 oid = 0;
  16472. int ret = 0;
  16473. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16474. WOLFSSL_MSG("\tfail: other name length");
  16475. return ASN_PARSE_E;
  16476. }
  16477. /* Consume the rest of this sequence. */
  16478. length -= (int)(((word32)strLen + idx - lenStartIdx));
  16479. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  16480. WOLFSSL_MSG("\tbad OID");
  16481. return ASN_PARSE_E;
  16482. }
  16483. /* handle parsing other type alt names */
  16484. switch (oid) {
  16485. #ifdef WOLFSSL_SEP
  16486. case HW_NAME_OID:
  16487. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  16488. if (ret != 0)
  16489. return ret;
  16490. break;
  16491. #endif /* WOLFSSL_SEP */
  16492. #ifdef WOLFSSL_FPKI
  16493. case FASCN_OID:
  16494. case UPN_OID:
  16495. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  16496. oid);
  16497. if (ret != 0)
  16498. return ret;
  16499. break;
  16500. #endif /* WOLFSSL_FPKI */
  16501. default:
  16502. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  16503. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16504. /* check to skip constructed other names too */
  16505. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  16506. (int)oid) != 0) {
  16507. WOLFSSL_MSG("\tfail: unsupported other name length");
  16508. return ASN_PARSE_E;
  16509. }
  16510. }
  16511. else {
  16512. idx += (word32)strLen;
  16513. }
  16514. }
  16515. (void)ret;
  16516. }
  16517. else {
  16518. int strLen;
  16519. word32 lenStartIdx = idx;
  16520. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16521. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16522. WOLFSSL_MSG("\tfail: unsupported name length");
  16523. return ASN_PARSE_E;
  16524. }
  16525. length -= (int)((word32)strLen + idx - lenStartIdx);
  16526. idx += (word32)strLen;
  16527. }
  16528. }
  16529. return 0;
  16530. #else
  16531. word32 idx = 0;
  16532. int length = 0;
  16533. int ret = 0;
  16534. WOLFSSL_ENTER("DecodeAltNames");
  16535. /* Get SEQUENCE and expect all data to be accounted for. */
  16536. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  16537. WOLFSSL_MSG("\tBad Sequence");
  16538. ret = ASN_PARSE_E;
  16539. }
  16540. if ((ret == 0) && (length == 0)) {
  16541. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16542. If the subjectAltName extension is present, the sequence MUST
  16543. contain at least one entry. */
  16544. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16545. ret = ASN_PARSE_E;
  16546. }
  16547. if (ret == 0) {
  16548. #ifdef OPENSSL_ALL
  16549. cert->extSubjAltNameSrc = input;
  16550. cert->extSubjAltNameSz = sz;
  16551. #endif
  16552. cert->weOwnAltNames = 1;
  16553. if ((word32)length + idx != sz) {
  16554. ret = ASN_PARSE_E;
  16555. }
  16556. }
  16557. while ((ret == 0) && (idx < sz)) {
  16558. ASNGetData dataASN[altNameASN_Length];
  16559. /* Clear dynamic data items. */
  16560. XMEMSET(dataASN, 0, sizeof(dataASN));
  16561. /* Parse GeneralName with the choices supported. */
  16562. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  16563. /* Decode a GeneralName choice. */
  16564. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  16565. &idx, sz);
  16566. if (ret == 0) {
  16567. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  16568. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  16569. }
  16570. }
  16571. return ret;
  16572. #endif
  16573. }
  16574. #ifdef WOLFSSL_ASN_TEMPLATE
  16575. /* ASN.1 template for BasicContraints.
  16576. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16577. */
  16578. static const ASNItem basicConsASN[] = {
  16579. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16580. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  16581. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  16582. };
  16583. enum {
  16584. BASICCONSASN_IDX_SEQ = 0,
  16585. BASICCONSASN_IDX_CA,
  16586. BASICCONSASN_IDX_PLEN
  16587. };
  16588. /* Number of items in ASN.1 template for BasicContraints. */
  16589. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  16590. #endif
  16591. /* Decode basic constraints extension in a certificate.
  16592. *
  16593. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16594. *
  16595. * @param [in] input Buffer holding data.
  16596. * @param [in] sz Size of data in buffer.
  16597. * @param [in, out] cert Certificate object.
  16598. * @return 0 on success.
  16599. * @return MEMORY_E on dynamic memory allocation failure.
  16600. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  16601. * @return ASN_PARSE_E when CA boolean is not present unless
  16602. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  16603. * @return ASN_PARSE_E when path length more than 7 bits.
  16604. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16605. * is invalid.
  16606. * @return BUFFER_E when data in buffer is too small.
  16607. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  16608. * non-zero length.
  16609. */
  16610. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  16611. {
  16612. #ifndef WOLFSSL_ASN_TEMPLATE
  16613. word32 idx = 0;
  16614. int length = 0;
  16615. int ret;
  16616. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  16617. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16618. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16619. return ASN_PARSE_E;
  16620. }
  16621. if (length == 0)
  16622. return 0;
  16623. /* If the basic ca constraint is false, this extension may be named, but
  16624. * left empty. So, if the length is 0, just return. */
  16625. ret = GetBoolean(input, &idx, (word32)sz);
  16626. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  16627. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16628. * When CA Boolean not asserted use the default value "False" */
  16629. if (ret < 0) {
  16630. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16631. ret = 0;
  16632. }
  16633. cert->isCA = ret ? 1 : 0;
  16634. /* If there isn't any more data, return. */
  16635. if (idx >= (word32)sz) {
  16636. return 0;
  16637. }
  16638. ret = GetInteger7Bit(input, &idx, (word32)sz);
  16639. if (ret < 0)
  16640. return ret;
  16641. cert->pathLength = (byte)ret;
  16642. cert->pathLengthSet = 1;
  16643. return 0;
  16644. #else
  16645. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16646. int ret = 0;
  16647. word32 idx = 0;
  16648. byte isCA = 0;
  16649. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16650. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16651. if (ret == 0) {
  16652. /* Get the CA boolean and path length when present. */
  16653. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16654. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16655. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16656. &idx, (word32)sz);
  16657. }
  16658. /* Empty SEQUENCE is OK - nothing to store. */
  16659. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16660. /* Bad encoding when CA Boolean is false
  16661. * (default when not present). */
  16662. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16663. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16664. ret = ASN_PARSE_E;
  16665. }
  16666. /* Path length must be a 7-bit value. */
  16667. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16668. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16669. ret = ASN_PARSE_E;
  16670. }
  16671. if ((ret == 0) && cert->pathLength > WOLFSSL_MAX_PATH_LEN) {
  16672. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_SIZE_E);
  16673. ret = ASN_PATHLEN_SIZE_E;
  16674. }
  16675. /* Store CA boolean and whether a path length was seen. */
  16676. if (ret == 0) {
  16677. /* isCA in certificate is a 1 bit of a byte. */
  16678. cert->isCA = isCA ? 1 : 0;
  16679. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16680. }
  16681. }
  16682. FREE_ASNGETDATA(dataASN, cert->heap);
  16683. return ret;
  16684. #endif
  16685. }
  16686. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16687. {
  16688. word32 idx = 0;
  16689. int length = 0;
  16690. int skipLength = 0;
  16691. int ret;
  16692. byte tag;
  16693. WOLFSSL_ENTER("DecodePolicyConstraints");
  16694. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16695. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16696. return ASN_PARSE_E;
  16697. }
  16698. if (length == 0)
  16699. return ASN_PARSE_E;
  16700. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  16701. WOLFSSL_MSG("\tfail: bad TAG");
  16702. return ASN_PARSE_E;
  16703. }
  16704. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16705. /* requireExplicitPolicy */
  16706. cert->extPolicyConstRxpSet = 1;
  16707. }
  16708. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16709. /* inhibitPolicyMapping */
  16710. cert->extPolicyConstIpmSet = 1;
  16711. }
  16712. else {
  16713. WOLFSSL_MSG("\tfail: invalid TAG");
  16714. return ASN_PARSE_E;
  16715. }
  16716. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  16717. if (ret < 0) {
  16718. WOLFSSL_MSG("\tfail: invalid length");
  16719. return ret;
  16720. }
  16721. if (skipLength > 1) {
  16722. WOLFSSL_MSG("\tfail: skip value too big");
  16723. return BUFFER_E;
  16724. }
  16725. if (idx >= (word32)sz) {
  16726. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16727. return BUFFER_E;
  16728. }
  16729. cert->policyConstSkip = input[idx];
  16730. return 0;
  16731. }
  16732. /* Context-Specific value for: DistributionPoint.distributionPoint
  16733. * From RFC5280 SS4.2.1.13, Distribution Point */
  16734. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16735. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16736. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16737. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16738. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16739. * From RFC3280 SS4.2.1.7, GeneralName */
  16740. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16741. #ifdef WOLFSSL_ASN_TEMPLATE
  16742. /* ASN.1 template for CRL distribution points.
  16743. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16744. */
  16745. static const ASNItem crlDistASN[] = {
  16746. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16747. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16748. /* Distribution point name */
  16749. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16750. /* fullName */
  16751. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16752. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16753. /* nameRelativeToCRLIssuer */
  16754. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16755. /* reasons: IMPLICIT BIT STRING */
  16756. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16757. /* cRLIssuer */
  16758. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16759. };
  16760. enum {
  16761. CRLDISTASN_IDX_SEQ = 0,
  16762. CRLDISTASN_IDX_DP_SEQ,
  16763. CRLDISTASN_IDX_DP_DISTPOINT,
  16764. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16765. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16766. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16767. CRLDISTASN_IDX_DP_REASONS,
  16768. CRLDISTASN_IDX_DP_CRLISSUER
  16769. };
  16770. /* Number of items in ASN.1 template for CRL distribution points. */
  16771. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  16772. #endif
  16773. /* Decode CRL distribution point extension in a certificate.
  16774. *
  16775. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16776. *
  16777. * @param [in] input Buffer holding data.
  16778. * @param [in] sz Size of data in buffer.
  16779. * @param [in, out] cert Certificate object.
  16780. * @return 0 on success.
  16781. * @return MEMORY_E on dynamic memory allocation failure.
  16782. * @return ASN_PARSE_E when invalid bits of reason are set.
  16783. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  16784. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  16785. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16786. * is invalid.
  16787. * @return BUFFER_E when data in buffer is too small.
  16788. */
  16789. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  16790. {
  16791. #ifndef WOLFSSL_ASN_TEMPLATE
  16792. word32 idx = 0, localIdx;
  16793. int length = 0;
  16794. byte tag = 0;
  16795. WOLFSSL_ENTER("DecodeCrlDist");
  16796. cert->extCrlInfoRaw = input;
  16797. cert->extCrlInfoRawSz = (int)sz;
  16798. /* Unwrap the list of Distribution Points*/
  16799. if (GetSequence(input, &idx, &length, sz) < 0)
  16800. return ASN_PARSE_E;
  16801. /* Unwrap a single Distribution Point */
  16802. if (GetSequence(input, &idx, &length, sz) < 0)
  16803. return ASN_PARSE_E;
  16804. /* The Distribution Point has three explicit optional members
  16805. * First check for a DistributionPointName
  16806. */
  16807. localIdx = idx;
  16808. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16809. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  16810. {
  16811. idx++;
  16812. if (GetLength(input, &idx, &length, sz) < 0)
  16813. return ASN_PARSE_E;
  16814. localIdx = idx;
  16815. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16816. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  16817. {
  16818. idx++;
  16819. if (GetLength(input, &idx, &length, sz) < 0)
  16820. return ASN_PARSE_E;
  16821. localIdx = idx;
  16822. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16823. tag == GENERALNAME_URI)
  16824. {
  16825. idx++;
  16826. if (GetLength(input, &idx, &length, sz) < 0)
  16827. return ASN_PARSE_E;
  16828. cert->extCrlInfoSz = length;
  16829. cert->extCrlInfo = input + idx;
  16830. idx += (word32)length;
  16831. }
  16832. else
  16833. /* This isn't a URI, skip it. */
  16834. idx += (word32)length;
  16835. }
  16836. else {
  16837. /* This isn't a FULLNAME, skip it. */
  16838. idx += (word32)length;
  16839. }
  16840. }
  16841. /* Check for reasonFlags */
  16842. localIdx = idx;
  16843. if (idx < (word32)sz &&
  16844. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16845. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  16846. {
  16847. idx++;
  16848. if (GetLength(input, &idx, &length, sz) < 0)
  16849. return ASN_PARSE_E;
  16850. idx += (word32)length;
  16851. }
  16852. /* Check for cRLIssuer */
  16853. localIdx = idx;
  16854. if (idx < (word32)sz &&
  16855. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16856. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  16857. {
  16858. idx++;
  16859. if (GetLength(input, &idx, &length, sz) < 0)
  16860. return ASN_PARSE_E;
  16861. idx += (word32)length;
  16862. }
  16863. if (idx < (word32)sz)
  16864. {
  16865. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16866. "but we only use the first one.");
  16867. }
  16868. return 0;
  16869. #else
  16870. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  16871. word32 idx = 0;
  16872. int ret = 0;
  16873. #ifdef CRLDP_VALIDATE_DATA
  16874. word16 reason;
  16875. #endif
  16876. WOLFSSL_ENTER("DecodeCrlDist");
  16877. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  16878. cert->extCrlInfoRaw = input;
  16879. cert->extCrlInfoRawSz = (int)sz;
  16880. if (ret == 0) {
  16881. /* Get the GeneralName choice */
  16882. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  16883. /* Parse CRL distribtion point. */
  16884. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  16885. &idx, sz);
  16886. }
  16887. if (ret == 0) {
  16888. /* If the choice was a URI, store it in certificate. */
  16889. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  16890. word32 sz32;
  16891. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  16892. &cert->extCrlInfo, &sz32);
  16893. cert->extCrlInfoSz = (int)sz32;
  16894. }
  16895. #ifdef CRLDP_VALIDATE_DATA
  16896. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  16897. /* TODO: test case */
  16898. /* Validate ReasonFlags. */
  16899. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  16900. &reason);
  16901. /* First bit (LSB) unused and eight other bits defined. */
  16902. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  16903. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16904. ret = ASN_PARSE_E;
  16905. }
  16906. }
  16907. #endif
  16908. }
  16909. /* Only parsing the first one. */
  16910. if (ret == 0 && idx < (word32)sz) {
  16911. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16912. "but we only use the first one.");
  16913. }
  16914. /* TODO: validate other points. */
  16915. FREE_ASNGETDATA(dataASN, cert->heap);
  16916. return ret;
  16917. #endif /* WOLFSSL_ASN_TEMPLATE */
  16918. }
  16919. #ifdef WOLFSSL_ASN_TEMPLATE
  16920. /* ASN.1 template for the access description.
  16921. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16922. */
  16923. static const ASNItem accessDescASN[] = {
  16924. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16925. /* accessMethod */
  16926. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  16927. /* accessLocation: GeneralName */
  16928. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16929. };
  16930. enum {
  16931. ACCESSDESCASN_IDX_SEQ = 0,
  16932. ACCESSDESCASN_IDX_METH,
  16933. ACCESSDESCASN_IDX_LOC
  16934. };
  16935. /* Number of items in ASN.1 template for the access description. */
  16936. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  16937. #endif
  16938. /* Decode authority information access extension in a certificate.
  16939. *
  16940. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16941. *
  16942. * @param [in] input Buffer holding data.
  16943. * @param [in] sz Size of data in buffer.
  16944. * @param [in, out] cert Certificate object.
  16945. * @return 0 on success.
  16946. * @return MEMORY_E on dynamic memory allocation failure.
  16947. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16948. * is invalid.
  16949. * @return BUFFER_E when data in buffer is too small.
  16950. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  16951. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16952. */
  16953. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  16954. {
  16955. #ifndef WOLFSSL_ASN_TEMPLATE
  16956. word32 idx = 0;
  16957. int length = 0;
  16958. int count = 0;
  16959. byte b = 0;
  16960. word32 oid;
  16961. WOLFSSL_ENTER("DecodeAuthInfo");
  16962. /* Unwrap the list of AIAs */
  16963. if (GetSequence(input, &idx, &length, sz) < 0)
  16964. return ASN_PARSE_E;
  16965. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16966. /* Unwrap a single AIA */
  16967. if (GetSequence(input, &idx, &length, sz) < 0)
  16968. return ASN_PARSE_E;
  16969. oid = 0;
  16970. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  16971. return ASN_PARSE_E;
  16972. }
  16973. /* Only supporting URIs right now. */
  16974. if (GetASNTag(input, &idx, &b, sz) < 0)
  16975. return ASN_PARSE_E;
  16976. if (GetLength(input, &idx, &length, sz) < 0)
  16977. return ASN_PARSE_E;
  16978. /* Set ocsp entry */
  16979. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  16980. {
  16981. cert->extAuthInfoSz = length;
  16982. cert->extAuthInfo = input + idx;
  16983. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16984. count++;
  16985. #else
  16986. break;
  16987. #endif
  16988. }
  16989. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16990. /* Set CaIssuers entry */
  16991. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  16992. {
  16993. cert->extAuthInfoCaIssuerSz = length;
  16994. cert->extAuthInfoCaIssuer = input + idx;
  16995. count++;
  16996. }
  16997. #endif
  16998. idx += (word32)length;
  16999. }
  17000. return 0;
  17001. #else
  17002. word32 idx = 0;
  17003. int length = 0;
  17004. int count = 0;
  17005. int ret = 0;
  17006. WOLFSSL_ENTER("DecodeAuthInfo");
  17007. /* Unwrap the list of AIAs */
  17008. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17009. ret = ASN_PARSE_E;
  17010. }
  17011. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  17012. ASNGetData dataASN[accessDescASN_Length];
  17013. /* Clear dynamic data and retrieve OID and name. */
  17014. XMEMSET(dataASN, 0, sizeof(dataASN));
  17015. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  17016. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  17017. /* Parse AccessDescription. */
  17018. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  17019. input, &idx, sz);
  17020. if (ret == 0) {
  17021. word32 sz32;
  17022. /* Check we have OCSP and URI. */
  17023. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  17024. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  17025. /* Store URI for OCSP lookup. */
  17026. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17027. &cert->extAuthInfo, &sz32);
  17028. cert->extAuthInfoSz = (int)sz32;
  17029. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17030. count++;
  17031. #else
  17032. break;
  17033. #endif
  17034. }
  17035. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17036. /* Check we have CA Issuer and URI. */
  17037. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  17038. AIA_CA_ISSUER_OID) &&
  17039. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  17040. /* Set CaIssuers entry */
  17041. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17042. &cert->extAuthInfoCaIssuer, &sz32);
  17043. cert->extAuthInfoCaIssuerSz = (int)sz32;
  17044. count++;
  17045. }
  17046. #endif
  17047. /* Otherwise skip. */
  17048. }
  17049. }
  17050. return ret;
  17051. #endif
  17052. }
  17053. #ifdef WOLFSSL_ASN_TEMPLATE
  17054. /* ASN.1 template for AuthorityKeyIdentifier.
  17055. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  17056. */
  17057. static const ASNItem authKeyIdASN[] = {
  17058. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17059. /* keyIdentifier */
  17060. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  17061. /* authorityCertIssuer */
  17062. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  17063. /* authorityCertSerialNumber */
  17064. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  17065. };
  17066. enum {
  17067. AUTHKEYIDASN_IDX_SEQ = 0,
  17068. AUTHKEYIDASN_IDX_KEYID,
  17069. AUTHKEYIDASN_IDX_ISSUER,
  17070. AUTHKEYIDASN_IDX_SERIAL
  17071. };
  17072. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  17073. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  17074. #endif
  17075. /* Decode authority information access extension in a certificate.
  17076. *
  17077. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17078. *
  17079. * @param [in] input Buffer holding data.
  17080. * @param [in] sz Size of data in buffer.
  17081. * @param [in, out] cert Certificate object.
  17082. * @return 0 on success.
  17083. * @return MEMORY_E on dynamic memory allocation failure.
  17084. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17085. * is invalid.
  17086. * @return BUFFER_E when data in buffer is too small.
  17087. */
  17088. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17089. {
  17090. #ifndef WOLFSSL_ASN_TEMPLATE
  17091. word32 idx = 0;
  17092. int length = 0;
  17093. byte tag;
  17094. WOLFSSL_ENTER("DecodeAuthKeyId");
  17095. if (GetSequence(input, &idx, &length, sz) < 0) {
  17096. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17097. return ASN_PARSE_E;
  17098. }
  17099. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  17100. return ASN_PARSE_E;
  17101. }
  17102. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  17103. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  17104. cert->extAuthKeyIdSet = 0;
  17105. return 0;
  17106. }
  17107. if (GetLength(input, &idx, &length, sz) <= 0) {
  17108. WOLFSSL_MSG("\tfail: extension data length");
  17109. return ASN_PARSE_E;
  17110. }
  17111. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17112. #ifdef WOLFSSL_AKID_NAME
  17113. cert->extRawAuthKeyIdSrc = input;
  17114. cert->extRawAuthKeyIdSz = sz;
  17115. #endif
  17116. cert->extAuthKeyIdSrc = &input[idx];
  17117. cert->extAuthKeyIdSz = length;
  17118. #endif /* OPENSSL_EXTRA */
  17119. return GetHashId(input + idx, length, cert->extAuthKeyId,
  17120. HashIdAlg(cert->signatureOID));
  17121. #else
  17122. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  17123. int ret = 0;
  17124. WOLFSSL_ENTER("DecodeAuthKeyId");
  17125. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  17126. if (ret == 0) {
  17127. /* Parse an authority key identifier. */
  17128. word32 idx = 0;
  17129. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  17130. &idx, sz);
  17131. }
  17132. /* Each field is optional */
  17133. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data != NULL) {
  17134. #ifdef OPENSSL_EXTRA
  17135. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID],
  17136. &cert->extAuthKeyIdSrc, &cert->extAuthKeyIdSz);
  17137. #endif /* OPENSSL_EXTRA */
  17138. /* Get the hash or hash of the hash if wrong size. */
  17139. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  17140. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  17141. cert->extAuthKeyId, HashIdAlg((int)cert->signatureOID));
  17142. }
  17143. #ifdef WOLFSSL_AKID_NAME
  17144. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.data != NULL) {
  17145. /* We only support using one (first) name. Parse the name to perform
  17146. * a sanity check. */
  17147. word32 idx = 0;
  17148. ASNGetData nameASN[altNameASN_Length];
  17149. XMEMSET(nameASN, 0, sizeof(nameASN));
  17150. /* Parse GeneralName with the choices supported. */
  17151. GetASN_Choice(&nameASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  17152. /* Decode a GeneralName choice. */
  17153. ret = GetASN_Items(altNameASN, nameASN, altNameASN_Length, 0,
  17154. dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.data, &idx,
  17155. dataASN[AUTHKEYIDASN_IDX_ISSUER].data.ref.length);
  17156. if (ret == 0) {
  17157. GetASN_GetConstRef(&nameASN[ALTNAMEASN_IDX_GN],
  17158. &cert->extAuthKeyIdIssuer, &cert->extAuthKeyIdIssuerSz);
  17159. }
  17160. }
  17161. if (ret == 0 && dataASN[AUTHKEYIDASN_IDX_SERIAL].data.ref.data != NULL) {
  17162. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_SERIAL],
  17163. &cert->extAuthKeyIdIssuerSN, &cert->extAuthKeyIdIssuerSNSz);
  17164. }
  17165. if (ret == 0) {
  17166. if ((cert->extAuthKeyIdIssuerSz > 0) ^
  17167. (cert->extAuthKeyIdIssuerSNSz > 0)) {
  17168. WOLFSSL_MSG("authorityCertIssuer and authorityCertSerialNumber MUST"
  17169. " both be present or both be absent");
  17170. }
  17171. }
  17172. #endif /* WOLFSSL_AKID_NAME */
  17173. if (ret == 0) {
  17174. #if defined(OPENSSL_EXTRA) && defined(WOLFSSL_AKID_NAME)
  17175. /* Store the raw authority key id. */
  17176. cert->extRawAuthKeyIdSrc = input;
  17177. cert->extRawAuthKeyIdSz = sz;
  17178. #endif /* OPENSSL_EXTRA */
  17179. }
  17180. FREE_ASNGETDATA(dataASN, cert->heap);
  17181. return ret;
  17182. #endif /* WOLFSSL_ASN_TEMPLATE */
  17183. }
  17184. /* Decode subject key id extension in a certificate.
  17185. *
  17186. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17187. *
  17188. * @param [in] input Buffer holding data.
  17189. * @param [in] sz Size of data in buffer.
  17190. * @param [in, out] cert Certificate object.
  17191. * @return 0 on success.
  17192. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  17193. * invalid.
  17194. * @return MEMORY_E on dynamic memory allocation failure.
  17195. */
  17196. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17197. {
  17198. word32 idx = 0;
  17199. int length = 0;
  17200. int ret = 0;
  17201. WOLFSSL_ENTER("DecodeSubjKeyId");
  17202. ret = GetOctetString(input, &idx, &length, sz);
  17203. if (ret > 0) {
  17204. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17205. cert->extSubjKeyIdSrc = &input[idx];
  17206. cert->extSubjKeyIdSz = (word32)length;
  17207. #endif /* OPENSSL_EXTRA */
  17208. /* Get the hash or hash of the hash if wrong size. */
  17209. ret = GetHashId(input + idx, length, cert->extSubjKeyId,
  17210. HashIdAlg(cert->signatureOID));
  17211. }
  17212. return ret;
  17213. }
  17214. #ifdef WOLFSSL_ASN_TEMPLATE
  17215. /* ASN.1 template for KeyUsage.
  17216. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17217. */
  17218. static const ASNItem keyUsageASN[] = {
  17219. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  17220. };
  17221. enum {
  17222. KEYUSAGEASN_IDX_STR = 0
  17223. };
  17224. /* Number of items in ASN.1 template for KeyUsage. */
  17225. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  17226. #endif
  17227. /* Decode key usage extension in a certificate.
  17228. *
  17229. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17230. *
  17231. * @param [in] input Buffer holding data.
  17232. * @param [in] sz Size of data in buffer.
  17233. * @param [in, out] cert Certificate object.
  17234. * @return 0 on success.
  17235. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17236. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17237. * is invalid.
  17238. * @return MEMORY_E on dynamic memory allocation failure.
  17239. */
  17240. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17241. {
  17242. #ifndef WOLFSSL_ASN_TEMPLATE
  17243. word32 idx = 0;
  17244. int length;
  17245. int ret;
  17246. WOLFSSL_ENTER("DecodeKeyUsage");
  17247. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  17248. if (ret != 0)
  17249. return ret;
  17250. if (length == 0 || length > 2)
  17251. return ASN_PARSE_E;
  17252. cert->extKeyUsage = (word16)(input[idx]);
  17253. if (length == 2)
  17254. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  17255. return 0;
  17256. #else
  17257. ASNGetData dataASN[keyUsageASN_Length];
  17258. word32 idx = 0;
  17259. WOLFSSL_ENTER("DecodeKeyUsage");
  17260. /* Clear dynamic data and set where to store extended key usage. */
  17261. XMEMSET(dataASN, 0, sizeof(dataASN));
  17262. GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
  17263. /* Parse key usage. */
  17264. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  17265. &idx, sz);
  17266. #endif /* WOLFSSL_ASN_TEMPLATE */
  17267. }
  17268. #ifdef WOLFSSL_ASN_TEMPLATE
  17269. /* ASN.1 template for KeyPurposeId.
  17270. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17271. */
  17272. static const ASNItem keyPurposeIdASN[] = {
  17273. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  17274. };
  17275. enum {
  17276. KEYPURPOSEIDASN_IDX_OID = 0
  17277. };
  17278. /* Number of items in ASN.1 template for KeyPurposeId. */
  17279. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  17280. #endif
  17281. /* Decode extended key usage extension in a certificate.
  17282. *
  17283. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17284. *
  17285. * @param [in] input Buffer holding data.
  17286. * @param [in] sz Size of data in buffer.
  17287. * @param [in, out] cert Certificate object.
  17288. * @return 0 on success.
  17289. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17290. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17291. * is invalid.
  17292. * @return MEMORY_E on dynamic memory allocation failure.
  17293. */
  17294. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17295. {
  17296. #ifndef WOLFSSL_ASN_TEMPLATE
  17297. word32 idx = 0, oid;
  17298. int length, ret;
  17299. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17300. if (GetSequence(input, &idx, &length, sz) < 0) {
  17301. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17302. return ASN_PARSE_E;
  17303. }
  17304. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17305. cert->extExtKeyUsageSrc = input + idx;
  17306. cert->extExtKeyUsageSz = length;
  17307. #endif
  17308. while (idx < (word32)sz) {
  17309. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  17310. if (ret == ASN_UNKNOWN_OID_E)
  17311. continue;
  17312. else if (ret < 0)
  17313. return ret;
  17314. switch (oid) {
  17315. case EKU_ANY_OID:
  17316. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17317. break;
  17318. case EKU_SERVER_AUTH_OID:
  17319. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17320. break;
  17321. case EKU_CLIENT_AUTH_OID:
  17322. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17323. break;
  17324. case EKU_CODESIGNING_OID:
  17325. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17326. break;
  17327. case EKU_EMAILPROTECT_OID:
  17328. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17329. break;
  17330. case EKU_TIMESTAMP_OID:
  17331. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17332. break;
  17333. case EKU_OCSP_SIGN_OID:
  17334. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17335. break;
  17336. #ifdef WOLFSSL_WOLFSSH
  17337. case EKU_SSH_CLIENT_AUTH_OID:
  17338. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  17339. break;
  17340. case EKU_SSH_MSCL_OID:
  17341. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  17342. break;
  17343. case EKU_SSH_KP_CLIENT_AUTH_OID:
  17344. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  17345. break;
  17346. #endif /* WOLFSSL_WOLFSSH */
  17347. default:
  17348. break;
  17349. }
  17350. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17351. cert->extExtKeyUsageCount++;
  17352. #endif
  17353. }
  17354. return 0;
  17355. #else
  17356. word32 idx = 0;
  17357. int length;
  17358. int ret = 0;
  17359. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17360. /* Strip SEQUENCE OF and expect to account for all the data. */
  17361. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17362. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17363. ret = ASN_PARSE_E;
  17364. }
  17365. if (ret == 0) {
  17366. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17367. /* Keep reference for WOLFSSL_X509. */
  17368. cert->extExtKeyUsageSrc = input + idx;
  17369. cert->extExtKeyUsageSz = (word32)length;
  17370. #endif
  17371. }
  17372. /* Check all OIDs. */
  17373. while ((ret == 0) && (idx < (word32)sz)) {
  17374. ASNGetData dataASN[keyPurposeIdASN_Length];
  17375. /* Clear dynamic data items and set OID type expected. */
  17376. XMEMSET(dataASN, 0, sizeof(dataASN));
  17377. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  17378. /* Decode KeyPurposeId. */
  17379. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  17380. input, &idx, sz);
  17381. /* Skip unknown OIDs. */
  17382. if (ret == ASN_UNKNOWN_OID_E) {
  17383. ret = 0;
  17384. }
  17385. else if (ret == 0) {
  17386. /* Store the bit for the OID. */
  17387. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  17388. case EKU_ANY_OID:
  17389. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17390. break;
  17391. case EKU_SERVER_AUTH_OID:
  17392. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17393. break;
  17394. case EKU_CLIENT_AUTH_OID:
  17395. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17396. break;
  17397. case EKU_CODESIGNING_OID:
  17398. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17399. break;
  17400. case EKU_EMAILPROTECT_OID:
  17401. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17402. break;
  17403. case EKU_TIMESTAMP_OID:
  17404. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17405. break;
  17406. case EKU_OCSP_SIGN_OID:
  17407. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17408. break;
  17409. }
  17410. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17411. /* Keep count for WOLFSSL_X509. */
  17412. cert->extExtKeyUsageCount++;
  17413. #endif
  17414. }
  17415. }
  17416. return ret;
  17417. #endif /* WOLFSSL_ASN_TEMPLATE */
  17418. }
  17419. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17420. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  17421. {
  17422. word32 idx = 0;
  17423. int len = 0;
  17424. WOLFSSL_ENTER("DecodeNsCertType");
  17425. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  17426. return ASN_PARSE_E;
  17427. /* Don't need to worry about unused bits as CheckBitString makes sure
  17428. * they're zero. */
  17429. if (idx < (word32)sz)
  17430. cert->nsCertType = input[idx];
  17431. else
  17432. return ASN_PARSE_E;
  17433. return 0;
  17434. }
  17435. #endif
  17436. #ifndef IGNORE_NAME_CONSTRAINTS
  17437. #ifdef WOLFSSL_ASN_TEMPLATE
  17438. /* ASN.1 template for GeneralSubtree.
  17439. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17440. */
  17441. static const ASNItem subTreeASN[] = {
  17442. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17443. /* base GeneralName */
  17444. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  17445. /* minimum BaseDistance DEFAULT 0*/
  17446. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  17447. /* maximum BaseDistance OPTIONAL */
  17448. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  17449. };
  17450. enum {
  17451. SUBTREEASN_IDX_SEQ = 0,
  17452. SUBTREEASN_IDX_BASE,
  17453. SUBTREEASN_IDX_MIN,
  17454. SUBTREEASN_IDX_MAX
  17455. };
  17456. /* Number of items in ASN.1 template for GeneralSubtree. */
  17457. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  17458. #endif
  17459. #ifdef WOLFSSL_ASN_TEMPLATE
  17460. /* Decode the Subtree's GeneralName.
  17461. *
  17462. * @param [in] input Buffer holding data.
  17463. * @param [in] sz Size of data in buffer.
  17464. * @param [in] tag BER tag on GeneralName.
  17465. * @param [in, out] head Linked list of subtree names.
  17466. * @param [in] heap Dynamic memory hint.
  17467. * @return 0 on success.
  17468. * @return MEMORY_E when dynamic memory allocation fails.
  17469. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17470. */
  17471. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  17472. Base_entry** head, void* heap)
  17473. {
  17474. Base_entry* entry;
  17475. word32 nameIdx = 0;
  17476. word32 len = sz;
  17477. int strLen;
  17478. int ret = 0;
  17479. (void)heap;
  17480. /* if constructed has leading sequence */
  17481. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  17482. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  17483. if (ret < 0) {
  17484. ret = ASN_PARSE_E;
  17485. }
  17486. else {
  17487. len = (word32)strLen;
  17488. ret = 0;
  17489. }
  17490. }
  17491. if (ret == 0) {
  17492. /* TODO: consider one malloc. */
  17493. /* Allocate Base Entry object. */
  17494. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17495. DYNAMIC_TYPE_ALTNAME);
  17496. if (entry == NULL) {
  17497. ret = MEMORY_E;
  17498. }
  17499. }
  17500. if (ret == 0) {
  17501. /* Allocate name. */
  17502. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  17503. if (entry->name == NULL) {
  17504. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17505. ret = MEMORY_E;
  17506. }
  17507. }
  17508. if (ret == 0) {
  17509. /* Store name, size and tag in object. */
  17510. XMEMCPY(entry->name, &input[nameIdx], len);
  17511. entry->name[len] = '\0';
  17512. entry->nameSz = (int)len;
  17513. entry->type = tag & ASN_TYPE_MASK;
  17514. /* Put entry at front of linked list. */
  17515. entry->next = *head;
  17516. *head = entry;
  17517. }
  17518. return ret;
  17519. }
  17520. #endif
  17521. /* Decode a subtree of a name constraints in a certificate.
  17522. *
  17523. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  17524. *
  17525. * @param [in] input Buffer holding data.
  17526. * @param [in] sz Size of data in buffer.
  17527. * @param [in, out] head Linked list of subtree names.
  17528. * @param [in] heap Dynamic memory hint.
  17529. * @return 0 on success.
  17530. * @return MEMORY_E when dynamic memory allocation fails.
  17531. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17532. */
  17533. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  17534. void* heap)
  17535. {
  17536. #ifndef WOLFSSL_ASN_TEMPLATE
  17537. word32 idx = 0;
  17538. int ret = 0;
  17539. (void)heap;
  17540. while (idx < (word32)sz) {
  17541. int seqLength, strLength;
  17542. word32 nameIdx;
  17543. byte b, bType;
  17544. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  17545. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17546. return ASN_PARSE_E;
  17547. }
  17548. if (idx >= (word32)sz) {
  17549. WOLFSSL_MSG("\tfail: expecting tag");
  17550. return ASN_PARSE_E;
  17551. }
  17552. nameIdx = idx;
  17553. b = input[nameIdx++];
  17554. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  17555. WOLFSSL_MSG("\tinvalid length");
  17556. return ASN_PARSE_E;
  17557. }
  17558. /* Get type, LSB 4-bits */
  17559. bType = (byte)(b & ASN_TYPE_MASK);
  17560. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  17561. bType == ASN_DIR_TYPE) {
  17562. Base_entry* entry;
  17563. /* if constructed has leading sequence */
  17564. if (b & ASN_CONSTRUCTED) {
  17565. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  17566. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  17567. return ASN_PARSE_E;
  17568. }
  17569. }
  17570. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17571. DYNAMIC_TYPE_ALTNAME);
  17572. if (entry == NULL) {
  17573. WOLFSSL_MSG("allocate error");
  17574. return MEMORY_E;
  17575. }
  17576. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  17577. DYNAMIC_TYPE_ALTNAME);
  17578. if (entry->name == NULL) {
  17579. WOLFSSL_MSG("allocate error");
  17580. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17581. return MEMORY_E;
  17582. }
  17583. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  17584. entry->name[strLength] = '\0';
  17585. entry->nameSz = strLength;
  17586. entry->type = bType;
  17587. entry->next = *head;
  17588. *head = entry;
  17589. }
  17590. idx += (word32)seqLength;
  17591. }
  17592. return ret;
  17593. #else
  17594. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  17595. word32 idx = 0;
  17596. int ret = 0;
  17597. (void)heap;
  17598. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  17599. /* Process all subtrees. */
  17600. while ((ret == 0) && (idx < (word32)sz)) {
  17601. byte minVal = 0;
  17602. byte maxVal = 0;
  17603. /* Clear dynamic data and set choice for GeneralName and location to
  17604. * store minimum and maximum.
  17605. */
  17606. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  17607. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  17608. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  17609. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  17610. /* Parse GeneralSubtree. */
  17611. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  17612. &idx, sz);
  17613. if (ret == 0) {
  17614. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  17615. /* Check GeneralName tag is one of the types we can handle. */
  17616. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  17617. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  17618. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  17619. /* Parse the general name and store a new entry. */
  17620. ret = DecodeSubtreeGeneralName(input +
  17621. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  17622. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  17623. }
  17624. /* Skip entry. */
  17625. }
  17626. }
  17627. FREE_ASNGETDATA(dataASN, heap);
  17628. return ret;
  17629. #endif
  17630. }
  17631. #ifdef WOLFSSL_ASN_TEMPLATE
  17632. /* ASN.1 template for NameConstraints.
  17633. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  17634. */
  17635. static const ASNItem nameConstraintsASN[] = {
  17636. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17637. /* permittedSubtrees */
  17638. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  17639. /* excludededSubtrees */
  17640. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17641. };
  17642. enum {
  17643. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  17644. NAMECONSTRAINTSASN_IDX_PERMIT,
  17645. NAMECONSTRAINTSASN_IDX_EXCLUDE
  17646. };
  17647. /* Number of items in ASN.1 template for NameConstraints. */
  17648. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  17649. #endif
  17650. /* Decode name constraints extension in a certificate.
  17651. *
  17652. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17653. *
  17654. * @param [in] input Buffer holding data.
  17655. * @param [in] sz Size of data in buffer.
  17656. * @param [in, out] cert Certificate object.
  17657. * @return 0 on success.
  17658. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17659. * is invalid.
  17660. * @return MEMORY_E on dynamic memory allocation failure.
  17661. */
  17662. static int DecodeNameConstraints(const byte* input, word32 sz,
  17663. DecodedCert* cert)
  17664. {
  17665. #ifndef WOLFSSL_ASN_TEMPLATE
  17666. word32 idx = 0;
  17667. int length = 0;
  17668. WOLFSSL_ENTER("DecodeNameConstraints");
  17669. if (GetSequence(input, &idx, &length, sz) < 0) {
  17670. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17671. return ASN_PARSE_E;
  17672. }
  17673. while (idx < (word32)sz) {
  17674. byte b = input[idx++];
  17675. Base_entry** subtree = NULL;
  17676. if (GetLength(input, &idx, &length, sz) <= 0) {
  17677. WOLFSSL_MSG("\tinvalid length");
  17678. return ASN_PARSE_E;
  17679. }
  17680. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17681. subtree = &cert->permittedNames;
  17682. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17683. subtree = &cert->excludedNames;
  17684. else {
  17685. WOLFSSL_MSG("\tinvalid subtree");
  17686. return ASN_PARSE_E;
  17687. }
  17688. if (DecodeSubtree(input + idx, (word32)length, subtree,
  17689. cert->heap) < 0) {
  17690. WOLFSSL_MSG("\terror parsing subtree");
  17691. return ASN_PARSE_E;
  17692. }
  17693. idx += (word32)length;
  17694. }
  17695. return 0;
  17696. #else
  17697. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17698. word32 idx = 0;
  17699. int ret = 0;
  17700. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17701. if (ret == 0) {
  17702. /* Parse NameConstraints. */
  17703. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17704. nameConstraintsASN_Length, 1, input, &idx, sz);
  17705. }
  17706. if (ret == 0) {
  17707. /* If there was a permittedSubtrees then parse it. */
  17708. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17709. ret = DecodeSubtree(
  17710. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17711. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17712. &cert->permittedNames, cert->heap);
  17713. }
  17714. }
  17715. if (ret == 0) {
  17716. /* If there was a excludedSubtrees then parse it. */
  17717. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17718. ret = DecodeSubtree(
  17719. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17720. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17721. &cert->excludedNames, cert->heap);
  17722. }
  17723. }
  17724. FREE_ASNGETDATA(dataASN, cert->heap);
  17725. return ret;
  17726. #endif /* WOLFSSL_ASN_TEMPLATE */
  17727. }
  17728. #endif /* IGNORE_NAME_CONSTRAINTS */
  17729. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17730. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17731. /* Decode ITU-T X.690 OID format to a string representation
  17732. * return string length */
  17733. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17734. {
  17735. word32 val, inIdx = 0, outIdx = 0;
  17736. int w = 0;
  17737. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17738. return BAD_FUNC_ARG;
  17739. /* The first byte expands into b/40 dot b%40. */
  17740. val = in[inIdx++];
  17741. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17742. if (w < 0) {
  17743. w = BUFFER_E;
  17744. goto exit;
  17745. }
  17746. outIdx += (word32)w;
  17747. val = 0;
  17748. while (inIdx < inSz && outIdx < outSz) {
  17749. /* extract the next OID digit from in to val */
  17750. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17751. if (in[inIdx] & 0x80) {
  17752. val += in[inIdx] & 0x7F;
  17753. val *= 128;
  17754. }
  17755. else {
  17756. /* write val as text into out */
  17757. val += in[inIdx];
  17758. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17759. if (w < 0 || (word32)w > outSz - outIdx) {
  17760. w = BUFFER_E;
  17761. goto exit;
  17762. }
  17763. outIdx += (word32)w;
  17764. val = 0;
  17765. }
  17766. inIdx++;
  17767. }
  17768. if (outIdx == outSz)
  17769. outIdx--;
  17770. out[outIdx] = 0;
  17771. w = (int)outIdx;
  17772. exit:
  17773. return w;
  17774. }
  17775. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  17776. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  17777. #ifdef WOLFSSL_ASN_TEMPLATE
  17778. /* ASN.1 template for PolicyInformation.
  17779. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  17780. */
  17781. static const ASNItem policyInfoASN[] = {
  17782. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17783. /* policyIdentifier */
  17784. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17785. /* policyQualifiers */
  17786. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  17787. };
  17788. enum {
  17789. POLICYINFOASN_IDX_SEQ = 0,
  17790. POLICYINFOASN_IDX_ID,
  17791. POLICYINFOASN_IDX_QUALI
  17792. };
  17793. /* Number of items in ASN.1 template for PolicyInformation. */
  17794. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  17795. #endif
  17796. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  17797. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  17798. {
  17799. #ifndef WOLFSSL_ASN_TEMPLATE
  17800. word32 idx = 0;
  17801. word32 oldIdx;
  17802. int policy_length = 0;
  17803. int ret;
  17804. int total_length = 0;
  17805. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17806. !defined(WOLFSSL_DUP_CERTPOL)
  17807. int i;
  17808. #endif
  17809. WOLFSSL_ENTER("DecodeCertPolicy");
  17810. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17811. /* Check if cert is null before dereferencing below */
  17812. if (cert == NULL)
  17813. return BAD_FUNC_ARG;
  17814. #else
  17815. (void)cert;
  17816. #endif
  17817. #if defined(WOLFSSL_CERT_EXT)
  17818. cert->extCertPoliciesNb = 0;
  17819. #endif
  17820. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  17821. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  17822. return ASN_PARSE_E;
  17823. }
  17824. /* Validate total length */
  17825. if (total_length > (int)(sz - idx)) {
  17826. WOLFSSL_MSG("\tCertPolicy length mismatch");
  17827. return ASN_PARSE_E;
  17828. }
  17829. /* Unwrap certificatePolicies */
  17830. do {
  17831. int length = 0;
  17832. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  17833. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  17834. return ASN_PARSE_E;
  17835. }
  17836. oldIdx = idx;
  17837. ret = GetASNObjectId(input, &idx, &length, sz);
  17838. if (ret != 0)
  17839. return ret;
  17840. policy_length -= (int)(idx - oldIdx);
  17841. if (length > 0) {
  17842. /* Verify length won't overrun buffer */
  17843. if (length > (int)(sz - idx)) {
  17844. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  17845. return ASN_PARSE_E;
  17846. }
  17847. #if defined(WOLFSSL_SEP)
  17848. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  17849. DYNAMIC_TYPE_X509_EXT);
  17850. if (cert->deviceType == NULL) {
  17851. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17852. return MEMORY_E;
  17853. }
  17854. cert->deviceTypeSz = length;
  17855. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  17856. break;
  17857. #elif defined(WOLFSSL_CERT_EXT)
  17858. /* decode cert policy */
  17859. if (DecodePolicyOID(cert->extCertPolicies[
  17860. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  17861. input + idx, length) <= 0) {
  17862. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17863. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17864. return ASN_PARSE_E;
  17865. }
  17866. #ifndef WOLFSSL_DUP_CERTPOL
  17867. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17868. * NOT appear more than once in a certificate policies
  17869. * extension". This is a sanity check for duplicates.
  17870. * extCertPolicies should only have OID values, additional
  17871. * qualifiers need to be stored in a separate array. */
  17872. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  17873. if (XMEMCMP(cert->extCertPolicies[i],
  17874. cert->extCertPolicies[cert->extCertPoliciesNb],
  17875. MAX_CERTPOL_SZ) == 0) {
  17876. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17877. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17878. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17879. return CERTPOLICIES_E;
  17880. }
  17881. }
  17882. #endif /* !WOLFSSL_DUP_CERTPOL */
  17883. cert->extCertPoliciesNb++;
  17884. #else
  17885. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17886. return 0;
  17887. #endif
  17888. }
  17889. idx += (word32)policy_length;
  17890. } while((int)idx < total_length
  17891. #if defined(WOLFSSL_CERT_EXT)
  17892. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  17893. #endif
  17894. );
  17895. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17896. return 0;
  17897. #else /* WOLFSSL_ASN_TEMPLATE */
  17898. word32 idx = 0;
  17899. int ret = 0;
  17900. int total_length = 0;
  17901. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17902. !defined(WOLFSSL_DUP_CERTPOL)
  17903. int i;
  17904. #endif
  17905. WOLFSSL_ENTER("DecodeCertPolicy");
  17906. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17907. /* Check if cert is null before dereferencing below */
  17908. if (cert == NULL)
  17909. ret = BAD_FUNC_ARG;
  17910. #endif
  17911. if (ret == 0) {
  17912. #if defined(WOLFSSL_CERT_EXT)
  17913. cert->extCertPoliciesNb = 0;
  17914. #endif
  17915. /* Strip SEQUENCE OF and check using all data. */
  17916. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  17917. {
  17918. ret = ASN_PARSE_E;
  17919. }
  17920. }
  17921. /* Unwrap certificatePolicies */
  17922. while ((ret == 0) && ((int)idx < total_length)
  17923. #if defined(WOLFSSL_CERT_EXT)
  17924. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  17925. #endif
  17926. ) {
  17927. ASNGetData dataASN[policyInfoASN_Length];
  17928. byte* data = NULL;
  17929. word32 length = 0;
  17930. /* Clear dynamic data and check OID is a cert policy type. */
  17931. XMEMSET(dataASN, 0, sizeof(dataASN));
  17932. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  17933. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  17934. input, &idx, (word32)sz);
  17935. if (ret == 0) {
  17936. /* Get the OID. */
  17937. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  17938. if (length == 0) {
  17939. ret = ASN_PARSE_E;
  17940. }
  17941. }
  17942. #if defined(WOLFSSL_SEP)
  17943. /* Store OID in device type. */
  17944. if (ret == 0) {
  17945. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17946. DYNAMIC_TYPE_X509_EXT);
  17947. if (cert->deviceType == NULL) {
  17948. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17949. ret = MEMORY_E;
  17950. }
  17951. }
  17952. if (ret == 0) {
  17953. /* Store device type data and length. */
  17954. cert->deviceTypeSz = (int)length;
  17955. XMEMCPY(cert->deviceType, data, length);
  17956. break;
  17957. }
  17958. #elif defined(WOLFSSL_CERT_EXT)
  17959. if (ret == 0) {
  17960. /* Decode cert policy. */
  17961. if (DecodePolicyOID(
  17962. cert->extCertPolicies[cert->extCertPoliciesNb],
  17963. MAX_CERTPOL_SZ, data, length) <= 0) {
  17964. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17965. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17966. ret = ASN_PARSE_E;
  17967. }
  17968. }
  17969. #ifndef WOLFSSL_DUP_CERTPOL
  17970. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17971. * NOT appear more than once in a certificate policies
  17972. * extension". This is a sanity check for duplicates.
  17973. * extCertPolicies should only have OID values, additional
  17974. * qualifiers need to be stored in a seperate array. */
  17975. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  17976. if (XMEMCMP(cert->extCertPolicies[i],
  17977. cert->extCertPolicies[cert->extCertPoliciesNb],
  17978. MAX_CERTPOL_SZ) == 0) {
  17979. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17980. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17981. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17982. ret = CERTPOLICIES_E;
  17983. }
  17984. }
  17985. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  17986. if (ret == 0) {
  17987. /* Keep count of policies seen. */
  17988. cert->extCertPoliciesNb++;
  17989. }
  17990. #else
  17991. (void)data;
  17992. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17993. break;
  17994. #endif
  17995. }
  17996. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17997. return ret;
  17998. #endif /* WOLFSSL_ASN_TEMPLATE */
  17999. }
  18000. #endif /* WOLFSSL_SEP */
  18001. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18002. #ifdef WOLFSSL_ASN_TEMPLATE
  18003. /* ASN.1 template for subject dir attribute.
  18004. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  18005. */
  18006. static const ASNItem subjDirAttrASN[] = {
  18007. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18008. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18009. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  18010. };
  18011. enum {
  18012. SUBJDIRATTRASN_IDX_SEQ = 0,
  18013. SUBJDIRATTRASN_IDX_OID,
  18014. SUBJDIRATTRASN_IDX_SET,
  18015. };
  18016. /* Number of items in ASN.1 template for BasicContraints. */
  18017. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  18018. #endif
  18019. /* Decode subject directory attributes extension in a certificate.
  18020. *
  18021. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  18022. *
  18023. * @param [in] input Buffer holding data.
  18024. * @param [in] sz Size of data in buffer.
  18025. * @param [in, out] cert Certificate object.
  18026. * @return 0 on success.
  18027. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18028. * is invalid.
  18029. */
  18030. static int DecodeSubjDirAttr(const byte* input, word32 sz, DecodedCert* cert)
  18031. {
  18032. #ifndef WOLFSSL_ASN_TEMPLATE
  18033. word32 idx = 0;
  18034. int length = 0;
  18035. int ret = 0;
  18036. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18037. #ifdef OPENSSL_ALL
  18038. cert->extSubjDirAttrSrc = input;
  18039. cert->extSubjDirAttrSz = sz;
  18040. #endif /* OPENSSL_ALL */
  18041. /* Unwrap the list of Attributes */
  18042. if (GetSequence(input, &idx, &length, sz) < 0)
  18043. return ASN_PARSE_E;
  18044. if (length == 0) {
  18045. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  18046. If the subjectDirectoryAttributes extension is present, the
  18047. sequence MUST contain at least one entry. */
  18048. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18049. return ASN_PARSE_E;
  18050. }
  18051. /* length is the length of the list contents */
  18052. while (idx < (word32)sz) {
  18053. word32 oid;
  18054. if (GetSequence(input, &idx, &length, sz) < 0)
  18055. return ASN_PARSE_E;
  18056. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  18057. return ASN_PARSE_E;
  18058. if (GetSet(input, &idx, &length, sz) < 0)
  18059. return ASN_PARSE_E;
  18060. /* There may be more than one countryOfCitizenship, but save the
  18061. * first one for now. */
  18062. if (oid == SDA_COC_OID) {
  18063. byte tag;
  18064. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  18065. return ASN_PARSE_E;
  18066. if (length != COUNTRY_CODE_LEN)
  18067. return ASN_PARSE_E;
  18068. if (tag == ASN_PRINTABLE_STRING) {
  18069. XMEMCPY(cert->countryOfCitizenship,
  18070. input + idx, COUNTRY_CODE_LEN);
  18071. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18072. }
  18073. }
  18074. idx += length;
  18075. }
  18076. return ret;
  18077. #else
  18078. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  18079. int ret = 0;
  18080. word32 idx = 0;
  18081. int length;
  18082. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18083. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  18084. /* Strip outer SEQUENCE. */
  18085. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  18086. ret = ASN_PARSE_E;
  18087. }
  18088. /* Handle each inner SEQUENCE. */
  18089. while ((ret == 0) && (idx < (word32)sz)) {
  18090. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  18091. input, &idx, sz);
  18092. /* There may be more than one countryOfCitizenship, but save the
  18093. * first one for now. */
  18094. if ((ret == 0) &&
  18095. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  18096. int cuLen;
  18097. word32 setIdx = 0;
  18098. byte* setData;
  18099. word32 setLen;
  18100. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  18101. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  18102. setLen) < 0) {
  18103. ret = ASN_PARSE_E;
  18104. }
  18105. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  18106. ret = ASN_PARSE_E;
  18107. }
  18108. if (ret == 0) {
  18109. XMEMCPY(cert->countryOfCitizenship, setData + setIdx,
  18110. (size_t)cuLen);
  18111. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18112. }
  18113. }
  18114. }
  18115. FREE_ASNGETDATA(dataASN, cert->heap);
  18116. return ret;
  18117. #endif /* WOLFSSL_ASN_TEMPLATE */
  18118. }
  18119. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  18120. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18121. /* Decode subject infomation access extension in a certificate.
  18122. *
  18123. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  18124. *
  18125. * @param [in] input Buffer holding data.
  18126. * @param [in] sz Size of data in buffer.
  18127. * @param [in, out] cert Certificate object.
  18128. * @return 0 on success.
  18129. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18130. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18131. * is invalid.
  18132. * @return MEMORY_E on dynamic memory allocation failure.
  18133. */
  18134. static int DecodeSubjInfoAcc(const byte* input, word32 sz, DecodedCert* cert)
  18135. {
  18136. word32 idx = 0;
  18137. int length = 0;
  18138. int ret = 0;
  18139. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  18140. #ifdef OPENSSL_ALL
  18141. cert->extSubjAltNameSrc = input;
  18142. cert->extSubjAltNameSz = sz;
  18143. #endif /* OPENSSL_ALL */
  18144. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  18145. if (GetSequence(input, &idx, &length, sz) < 0)
  18146. return ASN_PARSE_E;
  18147. if (length == 0) {
  18148. /* RFC 5280 4.2.2.2. Subject Information Access
  18149. If the subjectInformationAccess extension is present, the
  18150. sequence MUST contain at least one entry. */
  18151. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18152. return ASN_PARSE_E;
  18153. }
  18154. /* Per fpkx-x509-cert-profile-common... section 5.3.
  18155. * [The] subjectInfoAccess extension must contain at least one
  18156. * instance of the id-ad-caRepository access method containing a
  18157. * publicly accessible HTTP URI which returns as certs-only
  18158. * CMS.
  18159. */
  18160. while (idx < (word32)sz) {
  18161. word32 oid = 0;
  18162. byte b;
  18163. /* Unwrap an AccessDescription */
  18164. if (GetSequence(input, &idx, &length, sz) < 0)
  18165. return ASN_PARSE_E;
  18166. /* Get the accessMethod */
  18167. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  18168. return ASN_PARSE_E;
  18169. /* Only supporting URIs right now. */
  18170. if (GetASNTag(input, &idx, &b, sz) < 0)
  18171. return ASN_PARSE_E;
  18172. if (GetLength(input, &idx, &length, sz) < 0)
  18173. return ASN_PARSE_E;
  18174. /* Set caRepo entry */
  18175. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  18176. cert->extSubjInfoAccCaRepoSz = (word32)length;
  18177. cert->extSubjInfoAccCaRepo = input + idx;
  18178. break;
  18179. }
  18180. idx += (word32)length;
  18181. }
  18182. if (cert->extSubjInfoAccCaRepo == NULL ||
  18183. cert->extSubjInfoAccCaRepoSz == 0) {
  18184. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  18185. ret = ASN_PARSE_E;
  18186. }
  18187. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  18188. return ret;
  18189. }
  18190. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  18191. /* Macro to check if bit is set, if not sets and return success.
  18192. Otherwise returns failure */
  18193. /* Macro required here because bit-field operation */
  18194. #ifndef WOLFSSL_NO_ASN_STRICT
  18195. #define VERIFY_AND_SET_OID(bit) \
  18196. if ((bit) == 0) \
  18197. (bit) = 1; \
  18198. else \
  18199. return ASN_OBJECT_ID_E;
  18200. #else
  18201. /* With no strict defined, the verify is skipped */
  18202. #define VERIFY_AND_SET_OID(bit) bit = 1;
  18203. #endif
  18204. /* Parse extension type specific data based on OID sum.
  18205. *
  18206. * Supported extensions:
  18207. * Basic Constraints - BASIC_CA_OID
  18208. * CRL Distribution Points - CRL_DIST_OID
  18209. * Authority Information Access - AUTH_INFO_OID
  18210. * Subject Alternative Name - ALT_NAMES_OID
  18211. * Authority Key Identifier - AUTH_KEY_OID
  18212. * Subject Key Identifier - SUBJ_KEY_OID
  18213. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  18214. * Key Usage - KEY_USAGE_OID
  18215. * Extended Key Usage - EXT_KEY_USAGE_OID
  18216. * Name Constraints - NAME_CONS_OID
  18217. * Inhibit anyPolicy - INHIBIT_ANY_OID
  18218. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  18219. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  18220. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  18221. * Subject Information Access - SUBJ_INFO_ACC_OID
  18222. * Unsupported extensions from RFC 5280:
  18223. * 4.2.1.5 - Policy mappings
  18224. * 4.2.1.7 - Issuer Alternative Name
  18225. * 4.2.1.11 - Policy Constraints
  18226. * 4.2.1.15 - Freshest CRL
  18227. *
  18228. * @param [in] input Buffer containing extension type specific data.
  18229. * @param [in] length Length of data.
  18230. * @param [in] oid OID sum for extension.
  18231. * @param [in] critical Whether extension is critical.
  18232. * @param [in, out] cert Certificate object.
  18233. * @return 0 on success.
  18234. * @return ASN_PARSE_E when BER encoding is invalid.
  18235. * @return MEMORY_E on dynamic memory allocation failure.
  18236. * @return Other negative values on error.
  18237. */
  18238. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  18239. byte critical, DecodedCert* cert,
  18240. int *isUnknownExt)
  18241. {
  18242. int ret = 0;
  18243. word32 idx = 0;
  18244. if (isUnknownExt != NULL)
  18245. *isUnknownExt = 0;
  18246. switch (oid) {
  18247. /* Basic Constraints. */
  18248. case BASIC_CA_OID:
  18249. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  18250. cert->extBasicConstCrit = critical ? 1 : 0;
  18251. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  18252. ret = ASN_PARSE_E;
  18253. }
  18254. break;
  18255. /* CRL Distribution point. */
  18256. case CRL_DIST_OID:
  18257. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  18258. cert->extCRLdistCrit = critical ? 1 : 0;
  18259. if (DecodeCrlDist(input, length, cert) < 0) {
  18260. ret = ASN_PARSE_E;
  18261. }
  18262. break;
  18263. /* Authority information access. */
  18264. case AUTH_INFO_OID:
  18265. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  18266. cert->extAuthInfoCrit = critical ? 1 : 0;
  18267. if (DecodeAuthInfo(input, length, cert) < 0) {
  18268. ret = ASN_PARSE_E;
  18269. }
  18270. break;
  18271. /* Subject alternative name. */
  18272. case ALT_NAMES_OID:
  18273. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  18274. cert->extSubjAltNameCrit = critical ? 1 : 0;
  18275. ret = DecodeAltNames(input, length, cert);
  18276. break;
  18277. /* Authority Key Identifier. */
  18278. case AUTH_KEY_OID:
  18279. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  18280. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  18281. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18282. /* This check is added due to RFC 5280 section 4.2.1.1
  18283. * stating that conforming CA's must mark this extension
  18284. * as non-critical. When parsing extensions check that
  18285. * certificate was made in compliance with this. */
  18286. if (critical) {
  18287. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  18288. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18289. ret = ASN_CRIT_EXT_E;
  18290. }
  18291. #endif
  18292. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  18293. ret = ASN_PARSE_E;
  18294. }
  18295. break;
  18296. /* Subject Key Identifier. */
  18297. case SUBJ_KEY_OID:
  18298. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  18299. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  18300. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18301. /* This check is added due to RFC 5280 section 4.2.1.2
  18302. * stating that conforming CA's must mark this extension
  18303. * as non-critical. When parsing extensions check that
  18304. * certificate was made in compliance with this. */
  18305. if (critical) {
  18306. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  18307. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18308. ret = ASN_CRIT_EXT_E;
  18309. }
  18310. #endif
  18311. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  18312. ret = ASN_PARSE_E;
  18313. }
  18314. break;
  18315. /* Certificate policies. */
  18316. case CERT_POLICY_OID:
  18317. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  18318. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  18319. #if defined(OPENSSL_EXTRA) || \
  18320. defined(OPENSSL_EXTRA_X509_SMALL)
  18321. cert->extCertPolicyCrit = critical ? 1 : 0;
  18322. #endif
  18323. #endif
  18324. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  18325. defined(WOLFSSL_QT)
  18326. if (DecodeCertPolicy(input, length, cert) < 0) {
  18327. ret = ASN_PARSE_E;
  18328. }
  18329. #else
  18330. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  18331. #endif
  18332. break;
  18333. /* Key usage. */
  18334. case KEY_USAGE_OID:
  18335. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  18336. cert->extKeyUsageCrit = critical ? 1 : 0;
  18337. if (DecodeKeyUsage(input, length, cert) < 0) {
  18338. ret = ASN_PARSE_E;
  18339. }
  18340. break;
  18341. /* Extended key usage. */
  18342. case EXT_KEY_USAGE_OID:
  18343. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  18344. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  18345. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  18346. ret = ASN_PARSE_E;
  18347. }
  18348. break;
  18349. #ifndef IGNORE_NAME_CONSTRAINTS
  18350. /* Name constraints. */
  18351. case NAME_CONS_OID:
  18352. #ifndef WOLFSSL_NO_ASN_STRICT
  18353. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  18354. "The name constraints extension,
  18355. which MUST be used only in a CA certificate" */
  18356. if (!cert->isCA) {
  18357. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  18358. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  18359. ret = ASN_NAME_INVALID_E;
  18360. }
  18361. #endif
  18362. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  18363. cert->extNameConstraintCrit = critical ? 1 : 0;
  18364. if (DecodeNameConstraints(input, length, cert) < 0) {
  18365. ret = ASN_PARSE_E;
  18366. }
  18367. break;
  18368. #endif /* IGNORE_NAME_CONSTRAINTS */
  18369. /* Inhibit anyPolicy. */
  18370. case INHIBIT_ANY_OID:
  18371. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  18372. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  18373. break;
  18374. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18375. /* Netscape's certificate type. */
  18376. case NETSCAPE_CT_OID:
  18377. if (DecodeNsCertType(input, (int)length, cert) < 0)
  18378. ret = ASN_PARSE_E;
  18379. break;
  18380. #endif
  18381. #ifdef HAVE_OCSP
  18382. /* OCSP no check. */
  18383. case OCSP_NOCHECK_OID:
  18384. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  18385. ret = GetASNNull(input, &idx, length);
  18386. if (ret != 0) {
  18387. ret = ASN_PARSE_E;
  18388. }
  18389. break;
  18390. #endif
  18391. case POLICY_CONST_OID:
  18392. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  18393. cert->extPolicyConstCrit = critical ? 1 : 0;
  18394. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  18395. return ASN_PARSE_E;
  18396. break;
  18397. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18398. case SUBJ_DIR_ATTR_OID:
  18399. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  18400. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  18401. return ASN_PARSE_E;
  18402. break;
  18403. #endif
  18404. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18405. case SUBJ_INFO_ACC_OID:
  18406. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  18407. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  18408. return ASN_PARSE_E;
  18409. break;
  18410. #endif
  18411. default:
  18412. if (isUnknownExt != NULL)
  18413. *isUnknownExt = 1;
  18414. #ifndef WOLFSSL_NO_ASN_STRICT
  18415. /* While it is a failure to not support critical extensions,
  18416. * still parse the certificate ignoring the unsupported
  18417. * extension to allow caller to accept it with the verify
  18418. * callback. */
  18419. if (critical) {
  18420. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  18421. ret = ASN_CRIT_EXT_E;
  18422. }
  18423. #endif
  18424. break;
  18425. }
  18426. return ret;
  18427. }
  18428. #ifdef WOLFSSL_ASN_TEMPLATE
  18429. /* ASN.1 template for extensions.
  18430. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18431. */
  18432. static const ASNItem certExtHdrASN[] = {
  18433. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  18434. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18435. };
  18436. enum {
  18437. CERTEXTHDRASN_IDX_EXTTAG = 0,
  18438. CERTEXTHDRASN_IDX_EXTSEQ
  18439. };
  18440. /* Number of itesm in ASN.1 template for extensions. */
  18441. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  18442. /* ASN.1 template for Extension.
  18443. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18444. */
  18445. static const ASNItem certExtASN[] = {
  18446. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18447. /* Extension object id */
  18448. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18449. /* critical - when true, must be parseable. */
  18450. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  18451. /* Data for extension - leave index at start of data. */
  18452. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  18453. };
  18454. enum {
  18455. CERTEXTASN_IDX_SEQ = 0,
  18456. CERTEXTASN_IDX_OID,
  18457. CERTEXTASN_IDX_CRIT,
  18458. CERTEXTASN_IDX_VAL
  18459. };
  18460. /* Number of items in ASN.1 template for Extension. */
  18461. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  18462. #endif
  18463. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  18464. && defined(HAVE_OID_DECODING)
  18465. int wc_SetUnknownExtCallback(DecodedCert* cert,
  18466. wc_UnknownExtCallback cb) {
  18467. if (cert == NULL) {
  18468. return BAD_FUNC_ARG;
  18469. }
  18470. cert->unknownExtCallback = cb;
  18471. return 0;
  18472. }
  18473. #endif
  18474. /*
  18475. * Processing the Certificate Extensions. This does not modify the current
  18476. * index. It is works starting with the recorded extensions pointer.
  18477. */
  18478. static int DecodeCertExtensions(DecodedCert* cert)
  18479. {
  18480. #ifndef WOLFSSL_ASN_TEMPLATE
  18481. int ret = 0;
  18482. word32 idx = 0;
  18483. word32 sz = (word32)cert->extensionsSz;
  18484. const byte* input = cert->extensions;
  18485. int length;
  18486. word32 oid;
  18487. byte critical = 0;
  18488. byte criticalFail = 0;
  18489. byte tag = 0;
  18490. WOLFSSL_ENTER("DecodeCertExtensions");
  18491. if (input == NULL || sz == 0)
  18492. return BAD_FUNC_ARG;
  18493. #ifdef WOLFSSL_CERT_REQ
  18494. if (!cert->isCSR)
  18495. #endif
  18496. { /* Not included in CSR */
  18497. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  18498. return ASN_PARSE_E;
  18499. }
  18500. if (tag != ASN_EXTENSIONS) {
  18501. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  18502. return ASN_PARSE_E;
  18503. }
  18504. if (GetLength(input, &idx, &length, sz) < 0) {
  18505. WOLFSSL_MSG("\tfail: invalid length");
  18506. return ASN_PARSE_E;
  18507. }
  18508. }
  18509. if (GetSequence(input, &idx, &length, sz) < 0) {
  18510. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  18511. return ASN_PARSE_E;
  18512. }
  18513. while (idx < (word32)sz) {
  18514. word32 localIdx;
  18515. if (GetSequence(input, &idx, &length, sz) < 0) {
  18516. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18517. return ASN_PARSE_E;
  18518. }
  18519. oid = 0;
  18520. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  18521. WOLFSSL_MSG("\tfail: OBJECT ID");
  18522. return ret;
  18523. }
  18524. /* check for critical flag */
  18525. critical = 0;
  18526. if ((idx + 1) > (word32)sz) {
  18527. WOLFSSL_MSG("\tfail: malformed buffer");
  18528. return BUFFER_E;
  18529. }
  18530. localIdx = idx;
  18531. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  18532. if (tag == ASN_BOOLEAN) {
  18533. ret = GetBoolean(input, &idx, sz);
  18534. if (ret < 0) {
  18535. WOLFSSL_MSG("\tfail: critical boolean");
  18536. return ret;
  18537. }
  18538. critical = (byte)ret;
  18539. }
  18540. }
  18541. /* process the extension based on the OID */
  18542. ret = GetOctetString(input, &idx, &length, sz);
  18543. if (ret < 0) {
  18544. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  18545. return ret;
  18546. }
  18547. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  18548. cert, NULL);
  18549. if (ret == ASN_CRIT_EXT_E) {
  18550. ret = 0;
  18551. criticalFail = 1;
  18552. }
  18553. if (ret < 0)
  18554. goto end;
  18555. idx += (word32)length;
  18556. }
  18557. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  18558. end:
  18559. return ret;
  18560. #else
  18561. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18562. ASNGetData dataExtsASN[certExtHdrASN_Length];
  18563. int ret = 0;
  18564. const byte* input = cert->extensions;
  18565. int sz = cert->extensionsSz;
  18566. word32 idx = 0;
  18567. int criticalRet = 0;
  18568. int offset = 0;
  18569. WOLFSSL_ENTER("DecodeCertExtensions");
  18570. if (input == NULL || sz == 0)
  18571. ret = BAD_FUNC_ARG;
  18572. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  18573. #ifdef WOLFSSL_CERT_REQ
  18574. if (cert->isCSR) {
  18575. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  18576. }
  18577. #endif
  18578. if (ret == 0) {
  18579. /* Clear dynamic data. */
  18580. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  18581. /* Parse extensions header. */
  18582. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  18583. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  18584. input, &idx, (word32)sz);
  18585. }
  18586. /* Parse each extension. */
  18587. while ((ret == 0) && (idx < (word32)sz)) {
  18588. byte critical = 0;
  18589. int isUnknownExt = 0;
  18590. /* Clear dynamic data. */
  18591. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18592. /* Ensure OID is an extention type. */
  18593. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18594. /* Set criticality variable. */
  18595. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18596. /* Parse extension wrapper. */
  18597. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18598. &idx, (word32)sz);
  18599. if (ret == 0) {
  18600. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  18601. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  18602. /* Decode the extension by type. */
  18603. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  18604. &isUnknownExt);
  18605. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  18606. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  18607. word16 decOid[MAX_OID_SZ];
  18608. word32 decOidSz = sizeof(decOid);
  18609. ret = DecodeObjectId(
  18610. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  18611. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  18612. decOid, &decOidSz);
  18613. if (ret != 0) {
  18614. /* Should never get here as the extension was successfully
  18615. * decoded earlier. Something might be corrupted. */
  18616. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  18617. WOLFSSL_ERROR(ret);
  18618. }
  18619. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  18620. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  18621. dataASN[CERTEXTASN_IDX_VAL].length);
  18622. }
  18623. #endif
  18624. (void)isUnknownExt;
  18625. /* Move index on to next extension. */
  18626. idx += length;
  18627. }
  18628. /* Don't fail criticality until all other extensions have been checked.
  18629. */
  18630. if (ret == ASN_CRIT_EXT_E) {
  18631. criticalRet = ASN_CRIT_EXT_E;
  18632. ret = 0;
  18633. }
  18634. }
  18635. if (ret == 0) {
  18636. /* Use criticality return. */
  18637. ret = criticalRet;
  18638. }
  18639. FREE_ASNGETDATA(dataASN, cert->heap);
  18640. return ret;
  18641. #endif
  18642. }
  18643. #ifdef WOLFSSL_ASN_TEMPLATE
  18644. /* ASN template for an X509 certificate.
  18645. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18646. */
  18647. static const ASNItem x509CertASN[] = {
  18648. /* Certificate ::= SEQUENCE */
  18649. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18650. /* tbsCertificate TBSCertificate */
  18651. /* TBSCertificate ::= SEQUENCE */
  18652. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18653. /* version [0] EXPLICT Version DEFAULT v1 */
  18654. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  18655. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  18656. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18657. /* serialNumber CertificateSerialNumber */
  18658. /* CetificateSerialNumber ::= INTEGER */
  18659. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18660. /* signature AlgorithmIdentifier */
  18661. /* AlgorithmIdentifier ::= SEQUENCE */
  18662. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18663. /* Algorithm OBJECT IDENTIFIER */
  18664. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18665. /* parameters ANY defined by algorithm OPTIONAL */
  18666. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18667. #ifdef WC_RSA_PSS
  18668. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18669. #endif
  18670. /* issuer Name */
  18671. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18672. /* validity Validity */
  18673. /* Validity ::= SEQUENCE */
  18674. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18675. /* notBefore Time */
  18676. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18677. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18678. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18679. /* notAfter Time */
  18680. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18681. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18682. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18683. /* subject Name */
  18684. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18685. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18686. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18687. /* algorithm AlgorithmIdentifier */
  18688. /* AlgorithmIdentifier ::= SEQUENCE */
  18689. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18690. /* Algorithm OBJECT IDENTIFIER */
  18691. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18692. /* parameters ANY defined by algorithm OPTIONAL */
  18693. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18694. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18695. #ifdef WC_RSA_PSS
  18696. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18697. #endif
  18698. /* subjectPublicKey BIT STRING */
  18699. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18700. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18701. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18702. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18703. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18704. /* extensions Extensions OPTIONAL */
  18705. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18706. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18707. /* signatureAlgorithm AlgorithmIdentifier */
  18708. /* AlgorithmIdentifier ::= SEQUENCE */
  18709. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18710. /* Algorithm OBJECT IDENTIFIER */
  18711. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18712. /* parameters ANY defined by algorithm OPTIONAL */
  18713. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18714. #ifdef WC_RSA_PSS
  18715. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18716. #endif
  18717. /* signature BIT STRING */
  18718. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18719. };
  18720. enum {
  18721. X509CERTASN_IDX_SEQ = 0,
  18722. X509CERTASN_IDX_TBS_SEQ,
  18723. X509CERTASN_IDX_TBS_VER,
  18724. X509CERTASN_IDX_TBS_VER_INT,
  18725. X509CERTASN_IDX_TBS_SERIAL,
  18726. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  18727. X509CERTASN_IDX_TBS_ALGOID_OID,
  18728. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  18729. #ifdef WC_RSA_PSS
  18730. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  18731. #endif
  18732. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  18733. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  18734. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  18735. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  18736. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  18737. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  18738. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  18739. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  18740. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  18741. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  18742. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  18743. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  18744. #ifdef WC_RSA_PSS
  18745. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  18746. #endif
  18747. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  18748. X509CERTASN_IDX_TBS_ISSUERUID,
  18749. X509CERTASN_IDX_TBS_SUBJECTUID,
  18750. X509CERTASN_IDX_TBS_EXT,
  18751. X509CERTASN_IDX_TBS_EXT_SEQ,
  18752. X509CERTASN_IDX_SIGALGO_SEQ,
  18753. X509CERTASN_IDX_SIGALGO_OID,
  18754. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  18755. #ifdef WC_RSA_PSS
  18756. X509CERTASN_IDX_SIGALGO_PARAMS,
  18757. #endif
  18758. X509CERTASN_IDX_SIGNATURE,
  18759. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  18760. };
  18761. /* Number of items in ASN template for an X509 certificate. */
  18762. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  18763. /* Check the data data.
  18764. *
  18765. * @param [in] dataASN ASN template dynamic data item.
  18766. * @param [in] dataType BEFORE or AFTER date.
  18767. * @return 0 on success.
  18768. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  18769. * @return ASN_DATE_SZ_E when time data is not supported.
  18770. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18771. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18772. */
  18773. static int CheckDate(ASNGetData *dataASN, int dateType)
  18774. {
  18775. int ret = 0;
  18776. /* Check BER tag is valid. */
  18777. if ((dataASN->tag != ASN_UTC_TIME) &&
  18778. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  18779. ret = ASN_TIME_E;
  18780. }
  18781. /* Check date length is valid. */
  18782. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  18783. (dataASN->length < MIN_DATE_SIZE))) {
  18784. ret = ASN_DATE_SZ_E;
  18785. }
  18786. #ifndef NO_ASN_TIME_CHECK
  18787. /* Check date is a valid string and BEFORE or AFTER now. */
  18788. if ((ret == 0) &&
  18789. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  18790. if (dateType == BEFORE) {
  18791. ret = ASN_BEFORE_DATE_E;
  18792. }
  18793. else {
  18794. ret = ASN_AFTER_DATE_E;
  18795. }
  18796. }
  18797. #endif
  18798. (void)dateType;
  18799. return ret;
  18800. }
  18801. /* Decode a certificate. Internal/non-public API.
  18802. *
  18803. * @param [in] cert Certificate object.
  18804. * @param [in] verify Whether to verify dates before and after now.
  18805. * @param [out] criticalExt Critical extension return code.
  18806. * @param [out] badDateRet Bad date return code.
  18807. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  18808. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  18809. * @return 0 on success.
  18810. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18811. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18812. * @return ASN_DATE_SZ_E when time data is not supported.
  18813. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18814. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18815. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18816. * is invalid.
  18817. * @return BUFFER_E when data in buffer is too small.
  18818. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18819. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18820. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18821. * non-zero length.
  18822. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18823. */
  18824. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  18825. int* badDateRet, int stopAtPubKey,
  18826. int stopAfterPubKey)
  18827. {
  18828. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  18829. int ret = 0;
  18830. int badDate = 0;
  18831. byte version;
  18832. word32 idx;
  18833. word32 serialSz;
  18834. const unsigned char* issuer = NULL;
  18835. word32 issuerSz = 0;
  18836. const unsigned char* subject = NULL;
  18837. word32 subjectSz = 0;
  18838. word32 pubKeyOffset = 0;
  18839. word32 pubKeyEnd = 0;
  18840. int done = 0;
  18841. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  18842. if (ret == 0) {
  18843. version = 0;
  18844. serialSz = EXTERNAL_SERIAL_SIZE;
  18845. /* Get the version and put the serial number into the buffer. */
  18846. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  18847. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  18848. &serialSz);
  18849. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  18850. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  18851. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  18852. oidKeyType);
  18853. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  18854. oidCurveType);
  18855. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  18856. /* Parse the X509 certificate. */
  18857. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  18858. cert->source, &cert->srcIdx, cert->maxIdx);
  18859. #ifdef WOLFSSL_CLANG_TIDY
  18860. /* work around clang-tidy false positive re cert->source. */
  18861. if ((ret == 0) && (cert->source == NULL)) {
  18862. ret = ASN_PARSE_E;
  18863. }
  18864. #endif
  18865. }
  18866. /* Check version is valid/supported - can't be negative. */
  18867. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18868. WOLFSSL_MSG("Unexpected certificate version");
  18869. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18870. ret = ASN_PARSE_E;
  18871. }
  18872. if (ret == 0) {
  18873. int i;
  18874. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18875. /* Set fields extracted from data. */
  18876. cert->version = version;
  18877. cert->serialSz = (int)serialSz;
  18878. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  18879. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18880. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  18881. /* No bad date error - don't always care. */
  18882. badDate = 0;
  18883. /* Find the item with the BEFORE date and check it. */
  18884. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  18885. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  18886. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  18887. if ((CheckDate(&dataASN[i], BEFORE) < 0) && (verify != NO_VERIFY) &&
  18888. (verify != VERIFY_SKIP_DATE)) {
  18889. badDate = ASN_BEFORE_DATE_E;
  18890. }
  18891. /* Store reference to BEFOREdate. */
  18892. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  18893. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18894. /* Find the item with the AFTER date and check it. */
  18895. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  18896. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  18897. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  18898. if ((CheckDate(&dataASN[i], AFTER) < 0) && (verify != NO_VERIFY) &&
  18899. (verify != VERIFY_SKIP_DATE)) {
  18900. badDate = ASN_AFTER_DATE_E;
  18901. }
  18902. /* Store reference to AFTER date. */
  18903. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  18904. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18905. /* Get the issuer name. */
  18906. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18907. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  18908. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18909. /* Get the subject name. */
  18910. subject = cert->source +
  18911. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18912. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  18913. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18914. }
  18915. if ((ret == 0) && stopAtPubKey) {
  18916. /* Return any bad date error through badDateRet and return offset of
  18917. * subjectPublicKeyInfo.
  18918. */
  18919. if (badDateRet != NULL) {
  18920. *badDateRet = badDate;
  18921. }
  18922. done = 1;
  18923. }
  18924. if ((ret == 0) && (!done)) {
  18925. /* Store the signature information. */
  18926. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18927. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  18928. &cert->signature, &cert->sigLength);
  18929. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  18930. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  18931. != cert->signatureOID) {
  18932. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  18933. ret = ASN_SIG_OID_E;
  18934. }
  18935. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  18936. else if (IsSigAlgoECC(cert->signatureOID)) {
  18937. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  18938. #ifdef WC_RSA_PSS
  18939. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  18940. #endif
  18941. ) {
  18942. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18943. ret = ASN_PARSE_E;
  18944. }
  18945. }
  18946. #ifdef WC_RSA_PSS
  18947. /* Check parameters starting with a SEQUENCE. */
  18948. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  18949. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  18950. word32 sigAlgParamsSz = 0;
  18951. /* Parameters only with RSA PSS. */
  18952. if (oid != CTC_RSASSAPSS) {
  18953. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18954. ret = ASN_PARSE_E;
  18955. }
  18956. if (ret == 0) {
  18957. const byte* tbsParams;
  18958. word32 tbsParamsSz;
  18959. const byte* sigAlgParams;
  18960. /* Check RSA PSS parameters are the same. */
  18961. tbsParams =
  18962. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18963. cert->source);
  18964. tbsParamsSz =
  18965. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18966. cert->source);
  18967. sigAlgParams =
  18968. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18969. cert->source);
  18970. sigAlgParamsSz =
  18971. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18972. cert->source);
  18973. if ((tbsParamsSz != sigAlgParamsSz) ||
  18974. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  18975. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18976. ret = ASN_PARSE_E;
  18977. }
  18978. }
  18979. if (ret == 0) {
  18980. /* Store parameters for use in signature verification. */
  18981. cert->sigParamsIndex =
  18982. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  18983. cert->sigParamsLength = sigAlgParamsSz;
  18984. }
  18985. }
  18986. #endif
  18987. }
  18988. if ((ret == 0) && (!done)) {
  18989. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  18990. if (stopAfterPubKey) {
  18991. /* Return any bad date error through badDateRed and return offset
  18992. * after subjectPublicKeyInfo.
  18993. */
  18994. if (badDateRet != NULL) {
  18995. *badDateRet = badDate;
  18996. }
  18997. done = 1;
  18998. }
  18999. }
  19000. if ((ret == 0) && (!done) &&
  19001. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  19002. #ifndef ALLOW_V1_EXTENSIONS
  19003. /* Certificate extensions were only defined in version 2. */
  19004. if (cert->version < 2) {
  19005. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  19006. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  19007. ret = ASN_VERSION_E;
  19008. }
  19009. #endif
  19010. if (ret == 0) {
  19011. /* Save references to extension data. */
  19012. cert->extensions = GetASNItem_Addr(
  19013. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  19014. cert->extensionsSz = (int)GetASNItem_Length(
  19015. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  19016. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  19017. /* Advance past extensions. */
  19018. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  19019. }
  19020. }
  19021. /* Dispose of memory before allocating for extension decoding. */
  19022. FREE_ASNGETDATA(dataASN, cert->heap);
  19023. if ((ret == 0) && (issuer != NULL)) {
  19024. idx = 0;
  19025. /* Put issuer into cert and calculate hash. */
  19026. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  19027. &idx, issuerSz);
  19028. }
  19029. if ((ret == 0) && (subject != NULL)) {
  19030. idx = 0;
  19031. /* Put subject into cert and calculate hash. */
  19032. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19033. subject, &idx, subjectSz);
  19034. }
  19035. if (ret == 0) {
  19036. /* Determine if self signed by comparing issuer and subject hashes. */
  19037. #ifdef WOLFSSL_CERT_REQ
  19038. if (cert->isCSR) {
  19039. cert->selfSigned = 1;
  19040. }
  19041. else
  19042. #endif
  19043. {
  19044. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  19045. KEYID_SIZE) == 0);
  19046. }
  19047. if (stopAtPubKey) {
  19048. ret = (int)pubKeyOffset;
  19049. }
  19050. }
  19051. if ((ret == 0) && (!stopAtPubKey)) {
  19052. /* Parse the public key. */
  19053. idx = pubKeyOffset;
  19054. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  19055. }
  19056. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  19057. (cert->extensions != NULL)) {
  19058. /* Decode the extension data starting at [3]. */
  19059. ret = DecodeCertExtensions(cert);
  19060. if (criticalExt != NULL) {
  19061. if (ret == ASN_CRIT_EXT_E) {
  19062. /* Return critical extension not recognized. */
  19063. *criticalExt = ret;
  19064. ret = 0;
  19065. }
  19066. else {
  19067. /* No critical extension error. */
  19068. *criticalExt = 0;
  19069. }
  19070. }
  19071. }
  19072. if ((ret == 0) && (!done) && (badDate != 0)) {
  19073. /* Parsed whole certificate fine but return any date errors. */
  19074. ret = badDate;
  19075. }
  19076. return ret;
  19077. }
  19078. /* Decode BER/DER data into certificate object.
  19079. *
  19080. * BER/DER data information held in source, srcIdx and maxIdx fields of
  19081. * certificate object.
  19082. *
  19083. * @param [in] cert Decoded certificate object.
  19084. * @param [in] verify Whether to find CA and verify certificate.
  19085. * @param [in] criticalExt Any error for critical extensions not recognized.
  19086. * @return 0 on success.
  19087. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19088. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  19089. * @return ASN_DATE_SZ_E when time data is not supported.
  19090. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19091. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19092. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19093. * is invalid.
  19094. * @return BUFFER_E when data in buffer is too small.
  19095. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19096. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  19097. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19098. * non-zero length.
  19099. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19100. */
  19101. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  19102. {
  19103. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  19104. }
  19105. #ifdef WOLFSSL_CERT_REQ
  19106. /* ASN.1 template for certificate request Attribute.
  19107. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  19108. */
  19109. static const ASNItem reqAttrASN[] = {
  19110. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19111. /* type */
  19112. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  19113. /* values */
  19114. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  19115. };
  19116. enum {
  19117. REQATTRASN_IDX_SEQ = 0,
  19118. REQATTRASN_IDX_TYPE,
  19119. REQATTRASN_IDX_VALS
  19120. };
  19121. /* Number of items in ASN.1 template for certificate request Attribute. */
  19122. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  19123. /* ASN.1 template for a string choice. */
  19124. static const ASNItem strAttrASN[] = {
  19125. { 0, 0, 0, 0, 0 },
  19126. };
  19127. enum {
  19128. STRATTRASN_IDX_STR = 0
  19129. };
  19130. /* Number of items in ASN.1 template for a string choice. */
  19131. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  19132. /* ASN.1 choices for types for a string in an attribute. */
  19133. static const byte strAttrChoice[] = {
  19134. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  19135. };
  19136. /* Decode a certificate request attribute's value.
  19137. *
  19138. * @param [in] cert Certificate request object.
  19139. * @param [out] criticalExt Critical extension return code.
  19140. * @param [in] oid OID decribing which attribute was found.
  19141. * @param [in] aIdx Index into certificate source to start parsing.
  19142. * @param [in] input Attribute value data.
  19143. * @param [in] maxIdx Maximum index to parse to.
  19144. * @return 0 on success.
  19145. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19146. * is invalid.
  19147. */
  19148. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  19149. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  19150. {
  19151. int ret = 0;
  19152. word32 idx = 0;
  19153. ASNGetData strDataASN[strAttrASN_Length];
  19154. switch (oid) {
  19155. case PKCS9_CONTENT_TYPE_OID:
  19156. /* Clear dynamic data and specify choices acceptable. */
  19157. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19158. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19159. /* Parse a string. */
  19160. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19161. 1, input, &idx, maxIdx);
  19162. if (ret == 0) {
  19163. /* Store references to password data. */
  19164. cert->contentType =
  19165. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19166. cert->contentTypeLen =
  19167. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  19168. }
  19169. break;
  19170. /* A password by which the entity may request certificate revocation.
  19171. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  19172. */
  19173. case CHALLENGE_PASSWORD_OID:
  19174. /* Clear dynamic data and specify choices acceptable. */
  19175. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19176. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19177. /* Parse a string. */
  19178. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19179. 1, input, &idx, maxIdx);
  19180. if (ret == 0) {
  19181. /* Store references to password data. */
  19182. cert->cPwd =
  19183. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19184. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19185. data.ref.length;
  19186. }
  19187. break;
  19188. /* Requested serial number to issue with.
  19189. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  19190. * (References: ISO/IEC 9594-6:1997)
  19191. */
  19192. case SERIAL_NUMBER_OID:
  19193. /* Clear dynamic data and specify choices acceptable. */
  19194. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19195. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19196. /* Parse a string. */
  19197. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19198. 1, input, &idx, maxIdx);
  19199. if (ret == 0) {
  19200. /* Store references to serial number. */
  19201. cert->sNum =
  19202. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19203. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19204. data.ref.length;
  19205. /* Store serial number if small enough. */
  19206. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19207. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  19208. cert->serialSz = cert->sNumLen;
  19209. }
  19210. }
  19211. break;
  19212. /* Certificate extensions to be included in generated certificate.
  19213. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  19214. */
  19215. case EXTENSION_REQUEST_OID:
  19216. /* Store references to all extensions. */
  19217. cert->extensions = input;
  19218. cert->extensionsSz = (int)maxIdx;
  19219. cert->extensionsIdx = aIdx;
  19220. /* Decode and validate extensions. */
  19221. ret = DecodeCertExtensions(cert);
  19222. if (ret == ASN_CRIT_EXT_E) {
  19223. /* Return critical extension not recognized. */
  19224. *criticalExt = ret;
  19225. ret = 0;
  19226. }
  19227. else {
  19228. /* No critical extension error. */
  19229. *criticalExt = 0;
  19230. }
  19231. break;
  19232. default:
  19233. ret = ASN_PARSE_E;
  19234. break;
  19235. }
  19236. return ret;
  19237. }
  19238. /* Decode attributes of a BER encoded certificate request.
  19239. *
  19240. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19241. *
  19242. * Outer sequence has been removed.
  19243. *
  19244. * @param [in] cert Certificate request object.
  19245. * @param [out] criticalExt Critical extension return code.
  19246. * @param [in] idx Index into certificate source to start parsing.
  19247. * @param [in] maxIdx Maximum index to parse to.
  19248. * @return 0 on success.
  19249. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19250. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19251. * is invalid.
  19252. * @return BUFFER_E when data in buffer is too small.
  19253. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19254. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19255. * non-zero length.
  19256. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19257. */
  19258. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  19259. word32 idx, word32 maxIdx)
  19260. {
  19261. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  19262. int ret = 0;
  19263. WOLFSSL_ENTER("DecodeCertReqAttributes");
  19264. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  19265. /* Parse each attribute until all data used up. */
  19266. while ((ret == 0) && (idx < maxIdx)) {
  19267. /* Clear dynamic data. */
  19268. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  19269. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  19270. /* Parse an attribute. */
  19271. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  19272. cert->source, &idx, maxIdx);
  19273. /* idx is now at end of attribute data. */
  19274. if (ret == 0) {
  19275. ret = DecodeCertReqAttrValue(cert, criticalExt,
  19276. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  19277. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  19278. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  19279. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  19280. }
  19281. }
  19282. FREE_ASNGETDATA(dataASN, cert->heap);
  19283. return ret;
  19284. }
  19285. /* ASN.1 template for a certificate request.
  19286. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  19287. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  19288. */
  19289. static const ASNItem certReqASN[] = {
  19290. /* CertificationRequest */
  19291. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19292. /* CertificationRequestInfo */
  19293. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19294. /* version INTEGER { v1(0), v2(1), v3(2) */
  19295. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  19296. /* subject Name */
  19297. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  19298. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  19299. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19300. /* algorithm AlgorithmIdentifier */
  19301. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  19302. /* Algorithm OBJECT IDENTIFIER */
  19303. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  19304. /* parameters ANY defined by algorithm OPTIONAL */
  19305. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  19306. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  19307. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  19308. /* subjectPublicKey BIT STRING */
  19309. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  19310. /* attributes [0] Attributes */
  19311. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  19312. /* signatureAlgorithm AlgorithmIdentifier */
  19313. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19314. /* Algorithm OBJECT IDENTIFIER */
  19315. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  19316. /* parameters ANY defined by algorithm OPTIONAL */
  19317. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  19318. /* signature BIT STRING */
  19319. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19320. };
  19321. enum {
  19322. CERTREQASN_IDX_SEQ = 0,
  19323. CERTREQASN_IDX_INFO_SEQ,
  19324. CERTREQASN_IDX_INFO_VER,
  19325. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  19326. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  19327. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  19328. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  19329. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  19330. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  19331. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  19332. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  19333. CERTREQASN_IDX_INFO_ATTRS,
  19334. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  19335. CERTREQASN_IDX_INFO_SIGALGO_OID,
  19336. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  19337. CERTREQASN_IDX_INFO_SIGNATURE
  19338. };
  19339. /* Number of items in ASN.1 template for a certificate request. */
  19340. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  19341. /* Parse BER encoded certificate request.
  19342. *
  19343. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19344. *
  19345. * @param [in] cert Certificate request object.
  19346. * @param [out] criticalExt Critical extension return code.
  19347. * @return 0 on success.
  19348. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19349. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19350. * is invalid.
  19351. * @return BUFFER_E when data in buffer is too small.
  19352. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19353. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19354. * non-zero length.
  19355. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19356. * @return MEMORY_E on dynamic memory allocation failure.
  19357. */
  19358. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  19359. {
  19360. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  19361. int ret = 0;
  19362. byte version;
  19363. word32 idx;
  19364. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  19365. if (ret == 0) {
  19366. /* Default version is 0. */
  19367. version = 0;
  19368. /* Set version var and OID types to expect. */
  19369. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  19370. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19371. oidKeyType);
  19372. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19373. oidCurveType);
  19374. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19375. /* Parse a certificate request. */
  19376. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  19377. cert->source, &cert->srcIdx, cert->maxIdx);
  19378. }
  19379. /* Check version is valid/supported - can't be negative. */
  19380. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  19381. WOLFSSL_MSG("Unexpected certificate request version");
  19382. ret = ASN_PARSE_E;
  19383. }
  19384. if (ret == 0) {
  19385. /* Set fields of certificate request. */
  19386. cert->version = version;
  19387. cert->signatureOID =
  19388. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19389. cert->keyOID =
  19390. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  19391. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  19392. /* Parse the subject name. */
  19393. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  19394. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19395. cert->source, &idx,
  19396. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  19397. }
  19398. if (ret == 0) {
  19399. /* Parse the certificate request Attributes. */
  19400. ret = DecodeCertReqAttributes(cert, criticalExt,
  19401. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  19402. cert->source),
  19403. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  19404. }
  19405. if (ret == 0) {
  19406. /* Parse the certificate request's key. */
  19407. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  19408. ret = GetCertKey(cert, cert->source, &idx,
  19409. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  19410. }
  19411. if (ret == 0) {
  19412. /* Store references to signature. */
  19413. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  19414. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  19415. &cert->signature, &cert->sigLength);
  19416. }
  19417. FREE_ASNGETDATA(dataASN, cert->heap);
  19418. return ret;
  19419. }
  19420. #endif /* WOLFSSL_CERT_REQ */
  19421. #endif
  19422. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19423. {
  19424. int ret;
  19425. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19426. defined(WOLFSSL_DYN_CERT)
  19427. char* ptr;
  19428. #endif
  19429. ret = ParseCertRelative(cert, type, verify, cm);
  19430. if (ret < 0)
  19431. return ret;
  19432. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19433. defined(WOLFSSL_DYN_CERT)
  19434. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
  19435. if (cert->subjectCNLen > 0) {
  19436. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  19437. DYNAMIC_TYPE_SUBJECT_CN);
  19438. if (ptr == NULL)
  19439. return MEMORY_E;
  19440. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  19441. ptr[cert->subjectCNLen] = '\0';
  19442. cert->subjectCN = ptr;
  19443. cert->subjectCNStored = 1;
  19444. }
  19445. #endif
  19446. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19447. defined(WOLFSSL_DYN_CERT)
  19448. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  19449. if ((cert->keyOID == RSAk
  19450. #ifdef WC_RSA_PSS
  19451. || cert->keyOID == RSAPSSk
  19452. #endif
  19453. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  19454. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  19455. DYNAMIC_TYPE_PUBLIC_KEY);
  19456. if (ptr == NULL)
  19457. return MEMORY_E;
  19458. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  19459. cert->publicKey = (byte *)ptr;
  19460. cert->pubKeyStored = 1;
  19461. }
  19462. #endif
  19463. return ret;
  19464. }
  19465. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19466. {
  19467. return ParseCert(cert, type, verify, cm);
  19468. }
  19469. #ifdef WOLFCRYPT_ONLY
  19470. /* dummy functions, not using wolfSSL so don't need actual ones */
  19471. Signer* GetCA(void* signers, byte* hash);
  19472. Signer* GetCA(void* signers, byte* hash)
  19473. {
  19474. (void)hash;
  19475. return (Signer*)signers;
  19476. }
  19477. #ifndef NO_SKID
  19478. Signer* GetCAByName(void* signers, byte* hash);
  19479. Signer* GetCAByName(void* signers, byte* hash)
  19480. {
  19481. (void)hash;
  19482. return (Signer*)signers;
  19483. }
  19484. #endif /* NO_SKID */
  19485. #ifdef WOLFSSL_AKID_NAME
  19486. Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
  19487. const byte* serial, word32 serialSz);
  19488. Signer* GetCAByAKID(void* vp, const byte* issuer, word32 issuerSz,
  19489. const byte* serial, word32 serialSz)
  19490. {
  19491. (void)issuer;
  19492. (void)issuerSz;
  19493. (void)serial;
  19494. (void)serialSz;
  19495. return (Signer*)vp;
  19496. }
  19497. #endif
  19498. #endif /* WOLFCRYPT_ONLY */
  19499. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  19500. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  19501. {
  19502. Signer* ca = NULL;
  19503. if (cert->extSubjKeyIdSet)
  19504. ca = GetCA(cm, cert->extSubjKeyId);
  19505. if (ca == NULL)
  19506. ca = GetCAByName(cm, cert->subjectHash);
  19507. if (ca) {
  19508. if ((ca->pubKeySize == cert->pubKeySize) &&
  19509. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  19510. return ca;
  19511. }
  19512. }
  19513. return NULL;
  19514. }
  19515. #endif
  19516. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  19517. #ifdef WOLFSSL_ASN_TEMPLATE
  19518. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  19519. *
  19520. * @param [in] input Input data.
  19521. * @param [in] maxIdx Maximum index for data.
  19522. * @param [in] sigOID Signature OID for determining hash algorithm.
  19523. * @param [out] hash Hash of AKI.
  19524. * @param [out] set Whether the hash buffer was set.
  19525. * @param [in] heap Dynamic memory allocation hint.
  19526. * @return 0 on success.
  19527. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19528. * is invalid.
  19529. * @return MEMORY_E on dynamic memory allocation failure.
  19530. */
  19531. static int GetAKIHash(const byte* input, word32 maxIdx, word32 sigOID,
  19532. byte* hash, int* set, void* heap)
  19533. {
  19534. /* AKI and Certificate Extenion ASN.1 templates are the same length. */
  19535. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  19536. int ret = 0;
  19537. word32 idx = 0;
  19538. word32 extEndIdx;
  19539. byte* extData;
  19540. word32 extDataSz;
  19541. byte critical;
  19542. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  19543. (void)heap;
  19544. extEndIdx = idx + maxIdx;
  19545. /* Step through each extension looking for AKI. */
  19546. while ((ret == 0) && (idx < extEndIdx)) {
  19547. /* Clear dynamic data and check for certificate extension type OIDs. */
  19548. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  19549. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  19550. /* Set criticality variable. */
  19551. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  19552. /* Parse an extension. */
  19553. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  19554. &idx, extEndIdx);
  19555. if (ret == 0) {
  19556. /* Get reference to extension data and move index on past this
  19557. * extension. */
  19558. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  19559. idx += extDataSz;
  19560. /* Check whether we have the AKI extension. */
  19561. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  19562. /* Clear dynamic data. */
  19563. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  19564. /* Start parsing extension data from the start. */
  19565. idx = 0;
  19566. /* Parse AKI extension data. */
  19567. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  19568. 1, extData, &idx, extDataSz);
  19569. if ((ret == 0) &&
  19570. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  19571. != NULL)) {
  19572. /* We parsed successfully and have data. */
  19573. *set = 1;
  19574. /* Get the hash or hash of the hash if wrong size. */
  19575. ret = GetHashId(
  19576. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  19577. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  19578. hash, HashIdAlg(sigOID));
  19579. }
  19580. break;
  19581. }
  19582. }
  19583. }
  19584. FREE_ASNGETDATA(dataASN, heap);
  19585. return ret;
  19586. }
  19587. #endif
  19588. /* Only quick step through the certificate to find fields that are then used
  19589. * in certificate signature verification.
  19590. * Must use the signature OID from the signed part of the certificate.
  19591. * Works also on certificate signing requests.
  19592. *
  19593. * This is only for minimizing dynamic memory usage during TLS certificate
  19594. * chain processing.
  19595. * Doesn't support:
  19596. * OCSP Only: alt lookup using subject and pub key w/o sig check
  19597. */
  19598. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  19599. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  19600. {
  19601. #ifndef WOLFSSL_ASN_TEMPLATE
  19602. #ifndef WOLFSSL_SMALL_STACK
  19603. SignatureCtx sigCtx[1];
  19604. #else
  19605. SignatureCtx* sigCtx;
  19606. #endif
  19607. byte hash[KEYID_SIZE];
  19608. Signer* ca = NULL;
  19609. word32 idx = 0;
  19610. int len;
  19611. word32 tbsCertIdx = 0;
  19612. word32 sigIndex = 0;
  19613. word32 signatureOID = 0;
  19614. word32 oid = 0;
  19615. word32 issuerIdx = 0;
  19616. word32 issuerSz = 0;
  19617. #ifndef NO_SKID
  19618. int extLen = 0;
  19619. word32 extIdx = 0;
  19620. word32 extEndIdx = 0;
  19621. int extAuthKeyIdSet = 0;
  19622. #endif
  19623. int ret = 0;
  19624. word32 localIdx;
  19625. byte tag;
  19626. const byte* sigParams = NULL;
  19627. word32 sigParamsSz = 0;
  19628. if (cert == NULL) {
  19629. return BAD_FUNC_ARG;
  19630. }
  19631. #ifdef WOLFSSL_SMALL_STACK
  19632. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  19633. if (sigCtx == NULL)
  19634. return MEMORY_E;
  19635. #endif
  19636. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19637. /* Certificate SEQUENCE */
  19638. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19639. ret = ASN_PARSE_E;
  19640. if (ret == 0) {
  19641. tbsCertIdx = idx;
  19642. /* TBSCertificate SEQUENCE */
  19643. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19644. ret = ASN_PARSE_E;
  19645. }
  19646. if (ret == 0) {
  19647. sigIndex = len + idx;
  19648. if ((idx + 1) > certSz)
  19649. ret = BUFFER_E;
  19650. }
  19651. if (ret == 0) {
  19652. /* version - optional */
  19653. localIdx = idx;
  19654. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19655. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19656. idx++;
  19657. if (GetLength(cert, &idx, &len, certSz) < 0)
  19658. ret = ASN_PARSE_E;
  19659. idx += len;
  19660. }
  19661. }
  19662. }
  19663. if (ret == 0) {
  19664. /* serialNumber */
  19665. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19666. ret = ASN_PARSE_E;
  19667. }
  19668. if (ret == 0) {
  19669. idx += len;
  19670. /* signature */
  19671. if (!req) {
  19672. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  19673. ret = ASN_PARSE_E;
  19674. #ifdef WC_RSA_PSS
  19675. else if (signatureOID == CTC_RSASSAPSS) {
  19676. int start = idx;
  19677. sigParams = cert + idx;
  19678. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19679. ret = ASN_PARSE_E;
  19680. if (ret == 0) {
  19681. idx += len;
  19682. sigParamsSz = idx - start;
  19683. }
  19684. }
  19685. #endif
  19686. }
  19687. }
  19688. if (ret == 0) {
  19689. issuerIdx = idx;
  19690. /* issuer for cert or subject for csr */
  19691. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19692. ret = ASN_PARSE_E;
  19693. }
  19694. if (ret == 0) {
  19695. issuerSz = len + idx - issuerIdx;
  19696. }
  19697. #ifndef NO_SKID
  19698. if (!req && ret == 0) {
  19699. idx += len;
  19700. /* validity */
  19701. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19702. ret = ASN_PARSE_E;
  19703. }
  19704. if (!req && ret == 0) {
  19705. idx += len;
  19706. /* subject */
  19707. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19708. ret = ASN_PARSE_E;
  19709. }
  19710. if (ret == 0) {
  19711. idx += len;
  19712. /* subjectPublicKeyInfo */
  19713. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19714. ret = ASN_PARSE_E;
  19715. }
  19716. if (req && ret == 0) {
  19717. idx += len;
  19718. /* attributes */
  19719. if (GetASNHeader_ex(cert,
  19720. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  19721. &len, certSz, 1) < 0)
  19722. ret = ASN_PARSE_E;
  19723. }
  19724. if (!req) {
  19725. if (ret == 0) {
  19726. idx += len;
  19727. if ((idx + 1) > certSz)
  19728. ret = BUFFER_E;
  19729. }
  19730. if (ret == 0) {
  19731. /* issuerUniqueID - optional */
  19732. localIdx = idx;
  19733. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19734. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  19735. idx++;
  19736. if (GetLength(cert, &idx, &len, certSz) < 0)
  19737. ret = ASN_PARSE_E;
  19738. idx += len;
  19739. }
  19740. }
  19741. }
  19742. if (ret == 0) {
  19743. if ((idx + 1) > certSz)
  19744. ret = BUFFER_E;
  19745. }
  19746. if (ret == 0) {
  19747. /* subjectUniqueID - optional */
  19748. localIdx = idx;
  19749. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19750. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  19751. idx++;
  19752. if (GetLength(cert, &idx, &len, certSz) < 0)
  19753. ret = ASN_PARSE_E;
  19754. idx += len;
  19755. }
  19756. }
  19757. }
  19758. if (ret == 0) {
  19759. if ((idx + 1) > certSz)
  19760. ret = BUFFER_E;
  19761. }
  19762. /* extensions - optional */
  19763. localIdx = idx;
  19764. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19765. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  19766. idx++;
  19767. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  19768. ret = ASN_PARSE_E;
  19769. if (ret == 0) {
  19770. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  19771. ret = ASN_PARSE_E;
  19772. }
  19773. if (ret == 0) {
  19774. extEndIdx = idx + extLen;
  19775. /* Check each extension for the ones we want. */
  19776. while (ret == 0 && idx < extEndIdx) {
  19777. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19778. ret = ASN_PARSE_E;
  19779. if (ret == 0) {
  19780. extIdx = idx;
  19781. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  19782. certSz) < 0) {
  19783. ret = ASN_PARSE_E;
  19784. }
  19785. if (ret == 0) {
  19786. if ((extIdx + 1) > certSz)
  19787. ret = BUFFER_E;
  19788. }
  19789. }
  19790. if (ret == 0) {
  19791. localIdx = extIdx;
  19792. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19793. tag == ASN_BOOLEAN) {
  19794. if (GetBoolean(cert, &extIdx, certSz) < 0)
  19795. ret = ASN_PARSE_E;
  19796. }
  19797. }
  19798. if (ret == 0) {
  19799. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  19800. ret = ASN_PARSE_E;
  19801. }
  19802. if (ret == 0) {
  19803. switch (oid) {
  19804. case AUTH_KEY_OID:
  19805. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  19806. ret = ASN_PARSE_E;
  19807. if (ret == 0 && (extIdx + 1) >= certSz)
  19808. ret = BUFFER_E;
  19809. if (ret == 0 &&
  19810. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  19811. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  19812. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  19813. ret = ASN_PARSE_E;
  19814. if (ret == 0) {
  19815. extAuthKeyIdSet = 1;
  19816. /* Get the hash or hash of the hash if wrong
  19817. * size. */
  19818. ret = GetHashId(cert + extIdx, extLen,
  19819. hash, HashIdAlg(signatureOID));
  19820. }
  19821. }
  19822. break;
  19823. default:
  19824. break;
  19825. }
  19826. }
  19827. idx += len;
  19828. }
  19829. }
  19830. }
  19831. }
  19832. else if (ret == 0) {
  19833. idx += len;
  19834. }
  19835. if (ret == 0 && pubKey == NULL) {
  19836. if (extAuthKeyIdSet)
  19837. ca = GetCA(cm, hash);
  19838. if (ca == NULL) {
  19839. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  19840. HashIdAlg(signatureOID));
  19841. if (ret == 0)
  19842. ca = GetCAByName(cm, hash);
  19843. }
  19844. }
  19845. #else
  19846. if (ret == 0 && pubKey == NULL) {
  19847. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  19848. HashIdAlg(signatureOID));
  19849. if (ret == 0)
  19850. ca = GetCA(cm, hash);
  19851. }
  19852. #endif /* !NO_SKID */
  19853. if (ca == NULL && pubKey == NULL)
  19854. ret = ASN_NO_SIGNER_E;
  19855. if (ret == 0) {
  19856. idx = sigIndex;
  19857. /* signatureAlgorithm */
  19858. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  19859. ret = ASN_PARSE_E;
  19860. #ifdef WC_RSA_PSS
  19861. else if (signatureOID == CTC_RSASSAPSS) {
  19862. word32 sz = idx;
  19863. const byte* params = cert + idx;
  19864. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19865. ret = ASN_PARSE_E;
  19866. if (ret == 0) {
  19867. idx += len;
  19868. sz = idx - sz;
  19869. if (req) {
  19870. if ((sz != sigParamsSz) ||
  19871. (XMEMCMP(sigParams, params, sz) != 0)) {
  19872. ret = ASN_PARSE_E;
  19873. }
  19874. }
  19875. else {
  19876. sigParams = params;
  19877. sigParamsSz = sz;
  19878. }
  19879. }
  19880. }
  19881. #endif
  19882. /* In CSR signature data is not present in body */
  19883. if (req)
  19884. signatureOID = oid;
  19885. }
  19886. if (ret == 0) {
  19887. if (oid != signatureOID)
  19888. ret = ASN_SIG_OID_E;
  19889. }
  19890. if (ret == 0) {
  19891. /* signatureValue */
  19892. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  19893. ret = ASN_PARSE_E;
  19894. }
  19895. if (ret == 0) {
  19896. if (pubKey != NULL) {
  19897. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19898. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  19899. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  19900. }
  19901. else {
  19902. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19903. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  19904. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  19905. sigParamsSz, NULL);
  19906. }
  19907. if (ret != 0) {
  19908. WOLFSSL_ERROR_VERBOSE(ret);
  19909. WOLFSSL_MSG("Confirm signature failed");
  19910. }
  19911. }
  19912. FreeSignatureCtx(sigCtx);
  19913. #ifdef WOLFSSL_SMALL_STACK
  19914. if (sigCtx != NULL)
  19915. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19916. #endif
  19917. return ret;
  19918. #else /* WOLFSSL_ASN_TEMPLATE */
  19919. /* X509 ASN.1 template longer than Certificate Request template. */
  19920. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19921. #ifndef WOLFSSL_SMALL_STACK
  19922. SignatureCtx sigCtx[1];
  19923. #else
  19924. SignatureCtx* sigCtx = NULL;
  19925. #endif
  19926. byte hash[KEYID_SIZE];
  19927. Signer* ca = NULL;
  19928. int ret = 0;
  19929. word32 idx = 0;
  19930. #ifndef NO_SKID
  19931. int extAuthKeyIdSet = 0;
  19932. #endif
  19933. const byte* tbs = NULL;
  19934. word32 tbsSz = 0;
  19935. #ifdef WC_RSA_PSS
  19936. const byte* tbsParams = NULL;
  19937. word32 tbsParamsSz = 0;
  19938. #endif
  19939. const byte* sig = NULL;
  19940. word32 sigSz = 0;
  19941. word32 sigOID = 0;
  19942. const byte* sigParams = NULL;
  19943. word32 sigParamsSz = 0;
  19944. const byte* caName = NULL;
  19945. word32 caNameLen = 0;
  19946. #ifndef NO_SKID
  19947. const byte* akiData = NULL;
  19948. word32 akiLen = 0;
  19949. #endif
  19950. (void)req;
  19951. (void)heap;
  19952. if (cert == NULL) {
  19953. ret = BAD_FUNC_ARG;
  19954. }
  19955. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  19956. if ((ret == 0) && (!req)) {
  19957. /* Clear dynamic data for certificate items. */
  19958. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  19959. /* Set OID types expected for signature and public key. */
  19960. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19961. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19962. oidKeyType);
  19963. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19964. oidCurveType);
  19965. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19966. /* Parse certificate. */
  19967. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  19968. &idx, certSz);
  19969. /* Check signature OIDs match. */
  19970. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  19971. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  19972. ret = ASN_SIG_OID_E;
  19973. }
  19974. /* Store the data for verification in the certificate. */
  19975. if (ret == 0) {
  19976. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19977. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19978. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19979. cert);
  19980. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19981. cert);
  19982. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19983. #ifdef WC_RSA_PSS
  19984. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  19985. tbsParams =
  19986. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19987. cert);
  19988. tbsParamsSz =
  19989. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19990. cert);
  19991. }
  19992. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19993. sigParams =
  19994. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19995. cert);
  19996. sigParamsSz =
  19997. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19998. cert);
  19999. }
  20000. #endif
  20001. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  20002. #ifdef WC_RSA_PSS
  20003. if (tbsParamsSz != sigParamsSz) {
  20004. ret = ASN_PARSE_E;
  20005. }
  20006. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  20007. ret = ASN_PARSE_E;
  20008. }
  20009. else if ((tbsParamsSz > 0) &&
  20010. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  20011. ret = ASN_PARSE_E;
  20012. }
  20013. #endif
  20014. }
  20015. }
  20016. else if (ret == 0) {
  20017. #ifndef WOLFSSL_CERT_REQ
  20018. ret = NOT_COMPILED_IN;
  20019. #else
  20020. /* Clear dynamic data for certificate request items. */
  20021. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  20022. /* Set OID types expected for signature and public key. */
  20023. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  20024. oidKeyType);
  20025. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  20026. oidCurveType);
  20027. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  20028. /* Parse certificate request. */
  20029. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  20030. &idx, certSz);
  20031. if (ret == 0) {
  20032. /* Store the data for verification in the certificate. */
  20033. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  20034. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  20035. caName = GetASNItem_Addr(
  20036. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20037. caNameLen = GetASNItem_Length(
  20038. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20039. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  20040. #ifdef WC_RSA_PSS
  20041. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20042. cert);
  20043. sigParamsSz =
  20044. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20045. cert);
  20046. #endif
  20047. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  20048. &sigSz);
  20049. }
  20050. #endif
  20051. }
  20052. #ifndef NO_SKID
  20053. if ((ret == 0) && (pubKey == NULL) && !req) {
  20054. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  20055. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  20056. }
  20057. #endif
  20058. FREE_ASNGETDATA(dataASN, heap);
  20059. /* If no public passed, then find the CA. */
  20060. if ((ret == 0) && (pubKey == NULL)) {
  20061. #ifndef NO_SKID
  20062. /* Find the AKI extension in list of extensions and get hash. */
  20063. if ((!req) && (akiData != NULL)) {
  20064. /* TODO: test case */
  20065. ret = GetAKIHash(akiData, akiLen, sigOID, hash, &extAuthKeyIdSet,
  20066. heap);
  20067. }
  20068. /* Get the CA by hash one was found. */
  20069. if (extAuthKeyIdSet) {
  20070. ca = GetCA(cm, hash);
  20071. }
  20072. if (ca == NULL)
  20073. #endif
  20074. {
  20075. /* Try hash of issuer name. */
  20076. ret = CalcHashId_ex(caName, caNameLen, hash, HashIdAlg(sigOID));
  20077. if (ret == 0) {
  20078. ca = GetCAByName(cm, hash);
  20079. }
  20080. }
  20081. if (ca != NULL) {
  20082. /* Extract public key information. */
  20083. pubKey = ca->publicKey;
  20084. pubKeySz = ca->pubKeySize;
  20085. pubKeyOID = (int)ca->keyOID;
  20086. }
  20087. else {
  20088. /* No public key to verify with. */
  20089. ret = ASN_NO_SIGNER_E;
  20090. }
  20091. }
  20092. if (ret == 0) {
  20093. #ifdef WOLFSSL_SMALL_STACK
  20094. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  20095. DYNAMIC_TYPE_SIGNATURE);
  20096. if (sigCtx == NULL) {
  20097. ret = MEMORY_E;
  20098. }
  20099. if (ret == 0)
  20100. #endif
  20101. {
  20102. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  20103. /* Check signature. */
  20104. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  20105. (word32)pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz,
  20106. NULL);
  20107. if (ret != 0) {
  20108. WOLFSSL_MSG("Confirm signature failed");
  20109. }
  20110. FreeSignatureCtx(sigCtx);
  20111. #ifdef WOLFSSL_SMALL_STACK
  20112. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  20113. #endif
  20114. }
  20115. }
  20116. return ret;
  20117. #endif /* WOLFSSL_ASN_TEMPLATE */
  20118. }
  20119. #ifdef OPENSSL_EXTRA
  20120. /* Call CheckCertSignature_ex using a public key buffer for verification
  20121. */
  20122. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20123. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20124. {
  20125. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20126. pubKey, pubKeySz, pubKeyOID, 0);
  20127. }
  20128. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  20129. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20130. {
  20131. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  20132. pubKeyOID);
  20133. }
  20134. #ifdef WOLFSSL_CERT_REQ
  20135. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20136. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20137. {
  20138. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20139. pubKey, pubKeySz, pubKeyOID, 1);
  20140. }
  20141. #endif /* WOLFSSL_CERT_REQ */
  20142. #endif /* OPENSSL_EXTRA */
  20143. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  20144. /* Call CheckCertSignature_ex using a certificate manager (cm)
  20145. */
  20146. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  20147. {
  20148. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  20149. }
  20150. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  20151. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  20152. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  20153. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  20154. /* ASN.1 DER decode instruction. */
  20155. typedef struct DecodeInstr {
  20156. /* Tag expected. */
  20157. byte tag;
  20158. /* Operation to perform: step in or go over */
  20159. byte op:1;
  20160. /* ASN.1 item is optional. */
  20161. byte optional:1;
  20162. } DecodeInstr;
  20163. /* Step into ASN.1 item. */
  20164. #define DECODE_INSTR_IN 0
  20165. /* Step over ASN.1 item. */
  20166. #define DECODE_INSTR_OVER 1
  20167. /* Get the public key data from the DER encoded X.509 certificate.
  20168. *
  20169. * Assumes data has previously been parsed for complete validity.
  20170. *
  20171. * @param [in] cert DER encoded X.509 certificate data.
  20172. * @param [in] certSz Length of DER encoding.
  20173. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  20174. * @param [out] pubKeySz Length of public key data in bytes.
  20175. * @return 0 on success.
  20176. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  20177. * @return ASN_PARSE_E when certificate encoding is invalid.
  20178. */
  20179. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  20180. const unsigned char** pubKey, word32* pubKeySz)
  20181. {
  20182. int ret = 0;
  20183. int l;
  20184. word32 o = 0;
  20185. int i;
  20186. static DecodeInstr ops[] = {
  20187. /* Outer SEQ */
  20188. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20189. /* TBSCertificate: SEQ */
  20190. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20191. /* Version: [0] */
  20192. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  20193. DECODE_INSTR_OVER, 1 },
  20194. /* CertificateSerialNumber: INT */
  20195. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  20196. /* AlgorithmIdentifier: SEQ */
  20197. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20198. /* issuer: SEQ */
  20199. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20200. /* Validity: SEQ */
  20201. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20202. /* subject: SEQ */
  20203. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20204. /* subjectPublicKeyInfo SEQ */
  20205. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20206. /* AlgorithmIdentifier: SEQ */
  20207. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20208. /* PublicKey: BIT_STRING */
  20209. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  20210. };
  20211. /* Validate parameters. */
  20212. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  20213. ret = BAD_FUNC_ARG;
  20214. }
  20215. /* Process each instruction to take us to public key data. */
  20216. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  20217. DecodeInstr op = ops[i];
  20218. /* Check the current ASN.1 item has the expected tag. */
  20219. if (cert[o] != op.tag) {
  20220. /* If not optional then error, otherwise skip op. */
  20221. if (!op.optional) {
  20222. ret = ASN_PARSE_E;
  20223. }
  20224. }
  20225. else {
  20226. /* Move past tag. */
  20227. o++;
  20228. /* Get the length of ASN.1 item and move past length encoding. */
  20229. if (GetLength(cert, &o, &l, certSz) < 0) {
  20230. ret = ASN_PARSE_E;
  20231. }
  20232. /* Skip data if required. */
  20233. else if (op.op == DECODE_INSTR_OVER) {
  20234. o += (word32)l;
  20235. }
  20236. }
  20237. }
  20238. if (ret == 0) {
  20239. /* Return the public key data and length.
  20240. * Skip first byte of BIT_STRING data: unused bits. */
  20241. *pubKey = cert + o + 1;
  20242. *pubKeySz = (word32)(l - 1);
  20243. }
  20244. return ret;
  20245. }
  20246. #endif
  20247. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  20248. {
  20249. int ret = 0;
  20250. #ifndef WOLFSSL_ASN_TEMPLATE
  20251. word32 confirmOID = 0;
  20252. #ifdef WOLFSSL_CERT_REQ
  20253. int len = 0;
  20254. #endif
  20255. #endif
  20256. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20257. int idx = 0;
  20258. #endif
  20259. byte* sce_tsip_encRsaKeyIdx;
  20260. if (cert == NULL) {
  20261. return BAD_FUNC_ARG;
  20262. }
  20263. #ifdef WOLFSSL_CERT_REQ
  20264. if (type == CERTREQ_TYPE)
  20265. cert->isCSR = 1;
  20266. #endif
  20267. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  20268. #ifndef WOLFSSL_ASN_TEMPLATE
  20269. cert->badDate = 0;
  20270. cert->criticalExt = 0;
  20271. if ((ret = DecodeToKey(cert, verify)) < 0) {
  20272. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20273. cert->badDate = ret;
  20274. if (verify == VERIFY_SKIP_DATE)
  20275. ret = 0;
  20276. }
  20277. else
  20278. return ret;
  20279. }
  20280. WOLFSSL_MSG("Parsed Past Key");
  20281. #ifdef WOLFSSL_CERT_REQ
  20282. /* Read attributes */
  20283. if (cert->isCSR) {
  20284. if (GetASNHeader_ex(cert->source,
  20285. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  20286. &len, cert->maxIdx, 1) < 0) {
  20287. WOLFSSL_MSG("GetASNHeader_ex error");
  20288. return ASN_PARSE_E;
  20289. }
  20290. if (len) {
  20291. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  20292. word32 oid;
  20293. byte tag;
  20294. if (attrMaxIdx > cert->maxIdx) {
  20295. WOLFSSL_MSG("Attribute length greater than CSR length");
  20296. return ASN_PARSE_E;
  20297. }
  20298. while (cert->srcIdx < attrMaxIdx) {
  20299. /* Attributes have the structure:
  20300. * SEQ -> OID -> SET -> ATTRIBUTE */
  20301. if (GetSequence(cert->source, &cert->srcIdx, &len,
  20302. attrMaxIdx) < 0) {
  20303. WOLFSSL_MSG("attr GetSequence error");
  20304. return ASN_PARSE_E;
  20305. }
  20306. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  20307. oidCsrAttrType, attrMaxIdx) < 0) {
  20308. WOLFSSL_MSG("attr GetObjectId error");
  20309. return ASN_PARSE_E;
  20310. }
  20311. if (GetSet(cert->source, &cert->srcIdx, &len,
  20312. attrMaxIdx) < 0) {
  20313. WOLFSSL_MSG("attr GetSet error");
  20314. return ASN_PARSE_E;
  20315. }
  20316. switch (oid) {
  20317. case PKCS9_CONTENT_TYPE_OID:
  20318. if (GetHeader(cert->source, &tag,
  20319. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20320. WOLFSSL_MSG("attr GetHeader error");
  20321. return ASN_PARSE_E;
  20322. }
  20323. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20324. tag != ASN_IA5_STRING) {
  20325. WOLFSSL_MSG("Unsupported attribute value format");
  20326. return ASN_PARSE_E;
  20327. }
  20328. cert->contentType = (char*)cert->source + cert->srcIdx;
  20329. cert->contentTypeLen = len;
  20330. cert->srcIdx += (word32)len;
  20331. break;
  20332. case CHALLENGE_PASSWORD_OID:
  20333. if (GetHeader(cert->source, &tag,
  20334. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20335. WOLFSSL_MSG("attr GetHeader error");
  20336. return ASN_PARSE_E;
  20337. }
  20338. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20339. tag != ASN_IA5_STRING) {
  20340. WOLFSSL_MSG("Unsupported attribute value format");
  20341. return ASN_PARSE_E;
  20342. }
  20343. cert->cPwd = (char*)cert->source + cert->srcIdx;
  20344. cert->cPwdLen = len;
  20345. cert->srcIdx += (word32)len;
  20346. break;
  20347. case SERIAL_NUMBER_OID:
  20348. if (GetHeader(cert->source, &tag,
  20349. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20350. WOLFSSL_MSG("attr GetHeader error");
  20351. return ASN_PARSE_E;
  20352. }
  20353. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20354. tag != ASN_IA5_STRING) {
  20355. WOLFSSL_MSG("Unsupported attribute value format");
  20356. return ASN_PARSE_E;
  20357. }
  20358. cert->sNum = (char*)cert->source + cert->srcIdx;
  20359. cert->sNumLen = len;
  20360. cert->srcIdx += (word32)len;
  20361. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  20362. XMEMCPY(cert->serial, cert->sNum,
  20363. (size_t)cert->sNumLen);
  20364. cert->serialSz = cert->sNumLen;
  20365. }
  20366. break;
  20367. case DNQUALIFIER_OID:
  20368. if (GetHeader(cert->source, &tag,
  20369. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20370. WOLFSSL_MSG("attr GetHeader error");
  20371. return ASN_PARSE_E;
  20372. }
  20373. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  20374. cert->dnQualifierLen = len;
  20375. cert->srcIdx += (word32)len;
  20376. break;
  20377. case INITIALS_OID:
  20378. if (GetHeader(cert->source, &tag,
  20379. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20380. WOLFSSL_MSG("attr GetHeader error");
  20381. return ASN_PARSE_E;
  20382. }
  20383. cert->initials = (char*)cert->source + cert->srcIdx;
  20384. cert->initialsLen = len;
  20385. cert->srcIdx += (word32)len;
  20386. break;
  20387. case SURNAME_OID:
  20388. if (GetHeader(cert->source, &tag,
  20389. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20390. WOLFSSL_MSG("attr GetHeader error");
  20391. return ASN_PARSE_E;
  20392. }
  20393. cert->surname = (char*)cert->source + cert->srcIdx;
  20394. cert->surnameLen = len;
  20395. cert->srcIdx += (word32)len;
  20396. break;
  20397. case GIVEN_NAME_OID:
  20398. if (GetHeader(cert->source, &tag,
  20399. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20400. WOLFSSL_MSG("attr GetHeader error");
  20401. return ASN_PARSE_E;
  20402. }
  20403. cert->givenName = (char*)cert->source + cert->srcIdx;
  20404. cert->givenNameLen = len;
  20405. cert->srcIdx += (word32)len;
  20406. break;
  20407. case UNSTRUCTURED_NAME_OID:
  20408. if (GetHeader(cert->source, &tag,
  20409. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20410. WOLFSSL_MSG("attr GetHeader error");
  20411. return ASN_PARSE_E;
  20412. }
  20413. cert->unstructuredName =
  20414. (char*)cert->source + cert->srcIdx;
  20415. cert->unstructuredNameLen = len;
  20416. cert->srcIdx += (word32)len;
  20417. break;
  20418. case EXTENSION_REQUEST_OID:
  20419. /* save extensions */
  20420. cert->extensions = &cert->source[cert->srcIdx];
  20421. cert->extensionsSz = len;
  20422. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20423. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20424. if (ret == ASN_CRIT_EXT_E) {
  20425. cert->criticalExt = ret;
  20426. }
  20427. else {
  20428. return ret;
  20429. }
  20430. }
  20431. cert->srcIdx += (word32)len;
  20432. break;
  20433. default:
  20434. WOLFSSL_MSG("Unsupported attribute type");
  20435. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20436. return ASN_PARSE_E;
  20437. }
  20438. }
  20439. }
  20440. }
  20441. #endif
  20442. if (cert->srcIdx < cert->sigIndex) {
  20443. #ifndef ALLOW_V1_EXTENSIONS
  20444. if (cert->version < 2) {
  20445. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  20446. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  20447. return ASN_VERSION_E;
  20448. }
  20449. #endif
  20450. /* save extensions */
  20451. cert->extensions = &cert->source[cert->srcIdx];
  20452. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  20453. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20454. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20455. if (ret == ASN_CRIT_EXT_E)
  20456. cert->criticalExt = ret;
  20457. else
  20458. return ret;
  20459. }
  20460. #ifdef HAVE_OCSP
  20461. if (verify == VERIFY_OCSP_CERT) {
  20462. /* trust for the lifetime of the responder's cert*/
  20463. if (cert->ocspNoCheckSet)
  20464. verify = VERIFY;
  20465. else
  20466. verify = VERIFY_OCSP;
  20467. }
  20468. #endif
  20469. /* advance past extensions */
  20470. cert->srcIdx = cert->sigIndex;
  20471. }
  20472. if ((ret = GetSigAlg(cert,
  20473. #ifdef WOLFSSL_CERT_REQ
  20474. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  20475. #else
  20476. &confirmOID,
  20477. #endif
  20478. cert->maxIdx)) < 0) {
  20479. return ret;
  20480. }
  20481. if ((ret = GetSignature(cert)) < 0) {
  20482. return ret;
  20483. }
  20484. if (confirmOID != cert->signatureOID
  20485. #ifdef WOLFSSL_CERT_REQ
  20486. && !cert->isCSR
  20487. #endif
  20488. ) {
  20489. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  20490. return ASN_SIG_OID_E;
  20491. }
  20492. #else
  20493. #ifdef WOLFSSL_CERT_REQ
  20494. if (cert->isCSR) {
  20495. ret = DecodeCertReq(cert, &cert->criticalExt);
  20496. if (ret < 0) {
  20497. return ret;
  20498. }
  20499. }
  20500. else
  20501. #endif
  20502. {
  20503. ret = DecodeCert(cert, verify, &cert->criticalExt);
  20504. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20505. cert->badDate = ret;
  20506. if (verify == VERIFY_SKIP_DATE)
  20507. ret = 0;
  20508. }
  20509. else if (ret < 0) {
  20510. WOLFSSL_ERROR_VERBOSE(ret);
  20511. return ret;
  20512. }
  20513. }
  20514. #endif
  20515. #ifndef ALLOW_INVALID_CERTSIGN
  20516. /* https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.9
  20517. * If the cA boolean is not asserted, then the keyCertSign bit in the
  20518. * key usage extension MUST NOT be asserted. */
  20519. if (!cert->isCA && cert->extKeyUsageSet &&
  20520. (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  20521. WOLFSSL_ERROR_VERBOSE(KEYUSAGE_E);
  20522. return KEYUSAGE_E;
  20523. }
  20524. #endif
  20525. #ifndef NO_SKID
  20526. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  20527. cert->pubKeySize > 0) {
  20528. if (cert->signatureOID == CTC_SM3wSM2) {
  20529. /* TODO: GmSSL creates IDs this way but whole public key info
  20530. * block should be hashed. */
  20531. ret = CalcHashId_ex(cert->publicKey + cert->pubKeySize - 65, 65,
  20532. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  20533. }
  20534. else {
  20535. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  20536. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  20537. }
  20538. if (ret != 0) {
  20539. WOLFSSL_ERROR_VERBOSE(ret);
  20540. return ret;
  20541. }
  20542. }
  20543. #endif /* !NO_SKID */
  20544. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  20545. type != TRUSTED_PEER_TYPE)) {
  20546. cert->ca = NULL;
  20547. #ifndef NO_SKID
  20548. if (cert->extAuthKeyIdSet) {
  20549. cert->ca = GetCA(cm, cert->extAuthKeyId);
  20550. #ifdef WOLFSSL_AKID_NAME
  20551. if (cert->ca == NULL) {
  20552. cert->ca = GetCAByAKID(cm, cert->extAuthKeyIdIssuer,
  20553. cert->extAuthKeyIdIssuerSz, cert->extAuthKeyIdIssuerSN,
  20554. cert->extAuthKeyIdIssuerSNSz);
  20555. }
  20556. #endif
  20557. }
  20558. if (cert->ca == NULL && cert->extSubjKeyIdSet
  20559. && verify != VERIFY_OCSP) {
  20560. cert->ca = GetCA(cm, cert->extSubjKeyId);
  20561. }
  20562. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  20563. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  20564. cert->ca = NULL;
  20565. }
  20566. if (cert->ca == NULL) {
  20567. cert->ca = GetCAByName(cm, cert->issuerHash);
  20568. /* If AKID is available then this CA doesn't have the public
  20569. * key required */
  20570. if (cert->ca && cert->extAuthKeyIdSet) {
  20571. WOLFSSL_MSG("CA SKID doesn't match AKID");
  20572. cert->ca = NULL;
  20573. }
  20574. }
  20575. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  20576. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  20577. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  20578. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  20579. if (cert->ca) {
  20580. ret = 0; /* success */
  20581. goto exit_pcr;
  20582. }
  20583. }
  20584. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  20585. #else
  20586. cert->ca = GetCA(cm, cert->issuerHash);
  20587. #endif /* !NO_SKID */
  20588. if (cert->ca) {
  20589. WOLFSSL_MSG("CA found");
  20590. }
  20591. }
  20592. /* Set to WOLFSSL_MAX_PATH_LEN by default in InitDecodedCert_ex */
  20593. if (cert->pathLengthSet)
  20594. cert->maxPathLen = cert->pathLength;
  20595. if (!cert->selfSigned) {
  20596. /* Need to perform a pathlen check on anything that will be used
  20597. * to sign certificates later on. Otherwise, pathLen doesn't
  20598. * mean anything.
  20599. * Nothing to check if we don't have the issuer of this cert. */
  20600. if (type != CERT_TYPE && cert->isCA && cert->extKeyUsageSet &&
  20601. (cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0 && cert->ca) {
  20602. if (cert->ca->maxPathLen == 0) {
  20603. /* This cert CAN NOT be used as an intermediate cert. The
  20604. * issuer does not allow it. */
  20605. cert->maxPathLen = 0;
  20606. if (verify != NO_VERIFY) {
  20607. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20608. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20609. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20610. return ASN_PATHLEN_INV_E;
  20611. }
  20612. }
  20613. else {
  20614. cert->maxPathLen = (byte)min(cert->ca->maxPathLen - 1,
  20615. cert->maxPathLen);
  20616. }
  20617. }
  20618. }
  20619. #ifdef HAVE_OCSP
  20620. if (verify != NO_VERIFY && type != CA_TYPE &&
  20621. type != TRUSTED_PEER_TYPE) {
  20622. if (cert->ca) {
  20623. /* Need the CA's public key hash for OCSP */
  20624. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20625. KEYID_SIZE);
  20626. }
  20627. }
  20628. #endif /* HAVE_OCSP */
  20629. }
  20630. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20631. /* prepare for TSIP TLS cert verification API use */
  20632. if (cert->keyOID == RSAk) {
  20633. /* to call TSIP API, it needs keys position info in bytes */
  20634. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20635. cert->pubKeySize,
  20636. &cert->sigCtx.CertAtt.pubkey_n_start,
  20637. &cert->sigCtx.CertAtt.pubkey_n_len,
  20638. &cert->sigCtx.CertAtt.pubkey_e_start,
  20639. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20640. WOLFSSL_MSG("Decoding index from cert failed.");
  20641. return ret;
  20642. }
  20643. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20644. }
  20645. else if (cert->keyOID == ECDSAk) {
  20646. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20647. }
  20648. /* check if we can use TSIP for cert verification */
  20649. /* if the ca is verified as tsip root ca. */
  20650. /* TSIP can only handle 2048 bits(256 byte) key. */
  20651. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20652. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20653. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20654. /* assign memory to encrypted tsip Rsa key index */
  20655. if (!cert->sce_tsip_encRsaKeyIdx)
  20656. cert->sce_tsip_encRsaKeyIdx =
  20657. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20658. cert->heap, DYNAMIC_TYPE_RSA);
  20659. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20660. return MEMORY_E;
  20661. }
  20662. else {
  20663. if (cert->ca) {
  20664. /* TSIP isn't usable */
  20665. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  20666. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  20667. "by TSIP.");
  20668. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  20669. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  20670. "RSA 2048.");
  20671. else
  20672. WOLFSSL_MSG("SCE-TSIP isn't usable");
  20673. }
  20674. cert->sce_tsip_encRsaKeyIdx = NULL;
  20675. }
  20676. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  20677. #else
  20678. sce_tsip_encRsaKeyIdx = NULL;
  20679. #endif
  20680. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  20681. if (cert->ca) {
  20682. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20683. verify == VERIFY_SKIP_DATE) {
  20684. /* try to confirm/verify signature */
  20685. if ((ret = ConfirmSignature(&cert->sigCtx,
  20686. cert->source + cert->certBegin,
  20687. cert->sigIndex - cert->certBegin,
  20688. cert->ca->publicKey, cert->ca->pubKeySize,
  20689. cert->ca->keyOID, cert->signature,
  20690. cert->sigLength, cert->signatureOID,
  20691. #ifdef WC_RSA_PSS
  20692. cert->source + cert->sigParamsIndex,
  20693. cert->sigParamsLength,
  20694. #else
  20695. NULL, 0,
  20696. #endif
  20697. sce_tsip_encRsaKeyIdx)) != 0) {
  20698. if (ret != WC_PENDING_E) {
  20699. WOLFSSL_MSG("Confirm signature failed");
  20700. }
  20701. WOLFSSL_ERROR_VERBOSE(ret);
  20702. return ret;
  20703. }
  20704. }
  20705. #ifndef IGNORE_NAME_CONSTRAINTS
  20706. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20707. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  20708. /* check that this cert's name is permitted by the signer's
  20709. * name constraints */
  20710. if (!ConfirmNameConstraints(cert->ca, cert)) {
  20711. WOLFSSL_MSG("Confirm name constraint failed");
  20712. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  20713. return ASN_NAME_INVALID_E;
  20714. }
  20715. }
  20716. #endif /* IGNORE_NAME_CONSTRAINTS */
  20717. }
  20718. #ifdef WOLFSSL_CERT_REQ
  20719. else if (type == CERTREQ_TYPE) {
  20720. if ((ret = ConfirmSignature(&cert->sigCtx,
  20721. cert->source + cert->certBegin,
  20722. cert->sigIndex - cert->certBegin,
  20723. cert->publicKey, cert->pubKeySize,
  20724. cert->keyOID, cert->signature,
  20725. cert->sigLength, cert->signatureOID,
  20726. #ifdef WC_RSA_PSS
  20727. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  20728. #else
  20729. NULL, 0,
  20730. #endif
  20731. sce_tsip_encRsaKeyIdx)) != 0) {
  20732. if (ret != WC_PENDING_E) {
  20733. WOLFSSL_MSG("Confirm signature failed");
  20734. }
  20735. WOLFSSL_ERROR_VERBOSE(ret);
  20736. return ret;
  20737. }
  20738. }
  20739. #endif
  20740. else {
  20741. /* no signer */
  20742. WOLFSSL_MSG("No CA signer to verify with");
  20743. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  20744. /* ret needs to be self-signer error for Qt compat */
  20745. if (cert->selfSigned) {
  20746. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  20747. return ASN_SELF_SIGNED_E;
  20748. }
  20749. else
  20750. #endif
  20751. {
  20752. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  20753. return ASN_NO_SIGNER_E;
  20754. }
  20755. }
  20756. }
  20757. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20758. exit_pcr:
  20759. #endif
  20760. if (cert->badDate != 0) {
  20761. if (verify != VERIFY_SKIP_DATE) {
  20762. return cert->badDate;
  20763. }
  20764. WOLFSSL_MSG("Date error: Verify option is skipping");
  20765. }
  20766. if (cert->criticalExt != 0)
  20767. return cert->criticalExt;
  20768. return ret;
  20769. }
  20770. /* Create and init an new signer */
  20771. Signer* MakeSigner(void* heap)
  20772. {
  20773. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  20774. DYNAMIC_TYPE_SIGNER);
  20775. if (signer) {
  20776. XMEMSET(signer, 0, sizeof(Signer));
  20777. }
  20778. (void)heap;
  20779. return signer;
  20780. }
  20781. /* Free an individual signer.
  20782. *
  20783. * Used by Certificate Manager.
  20784. *
  20785. * @param [in, out] signer On in, signer object.
  20786. * On out, pointer is no longer valid.
  20787. * @param [in] heap Dynamic memory hint.
  20788. */
  20789. void FreeSigner(Signer* signer, void* heap)
  20790. {
  20791. (void)signer;
  20792. (void)heap;
  20793. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20794. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  20795. #ifndef IGNORE_NAME_CONSTRAINTS
  20796. if (signer->permittedNames)
  20797. FreeNameSubtrees(signer->permittedNames, heap);
  20798. if (signer->excludedNames)
  20799. FreeNameSubtrees(signer->excludedNames, heap);
  20800. #endif
  20801. #ifdef WOLFSSL_SIGNER_DER_CERT
  20802. FreeDer(&signer->derCert);
  20803. #endif
  20804. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  20805. }
  20806. /* Free the whole singer table with number of rows.
  20807. *
  20808. * Each table entry is a linked list of signers.
  20809. * Used by Certificate Manager.
  20810. *
  20811. * @param [in, out] table Array of signer objects.
  20812. * @param [in] rows Number of entries in table.
  20813. * @param [in] heap Dynamic memory hint.
  20814. */
  20815. void FreeSignerTable(Signer** table, int rows, void* heap)
  20816. {
  20817. int i;
  20818. for (i = 0; i < rows; i++) {
  20819. Signer* signer = table[i];
  20820. while (signer) {
  20821. Signer* next = signer->next;
  20822. FreeSigner(signer, heap);
  20823. signer = next;
  20824. }
  20825. table[i] = NULL;
  20826. }
  20827. }
  20828. #ifdef WOLFSSL_TRUST_PEER_CERT
  20829. /* Free an individual trusted peer cert.
  20830. *
  20831. * @param [in, out] tp Trusted peer certificate object.
  20832. * @param [in] heap Dynamic memory hint.
  20833. */
  20834. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  20835. {
  20836. if (tp == NULL) {
  20837. return;
  20838. }
  20839. if (tp->name) {
  20840. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20841. }
  20842. if (tp->sig) {
  20843. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  20844. }
  20845. #ifndef IGNORE_NAME_CONSTRAINTS
  20846. if (tp->permittedNames)
  20847. FreeNameSubtrees(tp->permittedNames, heap);
  20848. if (tp->excludedNames)
  20849. FreeNameSubtrees(tp->excludedNames, heap);
  20850. #endif
  20851. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  20852. (void)heap;
  20853. }
  20854. /* Free the whole Trusted Peer linked list.
  20855. *
  20856. * Each table entry is a linked list of trusted peer certificates.
  20857. * Used by Certificate Manager.
  20858. *
  20859. * @param [in, out] table Array of trusted peer certificate objects.
  20860. * @param [in] rows Number of entries in table.
  20861. * @param [in] heap Dynamic memory hint.
  20862. */
  20863. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  20864. {
  20865. int i;
  20866. for (i = 0; i < rows; i++) {
  20867. TrustedPeerCert* tp = table[i];
  20868. while (tp) {
  20869. TrustedPeerCert* next = tp->next;
  20870. FreeTrustedPeer(tp, heap);
  20871. tp = next;
  20872. }
  20873. table[i] = NULL;
  20874. }
  20875. }
  20876. #endif /* WOLFSSL_TRUST_PEER_CERT */
  20877. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  20878. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  20879. word32 outputSz, int maxSnSz)
  20880. {
  20881. int i;
  20882. int snSzInt = (int)snSz;
  20883. if (sn == NULL || output == NULL || snSzInt < 0)
  20884. return BAD_FUNC_ARG;
  20885. /* remove leading zeros */
  20886. while (snSzInt > 0 && sn[0] == 0) {
  20887. snSzInt--;
  20888. sn++;
  20889. }
  20890. /* RFC 5280 - 4.1.2.2:
  20891. * Serial numbers must be a positive value (and not zero) */
  20892. if (snSzInt == 0) {
  20893. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  20894. return BAD_FUNC_ARG;
  20895. }
  20896. if (sn[0] & 0x80)
  20897. maxSnSz--;
  20898. /* truncate if input is too long */
  20899. if (snSzInt > maxSnSz)
  20900. snSzInt = maxSnSz;
  20901. i = SetASNInt(snSzInt, sn[0], NULL);
  20902. /* truncate if input is too long */
  20903. if (snSzInt > (int)outputSz - i)
  20904. snSzInt = (int)outputSz - i;
  20905. /* sanity check number of bytes to copy */
  20906. if (snSzInt <= 0) {
  20907. return BUFFER_E;
  20908. }
  20909. /* write out ASN.1 Integer */
  20910. (void)SetASNInt(snSzInt, sn[0], output);
  20911. XMEMCPY(output + i, sn, (size_t)snSzInt);
  20912. /* compute final length */
  20913. i += snSzInt;
  20914. return i;
  20915. }
  20916. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20917. #endif /* !NO_CERTS */
  20918. #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \
  20919. (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT))
  20920. int SetMyVersion(word32 version, byte* output, int header)
  20921. {
  20922. int i = 0;
  20923. if (output == NULL)
  20924. return BAD_FUNC_ARG;
  20925. if (header) {
  20926. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  20927. output[i++] = 3;
  20928. }
  20929. output[i++] = ASN_INTEGER;
  20930. output[i++] = 0x01;
  20931. output[i++] = (byte)version;
  20932. return i;
  20933. }
  20934. #endif
  20935. #ifndef WOLFSSL_ASN_TEMPLATE
  20936. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  20937. byte* serial, int* serialSz, word32 maxIdx)
  20938. {
  20939. int result = 0;
  20940. int ret;
  20941. WOLFSSL_ENTER("wc_GetSerialNumber");
  20942. if (serial == NULL || input == NULL || serialSz == NULL) {
  20943. return BAD_FUNC_ARG;
  20944. }
  20945. /* First byte is ASN type */
  20946. if ((*inOutIdx+1) > maxIdx) {
  20947. WOLFSSL_MSG("Bad idx first");
  20948. return BUFFER_E;
  20949. }
  20950. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  20951. if (ret != 0)
  20952. return ret;
  20953. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  20954. WOLFSSL_MSG("Serial size bad");
  20955. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20956. return ASN_PARSE_E;
  20957. }
  20958. /* return serial */
  20959. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  20960. *inOutIdx += (word32)*serialSz;
  20961. return result;
  20962. }
  20963. #endif
  20964. #ifndef NO_CERTS
  20965. /* TODO: consider moving PEM code out to a different file. */
  20966. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20967. {
  20968. int ret = BAD_FUNC_ARG;
  20969. if (pDer) {
  20970. int dynType = 0;
  20971. DerBuffer* der;
  20972. /* Determine dynamic type */
  20973. switch (type) {
  20974. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  20975. case CHAIN_CERT_TYPE:
  20976. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  20977. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  20978. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  20979. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  20980. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  20981. default: dynType = DYNAMIC_TYPE_KEY; break;
  20982. }
  20983. /* Setup new buffer */
  20984. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  20985. if (*pDer == NULL) {
  20986. return MEMORY_E;
  20987. }
  20988. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  20989. der = *pDer;
  20990. der->type = type;
  20991. der->dynType = dynType; /* Cache this for FreeDer */
  20992. der->heap = heap;
  20993. der->buffer = (byte*)der + sizeof(DerBuffer);
  20994. der->length = length;
  20995. ret = 0; /* Success */
  20996. }
  20997. return ret;
  20998. }
  20999. void FreeDer(DerBuffer** pDer)
  21000. {
  21001. if (pDer && *pDer)
  21002. {
  21003. DerBuffer* der = (DerBuffer*)*pDer;
  21004. /* ForceZero private keys */
  21005. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  21006. ForceZero(der->buffer, der->length);
  21007. }
  21008. der->buffer = NULL;
  21009. der->length = 0;
  21010. XFREE(der, der->heap, der->dynType);
  21011. *pDer = NULL;
  21012. }
  21013. }
  21014. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  21015. {
  21016. return AllocDer(pDer, length, type, heap);
  21017. }
  21018. void wc_FreeDer(DerBuffer** pDer)
  21019. {
  21020. FreeDer(pDer);
  21021. }
  21022. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  21023. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  21024. updated to reflect maximum length and pem_struct_min_sz
  21025. to reflect minimum size */
  21026. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  21027. wcchar END_CERT = "-----END CERTIFICATE-----";
  21028. #ifdef WOLFSSL_CERT_REQ
  21029. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  21030. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  21031. #endif
  21032. #ifndef NO_DH
  21033. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  21034. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  21035. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  21036. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  21037. #endif
  21038. #ifndef NO_DSA
  21039. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  21040. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  21041. #endif
  21042. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  21043. wcchar END_X509_CRL = "-----END X509 CRL-----";
  21044. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  21045. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  21046. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  21047. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  21048. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  21049. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  21050. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  21051. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  21052. #ifdef HAVE_ECC
  21053. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  21054. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  21055. #ifdef OPENSSL_EXTRA
  21056. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  21057. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  21058. #endif
  21059. #endif
  21060. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21061. !defined(NO_DSA)
  21062. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  21063. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  21064. #endif
  21065. #ifdef OPENSSL_EXTRA
  21066. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  21067. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  21068. const char END_PRIV_KEY_PREFIX[] = "-----END";
  21069. #endif
  21070. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  21071. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  21072. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21073. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  21074. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  21075. #endif
  21076. #if defined(HAVE_PQC)
  21077. #if defined(HAVE_FALCON)
  21078. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  21079. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  21080. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  21081. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  21082. #endif /* HAVE_FALCON */
  21083. #if defined(HAVE_DILITHIUM)
  21084. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21085. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21086. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21087. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21088. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21089. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21090. #endif /* HAVE_DILITHIUM */
  21091. #if defined(HAVE_SPHINCS)
  21092. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21093. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21094. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21095. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21096. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21097. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21098. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21099. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21100. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21101. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21102. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21103. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21104. #endif /* HAVE_SPHINCS */
  21105. #endif /* HAVE_PQC */
  21106. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  21107. "-----END X509 CRL-----");
  21108. #ifdef WOLFSSL_PEM_TO_DER
  21109. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  21110. const char* endOfLine)
  21111. {
  21112. /* eat end of line characters */
  21113. while (line < endOfLine &&
  21114. (line[0] == '\r' || line[0] == '\n')) {
  21115. line++;
  21116. }
  21117. return line;
  21118. }
  21119. #endif
  21120. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  21121. {
  21122. int ret = BAD_FUNC_ARG;
  21123. switch (type) {
  21124. case CA_TYPE: /* same as below */
  21125. case TRUSTED_PEER_TYPE:
  21126. case CHAIN_CERT_TYPE:
  21127. case CERT_TYPE:
  21128. if (header) *header = BEGIN_CERT;
  21129. if (footer) *footer = END_CERT;
  21130. ret = 0;
  21131. break;
  21132. case CRL_TYPE:
  21133. if (header) *header = BEGIN_X509_CRL;
  21134. if (footer) *footer = END_X509_CRL;
  21135. ret = 0;
  21136. break;
  21137. #ifndef NO_DH
  21138. case DH_PARAM_TYPE:
  21139. if (header) *header = BEGIN_DH_PARAM;
  21140. if (footer) *footer = END_DH_PARAM;
  21141. ret = 0;
  21142. break;
  21143. case X942_PARAM_TYPE:
  21144. if (header) *header = BEGIN_X942_PARAM;
  21145. if (footer) *footer = END_X942_PARAM;
  21146. ret = 0;
  21147. break;
  21148. #endif
  21149. #ifndef NO_DSA
  21150. case DSA_PARAM_TYPE:
  21151. if (header) *header = BEGIN_DSA_PARAM;
  21152. if (footer) *footer = END_DSA_PARAM;
  21153. ret = 0;
  21154. break;
  21155. #endif
  21156. #ifdef WOLFSSL_CERT_REQ
  21157. case CERTREQ_TYPE:
  21158. if (header) *header = BEGIN_CERT_REQ;
  21159. if (footer) *footer = END_CERT_REQ;
  21160. ret = 0;
  21161. break;
  21162. #endif
  21163. #ifndef NO_DSA
  21164. case DSA_TYPE:
  21165. case DSA_PRIVATEKEY_TYPE:
  21166. if (header) *header = BEGIN_DSA_PRIV;
  21167. if (footer) *footer = END_DSA_PRIV;
  21168. ret = 0;
  21169. break;
  21170. #endif
  21171. #ifdef HAVE_ECC
  21172. case ECC_TYPE:
  21173. case ECC_PRIVATEKEY_TYPE:
  21174. if (header) *header = BEGIN_EC_PRIV;
  21175. if (footer) *footer = END_EC_PRIV;
  21176. ret = 0;
  21177. break;
  21178. #ifdef OPENSSL_EXTRA
  21179. case ECC_PARAM_TYPE:
  21180. if (header) *header = BEGIN_EC_PARAM;
  21181. if (footer) *footer = END_EC_PARAM;
  21182. ret = 0;
  21183. break;
  21184. #endif
  21185. #endif
  21186. case RSA_TYPE:
  21187. case PRIVATEKEY_TYPE:
  21188. if (header) *header = BEGIN_RSA_PRIV;
  21189. if (footer) *footer = END_RSA_PRIV;
  21190. ret = 0;
  21191. break;
  21192. #ifdef HAVE_ED25519
  21193. case ED25519_TYPE:
  21194. #endif
  21195. #ifdef HAVE_ED448
  21196. case ED448_TYPE:
  21197. #endif
  21198. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21199. case EDDSA_PRIVATEKEY_TYPE:
  21200. if (header) *header = BEGIN_EDDSA_PRIV;
  21201. if (footer) *footer = END_EDDSA_PRIV;
  21202. ret = 0;
  21203. break;
  21204. #endif
  21205. #ifdef HAVE_PQC
  21206. #ifdef HAVE_FALCON
  21207. case FALCON_LEVEL1_TYPE:
  21208. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  21209. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  21210. ret = 0;
  21211. break;
  21212. case FALCON_LEVEL5_TYPE:
  21213. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  21214. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  21215. ret = 0;
  21216. break;
  21217. #endif /* HAVE_FALCON */
  21218. #ifdef HAVE_DILITHIUM
  21219. case DILITHIUM_LEVEL2_TYPE:
  21220. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  21221. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  21222. ret = 0;
  21223. break;
  21224. case DILITHIUM_LEVEL3_TYPE:
  21225. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  21226. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  21227. ret = 0;
  21228. break;
  21229. case DILITHIUM_LEVEL5_TYPE:
  21230. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  21231. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  21232. ret = 0;
  21233. break;
  21234. #endif /* HAVE_DILITHIUM */
  21235. #ifdef HAVE_SPHINCS
  21236. case SPHINCS_FAST_LEVEL1_TYPE:
  21237. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  21238. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  21239. ret = 0;
  21240. break;
  21241. case SPHINCS_FAST_LEVEL3_TYPE:
  21242. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  21243. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  21244. ret = 0;
  21245. break;
  21246. case SPHINCS_FAST_LEVEL5_TYPE:
  21247. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  21248. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  21249. ret = 0;
  21250. break;
  21251. case SPHINCS_SMALL_LEVEL1_TYPE:
  21252. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  21253. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  21254. ret = 0;
  21255. break;
  21256. case SPHINCS_SMALL_LEVEL3_TYPE:
  21257. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  21258. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  21259. ret = 0;
  21260. break;
  21261. case SPHINCS_SMALL_LEVEL5_TYPE:
  21262. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  21263. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  21264. ret = 0;
  21265. break;
  21266. #endif /* HAVE_SPHINCS */
  21267. #endif /* HAVE_PQC */
  21268. case PUBLICKEY_TYPE:
  21269. case ECC_PUBLICKEY_TYPE:
  21270. if (header) *header = BEGIN_PUB_KEY;
  21271. if (footer) *footer = END_PUB_KEY;
  21272. ret = 0;
  21273. break;
  21274. case RSA_PUBLICKEY_TYPE:
  21275. if (header) *header = BEGIN_RSA_PUB;
  21276. if (footer) *footer = END_RSA_PUB;
  21277. ret = 0;
  21278. break;
  21279. #ifndef NO_DH
  21280. case DH_PRIVATEKEY_TYPE:
  21281. #endif
  21282. case PKCS8_PRIVATEKEY_TYPE:
  21283. if (header) *header = BEGIN_PRIV_KEY;
  21284. if (footer) *footer = END_PRIV_KEY;
  21285. ret = 0;
  21286. break;
  21287. case PKCS8_ENC_PRIVATEKEY_TYPE:
  21288. if (header) *header = BEGIN_ENC_PRIV_KEY;
  21289. if (footer) *footer = END_ENC_PRIV_KEY;
  21290. ret = 0;
  21291. break;
  21292. default:
  21293. break;
  21294. }
  21295. return ret;
  21296. }
  21297. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21298. static wcchar kProcTypeHeader = "Proc-Type";
  21299. static wcchar kDecInfoHeader = "DEK-Info";
  21300. #ifdef WOLFSSL_PEM_TO_DER
  21301. #ifndef NO_DES3
  21302. static wcchar kEncTypeDes = "DES-CBC";
  21303. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  21304. #endif
  21305. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21306. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  21307. #endif
  21308. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21309. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  21310. #endif
  21311. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21312. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  21313. #endif
  21314. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  21315. {
  21316. int ret = 0;
  21317. if (info == NULL || cipherInfo == NULL)
  21318. return BAD_FUNC_ARG;
  21319. /* determine cipher information */
  21320. #ifndef NO_DES3
  21321. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  21322. info->cipherType = WC_CIPHER_DES;
  21323. info->keySz = DES_KEY_SIZE;
  21324. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  21325. * block size. */
  21326. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21327. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21328. #else
  21329. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21330. #endif
  21331. }
  21332. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  21333. info->cipherType = WC_CIPHER_DES3;
  21334. info->keySz = DES3_KEY_SIZE;
  21335. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21336. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21337. #else
  21338. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21339. #endif
  21340. }
  21341. else
  21342. #endif /* !NO_DES3 */
  21343. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21344. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  21345. info->cipherType = WC_CIPHER_AES_CBC;
  21346. info->keySz = AES_128_KEY_SIZE;
  21347. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21348. }
  21349. else
  21350. #endif
  21351. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21352. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  21353. info->cipherType = WC_CIPHER_AES_CBC;
  21354. info->keySz = AES_192_KEY_SIZE;
  21355. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21356. }
  21357. else
  21358. #endif
  21359. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21360. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  21361. info->cipherType = WC_CIPHER_AES_CBC;
  21362. info->keySz = AES_256_KEY_SIZE;
  21363. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21364. }
  21365. else
  21366. #endif
  21367. {
  21368. ret = NOT_COMPILED_IN;
  21369. }
  21370. return ret;
  21371. }
  21372. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  21373. size_t bufSz)
  21374. {
  21375. int err = 0;
  21376. const char* bufferStart;
  21377. const char* bufferEnd;
  21378. char* line;
  21379. if (info == NULL || pBuffer == NULL || bufSz == 0)
  21380. return BAD_FUNC_ARG;
  21381. bufferStart = *pBuffer;
  21382. bufferEnd = bufferStart + bufSz;
  21383. /* find encrypted info marker */
  21384. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  21385. min((word32)bufSz, PEM_LINE_LEN));
  21386. if (line != NULL) {
  21387. word32 lineSz;
  21388. char* finish;
  21389. char* start;
  21390. word32 startSz;
  21391. const char* newline = NULL;
  21392. if (line >= bufferEnd) {
  21393. return BUFFER_E;
  21394. }
  21395. lineSz = (word32)(bufferEnd - line);
  21396. /* find DEC-Info marker */
  21397. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  21398. if (start == NULL)
  21399. return BUFFER_E;
  21400. /* skip dec-info and ": " */
  21401. start += XSTRLEN(kDecInfoHeader);
  21402. if (start >= bufferEnd)
  21403. return BUFFER_E;
  21404. if (start[0] == ':') {
  21405. start++;
  21406. if (start >= bufferEnd)
  21407. return BUFFER_E;
  21408. }
  21409. if (start[0] == ' ')
  21410. start++;
  21411. startSz = (word32)(bufferEnd - start);
  21412. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  21413. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  21414. word32 finishSz;
  21415. if (finish >= bufferEnd) {
  21416. return BUFFER_E;
  21417. }
  21418. finishSz = (word32)(bufferEnd - finish);
  21419. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  21420. /* get cipher name */
  21421. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  21422. return BUFFER_E;
  21423. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  21424. return BUFFER_E;
  21425. info->name[finish - start] = '\0'; /* null term */
  21426. /* populate info */
  21427. err = wc_EncryptedInfoGet(info, info->name);
  21428. if (err != 0)
  21429. return err;
  21430. /* get IV */
  21431. if (finishSz < info->ivSz + 1)
  21432. return BUFFER_E;
  21433. if (newline == NULL) {
  21434. newline = XSTRNSTR(finish, "\n", min(finishSz,
  21435. PEM_LINE_LEN));
  21436. }
  21437. if ((newline != NULL) && (newline > finish)) {
  21438. finish++;
  21439. info->ivSz = (word32)(newline - finish);
  21440. if (info->ivSz > IV_SZ)
  21441. return BUFFER_E;
  21442. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  21443. return BUFFER_E;
  21444. info->set = 1;
  21445. }
  21446. else
  21447. return BUFFER_E;
  21448. }
  21449. else
  21450. return BUFFER_E;
  21451. /* eat end of line characters */
  21452. newline = SkipEndOfLineChars(newline, bufferEnd);
  21453. /* return new headerEnd */
  21454. *pBuffer = newline;
  21455. }
  21456. return err;
  21457. }
  21458. #endif /* WOLFSSL_PEM_TO_DER */
  21459. #ifdef WOLFSSL_DER_TO_PEM
  21460. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  21461. {
  21462. if (cipherInfo != NULL) {
  21463. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  21464. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  21465. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  21466. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  21467. /* strncat's src length needs to include the NULL */
  21468. XSTRNCAT(dest, kProcTypeHeader, 10);
  21469. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  21470. XSTRNCAT(dest, kDecInfoHeader, 9);
  21471. XSTRNCAT(dest, ": ", 3);
  21472. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  21473. XSTRNCAT(dest, "\n\n", 4);
  21474. }
  21475. }
  21476. return 0;
  21477. }
  21478. #endif /* WOLFSSL_DER_TO_PEM */
  21479. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21480. #ifdef WOLFSSL_DER_TO_PEM
  21481. /* Used for compatibility API */
  21482. WOLFSSL_ABI
  21483. int wc_DerToPem(const byte* der, word32 derSz,
  21484. byte* output, word32 outSz, int type)
  21485. {
  21486. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  21487. }
  21488. /* convert der buffer to pem into output, can't do inplace, der and output
  21489. need to be different */
  21490. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  21491. byte *cipher_info, int type)
  21492. {
  21493. const char* headerStr = NULL;
  21494. const char* footerStr = NULL;
  21495. #ifdef WOLFSSL_SMALL_STACK
  21496. char* header = NULL;
  21497. char* footer = NULL;
  21498. #else
  21499. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  21500. char footer[MAX_X509_HEADER_SZ];
  21501. #endif
  21502. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  21503. int footerLen = MAX_X509_HEADER_SZ;
  21504. int i;
  21505. int err;
  21506. int outLen; /* return length or error */
  21507. (void)cipher_info;
  21508. if (der == output) /* no in place conversion */
  21509. return BAD_FUNC_ARG;
  21510. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  21511. if (err != 0)
  21512. return err;
  21513. #ifdef WOLFSSL_SMALL_STACK
  21514. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21515. if (header == NULL)
  21516. return MEMORY_E;
  21517. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21518. if (footer == NULL) {
  21519. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21520. return MEMORY_E;
  21521. }
  21522. #endif
  21523. /* build header and footer based on type */
  21524. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  21525. header[headerLen - 2] = 0;
  21526. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  21527. footer[footerLen - 2] = 0;
  21528. /* add new line to end */
  21529. XSTRNCAT(header, "\n", 2);
  21530. XSTRNCAT(footer, "\n", 2);
  21531. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21532. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  21533. if (err != 0) {
  21534. #ifdef WOLFSSL_SMALL_STACK
  21535. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21536. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21537. #endif
  21538. return err;
  21539. }
  21540. #endif
  21541. headerLen = (int)XSTRLEN(header);
  21542. footerLen = (int)XSTRLEN(footer);
  21543. /* if null output and 0 size passed in then return size needed */
  21544. if (!output && outSz == 0) {
  21545. #ifdef WOLFSSL_SMALL_STACK
  21546. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21547. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21548. #endif
  21549. outLen = 0;
  21550. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  21551. != LENGTH_ONLY_E) {
  21552. WOLFSSL_ERROR_VERBOSE(err);
  21553. return err;
  21554. }
  21555. return headerLen + footerLen + outLen;
  21556. }
  21557. if (!der || !output) {
  21558. #ifdef WOLFSSL_SMALL_STACK
  21559. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21560. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21561. #endif
  21562. return BAD_FUNC_ARG;
  21563. }
  21564. /* don't even try if outSz too short */
  21565. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  21566. #ifdef WOLFSSL_SMALL_STACK
  21567. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21568. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21569. #endif
  21570. return BAD_FUNC_ARG;
  21571. }
  21572. /* header */
  21573. XMEMCPY(output, header, (size_t)headerLen);
  21574. i = headerLen;
  21575. #ifdef WOLFSSL_SMALL_STACK
  21576. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21577. #endif
  21578. /* body */
  21579. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  21580. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  21581. #ifdef WOLFSSL_SMALL_STACK
  21582. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21583. #endif
  21584. WOLFSSL_ERROR_VERBOSE(err);
  21585. return err;
  21586. }
  21587. i += outLen;
  21588. /* footer */
  21589. if ( (i + footerLen) > (int)outSz) {
  21590. #ifdef WOLFSSL_SMALL_STACK
  21591. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21592. #endif
  21593. return BAD_FUNC_ARG;
  21594. }
  21595. XMEMCPY(output + i, footer, (size_t)footerLen);
  21596. #ifdef WOLFSSL_SMALL_STACK
  21597. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21598. #endif
  21599. return outLen + headerLen + footerLen;
  21600. }
  21601. #endif /* WOLFSSL_DER_TO_PEM */
  21602. #ifdef WOLFSSL_PEM_TO_DER
  21603. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  21604. info->consumed tracks of PEM bytes consumed in case multiple parts */
  21605. int PemToDer(const unsigned char* buff, long longSz, int type,
  21606. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21607. {
  21608. const char* header = NULL;
  21609. const char* footer = NULL;
  21610. const char* headerEnd;
  21611. const char* footerEnd;
  21612. const char* consumedEnd;
  21613. const char* bufferEnd = (const char*)(buff + longSz);
  21614. long neededSz;
  21615. int ret = 0;
  21616. word32 sz = (word32)longSz;
  21617. int encrypted_key = 0;
  21618. DerBuffer* der;
  21619. word32 algId = 0;
  21620. word32 idx;
  21621. #ifdef OPENSSL_EXTRA
  21622. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21623. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21624. #endif
  21625. WOLFSSL_ENTER("PemToDer");
  21626. /* get PEM header and footer based on type */
  21627. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  21628. if (ret != 0)
  21629. return ret;
  21630. /* map header if not found for type */
  21631. for (;;) {
  21632. headerEnd = XSTRNSTR((char*)buff, header, sz);
  21633. if (headerEnd) {
  21634. break;
  21635. }
  21636. if (type == PRIVATEKEY_TYPE) {
  21637. if (header == BEGIN_RSA_PRIV) {
  21638. header = BEGIN_PRIV_KEY;
  21639. footer = END_PRIV_KEY;
  21640. }
  21641. else if (header == BEGIN_PRIV_KEY) {
  21642. header = BEGIN_ENC_PRIV_KEY;
  21643. footer = END_ENC_PRIV_KEY;
  21644. }
  21645. #ifdef HAVE_ECC
  21646. else if (header == BEGIN_ENC_PRIV_KEY) {
  21647. header = BEGIN_EC_PRIV;
  21648. footer = END_EC_PRIV;
  21649. }
  21650. else if (header == BEGIN_EC_PRIV) {
  21651. header = BEGIN_DSA_PRIV;
  21652. footer = END_DSA_PRIV;
  21653. }
  21654. #endif
  21655. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21656. #ifdef HAVE_ECC
  21657. else if (header == BEGIN_DSA_PRIV) {
  21658. #else
  21659. else if (header == BEGIN_ENC_PRIV_KEY) {
  21660. #endif
  21661. header = BEGIN_EDDSA_PRIV;
  21662. footer = END_EDDSA_PRIV;
  21663. }
  21664. #endif
  21665. else {
  21666. #ifdef WOLF_PRIVATE_KEY_ID
  21667. /* allow loading a public key for use with crypto or PK callbacks */
  21668. type = PUBLICKEY_TYPE;
  21669. header = BEGIN_PUB_KEY;
  21670. footer = END_PUB_KEY;
  21671. #else
  21672. break;
  21673. #endif
  21674. }
  21675. }
  21676. else if (type == PUBLICKEY_TYPE) {
  21677. if (header == BEGIN_PUB_KEY) {
  21678. header = BEGIN_RSA_PUB;
  21679. footer = END_RSA_PUB;
  21680. }
  21681. else {
  21682. break;
  21683. }
  21684. }
  21685. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  21686. else if (type == ECC_PARAM_TYPE) {
  21687. if (header == BEGIN_EC_PARAM) {
  21688. header = BEGIN_EC_PARAM;
  21689. footer = END_EC_PARAM;
  21690. }
  21691. else {
  21692. break;
  21693. }
  21694. }
  21695. #endif
  21696. #ifdef HAVE_CRL
  21697. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  21698. header = BEGIN_X509_CRL;
  21699. footer = END_X509_CRL;
  21700. }
  21701. #endif
  21702. else {
  21703. break;
  21704. }
  21705. }
  21706. if (!headerEnd) {
  21707. #ifdef OPENSSL_EXTRA
  21708. if (type == PRIVATEKEY_TYPE) {
  21709. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  21710. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  21711. if (headerEnd) {
  21712. const char* beginEnd;
  21713. unsigned int endLen;
  21714. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  21715. if (beginEnd >= (char*)buff + sz) {
  21716. return BUFFER_E;
  21717. }
  21718. /* back up to BEGIN_PRIV_KEY_PREFIX */
  21719. while (headerEnd > (char*)buff &&
  21720. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21721. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  21722. *headerEnd != '\n') {
  21723. headerEnd--;
  21724. }
  21725. if (headerEnd <= (char*)buff ||
  21726. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21727. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  21728. beginEnd - headerEnd > PEM_LINE_LEN) {
  21729. WOLFSSL_MSG("Couldn't find PEM header");
  21730. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21731. return ASN_NO_PEM_HEADER;
  21732. }
  21733. /* headerEnd now points to beginning of header */
  21734. XMEMCPY(beginBuf, headerEnd, (size_t)(beginEnd - headerEnd));
  21735. beginBuf[beginEnd - headerEnd] = '\0';
  21736. /* look for matching footer */
  21737. footer = XSTRNSTR(beginEnd,
  21738. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  21739. (unsigned int)((char*)buff + sz - beginEnd));
  21740. if (!footer) {
  21741. WOLFSSL_MSG("Couldn't find PEM footer");
  21742. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21743. return ASN_NO_PEM_HEADER;
  21744. }
  21745. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  21746. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  21747. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  21748. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  21749. WOLFSSL_MSG("Unexpected footer for PEM");
  21750. return BUFFER_E;
  21751. }
  21752. endLen = (unsigned int)((size_t)(beginEnd - headerEnd) -
  21753. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  21754. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  21755. XMEMCPY(endBuf, footer, (size_t)endLen);
  21756. endBuf[endLen] = '\0';
  21757. header = beginBuf;
  21758. footer = endBuf;
  21759. headerEnd = beginEnd;
  21760. }
  21761. }
  21762. if (!headerEnd) {
  21763. WOLFSSL_MSG("Couldn't find PEM header");
  21764. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21765. return ASN_NO_PEM_HEADER;
  21766. }
  21767. #else
  21768. WOLFSSL_MSG("Couldn't find PEM header");
  21769. return ASN_NO_PEM_HEADER;
  21770. #endif
  21771. } else {
  21772. headerEnd += XSTRLEN(header);
  21773. }
  21774. /* eat end of line characters */
  21775. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  21776. if (keyFormat) {
  21777. /* keyFormat is Key_Sum enum */
  21778. if (type == PRIVATEKEY_TYPE) {
  21779. #ifndef NO_RSA
  21780. if (header == BEGIN_RSA_PRIV)
  21781. *keyFormat = RSAk;
  21782. #endif
  21783. #ifdef HAVE_ECC
  21784. if (header == BEGIN_EC_PRIV)
  21785. *keyFormat = ECDSAk;
  21786. #endif
  21787. #ifndef NO_DSA
  21788. if (header == BEGIN_DSA_PRIV)
  21789. *keyFormat = DSAk;
  21790. #endif
  21791. }
  21792. #ifdef WOLF_PRIVATE_KEY_ID
  21793. else if (type == PUBLICKEY_TYPE) {
  21794. #ifndef NO_RSA
  21795. if (header == BEGIN_RSA_PUB)
  21796. *keyFormat = RSAk;
  21797. #endif
  21798. }
  21799. #endif
  21800. }
  21801. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21802. if (info) {
  21803. ret = wc_EncryptedInfoParse(info, &headerEnd,
  21804. (size_t)(bufferEnd - headerEnd));
  21805. if (ret < 0)
  21806. return ret;
  21807. if (info->set)
  21808. encrypted_key = 1;
  21809. }
  21810. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21811. /* find footer */
  21812. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  21813. sz - headerEnd));
  21814. if (!footerEnd) {
  21815. if (info)
  21816. info->consumed = longSz; /* No more certs if no footer */
  21817. return BUFFER_E;
  21818. }
  21819. consumedEnd = footerEnd + XSTRLEN(footer);
  21820. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  21821. /* eat end of line characters */
  21822. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  21823. /* skip possible null term */
  21824. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  21825. consumedEnd++;
  21826. }
  21827. if (info)
  21828. info->consumed = (long)(consumedEnd - (const char*)buff);
  21829. /* set up der buffer */
  21830. neededSz = (long)(footerEnd - headerEnd);
  21831. if (neededSz > (long)sz || neededSz <= 0)
  21832. return BUFFER_E;
  21833. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  21834. if (ret < 0) {
  21835. return ret;
  21836. }
  21837. der = *pDer;
  21838. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  21839. der->buffer, &der->length) < 0) {
  21840. WOLFSSL_ERROR(BUFFER_E);
  21841. return BUFFER_E;
  21842. }
  21843. if ((header == BEGIN_PRIV_KEY
  21844. #ifdef OPENSSL_EXTRA
  21845. || header == beginBuf
  21846. #endif
  21847. #ifdef HAVE_ECC
  21848. || header == BEGIN_EC_PRIV
  21849. #endif
  21850. ) && !encrypted_key)
  21851. {
  21852. /* detect pkcs8 key and get alg type */
  21853. /* keep PKCS8 header */
  21854. idx = 0;
  21855. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  21856. if (ret > 0) {
  21857. if (keyFormat)
  21858. *keyFormat = (int)algId;
  21859. }
  21860. else {
  21861. /* ignore failure here and assume key is not pkcs8 wrapped */
  21862. }
  21863. return 0;
  21864. }
  21865. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21866. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  21867. int passwordSz = NAME_SZ;
  21868. #ifdef WOLFSSL_SMALL_STACK
  21869. char* password = NULL;
  21870. #else
  21871. char password[NAME_SZ];
  21872. #endif
  21873. if (!info || !info->passwd_cb) {
  21874. WOLFSSL_MSG("No password callback set");
  21875. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21876. return NO_PASSWORD;
  21877. }
  21878. #ifdef WOLFSSL_SMALL_STACK
  21879. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  21880. if (password == NULL) {
  21881. return MEMORY_E;
  21882. }
  21883. #endif
  21884. /* get password */
  21885. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  21886. info->passwd_userdata);
  21887. if (ret >= 0) {
  21888. passwordSz = ret;
  21889. #ifdef WOLFSSL_CHECK_MEM_ZERO
  21890. wc_MemZero_Add("PEM password", password, passwordSz);
  21891. #endif
  21892. /* convert and adjust length */
  21893. if (header == BEGIN_ENC_PRIV_KEY) {
  21894. #ifndef NO_PWDBASED
  21895. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  21896. password, passwordSz);
  21897. if (ret > 0) {
  21898. /* update length by decrypted content */
  21899. der->length = (word32)ret;
  21900. idx = 0;
  21901. /* detect pkcs8 key and get alg type */
  21902. /* keep PKCS8 header */
  21903. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  21904. &algId);
  21905. if (ret >= 0) {
  21906. if (keyFormat)
  21907. *keyFormat = (int)algId;
  21908. ret = 0;
  21909. }
  21910. }
  21911. #else
  21912. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  21913. ret = NOT_COMPILED_IN;
  21914. #endif
  21915. }
  21916. /* decrypt the key */
  21917. else {
  21918. if (passwordSz == 0) {
  21919. /* The key is encrypted but does not have a password */
  21920. WOLFSSL_MSG("No password for encrypted key");
  21921. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21922. ret = NO_PASSWORD;
  21923. }
  21924. else {
  21925. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  21926. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21927. defined(HAVE_AES_DECRYPT))) && \
  21928. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  21929. int padVal = 0;
  21930. #endif
  21931. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  21932. (byte*)password, passwordSz, WC_MD5);
  21933. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  21934. #ifndef NO_DES3
  21935. if (info->cipherType == WC_CIPHER_DES3) {
  21936. /* Assuming there is padding:
  21937. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  21938. * (der->length % DES_BLOCK_SIZE) != 0)
  21939. * and assuming the last value signifies the number of
  21940. * padded bytes IE if last value is 0x08 then there are
  21941. * 8 bytes of padding:
  21942. * padVal = der->buffer[der->length-1];
  21943. * then strip this padding before proceeding:
  21944. * der->length -= padVal;
  21945. */
  21946. if (der->length > DES_BLOCK_SIZE &&
  21947. (der->length % DES_BLOCK_SIZE) != 0) {
  21948. padVal = der->buffer[der->length-1];
  21949. if (padVal < DES_BLOCK_SIZE) {
  21950. der->length -= (word32)padVal;
  21951. }
  21952. }
  21953. }
  21954. #endif /* !NO_DES3 */
  21955. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21956. defined(HAVE_AES_DECRYPT)
  21957. if (info->cipherType == WC_CIPHER_AES_CBC) {
  21958. if (der->length > AES_BLOCK_SIZE) {
  21959. padVal = der->buffer[der->length-1];
  21960. if (padVal <= AES_BLOCK_SIZE) {
  21961. der->length -= (word32)padVal;
  21962. }
  21963. }
  21964. }
  21965. #endif
  21966. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  21967. }
  21968. }
  21969. #ifdef OPENSSL_EXTRA
  21970. if (ret) {
  21971. PEMerr(0, PEM_R_BAD_DECRYPT);
  21972. }
  21973. #endif
  21974. ForceZero(password, (word32)passwordSz);
  21975. }
  21976. #ifdef OPENSSL_EXTRA
  21977. else {
  21978. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  21979. }
  21980. #endif
  21981. #ifdef WOLFSSL_SMALL_STACK
  21982. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  21983. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  21984. wc_MemZero_Check(password, NAME_SZ);
  21985. #endif
  21986. }
  21987. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21988. return ret;
  21989. }
  21990. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  21991. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21992. {
  21993. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  21994. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  21995. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  21996. DerBuffer* der = *pDer;
  21997. /* if a PKCS8 key header exists remove it */
  21998. ret = ToTraditional(der->buffer, der->length);
  21999. if (ret > 0) {
  22000. der->length = (word32)ret;
  22001. }
  22002. ret = 0; /* ignore error removing PKCS8 header */
  22003. }
  22004. #endif
  22005. return ret;
  22006. }
  22007. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22008. /* our KeyPemToDer password callback, password in userData */
  22009. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  22010. {
  22011. (void)rw;
  22012. if (userdata == NULL)
  22013. return 0;
  22014. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  22015. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  22016. }
  22017. #endif
  22018. /* Return bytes written to buff or < 0 for error */
  22019. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  22020. unsigned char* buff, int buffSz, const char* pass)
  22021. {
  22022. int ret;
  22023. DerBuffer* der = NULL;
  22024. #ifdef WOLFSSL_SMALL_STACK
  22025. EncryptedInfo* info = NULL;
  22026. #else
  22027. EncryptedInfo info[1];
  22028. #endif
  22029. WOLFSSL_ENTER("wc_KeyPemToDer");
  22030. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22031. WOLFSSL_MSG("Bad pem der args");
  22032. return BAD_FUNC_ARG;
  22033. }
  22034. #ifdef WOLFSSL_SMALL_STACK
  22035. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  22036. DYNAMIC_TYPE_ENCRYPTEDINFO);
  22037. if (info == NULL)
  22038. return MEMORY_E;
  22039. #endif
  22040. XMEMSET(info, 0, sizeof(EncryptedInfo));
  22041. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22042. info->passwd_cb = KeyPemToDerPassCb;
  22043. info->passwd_userdata = (void*)pass;
  22044. #else
  22045. (void)pass;
  22046. #endif
  22047. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  22048. #ifdef WOLFSSL_SMALL_STACK
  22049. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  22050. #endif
  22051. if (ret < 0 || der == NULL) {
  22052. WOLFSSL_MSG("Bad Pem To Der");
  22053. }
  22054. else if (buff == NULL) {
  22055. WOLFSSL_MSG("Return needed der buff length");
  22056. ret = (int)der->length;
  22057. }
  22058. else if (der->length <= (word32)buffSz) {
  22059. XMEMCPY(buff, der->buffer, der->length);
  22060. ret = (int)der->length;
  22061. }
  22062. else {
  22063. WOLFSSL_MSG("Bad der length");
  22064. ret = BAD_FUNC_ARG;
  22065. }
  22066. FreeDer(&der);
  22067. return ret;
  22068. }
  22069. /* Return bytes written to buff or < 0 for error */
  22070. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  22071. unsigned char* buff, int buffSz, int type)
  22072. {
  22073. int ret;
  22074. DerBuffer* der = NULL;
  22075. WOLFSSL_ENTER("wc_CertPemToDer");
  22076. if (pem == NULL || buff == NULL || buffSz <= 0) {
  22077. WOLFSSL_MSG("Bad pem der args");
  22078. return BAD_FUNC_ARG;
  22079. }
  22080. if (type != CERT_TYPE && type != CHAIN_CERT_TYPE && type != CA_TYPE &&
  22081. type != CERTREQ_TYPE) {
  22082. WOLFSSL_MSG("Bad cert type");
  22083. return BAD_FUNC_ARG;
  22084. }
  22085. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  22086. if (ret < 0 || der == NULL) {
  22087. WOLFSSL_MSG("Bad Pem To Der");
  22088. }
  22089. else {
  22090. if (der->length <= (word32)buffSz) {
  22091. XMEMCPY(buff, der->buffer, der->length);
  22092. ret = (int)der->length;
  22093. }
  22094. else {
  22095. WOLFSSL_MSG("Bad der length");
  22096. ret = BAD_FUNC_ARG;
  22097. }
  22098. }
  22099. FreeDer(&der);
  22100. return ret;
  22101. }
  22102. #endif /* WOLFSSL_PEM_TO_DER */
  22103. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  22104. #ifdef WOLFSSL_PEM_TO_DER
  22105. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22106. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  22107. zero for error */
  22108. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  22109. unsigned char* buff, int buffSz)
  22110. {
  22111. int ret;
  22112. DerBuffer* der = NULL;
  22113. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  22114. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22115. WOLFSSL_MSG("Bad pem der args");
  22116. return BAD_FUNC_ARG;
  22117. }
  22118. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  22119. if (ret < 0 || der == NULL) {
  22120. WOLFSSL_MSG("Bad Pem To Der");
  22121. }
  22122. else if (buff == NULL) {
  22123. WOLFSSL_MSG("Return needed der buff length");
  22124. ret = (int)der->length;
  22125. }
  22126. else if (der->length <= (word32)buffSz) {
  22127. XMEMCPY(buff, der->buffer, der->length);
  22128. ret = (int)der->length;
  22129. }
  22130. else {
  22131. WOLFSSL_MSG("Bad der length");
  22132. ret = BAD_FUNC_ARG;
  22133. }
  22134. FreeDer(&der);
  22135. return ret;
  22136. }
  22137. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22138. #endif /* WOLFSSL_PEM_TO_DER */
  22139. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  22140. #ifdef WOLFSSL_CERT_GEN
  22141. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  22142. {
  22143. #ifndef WOLFSSL_SMALL_STACK
  22144. byte staticBuffer[FILE_BUFFER_SIZE];
  22145. #endif
  22146. byte* fileBuf = NULL;
  22147. int ret = 0;
  22148. XFILE file = XBADFILE;
  22149. int dynamic = 0;
  22150. long sz = 0;
  22151. WOLFSSL_ENTER("wc_PemCertToDer");
  22152. if (fileName == NULL) {
  22153. ret = BAD_FUNC_ARG;
  22154. }
  22155. else {
  22156. file = XFOPEN(fileName, "rb");
  22157. if (file == XBADFILE) {
  22158. ret = IO_FAILED_E;
  22159. }
  22160. }
  22161. if (ret == 0) {
  22162. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22163. ret = IO_FAILED_E;
  22164. }
  22165. }
  22166. if (ret == 0) {
  22167. sz = XFTELL(file);
  22168. if (sz <= 0) {
  22169. ret = IO_FAILED_E;
  22170. }
  22171. }
  22172. if (ret == 0) {
  22173. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22174. ret = IO_FAILED_E;
  22175. }
  22176. }
  22177. if (ret == 0) {
  22178. #ifndef WOLFSSL_SMALL_STACK
  22179. if (sz <= (long)sizeof(staticBuffer))
  22180. fileBuf = staticBuffer;
  22181. else
  22182. #endif
  22183. {
  22184. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22185. if (fileBuf == NULL)
  22186. ret = MEMORY_E;
  22187. else
  22188. dynamic = 1;
  22189. }
  22190. }
  22191. if (ret == 0) {
  22192. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22193. ret = IO_FAILED_E;
  22194. }
  22195. else {
  22196. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  22197. }
  22198. }
  22199. if (file != XBADFILE)
  22200. XFCLOSE(file);
  22201. if (dynamic)
  22202. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22203. return ret;
  22204. }
  22205. /* load pem cert from file into der buffer, return der size or error */
  22206. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  22207. {
  22208. int ret;
  22209. DerBuffer* converted = NULL;
  22210. ret = wc_PemCertToDer_ex(fileName, &converted);
  22211. if (ret == 0) {
  22212. if (converted->length < (word32)derSz) {
  22213. XMEMCPY(derBuf, converted->buffer, converted->length);
  22214. ret = (int)converted->length;
  22215. }
  22216. else
  22217. ret = BUFFER_E;
  22218. FreeDer(&converted);
  22219. }
  22220. return ret;
  22221. }
  22222. #endif /* WOLFSSL_CERT_GEN */
  22223. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22224. /* load pem public key from file into der buffer, return der size or error */
  22225. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  22226. {
  22227. #ifndef WOLFSSL_SMALL_STACK
  22228. byte staticBuffer[FILE_BUFFER_SIZE];
  22229. #endif
  22230. byte* fileBuf = NULL;
  22231. int dynamic = 0;
  22232. int ret = 0;
  22233. long sz = 0;
  22234. XFILE file = XBADFILE;
  22235. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  22236. if (fileName == NULL) {
  22237. ret = BAD_FUNC_ARG;
  22238. }
  22239. else {
  22240. file = XFOPEN(fileName, "rb");
  22241. if (file == XBADFILE) {
  22242. ret = IO_FAILED_E;
  22243. }
  22244. }
  22245. if (ret == 0) {
  22246. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22247. ret = IO_FAILED_E;
  22248. }
  22249. }
  22250. if (ret == 0) {
  22251. sz = XFTELL(file);
  22252. if (sz <= 0) {
  22253. ret = IO_FAILED_E;
  22254. }
  22255. }
  22256. if (ret == 0) {
  22257. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22258. ret = IO_FAILED_E;
  22259. }
  22260. }
  22261. if (ret == 0) {
  22262. #ifndef WOLFSSL_SMALL_STACK
  22263. if (sz <= (long)sizeof(staticBuffer))
  22264. fileBuf = staticBuffer;
  22265. else
  22266. #endif
  22267. {
  22268. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22269. if (fileBuf == NULL)
  22270. ret = MEMORY_E;
  22271. else
  22272. dynamic = 1;
  22273. }
  22274. }
  22275. if (ret == 0) {
  22276. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22277. ret = BUFFER_E;
  22278. }
  22279. else {
  22280. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  22281. 0, NULL, NULL);
  22282. }
  22283. }
  22284. if (file != XBADFILE)
  22285. XFCLOSE(file);
  22286. if (dynamic)
  22287. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22288. return ret;
  22289. }
  22290. /* load pem public key from file into der buffer, return der size or error */
  22291. int wc_PemPubKeyToDer(const char* fileName,
  22292. unsigned char* derBuf, int derSz)
  22293. {
  22294. int ret;
  22295. DerBuffer* converted = NULL;
  22296. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  22297. if (ret == 0) {
  22298. if (converted->length < (word32)derSz) {
  22299. XMEMCPY(derBuf, converted->buffer, converted->length);
  22300. ret = (int)converted->length;
  22301. }
  22302. else
  22303. ret = BUFFER_E;
  22304. FreeDer(&converted);
  22305. }
  22306. return ret;
  22307. }
  22308. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22309. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  22310. /* Get public key in DER format from a populated DecodedCert struct.
  22311. *
  22312. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  22313. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  22314. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  22315. * wc_InitDecodedCert().
  22316. *
  22317. * cert - populated DecodedCert struct holding X.509 certificate
  22318. * derKey - output buffer to place DER/ASN.1 encoded public key
  22319. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  22320. * on return. If derKey is passed in as NULL, derKeySz
  22321. * will be set to required buffer size for public key
  22322. * and LENGTH_ONLY_E will be returned from function.
  22323. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  22324. * if derKey is NULL and returning length only.
  22325. */
  22326. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  22327. byte* derKey, word32* derKeySz)
  22328. {
  22329. int ret = 0;
  22330. /* derKey may be NULL to return length only */
  22331. if (cert == NULL || derKeySz == NULL ||
  22332. (derKey != NULL && *derKeySz == 0)) {
  22333. return BAD_FUNC_ARG;
  22334. }
  22335. if (cert->publicKey == NULL) {
  22336. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  22337. return BAD_FUNC_ARG;
  22338. }
  22339. /* if derKey is NULL, return required output buffer size in derKeySz */
  22340. if (derKey == NULL) {
  22341. *derKeySz = cert->pubKeySize;
  22342. ret = LENGTH_ONLY_E;
  22343. }
  22344. if (ret == 0) {
  22345. if (cert->pubKeySize > *derKeySz) {
  22346. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  22347. ret = BAD_FUNC_ARG;
  22348. }
  22349. else {
  22350. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  22351. *derKeySz = cert->pubKeySize;
  22352. }
  22353. }
  22354. return ret;
  22355. }
  22356. #ifdef WOLFSSL_FPKI
  22357. /* Search through list for first matching alt name of the same type
  22358. * If 'current' is null then the search starts at the head of the list
  22359. * otherwise the search starts from the node after 'current' alt name.
  22360. * Returns 0 on success
  22361. */
  22362. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  22363. DNS_entry* current)
  22364. {
  22365. DNS_entry* entry;
  22366. if (current == NULL) {
  22367. entry = cert->altNames;
  22368. }
  22369. else {
  22370. entry = current->next;
  22371. }
  22372. /* cycle through alt names to check for needed types */
  22373. while (entry != NULL) {
  22374. if (entry->type == nameType) {
  22375. break;
  22376. }
  22377. entry = entry->next;
  22378. }
  22379. return entry;
  22380. }
  22381. /* returns 0 on success */
  22382. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  22383. {
  22384. int ret = ALT_NAME_E;
  22385. DNS_entry* id = NULL;
  22386. do {
  22387. id = FindAltName(cert, ASN_URI_TYPE, id);
  22388. if (id != NULL) {
  22389. /* check if URI string matches expected format for UUID */
  22390. if (id->len != DEFAULT_UUID_SZ) {
  22391. continue; /* size not right not a UUID URI */
  22392. }
  22393. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  22394. continue; /* beginning text not right for a UUID URI */
  22395. }
  22396. if (uuid == NULL) {
  22397. *uuidSz = (word32)id->len;
  22398. return LENGTH_ONLY_E;
  22399. }
  22400. if ((int)*uuidSz < id->len) {
  22401. return BUFFER_E;
  22402. }
  22403. XMEMCPY(uuid, id->name, (size_t)id->len);
  22404. ret = 0; /* success */
  22405. break;
  22406. }
  22407. } while (id != NULL);
  22408. return ret;
  22409. }
  22410. /* reutrns 0 on success */
  22411. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  22412. {
  22413. int ret = ALT_NAME_E;
  22414. DNS_entry* id = NULL;
  22415. do {
  22416. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  22417. if (id != NULL && id->oidSum == FASCN_OID) {
  22418. if (fascn == NULL) {
  22419. *fascnSz = (word32)id->len;
  22420. return LENGTH_ONLY_E;
  22421. }
  22422. if ((int)*fascnSz < id->len) {
  22423. return BUFFER_E;
  22424. }
  22425. XMEMCPY(fascn, id->name, (size_t)id->len);
  22426. ret = 0; /* success */
  22427. }
  22428. } while (id != NULL);
  22429. return ret;
  22430. }
  22431. #endif /* WOLFSSL_FPKI */
  22432. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  22433. defined(WOLFSSL_KCAPI_RSA) || \
  22434. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  22435. /* USER RSA ifdef portions used instead of refactor in consideration for
  22436. possible fips build */
  22437. /* Encode a public RSA key to output.
  22438. *
  22439. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22440. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22441. *
  22442. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22443. * (RSAPublicKey).
  22444. *
  22445. * @param [out] output Buffer to put encoded data in.
  22446. * @param [in] key RSA key object.
  22447. * @param [in] outLen Size of the output buffer in bytes.
  22448. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22449. * @return Size of encoded data in bytes on success.
  22450. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  22451. * minimum length (5 bytes).
  22452. * @return MEMORY_E when dynamic memory allocation failed.
  22453. */
  22454. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  22455. int with_header)
  22456. {
  22457. #ifndef WOLFSSL_ASN_TEMPLATE
  22458. int nSz, eSz;
  22459. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  22460. byte seq[MAX_SEQ_SZ];
  22461. byte headSeq[MAX_SEQ_SZ];
  22462. byte bitString[1 + MAX_LENGTH_SZ + 1];
  22463. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  22464. if (key == NULL) {
  22465. return BAD_FUNC_ARG;
  22466. }
  22467. #ifdef HAVE_USER_RSA
  22468. nSz = SetASNIntRSA(key->n, NULL);
  22469. #else
  22470. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  22471. #endif
  22472. if (nSz < 0)
  22473. return nSz;
  22474. #ifdef HAVE_USER_RSA
  22475. eSz = SetASNIntRSA(key->e, NULL);
  22476. #else
  22477. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  22478. #endif
  22479. if (eSz < 0)
  22480. return eSz;
  22481. seqSz = SetSequence((word32)(nSz + eSz), seq);
  22482. /* headers */
  22483. if (with_header) {
  22484. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  22485. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  22486. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  22487. headSeq);
  22488. }
  22489. /* if getting length only */
  22490. if (output == NULL) {
  22491. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  22492. }
  22493. /* check output size */
  22494. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  22495. return BUFFER_E;
  22496. }
  22497. /* write output */
  22498. idx = 0;
  22499. if (with_header) {
  22500. /* header size */
  22501. XMEMCPY(output + idx, headSeq, headSz);
  22502. idx += headSz;
  22503. /* algo */
  22504. XMEMCPY(output + idx, algo, algoSz);
  22505. idx += algoSz;
  22506. /* bit string */
  22507. XMEMCPY(output + idx, bitString, bitStringSz);
  22508. idx += bitStringSz;
  22509. }
  22510. /* seq */
  22511. XMEMCPY(output + idx, seq, seqSz);
  22512. idx += seqSz;
  22513. /* n */
  22514. #ifdef HAVE_USER_RSA
  22515. nSz = SetASNIntRSA(key->n, output + idx);
  22516. #else
  22517. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  22518. #endif
  22519. idx += (word32)nSz;
  22520. /* e */
  22521. #ifdef HAVE_USER_RSA
  22522. eSz = SetASNIntRSA(key->e, output + idx);
  22523. #else
  22524. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  22525. #endif
  22526. idx += (word32)eSz;
  22527. return (int)idx;
  22528. #else
  22529. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  22530. int sz = 0;
  22531. int ret = 0;
  22532. int o = 0;
  22533. /* Check parameter validity. */
  22534. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  22535. ret = BAD_FUNC_ARG;
  22536. }
  22537. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  22538. if (ret == 0) {
  22539. if (!with_header) {
  22540. /* Start encoding with items after header. */
  22541. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  22542. }
  22543. /* Set OID for RSA key. */
  22544. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  22545. #ifdef WC_RSA_PSS
  22546. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  22547. #endif
  22548. /* Set public key mp_ints. */
  22549. #ifdef HAVE_USER_RSA
  22550. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  22551. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  22552. #else
  22553. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  22554. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  22555. #endif
  22556. /* Calculate size of RSA public key. */
  22557. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22558. (int)rsaPublicKeyASN_Length - o, &sz);
  22559. }
  22560. /* Check output buffer is big enough for encoding. */
  22561. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22562. ret = BUFFER_E;
  22563. }
  22564. if ((ret == 0) && (output != NULL)) {
  22565. /* Encode RSA public key. */
  22566. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22567. (int)rsaPublicKeyASN_Length - o, output);
  22568. }
  22569. if (ret == 0) {
  22570. /* Return size of encoding. */
  22571. ret = sz;
  22572. }
  22573. FREE_ASNSETDATA(dataASN, key->heap);
  22574. return ret;
  22575. #endif /* WOLFSSL_ASN_TEMPLATE */
  22576. }
  22577. /* Calculate size of encoded public RSA key in bytes.
  22578. *
  22579. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22580. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22581. *
  22582. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22583. * (RSAPublicKey).
  22584. *
  22585. * @param [in] key RSA key object.
  22586. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22587. * @return Size of encoded data in bytes on success.
  22588. * @return BAD_FUNC_ARG when key is NULL.
  22589. * @return MEMORY_E when dynamic memory allocation failed.
  22590. */
  22591. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  22592. {
  22593. return SetRsaPublicKey(NULL, key, 0, with_header);
  22594. }
  22595. /* Encode public RSA key in DER format.
  22596. *
  22597. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22598. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22599. *
  22600. * @param [in] key RSA key object.
  22601. * @param [out] output Buffer to put encoded data in.
  22602. * @param [in] inLen Size of buffer in bytes.
  22603. * @return Size of encoded data in bytes on success.
  22604. * @return BAD_FUNC_ARG when key or output is NULL.
  22605. * @return MEMORY_E when dynamic memory allocation failed.
  22606. */
  22607. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  22608. {
  22609. return SetRsaPublicKey(output, key, (int)inLen, 1);
  22610. }
  22611. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  22612. * seq + n + e is returned in ASN.1 DER format */
  22613. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  22614. int with_header)
  22615. {
  22616. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  22617. }
  22618. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  22619. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  22620. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  22621. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  22622. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  22623. /* Encode private RSA key in DER format.
  22624. *
  22625. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  22626. *
  22627. * @param [in] key RSA key object.
  22628. * @param [out] output Buffer to put encoded data in.
  22629. * @param [in] inLen Size of buffer in bytes.
  22630. * @return Size of encoded data in bytes on success.
  22631. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22632. * @return MEMORY_E when dynamic memory allocation failed.
  22633. */
  22634. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22635. {
  22636. #ifndef WOLFSSL_ASN_TEMPLATE
  22637. int ret = 0, i;
  22638. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
  22639. word32 sizes[RSA_INTS];
  22640. byte seq[MAX_SEQ_SZ];
  22641. byte ver[MAX_VERSION_SZ];
  22642. byte* tmps[RSA_INTS];
  22643. if (key == NULL)
  22644. return BAD_FUNC_ARG;
  22645. if (key->type != RSA_PRIVATE)
  22646. return BAD_FUNC_ARG;
  22647. for (i = 0; i < RSA_INTS; i++)
  22648. tmps[i] = NULL;
  22649. /* write all big ints from key to DER tmps */
  22650. for (i = 0; i < RSA_INTS; i++) {
  22651. mp_int* keyInt = GetRsaInt(key, i);
  22652. int mpSz;
  22653. word32 rawLen;
  22654. ret = mp_unsigned_bin_size(keyInt);
  22655. if (ret < 0)
  22656. return ret;
  22657. rawLen = (word32)ret + 1;
  22658. ret = 0;
  22659. if (output != NULL) {
  22660. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22661. DYNAMIC_TYPE_RSA);
  22662. if (tmps[i] == NULL) {
  22663. ret = MEMORY_E;
  22664. break;
  22665. }
  22666. }
  22667. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  22668. if (mpSz < 0) {
  22669. ret = mpSz;
  22670. break;
  22671. }
  22672. sizes[i] = (word32)mpSz;
  22673. intTotalLen += (word32)mpSz;
  22674. }
  22675. if (ret == 0) {
  22676. /* make headers */
  22677. ret = SetMyVersion(0, ver, FALSE);
  22678. }
  22679. if (ret >= 0) {
  22680. verSz = (word32)ret;
  22681. ret = 0;
  22682. seqSz = SetSequence(verSz + intTotalLen, seq);
  22683. outLen = seqSz + verSz + intTotalLen;
  22684. if (output != NULL && outLen > inLen)
  22685. ret = BUFFER_E;
  22686. }
  22687. if (ret == 0 && output != NULL) {
  22688. word32 j;
  22689. /* write to output */
  22690. XMEMCPY(output, seq, seqSz);
  22691. j = seqSz;
  22692. XMEMCPY(output + j, ver, verSz);
  22693. j += verSz;
  22694. for (i = 0; i < RSA_INTS; i++) {
  22695. XMEMCPY(output + j, tmps[i], sizes[i]);
  22696. j += sizes[i];
  22697. }
  22698. }
  22699. for (i = 0; i < RSA_INTS; i++) {
  22700. if (tmps[i])
  22701. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  22702. }
  22703. if (ret == 0)
  22704. ret = (int)outLen;
  22705. return ret;
  22706. #else
  22707. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  22708. int i;
  22709. int sz = 0;
  22710. int ret = 0;
  22711. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  22712. ret = BAD_FUNC_ARG;
  22713. }
  22714. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  22715. if (ret == 0) {
  22716. /* Set the version. */
  22717. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  22718. /* Set all the mp_ints in private key. */
  22719. for (i = 0; i < RSA_INTS; i++) {
  22720. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  22721. }
  22722. /* Calculate size of RSA private key encoding. */
  22723. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  22724. }
  22725. /* Check output buffer has enough space for encoding. */
  22726. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  22727. ret = BAD_FUNC_ARG;
  22728. }
  22729. if ((ret == 0) && (output != NULL)) {
  22730. /* Encode RSA private key. */
  22731. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  22732. }
  22733. if (ret == 0) {
  22734. /* Return size of encoding. */
  22735. ret = sz;
  22736. }
  22737. FREE_ASNSETDATA(dataASN, key->heap);
  22738. return ret;
  22739. #endif
  22740. }
  22741. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  22742. #ifdef WOLFSSL_CERT_GEN
  22743. /* Initialize and Set Certificate defaults:
  22744. version = 3 (0x2)
  22745. serial = 0
  22746. sigType = SHA_WITH_RSA
  22747. issuer = blank
  22748. daysValid = 500
  22749. selfSigned = 1 (true) use subject as issuer
  22750. subject = blank
  22751. */
  22752. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  22753. {
  22754. #ifdef WOLFSSL_MULTI_ATTRIB
  22755. int i = 0;
  22756. #endif
  22757. if (cert == NULL) {
  22758. return BAD_FUNC_ARG;
  22759. }
  22760. XMEMSET(cert, 0, sizeof(Cert));
  22761. cert->version = 2; /* version 3 is hex 2 */
  22762. #ifndef NO_SHA
  22763. cert->sigType = CTC_SHAwRSA;
  22764. #elif !defined(NO_SHA256)
  22765. cert->sigType = CTC_SHA256wRSA;
  22766. #else
  22767. cert->sigType = 0;
  22768. #endif
  22769. cert->daysValid = 500;
  22770. cert->selfSigned = 1;
  22771. cert->keyType = RSA_KEY;
  22772. cert->issuer.countryEnc = CTC_PRINTABLE;
  22773. cert->issuer.stateEnc = CTC_UTF8;
  22774. cert->issuer.streetEnc = CTC_UTF8;
  22775. cert->issuer.localityEnc = CTC_UTF8;
  22776. cert->issuer.surEnc = CTC_UTF8;
  22777. #ifdef WOLFSSL_CERT_NAME_ALL
  22778. cert->issuer.givenNameEnc = CTC_UTF8;
  22779. cert->issuer.initialsEnc = CTC_UTF8;
  22780. cert->issuer.dnQualifierEnc = CTC_UTF8;
  22781. cert->issuer.dnNameEnc = CTC_UTF8;
  22782. #endif
  22783. cert->issuer.orgEnc = CTC_UTF8;
  22784. cert->issuer.unitEnc = CTC_UTF8;
  22785. cert->issuer.commonNameEnc = CTC_UTF8;
  22786. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  22787. cert->issuer.userIdEnc = CTC_UTF8;
  22788. cert->issuer.postalCodeEnc = CTC_UTF8;
  22789. #ifdef WOLFSSL_CERT_EXT
  22790. cert->issuer.busCatEnc = CTC_UTF8;
  22791. cert->issuer.joiCEnc = CTC_UTF8;
  22792. cert->issuer.joiStEnc = CTC_UTF8;
  22793. #endif
  22794. cert->subject.countryEnc = CTC_PRINTABLE;
  22795. cert->subject.stateEnc = CTC_UTF8;
  22796. cert->subject.streetEnc = CTC_UTF8;
  22797. cert->subject.localityEnc = CTC_UTF8;
  22798. cert->subject.surEnc = CTC_UTF8;
  22799. #ifdef WOLFSSL_CERT_NAME_ALL
  22800. cert->subject.givenNameEnc = CTC_UTF8;
  22801. cert->subject.initialsEnc = CTC_UTF8;
  22802. cert->subject.dnQualifierEnc = CTC_UTF8;
  22803. cert->subject.dnNameEnc = CTC_UTF8;
  22804. #endif
  22805. cert->subject.orgEnc = CTC_UTF8;
  22806. cert->subject.unitEnc = CTC_UTF8;
  22807. cert->subject.commonNameEnc = CTC_UTF8;
  22808. cert->subject.serialDevEnc = CTC_PRINTABLE;
  22809. cert->subject.userIdEnc = CTC_UTF8;
  22810. cert->subject.postalCodeEnc = CTC_UTF8;
  22811. #ifdef WOLFSSL_CERT_EXT
  22812. cert->subject.busCatEnc = CTC_UTF8;
  22813. cert->subject.joiCEnc = CTC_UTF8;
  22814. cert->subject.joiStEnc = CTC_UTF8;
  22815. #endif
  22816. #ifdef WOLFSSL_MULTI_ATTRIB
  22817. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  22818. cert->issuer.name[i].type = CTC_UTF8;
  22819. cert->subject.name[i].type = CTC_UTF8;
  22820. }
  22821. #endif /* WOLFSSL_MULTI_ATTRIB */
  22822. cert->heap = heap;
  22823. (void)devId; /* future */
  22824. return 0;
  22825. }
  22826. WOLFSSL_ABI
  22827. int wc_InitCert(Cert* cert)
  22828. {
  22829. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  22830. }
  22831. WOLFSSL_ABI
  22832. Cert* wc_CertNew(void* heap)
  22833. {
  22834. Cert* certNew;
  22835. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  22836. if (certNew) {
  22837. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  22838. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  22839. certNew = NULL;
  22840. }
  22841. }
  22842. return certNew;
  22843. }
  22844. WOLFSSL_ABI
  22845. void wc_CertFree(Cert* cert)
  22846. {
  22847. if (cert) {
  22848. void* heap = cert->heap;
  22849. ForceZero(cert, sizeof(Cert));
  22850. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  22851. (void)heap;
  22852. }
  22853. }
  22854. /* DER encoded x509 Certificate */
  22855. typedef struct DerCert {
  22856. byte size[MAX_LENGTH_SZ]; /* length encoded */
  22857. byte version[MAX_VERSION_SZ]; /* version encoded */
  22858. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  22859. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  22860. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  22861. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  22862. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  22863. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  22864. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  22865. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  22866. #ifdef WOLFSSL_CERT_EXT
  22867. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  22868. byte akid[MAX_KID_SZ
  22869. #ifdef WOLFSSL_AKID_NAME
  22870. + sizeof(CertName) + CTC_SERIAL_SIZE
  22871. #endif
  22872. ]; /* Authority Key Identifier extension */
  22873. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  22874. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  22875. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22876. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  22877. #endif
  22878. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  22879. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  22880. #endif
  22881. #ifdef WOLFSSL_CERT_REQ
  22882. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  22883. #ifdef WOLFSSL_CUSTOM_OID
  22884. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  22885. #endif
  22886. #endif
  22887. #ifdef WOLFSSL_ALT_NAMES
  22888. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  22889. #endif
  22890. int sizeSz; /* encoded size length */
  22891. int versionSz; /* encoded version length */
  22892. int serialSz; /* encoded serial length */
  22893. int sigAlgoSz; /* encoded sig algo length */
  22894. int issuerSz; /* encoded issuer length */
  22895. int subjectSz; /* encoded subject length */
  22896. int validitySz; /* encoded validity length */
  22897. int publicKeySz; /* encoded public key length */
  22898. int caSz; /* encoded CA extension length */
  22899. #ifdef WOLFSSL_CERT_EXT
  22900. int skidSz; /* encoded SKID extension length */
  22901. int akidSz; /* encoded SKID extension length */
  22902. int keyUsageSz; /* encoded KeyUsage extension length */
  22903. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  22904. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22905. int nsCertTypeSz; /* encoded Netscape Certifcate Type
  22906. * extension length */
  22907. #endif
  22908. int certPoliciesSz; /* encoded CertPolicies extension length*/
  22909. int crlInfoSz; /* encoded CRL Dist Points length */
  22910. #endif
  22911. #ifdef WOLFSSL_ALT_NAMES
  22912. int altNamesSz; /* encoded AltNames extension length */
  22913. #endif
  22914. int extensionsSz; /* encoded extensions total length */
  22915. int total; /* total encoded lengths */
  22916. #ifdef WOLFSSL_CERT_REQ
  22917. int attribSz;
  22918. #ifdef WOLFSSL_CUSTOM_OID
  22919. int extCustomSz;
  22920. #endif
  22921. #endif
  22922. } DerCert;
  22923. #ifdef WOLFSSL_CERT_REQ
  22924. #ifndef WOLFSSL_ASN_TEMPLATE
  22925. /* Write a set header to output */
  22926. static word32 SetPrintableString(word32 len, byte* output)
  22927. {
  22928. output[0] = ASN_PRINTABLE_STRING;
  22929. return SetLength(len, output + 1) + 1;
  22930. }
  22931. static word32 SetUTF8String(word32 len, byte* output)
  22932. {
  22933. output[0] = ASN_UTF8STRING;
  22934. return SetLength(len, output + 1) + 1;
  22935. }
  22936. #endif
  22937. #endif /* WOLFSSL_CERT_REQ */
  22938. #ifndef WOLFSSL_CERT_GEN_CACHE
  22939. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  22940. static
  22941. #endif
  22942. WOLFSSL_ABI
  22943. void wc_SetCert_Free(Cert* cert)
  22944. {
  22945. if (cert != NULL) {
  22946. cert->der = NULL;
  22947. if (cert->decodedCert) {
  22948. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  22949. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  22950. cert->decodedCert = NULL;
  22951. }
  22952. }
  22953. }
  22954. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  22955. int devId)
  22956. {
  22957. int ret;
  22958. if (cert == NULL) {
  22959. ret = BAD_FUNC_ARG;
  22960. }
  22961. else {
  22962. /* Allocate DecodedCert struct and Zero */
  22963. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22964. DYNAMIC_TYPE_DCERT);
  22965. if (cert->decodedCert == NULL) {
  22966. ret = MEMORY_E;
  22967. }
  22968. else {
  22969. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  22970. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  22971. cert->heap, devId);
  22972. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  22973. CERT_TYPE, 0, NULL);
  22974. if (ret >= 0) {
  22975. cert->der = (byte*)der;
  22976. }
  22977. else {
  22978. wc_SetCert_Free(cert);
  22979. }
  22980. }
  22981. }
  22982. return ret;
  22983. }
  22984. #endif /* WOLFSSL_CERT_GEN */
  22985. #ifdef WOLFSSL_CERT_GEN
  22986. #ifndef NO_ASN_TIME
  22987. static WC_INLINE byte itob(int number)
  22988. {
  22989. return (byte)number + 0x30;
  22990. }
  22991. /* write time to output, format */
  22992. static void SetTime(struct tm* date, byte* output)
  22993. {
  22994. int i = 0;
  22995. output[i++] = itob((date->tm_year % 10000) / 1000);
  22996. output[i++] = itob((date->tm_year % 1000) / 100);
  22997. output[i++] = itob((date->tm_year % 100) / 10);
  22998. output[i++] = itob( date->tm_year % 10);
  22999. output[i++] = itob(date->tm_mon / 10);
  23000. output[i++] = itob(date->tm_mon % 10);
  23001. output[i++] = itob(date->tm_mday / 10);
  23002. output[i++] = itob(date->tm_mday % 10);
  23003. output[i++] = itob(date->tm_hour / 10);
  23004. output[i++] = itob(date->tm_hour % 10);
  23005. output[i++] = itob(date->tm_min / 10);
  23006. output[i++] = itob(date->tm_min % 10);
  23007. output[i++] = itob(date->tm_sec / 10);
  23008. output[i++] = itob(date->tm_sec % 10);
  23009. output[i] = 'Z'; /* Zulu profile */
  23010. }
  23011. #endif
  23012. #ifndef WOLFSSL_ASN_TEMPLATE
  23013. /* Copy Dates from cert, return bytes written */
  23014. static int CopyValidity(byte* output, Cert* cert)
  23015. {
  23016. word32 seqSz;
  23017. WOLFSSL_ENTER("CopyValidity");
  23018. /* headers and output */
  23019. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  23020. output);
  23021. if (output) {
  23022. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  23023. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  23024. (size_t)cert->afterDateSz);
  23025. }
  23026. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  23027. }
  23028. #endif /* !WOLFSSL_ASN_TEMPLATE */
  23029. /* Simple name OID size. */
  23030. #define NAME_OID_SZ 3
  23031. /* Domain name OIDs. */
  23032. static const byte nameOid[][NAME_OID_SZ] = {
  23033. { 0x55, 0x04, ASN_COUNTRY_NAME },
  23034. { 0x55, 0x04, ASN_STATE_NAME },
  23035. { 0x55, 0x04, ASN_STREET_ADDR },
  23036. { 0x55, 0x04, ASN_LOCALITY_NAME },
  23037. #ifdef WOLFSSL_CERT_NAME_ALL
  23038. { 0x55, 0x04, ASN_NAME },
  23039. { 0x55, 0x04, ASN_GIVEN_NAME },
  23040. { 0x55, 0x04, ASN_INITIALS },
  23041. { 0x55, 0x04, ASN_DNQUALIFIER },
  23042. #endif
  23043. { 0x55, 0x04, ASN_SUR_NAME },
  23044. { 0x55, 0x04, ASN_ORG_NAME },
  23045. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  23046. /* list all DC values before OUs */
  23047. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  23048. { 0x55, 0x04, ASN_COMMON_NAME },
  23049. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  23050. #ifdef WOLFSSL_CERT_EXT
  23051. { 0x55, 0x04, ASN_BUS_CAT },
  23052. #endif
  23053. { 0x55, 0x04, ASN_POSTAL_CODE },
  23054. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  23055. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  23056. #ifdef WOLFSSL_CUSTOM_OID
  23057. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  23058. #endif
  23059. };
  23060. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  23061. /* Get ASN Name from index */
  23062. byte GetCertNameId(int idx)
  23063. {
  23064. if (idx < NAME_ENTRIES)
  23065. return nameOid[idx][2];
  23066. return 0;
  23067. }
  23068. /* Get Which Name from index */
  23069. const char* GetOneCertName(CertName* name, int idx)
  23070. {
  23071. byte type = GetCertNameId(idx);
  23072. switch (type) {
  23073. case ASN_COUNTRY_NAME:
  23074. return name->country;
  23075. case ASN_STATE_NAME:
  23076. return name->state;
  23077. case ASN_STREET_ADDR:
  23078. return name->street;
  23079. case ASN_LOCALITY_NAME:
  23080. return name->locality;
  23081. #ifdef WOLFSSL_CERT_NAME_ALL
  23082. case ASN_NAME:
  23083. return name->dnName;
  23084. case ASN_GIVEN_NAME:
  23085. return name->givenName;
  23086. case ASN_INITIALS:
  23087. return name->initials;
  23088. case ASN_DNQUALIFIER:
  23089. return name->dnQualifier;
  23090. #endif /* WOLFSSL_CERT_NAME_ALL */
  23091. case ASN_SUR_NAME:
  23092. return name->sur;
  23093. case ASN_ORG_NAME:
  23094. return name->org;
  23095. case ASN_ORGUNIT_NAME:
  23096. return name->unit;
  23097. case ASN_COMMON_NAME:
  23098. return name->commonName;
  23099. case ASN_SERIAL_NUMBER:
  23100. return name->serialDev;
  23101. case ASN_USER_ID:
  23102. return name->userId;
  23103. case ASN_POSTAL_CODE:
  23104. return name->postalCode;
  23105. case ASN_EMAIL_NAME:
  23106. return name->email;
  23107. #ifdef WOLFSSL_CERT_EXT
  23108. case ASN_BUS_CAT:
  23109. return name->busCat;
  23110. #endif
  23111. #ifdef WOLFSSL_CUSTOM_OID
  23112. case ASN_CUSTOM_NAME:
  23113. return (const char*)name->custom.val;
  23114. #endif
  23115. default:
  23116. return NULL;
  23117. }
  23118. }
  23119. /* Get Which Name Encoding from index */
  23120. static char GetNameType(CertName* name, int idx)
  23121. {
  23122. byte type = GetCertNameId(idx);
  23123. switch (type) {
  23124. case ASN_COUNTRY_NAME:
  23125. return name->countryEnc;
  23126. case ASN_STATE_NAME:
  23127. return name->stateEnc;
  23128. case ASN_STREET_ADDR:
  23129. return name->streetEnc;
  23130. case ASN_LOCALITY_NAME:
  23131. return name->localityEnc;
  23132. #ifdef WOLFSSL_CERT_NAME_ALL
  23133. case ASN_NAME:
  23134. return name->dnNameEnc;
  23135. case ASN_GIVEN_NAME:
  23136. return name->givenNameEnc;
  23137. case ASN_INITIALS:
  23138. return name->initialsEnc;
  23139. case ASN_DNQUALIFIER:
  23140. return name->dnQualifierEnc;
  23141. #endif /* WOLFSSL_CERT_NAME_ALL */
  23142. case ASN_SUR_NAME:
  23143. return name->surEnc;
  23144. case ASN_ORG_NAME:
  23145. return name->orgEnc;
  23146. case ASN_ORGUNIT_NAME:
  23147. return name->unitEnc;
  23148. case ASN_COMMON_NAME:
  23149. return name->commonNameEnc;
  23150. case ASN_SERIAL_NUMBER:
  23151. return name->serialDevEnc;
  23152. case ASN_USER_ID:
  23153. return name->userIdEnc;
  23154. case ASN_POSTAL_CODE:
  23155. return name->postalCodeEnc;
  23156. case ASN_EMAIL_NAME:
  23157. return 0; /* special */
  23158. #ifdef WOLFSSL_CERT_EXT
  23159. case ASN_BUS_CAT:
  23160. return name->busCatEnc;
  23161. #endif
  23162. #ifdef WOLFSSL_CUSTOM_OID
  23163. case ASN_CUSTOM_NAME:
  23164. return name->custom.enc;
  23165. #endif
  23166. default:
  23167. return 0;
  23168. }
  23169. }
  23170. #ifndef WOLFSSL_ASN_TEMPLATE
  23171. /*
  23172. Extensions ::= SEQUENCE OF Extension
  23173. Extension ::= SEQUENCE {
  23174. extnId OBJECT IDENTIFIER,
  23175. critical BOOLEAN DEFAULT FALSE,
  23176. extnValue OCTET STRING }
  23177. */
  23178. /* encode all extensions, return total bytes written */
  23179. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  23180. const byte* ext, int extSz)
  23181. {
  23182. if (out == NULL || IdxInOut == NULL || ext == NULL)
  23183. return BAD_FUNC_ARG;
  23184. if (outSz < (word32)(*IdxInOut+extSz))
  23185. return BUFFER_E;
  23186. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  23187. *IdxInOut += extSz;
  23188. return *IdxInOut;
  23189. }
  23190. /* encode extensions header, return total bytes written */
  23191. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  23192. {
  23193. byte sequence[MAX_SEQ_SZ];
  23194. byte len[MAX_LENGTH_SZ];
  23195. word32 seqSz, lenSz, idx = 0;
  23196. if (out == NULL)
  23197. return BAD_FUNC_ARG;
  23198. if (outSz < 3)
  23199. return BUFFER_E;
  23200. seqSz = SetSequence(extSz, sequence);
  23201. /* encode extensions length provided */
  23202. lenSz = SetLength(extSz+seqSz, len);
  23203. if (outSz < (word32)(lenSz+seqSz+1))
  23204. return BUFFER_E;
  23205. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  23206. XMEMCPY(&out[idx], len, lenSz); /* length */
  23207. idx += lenSz;
  23208. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  23209. idx += seqSz;
  23210. return (int)idx;
  23211. }
  23212. /* encode CA basic constraints true with path length
  23213. * return total bytes written */
  23214. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  23215. {
  23216. /* ASN1->DER sequence for Basic Constraints True and path length */
  23217. const byte caPathLenBasicConstASN1[] = {
  23218. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  23219. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  23220. 0x00
  23221. };
  23222. if (out == NULL)
  23223. return BAD_FUNC_ARG;
  23224. if (outSz < sizeof(caPathLenBasicConstASN1))
  23225. return BUFFER_E;
  23226. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23227. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23228. return (int)sizeof(caPathLenBasicConstASN1);
  23229. }
  23230. /* encode CA basic constraints true
  23231. * return total bytes written */
  23232. static int SetCa(byte* out, word32 outSz)
  23233. {
  23234. /* ASN1->DER sequence for Basic Constraints True */
  23235. const byte caBasicConstASN1[] = {
  23236. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23237. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23238. };
  23239. if (out == NULL)
  23240. return BAD_FUNC_ARG;
  23241. if (outSz < sizeof(caBasicConstASN1))
  23242. return BUFFER_E;
  23243. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23244. return (int)sizeof(caBasicConstASN1);
  23245. }
  23246. /* encode basic constraints without CA Boolean
  23247. * return total bytes written */
  23248. static int SetBC(byte* out, word32 outSz)
  23249. {
  23250. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23251. const byte BasicConstASN1[] = {
  23252. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23253. 0x02, 0x30, 0x00
  23254. };
  23255. if (out == NULL)
  23256. return BAD_FUNC_ARG;
  23257. if (outSz < sizeof(BasicConstASN1))
  23258. return BUFFER_E;
  23259. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23260. return (int)sizeof(BasicConstASN1);
  23261. }
  23262. #endif
  23263. #ifdef WOLFSSL_CERT_EXT
  23264. #ifndef WOLFSSL_ASN_TEMPLATE
  23265. /* encode OID and associated value, return total bytes written */
  23266. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23267. byte *in, word32 inSz)
  23268. {
  23269. word32 idx = 0;
  23270. if (out == NULL || oid == NULL || in == NULL)
  23271. return BAD_FUNC_ARG;
  23272. if (outSz < 3)
  23273. return BUFFER_E;
  23274. /* sequence, + 1 => byte to put value size */
  23275. idx = SetSequence(inSz + oidSz + 1, out);
  23276. if ((idx + inSz + oidSz + 1) > outSz)
  23277. return BUFFER_E;
  23278. XMEMCPY(out+idx, oid, oidSz);
  23279. idx += oidSz;
  23280. out[idx++] = (byte)inSz;
  23281. XMEMCPY(out+idx, in, inSz);
  23282. return (int)(idx+inSz);
  23283. }
  23284. /* encode Subject Key Identifier, return total bytes written
  23285. * RFC5280 : non-critical */
  23286. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23287. {
  23288. byte skid_len[1 + MAX_LENGTH_SZ];
  23289. byte skid_enc_len[MAX_LENGTH_SZ];
  23290. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  23291. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23292. if (output == NULL || input == NULL)
  23293. return BAD_FUNC_ARG;
  23294. /* Octet String header */
  23295. skid_lenSz = SetOctetString(length, skid_len);
  23296. /* length of encoded value */
  23297. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23298. if (outSz < 3)
  23299. return BUFFER_E;
  23300. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  23301. skid_enc_lenSz, output);
  23302. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23303. return BUFFER_E;
  23304. /* put oid */
  23305. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23306. idx += sizeof(skid_oid);
  23307. /* put encoded len */
  23308. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23309. idx += skid_enc_lenSz;
  23310. /* put octet header */
  23311. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23312. idx += skid_lenSz;
  23313. /* put value */
  23314. XMEMCPY(output+idx, input, length);
  23315. idx += length;
  23316. return (int)idx;
  23317. }
  23318. /* encode Authority Key Identifier, return total bytes written
  23319. * RFC5280 : non-critical */
  23320. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23321. byte rawAkid)
  23322. {
  23323. int enc_valSz;
  23324. byte enc_val_buf[MAX_KID_SZ];
  23325. byte* enc_val;
  23326. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23327. const byte akid_cs[] = { 0x80 };
  23328. word32 inSeqSz, idx;
  23329. (void)rawAkid;
  23330. if (output == NULL || input == NULL)
  23331. return BAD_FUNC_ARG;
  23332. #ifdef WOLFSSL_AKID_NAME
  23333. if (rawAkid) {
  23334. enc_val = input;
  23335. enc_valSz = length;
  23336. }
  23337. else
  23338. #endif
  23339. {
  23340. enc_val = enc_val_buf;
  23341. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  23342. if (enc_valSz > (int)sizeof(enc_val_buf))
  23343. return BAD_FUNC_ARG;
  23344. /* sequence for ContentSpec & value */
  23345. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  23346. sizeof(akid_cs), input, length);
  23347. if (enc_valSz <= 0)
  23348. return enc_valSz;
  23349. }
  23350. /* The size of the extension sequence contents */
  23351. inSeqSz = (word32)sizeof(akid_oid) +
  23352. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  23353. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23354. return BAD_FUNC_ARG;
  23355. /* Write out the sequence header */
  23356. idx = SetSequence(inSeqSz, output);
  23357. /* Write out OID */
  23358. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23359. idx += sizeof(akid_oid);
  23360. /* Write out AKID */
  23361. idx += SetOctetString((word32)enc_valSz, output + idx);
  23362. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  23363. return (int)idx + enc_valSz;
  23364. }
  23365. /* encode Key Usage, return total bytes written
  23366. * RFC5280 : critical */
  23367. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23368. {
  23369. byte ku[5];
  23370. word32 idx;
  23371. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23372. 0x01, 0x01, 0xff, 0x04};
  23373. if (output == NULL)
  23374. return BAD_FUNC_ARG;
  23375. idx = SetBitString16Bit(input, ku);
  23376. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23377. ku, idx);
  23378. }
  23379. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  23380. const byte* oid, word32 oidSz)
  23381. {
  23382. /* verify room */
  23383. if (*idx + 2 + oidSz >= outSz)
  23384. return ASN_PARSE_E;
  23385. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  23386. XMEMCPY(&output[*idx], oid, oidSz);
  23387. *idx += oidSz;
  23388. return 0;
  23389. }
  23390. #endif
  23391. #ifdef WOLFSSL_ASN_TEMPLATE
  23392. /* ASN.1 template for extended key usage.
  23393. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23394. * Dynamic creation of template for encoding.
  23395. */
  23396. static const ASNItem ekuASN[] = {
  23397. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23398. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23399. };
  23400. enum {
  23401. EKUASN_IDX_SEQ = 0,
  23402. EKUASN_IDX_OID
  23403. };
  23404. /* OIDs corresponding to extended key usage. */
  23405. struct {
  23406. const byte* oid;
  23407. word32 oidSz;
  23408. } ekuOid[] = {
  23409. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23410. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23411. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23412. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23413. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23414. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23415. };
  23416. #define EKU_OID_LO 1
  23417. #define EKU_OID_HI 6
  23418. #endif /* WOLFSSL_ASN_TEMPLATE */
  23419. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23420. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23421. {
  23422. #ifndef WOLFSSL_ASN_TEMPLATE
  23423. word32 idx = 0, oidListSz = 0, totalSz;
  23424. int ret = 0;
  23425. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23426. if (output == NULL)
  23427. return BAD_FUNC_ARG;
  23428. /* Skip to OID List */
  23429. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23430. idx = totalSz;
  23431. /* Build OID List */
  23432. /* If any set, then just use it */
  23433. if (input & EXTKEYUSE_ANY) {
  23434. ret |= SetOjectIdValue(output, outSz, &idx,
  23435. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23436. }
  23437. else {
  23438. if (input & EXTKEYUSE_SERVER_AUTH)
  23439. ret |= SetOjectIdValue(output, outSz, &idx,
  23440. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23441. if (input & EXTKEYUSE_CLIENT_AUTH)
  23442. ret |= SetOjectIdValue(output, outSz, &idx,
  23443. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23444. if (input & EXTKEYUSE_CODESIGN)
  23445. ret |= SetOjectIdValue(output, outSz, &idx,
  23446. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23447. if (input & EXTKEYUSE_EMAILPROT)
  23448. ret |= SetOjectIdValue(output, outSz, &idx,
  23449. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23450. if (input & EXTKEYUSE_TIMESTAMP)
  23451. ret |= SetOjectIdValue(output, outSz, &idx,
  23452. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23453. if (input & EXTKEYUSE_OCSP_SIGN)
  23454. ret |= SetOjectIdValue(output, outSz, &idx,
  23455. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23456. #ifdef WOLFSSL_EKU_OID
  23457. /* iterate through OID values */
  23458. if (input & EXTKEYUSE_USER) {
  23459. int i, sz;
  23460. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23461. sz = cert->extKeyUsageOIDSz[i];
  23462. if (sz > 0) {
  23463. ret |= SetOjectIdValue(output, outSz, &idx,
  23464. cert->extKeyUsageOID[i], sz);
  23465. }
  23466. }
  23467. }
  23468. #endif /* WOLFSSL_EKU_OID */
  23469. }
  23470. if (ret != 0)
  23471. return ASN_PARSE_E;
  23472. /* Calculate Sizes */
  23473. oidListSz = idx - totalSz;
  23474. totalSz = idx - 2; /* exclude first seq/len (2) */
  23475. /* 1. Seq + Total Len (2) */
  23476. idx = SetSequence(totalSz, output);
  23477. /* 2. Object ID (2) */
  23478. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23479. idx += sizeof(extkeyusage_oid);
  23480. /* 3. Octet String (2) */
  23481. idx += SetOctetString(totalSz - idx, &output[idx]);
  23482. /* 4. Seq + OidListLen (2) */
  23483. idx += SetSequence(oidListSz, &output[idx]);
  23484. /* 5. Oid List (already set in-place above) */
  23485. idx += oidListSz;
  23486. (void)cert;
  23487. return (int)idx;
  23488. #else
  23489. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23490. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23491. ASNSetData* dataASN;
  23492. ASNItem* extKuASN = NULL;
  23493. int asnIdx = 1;
  23494. size_t cnt = 1 + EKU_OID_HI;
  23495. int i;
  23496. int ret = 0;
  23497. int sz = 0;
  23498. #ifdef WOLFSSL_EKU_OID
  23499. cnt += CTC_MAX_EKU_NB;
  23500. #endif
  23501. /* Allocate memory for dynamic data items. */
  23502. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23503. DYNAMIC_TYPE_TMP_BUFFER);
  23504. if (dataASN == NULL) {
  23505. ret = MEMORY_E;
  23506. }
  23507. if (ret == 0) {
  23508. /* Allocate memory for dynamic ASN.1 template. */
  23509. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23510. DYNAMIC_TYPE_TMP_BUFFER);
  23511. if (extKuASN == NULL) {
  23512. ret = MEMORY_E;
  23513. }
  23514. }
  23515. if (ret == 0) {
  23516. /* Copy Sequence into dynamic ASN.1 template. */
  23517. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23518. /* Clear dynamic data. */
  23519. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23520. /* Build up the template and data. */
  23521. /* If 'any' set, then just use it. */
  23522. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23523. /* Set template item. */
  23524. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23525. sizeof(ASNItem));
  23526. /* Set data item. */
  23527. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23528. sizeof(extExtKeyUsageAnyOid));
  23529. asnIdx++;
  23530. }
  23531. else {
  23532. /* Step through the flagged purposes. */
  23533. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23534. if ((input & (1 << i)) != 0) {
  23535. /* Set template item. */
  23536. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23537. sizeof(ASNItem));
  23538. /* Set data item. */
  23539. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23540. ekuOid[i - 1].oidSz);
  23541. asnIdx++;
  23542. }
  23543. }
  23544. #ifdef WOLFSSL_EKU_OID
  23545. if (input & EXTKEYUSE_USER) {
  23546. /* Iterate through OID values */
  23547. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23548. sz = cert->extKeyUsageOIDSz[i];
  23549. if (sz > 0) {
  23550. /* Set template item. */
  23551. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23552. sizeof(ASNItem));
  23553. /* Set data item. */
  23554. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23555. sz);
  23556. asnIdx++;
  23557. }
  23558. }
  23559. }
  23560. #endif /* WOLFSSL_EKU_OID */
  23561. (void)cert;
  23562. }
  23563. /* Calculate size of encoding. */
  23564. sz = 0;
  23565. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23566. }
  23567. /* When buffer to write to, ensure it's big enough. */
  23568. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23569. ret = BUFFER_E;
  23570. }
  23571. if ((ret == 0) && (output != NULL)) {
  23572. /* Encode extended key usage. */
  23573. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23574. }
  23575. if (ret == 0) {
  23576. /* Return the encoding size. */
  23577. ret = sz;
  23578. }
  23579. /* Dispose of allocated data. */
  23580. if (extKuASN != NULL) {
  23581. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23582. }
  23583. if (dataASN != NULL) {
  23584. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23585. }
  23586. return ret;
  23587. #endif
  23588. }
  23589. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23590. #ifndef WOLFSSL_ASN_TEMPLATE
  23591. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23592. {
  23593. word32 idx;
  23594. byte unusedBits = 0;
  23595. byte nsCertType = input;
  23596. word32 totalSz;
  23597. word32 bitStrSz;
  23598. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23599. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23600. if (cert == NULL || output == NULL ||
  23601. input == 0)
  23602. return BAD_FUNC_ARG;
  23603. totalSz = sizeof(nscerttype_oid);
  23604. /* Get amount of lsb zero's */
  23605. for (;(input & 1) == 0; input >>= 1)
  23606. unusedBits++;
  23607. /* 1 byte of NS Cert Type extension */
  23608. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23609. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23610. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23611. return BAD_FUNC_ARG;
  23612. /* 1. Seq + Total Len */
  23613. idx = SetSequence(totalSz, output);
  23614. /* 2. Object ID */
  23615. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23616. idx += sizeof(nscerttype_oid);
  23617. /* 3. Octet String */
  23618. idx += SetOctetString(bitStrSz, &output[idx]);
  23619. /* 4. Bit String */
  23620. idx += SetBitString(1, unusedBits, &output[idx]);
  23621. output[idx++] = nsCertType;
  23622. return (int)idx;
  23623. }
  23624. #endif
  23625. #endif
  23626. #ifndef WOLFSSL_ASN_TEMPLATE
  23627. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23628. int inSz)
  23629. {
  23630. word32 idx;
  23631. word32 totalSz;
  23632. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23633. if (cert == NULL || output == NULL ||
  23634. input == 0 || inSz <= 0)
  23635. return BAD_FUNC_ARG;
  23636. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  23637. (word32)inSz;
  23638. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23639. return BAD_FUNC_ARG;
  23640. /* 1. Seq + Total Len */
  23641. idx = SetSequence(totalSz, output);
  23642. /* 2. Object ID */
  23643. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23644. idx += sizeof(crlinfo_oid);
  23645. /* 3. Octet String */
  23646. idx += SetOctetString((word32)inSz, &output[idx]);
  23647. /* 4. CRL Info */
  23648. XMEMCPY(&output[idx], input, (size_t)inSz);
  23649. idx += (word32)inSz;
  23650. return (int)idx;
  23651. }
  23652. #endif
  23653. /* encode Certificate Policies, return total bytes written
  23654. * each input value must be ITU-T X.690 formatted : a.b.c...
  23655. * input must be an array of values with a NULL terminated for the latest
  23656. * RFC5280 : non-critical */
  23657. static int SetCertificatePolicies(byte *output,
  23658. word32 outputSz,
  23659. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23660. word16 nb_certpol,
  23661. void* heap)
  23662. {
  23663. #ifndef WOLFSSL_ASN_TEMPLATE
  23664. byte oid[MAX_OID_SZ];
  23665. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  23666. byte out[MAX_CERTPOL_SZ];
  23667. word32 oidSz;
  23668. word32 outSz;
  23669. word32 i = 0;
  23670. word32 der_oidSz[MAX_CERTPOL_NB];
  23671. int ret;
  23672. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  23673. const byte oid_oid[] = { 0x06 };
  23674. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  23675. return BAD_FUNC_ARG;
  23676. for (i = 0; i < nb_certpol; i++) {
  23677. oidSz = sizeof(oid);
  23678. XMEMSET(oid, 0, oidSz);
  23679. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23680. if (ret != 0)
  23681. return ret;
  23682. /* compute sequence value for the oid */
  23683. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  23684. sizeof(oid_oid), oid, oidSz);
  23685. if (ret <= 0)
  23686. return ret;
  23687. else
  23688. der_oidSz[i] = (word32)ret;
  23689. }
  23690. /* concatenate oid, keep two byte for sequence/size of the created value */
  23691. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  23692. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  23693. outSz += der_oidSz[i];
  23694. }
  23695. /* add sequence */
  23696. ret = (int)SetSequence(outSz-2, out);
  23697. if (ret <= 0)
  23698. return ret;
  23699. /* add Policy OID to compute final value */
  23700. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  23701. out, outSz);
  23702. #else
  23703. int i;
  23704. int ret = 0;
  23705. byte oid[MAX_OID_SZ];
  23706. word32 oidSz;
  23707. word32 sz = 0;
  23708. int piSz;
  23709. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  23710. ret = BAD_FUNC_ARG;
  23711. }
  23712. /* Put in policyIdentifier but not policyQualifiers. */
  23713. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  23714. ASNSetData dataASN[policyInfoASN_Length];
  23715. oidSz = sizeof(oid);
  23716. XMEMSET(oid, 0, oidSz);
  23717. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  23718. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23719. if (ret == 0) {
  23720. XMEMSET(dataASN, 0, sizeof(dataASN));
  23721. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  23722. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23723. &piSz);
  23724. }
  23725. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  23726. ret = BUFFER_E;
  23727. }
  23728. if (ret == 0) {
  23729. if (output != NULL) {
  23730. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23731. output);
  23732. output += piSz;
  23733. }
  23734. sz += (word32)piSz;
  23735. }
  23736. }
  23737. if (ret == 0) {
  23738. ret = (int)sz;
  23739. }
  23740. return ret;
  23741. #endif
  23742. }
  23743. #endif /* WOLFSSL_CERT_EXT */
  23744. #ifdef WOLFSSL_ALT_NAMES
  23745. #ifndef WOLFSSL_ASN_TEMPLATE
  23746. /* encode Alternative Names, return total bytes written */
  23747. static int SetAltNames(byte *output, word32 outSz,
  23748. const byte *input, word32 length, int critical)
  23749. {
  23750. byte san_len[1 + MAX_LENGTH_SZ];
  23751. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  23752. const byte san_crit[] = { 0x01, 0x01, 0xff };
  23753. word32 seqSz, san_lenSz, idx = 0;
  23754. if (output == NULL || input == NULL)
  23755. return BAD_FUNC_ARG;
  23756. if (outSz < length)
  23757. return BUFFER_E;
  23758. /* Octet String header */
  23759. san_lenSz = SetOctetString(length, san_len);
  23760. if (outSz < MAX_SEQ_SZ)
  23761. return BUFFER_E;
  23762. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  23763. if (critical)
  23764. seqSz += sizeof(san_crit);
  23765. idx = SetSequence(seqSz, output);
  23766. if (seqSz > outSz)
  23767. return BUFFER_E;
  23768. /* put oid */
  23769. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  23770. idx += sizeof(san_oid);
  23771. if (critical) {
  23772. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  23773. idx += sizeof(san_crit);
  23774. }
  23775. /* put octet header */
  23776. XMEMCPY(output+idx, san_len, san_lenSz);
  23777. idx += san_lenSz;
  23778. /* put value */
  23779. XMEMCPY(output+idx, input, length);
  23780. idx += length;
  23781. return (int)idx;
  23782. }
  23783. #endif /* WOLFSSL_ASN_TEMPLATE */
  23784. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  23785. {
  23786. word32 idx;
  23787. const DNS_entry* curName;
  23788. word32 namesSz = 0;
  23789. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23790. word32 i;
  23791. #endif
  23792. if (output == NULL)
  23793. return BAD_FUNC_ARG;
  23794. if (names == NULL)
  23795. return 0;
  23796. curName = names;
  23797. do {
  23798. namesSz += (word32)curName->len + 2 +
  23799. ((curName->len < ASN_LONG_LENGTH) ? 0
  23800. : BytePrecision((word32)curName->len));
  23801. curName = curName->next;
  23802. } while (curName != NULL);
  23803. if (outputSz < MAX_SEQ_SZ + namesSz)
  23804. return BUFFER_E;
  23805. idx = SetSequence(namesSz, output);
  23806. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23807. namesSz += idx;
  23808. i = namesSz;
  23809. #endif
  23810. curName = names;
  23811. do {
  23812. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23813. word32 len = SetLength(curName->len, NULL);
  23814. idx = i - curName->len - len - 1;
  23815. i = idx;
  23816. #endif
  23817. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  23818. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  23819. output[idx] |= ASN_CONSTRUCTED;
  23820. }
  23821. idx++;
  23822. idx += SetLength((word32)curName->len, output + idx);
  23823. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  23824. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  23825. idx += (word32)curName->len;
  23826. #endif
  23827. curName = curName->next;
  23828. } while (curName != NULL);
  23829. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23830. idx = namesSz;
  23831. #endif
  23832. return (int)idx;
  23833. }
  23834. #endif /* WOLFSSL_ALT_NAMES */
  23835. #endif /* WOLFSSL_CERT_GEN */
  23836. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23837. /* Simple domain name OID size. */
  23838. #define DN_OID_SZ 3
  23839. /* Encodes one attribute of the name (issuer/subject)
  23840. *
  23841. * name structure to hold result of encoding
  23842. * nameStr value to be encoded
  23843. * nameTag tag of encoding i.e CTC_UTF8
  23844. * type id of attribute i.e ASN_COMMON_NAME
  23845. * emailTag tag of email i.e CTC_UTF8
  23846. * returns length on success
  23847. */
  23848. static int EncodeName(EncodedName* name, const char* nameStr,
  23849. byte nameTag, byte type, byte emailTag, CertName* cname)
  23850. {
  23851. #if !defined(WOLFSSL_ASN_TEMPLATE)
  23852. word32 idx = 0;
  23853. /* bottom up */
  23854. byte firstLen[1 + MAX_LENGTH_SZ];
  23855. byte secondLen[MAX_LENGTH_SZ];
  23856. byte sequence[MAX_SEQ_SZ];
  23857. byte set[MAX_SET_SZ];
  23858. word32 strLen;
  23859. word32 thisLen;
  23860. word32 firstSz, secondSz, seqSz, setSz;
  23861. if (nameStr == NULL) {
  23862. name->used = 0;
  23863. return 0;
  23864. }
  23865. thisLen = strLen = (word32)XSTRLEN(nameStr);
  23866. #ifdef WOLFSSL_CUSTOM_OID
  23867. if (type == ASN_CUSTOM_NAME) {
  23868. if (cname == NULL || cname->custom.oidSz == 0) {
  23869. name->used = 0;
  23870. return 0;
  23871. }
  23872. thisLen = strLen = (word32)cname->custom.valSz;
  23873. }
  23874. #else
  23875. (void)cname;
  23876. #endif
  23877. if (strLen == 0) { /* no user data for this item */
  23878. name->used = 0;
  23879. return 0;
  23880. }
  23881. /* Restrict country code size */
  23882. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  23883. WOLFSSL_MSG("Country code size error");
  23884. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  23885. return ASN_COUNTRY_SIZE_E;
  23886. }
  23887. secondSz = SetLength(strLen, secondLen);
  23888. thisLen += secondSz;
  23889. switch (type) {
  23890. case ASN_EMAIL_NAME: /* email */
  23891. thisLen += (int)sizeof(attrEmailOid);
  23892. firstSz = (int)sizeof(attrEmailOid);
  23893. break;
  23894. case ASN_DOMAIN_COMPONENT:
  23895. thisLen += (int)sizeof(dcOid);
  23896. firstSz = (int)sizeof(dcOid);
  23897. break;
  23898. case ASN_USER_ID:
  23899. thisLen += (int)sizeof(uidOid);
  23900. firstSz = (int)sizeof(uidOid);
  23901. break;
  23902. case ASN_FAVOURITE_DRINK:
  23903. thisLen += (int)sizeof(fvrtDrk);
  23904. firstSz = (int)sizeof(fvrtDrk);
  23905. break;
  23906. #ifdef WOLFSSL_CUSTOM_OID
  23907. case ASN_CUSTOM_NAME:
  23908. thisLen += cname->custom.oidSz;
  23909. firstSz = cname->custom.oidSz;
  23910. break;
  23911. #endif
  23912. default:
  23913. thisLen += DN_OID_SZ;
  23914. firstSz = DN_OID_SZ;
  23915. }
  23916. thisLen++; /* id type */
  23917. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  23918. thisLen += firstSz;
  23919. seqSz = SetSequence(thisLen, sequence);
  23920. thisLen += seqSz;
  23921. setSz = SetSet(thisLen, set);
  23922. thisLen += setSz;
  23923. if (thisLen > (int)sizeof(name->encoded)) {
  23924. return BUFFER_E;
  23925. }
  23926. /* store it */
  23927. idx = 0;
  23928. /* set */
  23929. XMEMCPY(name->encoded, set, setSz);
  23930. idx += setSz;
  23931. /* seq */
  23932. XMEMCPY(name->encoded + idx, sequence, seqSz);
  23933. idx += seqSz;
  23934. /* asn object id */
  23935. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  23936. idx += firstSz;
  23937. switch (type) {
  23938. case ASN_EMAIL_NAME:
  23939. /* email joint id */
  23940. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  23941. idx += (int)sizeof(attrEmailOid);
  23942. name->encoded[idx++] = emailTag;
  23943. break;
  23944. case ASN_DOMAIN_COMPONENT:
  23945. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  23946. idx += (int)sizeof(dcOid)-1;
  23947. /* id type */
  23948. name->encoded[idx++] = type;
  23949. /* str type */
  23950. name->encoded[idx++] = nameTag;
  23951. break;
  23952. case ASN_USER_ID:
  23953. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  23954. idx += (int)sizeof(uidOid);
  23955. /* str type */
  23956. name->encoded[idx++] = nameTag;
  23957. break;
  23958. case ASN_FAVOURITE_DRINK:
  23959. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  23960. idx += (int)sizeof(fvrtDrk);
  23961. /* str type */
  23962. name->encoded[idx++] = nameTag;
  23963. break;
  23964. #ifdef WOLFSSL_CUSTOM_OID
  23965. case ASN_CUSTOM_NAME:
  23966. XMEMCPY(name->encoded + idx, cname->custom.oid,
  23967. cname->custom.oidSz);
  23968. idx += cname->custom.oidSz;
  23969. /* str type */
  23970. name->encoded[idx++] = nameTag;
  23971. break;
  23972. #endif
  23973. default:
  23974. name->encoded[idx++] = 0x55;
  23975. name->encoded[idx++] = 0x04;
  23976. /* id type */
  23977. name->encoded[idx++] = type;
  23978. /* str type */
  23979. name->encoded[idx++] = nameTag;
  23980. }
  23981. /* second length */
  23982. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  23983. idx += secondSz;
  23984. /* str value */
  23985. XMEMCPY(name->encoded + idx, nameStr, strLen);
  23986. idx += strLen;
  23987. name->type = type;
  23988. name->totalLen = (int)idx;
  23989. name->used = 1;
  23990. return (int)idx;
  23991. #else
  23992. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  23993. ASNItem namesASN[rdnASN_Length];
  23994. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  23995. int ret = 0;
  23996. int sz = 0;
  23997. const byte* oid;
  23998. word32 oidSz;
  23999. word32 nameSz;
  24000. /* Validate input parameters. */
  24001. if ((name == NULL) || (nameStr == NULL)) {
  24002. ret = BAD_FUNC_ARG;
  24003. }
  24004. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  24005. if (ret == 0) {
  24006. nameSz = (word32)XSTRLEN(nameStr);
  24007. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  24008. * based on type. */
  24009. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  24010. /* Set OID and ASN.1 tag for name depending on type. */
  24011. switch (type) {
  24012. case ASN_EMAIL_NAME:
  24013. /* email OID different to standard types. */
  24014. oid = attrEmailOid;
  24015. oidSz = sizeof(attrEmailOid);
  24016. /* Use email specific type/tag. */
  24017. nameTag = emailTag;
  24018. break;
  24019. case ASN_DOMAIN_COMPONENT:
  24020. /* Domain component OID different to standard types. */
  24021. oid = dcOid;
  24022. oidSz = sizeof(dcOid);
  24023. break;
  24024. case ASN_USER_ID:
  24025. /* Domain component OID different to standard types. */
  24026. oid = uidOid;
  24027. oidSz = sizeof(uidOid);
  24028. break;
  24029. case ASN_FAVOURITE_DRINK:
  24030. oid = fvrtDrk;
  24031. oidSz = sizeof(fvrtDrk);
  24032. break;
  24033. #ifdef WOLFSSL_CUSTOM_OID
  24034. case ASN_CUSTOM_NAME:
  24035. nameSz = cname->custom.valSz;
  24036. oid = cname->custom.oid;
  24037. oidSz = cname->custom.oidSz;
  24038. break;
  24039. #endif
  24040. default:
  24041. /* Construct OID using type. */
  24042. dnOid[2] = type;
  24043. oid = dnOid;
  24044. oidSz = DN_OID_SZ;
  24045. break;
  24046. }
  24047. /* Set OID corresponding to the name type. */
  24048. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24049. /* Set name string. */
  24050. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  24051. /* Set the ASN.1 tag for the name string. */
  24052. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  24053. /* Calculate size of encoded name and indexes of components. */
  24054. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  24055. }
  24056. /* Check if name's buffer is big enough. */
  24057. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  24058. ret = BUFFER_E;
  24059. }
  24060. if (ret == 0) {
  24061. /* Encode name into the buffer. */
  24062. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  24063. /* Cache the type and size, and set that it is used. */
  24064. name->type = type;
  24065. name->totalLen = sz;
  24066. name->used = 1;
  24067. /* Return size of encoding. */
  24068. ret = sz;
  24069. }
  24070. (void)cname;
  24071. FREE_ASNSETDATA(dataASN, NULL);
  24072. return ret;
  24073. #endif /* WOLFSSL_ASN_TEMPLATE */
  24074. }
  24075. /* canonical encoding one attribute of the name (issuer/subject)
  24076. * call EncodeName with CTC_UTF8 for email type
  24077. *
  24078. * name structure to hold result of encoding
  24079. * nameStr value to be encoded
  24080. * nameType type of encoding i.e CTC_UTF8
  24081. * type id of attribute i.e ASN_COMMON_NAME
  24082. *
  24083. * returns length on success
  24084. */
  24085. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  24086. char nameType, byte type)
  24087. {
  24088. return EncodeName(name, nameStr, (byte)nameType, type,
  24089. ASN_UTF8STRING, NULL);
  24090. }
  24091. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  24092. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) || \
  24093. (defined(OPENSSL_ALL) || defined(OPENSSL_EXTRA))
  24094. /* Convert key usage string (comma delimited, null terminated) to word16
  24095. * Returns 0 on success, negative on error */
  24096. int ParseKeyUsageStr(const char* value, word16* keyUsage, void* heap)
  24097. {
  24098. int ret = 0;
  24099. char *token, *str, *ptr;
  24100. word32 len = 0;
  24101. word16 usage = 0;
  24102. if (value == NULL || keyUsage == NULL) {
  24103. return BAD_FUNC_ARG;
  24104. }
  24105. /* duplicate string (including terminator) */
  24106. len = (word32)XSTRLEN(value);
  24107. str = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24108. if (str == NULL) {
  24109. return MEMORY_E;
  24110. }
  24111. XMEMCPY(str, value, len + 1);
  24112. /* parse value, and set corresponding Key Usage value */
  24113. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  24114. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24115. return KEYUSAGE_E;
  24116. }
  24117. while (token != NULL) {
  24118. if (!XSTRCASECMP(token, "digitalSignature"))
  24119. usage |= KEYUSE_DIGITAL_SIG;
  24120. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  24121. !XSTRCASECMP(token, "contentCommitment"))
  24122. usage |= KEYUSE_CONTENT_COMMIT;
  24123. else if (!XSTRCASECMP(token, "keyEncipherment"))
  24124. usage |= KEYUSE_KEY_ENCIPHER;
  24125. else if (!XSTRCASECMP(token, "dataEncipherment"))
  24126. usage |= KEYUSE_DATA_ENCIPHER;
  24127. else if (!XSTRCASECMP(token, "keyAgreement"))
  24128. usage |= KEYUSE_KEY_AGREE;
  24129. else if (!XSTRCASECMP(token, "keyCertSign"))
  24130. usage |= KEYUSE_KEY_CERT_SIGN;
  24131. else if (!XSTRCASECMP(token, "cRLSign"))
  24132. usage |= KEYUSE_CRL_SIGN;
  24133. else if (!XSTRCASECMP(token, "encipherOnly"))
  24134. usage |= KEYUSE_ENCIPHER_ONLY;
  24135. else if (!XSTRCASECMP(token, "decipherOnly"))
  24136. usage |= KEYUSE_DECIPHER_ONLY;
  24137. else {
  24138. ret = KEYUSAGE_E;
  24139. break;
  24140. }
  24141. token = XSTRTOK(NULL, ",", &ptr);
  24142. }
  24143. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24144. if (ret == 0) {
  24145. *keyUsage = usage;
  24146. }
  24147. return ret;
  24148. }
  24149. /* Convert extended key usage string (comma delimited, null terminated) to byte
  24150. * Returns 0 on success, negative on error */
  24151. int ParseExtKeyUsageStr(const char* value, byte* extKeyUsage, void* heap)
  24152. {
  24153. int ret = 0;
  24154. char *token, *str, *ptr;
  24155. word32 len = 0;
  24156. byte usage = 0;
  24157. if (value == NULL || extKeyUsage == NULL) {
  24158. return BAD_FUNC_ARG;
  24159. }
  24160. /* duplicate string (including terminator) */
  24161. len = (word32)XSTRLEN(value);
  24162. str = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24163. if (str == NULL) {
  24164. return MEMORY_E;
  24165. }
  24166. XMEMCPY(str, value, len + 1);
  24167. /* parse value, and set corresponding Key Usage value */
  24168. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  24169. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24170. return EXTKEYUSAGE_E;
  24171. }
  24172. while (token != NULL) {
  24173. if (!XSTRCASECMP(token, "any"))
  24174. usage |= EXTKEYUSE_ANY;
  24175. else if (!XSTRCASECMP(token, "serverAuth"))
  24176. usage |= EXTKEYUSE_SERVER_AUTH;
  24177. else if (!XSTRCASECMP(token, "clientAuth"))
  24178. usage |= EXTKEYUSE_CLIENT_AUTH;
  24179. else if (!XSTRCASECMP(token, "codeSigning"))
  24180. usage |= EXTKEYUSE_CODESIGN;
  24181. else if (!XSTRCASECMP(token, "emailProtection"))
  24182. usage |= EXTKEYUSE_EMAILPROT;
  24183. else if (!XSTRCASECMP(token, "timeStamping"))
  24184. usage |= EXTKEYUSE_TIMESTAMP;
  24185. else if (!XSTRCASECMP(token, "OCSPSigning"))
  24186. usage |= EXTKEYUSE_OCSP_SIGN;
  24187. else {
  24188. ret = EXTKEYUSAGE_E;
  24189. break;
  24190. }
  24191. token = XSTRTOK(NULL, ",", &ptr);
  24192. }
  24193. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24194. if (ret == 0) {
  24195. *extKeyUsage = usage;
  24196. }
  24197. return ret;
  24198. }
  24199. #endif /* (CERT_GEN && CERT_EXT) || (OPENSSL_ALL || OPENSSL_EXTRA) */
  24200. #ifdef WOLFSSL_CERT_GEN
  24201. /* Encodes one attribute of the name (issuer/subject)
  24202. * call we_EncodeName_ex with 0x16, IA5String for email type
  24203. * name structure to hold result of encoding
  24204. * nameStr value to be encoded
  24205. * nameType type of encoding i.e CTC_UTF8
  24206. * type id of attribute i.e ASN_COMMON_NAME
  24207. *
  24208. * returns length on success
  24209. */
  24210. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  24211. byte type)
  24212. {
  24213. return EncodeName(name, nameStr, (byte)nameType, type,
  24214. ASN_IA5_STRING, NULL);
  24215. }
  24216. #ifdef WOLFSSL_ASN_TEMPLATE
  24217. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  24218. word32 oidSz, byte tag, const byte* data, word32 sz)
  24219. {
  24220. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  24221. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24222. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  24223. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  24224. }
  24225. #ifdef WOLFSSL_MULTI_ATTRIB
  24226. static int FindMultiAttrib(CertName* name, int id, int* idx)
  24227. {
  24228. int i;
  24229. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  24230. if (name->name[i].sz > 0 && name->name[i].id == id) {
  24231. break;
  24232. }
  24233. }
  24234. if (i == CTC_MAX_ATTRIB) {
  24235. i = -1;
  24236. }
  24237. *idx = i;
  24238. return i >= 0;
  24239. }
  24240. #endif
  24241. /* ASN.1 template for the SEQUENCE around the RDNs.
  24242. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  24243. */
  24244. static const ASNItem nameASN[] = {
  24245. { 0, ASN_SEQUENCE, 1, 1, 0 },
  24246. };
  24247. enum {
  24248. NAMEASN_IDX_SEQ = 0
  24249. };
  24250. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  24251. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  24252. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  24253. int maxIdx, CertName* name)
  24254. {
  24255. int i;
  24256. int idx;
  24257. int ret = 0;
  24258. word32 nameLen[NAME_ENTRIES];
  24259. #ifdef WOLFSSL_MULTI_ATTRIB
  24260. int j;
  24261. #endif
  24262. for (i = 0; i < NAME_ENTRIES; i++) {
  24263. /* Keep name length to identify component is to be encoded. */
  24264. const char* nameStr = GetOneCertName(name, i);
  24265. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  24266. }
  24267. idx = nameASN_Length;
  24268. for (i = 0; i < NAME_ENTRIES; i++) {
  24269. int type = GetCertNameId(i);
  24270. #ifdef WOLFSSL_MULTI_ATTRIB
  24271. j = -1;
  24272. /* Put DomainComponents before OrgUnitName. */
  24273. while (FindMultiAttrib(name, type, &j)) {
  24274. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  24275. continue;
  24276. }
  24277. if (dataASN != NULL && namesASN != NULL) {
  24278. if (idx > maxIdx - (int)rdnASN_Length) {
  24279. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24280. ret = BUFFER_E;
  24281. break;
  24282. }
  24283. /* Copy data into dynamic vars. */
  24284. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  24285. sizeof(dcOid), (byte)name->name[j].type,
  24286. (byte*)name->name[j].value,
  24287. (word32)name->name[j].sz);
  24288. }
  24289. idx += (int)rdnASN_Length;
  24290. }
  24291. if (ret != 0)
  24292. break;
  24293. #endif
  24294. if (nameLen[i] > 0) {
  24295. if (dataASN != NULL) {
  24296. if (idx > maxIdx - (int)rdnASN_Length) {
  24297. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24298. ret = BUFFER_E;
  24299. break;
  24300. }
  24301. /* Write out first instance of attribute type. */
  24302. if (type == ASN_EMAIL_NAME) {
  24303. /* Copy email data into dynamic vars. */
  24304. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  24305. sizeof(attrEmailOid), ASN_IA5_STRING,
  24306. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24307. }
  24308. else if (type == ASN_USER_ID) {
  24309. /* Copy userID data into dynamic vars. */
  24310. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  24311. sizeof(uidOid), (byte)GetNameType(name, i),
  24312. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24313. }
  24314. else if (type == ASN_FAVOURITE_DRINK) {
  24315. /* Copy favourite drink data into dynamic vars. */
  24316. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  24317. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  24318. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24319. }
  24320. else if (type == ASN_CUSTOM_NAME) {
  24321. #ifdef WOLFSSL_CUSTOM_OID
  24322. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  24323. name->custom.oidSz, name->custom.enc,
  24324. name->custom.val, name->custom.valSz);
  24325. #endif
  24326. }
  24327. else {
  24328. /* Copy name data into dynamic vars. */
  24329. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24330. NAME_OID_SZ, (byte)GetNameType(name, i),
  24331. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24332. }
  24333. }
  24334. idx += (int)rdnASN_Length;
  24335. }
  24336. #ifdef WOLFSSL_MULTI_ATTRIB
  24337. j = -1;
  24338. /* Write all other attributes of this type. */
  24339. while (FindMultiAttrib(name, type, &j)) {
  24340. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  24341. continue;
  24342. }
  24343. if (dataASN != NULL && namesASN != NULL) {
  24344. if (idx > maxIdx - (int)rdnASN_Length) {
  24345. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24346. ret = BUFFER_E;
  24347. break;
  24348. }
  24349. /* Copy data into dynamic vars. */
  24350. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24351. NAME_OID_SZ, (byte)name->name[j].type,
  24352. (byte*)name->name[j].value, (word32)name->name[j].sz);
  24353. }
  24354. idx += (int)rdnASN_Length;
  24355. }
  24356. if (ret != 0)
  24357. break;
  24358. #endif
  24359. }
  24360. if (ret == 0)
  24361. ret = idx;
  24362. return ret;
  24363. }
  24364. #endif
  24365. /* encode CertName into output, return total bytes written */
  24366. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24367. {
  24368. #ifndef WOLFSSL_ASN_TEMPLATE
  24369. int ret;
  24370. int i;
  24371. word32 idx, totalBytes = 0;
  24372. #ifdef WOLFSSL_SMALL_STACK
  24373. EncodedName* names = NULL;
  24374. #else
  24375. EncodedName names[NAME_ENTRIES];
  24376. #endif
  24377. #ifdef WOLFSSL_MULTI_ATTRIB
  24378. EncodedName addNames[CTC_MAX_ATTRIB];
  24379. int j, type;
  24380. #endif
  24381. if (output == NULL || name == NULL)
  24382. return BAD_FUNC_ARG;
  24383. if (outputSz < 3)
  24384. return BUFFER_E;
  24385. #ifdef WOLFSSL_SMALL_STACK
  24386. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24387. DYNAMIC_TYPE_TMP_BUFFER);
  24388. if (names == NULL)
  24389. return MEMORY_E;
  24390. #endif
  24391. for (i = 0; i < NAME_ENTRIES; i++) {
  24392. const char* nameStr = GetOneCertName(name, i);
  24393. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  24394. GetCertNameId(i), ASN_IA5_STRING, name);
  24395. if (ret < 0) {
  24396. #ifdef WOLFSSL_SMALL_STACK
  24397. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24398. #endif
  24399. WOLFSSL_MSG("EncodeName failed");
  24400. return BUFFER_E;
  24401. }
  24402. totalBytes += (word32)ret;
  24403. }
  24404. #ifdef WOLFSSL_MULTI_ATTRIB
  24405. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24406. if (name->name[i].sz > 0) {
  24407. ret = EncodeName(&addNames[i], name->name[i].value,
  24408. (byte)name->name[i].type, (byte)name->name[i].id,
  24409. ASN_IA5_STRING, NULL);
  24410. if (ret < 0) {
  24411. #ifdef WOLFSSL_SMALL_STACK
  24412. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24413. #endif
  24414. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24415. return BUFFER_E;
  24416. }
  24417. totalBytes += (word32)ret;
  24418. }
  24419. else {
  24420. addNames[i].used = 0;
  24421. }
  24422. }
  24423. #endif /* WOLFSSL_MULTI_ATTRIB */
  24424. /* header */
  24425. idx = SetSequence(totalBytes, output);
  24426. totalBytes += idx;
  24427. if (totalBytes > WC_ASN_NAME_MAX) {
  24428. #ifdef WOLFSSL_SMALL_STACK
  24429. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24430. #endif
  24431. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24432. return BUFFER_E;
  24433. }
  24434. for (i = 0; i < NAME_ENTRIES; i++) {
  24435. #ifdef WOLFSSL_MULTI_ATTRIB
  24436. type = GetCertNameId(i);
  24437. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24438. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24439. if (outputSz < idx + (word32)addNames[j].totalLen) {
  24440. #ifdef WOLFSSL_SMALL_STACK
  24441. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24442. #endif
  24443. WOLFSSL_MSG("Not enough space left for DC value");
  24444. return BUFFER_E;
  24445. }
  24446. XMEMCPY(output + idx, addNames[j].encoded,
  24447. (size_t)addNames[j].totalLen);
  24448. idx += (word32)addNames[j].totalLen;
  24449. }
  24450. }
  24451. #endif /* WOLFSSL_MULTI_ATTRIB */
  24452. if (names[i].used) {
  24453. if (outputSz < idx + (word32)names[i].totalLen) {
  24454. #ifdef WOLFSSL_SMALL_STACK
  24455. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24456. #endif
  24457. return BUFFER_E;
  24458. }
  24459. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  24460. idx += (word32)names[i].totalLen;
  24461. }
  24462. }
  24463. #ifdef WOLFSSL_SMALL_STACK
  24464. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24465. #endif
  24466. (void)heap;
  24467. return (int)totalBytes;
  24468. #else
  24469. /* TODO: consider calculating size of entries, putting length into
  24470. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24471. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24472. ASNItem* namesASN = NULL;
  24473. word32 items = 0;
  24474. int ret = 0;
  24475. int sz = 0;
  24476. /* Calculate length of name entries and size for allocating. */
  24477. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24478. if (ret > 0) {
  24479. items = (word32)ret;
  24480. ret = 0;
  24481. }
  24482. /* Allocate dynamic data items. */
  24483. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24484. DYNAMIC_TYPE_TMP_BUFFER);
  24485. if (dataASN == NULL) {
  24486. ret = MEMORY_E;
  24487. }
  24488. else {
  24489. /* Allocate dynamic ASN.1 template items. */
  24490. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24491. DYNAMIC_TYPE_TMP_BUFFER);
  24492. if (namesASN == NULL) {
  24493. ret = MEMORY_E;
  24494. }
  24495. }
  24496. if (ret == 0) {
  24497. /* Clear the dynamic data. */
  24498. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24499. /* Copy in the outer sequence. */
  24500. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24501. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  24502. if (ret == (int)items)
  24503. ret = 0;
  24504. else if (ret > 0) {
  24505. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24506. ret = BUFFER_E;
  24507. }
  24508. }
  24509. if (ret == 0) {
  24510. /* Calculate size of encoding. */
  24511. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  24512. }
  24513. /* Check buffer size if passed in. */
  24514. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24515. ret = BUFFER_E;
  24516. }
  24517. if (ret == 0) {
  24518. if (output != NULL) {
  24519. /* Encode Name. */
  24520. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  24521. }
  24522. else {
  24523. /* Return the encoding size. */
  24524. ret = sz;
  24525. }
  24526. }
  24527. if (namesASN != NULL)
  24528. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24529. if (dataASN != NULL)
  24530. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24531. (void)heap;
  24532. return ret;
  24533. #endif
  24534. }
  24535. int SetName(byte* output, word32 outputSz, CertName* name)
  24536. {
  24537. return SetNameEx(output, outputSz, name, NULL);
  24538. }
  24539. #ifdef WOLFSSL_ASN_TEMPLATE
  24540. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24541. RsaKey* rsaKey, ecc_key* eccKey,
  24542. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24543. DsaKey* dsaKey)
  24544. {
  24545. int ret = 0;
  24546. (void)outLen;
  24547. (void)rsaKey;
  24548. (void)eccKey;
  24549. (void)ed25519Key;
  24550. (void)ed448Key;
  24551. (void)dsaKey;
  24552. switch (keyType) {
  24553. #ifndef NO_RSA
  24554. case RSA_KEY:
  24555. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24556. if (ret <= 0) {
  24557. ret = PUBLIC_KEY_E;
  24558. }
  24559. break;
  24560. #endif
  24561. #ifdef HAVE_ECC
  24562. case ECC_KEY:
  24563. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24564. if (ret <= 0) {
  24565. ret = PUBLIC_KEY_E;
  24566. }
  24567. break;
  24568. #endif /* HAVE_ECC */
  24569. #ifdef HAVE_ED25519
  24570. case ED25519_KEY:
  24571. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  24572. (word32)outLen, 1);
  24573. if (ret <= 0) {
  24574. ret = PUBLIC_KEY_E;
  24575. }
  24576. break;
  24577. #endif
  24578. #ifdef HAVE_ED448
  24579. case ED448_KEY:
  24580. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  24581. if (ret <= 0) {
  24582. ret = PUBLIC_KEY_E;
  24583. }
  24584. break;
  24585. #endif
  24586. default:
  24587. ret = PUBLIC_KEY_E;
  24588. break;
  24589. }
  24590. return ret;
  24591. }
  24592. /* ASN.1 template for certificate extensions.
  24593. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24594. * All extensions supported for encoding are described.
  24595. */
  24596. static const ASNItem static_certExtsASN[] = {
  24597. /* Basic Constraints Extension - 4.2.1.9 */
  24598. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24599. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24600. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24601. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24602. /* cA */
  24603. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24604. /* pathLenConstraint */
  24605. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24606. /* Subject Alternative Name - 4.2.1.6 */
  24607. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24608. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24609. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24610. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24611. /* Subject Key Identifier - 4.2.1.2 */
  24612. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24613. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24614. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24615. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24616. /* Authority Key Identifier - 4.2.1.1 */
  24617. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24618. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24619. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24620. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24621. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24622. /* Key Usage - 4.2.1.3 */
  24623. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24624. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24625. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24626. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24627. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24628. /* Extended Key Usage - 4,2,1,12 */
  24629. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24630. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24631. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24632. /* Certificate Policies - 4.2.1.4 */
  24633. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24634. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24635. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24636. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24637. /* Netscape Certificate Type */
  24638. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24639. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24640. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24641. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24642. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24643. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24644. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24645. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24646. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24647. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24648. };
  24649. enum {
  24650. CERTEXTSASN_IDX_BC_SEQ = 0,
  24651. CERTEXTSASN_IDX_BC_OID,
  24652. CERTEXTSASN_IDX_BC_STR,
  24653. CERTEXTSASN_IDX_BC_STR_SEQ,
  24654. CERTEXTSASN_IDX_BC_CA,
  24655. CERTEXTSASN_IDX_BC_PATHLEN,
  24656. CERTEXTSASN_IDX_SAN_SEQ,
  24657. CERTEXTSASN_IDX_SAN_OID,
  24658. CERTEXTSASN_IDX_SAN_CRIT,
  24659. CERTEXTSASN_IDX_SAN_STR,
  24660. CERTEXTSASN_IDX_SKID_SEQ,
  24661. CERTEXTSASN_IDX_SKID_OID,
  24662. CERTEXTSASN_IDX_SKID_STR,
  24663. CERTEXTSASN_IDX_SKID_KEYID,
  24664. CERTEXTSASN_IDX_AKID_SEQ,
  24665. CERTEXTSASN_IDX_AKID_OID,
  24666. CERTEXTSASN_IDX_AKID_STR,
  24667. CERTEXTSASN_IDX_AKID_STR_SEQ,
  24668. CERTEXTSASN_IDX_AKID_KEYID,
  24669. CERTEXTSASN_IDX_KU_SEQ,
  24670. CERTEXTSASN_IDX_KU_OID,
  24671. CERTEXTSASN_IDX_KU_CRIT,
  24672. CERTEXTSASN_IDX_KU_STR,
  24673. CERTEXTSASN_IDX_KU_USAGE,
  24674. CERTEXTSASN_IDX_EKU_SEQ,
  24675. CERTEXTSASN_IDX_EKU_OID,
  24676. CERTEXTSASN_IDX_EKU_STR,
  24677. CERTEXTSASN_IDX_POLICIES_SEQ,
  24678. CERTEXTSASN_IDX_POLICIES_OID,
  24679. CERTEXTSASN_IDX_POLICIES_STR,
  24680. CERTEXTSASN_IDX_POLICIES_INFO,
  24681. CERTEXTSASN_IDX_NSTYPE_SEQ,
  24682. CERTEXTSASN_IDX_NSTYPE_OID,
  24683. CERTEXTSASN_IDX_NSTYPE_STR,
  24684. CERTEXTSASN_IDX_NSTYPE_USAGE,
  24685. CERTEXTSASN_IDX_CRLINFO_SEQ,
  24686. CERTEXTSASN_IDX_CRLINFO_OID,
  24687. CERTEXTSASN_IDX_CRLINFO_STR,
  24688. CERTEXTSASN_IDX_CUSTOM_SEQ,
  24689. CERTEXTSASN_IDX_CUSTOM_OID,
  24690. CERTEXTSASN_IDX_CUSTOM_STR,
  24691. CERTEXTSASN_IDX_START_CUSTOM
  24692. };
  24693. /* Number of items in ASN.1 template for certificate extensions. We multiply
  24694. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  24695. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  24696. + (NUM_CUSTOM_EXT * 4))
  24697. static const ASNItem customExtASN[] = {
  24698. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24699. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24700. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24701. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24702. };
  24703. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  24704. int forRequest)
  24705. {
  24706. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  24707. int sz;
  24708. int ret = 0;
  24709. int i = 0;
  24710. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  24711. #ifdef WOLFSSL_ALT_NAMES
  24712. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  24713. #endif
  24714. #ifdef WOLFSSL_CERT_EXT
  24715. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  24716. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  24717. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  24718. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  24719. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  24720. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  24721. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24722. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  24723. #endif
  24724. #ifdef WOLFSSL_SMALL_STACK
  24725. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24726. byte *encodedOids;
  24727. #endif
  24728. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  24729. sizeof(ASNItem), cert->heap,
  24730. DYNAMIC_TYPE_TMP_BUFFER);
  24731. if (certExtsASN == NULL) {
  24732. return MEMORY_E;
  24733. }
  24734. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24735. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  24736. DYNAMIC_TYPE_TMP_BUFFER);
  24737. if (encodedOids == NULL) {
  24738. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24739. return MEMORY_E;
  24740. }
  24741. #endif
  24742. #else
  24743. ASNItem certExtsASN[certExtsASN_Length];
  24744. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24745. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  24746. #endif
  24747. #endif
  24748. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  24749. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  24750. * above definition of certExtsASN_Length. */
  24751. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  24752. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  24753. i < (int)certExtsASN_Length; i += 4) {
  24754. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  24755. }
  24756. (void)forRequest;
  24757. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  24758. if (ret == 0) {
  24759. if (cert->isCA) {
  24760. /* Set Basic Constraints to be a Certificate Authority. */
  24761. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  24762. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24763. if (cert->pathLenSet
  24764. #ifdef WOLFSSL_CERT_EXT
  24765. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24766. #endif
  24767. ) {
  24768. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  24769. cert->pathLen);
  24770. }
  24771. else {
  24772. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24773. }
  24774. }
  24775. else if (cert->basicConstSet) {
  24776. /* Set Basic Constraints to be a non Certificate Authority. */
  24777. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24778. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  24779. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24780. }
  24781. else {
  24782. /* Don't write out Basic Constraints extension items. */
  24783. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  24784. CERTEXTSASN_IDX_BC_PATHLEN);
  24785. }
  24786. #ifdef WOLFSSL_ALT_NAMES
  24787. if (cert->altNamesSz > 0) {
  24788. /* Set Subject Alternative Name OID and data. */
  24789. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  24790. sanOID, sizeof(sanOID));
  24791. if (cert->altNamesCrit) {
  24792. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  24793. }
  24794. else {
  24795. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  24796. }
  24797. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  24798. cert->altNames, (word32)cert->altNamesSz);
  24799. }
  24800. else
  24801. #endif
  24802. {
  24803. /* Don't write out Subject Alternative Name extension items. */
  24804. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  24805. CERTEXTSASN_IDX_SAN_STR);
  24806. }
  24807. #ifdef WOLFSSL_CERT_EXT
  24808. if (cert->skidSz > 0) {
  24809. /* Set Subject Key Identifier OID and data. */
  24810. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  24811. skidOID, sizeof(skidOID));
  24812. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  24813. cert->skid, (word32)cert->skidSz);
  24814. }
  24815. else
  24816. #endif
  24817. {
  24818. /* Don't write out Subject Key Identifier extension items. */
  24819. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  24820. CERTEXTSASN_IDX_SKID_KEYID);
  24821. }
  24822. #ifdef WOLFSSL_CERT_EXT
  24823. if (cert->akidSz > 0) {
  24824. /* Set Authority Key Identifier OID and data. */
  24825. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  24826. akidOID, sizeof(akidOID));
  24827. #ifdef WOLFSSL_AKID_NAME
  24828. if (cert->rawAkid) {
  24829. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  24830. cert->akid, (word32)cert->akidSz);
  24831. /* cert->akid contains the internal ext structure */
  24832. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  24833. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  24834. }
  24835. else
  24836. #endif
  24837. {
  24838. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  24839. cert->akid, (word32)cert->akidSz);
  24840. }
  24841. }
  24842. else
  24843. #endif
  24844. {
  24845. /* Don't write out Authority Key Identifier extension items. */
  24846. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  24847. CERTEXTSASN_IDX_AKID_KEYID);
  24848. }
  24849. #ifdef WOLFSSL_CERT_EXT
  24850. if (cert->keyUsage != 0) {
  24851. /* Set Key Usage OID, critical and value. */
  24852. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  24853. kuOID, sizeof(kuOID));
  24854. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  24855. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  24856. cert->keyUsage);
  24857. }
  24858. else
  24859. #endif
  24860. {
  24861. /* Don't write out Key Usage extension items. */
  24862. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  24863. CERTEXTSASN_IDX_KU_USAGE);
  24864. }
  24865. #ifdef WOLFSSL_CERT_EXT
  24866. if (cert->extKeyUsage != 0) {
  24867. /* Calculate size of Extended Key Usage data. */
  24868. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  24869. if (sz <= 0) {
  24870. ret = KEYUSAGE_E;
  24871. }
  24872. /* Set Extended Key Usage OID and data. */
  24873. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  24874. ekuOID, sizeof(ekuOID));
  24875. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  24876. NULL, (word32)sz);
  24877. }
  24878. else
  24879. #endif
  24880. {
  24881. /* Don't write out Extended Key Usage extension items. */
  24882. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  24883. CERTEXTSASN_IDX_EKU_STR);
  24884. }
  24885. #ifdef WOLFSSL_CERT_EXT
  24886. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24887. /* Calculate size of certificate policies. */
  24888. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  24889. cert->certPoliciesNb, cert->heap);
  24890. if (sz > 0) {
  24891. /* Set Certificate Policies OID. */
  24892. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  24893. cpOID, sizeof(cpOID));
  24894. /* Make space for data. */
  24895. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  24896. NULL, (word32)sz);
  24897. }
  24898. else {
  24899. ret = CERTPOLICIES_E;
  24900. }
  24901. }
  24902. else
  24903. #endif
  24904. {
  24905. /* Don't write out Certificate Policies extension items. */
  24906. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  24907. CERTEXTSASN_IDX_POLICIES_INFO);
  24908. }
  24909. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  24910. /* Netscape Certificate Type */
  24911. if (cert->nsCertType != 0) {
  24912. /* Set Netscape Certificate Type OID and data. */
  24913. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  24914. nsCertOID, sizeof(nsCertOID));
  24915. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  24916. &cert->nsCertType, 1);
  24917. }
  24918. else
  24919. #endif
  24920. {
  24921. /* Don't write out Netscape Certificate Type. */
  24922. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  24923. CERTEXTSASN_IDX_NSTYPE_USAGE);
  24924. }
  24925. #ifdef WOLFSSL_CERT_EXT
  24926. if (cert->crlInfoSz > 0) {
  24927. /* Set CRL Distribution Points OID and data. */
  24928. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  24929. crlInfoOID, sizeof(crlInfoOID));
  24930. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  24931. cert->crlInfo, (word32)cert->crlInfoSz);
  24932. }
  24933. else
  24934. #endif
  24935. {
  24936. /* Don't write out CRL Distribution Points. */
  24937. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  24938. CERTEXTSASN_IDX_CRLINFO_STR);
  24939. }
  24940. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24941. /* encode a custom oid and value */
  24942. if (cert->extCustom.oidSz > 0) {
  24943. /* Set CRL Distribution Points OID and data. */
  24944. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  24945. cert->extCustom.oid, cert->extCustom.oidSz);
  24946. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  24947. cert->extCustom.val, cert->extCustom.valSz);
  24948. }
  24949. else
  24950. #endif
  24951. {
  24952. /* Don't write out custom OID. */
  24953. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  24954. CERTEXTSASN_IDX_CUSTOM_STR);
  24955. }
  24956. i = 0;
  24957. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24958. for (; i < cert->customCertExtCount; i++) {
  24959. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  24960. word32 encodedOidSz = MAX_OID_SZ;
  24961. idx++; /* Skip one for for SEQ. */
  24962. /* EncodePolicyOID() will never return error since we parsed this
  24963. * OID when it was set. */
  24964. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  24965. cert->customCertExt[i].oid, NULL);
  24966. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  24967. encodedOidSz);
  24968. idx++;
  24969. if (cert->customCertExt[i].crit) {
  24970. SetASN_Boolean(&dataASN[idx], 1);
  24971. } else {
  24972. dataASN[idx].noOut = 1;
  24973. }
  24974. idx++;
  24975. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  24976. cert->customCertExt[i].valSz);
  24977. }
  24978. #endif
  24979. while (i < NUM_CUSTOM_EXT) {
  24980. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  24981. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  24982. i++;
  24983. }
  24984. }
  24985. if (ret == 0) {
  24986. /* Calculate size of encoded extensions. */
  24987. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  24988. }
  24989. if (ret == 0) {
  24990. /* Only SEQUENCE - don't encode extensions. */
  24991. if (sz == 2) {
  24992. sz = 0;
  24993. }
  24994. /* Check buffer is big enough. */
  24995. else if ((output != NULL) && (sz > (int)maxSz)) {
  24996. ret = BUFFER_E;
  24997. }
  24998. }
  24999. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  25000. /* Encode certificate extensions into buffer. */
  25001. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  25002. #ifdef WOLFSSL_CERT_EXT
  25003. if (cert->extKeyUsage != 0){
  25004. /* Encode Extended Key Usage into space provided. */
  25005. if (SetExtKeyUsage(cert,
  25006. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  25007. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  25008. cert->extKeyUsage) <= 0) {
  25009. ret = KEYUSAGE_E;
  25010. }
  25011. }
  25012. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  25013. /* Encode Certificate Policies into space provided. */
  25014. if (SetCertificatePolicies(
  25015. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  25016. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  25017. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  25018. ret = CERTPOLICIES_E;
  25019. }
  25020. }
  25021. #endif
  25022. }
  25023. if (ret == 0) {
  25024. /* Return the encoding size. */
  25025. ret = sz;
  25026. }
  25027. FREE_ASNSETDATA(dataASN, cert->heap);
  25028. #ifdef WOLFSSL_SMALL_STACK
  25029. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  25030. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25031. #endif
  25032. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25033. #endif
  25034. return ret;
  25035. }
  25036. #endif /* WOLFSSL_ASN_TEMPLATE */
  25037. #ifndef WOLFSSL_ASN_TEMPLATE
  25038. /* Set Date validity from now until now + daysValid
  25039. * return size in bytes written to output, 0 on error */
  25040. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  25041. * "MUST always encode certificate validity dates through the year 2049 as
  25042. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  25043. * GeneralizedTime." */
  25044. static int SetValidity(byte* output, int daysValid)
  25045. {
  25046. #ifndef NO_ASN_TIME
  25047. byte before[MAX_DATE_SIZE];
  25048. byte after[MAX_DATE_SIZE];
  25049. word32 beforeSz, afterSz, seqSz;
  25050. time_t now;
  25051. time_t then;
  25052. struct tm* tmpTime;
  25053. struct tm* expandedTime;
  25054. struct tm localTime;
  25055. #if defined(NEED_TMP_TIME)
  25056. /* for use with gmtime_r */
  25057. struct tm tmpTimeStorage;
  25058. tmpTime = &tmpTimeStorage;
  25059. #else
  25060. tmpTime = NULL;
  25061. #endif
  25062. (void)tmpTime;
  25063. now = wc_Time(0);
  25064. /* before now */
  25065. before[0] = ASN_GENERALIZED_TIME;
  25066. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  25067. /* subtract 1 day of seconds for more compliance */
  25068. then = now - 86400;
  25069. expandedTime = XGMTIME(&then, tmpTime);
  25070. if (expandedTime == NULL) {
  25071. WOLFSSL_MSG("XGMTIME failed");
  25072. return 0; /* error */
  25073. }
  25074. localTime = *expandedTime;
  25075. /* adjust */
  25076. localTime.tm_year += 1900;
  25077. localTime.tm_mon += 1;
  25078. SetTime(&localTime, before + beforeSz);
  25079. beforeSz += ASN_GEN_TIME_SZ;
  25080. after[0] = ASN_GENERALIZED_TIME;
  25081. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  25082. /* add daysValid of seconds */
  25083. then = now + (daysValid * (time_t)86400);
  25084. expandedTime = XGMTIME(&then, tmpTime);
  25085. if (expandedTime == NULL) {
  25086. WOLFSSL_MSG("XGMTIME failed");
  25087. return 0; /* error */
  25088. }
  25089. localTime = *expandedTime;
  25090. /* adjust */
  25091. localTime.tm_year += 1900;
  25092. localTime.tm_mon += 1;
  25093. SetTime(&localTime, after + afterSz);
  25094. afterSz += ASN_GEN_TIME_SZ;
  25095. /* headers and output */
  25096. seqSz = SetSequence(beforeSz + afterSz, output);
  25097. XMEMCPY(output + seqSz, before, beforeSz);
  25098. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  25099. return (int)(seqSz + beforeSz + afterSz);
  25100. #else
  25101. (void)output;
  25102. (void)daysValid;
  25103. return NOT_COMPILED_IN;
  25104. #endif
  25105. }
  25106. #else
  25107. static int SetValidity(byte* before, byte* after, int daysValid)
  25108. {
  25109. #ifndef NO_ASN_TIME
  25110. int ret = 0;
  25111. time_t now;
  25112. time_t then;
  25113. struct tm* tmpTime;
  25114. struct tm* expandedTime;
  25115. struct tm localTime;
  25116. #if defined(NEED_TMP_TIME)
  25117. /* for use with gmtime_r */
  25118. struct tm tmpTimeStorage;
  25119. tmpTime = &tmpTimeStorage;
  25120. #else
  25121. tmpTime = NULL;
  25122. #endif
  25123. (void)tmpTime;
  25124. now = wc_Time(0);
  25125. /* subtract 1 day of seconds for more compliance */
  25126. then = now - 86400;
  25127. expandedTime = XGMTIME(&then, tmpTime);
  25128. if (expandedTime == NULL) {
  25129. WOLFSSL_MSG("XGMTIME failed");
  25130. ret = DATE_E;
  25131. }
  25132. if (ret == 0) {
  25133. localTime = *expandedTime;
  25134. /* adjust */
  25135. localTime.tm_year += 1900;
  25136. localTime.tm_mon += 1;
  25137. SetTime(&localTime, before);
  25138. /* add daysValid of seconds */
  25139. then = now + (daysValid * (time_t)86400);
  25140. expandedTime = XGMTIME(&then, tmpTime);
  25141. if (expandedTime == NULL) {
  25142. WOLFSSL_MSG("XGMTIME failed");
  25143. ret = DATE_E;
  25144. }
  25145. }
  25146. if (ret == 0) {
  25147. localTime = *expandedTime;
  25148. /* adjust */
  25149. localTime.tm_year += 1900;
  25150. localTime.tm_mon += 1;
  25151. SetTime(&localTime, after);
  25152. }
  25153. return ret;
  25154. #else
  25155. (void)before;
  25156. (void)after;
  25157. (void)daysValid;
  25158. return NOT_COMPILED_IN;
  25159. #endif
  25160. }
  25161. #endif /* WOLFSSL_ASN_TEMPLATE */
  25162. #ifndef WOLFSSL_ASN_TEMPLATE
  25163. /* encode info from cert into DER encoded format */
  25164. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  25165. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  25166. ed448_key* ed448Key, falcon_key* falconKey,
  25167. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25168. {
  25169. int ret;
  25170. if (cert == NULL || der == NULL || rng == NULL)
  25171. return BAD_FUNC_ARG;
  25172. /* make sure at least one key type is provided */
  25173. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  25174. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  25175. dilithiumKey == NULL && sphincsKey == NULL) {
  25176. return PUBLIC_KEY_E;
  25177. }
  25178. /* init */
  25179. XMEMSET(der, 0, sizeof(DerCert));
  25180. /* version */
  25181. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  25182. /* serial number (must be positive) */
  25183. if (cert->serialSz == 0) {
  25184. /* generate random serial */
  25185. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25186. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  25187. if (ret != 0)
  25188. return ret;
  25189. /* Clear the top bit to avoid a negative value */
  25190. cert->serial[0] &= 0x7f;
  25191. }
  25192. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  25193. der->serial, sizeof(der->serial),
  25194. CTC_SERIAL_SIZE);
  25195. if (der->serialSz < 0)
  25196. return der->serialSz;
  25197. /* signature algo */
  25198. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  25199. if (der->sigAlgoSz <= 0)
  25200. return ALGO_ID_E;
  25201. /* public key */
  25202. #ifndef NO_RSA
  25203. if (cert->keyType == RSA_KEY) {
  25204. if (rsaKey == NULL)
  25205. return PUBLIC_KEY_E;
  25206. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  25207. sizeof(der->publicKey), 1);
  25208. }
  25209. #endif
  25210. #ifdef HAVE_ECC
  25211. if (cert->keyType == ECC_KEY) {
  25212. if (eccKey == NULL)
  25213. return PUBLIC_KEY_E;
  25214. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  25215. sizeof(der->publicKey), 1, 0);
  25216. }
  25217. #endif
  25218. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  25219. if (cert->keyType == DSA_KEY) {
  25220. if (dsaKey == NULL)
  25221. return PUBLIC_KEY_E;
  25222. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  25223. sizeof(der->publicKey), 1);
  25224. }
  25225. #endif
  25226. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  25227. if (cert->keyType == ED25519_KEY) {
  25228. if (ed25519Key == NULL)
  25229. return PUBLIC_KEY_E;
  25230. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  25231. (word32)sizeof(der->publicKey), 1);
  25232. }
  25233. #endif
  25234. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  25235. if (cert->keyType == ED448_KEY) {
  25236. if (ed448Key == NULL)
  25237. return PUBLIC_KEY_E;
  25238. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  25239. (word32)sizeof(der->publicKey), 1);
  25240. }
  25241. #endif
  25242. #if defined(HAVE_PQC)
  25243. #if defined(HAVE_FALCON)
  25244. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  25245. (cert->keyType == FALCON_LEVEL5_KEY)) {
  25246. if (falconKey == NULL)
  25247. return PUBLIC_KEY_E;
  25248. der->publicKeySz =
  25249. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  25250. (word32)sizeof(der->publicKey), 1);
  25251. }
  25252. #endif /* HAVE_FALCON */
  25253. #if defined(HAVE_DILITHIUM)
  25254. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  25255. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  25256. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  25257. if (dilithiumKey == NULL)
  25258. return PUBLIC_KEY_E;
  25259. der->publicKeySz =
  25260. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  25261. (word32)sizeof(der->publicKey), 1);
  25262. }
  25263. #endif /* HAVE_DILITHIUM */
  25264. #if defined(HAVE_SPHINCS)
  25265. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  25266. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  25267. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  25268. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  25269. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  25270. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  25271. if (sphincsKey == NULL)
  25272. return PUBLIC_KEY_E;
  25273. der->publicKeySz =
  25274. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  25275. (word32)sizeof(der->publicKey), 1);
  25276. }
  25277. #endif /* HAVE_SPHINCS */
  25278. #endif /* HAVE_PQC */
  25279. if (der->publicKeySz <= 0)
  25280. return PUBLIC_KEY_E;
  25281. der->validitySz = 0;
  25282. /* copy date validity if already set in cert struct */
  25283. if (cert->beforeDateSz && cert->afterDateSz) {
  25284. der->validitySz = CopyValidity(der->validity, cert);
  25285. if (der->validitySz <= 0)
  25286. return DATE_E;
  25287. }
  25288. /* set date validity using daysValid if not set already */
  25289. if (der->validitySz == 0) {
  25290. der->validitySz = SetValidity(der->validity, cert->daysValid);
  25291. if (der->validitySz <= 0)
  25292. return DATE_E;
  25293. }
  25294. /* subject name */
  25295. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25296. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  25297. /* Use the raw subject */
  25298. word32 idx;
  25299. der->subjectSz = (int)min((word32)sizeof(der->subject),
  25300. (word32)XSTRLEN((const char*)cert->sbjRaw));
  25301. /* header */
  25302. idx = SetSequence((word32)der->subjectSz, der->subject);
  25303. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  25304. return SUBJECT_E;
  25305. }
  25306. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  25307. (size_t)der->subjectSz);
  25308. der->subjectSz += (int)idx;
  25309. }
  25310. else
  25311. #endif
  25312. {
  25313. /* Use the name structure */
  25314. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  25315. &cert->subject, cert->heap);
  25316. }
  25317. if (der->subjectSz <= 0)
  25318. return SUBJECT_E;
  25319. /* issuer name */
  25320. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25321. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  25322. /* Use the raw issuer */
  25323. word32 idx;
  25324. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  25325. (word32)XSTRLEN((const char*)cert->issRaw));
  25326. /* header */
  25327. idx = SetSequence((word32)der->issuerSz, der->issuer);
  25328. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  25329. return ISSUER_E;
  25330. }
  25331. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  25332. (size_t)der->issuerSz);
  25333. der->issuerSz += (int)idx;
  25334. }
  25335. else
  25336. #endif
  25337. {
  25338. /* Use the name structure */
  25339. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  25340. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25341. }
  25342. if (der->issuerSz <= 0)
  25343. return ISSUER_E;
  25344. /* set the extensions */
  25345. der->extensionsSz = 0;
  25346. /* RFC 5280 : 4.2.1.9. Basic Constraints
  25347. * The pathLenConstraint field is meaningful only if the CA boolean is
  25348. * asserted and the key usage extension, if present, asserts the
  25349. * keyCertSign bit */
  25350. /* Set CA and path length */
  25351. if ((cert->isCA) && (cert->pathLenSet)
  25352. #ifdef WOLFSSL_CERT_EXT
  25353. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25354. #endif
  25355. ) {
  25356. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  25357. if (der->caSz <= 0)
  25358. return CA_TRUE_E;
  25359. der->extensionsSz += der->caSz;
  25360. }
  25361. /* Set CA */
  25362. else if (cert->isCA) {
  25363. der->caSz = SetCa(der->ca, sizeof(der->ca));
  25364. if (der->caSz <= 0)
  25365. return CA_TRUE_E;
  25366. der->extensionsSz += der->caSz;
  25367. }
  25368. /* Set Basic Constraint */
  25369. else if (cert->basicConstSet) {
  25370. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25371. if (der->caSz <= 0)
  25372. return EXTENSIONS_E;
  25373. der->extensionsSz += der->caSz;
  25374. }
  25375. else
  25376. der->caSz = 0;
  25377. #ifdef WOLFSSL_ALT_NAMES
  25378. /* Alternative Name */
  25379. if (cert->altNamesSz) {
  25380. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25381. cert->altNames, (word32)cert->altNamesSz,
  25382. cert->altNamesCrit);
  25383. if (der->altNamesSz <= 0)
  25384. return ALT_NAME_E;
  25385. der->extensionsSz += der->altNamesSz;
  25386. }
  25387. else
  25388. der->altNamesSz = 0;
  25389. #endif
  25390. #ifdef WOLFSSL_CERT_EXT
  25391. /* SKID */
  25392. if (cert->skidSz) {
  25393. /* check the provided SKID size */
  25394. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25395. return SKID_E;
  25396. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25397. cert (CTC_MAX_SKID_SIZE). */
  25398. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25399. cert->skid, (word32)cert->skidSz);
  25400. if (der->skidSz <= 0)
  25401. return SKID_E;
  25402. der->extensionsSz += der->skidSz;
  25403. }
  25404. else
  25405. der->skidSz = 0;
  25406. /* AKID */
  25407. if (cert->akidSz) {
  25408. /* check the provided AKID size */
  25409. if ((
  25410. #ifdef WOLFSSL_AKID_NAME
  25411. !cert->rawAkid &&
  25412. #endif
  25413. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25414. #ifdef WOLFSSL_AKID_NAME
  25415. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25416. #endif
  25417. )
  25418. return AKID_E;
  25419. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25420. (word32)cert->akidSz,
  25421. #ifdef WOLFSSL_AKID_NAME
  25422. cert->rawAkid
  25423. #else
  25424. 0
  25425. #endif
  25426. );
  25427. if (der->akidSz <= 0)
  25428. return AKID_E;
  25429. der->extensionsSz += der->akidSz;
  25430. }
  25431. else
  25432. der->akidSz = 0;
  25433. /* Key Usage */
  25434. if (cert->keyUsage != 0){
  25435. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25436. cert->keyUsage);
  25437. if (der->keyUsageSz <= 0)
  25438. return KEYUSAGE_E;
  25439. der->extensionsSz += der->keyUsageSz;
  25440. }
  25441. else
  25442. der->keyUsageSz = 0;
  25443. /* Extended Key Usage */
  25444. if (cert->extKeyUsage != 0){
  25445. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25446. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25447. if (der->extKeyUsageSz <= 0)
  25448. return EXTKEYUSAGE_E;
  25449. der->extensionsSz += der->extKeyUsageSz;
  25450. }
  25451. else
  25452. der->extKeyUsageSz = 0;
  25453. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25454. /* Netscape Certificate Type */
  25455. if (cert->nsCertType != 0) {
  25456. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25457. sizeof(der->nsCertType), cert->nsCertType);
  25458. if (der->nsCertTypeSz <= 0)
  25459. return EXTENSIONS_E;
  25460. der->extensionsSz += der->nsCertTypeSz;
  25461. }
  25462. else
  25463. der->nsCertTypeSz = 0;
  25464. #endif
  25465. if (cert->crlInfoSz > 0) {
  25466. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25467. cert->crlInfo, cert->crlInfoSz);
  25468. if (der->crlInfoSz <= 0)
  25469. return EXTENSIONS_E;
  25470. der->extensionsSz += der->crlInfoSz;
  25471. }
  25472. else
  25473. der->crlInfoSz = 0;
  25474. /* Certificate Policies */
  25475. if (cert->certPoliciesNb != 0) {
  25476. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25477. sizeof(der->certPolicies),
  25478. cert->certPolicies,
  25479. cert->certPoliciesNb,
  25480. cert->heap);
  25481. if (der->certPoliciesSz <= 0)
  25482. return CERTPOLICIES_E;
  25483. der->extensionsSz += der->certPoliciesSz;
  25484. }
  25485. else
  25486. der->certPoliciesSz = 0;
  25487. #endif /* WOLFSSL_CERT_EXT */
  25488. /* put extensions */
  25489. if (der->extensionsSz > 0) {
  25490. /* put the start of extensions sequence (ID, Size) */
  25491. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25492. sizeof(der->extensions),
  25493. (word32)der->extensionsSz);
  25494. if (der->extensionsSz <= 0)
  25495. return EXTENSIONS_E;
  25496. /* put CA */
  25497. if (der->caSz) {
  25498. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25499. &der->extensionsSz,
  25500. der->ca, der->caSz);
  25501. if (ret == 0)
  25502. return EXTENSIONS_E;
  25503. }
  25504. #ifdef WOLFSSL_ALT_NAMES
  25505. /* put Alternative Names */
  25506. if (der->altNamesSz) {
  25507. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25508. &der->extensionsSz,
  25509. der->altNames, der->altNamesSz);
  25510. if (ret <= 0)
  25511. return EXTENSIONS_E;
  25512. }
  25513. #endif
  25514. #ifdef WOLFSSL_CERT_EXT
  25515. /* put SKID */
  25516. if (der->skidSz) {
  25517. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25518. &der->extensionsSz,
  25519. der->skid, der->skidSz);
  25520. if (ret <= 0)
  25521. return EXTENSIONS_E;
  25522. }
  25523. /* put AKID */
  25524. if (der->akidSz) {
  25525. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25526. &der->extensionsSz,
  25527. der->akid, der->akidSz);
  25528. if (ret <= 0)
  25529. return EXTENSIONS_E;
  25530. }
  25531. /* put CRL Distribution Points */
  25532. if (der->crlInfoSz) {
  25533. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25534. &der->extensionsSz,
  25535. der->crlInfo, der->crlInfoSz);
  25536. if (ret <= 0)
  25537. return EXTENSIONS_E;
  25538. }
  25539. /* put KeyUsage */
  25540. if (der->keyUsageSz) {
  25541. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25542. &der->extensionsSz,
  25543. der->keyUsage, der->keyUsageSz);
  25544. if (ret <= 0)
  25545. return EXTENSIONS_E;
  25546. }
  25547. /* put ExtendedKeyUsage */
  25548. if (der->extKeyUsageSz) {
  25549. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25550. &der->extensionsSz,
  25551. der->extKeyUsage, der->extKeyUsageSz);
  25552. if (ret <= 0)
  25553. return EXTENSIONS_E;
  25554. }
  25555. /* put Netscape Cert Type */
  25556. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25557. if (der->nsCertTypeSz) {
  25558. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25559. &der->extensionsSz,
  25560. der->nsCertType, der->nsCertTypeSz);
  25561. if (ret <= 0)
  25562. return EXTENSIONS_E;
  25563. }
  25564. #endif
  25565. /* put Certificate Policies */
  25566. if (der->certPoliciesSz) {
  25567. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25568. &der->extensionsSz,
  25569. der->certPolicies, der->certPoliciesSz);
  25570. if (ret <= 0)
  25571. return EXTENSIONS_E;
  25572. }
  25573. #endif /* WOLFSSL_CERT_EXT */
  25574. }
  25575. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25576. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25577. der->extensionsSz;
  25578. return 0;
  25579. }
  25580. /* write DER encoded cert to buffer, size already checked */
  25581. static int WriteCertBody(DerCert* der, byte* buf)
  25582. {
  25583. word32 idx;
  25584. /* signed part header */
  25585. idx = SetSequence((word32)der->total, buf);
  25586. /* version */
  25587. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  25588. idx += (word32)der->versionSz;
  25589. /* serial */
  25590. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  25591. idx += (word32)der->serialSz;
  25592. /* sig algo */
  25593. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  25594. idx += (word32)der->sigAlgoSz;
  25595. /* issuer */
  25596. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  25597. idx += (word32)der->issuerSz;
  25598. /* validity */
  25599. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  25600. idx += (word32)der->validitySz;
  25601. /* subject */
  25602. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  25603. idx += (word32)der->subjectSz;
  25604. /* public key */
  25605. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  25606. idx += (word32)der->publicKeySz;
  25607. if (der->extensionsSz) {
  25608. /* extensions */
  25609. XMEMCPY(buf + idx, der->extensions,
  25610. min((word32)der->extensionsSz,
  25611. (word32)sizeof(der->extensions)));
  25612. idx += (word32)der->extensionsSz;
  25613. }
  25614. return (int)idx;
  25615. }
  25616. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25617. /* Make signature from buffer (sz), write to sig (sigSz) */
  25618. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  25619. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25620. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25621. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25622. word32 sigAlgoType, void* heap)
  25623. {
  25624. int digestSz = 0, typeH = 0, ret = 0;
  25625. (void)digestSz;
  25626. (void)typeH;
  25627. (void)buf;
  25628. (void)sz;
  25629. (void)sig;
  25630. (void)sigSz;
  25631. (void)rsaKey;
  25632. (void)eccKey;
  25633. (void)ed25519Key;
  25634. (void)ed448Key;
  25635. (void)falconKey;
  25636. (void)dilithiumKey;
  25637. (void)sphincsKey;
  25638. (void)rng;
  25639. (void)heap;
  25640. switch (certSignCtx->state) {
  25641. case CERTSIGN_STATE_BEGIN:
  25642. case CERTSIGN_STATE_DIGEST:
  25643. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  25644. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  25645. DYNAMIC_TYPE_TMP_BUFFER);
  25646. if (certSignCtx->digest == NULL) {
  25647. ret = MEMORY_E; goto exit_ms;
  25648. }
  25649. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  25650. &typeH, &digestSz, 0);
  25651. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  25652. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  25653. if (ret != 0) {
  25654. goto exit_ms;
  25655. }
  25656. FALL_THROUGH;
  25657. case CERTSIGN_STATE_ENCODE:
  25658. #ifndef NO_RSA
  25659. if (rsaKey) {
  25660. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  25661. DYNAMIC_TYPE_TMP_BUFFER);
  25662. if (certSignCtx->encSig == NULL) {
  25663. ret = MEMORY_E; goto exit_ms;
  25664. }
  25665. /* signature */
  25666. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  25667. certSignCtx->digest, (word32)digestSz, typeH);
  25668. }
  25669. #endif /* !NO_RSA */
  25670. FALL_THROUGH;
  25671. case CERTSIGN_STATE_DO:
  25672. certSignCtx->state = CERTSIGN_STATE_DO;
  25673. ret = ALGO_ID_E; /* default to error */
  25674. #ifndef NO_RSA
  25675. if (rsaKey) {
  25676. /* signature */
  25677. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  25678. (word32)certSignCtx->encSigSz,
  25679. sig, sigSz, rsaKey, rng);
  25680. }
  25681. #endif /* !NO_RSA */
  25682. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  25683. if (!rsaKey && eccKey) {
  25684. word32 outSz = sigSz;
  25685. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  25686. sig, &outSz, rng, eccKey);
  25687. if (ret == 0)
  25688. ret = (int)outSz;
  25689. }
  25690. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  25691. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  25692. if (!rsaKey && !eccKey && ed25519Key) {
  25693. word32 outSz = sigSz;
  25694. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  25695. if (ret == 0)
  25696. ret = (int)outSz;
  25697. }
  25698. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  25699. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  25700. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  25701. word32 outSz = sigSz;
  25702. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  25703. if (ret == 0)
  25704. ret = (int)outSz;
  25705. }
  25706. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  25707. #if defined(HAVE_PQC)
  25708. #if defined(HAVE_FALCON)
  25709. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  25710. word32 outSz = sigSz;
  25711. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  25712. if (ret == 0)
  25713. ret = outSz;
  25714. }
  25715. #endif /* HAVE_FALCON */
  25716. #if defined(HAVE_DILITHIUM)
  25717. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25718. dilithiumKey) {
  25719. word32 outSz = sigSz;
  25720. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  25721. if (ret == 0)
  25722. ret = outSz;
  25723. }
  25724. #endif /* HAVE_DILITHIUM */
  25725. #if defined(HAVE_SPHINCS)
  25726. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25727. !dilithiumKey && sphincsKey) {
  25728. word32 outSz = sigSz;
  25729. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  25730. if (ret == 0)
  25731. ret = outSz;
  25732. }
  25733. #endif /* HAVE_SPHINCS */
  25734. #endif /* HAVE_PQC */
  25735. break;
  25736. }
  25737. exit_ms:
  25738. #ifdef WOLFSSL_ASYNC_CRYPT
  25739. if (ret == WC_PENDING_E) {
  25740. return ret;
  25741. }
  25742. #endif
  25743. #ifndef NO_RSA
  25744. if (rsaKey) {
  25745. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25746. }
  25747. #endif /* !NO_RSA */
  25748. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25749. certSignCtx->digest = NULL;
  25750. /* reset state */
  25751. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  25752. if (ret < 0) {
  25753. WOLFSSL_ERROR_VERBOSE(ret);
  25754. }
  25755. return ret;
  25756. }
  25757. #ifdef WOLFSSL_ASN_TEMPLATE
  25758. /* Generate a random integer value of at most len bytes.
  25759. *
  25760. * Most-significant bit will not be set when maximum size.
  25761. * Random value may be smaller than maximum size in bytes.
  25762. *
  25763. * @param [in] rng Random number generator.
  25764. * @param [out] out Buffer to hold integer value.
  25765. * @param [in] len Maximum number of bytes of integer.
  25766. * @return 0 on success.
  25767. * @return -ve when random number generation failed.
  25768. */
  25769. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  25770. {
  25771. int ret;
  25772. /* Generate random number. */
  25773. ret = wc_RNG_GenerateBlock(rng, out, len);
  25774. if (ret == 0) {
  25775. int i;
  25776. /* Clear the top bit to make positive. */
  25777. out[0] &= 0x7f;
  25778. /* Find first non-zero byte. One zero byte is valid though. */
  25779. for (i = 0; i < (int)len - 1; i++) {
  25780. if (out[i] != 0) {
  25781. break;
  25782. }
  25783. }
  25784. if (i != 0) {
  25785. /* Remove leading zeros. */
  25786. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  25787. }
  25788. }
  25789. return ret;
  25790. }
  25791. /* ASN.1 template for a Certificate.
  25792. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25793. */
  25794. static const ASNItem sigASN[] = {
  25795. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25796. /* tbsCertificate */
  25797. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25798. /* signatureAlgorithm */
  25799. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25800. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25801. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  25802. /* signatureValue */
  25803. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25804. };
  25805. enum {
  25806. SIGASN_IDX_SEQ = 0,
  25807. SIGASN_IDX_TBS_SEQ,
  25808. SIGASN_IDX_SIGALGO_SEQ,
  25809. SIGASN_IDX_SIGALGO_OID,
  25810. SIGASN_IDX_SIGALGO_NULL,
  25811. SIGASN_IDX_SIGNATURE
  25812. };
  25813. /* Number of items in ASN.1 template for a Certificate. */
  25814. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  25815. #endif
  25816. /* add signature to end of buffer, size of buffer assumed checked, return
  25817. new length */
  25818. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  25819. int sigAlgoType)
  25820. {
  25821. #ifndef WOLFSSL_ASN_TEMPLATE
  25822. byte seq[MAX_SEQ_SZ];
  25823. word32 idx, seqSz;
  25824. if ((bodySz < 0) || (sigSz < 0))
  25825. return BUFFER_E;
  25826. idx = (word32)bodySz;
  25827. /* algo */
  25828. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  25829. /* bit string */
  25830. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  25831. /* signature */
  25832. if (buf)
  25833. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  25834. idx += (word32)sigSz;
  25835. /* make room for overall header */
  25836. seqSz = SetSequence(idx, seq);
  25837. if (buf) {
  25838. XMEMMOVE(buf + seqSz, buf, idx);
  25839. XMEMCPY(buf, seq, seqSz);
  25840. }
  25841. return (int)(idx + seqSz);
  25842. #else
  25843. DECL_ASNSETDATA(dataASN, sigASN_Length);
  25844. word32 seqSz;
  25845. int sz;
  25846. int ret = 0;
  25847. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  25848. /* In place, put body between SEQUENCE and signature. */
  25849. if (ret == 0) {
  25850. /* Set sigature OID and signature data. */
  25851. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  25852. oidSigType);
  25853. if (IsSigAlgoECC((word32)sigAlgoType)) {
  25854. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  25855. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  25856. }
  25857. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  25858. /* Calculate size of signature data. */
  25859. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  25860. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  25861. }
  25862. if (ret == 0) {
  25863. /* Calculate size of outer sequence by calculating size of the encoded
  25864. * length and adding 1 for tag. */
  25865. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  25866. if (buf != NULL) {
  25867. /* Move body to after sequence. */
  25868. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  25869. }
  25870. /* Leave space for body in encoding. */
  25871. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  25872. (word32)bodySz);
  25873. /* Calculate overall size and put in offsets and lengths. */
  25874. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  25875. }
  25876. if ((ret == 0) && (buf != NULL)) {
  25877. /* Write SEQUENCE and signature around body. */
  25878. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  25879. }
  25880. if (ret == 0) {
  25881. /* Return the encoding size. */
  25882. ret = sz;
  25883. }
  25884. FREE_ASNSETDATA(dataASN, NULL);
  25885. return ret;
  25886. #endif /* WOLFSSL_ASN_TEMPLATE */
  25887. }
  25888. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  25889. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  25890. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  25891. DsaKey* dsaKey, ed25519_key* ed25519Key,
  25892. ed448_key* ed448Key, falcon_key* falconKey,
  25893. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25894. {
  25895. #ifndef WOLFSSL_ASN_TEMPLATE
  25896. int ret;
  25897. #ifdef WOLFSSL_SMALL_STACK
  25898. DerCert* der;
  25899. #else
  25900. DerCert der[1];
  25901. #endif
  25902. if (derBuffer == NULL)
  25903. return BAD_FUNC_ARG;
  25904. if (eccKey)
  25905. cert->keyType = ECC_KEY;
  25906. else if (rsaKey)
  25907. cert->keyType = RSA_KEY;
  25908. else if (dsaKey)
  25909. cert->keyType = DSA_KEY;
  25910. else if (ed25519Key)
  25911. cert->keyType = ED25519_KEY;
  25912. else if (ed448Key)
  25913. cert->keyType = ED448_KEY;
  25914. #ifdef HAVE_PQC
  25915. #ifdef HAVE_FALCON
  25916. else if ((falconKey != NULL) && (falconKey->level == 1))
  25917. cert->keyType = FALCON_LEVEL1_KEY;
  25918. else if ((falconKey != NULL) && (falconKey->level == 5))
  25919. cert->keyType = FALCON_LEVEL5_KEY;
  25920. #endif /* HAVE_FALCON */
  25921. #ifdef HAVE_DILITHIUM
  25922. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  25923. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25924. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  25925. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25926. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  25927. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25928. #endif /* HAVE_DILITHIUM */
  25929. #ifdef HAVE_SPHINCS
  25930. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25931. && (sphincsKey->optim == FAST_VARIANT))
  25932. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25933. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25934. && (sphincsKey->optim == FAST_VARIANT))
  25935. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25936. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25937. && (sphincsKey->optim == FAST_VARIANT))
  25938. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25939. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25940. && (sphincsKey->optim == SMALL_VARIANT))
  25941. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25942. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25943. && (sphincsKey->optim == SMALL_VARIANT))
  25944. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25945. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25946. && (sphincsKey->optim == SMALL_VARIANT))
  25947. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25948. #endif /* HAVE_SPHINCS */
  25949. #endif /* HAVE_PQC */
  25950. else
  25951. return BAD_FUNC_ARG;
  25952. #ifdef WOLFSSL_SMALL_STACK
  25953. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25954. if (der == NULL)
  25955. return MEMORY_E;
  25956. #endif
  25957. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  25958. ed448Key, falconKey, dilithiumKey, sphincsKey);
  25959. if (ret == 0) {
  25960. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  25961. ret = BUFFER_E;
  25962. else
  25963. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  25964. }
  25965. #ifdef WOLFSSL_SMALL_STACK
  25966. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25967. #endif
  25968. return ret;
  25969. #else
  25970. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  25971. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  25972. word32 publicKeySz = 0;
  25973. word32 issuerSz = 0;
  25974. word32 subjectSz = 0;
  25975. word32 extSz = 0;
  25976. int sz = 0;
  25977. int ret = 0;
  25978. word32 issRawLen = 0;
  25979. word32 sbjRawLen = 0;
  25980. /* Unused without OQS */
  25981. (void)falconKey;
  25982. (void)dilithiumKey;
  25983. (void)sphincsKey;
  25984. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  25985. if (ret == 0) {
  25986. /* Set key type into certificate object based on key passed in. */
  25987. if (rsaKey) {
  25988. cert->keyType = RSA_KEY;
  25989. }
  25990. else if (eccKey) {
  25991. cert->keyType = ECC_KEY;
  25992. }
  25993. else if (dsaKey) {
  25994. cert->keyType = DSA_KEY;
  25995. }
  25996. else if (ed25519Key) {
  25997. cert->keyType = ED25519_KEY;
  25998. }
  25999. else if (ed448Key) {
  26000. cert->keyType = ED448_KEY;
  26001. }
  26002. #ifdef HAVE_PQC
  26003. #ifdef HAVE_FALCON
  26004. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26005. cert->keyType = FALCON_LEVEL1_KEY;
  26006. }
  26007. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26008. cert->keyType = FALCON_LEVEL5_KEY;
  26009. }
  26010. #endif /* HAVE_FALCON */
  26011. #ifdef HAVE_DILITHIUM
  26012. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26013. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26014. }
  26015. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26016. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26017. }
  26018. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26019. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26020. }
  26021. #endif /* HAVE_DILITHIUM */
  26022. #ifdef HAVE_SPHINCS
  26023. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26024. && (sphincsKey->optim == FAST_VARIANT)) {
  26025. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26026. }
  26027. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26028. && (sphincsKey->optim == FAST_VARIANT)) {
  26029. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26030. }
  26031. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26032. && (sphincsKey->optim == FAST_VARIANT)) {
  26033. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26034. }
  26035. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26036. && (sphincsKey->optim == SMALL_VARIANT)) {
  26037. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26038. }
  26039. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26040. && (sphincsKey->optim == SMALL_VARIANT)) {
  26041. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26042. }
  26043. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26044. && (sphincsKey->optim == SMALL_VARIANT)) {
  26045. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26046. }
  26047. #endif /* HAVE_SPHINCS */
  26048. #endif /* HAVE_PQC */
  26049. else {
  26050. ret = BAD_FUNC_ARG;
  26051. }
  26052. }
  26053. if ((ret == 0) && (cert->serialSz == 0)) {
  26054. /* Generate random serial number. */
  26055. cert->serialSz = CTC_GEN_SERIAL_SZ;
  26056. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  26057. }
  26058. if (ret == 0) {
  26059. /* Determine issuer name size. */
  26060. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26061. defined(WOLFSSL_CERT_REQ)
  26062. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  26063. if (issRawLen > 0) {
  26064. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  26065. }
  26066. else
  26067. #endif
  26068. {
  26069. /* Calculate issuer name encoding size. If the cert is self-signed
  26070. * use the subject instead of the issuer. */
  26071. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  26072. &cert->subject : &cert->issuer, cert->heap);
  26073. issuerSz = (word32)ret;
  26074. }
  26075. }
  26076. if (ret >= 0) {
  26077. /* Determine subject name size. */
  26078. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26079. defined(WOLFSSL_CERT_REQ)
  26080. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26081. if (sbjRawLen > 0) {
  26082. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  26083. }
  26084. else
  26085. #endif
  26086. {
  26087. /* Calculate subject name encoding size. */
  26088. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  26089. cert->heap);
  26090. subjectSz = (word32)ret;
  26091. }
  26092. }
  26093. if (ret >= 0) {
  26094. /* Calculate public key encoding size. */
  26095. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26096. eccKey, ed25519Key, ed448Key, dsaKey);
  26097. publicKeySz = (word32)ret;
  26098. }
  26099. if (ret >= 0) {
  26100. /* Calculate extensions encoding size - may be 0. */
  26101. ret = EncodeExtensions(cert, NULL, 0, 0);
  26102. extSz = (word32)ret;
  26103. }
  26104. if (ret >= 0) {
  26105. /* Don't write out outer sequence - only doing body. */
  26106. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  26107. /* Set version, serial number and signature OID */
  26108. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  26109. (byte)cert->version);
  26110. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  26111. (word32)cert->serialSz);
  26112. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  26113. (word32)cert->sigType, oidSigType);
  26114. if (IsSigAlgoECC((word32)cert->sigType)) {
  26115. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  26116. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  26117. }
  26118. #ifdef WC_RSA_PSS
  26119. /* TODO: Encode RSA PSS parameters. */
  26120. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  26121. #endif
  26122. if (issRawLen > 0) {
  26123. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26124. defined(WOLFSSL_CERT_REQ)
  26125. /* Put in encoded issuer name. */
  26126. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  26127. cert->issRaw, issuerSz);
  26128. #endif
  26129. }
  26130. else {
  26131. /* Leave space for issuer name. */
  26132. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  26133. NULL, issuerSz);
  26134. }
  26135. if (cert->beforeDateSz && cert->afterDateSz) {
  26136. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  26137. /* Make space for before date data. */
  26138. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  26139. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  26140. /* Don't put out Generalized Time before data. */
  26141. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  26142. }
  26143. else {
  26144. /* Don't put out UTC before data. */
  26145. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  26146. /* Make space for before date data. */
  26147. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  26148. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  26149. }
  26150. if (cert->afterDate[0] == ASN_UTC_TIME) {
  26151. /* Make space for after date data. */
  26152. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  26153. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  26154. /* Don't put out UTC Generalized Time after data. */
  26155. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  26156. }
  26157. else {
  26158. /* Don't put out UTC after data. */
  26159. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  26160. /* Make space for after date data. */
  26161. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  26162. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  26163. }
  26164. }
  26165. else
  26166. {
  26167. /* Don't put out UTC before data. */
  26168. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  26169. /* Make space for before date data. */
  26170. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  26171. NULL, ASN_GEN_TIME_SZ);
  26172. /* Don't put out UTC after data. */
  26173. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  26174. /* Make space for after date data. */
  26175. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  26176. NULL, ASN_GEN_TIME_SZ);
  26177. }
  26178. if (sbjRawLen > 0) {
  26179. /* Put in encoded subject name. */
  26180. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26181. defined(WOLFSSL_CERT_REQ)
  26182. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  26183. cert->sbjRaw, subjectSz);
  26184. #endif
  26185. }
  26186. else {
  26187. /* Leave space for subject name. */
  26188. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  26189. NULL, subjectSz);
  26190. }
  26191. /* Leave space for public key. */
  26192. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  26193. NULL, publicKeySz);
  26194. /* Replacement buffer instead of algorithm identifier items. */
  26195. SetASNItem_NoOut(dataASN,
  26196. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  26197. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  26198. /* issuerUniqueID and subjectUniqueID not supported. */
  26199. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  26200. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  26201. /* Leave space for extensions if any set into certificate object. */
  26202. if (extSz > 0) {
  26203. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  26204. }
  26205. else {
  26206. SetASNItem_NoOutNode(dataASN, x509CertASN,
  26207. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  26208. }
  26209. /* No signature - added later. */
  26210. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  26211. X509CERTASN_IDX_SIGNATURE);
  26212. /* Calculate encoded certificate body size. */
  26213. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  26214. }
  26215. /* Check buffer is big enough for encoded data. */
  26216. if ((ret == 0) && (sz > (int)derSz)) {
  26217. ret = BUFFER_E;
  26218. }
  26219. if (ret == 0) {
  26220. /* Encode certificate body into buffer. */
  26221. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  26222. if (issRawLen == 0) {
  26223. /* Encode issuer name into buffer. Use the subject as the issuer
  26224. * if it is self-signed. Size will be correct because we did the
  26225. * same for size. */
  26226. ret = SetNameEx(
  26227. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  26228. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  26229. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  26230. }
  26231. }
  26232. if ((ret >= 0) && (sbjRawLen == 0)) {
  26233. /* Encode subject name into buffer. */
  26234. ret = SetNameEx(
  26235. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  26236. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  26237. &cert->subject, cert->heap);
  26238. }
  26239. if (ret >= 0) {
  26240. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  26241. {
  26242. /* Encode validity into buffer. */
  26243. ret = SetValidity(
  26244. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  26245. .data.buffer.data,
  26246. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  26247. .data.buffer.data, cert->daysValid);
  26248. }
  26249. }
  26250. if (ret >= 0) {
  26251. /* Encode public key into buffer. */
  26252. ret = EncodePublicKey(cert->keyType,
  26253. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  26254. .data.buffer.data,
  26255. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  26256. .data.buffer.length,
  26257. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26258. }
  26259. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  26260. /* Encode extensions into buffer. */
  26261. ret = EncodeExtensions(cert,
  26262. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  26263. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  26264. }
  26265. if (ret >= 0) {
  26266. /* Store encoded certifcate body size. */
  26267. cert->bodySz = sz;
  26268. /* Return the encoding size. */
  26269. ret = sz;
  26270. }
  26271. FREE_ASNSETDATA(dataASN, cert->heap);
  26272. return ret;
  26273. #endif
  26274. }
  26275. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26276. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26277. void* key, WC_RNG* rng)
  26278. {
  26279. RsaKey* rsaKey = NULL;
  26280. DsaKey* dsaKey = NULL;
  26281. ecc_key* eccKey = NULL;
  26282. ed25519_key* ed25519Key = NULL;
  26283. ed448_key* ed448Key = NULL;
  26284. falcon_key* falconKey = NULL;
  26285. dilithium_key* dilithiumKey = NULL;
  26286. sphincs_key* sphincsKey = NULL;
  26287. if (keyType == RSA_TYPE)
  26288. rsaKey = (RsaKey*)key;
  26289. else if (keyType == DSA_TYPE)
  26290. dsaKey = (DsaKey*)key;
  26291. else if (keyType == ECC_TYPE)
  26292. eccKey = (ecc_key*)key;
  26293. else if (keyType == ED25519_TYPE)
  26294. ed25519Key = (ed25519_key*)key;
  26295. else if (keyType == ED448_TYPE)
  26296. ed448Key = (ed448_key*)key;
  26297. else if (keyType == FALCON_LEVEL1_TYPE)
  26298. falconKey = (falcon_key*)key;
  26299. else if (keyType == FALCON_LEVEL5_TYPE)
  26300. falconKey = (falcon_key*)key;
  26301. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26302. dilithiumKey = (dilithium_key*)key;
  26303. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26304. dilithiumKey = (dilithium_key*)key;
  26305. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26306. dilithiumKey = (dilithium_key*)key;
  26307. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26308. sphincsKey = (sphincs_key*)key;
  26309. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26310. sphincsKey = (sphincs_key*)key;
  26311. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26312. sphincsKey = (sphincs_key*)key;
  26313. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26314. sphincsKey = (sphincs_key*)key;
  26315. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26316. sphincsKey = (sphincs_key*)key;
  26317. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26318. sphincsKey = (sphincs_key*)key;
  26319. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  26320. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26321. sphincsKey);
  26322. }
  26323. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26324. WOLFSSL_ABI
  26325. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  26326. ecc_key* eccKey, WC_RNG* rng)
  26327. {
  26328. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  26329. NULL, NULL, NULL, NULL);
  26330. }
  26331. #ifdef WOLFSSL_CERT_REQ
  26332. #ifndef WOLFSSL_ASN_TEMPLATE
  26333. /* return size of data set on success
  26334. * if getting size only then attr and oid should be NULL
  26335. */
  26336. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  26337. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  26338. word32 extSz)
  26339. {
  26340. word32 totalSz = 0;
  26341. word32 seqSz = 0;
  26342. word32 setSz = 0;
  26343. word32 strSz = 0;
  26344. byte seq[MAX_SEQ_SZ];
  26345. byte set[MAX_SET_SZ];
  26346. byte str[MAX_PRSTR_SZ];
  26347. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  26348. totalSz += oidSz;
  26349. if (extSz > 0) {
  26350. totalSz += setSz = SetSet(extSz, set);
  26351. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26352. totalSz += extSz;
  26353. }
  26354. else {
  26355. if (printable) {
  26356. strSz = SetPrintableString(attrSz, str);
  26357. totalSz += strSz;
  26358. }
  26359. else {
  26360. totalSz += strSz = SetUTF8String(attrSz, str);
  26361. }
  26362. totalSz += setSz = SetSet(strSz + attrSz, set);
  26363. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26364. totalSz += attrSz;
  26365. }
  26366. if (oid) {
  26367. XMEMCPY(&output[*idx], seq, seqSz);
  26368. *idx += seqSz;
  26369. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  26370. XMEMCPY(&output[*idx], oid, oidSz);
  26371. *idx += oidSz;
  26372. XMEMCPY(&output[*idx], set, setSz);
  26373. *idx += setSz;
  26374. if (strSz > 0) {
  26375. XMEMCPY(&output[*idx], str, strSz);
  26376. *idx += strSz;
  26377. if (attrSz > 0) {
  26378. XMEMCPY(&output[*idx], attr, attrSz);
  26379. *idx += attrSz;
  26380. }
  26381. }
  26382. }
  26383. return totalSz;
  26384. }
  26385. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  26386. {
  26387. word32 sz = 0; /* overall size */
  26388. word32 setSz = 0;
  26389. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26390. sz++;
  26391. if (cert->challengePw[0]) {
  26392. setSz += SetReqAttribSingle(output, &sz, NULL,
  26393. (word32)XSTRLEN(cert->challengePw), NULL,
  26394. sizeof(attrChallengePasswordOid),
  26395. (byte)cert->challengePwPrintableString, 0);
  26396. }
  26397. if (cert->unstructuredName[0]) {
  26398. setSz += SetReqAttribSingle(output, &sz, NULL,
  26399. (word32)XSTRLEN(cert->unstructuredName), NULL,
  26400. sizeof(attrUnstructuredNameOid), 1, 0);
  26401. }
  26402. if (extSz) {
  26403. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26404. sizeof(attrExtensionRequestOid), 1, extSz);
  26405. }
  26406. /* Put the pieces together. */
  26407. sz += SetLength(setSz, &output[sz]);
  26408. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26409. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26410. return REQ_ATTRIBUTE_E;
  26411. }
  26412. if (cert->challengePw[0]) {
  26413. SetReqAttribSingle(output, &sz, cert->challengePw,
  26414. (word32)XSTRLEN(cert->challengePw),
  26415. &attrChallengePasswordOid[0],
  26416. sizeof(attrChallengePasswordOid),
  26417. (byte)cert->challengePwPrintableString, 0);
  26418. }
  26419. if (cert->unstructuredName[0]) {
  26420. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26421. (word32)XSTRLEN(cert->unstructuredName),
  26422. &attrUnstructuredNameOid[0],
  26423. sizeof(attrUnstructuredNameOid), 1, 0);
  26424. }
  26425. if (extSz) {
  26426. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26427. sizeof(attrExtensionRequestOid), 1, extSz);
  26428. /* The actual extension data will be tacked onto the output later. */
  26429. }
  26430. return (int)sz;
  26431. }
  26432. #ifdef WOLFSSL_CUSTOM_OID
  26433. /* encode a custom oid and value */
  26434. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26435. CertOidField* custom)
  26436. {
  26437. int idx = 0, cust_lenSz, cust_oidSz;
  26438. if (cert == NULL || output == NULL || custom == NULL) {
  26439. return BAD_FUNC_ARG;
  26440. }
  26441. if (custom->oid == NULL || custom->oidSz <= 0) {
  26442. return 0; /* none set */
  26443. }
  26444. /* Octet String header */
  26445. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26446. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26447. /* check for output buffer room */
  26448. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26449. outSz) {
  26450. return BUFFER_E;
  26451. }
  26452. /* put sequence with total */
  26453. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26454. output);
  26455. /* put oid header */
  26456. idx += SetObjectId(custom->oidSz, output+idx);
  26457. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26458. idx += custom->oidSz;
  26459. /* put value */
  26460. idx += SetOctetString(custom->valSz, output+idx);
  26461. XMEMCPY(output+idx, custom->val, custom->valSz);
  26462. idx += custom->valSz;
  26463. return idx;
  26464. }
  26465. #endif /* WOLFSSL_CUSTOM_OID */
  26466. /* encode info from cert into DER encoded format */
  26467. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26468. DsaKey* dsaKey, ecc_key* eccKey,
  26469. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26470. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26471. sphincs_key* sphincsKey)
  26472. {
  26473. int ret;
  26474. (void)eccKey;
  26475. (void)ed25519Key;
  26476. (void)ed448Key;
  26477. (void)falconKey;
  26478. (void)dilithiumKey;
  26479. (void)sphincsKey;
  26480. if (cert == NULL || der == NULL)
  26481. return BAD_FUNC_ARG;
  26482. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26483. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26484. falconKey == NULL) {
  26485. return PUBLIC_KEY_E;
  26486. }
  26487. /* init */
  26488. XMEMSET(der, 0, sizeof(DerCert));
  26489. /* version */
  26490. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  26491. /* subject name */
  26492. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26493. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26494. /* Use the raw subject */
  26495. int idx;
  26496. der->subjectSz = (int)min(sizeof(der->subject),
  26497. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26498. /* header */
  26499. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  26500. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26501. return SUBJECT_E;
  26502. }
  26503. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26504. (size_t)der->subjectSz);
  26505. der->subjectSz += idx;
  26506. }
  26507. else
  26508. #endif
  26509. {
  26510. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26511. &cert->subject, cert->heap);
  26512. }
  26513. if (der->subjectSz <= 0)
  26514. return SUBJECT_E;
  26515. /* public key */
  26516. #ifndef NO_RSA
  26517. if (cert->keyType == RSA_KEY) {
  26518. if (rsaKey == NULL)
  26519. return PUBLIC_KEY_E;
  26520. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26521. sizeof(der->publicKey), 1);
  26522. }
  26523. #endif
  26524. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26525. if (cert->keyType == DSA_KEY) {
  26526. if (dsaKey == NULL)
  26527. return PUBLIC_KEY_E;
  26528. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26529. sizeof(der->publicKey), 1);
  26530. }
  26531. #endif
  26532. #ifdef HAVE_ECC
  26533. if (cert->keyType == ECC_KEY) {
  26534. if (eccKey == NULL)
  26535. return PUBLIC_KEY_E;
  26536. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26537. sizeof(der->publicKey), 1, 0);
  26538. }
  26539. #endif
  26540. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26541. if (cert->keyType == ED25519_KEY) {
  26542. if (ed25519Key == NULL)
  26543. return PUBLIC_KEY_E;
  26544. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26545. (word32)sizeof(der->publicKey), 1);
  26546. }
  26547. #endif
  26548. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26549. if (cert->keyType == ED448_KEY) {
  26550. if (ed448Key == NULL)
  26551. return PUBLIC_KEY_E;
  26552. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26553. (word32)sizeof(der->publicKey), 1);
  26554. }
  26555. #endif
  26556. #if defined(HAVE_PQC)
  26557. #if defined(HAVE_FALCON)
  26558. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26559. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26560. if (falconKey == NULL)
  26561. return PUBLIC_KEY_E;
  26562. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26563. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26564. }
  26565. #endif
  26566. #if defined(HAVE_DILITHIUM)
  26567. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26568. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26569. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26570. if (dilithiumKey == NULL)
  26571. return PUBLIC_KEY_E;
  26572. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26573. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26574. }
  26575. #endif
  26576. #if defined(HAVE_SPHINCS)
  26577. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26578. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26579. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26580. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26581. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26582. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26583. if (sphincsKey == NULL)
  26584. return PUBLIC_KEY_E;
  26585. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26586. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26587. }
  26588. #endif
  26589. #endif /* HAVE_PQC */
  26590. if (der->publicKeySz <= 0)
  26591. return PUBLIC_KEY_E;
  26592. /* set the extensions */
  26593. der->extensionsSz = 0;
  26594. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26595. * The pathLenConstraint field is meaningful only if the CA boolean is
  26596. * asserted and the key usage extension, if present, asserts the
  26597. * keyCertSign bit */
  26598. /* Set CA and path length */
  26599. if ((cert->isCA) && (cert->pathLenSet)
  26600. #ifdef WOLFSSL_CERT_EXT
  26601. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26602. #endif
  26603. ) {
  26604. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26605. if (der->caSz <= 0)
  26606. return CA_TRUE_E;
  26607. der->extensionsSz += der->caSz;
  26608. }
  26609. /* Set CA */
  26610. else if (cert->isCA) {
  26611. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26612. if (der->caSz <= 0)
  26613. return CA_TRUE_E;
  26614. der->extensionsSz += der->caSz;
  26615. }
  26616. /* Set Basic Constraint */
  26617. else if (cert->basicConstSet) {
  26618. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26619. if (der->caSz <= 0)
  26620. return EXTENSIONS_E;
  26621. der->extensionsSz += der->caSz;
  26622. }
  26623. else
  26624. der->caSz = 0;
  26625. #ifdef WOLFSSL_ALT_NAMES
  26626. /* Alternative Name */
  26627. if (cert->altNamesSz) {
  26628. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26629. cert->altNames, (word32)cert->altNamesSz,
  26630. cert->altNamesCrit);
  26631. if (der->altNamesSz <= 0)
  26632. return ALT_NAME_E;
  26633. der->extensionsSz += der->altNamesSz;
  26634. }
  26635. else
  26636. der->altNamesSz = 0;
  26637. #endif
  26638. #ifdef WOLFSSL_CERT_EXT
  26639. /* SKID */
  26640. if (cert->skidSz) {
  26641. /* check the provided SKID size */
  26642. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26643. return SKID_E;
  26644. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26645. cert->skid, (word32)cert->skidSz);
  26646. if (der->skidSz <= 0)
  26647. return SKID_E;
  26648. der->extensionsSz += der->skidSz;
  26649. }
  26650. else
  26651. der->skidSz = 0;
  26652. /* Key Usage */
  26653. if (cert->keyUsage != 0) {
  26654. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26655. cert->keyUsage);
  26656. if (der->keyUsageSz <= 0)
  26657. return KEYUSAGE_E;
  26658. der->extensionsSz += der->keyUsageSz;
  26659. }
  26660. else
  26661. der->keyUsageSz = 0;
  26662. /* Extended Key Usage */
  26663. if (cert->extKeyUsage != 0) {
  26664. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26665. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26666. if (der->extKeyUsageSz <= 0)
  26667. return EXTKEYUSAGE_E;
  26668. der->extensionsSz += der->extKeyUsageSz;
  26669. }
  26670. else
  26671. der->extKeyUsageSz = 0;
  26672. #endif /* WOLFSSL_CERT_EXT */
  26673. #ifdef WOLFSSL_CUSTOM_OID
  26674. /* encode a custom oid and value */
  26675. /* zero returns, means none set */
  26676. ret = SetCustomObjectId(cert, der->extCustom,
  26677. sizeof(der->extCustom), &cert->extCustom);
  26678. if (ret < 0)
  26679. return ret;
  26680. der->extCustomSz = ret;
  26681. der->extensionsSz += der->extCustomSz;
  26682. #endif
  26683. /* put extensions */
  26684. if (der->extensionsSz > 0) {
  26685. /* put the start of sequence (ID, Size) */
  26686. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  26687. der->extensions);
  26688. if (der->extensionsSz <= 0)
  26689. return EXTENSIONS_E;
  26690. /* put CA */
  26691. if (der->caSz) {
  26692. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26693. &der->extensionsSz,
  26694. der->ca, der->caSz);
  26695. if (ret <= 0)
  26696. return EXTENSIONS_E;
  26697. }
  26698. #ifdef WOLFSSL_ALT_NAMES
  26699. /* put Alternative Names */
  26700. if (der->altNamesSz) {
  26701. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26702. &der->extensionsSz,
  26703. der->altNames, der->altNamesSz);
  26704. if (ret <= 0)
  26705. return EXTENSIONS_E;
  26706. }
  26707. #endif
  26708. #ifdef WOLFSSL_CERT_EXT
  26709. /* put SKID */
  26710. if (der->skidSz) {
  26711. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26712. &der->extensionsSz,
  26713. der->skid, der->skidSz);
  26714. if (ret <= 0)
  26715. return EXTENSIONS_E;
  26716. }
  26717. /* put AKID */
  26718. if (der->akidSz) {
  26719. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26720. &der->extensionsSz,
  26721. der->akid, der->akidSz);
  26722. if (ret <= 0)
  26723. return EXTENSIONS_E;
  26724. }
  26725. /* put KeyUsage */
  26726. if (der->keyUsageSz) {
  26727. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26728. &der->extensionsSz,
  26729. der->keyUsage, der->keyUsageSz);
  26730. if (ret <= 0)
  26731. return EXTENSIONS_E;
  26732. }
  26733. /* put ExtendedKeyUsage */
  26734. if (der->extKeyUsageSz) {
  26735. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26736. &der->extensionsSz,
  26737. der->extKeyUsage, der->extKeyUsageSz);
  26738. if (ret <= 0)
  26739. return EXTENSIONS_E;
  26740. }
  26741. #ifdef WOLFSSL_CUSTOM_OID
  26742. if (der->extCustomSz) {
  26743. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26744. &der->extensionsSz,
  26745. der->extCustom, der->extCustomSz);
  26746. if (ret <= 0)
  26747. return EXTENSIONS_E;
  26748. }
  26749. #endif
  26750. #endif /* WOLFSSL_CERT_EXT */
  26751. }
  26752. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  26753. if (der->attribSz <= 0)
  26754. return REQ_ATTRIBUTE_E;
  26755. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  26756. der->extensionsSz + der->attribSz;
  26757. return 0;
  26758. }
  26759. /* write DER encoded cert req to buffer, size already checked */
  26760. static int WriteCertReqBody(DerCert* der, byte* buf)
  26761. {
  26762. int idx;
  26763. /* signed part header */
  26764. idx = (int)SetSequence((word32)der->total, buf);
  26765. /* version */
  26766. if (buf)
  26767. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  26768. idx += der->versionSz;
  26769. /* subject */
  26770. if (buf)
  26771. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  26772. idx += der->subjectSz;
  26773. /* public key */
  26774. if (buf)
  26775. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  26776. idx += der->publicKeySz;
  26777. /* attributes */
  26778. if (buf)
  26779. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  26780. idx += der->attribSz;
  26781. /* extensions */
  26782. if (der->extensionsSz) {
  26783. if (buf)
  26784. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  26785. sizeof(der->extensions)));
  26786. idx += der->extensionsSz;
  26787. }
  26788. return idx;
  26789. }
  26790. #endif
  26791. #ifdef WOLFSSL_ASN_TEMPLATE
  26792. /* ASN.1 template for Certificate Request body.
  26793. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  26794. */
  26795. static const ASNItem certReqBodyASN[] = {
  26796. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26797. /* version */
  26798. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  26799. /* subject */
  26800. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26801. /* subjectPKInfo */
  26802. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26803. /* attributes*/
  26804. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26805. /* Challenge Password Attribute */
  26806. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26807. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26808. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  26809. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  26810. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  26811. /* Extensions Attribute */
  26812. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26813. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26814. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  26815. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  26816. };
  26817. enum {
  26818. CERTREQBODYASN_IDX_SEQ = 0,
  26819. CERTREQBODYASN_IDX_VER,
  26820. CERTREQBODYASN_IDX_SUBJ_SEQ,
  26821. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  26822. CERTREQBODYASN_IDX_ATTRS,
  26823. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  26824. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  26825. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  26826. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  26827. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  26828. CERTREQBODYASN_IDX_EXT_SEQ,
  26829. CERTREQBODYASN_IDX_EXT_OID,
  26830. CERTREQBODYASN_IDX_EXT_SET,
  26831. CERTREQBODYASN_IDX_EXT_BODY
  26832. };
  26833. /* Number of items in ASN.1 template for Certificate Request body. */
  26834. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  26835. #endif
  26836. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26837. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  26838. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26839. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26840. sphincs_key* sphincsKey)
  26841. {
  26842. #ifndef WOLFSSL_ASN_TEMPLATE
  26843. int ret;
  26844. #ifdef WOLFSSL_SMALL_STACK
  26845. DerCert* der;
  26846. #else
  26847. DerCert der[1];
  26848. #endif
  26849. if (eccKey)
  26850. cert->keyType = ECC_KEY;
  26851. else if (rsaKey)
  26852. cert->keyType = RSA_KEY;
  26853. else if (dsaKey)
  26854. cert->keyType = DSA_KEY;
  26855. else if (ed25519Key)
  26856. cert->keyType = ED25519_KEY;
  26857. else if (ed448Key)
  26858. cert->keyType = ED448_KEY;
  26859. #ifdef HAVE_PQC
  26860. #ifdef HAVE_FALCON
  26861. else if ((falconKey != NULL) && (falconKey->level == 1))
  26862. cert->keyType = FALCON_LEVEL1_KEY;
  26863. else if ((falconKey != NULL) && (falconKey->level == 5))
  26864. cert->keyType = FALCON_LEVEL5_KEY;
  26865. #endif /* HAVE_FALCON */
  26866. #ifdef HAVE_DILITHIUM
  26867. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26868. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26869. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26870. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26871. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26872. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26873. #endif /* HAVE_DILITHIUM */
  26874. #ifdef HAVE_SPHINCS
  26875. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26876. && (sphincsKey->optim == FAST_VARIANT))
  26877. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26878. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26879. && (sphincsKey->optim == FAST_VARIANT))
  26880. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26881. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26882. && (sphincsKey->optim == FAST_VARIANT))
  26883. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26884. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26885. && (sphincsKey->optim == SMALL_VARIANT))
  26886. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26887. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26888. && (sphincsKey->optim == SMALL_VARIANT))
  26889. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26890. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26891. && (sphincsKey->optim == SMALL_VARIANT))
  26892. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26893. #endif /* HAVE_SPHINCS */
  26894. #endif /* HAVE_PQC */
  26895. else
  26896. return BAD_FUNC_ARG;
  26897. #ifdef WOLFSSL_SMALL_STACK
  26898. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  26899. DYNAMIC_TYPE_TMP_BUFFER);
  26900. if (der == NULL)
  26901. return MEMORY_E;
  26902. #endif
  26903. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  26904. falconKey, dilithiumKey, sphincsKey);
  26905. if (ret == 0) {
  26906. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26907. ret = BUFFER_E;
  26908. else
  26909. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  26910. }
  26911. #ifdef WOLFSSL_SMALL_STACK
  26912. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26913. #endif
  26914. return ret;
  26915. #else
  26916. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  26917. word32 publicKeySz = 0;
  26918. word32 subjectSz = 0;
  26919. word32 extSz = 0;
  26920. int sz = 0;
  26921. int ret = 0;
  26922. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26923. word32 sbjRawSz = 0;
  26924. #endif
  26925. /* Unused without OQS */
  26926. (void)falconKey;
  26927. (void)dilithiumKey;
  26928. (void)sphincsKey;
  26929. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  26930. if (ret == 0) {
  26931. /* Set key type into certificate object based on key passed in. */
  26932. if (rsaKey != NULL) {
  26933. cert->keyType = RSA_KEY;
  26934. }
  26935. else if (eccKey != NULL) {
  26936. cert->keyType = ECC_KEY;
  26937. }
  26938. else if (dsaKey != NULL) {
  26939. cert->keyType = DSA_KEY;
  26940. }
  26941. else if (ed25519Key != NULL) {
  26942. cert->keyType = ED25519_KEY;
  26943. }
  26944. else if (ed448Key != NULL) {
  26945. cert->keyType = ED448_KEY;
  26946. }
  26947. #ifdef HAVE_PQC
  26948. #ifdef HAVE_FALCON
  26949. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26950. cert->keyType = FALCON_LEVEL1_KEY;
  26951. }
  26952. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26953. cert->keyType = FALCON_LEVEL5_KEY;
  26954. }
  26955. #endif /* HAVE_FALCON */
  26956. #ifdef HAVE_DILITHIUM
  26957. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26958. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26959. }
  26960. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26961. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26962. }
  26963. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26964. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26965. }
  26966. #endif /* HAVE_DILITHIUM */
  26967. #ifdef HAVE_SPHINCS
  26968. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26969. && (sphincsKey->optim == FAST_VARIANT)) {
  26970. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26971. }
  26972. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26973. && (sphincsKey->optim == FAST_VARIANT)) {
  26974. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26975. }
  26976. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26977. && (sphincsKey->optim == FAST_VARIANT)) {
  26978. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26979. }
  26980. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26981. && (sphincsKey->optim == SMALL_VARIANT)) {
  26982. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26983. }
  26984. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26985. && (sphincsKey->optim == SMALL_VARIANT)) {
  26986. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26987. }
  26988. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26989. && (sphincsKey->optim == SMALL_VARIANT)) {
  26990. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26991. }
  26992. #endif /* HAVE_SPHINCS */
  26993. #endif /* HAVE_PQC */
  26994. else {
  26995. ret = BAD_FUNC_ARG;
  26996. }
  26997. }
  26998. if (ret == 0) {
  26999. /* Determine subject name size. */
  27000. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27001. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  27002. if (sbjRawSz > 0) {
  27003. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  27004. }
  27005. else
  27006. #endif
  27007. {
  27008. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  27009. subjectSz = (word32)ret;
  27010. }
  27011. }
  27012. if (ret >= 0) {
  27013. /* Determine encode public key size. */
  27014. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  27015. eccKey, ed25519Key, ed448Key, dsaKey);
  27016. publicKeySz = (word32)ret;
  27017. }
  27018. if (ret >= 0) {
  27019. /* Determine encode extensions size. */
  27020. ret = EncodeExtensions(cert, NULL, 0, 1);
  27021. extSz = (word32)ret;
  27022. }
  27023. if (ret >= 0) {
  27024. /* Set version. */
  27025. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  27026. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27027. if (sbjRawSz > 0) {
  27028. /* Put in encoded subject name. */
  27029. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  27030. subjectSz);
  27031. }
  27032. else
  27033. #endif
  27034. {
  27035. /* Leave space for subject name. */
  27036. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  27037. subjectSz);
  27038. }
  27039. /* Leave space for public key. */
  27040. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  27041. NULL, publicKeySz);
  27042. if (cert->challengePw[0] != '\0') {
  27043. /* Add challenge password attribute. */
  27044. /* Set challenge password OID. */
  27045. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  27046. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  27047. /* Enable the ASN template item with the appropriate tag. */
  27048. if (cert->challengePwPrintableString) {
  27049. /* PRINTABLE_STRING - set buffer */
  27050. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  27051. (byte*)cert->challengePw,
  27052. (word32)XSTRLEN(cert->challengePw));
  27053. /* UTF8STRING - don't encode */
  27054. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  27055. }
  27056. else {
  27057. /* PRINTABLE_STRING - don't encode */
  27058. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  27059. /* UTF8STRING - set buffer */
  27060. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  27061. (byte*)cert->challengePw,
  27062. (word32)XSTRLEN(cert->challengePw));
  27063. }
  27064. }
  27065. else {
  27066. /* Leave out challenge password attribute items. */
  27067. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  27068. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  27069. }
  27070. if (extSz > 0) {
  27071. /* Set extension attribute OID. */
  27072. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  27073. sizeof(attrExtensionRequestOid));
  27074. /* Leave space for data. */
  27075. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  27076. }
  27077. else {
  27078. /* Leave out extension attribute items. */
  27079. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  27080. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  27081. }
  27082. /* Calculate size of encoded certificate request body. */
  27083. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  27084. &sz);
  27085. }
  27086. /* Check buffer is big enough for encoded data. */
  27087. if ((ret == 0) && (sz > (int)derSz)) {
  27088. ret = BUFFER_E;
  27089. }
  27090. if (ret == 0 && derBuffer != NULL) {
  27091. /* Encode certificate request body into buffer. */
  27092. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  27093. /* Put in generated data */
  27094. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  27095. if (sbjRawSz == 0)
  27096. #endif
  27097. {
  27098. /* Encode subject name into space in buffer. */
  27099. ret = SetNameEx(
  27100. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  27101. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  27102. &cert->subject, cert->heap);
  27103. }
  27104. }
  27105. if (ret >= 0 && derBuffer != NULL) {
  27106. /* Encode public key into space in buffer. */
  27107. ret = EncodePublicKey(cert->keyType,
  27108. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  27109. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  27110. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  27111. }
  27112. if ((ret >= 0 && derBuffer != NULL) &&
  27113. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  27114. /* Encode extensions into space in buffer. */
  27115. ret = EncodeExtensions(cert,
  27116. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  27117. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  27118. }
  27119. if (ret >= 0) {
  27120. /* Store encoded certifcate request body size. */
  27121. cert->bodySz = sz;
  27122. /* Return the encoding size. */
  27123. ret = sz;
  27124. }
  27125. FREE_ASNSETDATA(dataASN, cert->heap);
  27126. return ret;
  27127. #endif /* WOLFSSL_ASN_TEMPLATE */
  27128. }
  27129. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  27130. void* key)
  27131. {
  27132. RsaKey* rsaKey = NULL;
  27133. DsaKey* dsaKey = NULL;
  27134. ecc_key* eccKey = NULL;
  27135. ed25519_key* ed25519Key = NULL;
  27136. ed448_key* ed448Key = NULL;
  27137. falcon_key* falconKey = NULL;
  27138. dilithium_key* dilithiumKey = NULL;
  27139. sphincs_key* sphincsKey = NULL;
  27140. if (keyType == RSA_TYPE)
  27141. rsaKey = (RsaKey*)key;
  27142. else if (keyType == DSA_TYPE)
  27143. dsaKey = (DsaKey*)key;
  27144. else if (keyType == ECC_TYPE)
  27145. eccKey = (ecc_key*)key;
  27146. else if (keyType == ED25519_TYPE)
  27147. ed25519Key = (ed25519_key*)key;
  27148. else if (keyType == ED448_TYPE)
  27149. ed448Key = (ed448_key*)key;
  27150. else if (keyType == FALCON_LEVEL1_TYPE)
  27151. falconKey = (falcon_key*)key;
  27152. else if (keyType == FALCON_LEVEL5_TYPE)
  27153. falconKey = (falcon_key*)key;
  27154. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27155. dilithiumKey = (dilithium_key*)key;
  27156. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27157. dilithiumKey = (dilithium_key*)key;
  27158. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27159. dilithiumKey = (dilithium_key*)key;
  27160. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27161. sphincsKey = (sphincs_key*)key;
  27162. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27163. sphincsKey = (sphincs_key*)key;
  27164. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27165. sphincsKey = (sphincs_key*)key;
  27166. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27167. sphincsKey = (sphincs_key*)key;
  27168. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27169. sphincsKey = (sphincs_key*)key;
  27170. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27171. sphincsKey = (sphincs_key*)key;
  27172. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  27173. ed25519Key, ed448Key, falconKey, dilithiumKey,
  27174. sphincsKey);
  27175. }
  27176. WOLFSSL_ABI
  27177. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  27178. RsaKey* rsaKey, ecc_key* eccKey)
  27179. {
  27180. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  27181. NULL, NULL, NULL, NULL);
  27182. }
  27183. #endif /* WOLFSSL_CERT_REQ */
  27184. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27185. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  27186. ed448_key* ed448Key, falcon_key* falconKey,
  27187. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  27188. WC_RNG* rng)
  27189. {
  27190. int sigSz = 0;
  27191. void* heap = NULL;
  27192. CertSignCtx certSignCtx_lcl;
  27193. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  27194. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  27195. if (requestSz < 0)
  27196. return requestSz;
  27197. /* locate ctx */
  27198. if (rsaKey) {
  27199. #ifndef NO_RSA
  27200. #ifdef WOLFSSL_ASYNC_CRYPT
  27201. certSignCtx = &rsaKey->certSignCtx;
  27202. #endif
  27203. heap = rsaKey->heap;
  27204. #else
  27205. return NOT_COMPILED_IN;
  27206. #endif /* NO_RSA */
  27207. }
  27208. else if (eccKey) {
  27209. #ifdef HAVE_ECC
  27210. #ifdef WOLFSSL_ASYNC_CRYPT
  27211. certSignCtx = &eccKey->certSignCtx;
  27212. #endif
  27213. heap = eccKey->heap;
  27214. #else
  27215. return NOT_COMPILED_IN;
  27216. #endif /* HAVE_ECC */
  27217. }
  27218. if (certSignCtx->sig == NULL) {
  27219. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  27220. DYNAMIC_TYPE_TMP_BUFFER);
  27221. if (certSignCtx->sig == NULL)
  27222. return MEMORY_E;
  27223. }
  27224. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  27225. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  27226. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  27227. #ifdef WOLFSSL_ASYNC_CRYPT
  27228. if (sigSz == WC_PENDING_E) {
  27229. /* Not free'ing certSignCtx->sig here because it could still be in use
  27230. * with async operations. */
  27231. return sigSz;
  27232. }
  27233. #endif
  27234. if (sigSz >= 0) {
  27235. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  27236. sigSz = BUFFER_E;
  27237. else
  27238. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  27239. sType);
  27240. }
  27241. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27242. certSignCtx->sig = NULL;
  27243. return sigSz;
  27244. }
  27245. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  27246. int keyType, void* key, WC_RNG* rng)
  27247. {
  27248. RsaKey* rsaKey = NULL;
  27249. ecc_key* eccKey = NULL;
  27250. ed25519_key* ed25519Key = NULL;
  27251. ed448_key* ed448Key = NULL;
  27252. falcon_key* falconKey = NULL;
  27253. dilithium_key* dilithiumKey = NULL;
  27254. sphincs_key* sphincsKey = NULL;
  27255. if (keyType == RSA_TYPE)
  27256. rsaKey = (RsaKey*)key;
  27257. else if (keyType == ECC_TYPE)
  27258. eccKey = (ecc_key*)key;
  27259. else if (keyType == ED25519_TYPE)
  27260. ed25519Key = (ed25519_key*)key;
  27261. else if (keyType == ED448_TYPE)
  27262. ed448Key = (ed448_key*)key;
  27263. else if (keyType == FALCON_LEVEL1_TYPE)
  27264. falconKey = (falcon_key*)key;
  27265. else if (keyType == FALCON_LEVEL5_TYPE)
  27266. falconKey = (falcon_key*)key;
  27267. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27268. dilithiumKey = (dilithium_key*)key;
  27269. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27270. dilithiumKey = (dilithium_key*)key;
  27271. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27272. dilithiumKey = (dilithium_key*)key;
  27273. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27274. sphincsKey = (sphincs_key*)key;
  27275. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27276. sphincsKey = (sphincs_key*)key;
  27277. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27278. sphincsKey = (sphincs_key*)key;
  27279. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27280. sphincsKey = (sphincs_key*)key;
  27281. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27282. sphincsKey = (sphincs_key*)key;
  27283. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27284. sphincsKey = (sphincs_key*)key;
  27285. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  27286. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  27287. }
  27288. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27289. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  27290. {
  27291. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  27292. NULL, NULL, NULL, rng);
  27293. }
  27294. WOLFSSL_ABI
  27295. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  27296. RsaKey* key, WC_RNG* rng)
  27297. {
  27298. int ret;
  27299. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  27300. if (ret < 0)
  27301. return ret;
  27302. return wc_SignCert(cert->bodySz, cert->sigType,
  27303. buf, buffSz, key, NULL, rng);
  27304. }
  27305. #ifdef WOLFSSL_CERT_EXT
  27306. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  27307. The raw subject pointer will only be valid while "cert" is valid. */
  27308. WOLFSSL_ABI
  27309. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  27310. {
  27311. int rc = BAD_FUNC_ARG;
  27312. if ((subjectRaw != NULL) && (cert != NULL)) {
  27313. *subjectRaw = cert->sbjRaw;
  27314. rc = 0;
  27315. }
  27316. return rc;
  27317. }
  27318. /* Set KID from public key */
  27319. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27320. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27321. falcon_key* falconKey,
  27322. dilithium_key* dilithiumKey,
  27323. sphincs_key *sphincsKey, int kid_type)
  27324. {
  27325. byte *buf;
  27326. int bufferSz, ret;
  27327. if (cert == NULL ||
  27328. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27329. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27330. sphincsKey == NULL) ||
  27331. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27332. return BAD_FUNC_ARG;
  27333. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27334. DYNAMIC_TYPE_TMP_BUFFER);
  27335. if (buf == NULL)
  27336. return MEMORY_E;
  27337. /* Public Key */
  27338. bufferSz = -1;
  27339. #ifndef NO_RSA
  27340. /* RSA public key */
  27341. if (rsakey != NULL)
  27342. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27343. #endif
  27344. #ifdef HAVE_ECC
  27345. /* ECC public key */
  27346. if (eckey != NULL)
  27347. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27348. #endif
  27349. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27350. /* ED25519 public key */
  27351. if (ed25519Key != NULL) {
  27352. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27353. }
  27354. #endif
  27355. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27356. /* ED448 public key */
  27357. if (ed448Key != NULL) {
  27358. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27359. }
  27360. #endif
  27361. #if defined(HAVE_PQC)
  27362. #if defined(HAVE_FALCON)
  27363. if (falconKey != NULL) {
  27364. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27365. 0);
  27366. }
  27367. #endif
  27368. #if defined(HAVE_DILITHIUM)
  27369. if (dilithiumKey != NULL) {
  27370. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27371. MAX_PUBLIC_KEY_SZ, 0);
  27372. }
  27373. #endif
  27374. #if defined(HAVE_SPHINCS)
  27375. if (sphincsKey != NULL) {
  27376. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27377. MAX_PUBLIC_KEY_SZ, 0);
  27378. }
  27379. #endif
  27380. #endif /* HAVE_PQC */
  27381. if (bufferSz <= 0) {
  27382. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27383. return PUBLIC_KEY_E;
  27384. }
  27385. /* Compute SKID by hashing public key */
  27386. if (kid_type == SKID_TYPE) {
  27387. int hashId = HashIdAlg((word32)cert->sigType);
  27388. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->skid, hashId);
  27389. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27390. cert->skidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  27391. #else
  27392. cert->skidSz = KEYID_SIZE;
  27393. #endif
  27394. }
  27395. else if (kid_type == AKID_TYPE) {
  27396. int hashId = HashIdAlg((word32)cert->sigType);
  27397. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->akid, hashId);
  27398. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27399. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  27400. #else
  27401. cert->akidSz = KEYID_SIZE;
  27402. #endif
  27403. }
  27404. else
  27405. ret = BAD_FUNC_ARG;
  27406. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27407. return ret;
  27408. }
  27409. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27410. {
  27411. RsaKey* rsaKey = NULL;
  27412. ecc_key* eccKey = NULL;
  27413. ed25519_key* ed25519Key = NULL;
  27414. ed448_key* ed448Key = NULL;
  27415. falcon_key* falconKey = NULL;
  27416. dilithium_key* dilithiumKey = NULL;
  27417. sphincs_key* sphincsKey = NULL;
  27418. if (keyType == RSA_TYPE)
  27419. rsaKey = (RsaKey*)key;
  27420. else if (keyType == ECC_TYPE)
  27421. eccKey = (ecc_key*)key;
  27422. else if (keyType == ED25519_TYPE)
  27423. ed25519Key = (ed25519_key*)key;
  27424. else if (keyType == ED448_TYPE)
  27425. ed448Key = (ed448_key*)key;
  27426. else if (keyType == FALCON_LEVEL1_TYPE)
  27427. falconKey = (falcon_key*)key;
  27428. else if (keyType == FALCON_LEVEL5_TYPE)
  27429. falconKey = (falcon_key*)key;
  27430. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27431. dilithiumKey = (dilithium_key*)key;
  27432. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27433. dilithiumKey = (dilithium_key*)key;
  27434. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27435. dilithiumKey = (dilithium_key*)key;
  27436. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27437. sphincsKey = (sphincs_key*)key;
  27438. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27439. sphincsKey = (sphincs_key*)key;
  27440. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27441. sphincsKey = (sphincs_key*)key;
  27442. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27443. sphincsKey = (sphincs_key*)key;
  27444. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27445. sphincsKey = (sphincs_key*)key;
  27446. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27447. sphincsKey = (sphincs_key*)key;
  27448. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27449. falconKey, dilithiumKey, sphincsKey,
  27450. SKID_TYPE);
  27451. }
  27452. /* Set SKID from RSA or ECC public key */
  27453. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27454. {
  27455. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27456. NULL, SKID_TYPE);
  27457. }
  27458. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27459. {
  27460. RsaKey* rsaKey = NULL;
  27461. ecc_key* eccKey = NULL;
  27462. ed25519_key* ed25519Key = NULL;
  27463. ed448_key* ed448Key = NULL;
  27464. falcon_key* falconKey = NULL;
  27465. dilithium_key* dilithiumKey = NULL;
  27466. sphincs_key* sphincsKey = NULL;
  27467. if (keyType == RSA_TYPE)
  27468. rsaKey = (RsaKey*)key;
  27469. else if (keyType == ECC_TYPE)
  27470. eccKey = (ecc_key*)key;
  27471. else if (keyType == ED25519_TYPE)
  27472. ed25519Key = (ed25519_key*)key;
  27473. else if (keyType == ED448_TYPE)
  27474. ed448Key = (ed448_key*)key;
  27475. else if (keyType == FALCON_LEVEL1_TYPE)
  27476. falconKey = (falcon_key*)key;
  27477. else if (keyType == FALCON_LEVEL5_TYPE)
  27478. falconKey = (falcon_key*)key;
  27479. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27480. dilithiumKey = (dilithium_key*)key;
  27481. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27482. dilithiumKey = (dilithium_key*)key;
  27483. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27484. dilithiumKey = (dilithium_key*)key;
  27485. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27486. sphincsKey = (sphincs_key*)key;
  27487. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27488. sphincsKey = (sphincs_key*)key;
  27489. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27490. sphincsKey = (sphincs_key*)key;
  27491. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27492. sphincsKey = (sphincs_key*)key;
  27493. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27494. sphincsKey = (sphincs_key*)key;
  27495. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27496. sphincsKey = (sphincs_key*)key;
  27497. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27498. falconKey, dilithiumKey, sphincsKey,
  27499. AKID_TYPE);
  27500. }
  27501. /* Set SKID from RSA or ECC public key */
  27502. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27503. {
  27504. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27505. NULL, AKID_TYPE);
  27506. }
  27507. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27508. /* Set SKID from public key file in PEM */
  27509. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27510. {
  27511. int ret, derSz;
  27512. byte* der;
  27513. word32 idx;
  27514. RsaKey *rsakey = NULL;
  27515. ecc_key *eckey = NULL;
  27516. if (cert == NULL || file == NULL)
  27517. return BAD_FUNC_ARG;
  27518. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27519. if (der == NULL) {
  27520. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27521. return MEMORY_E;
  27522. }
  27523. derSz = MAX_PUBLIC_KEY_SZ;
  27524. XMEMSET(der, 0, (size_t)derSz);
  27525. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27526. if (derSz <= 0) {
  27527. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27528. return derSz;
  27529. }
  27530. /* Load PubKey in internal structure */
  27531. #ifndef NO_RSA
  27532. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27533. if (rsakey == NULL) {
  27534. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27535. return MEMORY_E;
  27536. }
  27537. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27538. WOLFSSL_MSG("wc_InitRsaKey failure");
  27539. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27540. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27541. return MEMORY_E;
  27542. }
  27543. idx = 0;
  27544. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  27545. if (ret != 0)
  27546. #endif
  27547. {
  27548. #ifndef NO_RSA
  27549. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27550. wc_FreeRsaKey(rsakey);
  27551. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27552. rsakey = NULL;
  27553. #endif
  27554. #ifdef HAVE_ECC
  27555. /* Check to load ecc public key */
  27556. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27557. DYNAMIC_TYPE_ECC);
  27558. if (eckey == NULL) {
  27559. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27560. return MEMORY_E;
  27561. }
  27562. if (wc_ecc_init(eckey) != 0) {
  27563. WOLFSSL_MSG("wc_ecc_init failure");
  27564. wc_ecc_free(eckey);
  27565. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27566. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27567. return MEMORY_E;
  27568. }
  27569. idx = 0;
  27570. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  27571. if (ret != 0) {
  27572. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27573. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27574. wc_ecc_free(eckey);
  27575. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27576. return PUBLIC_KEY_E;
  27577. }
  27578. #else
  27579. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27580. return PUBLIC_KEY_E;
  27581. #endif /* HAVE_ECC */
  27582. }
  27583. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27584. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27585. #ifndef NO_RSA
  27586. wc_FreeRsaKey(rsakey);
  27587. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27588. #endif
  27589. #ifdef HAVE_ECC
  27590. wc_ecc_free(eckey);
  27591. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27592. #endif
  27593. return ret;
  27594. }
  27595. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27596. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27597. {
  27598. int ret = 0;
  27599. /* Subject Key Id not found !! */
  27600. if (decoded->extSubjKeyIdSet == 0) {
  27601. ret = ASN_NO_SKID;
  27602. }
  27603. /* SKID invalid size */
  27604. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27605. ret = MEMORY_E;
  27606. }
  27607. else {
  27608. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27609. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(HashIdAlg(
  27610. cert->sigType)));
  27611. #else
  27612. cert->akidSz = KEYID_SIZE;
  27613. #endif
  27614. /* Put the SKID of CA to AKID of certificate */
  27615. XMEMCPY(cert->akid, decoded->extSubjKeyId, (size_t)cert->akidSz);
  27616. }
  27617. return ret;
  27618. }
  27619. /* Set AKID from certificate contains in buffer (DER encoded) */
  27620. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  27621. {
  27622. int ret = 0;
  27623. if (cert == NULL) {
  27624. ret = BAD_FUNC_ARG;
  27625. }
  27626. else {
  27627. /* Check if decodedCert is cached */
  27628. if (cert->der != der) {
  27629. /* Allocate cache for the decoded cert */
  27630. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27631. }
  27632. if (ret >= 0) {
  27633. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27634. #ifndef WOLFSSL_CERT_GEN_CACHE
  27635. wc_SetCert_Free(cert);
  27636. #endif
  27637. }
  27638. }
  27639. return ret;
  27640. }
  27641. #ifndef NO_FILESYSTEM
  27642. /* Set AKID from certificate file in PEM */
  27643. int wc_SetAuthKeyId(Cert *cert, const char* file)
  27644. {
  27645. int ret;
  27646. DerBuffer* der = NULL;
  27647. if (cert == NULL || file == NULL)
  27648. return BAD_FUNC_ARG;
  27649. ret = wc_PemCertToDer_ex(file, &der);
  27650. if (ret == 0)
  27651. {
  27652. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  27653. FreeDer(&der);
  27654. }
  27655. return ret;
  27656. }
  27657. #endif /* !NO_FILESYSTEM */
  27658. /* Set KeyUsage from human readable string */
  27659. int wc_SetKeyUsage(Cert *cert, const char *value)
  27660. {
  27661. int ret = 0;
  27662. if (cert == NULL || value == NULL)
  27663. return BAD_FUNC_ARG;
  27664. cert->keyUsage = 0;
  27665. ret = ParseKeyUsageStr(value, &cert->keyUsage, cert->heap);
  27666. return ret;
  27667. }
  27668. /* Set ExtendedKeyUsage from human readable string */
  27669. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  27670. {
  27671. int ret = 0;
  27672. if (cert == NULL || value == NULL)
  27673. return BAD_FUNC_ARG;
  27674. cert->extKeyUsage = 0;
  27675. ret = ParseExtKeyUsageStr(value, &cert->extKeyUsage, cert->heap);
  27676. return ret;
  27677. }
  27678. #ifdef WOLFSSL_EKU_OID
  27679. /*
  27680. * cert structure to set EKU oid in
  27681. * oid the oid in byte representation
  27682. * sz size of oid buffer
  27683. * idx index of array to place oid
  27684. *
  27685. * returns 0 on success
  27686. */
  27687. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  27688. void* heap)
  27689. {
  27690. byte oid[MAX_OID_SZ];
  27691. word32 oidSz = MAX_OID_SZ;
  27692. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  27693. WOLFSSL_MSG("Either idx or sz was too large");
  27694. return BAD_FUNC_ARG;
  27695. }
  27696. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  27697. return BUFFER_E;
  27698. }
  27699. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  27700. cert->extKeyUsageOIDSz[idx] = oidSz;
  27701. cert->extKeyUsage |= EXTKEYUSE_USER;
  27702. return 0;
  27703. }
  27704. #endif /* WOLFSSL_EKU_OID */
  27705. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  27706. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  27707. defined(WOLFSSL_CERT_EXT)
  27708. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  27709. const byte *der, word32 derSz) {
  27710. CertExtension *ext;
  27711. byte encodedOid[MAX_OID_SZ];
  27712. word32 encodedOidSz = MAX_OID_SZ;
  27713. int ret;
  27714. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  27715. return BAD_FUNC_ARG;
  27716. }
  27717. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  27718. return MEMORY_E;
  27719. }
  27720. /* Make sure we can properly parse the OID. */
  27721. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  27722. if (ret != 0) {
  27723. return ret;
  27724. }
  27725. ext = &cert->customCertExt[cert->customCertExtCount];
  27726. ext->oid = oid;
  27727. ext->crit = (critical == 0) ? 0 : 1;
  27728. ext->val = der;
  27729. ext->valSz = derSz;
  27730. cert->customCertExtCount++;
  27731. return 0;
  27732. }
  27733. #endif
  27734. #endif /* WOLFSSL_CERT_EXT */
  27735. #ifdef WOLFSSL_ALT_NAMES
  27736. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  27737. {
  27738. int ret = 0;
  27739. cert->altNamesSz = 0;
  27740. if (decoded->altNames) {
  27741. ret = FlattenAltNames(cert->altNames,
  27742. sizeof(cert->altNames), decoded->altNames);
  27743. if (ret >= 0) {
  27744. cert->altNamesSz = ret;
  27745. ret = 0;
  27746. }
  27747. }
  27748. return ret;
  27749. }
  27750. #ifndef NO_FILESYSTEM
  27751. /* Set Alt Names from der cert, return 0 on success */
  27752. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  27753. int devId)
  27754. {
  27755. int ret;
  27756. #ifdef WOLFSSL_SMALL_STACK
  27757. DecodedCert* decoded;
  27758. #else
  27759. DecodedCert decoded[1];
  27760. #endif
  27761. if (derSz < 0)
  27762. return derSz;
  27763. #ifdef WOLFSSL_SMALL_STACK
  27764. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  27765. DYNAMIC_TYPE_TMP_BUFFER);
  27766. if (decoded == NULL)
  27767. return MEMORY_E;
  27768. #endif
  27769. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27770. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27771. if (ret < 0) {
  27772. WOLFSSL_MSG("ParseCertRelative error");
  27773. }
  27774. else {
  27775. ret = SetAltNamesFromDcert(cert, decoded);
  27776. }
  27777. FreeDecodedCert(decoded);
  27778. #ifdef WOLFSSL_SMALL_STACK
  27779. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27780. #endif
  27781. return ret < 0 ? ret : 0;
  27782. }
  27783. #endif
  27784. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  27785. {
  27786. int ret = 0;
  27787. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  27788. WOLFSSL_MSG("Couldn't extract dates");
  27789. ret = -1;
  27790. }
  27791. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  27792. decoded->afterDateLen > MAX_DATE_SIZE) {
  27793. WOLFSSL_MSG("Bad date size");
  27794. ret = -1;
  27795. }
  27796. else {
  27797. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  27798. (size_t)decoded->beforeDateLen);
  27799. XMEMCPY(cert->afterDate, decoded->afterDate,
  27800. (size_t)decoded->afterDateLen);
  27801. cert->beforeDateSz = decoded->beforeDateLen;
  27802. cert->afterDateSz = decoded->afterDateLen;
  27803. }
  27804. return ret;
  27805. }
  27806. #endif /* WOLFSSL_ALT_NAMES */
  27807. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  27808. {
  27809. int sz;
  27810. if (decoded->subjectCN) {
  27811. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  27812. : CTC_NAME_SIZE - 1;
  27813. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  27814. cn->commonName[sz] = '\0';
  27815. cn->commonNameEnc = decoded->subjectCNEnc;
  27816. }
  27817. if (decoded->subjectC) {
  27818. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  27819. : CTC_NAME_SIZE - 1;
  27820. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  27821. cn->country[sz] = '\0';
  27822. cn->countryEnc = decoded->subjectCEnc;
  27823. }
  27824. if (decoded->subjectST) {
  27825. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  27826. : CTC_NAME_SIZE - 1;
  27827. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  27828. cn->state[sz] = '\0';
  27829. cn->stateEnc = decoded->subjectSTEnc;
  27830. }
  27831. if (decoded->subjectL) {
  27832. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  27833. : CTC_NAME_SIZE - 1;
  27834. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  27835. cn->locality[sz] = '\0';
  27836. cn->localityEnc = decoded->subjectLEnc;
  27837. }
  27838. if (decoded->subjectO) {
  27839. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  27840. : CTC_NAME_SIZE - 1;
  27841. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  27842. cn->org[sz] = '\0';
  27843. cn->orgEnc = decoded->subjectOEnc;
  27844. }
  27845. if (decoded->subjectOU) {
  27846. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  27847. : CTC_NAME_SIZE - 1;
  27848. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  27849. cn->unit[sz] = '\0';
  27850. cn->unitEnc = decoded->subjectOUEnc;
  27851. }
  27852. if (decoded->subjectSN) {
  27853. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  27854. : CTC_NAME_SIZE - 1;
  27855. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  27856. cn->sur[sz] = '\0';
  27857. cn->surEnc = decoded->subjectSNEnc;
  27858. }
  27859. if (decoded->subjectSND) {
  27860. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  27861. : CTC_NAME_SIZE - 1;
  27862. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  27863. cn->serialDev[sz] = '\0';
  27864. cn->serialDevEnc = decoded->subjectSNDEnc;
  27865. }
  27866. if (decoded->subjectUID) {
  27867. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  27868. : CTC_NAME_SIZE - 1;
  27869. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  27870. cn->userId[sz] = '\0';
  27871. cn->userIdEnc = decoded->subjectUIDEnc;
  27872. }
  27873. #ifdef WOLFSSL_CERT_EXT
  27874. if (decoded->subjectBC) {
  27875. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  27876. : CTC_NAME_SIZE - 1;
  27877. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  27878. cn->busCat[sz] = '\0';
  27879. cn->busCatEnc = decoded->subjectBCEnc;
  27880. }
  27881. if (decoded->subjectJC) {
  27882. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  27883. : CTC_NAME_SIZE - 1;
  27884. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  27885. cn->joiC[sz] = '\0';
  27886. cn->joiCEnc = decoded->subjectJCEnc;
  27887. }
  27888. if (decoded->subjectJS) {
  27889. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  27890. : CTC_NAME_SIZE - 1;
  27891. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  27892. cn->joiSt[sz] = '\0';
  27893. cn->joiStEnc = decoded->subjectJSEnc;
  27894. }
  27895. #endif
  27896. if (decoded->subjectEmail) {
  27897. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  27898. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  27899. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  27900. cn->email[sz] = '\0';
  27901. }
  27902. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  27903. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  27904. if (decoded->subjectN) {
  27905. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  27906. : CTC_NAME_SIZE - 1;
  27907. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  27908. cn->dnName[sz] = '\0';
  27909. cn->dnNameEnc = decoded->subjectNEnc;
  27910. }
  27911. if (decoded->subjectI) {
  27912. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  27913. : CTC_NAME_SIZE - 1;
  27914. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  27915. cn->initials[sz] = '\0';
  27916. cn->initialsEnc = decoded->subjectIEnc;
  27917. }
  27918. if (decoded->subjectGN) {
  27919. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  27920. : CTC_NAME_SIZE - 1;
  27921. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  27922. cn->givenName[sz] = '\0';
  27923. cn->givenNameEnc = decoded->subjectGNEnc;
  27924. }
  27925. if (decoded->subjectDNQ) {
  27926. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  27927. : CTC_NAME_SIZE - 1;
  27928. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  27929. cn->dnQualifier[sz] = '\0';
  27930. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  27931. }
  27932. #endif /* WOLFSSL_CERT_NAME_ALL */
  27933. }
  27934. #ifndef NO_FILESYSTEM
  27935. /* Set cn name from der buffer, return 0 on success */
  27936. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  27937. {
  27938. int ret;
  27939. #ifdef WOLFSSL_SMALL_STACK
  27940. DecodedCert* decoded;
  27941. #else
  27942. DecodedCert decoded[1];
  27943. #endif
  27944. if (derSz < 0)
  27945. return derSz;
  27946. #ifdef WOLFSSL_SMALL_STACK
  27947. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  27948. DYNAMIC_TYPE_TMP_BUFFER);
  27949. if (decoded == NULL)
  27950. return MEMORY_E;
  27951. #endif
  27952. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27953. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27954. if (ret < 0) {
  27955. WOLFSSL_MSG("ParseCertRelative error");
  27956. }
  27957. else {
  27958. SetNameFromDcert(cn, decoded);
  27959. }
  27960. FreeDecodedCert(decoded);
  27961. #ifdef WOLFSSL_SMALL_STACK
  27962. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  27963. #endif
  27964. return ret < 0 ? ret : 0;
  27965. }
  27966. /* Set cert issuer from issuerFile in PEM */
  27967. WOLFSSL_ABI
  27968. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  27969. {
  27970. int ret;
  27971. DerBuffer* der = NULL;
  27972. if (cert == NULL || issuerFile == NULL)
  27973. return BAD_FUNC_ARG;
  27974. ret = wc_PemCertToDer_ex(issuerFile, &der);
  27975. if (ret == 0) {
  27976. cert->selfSigned = 0;
  27977. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  27978. INVALID_DEVID);
  27979. FreeDer(&der);
  27980. }
  27981. return ret;
  27982. }
  27983. /* Set cert subject from subjectFile in PEM */
  27984. WOLFSSL_ABI
  27985. int wc_SetSubject(Cert* cert, const char* subjectFile)
  27986. {
  27987. int ret;
  27988. DerBuffer* der = NULL;
  27989. if (cert == NULL || subjectFile == NULL)
  27990. return BAD_FUNC_ARG;
  27991. ret = wc_PemCertToDer_ex(subjectFile, &der);
  27992. if (ret == 0) {
  27993. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  27994. INVALID_DEVID);
  27995. FreeDer(&der);
  27996. }
  27997. return ret;
  27998. }
  27999. #ifdef WOLFSSL_ALT_NAMES
  28000. /* Set alt names from file in PEM */
  28001. WOLFSSL_ABI
  28002. int wc_SetAltNames(Cert* cert, const char* file)
  28003. {
  28004. int ret;
  28005. DerBuffer* der = NULL;
  28006. if (cert == NULL) {
  28007. return BAD_FUNC_ARG;
  28008. }
  28009. ret = wc_PemCertToDer_ex(file, &der);
  28010. if (ret == 0) {
  28011. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  28012. INVALID_DEVID);
  28013. FreeDer(&der);
  28014. }
  28015. return ret;
  28016. }
  28017. #endif /* WOLFSSL_ALT_NAMES */
  28018. #endif /* !NO_FILESYSTEM */
  28019. /* Set cert issuer from DER buffer */
  28020. WOLFSSL_ABI
  28021. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  28022. {
  28023. int ret = 0;
  28024. if (cert == NULL) {
  28025. ret = BAD_FUNC_ARG;
  28026. }
  28027. else {
  28028. cert->selfSigned = 0;
  28029. /* Check if decodedCert is cached */
  28030. if (cert->der != der) {
  28031. /* Allocate cache for the decoded cert */
  28032. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28033. }
  28034. if (ret >= 0) {
  28035. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  28036. #ifndef WOLFSSL_CERT_GEN_CACHE
  28037. wc_SetCert_Free(cert);
  28038. #endif
  28039. }
  28040. }
  28041. return ret;
  28042. }
  28043. /* Set cert subject from DER buffer */
  28044. WOLFSSL_ABI
  28045. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  28046. {
  28047. int ret = 0;
  28048. if (cert == NULL) {
  28049. ret = BAD_FUNC_ARG;
  28050. }
  28051. else {
  28052. /* Check if decodedCert is cached */
  28053. if (cert->der != der) {
  28054. /* Allocate cache for the decoded cert */
  28055. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28056. }
  28057. if (ret >= 0) {
  28058. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  28059. #ifndef WOLFSSL_CERT_GEN_CACHE
  28060. wc_SetCert_Free(cert);
  28061. #endif
  28062. }
  28063. }
  28064. return ret;
  28065. }
  28066. #ifdef WOLFSSL_CERT_EXT
  28067. /* Set cert raw subject from DER buffer */
  28068. WOLFSSL_ABI
  28069. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  28070. {
  28071. int ret = 0;
  28072. if (cert == NULL) {
  28073. ret = BAD_FUNC_ARG;
  28074. }
  28075. else {
  28076. /* Check if decodedCert is cached */
  28077. if (cert->der != der) {
  28078. /* Allocate cache for the decoded cert */
  28079. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28080. }
  28081. if (ret >= 0) {
  28082. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  28083. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  28084. (int)sizeof(CertName))) {
  28085. XMEMCPY(cert->sbjRaw,
  28086. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  28087. (size_t)((DecodedCert*)cert->decodedCert)->
  28088. subjectRawLen);
  28089. }
  28090. #ifndef WOLFSSL_CERT_GEN_CACHE
  28091. wc_SetCert_Free(cert);
  28092. #endif
  28093. }
  28094. }
  28095. return ret;
  28096. }
  28097. /* Set cert raw issuer from DER buffer */
  28098. WOLFSSL_ABI
  28099. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  28100. {
  28101. int ret = 0;
  28102. if (cert == NULL) {
  28103. ret = BAD_FUNC_ARG;
  28104. }
  28105. else {
  28106. /* Check if decodedCert is cached */
  28107. if (cert->der != der) {
  28108. /* Allocate cache for the decoded cert */
  28109. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28110. }
  28111. if (ret >= 0) {
  28112. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  28113. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  28114. (int)sizeof(CertName))) {
  28115. /* Copy the subject to the issuer field */
  28116. XMEMCPY(cert->issRaw,
  28117. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  28118. (size_t)((DecodedCert*)cert->decodedCert)->
  28119. subjectRawLen);
  28120. }
  28121. #ifndef WOLFSSL_CERT_GEN_CACHE
  28122. wc_SetCert_Free(cert);
  28123. #endif
  28124. }
  28125. }
  28126. return ret;
  28127. }
  28128. #endif
  28129. #ifdef WOLFSSL_ALT_NAMES
  28130. /* Set cert alt names from DER buffer */
  28131. WOLFSSL_ABI
  28132. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  28133. {
  28134. int ret = 0;
  28135. if (cert == NULL) {
  28136. ret = BAD_FUNC_ARG;
  28137. }
  28138. else {
  28139. /* Check if decodedCert is cached */
  28140. if (cert->der != der) {
  28141. /* Allocate cache for the decoded cert */
  28142. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28143. }
  28144. if (ret >= 0) {
  28145. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28146. #ifndef WOLFSSL_CERT_GEN_CACHE
  28147. wc_SetCert_Free(cert);
  28148. #endif
  28149. }
  28150. }
  28151. return(ret);
  28152. }
  28153. /* Set cert dates from DER buffer */
  28154. WOLFSSL_ABI
  28155. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  28156. {
  28157. int ret = 0;
  28158. if (cert == NULL) {
  28159. ret = BAD_FUNC_ARG;
  28160. }
  28161. else {
  28162. /* Check if decodedCert is cached */
  28163. if (cert->der != der) {
  28164. /* Allocate cache for the decoded cert */
  28165. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28166. }
  28167. if (ret >= 0) {
  28168. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28169. #ifndef WOLFSSL_CERT_GEN_CACHE
  28170. wc_SetCert_Free(cert);
  28171. #endif
  28172. }
  28173. }
  28174. return(ret);
  28175. }
  28176. #endif /* WOLFSSL_ALT_NAMES */
  28177. #endif /* WOLFSSL_CERT_GEN */
  28178. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  28179. || defined(OPENSSL_EXTRA)
  28180. /* Encode OID string representation to ITU-T X.690 format */
  28181. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  28182. {
  28183. word32 idx = 0, nb_val;
  28184. char *token, *str, *ptr;
  28185. word32 len;
  28186. (void)heap;
  28187. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  28188. return BAD_FUNC_ARG;
  28189. /* duplicate string (including terminator) */
  28190. len = (word32)XSTRLEN(in);
  28191. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28192. if (str == NULL)
  28193. return MEMORY_E;
  28194. XMEMCPY(str, in, len+1);
  28195. nb_val = 0;
  28196. /* parse value, and set corresponding Policy OID value */
  28197. token = XSTRTOK(str, ".", &ptr);
  28198. while (token != NULL)
  28199. {
  28200. word32 val = (word32)XATOI(token);
  28201. if (nb_val == 0) {
  28202. if (val > 2) {
  28203. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28204. return ASN_OBJECT_ID_E;
  28205. }
  28206. out[idx] = (byte)(40 * val);
  28207. }
  28208. else if (nb_val == 1) {
  28209. if (val > 127) {
  28210. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28211. return ASN_OBJECT_ID_E;
  28212. }
  28213. if (idx > *outSz) {
  28214. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28215. return BUFFER_E;
  28216. }
  28217. out[idx++] += (byte)val;
  28218. }
  28219. else {
  28220. word32 tb = 0;
  28221. int i = 0;
  28222. byte oid[MAX_OID_SZ];
  28223. while (val >= 128) {
  28224. word32 x = val % 128;
  28225. val /= 128;
  28226. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  28227. }
  28228. if ((idx+(word32)i) >= *outSz) {
  28229. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28230. return BUFFER_E;
  28231. }
  28232. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  28233. /* push value in the right order */
  28234. while (i >= 0)
  28235. out[idx++] = oid[i--];
  28236. }
  28237. token = XSTRTOK(NULL, ".", &ptr);
  28238. nb_val++;
  28239. }
  28240. *outSz = idx;
  28241. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28242. return 0;
  28243. }
  28244. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  28245. #endif /* !NO_CERTS */
  28246. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  28247. /* Helper function for wolfSSL_i2d_DHparams */
  28248. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  28249. {
  28250. #ifndef WOLFSSL_ASN_TEMPLATE
  28251. word32 idx = 0;
  28252. word32 total;
  28253. WOLFSSL_ENTER("StoreDHparams");
  28254. if (out == NULL) {
  28255. WOLFSSL_MSG("Null buffer error");
  28256. return BUFFER_E;
  28257. }
  28258. /* determine size */
  28259. /* integer - g */
  28260. idx = SetASNIntMP(g, -1, NULL);
  28261. /* integer - p */
  28262. idx += SetASNIntMP(p, -1, NULL);
  28263. total = idx;
  28264. /* sequence */
  28265. idx += SetSequence(idx, NULL);
  28266. /* make sure output fits in buffer */
  28267. if (idx > *outLen) {
  28268. return BUFFER_E;
  28269. }
  28270. /* write DH parameters */
  28271. /* sequence - for P and G only */
  28272. idx = SetSequence(total, out);
  28273. /* integer - p */
  28274. idx += SetASNIntMP(p, -1, out + idx);
  28275. /* integer - g */
  28276. idx += SetASNIntMP(g, -1, out + idx);
  28277. *outLen = idx;
  28278. return 0;
  28279. #else
  28280. ASNSetData dataASN[dhParamASN_Length];
  28281. int ret = 0;
  28282. int sz = 0;
  28283. WOLFSSL_ENTER("StoreDHparams");
  28284. if (out == NULL) {
  28285. ret = BUFFER_E;
  28286. }
  28287. if (ret == 0) {
  28288. XMEMSET(dataASN, 0, sizeof(dataASN));
  28289. /* Set mp_int containing p and g. */
  28290. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28291. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28292. /* privateValueLength not encoded. */
  28293. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28294. /* Calculate the size of the DH parameters. */
  28295. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28296. }
  28297. /* Check buffer is big enough for encoding. */
  28298. if ((ret == 0) && ((int)*outLen < sz)) {
  28299. ret = BUFFER_E;
  28300. }
  28301. if (ret == 0) {
  28302. /* Encode the DH parameters into buffer. */
  28303. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28304. /* Set the actual encoding size. */
  28305. *outLen = (word32)sz;
  28306. }
  28307. return ret;
  28308. #endif /* WOLFSSL_ASN_TEMPLATE */
  28309. }
  28310. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28311. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28312. #ifdef WOLFSSL_ASN_TEMPLATE
  28313. /* ASN.1 template for DSA signature.
  28314. * RFC 5912, 6 - DSA-Sig-Value
  28315. */
  28316. static const ASNItem dsaSigASN[] = {
  28317. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28318. /* r */
  28319. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28320. /* s */
  28321. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28322. };
  28323. enum {
  28324. DSASIGASN_IDX_SEQ = 0,
  28325. DSASIGASN_IDX_R,
  28326. DSASIGASN_IDX_S
  28327. };
  28328. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28329. #endif
  28330. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28331. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28332. {
  28333. #ifndef WOLFSSL_ASN_TEMPLATE
  28334. word32 idx = 0;
  28335. int rSz; /* encoding size */
  28336. int sSz;
  28337. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28338. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28339. int rLeadingZero = mp_leading_bit(r);
  28340. int sLeadingZero = mp_leading_bit(s);
  28341. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28342. int sLen = mp_unsigned_bin_size(s);
  28343. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  28344. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  28345. return BUFFER_E;
  28346. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  28347. headerSz), out);
  28348. /* store r */
  28349. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  28350. if (rSz < 0)
  28351. return rSz;
  28352. idx += (word32)rSz;
  28353. /* store s */
  28354. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  28355. if (sSz < 0)
  28356. return sSz;
  28357. idx += (word32)sSz;
  28358. *outLen = idx;
  28359. return 0;
  28360. #else
  28361. ASNSetData dataASN[dsaSigASN_Length];
  28362. int ret;
  28363. int sz;
  28364. /* Clear dynamic data and set mp_ints r and s */
  28365. XMEMSET(dataASN, 0, sizeof(dataASN));
  28366. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28367. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28368. /* Calculate size of encoding. */
  28369. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28370. /* Check buffer is big enough for encoding. */
  28371. if ((ret == 0) && ((int)*outLen < sz)) {
  28372. ret = BUFFER_E;
  28373. }
  28374. if (ret == 0) {
  28375. /* Encode DSA signature into buffer. */
  28376. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28377. /* Set the actual encoding size. */
  28378. *outLen = (word32)sz;
  28379. }
  28380. return ret;
  28381. #endif /* WOLFSSL_ASN_TEMPLATE */
  28382. }
  28383. #ifndef WOLFSSL_ASN_TEMPLATE
  28384. /* determine if leading bit is set */
  28385. static word32 is_leading_bit_set(const byte* input, word32 sz)
  28386. {
  28387. byte c = 0;
  28388. if (sz > 0)
  28389. c = input[0];
  28390. return (c & 0x80) != 0;
  28391. }
  28392. static word32 trim_leading_zeros(const byte** input, word32 sz)
  28393. {
  28394. int i;
  28395. word32 leadingZeroCount = 0;
  28396. const byte* tmp = *input;
  28397. for (i=0; i<(int)sz; i++) {
  28398. if (tmp[i] != 0)
  28399. break;
  28400. leadingZeroCount++;
  28401. }
  28402. /* catch all zero case */
  28403. if (sz > 0 && leadingZeroCount == sz) {
  28404. leadingZeroCount--;
  28405. }
  28406. *input += leadingZeroCount;
  28407. sz -= leadingZeroCount;
  28408. return sz;
  28409. }
  28410. #endif
  28411. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28412. /* All input/outputs are assumed to be big-endian */
  28413. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28414. const byte* s, word32 sLen)
  28415. {
  28416. #ifndef WOLFSSL_ASN_TEMPLATE
  28417. int ret;
  28418. word32 idx;
  28419. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28420. word32 rAddLeadZero, sAddLeadZero;
  28421. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28422. return BAD_FUNC_ARG;
  28423. /* Trim leading zeros */
  28424. rLen = trim_leading_zeros(&r, rLen);
  28425. sLen = trim_leading_zeros(&s, sLen);
  28426. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28427. /* Add leading zero if MSB is set */
  28428. rAddLeadZero = is_leading_bit_set(r, rLen);
  28429. sAddLeadZero = is_leading_bit_set(s, sLen);
  28430. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28431. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28432. return BUFFER_E;
  28433. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28434. /* store r */
  28435. ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28436. if (ret < 0)
  28437. return ret;
  28438. idx += (word32)ret;
  28439. XMEMCPY(&out[idx], r, rLen);
  28440. idx += rLen;
  28441. /* store s */
  28442. ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28443. if (ret < 0)
  28444. return ret;
  28445. idx += (word32)ret;
  28446. XMEMCPY(&out[idx], s, sLen);
  28447. idx += sLen;
  28448. *outLen = idx;
  28449. return 0;
  28450. #else
  28451. ASNSetData dataASN[dsaSigASN_Length];
  28452. int ret;
  28453. int sz;
  28454. /* Clear dynamic data and set buffers for r and s */
  28455. XMEMSET(dataASN, 0, sizeof(dataASN));
  28456. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28457. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28458. /* Calculate size of encoding. */
  28459. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28460. /* Check buffer is big enough for encoding. */
  28461. if ((ret == 0) && ((int)*outLen < sz)) {
  28462. ret = BUFFER_E;
  28463. }
  28464. if (ret == 0) {
  28465. /* Encode DSA signature into buffer. */
  28466. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28467. /* Set the actual encoding size. */
  28468. *outLen = (word32)sz;
  28469. }
  28470. return ret;
  28471. #endif /* WOLFSSL_ASN_TEMPLATE */
  28472. }
  28473. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28474. /* All input/outputs are assumed to be big-endian */
  28475. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28476. byte* s, word32* sLen)
  28477. {
  28478. #ifndef WOLFSSL_ASN_TEMPLATE
  28479. int ret;
  28480. word32 idx = 0;
  28481. int len = 0;
  28482. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28483. return ASN_ECC_KEY_E;
  28484. }
  28485. #ifndef NO_STRICT_ECDSA_LEN
  28486. /* enable strict length checking for signature */
  28487. if (sigLen != idx + (word32)len) {
  28488. return ASN_ECC_KEY_E;
  28489. }
  28490. #else
  28491. /* allow extra signature bytes at end */
  28492. if ((word32)len > (sigLen - idx)) {
  28493. return ASN_ECC_KEY_E;
  28494. }
  28495. #endif
  28496. ret = GetASNInt(sig, &idx, &len, sigLen);
  28497. if (ret != 0)
  28498. return ret;
  28499. if (rLen)
  28500. *rLen = (word32)len;
  28501. if (r)
  28502. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  28503. idx += (word32)len;
  28504. ret = GetASNInt(sig, &idx, &len, sigLen);
  28505. if (ret != 0)
  28506. return ret;
  28507. if (sLen)
  28508. *sLen = (word32)len;
  28509. if (s)
  28510. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  28511. #ifndef NO_STRICT_ECDSA_LEN
  28512. /* sanity check that the index has been advanced all the way to the end of
  28513. * the buffer */
  28514. if (idx + (word32)len != sigLen) {
  28515. ret = ASN_ECC_KEY_E;
  28516. }
  28517. #endif
  28518. return ret;
  28519. #else
  28520. ASNGetData dataASN[dsaSigASN_Length];
  28521. word32 idx = 0;
  28522. /* Clear dynamic data and set buffers to put r and s into. */
  28523. XMEMSET(dataASN, 0, sizeof(dataASN));
  28524. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28525. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28526. /* Decode the DSA signature. */
  28527. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28528. sigLen);
  28529. #endif /* WOLFSSL_ASN_TEMPLATE */
  28530. }
  28531. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28532. {
  28533. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  28534. }
  28535. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  28536. int init)
  28537. {
  28538. #ifndef WOLFSSL_ASN_TEMPLATE
  28539. word32 idx = 0;
  28540. int len = 0;
  28541. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28542. return ASN_ECC_KEY_E;
  28543. }
  28544. #ifndef NO_STRICT_ECDSA_LEN
  28545. /* enable strict length checking for signature */
  28546. if (sigLen != idx + (word32)len) {
  28547. return ASN_ECC_KEY_E;
  28548. }
  28549. #else
  28550. /* allow extra signature bytes at end */
  28551. if ((word32)len > (sigLen - idx)) {
  28552. return ASN_ECC_KEY_E;
  28553. }
  28554. #endif
  28555. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  28556. return ASN_ECC_KEY_E;
  28557. }
  28558. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  28559. mp_clear(r);
  28560. return ASN_ECC_KEY_E;
  28561. }
  28562. #ifndef NO_STRICT_ECDSA_LEN
  28563. /* sanity check that the index has been advanced all the way to the end of
  28564. * the buffer */
  28565. if (idx != sigLen) {
  28566. mp_clear(r);
  28567. mp_clear(s);
  28568. return ASN_ECC_KEY_E;
  28569. }
  28570. #endif
  28571. return 0;
  28572. #else
  28573. ASNGetData dataASN[dsaSigASN_Length];
  28574. word32 idx = 0;
  28575. int ret;
  28576. /* Clear dynamic data and set mp_ints to put r and s into. */
  28577. XMEMSET(dataASN, 0, sizeof(dataASN));
  28578. if (init) {
  28579. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28580. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28581. }
  28582. else {
  28583. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  28584. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  28585. }
  28586. /* Decode the DSA signature. */
  28587. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  28588. sigLen);
  28589. #ifndef NO_STRICT_ECDSA_LEN
  28590. /* sanity check that the index has been advanced all the way to the end of
  28591. * the buffer */
  28592. if ((ret == 0) && (idx != sigLen)) {
  28593. ret = ASN_ECC_KEY_E;
  28594. }
  28595. #endif
  28596. if (ret != 0) {
  28597. mp_clear(r);
  28598. mp_clear(s);
  28599. }
  28600. return ret;
  28601. #endif /* WOLFSSL_ASN_TEMPLATE */
  28602. }
  28603. #endif
  28604. #ifdef WOLFSSL_ASN_TEMPLATE
  28605. #ifdef WOLFSSL_CUSTOM_CURVES
  28606. /* Convert data to hex string.
  28607. *
  28608. * Big-endian byte array is converted to big-endian hexadecimal string.
  28609. *
  28610. * @param [in] input Buffer containing data.
  28611. * @param [in] inSz Size of data in buffer.
  28612. * @param [out] out Buffer to hold hex string.
  28613. */
  28614. static void DataToHexString(const byte* input, word32 inSz, char* out)
  28615. {
  28616. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  28617. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  28618. word32 i;
  28619. /* Converting a byte of data at a time to two hex characters. */
  28620. for (i = 0; i < inSz; i++) {
  28621. out[i*2 + 0] = hexChar[input[i] >> 4];
  28622. out[i*2 + 1] = hexChar[input[i] & 0xf];
  28623. }
  28624. /* NUL terminate string. */
  28625. out[i * 2] = '\0';
  28626. }
  28627. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28628. /* Convert data to hex string and place in allocated buffer.
  28629. *
  28630. * Big-endian byte array is converted to big-endian hexadecimal string.
  28631. *
  28632. * @param [in] input Buffer containing data.
  28633. * @param [in] inSz Size of data in buffer.
  28634. * @param [out] out Allocated buffer holding hex string.
  28635. * @param [in] heap Dynamic memory allocation hint.
  28636. * @param [in] heapType Type of heap to use.
  28637. * @return 0 on succcess.
  28638. * @return MEMORY_E when dynamic memory allocation fails.
  28639. */
  28640. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  28641. void* heap, int heapType)
  28642. {
  28643. int ret = 0;
  28644. char* str;
  28645. /* Allocate for 2 string characters ber byte plus NUL. */
  28646. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  28647. if (str == NULL) {
  28648. ret = MEMORY_E;
  28649. }
  28650. else {
  28651. /* Convert to hex string. */
  28652. DataToHexString(input, inSz, str);
  28653. *out = str;
  28654. }
  28655. (void)heap;
  28656. (void)heapType;
  28657. return ret;
  28658. }
  28659. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28660. /* ASN.1 template for SpecifiedECDomain.
  28661. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  28662. * NOTE: characteristic-two-field not supported. */
  28663. static const ASNItem eccSpecifiedASN[] = {
  28664. /* version */
  28665. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28666. /* fieldID */
  28667. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28668. /* prime-field or characteristic-two-field */
  28669. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  28670. /* Prime-p */
  28671. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  28672. /* fieldID */
  28673. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28674. /* a */
  28675. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28676. /* b */
  28677. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28678. /* seed */
  28679. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  28680. /* base */
  28681. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  28682. /* order */
  28683. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28684. /* cofactor */
  28685. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  28686. /* hash */
  28687. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  28688. };
  28689. enum {
  28690. ECCSPECIFIEDASN_IDX_VER = 0,
  28691. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  28692. ECCSPECIFIEDASN_IDX_PRIME_OID,
  28693. ECCSPECIFIEDASN_IDX_PRIME_P,
  28694. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  28695. ECCSPECIFIEDASN_IDX_PARAM_A,
  28696. ECCSPECIFIEDASN_IDX_PARAM_B,
  28697. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  28698. ECCSPECIFIEDASN_IDX_BASE,
  28699. ECCSPECIFIEDASN_IDX_ORDER,
  28700. ECCSPECIFIEDASN_IDX_COFACTOR,
  28701. ECCSPECIFIEDASN_IDX_HASH_SEQ
  28702. };
  28703. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  28704. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  28705. /* OID indicating the prime field is explicity defined. */
  28706. static const byte primeFieldOID[] = {
  28707. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  28708. };
  28709. static const char ecSetCustomName[] = "Custom";
  28710. /* Explicit EC parameter values. */
  28711. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  28712. ecc_key* key)
  28713. {
  28714. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  28715. int ret = 0;
  28716. ecc_set_type* curve;
  28717. word32 idx = 0;
  28718. byte version;
  28719. byte cofactor;
  28720. const byte *base;
  28721. word32 baseLen;
  28722. /* Allocate a new parameter set. */
  28723. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28724. DYNAMIC_TYPE_ECC_BUFFER);
  28725. if (curve == NULL) {
  28726. ret = MEMORY_E;
  28727. }
  28728. else {
  28729. /* Clear out parameters and set fields to indicate it is custom. */
  28730. XMEMSET(curve, 0, sizeof(*curve));
  28731. }
  28732. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  28733. if (ret == 0) {
  28734. /* Set name to be: "Custom" */
  28735. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28736. curve->name = ecSetCustomName;
  28737. #else
  28738. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  28739. #endif
  28740. curve->id = ECC_CURVE_CUSTOM;
  28741. /* Get version, must have prime field OID and get co-factor. */
  28742. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  28743. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  28744. primeFieldOID, sizeof(primeFieldOID));
  28745. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  28746. /* Decode the explicit parameters. */
  28747. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  28748. input, &idx, inSz);
  28749. }
  28750. /* Version must be 1 or 2 for supporting explicit parameters. */
  28751. if ((ret == 0) && (version < 1 || version > 3)) {
  28752. ret = ASN_PARSE_E;
  28753. }
  28754. #ifndef WOLFSSL_NO_ASN_STRICT
  28755. /* Only version 2 and above can have a seed. */
  28756. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  28757. (version < 2)) {
  28758. ret = ASN_PARSE_E;
  28759. }
  28760. #endif
  28761. /* Only version 2 and above can have a hash algorithm. */
  28762. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  28763. (version < 2)) {
  28764. ret = ASN_PARSE_E;
  28765. }
  28766. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  28767. /* Store optional co-factor. */
  28768. curve->cofactor = cofactor;
  28769. }
  28770. if (ret == 0) {
  28771. /* Length of the prime in bytes is the curve size. */
  28772. curve->size =
  28773. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  28774. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  28775. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  28776. &baseLen);
  28777. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  28778. ret = ASN_PARSE_E;
  28779. }
  28780. }
  28781. /* Put the curve parameters into the set.
  28782. * Convert the big-endian number byte array to a big-endian string.
  28783. */
  28784. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28785. /* Allocate buffer to put hex strings into. */
  28786. if (ret == 0) {
  28787. /* Base X-ordinate */
  28788. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  28789. (char**)&curve->Gx, key->heap,
  28790. DYNAMIC_TYPE_ECC_BUFFER);
  28791. }
  28792. if (ret == 0) {
  28793. /* Base Y-ordinate */
  28794. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  28795. (char**)&curve->Gy, key->heap,
  28796. DYNAMIC_TYPE_ECC_BUFFER);
  28797. }
  28798. if (ret == 0) {
  28799. /* Prime */
  28800. ret = DataToHexStringAlloc(
  28801. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28802. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28803. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28804. }
  28805. if (ret == 0) {
  28806. /* Parameter A */
  28807. ret = DataToHexStringAlloc(
  28808. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28809. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28810. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28811. }
  28812. if (ret == 0) {
  28813. /* Parameter B */
  28814. ret = DataToHexStringAlloc(
  28815. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28816. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28817. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28818. }
  28819. if (ret == 0) {
  28820. /* Order of curve */
  28821. ret = DataToHexStringAlloc(
  28822. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28823. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28824. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28825. }
  28826. #else
  28827. if (ret == 0) {
  28828. /* Base X-ordinate */
  28829. DataToHexString(base + 1, curve->size, curve->Gx);
  28830. /* Base Y-ordinate */
  28831. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  28832. /* Prime */
  28833. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28834. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28835. curve->prime);
  28836. /* Parameter A */
  28837. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28838. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28839. curve->Af);
  28840. /* Parameter B */
  28841. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28842. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28843. curve->Bf);
  28844. /* Order of curve */
  28845. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28846. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28847. curve->order);
  28848. }
  28849. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28850. /* Store parameter set in key. */
  28851. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  28852. ret = ASN_PARSE_E;
  28853. }
  28854. if (ret == 0) {
  28855. /* The parameter set was allocated.. */
  28856. key->deallocSet = 1;
  28857. }
  28858. if ((ret != 0) && (curve != NULL)) {
  28859. /* Failed to set parameters so free paramter set. */
  28860. wc_ecc_free_curve(curve, key->heap);
  28861. }
  28862. FREE_ASNGETDATA(dataASN, key->heap);
  28863. return ret;
  28864. }
  28865. #endif /* WOLFSSL_CUSTOM_CURVES */
  28866. #endif /* WOLFSSL_ASN_TEMPLATE */
  28867. #ifdef HAVE_ECC
  28868. #ifdef WOLFSSL_ASN_TEMPLATE
  28869. /* ASN.1 template for ECC private key.
  28870. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  28871. */
  28872. static const ASNItem eccKeyASN[] = {
  28873. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28874. /* version */
  28875. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  28876. /* privateKey */
  28877. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28878. /* parameters */
  28879. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  28880. /* named */
  28881. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  28882. /* specified */
  28883. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  28884. /* publicKey */
  28885. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  28886. /* Uncompressed point - X9.62. */
  28887. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  28888. };
  28889. enum {
  28890. ECCKEYASN_IDX_SEQ = 0,
  28891. ECCKEYASN_IDX_VER,
  28892. ECCKEYASN_IDX_PKEY,
  28893. ECCKEYASN_IDX_PARAMS,
  28894. ECCKEYASN_IDX_CURVEID,
  28895. ECCKEYASN_IDX_CURVEPARAMS,
  28896. ECCKEYASN_IDX_PUBKEY,
  28897. ECCKEYASN_IDX_PUBKEY_VAL
  28898. };
  28899. /* Number of items in ASN.1 template for ECC private key. */
  28900. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  28901. #endif
  28902. WOLFSSL_ABI
  28903. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  28904. word32 inSz)
  28905. {
  28906. #ifndef WOLFSSL_ASN_TEMPLATE
  28907. word32 oidSum;
  28908. int version, length;
  28909. int privSz, pubSz = 0;
  28910. byte b;
  28911. int ret = 0;
  28912. int curve_id = ECC_CURVE_DEF;
  28913. #ifdef WOLFSSL_SMALL_STACK
  28914. byte* priv;
  28915. byte* pub = NULL;
  28916. #else
  28917. byte priv[ECC_MAXSIZE+1];
  28918. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  28919. #endif
  28920. word32 algId = 0;
  28921. byte* pubData = NULL;
  28922. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28923. return BAD_FUNC_ARG;
  28924. /* if has pkcs8 header skip it */
  28925. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28926. /* ignore error, did not have pkcs8 header */
  28927. }
  28928. else {
  28929. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  28930. }
  28931. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28932. return ASN_PARSE_E;
  28933. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  28934. return ASN_PARSE_E;
  28935. if (*inOutIdx >= inSz)
  28936. return ASN_PARSE_E;
  28937. b = input[*inOutIdx];
  28938. *inOutIdx += 1;
  28939. /* priv type */
  28940. if (b != 4 && b != 6 && b != 7)
  28941. return ASN_PARSE_E;
  28942. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28943. return ASN_PARSE_E;
  28944. privSz = length;
  28945. if (privSz > ECC_MAXSIZE)
  28946. return BUFFER_E;
  28947. #ifdef WOLFSSL_SMALL_STACK
  28948. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28949. if (priv == NULL)
  28950. return MEMORY_E;
  28951. #endif
  28952. /* priv key */
  28953. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  28954. *inOutIdx += (word32)length;
  28955. if ((*inOutIdx + 1) < inSz) {
  28956. /* prefix 0, may have */
  28957. b = input[*inOutIdx];
  28958. if (b == ECC_PREFIX_0) {
  28959. *inOutIdx += 1;
  28960. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28961. ret = ASN_PARSE_E;
  28962. else {
  28963. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  28964. inSz);
  28965. if (ret == 0) {
  28966. if ((ret = CheckCurve(oidSum)) < 0)
  28967. ret = ECC_CURVE_OID_E;
  28968. else {
  28969. curve_id = ret;
  28970. ret = 0;
  28971. }
  28972. }
  28973. }
  28974. }
  28975. }
  28976. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  28977. /* prefix 1 */
  28978. b = input[*inOutIdx];
  28979. *inOutIdx += 1;
  28980. if (b != ECC_PREFIX_1) {
  28981. ret = ASN_ECC_KEY_E;
  28982. }
  28983. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  28984. ret = ASN_PARSE_E;
  28985. }
  28986. else {
  28987. /* key header */
  28988. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  28989. if (ret == 0) {
  28990. /* pub key */
  28991. pubSz = length;
  28992. if (pubSz > 2*(ECC_MAXSIZE+1))
  28993. ret = BUFFER_E;
  28994. else {
  28995. #ifdef WOLFSSL_SMALL_STACK
  28996. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28997. if (pub == NULL)
  28998. ret = MEMORY_E;
  28999. else
  29000. #endif
  29001. {
  29002. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  29003. *inOutIdx += (word32)length;
  29004. pubData = pub;
  29005. }
  29006. }
  29007. }
  29008. }
  29009. }
  29010. if (ret == 0) {
  29011. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  29012. (word32)pubSz, key, curve_id);
  29013. }
  29014. #ifdef WOLFSSL_SMALL_STACK
  29015. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29016. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29017. #endif
  29018. return ret;
  29019. #else
  29020. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29021. byte version;
  29022. int ret = 0;
  29023. int curve_id = ECC_CURVE_DEF;
  29024. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  29025. word32 algId = 0;
  29026. #endif
  29027. /* Validate parameters. */
  29028. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29029. ret = BAD_FUNC_ARG;
  29030. }
  29031. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  29032. /* if has pkcs8 header skip it */
  29033. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  29034. /* ignore error, did not have pkcs8 header */
  29035. }
  29036. else {
  29037. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  29038. }
  29039. #endif
  29040. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29041. if (ret == 0) {
  29042. /* Get the version and set the expected OID type. */
  29043. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  29044. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  29045. /* Decode the private ECC key. */
  29046. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29047. inOutIdx, inSz);
  29048. }
  29049. /* Only version 1 supported. */
  29050. if ((ret == 0) && (version != 1)) {
  29051. ret = ASN_PARSE_E;
  29052. }
  29053. /* Curve Parameters are optional. */
  29054. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  29055. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  29056. /* Named curve - check and get id. */
  29057. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  29058. if (curve_id < 0) {
  29059. ret = ECC_CURVE_OID_E;
  29060. }
  29061. }
  29062. else {
  29063. #ifdef WOLFSSL_CUSTOM_CURVES
  29064. /* Parse explicit parameters. */
  29065. ret = EccSpecifiedECDomainDecode(
  29066. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  29067. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  29068. #else
  29069. /* Explicit parameters not supported in build configuration. */
  29070. ret = ASN_PARSE_E;
  29071. #endif
  29072. }
  29073. }
  29074. if (ret == 0) {
  29075. /* Import private key value and public point (may be NULL). */
  29076. ret = wc_ecc_import_private_key_ex(
  29077. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  29078. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  29079. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  29080. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  29081. key, curve_id);
  29082. }
  29083. FREE_ASNGETDATA(dataASN, key->heap);
  29084. return ret;
  29085. #endif
  29086. }
  29087. #ifdef WOLFSSL_CUSTOM_CURVES
  29088. #ifndef WOLFSSL_ASN_TEMPLATE
  29089. /* returns 0 on success */
  29090. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  29091. word32 inSz, void* heap, int heapType)
  29092. {
  29093. int len;
  29094. int i;
  29095. char* str;
  29096. word32 localIdx;
  29097. byte tag;
  29098. if (*inOutIdx >= inSz) {
  29099. return BUFFER_E;
  29100. }
  29101. localIdx = *inOutIdx;
  29102. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  29103. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  29104. return ASN_PARSE_E;
  29105. }
  29106. else {
  29107. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  29108. return ASN_PARSE_E;
  29109. }
  29110. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  29111. if (str == NULL) {
  29112. return MEMORY_E;
  29113. }
  29114. for (i=0; i<len; i++)
  29115. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  29116. str[len*2] = '\0';
  29117. *inOutIdx += (word32)len;
  29118. *out = str;
  29119. (void)heap;
  29120. (void)heapType;
  29121. return 0;
  29122. }
  29123. static int EccKeyParamCopy(char** dst, char* src)
  29124. {
  29125. int ret = 0;
  29126. #ifdef WOLFSSL_ECC_CURVE_STATIC
  29127. word32 length;
  29128. #endif
  29129. if (dst == NULL || src == NULL)
  29130. return BAD_FUNC_ARG;
  29131. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29132. *dst = src;
  29133. #else
  29134. length = (int)XSTRLEN(src) + 1;
  29135. if (length > MAX_ECC_STRING) {
  29136. WOLFSSL_MSG("ECC Param too large for buffer");
  29137. ret = BUFFER_E;
  29138. }
  29139. else {
  29140. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  29141. }
  29142. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29143. #endif
  29144. return ret;
  29145. }
  29146. #endif /* !WOLFSSL_ASN_TEMPLATE */
  29147. #endif /* WOLFSSL_CUSTOM_CURVES */
  29148. WOLFSSL_ABI
  29149. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  29150. ecc_key* key, word32 inSz)
  29151. {
  29152. #ifndef WOLFSSL_ASN_TEMPLATE
  29153. int ret;
  29154. int version, length;
  29155. int curve_id = ECC_CURVE_DEF;
  29156. word32 oidSum, localIdx;
  29157. byte tag, isPrivFormat = 0;
  29158. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  29159. return BAD_FUNC_ARG;
  29160. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29161. return ASN_PARSE_E;
  29162. /* Check if ECC private key is being used and skip private portion */
  29163. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  29164. isPrivFormat = 1;
  29165. /* Type private key */
  29166. if (*inOutIdx >= inSz)
  29167. return ASN_PARSE_E;
  29168. tag = input[*inOutIdx];
  29169. *inOutIdx += 1;
  29170. if (tag != 4 && tag != 6 && tag != 7)
  29171. return ASN_PARSE_E;
  29172. /* Skip Private Key */
  29173. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  29174. return ASN_PARSE_E;
  29175. if (length > ECC_MAXSIZE)
  29176. return BUFFER_E;
  29177. *inOutIdx += (word32)length;
  29178. /* Private Curve Header */
  29179. if (*inOutIdx >= inSz)
  29180. return ASN_PARSE_E;
  29181. tag = input[*inOutIdx];
  29182. *inOutIdx += 1;
  29183. if (tag != ECC_PREFIX_0)
  29184. return ASN_ECC_KEY_E;
  29185. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29186. return ASN_PARSE_E;
  29187. }
  29188. /* Standard ECC public key */
  29189. else {
  29190. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29191. return ASN_PARSE_E;
  29192. ret = SkipObjectId(input, inOutIdx, inSz);
  29193. if (ret != 0)
  29194. return ret;
  29195. }
  29196. if (*inOutIdx >= inSz) {
  29197. return BUFFER_E;
  29198. }
  29199. localIdx = *inOutIdx;
  29200. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  29201. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  29202. #ifdef WOLFSSL_CUSTOM_CURVES
  29203. ecc_set_type* curve;
  29204. int len;
  29205. char* point = NULL;
  29206. ret = 0;
  29207. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  29208. DYNAMIC_TYPE_ECC_BUFFER);
  29209. if (curve == NULL)
  29210. ret = MEMORY_E;
  29211. if (ret == 0) {
  29212. static const char customName[] = "Custom";
  29213. XMEMSET(curve, 0, sizeof(*curve));
  29214. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29215. curve->name = customName;
  29216. #else
  29217. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  29218. #endif
  29219. curve->id = ECC_CURVE_CUSTOM;
  29220. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29221. ret = ASN_PARSE_E;
  29222. }
  29223. if (ret == 0) {
  29224. GetInteger7Bit(input, inOutIdx, inSz);
  29225. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29226. ret = ASN_PARSE_E;
  29227. }
  29228. if (ret == 0) {
  29229. char* p = NULL;
  29230. SkipObjectId(input, inOutIdx, inSz);
  29231. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  29232. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29233. if (ret == 0) {
  29234. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29235. ret = EccKeyParamCopy((char**)&curve->prime, p);
  29236. #else
  29237. const char *_tmp_ptr = &curve->prime[0];
  29238. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  29239. #endif
  29240. }
  29241. }
  29242. if (ret == 0) {
  29243. curve->size = (int)XSTRLEN(curve->prime) / 2;
  29244. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29245. ret = ASN_PARSE_E;
  29246. }
  29247. if (ret == 0) {
  29248. char* af = NULL;
  29249. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  29250. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29251. if (ret == 0) {
  29252. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29253. ret = EccKeyParamCopy((char**)&curve->Af, af);
  29254. #else
  29255. const char *_tmp_ptr = &curve->Af[0];
  29256. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  29257. #endif
  29258. }
  29259. }
  29260. if (ret == 0) {
  29261. char* bf = NULL;
  29262. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  29263. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29264. if (ret == 0) {
  29265. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29266. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29267. #else
  29268. const char *_tmp_ptr = &curve->Bf[0];
  29269. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29270. #endif
  29271. }
  29272. }
  29273. if (ret == 0) {
  29274. localIdx = *inOutIdx;
  29275. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29276. == 0 && tag == ASN_BIT_STRING) {
  29277. len = 0;
  29278. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29279. if (ret > 0)
  29280. ret = 0; /* reset on success */
  29281. *inOutIdx += (word32)len;
  29282. }
  29283. }
  29284. if (ret == 0) {
  29285. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29286. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29287. /* sanity check that point buffer is not smaller than the expected
  29288. * size to hold ( 0 4 || Gx || Gy )
  29289. * where Gx and Gy are each the size of curve->size * 2 */
  29290. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29291. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29292. ret = BUFFER_E;
  29293. }
  29294. }
  29295. if (ret == 0) {
  29296. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29297. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29298. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29299. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29300. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29301. if (curve->Gx == NULL || curve->Gy == NULL) {
  29302. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29303. ret = MEMORY_E;
  29304. }
  29305. #else
  29306. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29307. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29308. ret = BUFFER_E;
  29309. }
  29310. #endif
  29311. }
  29312. if (ret == 0) {
  29313. char* o = NULL;
  29314. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  29315. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29316. (size_t)curve->size * 2);
  29317. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29318. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29319. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29320. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29321. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29322. if (ret == 0) {
  29323. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29324. ret = EccKeyParamCopy((char**)&curve->order, o);
  29325. #else
  29326. const char *_tmp_ptr = &curve->order[0];
  29327. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29328. #endif
  29329. }
  29330. }
  29331. if (ret == 0) {
  29332. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29333. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29334. curve->oid = NULL;
  29335. #else
  29336. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29337. #endif
  29338. curve->oidSz = 0;
  29339. curve->oidSum = 0;
  29340. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29341. ret = ASN_PARSE_E;
  29342. }
  29343. key->deallocSet = 1;
  29344. curve = NULL;
  29345. }
  29346. if (curve != NULL)
  29347. wc_ecc_free_curve(curve, key->heap);
  29348. if (ret < 0)
  29349. return ret;
  29350. #else
  29351. return ASN_PARSE_E;
  29352. #endif /* WOLFSSL_CUSTOM_CURVES */
  29353. }
  29354. else {
  29355. /* ecc params information */
  29356. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29357. if (ret != 0)
  29358. return ret;
  29359. /* get curve id */
  29360. if ((ret = CheckCurve(oidSum)) < 0)
  29361. return ECC_CURVE_OID_E;
  29362. else {
  29363. curve_id = ret;
  29364. }
  29365. }
  29366. if (isPrivFormat) {
  29367. /* Public Curve Header - skip */
  29368. if (*inOutIdx >= inSz)
  29369. return ASN_PARSE_E;
  29370. tag = input[*inOutIdx];
  29371. *inOutIdx += 1;
  29372. if (tag != ECC_PREFIX_1)
  29373. return ASN_ECC_KEY_E;
  29374. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29375. return ASN_PARSE_E;
  29376. }
  29377. /* key header */
  29378. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29379. if (ret != 0)
  29380. return ret;
  29381. /* This is the raw point data compressed or uncompressed. */
  29382. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  29383. curve_id) != 0) {
  29384. return ASN_ECC_KEY_E;
  29385. }
  29386. *inOutIdx += (word32)length;
  29387. return 0;
  29388. #else
  29389. /* eccKeyASN is longer than eccPublicKeyASN. */
  29390. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29391. int ret = 0;
  29392. int curve_id = ECC_CURVE_DEF;
  29393. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29394. #ifdef WOLFSSL_CUSTOM_CURVES
  29395. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29396. #endif
  29397. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29398. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29399. ret = BAD_FUNC_ARG;
  29400. }
  29401. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29402. if (ret == 0) {
  29403. /* Clear dynamic data for ECC public key. */
  29404. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29405. #if !defined(WOLFSSL_SM2) || !defined(WOLFSSL_SM3)
  29406. /* Set required ECDSA OID and ignore the curve OID type. */
  29407. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29408. sizeof(keyEcdsaOid));
  29409. #else
  29410. GetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  29411. #endif
  29412. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  29413. /* Decode the public ECC key. */
  29414. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29415. input, inOutIdx, inSz);
  29416. if (ret != 0) {
  29417. oidIdx = ECCKEYASN_IDX_CURVEID;
  29418. #ifdef WOLFSSL_CUSTOM_CURVES
  29419. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29420. #endif
  29421. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29422. /* Clear dynamic data for ECC private key. */
  29423. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29424. /* Check named curve OID type. */
  29425. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  29426. /* Try private key format .*/
  29427. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29428. inOutIdx, inSz);
  29429. if (ret != 0) {
  29430. ret = ASN_PARSE_E;
  29431. }
  29432. }
  29433. }
  29434. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  29435. if ((ret == 0) && (oidIdx == ECCPUBLICKEYASN_IDX_ALGOID_CURVEID)) {
  29436. int oidSum = dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  29437. if ((oidSum != ECDSAk) && (oidSum != SM2k)) {
  29438. ret = ASN_PARSE_E;
  29439. }
  29440. }
  29441. #endif
  29442. if (ret == 0) {
  29443. if (dataASN[oidIdx].tag != 0) {
  29444. /* Named curve - check and get id. */
  29445. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29446. if (curve_id < 0) {
  29447. ret = ASN_OBJECT_ID_E;
  29448. }
  29449. }
  29450. else {
  29451. #ifdef WOLFSSL_CUSTOM_CURVES
  29452. /* Parse explicit parameters. */
  29453. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29454. dataASN[specIdx].data.ref.length, key);
  29455. #else
  29456. /* Explicit parameters not supported in build configuration. */
  29457. ret = ASN_PARSE_E;
  29458. #endif
  29459. }
  29460. }
  29461. if (ret == 0) {
  29462. /* Import public point. */
  29463. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29464. dataASN[pubIdx].data.ref.length, key, curve_id);
  29465. if (ret != 0) {
  29466. ret = ASN_ECC_KEY_E;
  29467. }
  29468. }
  29469. FREE_ASNGETDATA(dataASN, key->heap);
  29470. return ret;
  29471. #endif /* WOLFSSL_ASN_TEMPLATE */
  29472. }
  29473. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29474. /* build DER formatted ECC key, include optional public key if requested,
  29475. * return length on success, negative on error */
  29476. int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29477. int pubIn, int curveIn)
  29478. {
  29479. #ifndef WOLFSSL_ASN_TEMPLATE
  29480. byte curve[MAX_ALGO_SZ+2];
  29481. byte ver[MAX_VERSION_SZ];
  29482. byte seq[MAX_SEQ_SZ];
  29483. int ret, curveSz, verSz;
  29484. word32 totalSz;
  29485. int privHdrSz = ASN_ECC_HEADER_SZ;
  29486. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29487. #ifdef WOLFSSL_NO_MALLOC
  29488. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29489. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29490. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29491. #else
  29492. byte *prv = NULL, *pub = NULL;
  29493. #endif
  29494. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29495. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29496. if (key == NULL || (output == NULL && inLen == NULL))
  29497. return BAD_FUNC_ARG;
  29498. if (curveIn) {
  29499. /* curve */
  29500. curve[curveidx++] = ECC_PREFIX_0;
  29501. curveidx++ /* to put the size after computation */;
  29502. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29503. if (curveSz < 0)
  29504. return curveSz;
  29505. /* set computed size */
  29506. curve[1] = (byte)curveSz;
  29507. curveidx += (word32)curveSz;
  29508. }
  29509. /* private */
  29510. privSz = (word32)key->dp->size;
  29511. #ifdef WOLFSSL_QNX_CAAM
  29512. /* check if is a black key, and add MAC size if needed */
  29513. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29514. privSz = privSz + WC_CAAM_MAC_SZ;
  29515. }
  29516. #endif
  29517. #ifndef WOLFSSL_NO_MALLOC
  29518. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  29519. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29520. if (prv == NULL) {
  29521. return MEMORY_E;
  29522. }
  29523. #else
  29524. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29525. return BUFFER_E;
  29526. }
  29527. #endif
  29528. if (privSz < ASN_LONG_LENGTH) {
  29529. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29530. }
  29531. else {
  29532. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29533. }
  29534. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29535. if (ret < 0) {
  29536. #ifndef WOLFSSL_NO_MALLOC
  29537. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29538. #endif
  29539. return ret;
  29540. }
  29541. prvidx += privSz;
  29542. /* pubIn */
  29543. if (pubIn) {
  29544. PRIVATE_KEY_UNLOCK();
  29545. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29546. PRIVATE_KEY_LOCK();
  29547. if (ret != LENGTH_ONLY_E) {
  29548. #ifndef WOLFSSL_NO_MALLOC
  29549. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29550. #endif
  29551. return ret;
  29552. }
  29553. #ifndef WOLFSSL_NO_MALLOC
  29554. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  29555. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29556. if (pub == NULL) {
  29557. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29558. return MEMORY_E;
  29559. }
  29560. #else
  29561. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29562. return BUFFER_E;
  29563. }
  29564. #endif
  29565. pub[pubidx++] = ECC_PREFIX_1;
  29566. if (pubSz > 128) /* leading zero + extra size byte */
  29567. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29568. else /* leading zero */
  29569. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29570. /* SetBitString adds leading zero */
  29571. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29572. PRIVATE_KEY_UNLOCK();
  29573. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29574. PRIVATE_KEY_LOCK();
  29575. if (ret != 0) {
  29576. #ifndef WOLFSSL_NO_MALLOC
  29577. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29578. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29579. #endif
  29580. return ret;
  29581. }
  29582. pubidx += pubSz;
  29583. }
  29584. /* make headers */
  29585. verSz = SetMyVersion(1, ver, FALSE);
  29586. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  29587. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  29588. if (output == NULL) {
  29589. *inLen = totalSz;
  29590. #ifndef WOLFSSL_NO_MALLOC
  29591. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29592. if (pubIn) {
  29593. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29594. }
  29595. #endif
  29596. return LENGTH_ONLY_E;
  29597. }
  29598. if (inLen != NULL && totalSz > *inLen) {
  29599. #ifndef WOLFSSL_NO_MALLOC
  29600. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29601. if (pubIn) {
  29602. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29603. }
  29604. #endif
  29605. return BAD_FUNC_ARG;
  29606. }
  29607. /* write out */
  29608. /* seq */
  29609. XMEMCPY(output + idx, seq, seqSz);
  29610. idx = seqSz;
  29611. /* ver */
  29612. XMEMCPY(output + idx, ver, (size_t)verSz);
  29613. idx += (word32)verSz;
  29614. /* private */
  29615. XMEMCPY(output + idx, prv, prvidx);
  29616. idx += prvidx;
  29617. #ifndef WOLFSSL_NO_MALLOC
  29618. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29619. #endif
  29620. /* curve */
  29621. XMEMCPY(output + idx, curve, curveidx);
  29622. idx += curveidx;
  29623. /* pubIn */
  29624. if (pubIn) {
  29625. XMEMCPY(output + idx, pub, pubidx);
  29626. /* idx += pubidx; not used after write, if more data remove comment */
  29627. #ifndef WOLFSSL_NO_MALLOC
  29628. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29629. #endif
  29630. }
  29631. return (int)totalSz;
  29632. #else
  29633. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  29634. word32 privSz, pubSz;
  29635. int sz = 0;
  29636. int ret = 0;
  29637. int curveIdSz = 0;
  29638. /* Check validity of parameters. */
  29639. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  29640. ret = BAD_FUNC_ARG;
  29641. }
  29642. /* Check key has parameters when encoding curve. */
  29643. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  29644. ret = BAD_FUNC_ARG;
  29645. }
  29646. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29647. if (ret == 0) {
  29648. /* Private key size is the curve size. */
  29649. privSz = (word32)key->dp->size;
  29650. if (pubIn) {
  29651. /* Get the length of the public key. */
  29652. PRIVATE_KEY_UNLOCK();
  29653. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29654. PRIVATE_KEY_LOCK();
  29655. if (ret == LENGTH_ONLY_E)
  29656. ret = 0;
  29657. }
  29658. }
  29659. if (ret == 0) {
  29660. /* Version: 1 */
  29661. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  29662. /* Leave space for private key. */
  29663. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  29664. if (curveIn) {
  29665. /* Get length of the named curve OID to put into the encoding. */
  29666. curveIdSz = SetCurve(key, NULL, 0);
  29667. if (curveIdSz < 0) {
  29668. ret = curveIdSz;
  29669. }
  29670. /* Curve OID */
  29671. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  29672. (word32)curveIdSz);
  29673. /* TODO: add support for SpecifiedECDomain curve. */
  29674. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  29675. }
  29676. else {
  29677. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  29678. eccKeyASN_Length);
  29679. }
  29680. if (ret == 0) {
  29681. if (pubIn) {
  29682. /* Leave space for public key. */
  29683. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  29684. }
  29685. else {
  29686. /* Don't write out public key. */
  29687. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  29688. eccKeyASN_Length);
  29689. }
  29690. /* Calculate size of the private key encoding. */
  29691. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  29692. }
  29693. }
  29694. /* Return the size if no buffer. */
  29695. if ((ret == 0) && (output == NULL)) {
  29696. *inLen = (word32)sz;
  29697. ret = LENGTH_ONLY_E;
  29698. }
  29699. /* Check the buffer is big enough. */
  29700. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  29701. ret = BAD_FUNC_ARG;
  29702. }
  29703. if ((ret == 0) && (output != NULL)) {
  29704. /* Encode the private key. */
  29705. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  29706. if (curveIn) {
  29707. /* Put named curve OID data into encoding. */
  29708. curveIdSz = SetCurve(key,
  29709. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  29710. (size_t)curveIdSz);
  29711. if (curveIdSz < 0) {
  29712. ret = curveIdSz;
  29713. }
  29714. }
  29715. if (ret == 0) {
  29716. /* Export the private value into the buffer. */
  29717. ret = wc_ecc_export_private_only(key,
  29718. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  29719. }
  29720. if ((ret == 0) && pubIn) {
  29721. /* Export the public point into the buffer. */
  29722. PRIVATE_KEY_UNLOCK();
  29723. ret = wc_ecc_export_x963(key,
  29724. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  29725. &pubSz);
  29726. PRIVATE_KEY_LOCK();
  29727. }
  29728. }
  29729. if (ret == 0) {
  29730. /* Return the encoding size. */
  29731. ret = sz;
  29732. }
  29733. FREE_ASNSETDATA(dataASN, key->heap);
  29734. return ret;
  29735. #endif
  29736. }
  29737. /* Write a Private ecc key, including public to DER format,
  29738. * length on success else < 0 */
  29739. WOLFSSL_ABI
  29740. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29741. {
  29742. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  29743. }
  29744. /* Write only private ecc key to DER format,
  29745. * length on success else < 0 */
  29746. int wc_EccKeyDerSize(ecc_key* key, int pub)
  29747. {
  29748. word32 sz = 0;
  29749. int ret;
  29750. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  29751. if (ret != LENGTH_ONLY_E) {
  29752. return ret;
  29753. }
  29754. return (int)sz;
  29755. }
  29756. /* Write only private ecc key to DER format,
  29757. * length on success else < 0 */
  29758. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29759. {
  29760. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  29761. }
  29762. #ifdef HAVE_PKCS8
  29763. /* Write only private ecc key or both private and public parts to unencrypted
  29764. * PKCS#8 format.
  29765. *
  29766. * If output is NULL, places required PKCS#8 buffer size in outLen and
  29767. * returns LENGTH_ONLY_E.
  29768. *
  29769. * return length on success else < 0 */
  29770. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  29771. int includePublic)
  29772. {
  29773. int ret;
  29774. word32 tmpDerSz;
  29775. int algoID = 0;
  29776. word32 oidSz = 0;
  29777. word32 pkcs8Sz = 0;
  29778. const byte* curveOID = NULL;
  29779. #ifdef WOLFSSL_NO_MALLOC
  29780. byte tmpDer[ECC_BUFSIZE];
  29781. #else
  29782. byte* tmpDer = NULL;
  29783. #endif
  29784. word32 sz = ECC_BUFSIZE;
  29785. if (key == NULL || key->dp == NULL || outLen == NULL)
  29786. return BAD_FUNC_ARG;
  29787. /* set algoID, get curve OID */
  29788. algoID = ECDSAk;
  29789. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  29790. if (ret < 0)
  29791. return ret;
  29792. #ifndef WOLFSSL_NO_MALLOC
  29793. /* temp buffer for plain DER key */
  29794. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29795. if (tmpDer == NULL)
  29796. return MEMORY_E;
  29797. #endif
  29798. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  29799. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  29800. if (ret < 0) {
  29801. #ifndef WOLFSSL_NO_MALLOC
  29802. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29803. #endif
  29804. return ret;
  29805. }
  29806. tmpDerSz = (word32)ret;
  29807. /* get pkcs8 expected output size */
  29808. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  29809. curveOID, oidSz);
  29810. if (ret != LENGTH_ONLY_E) {
  29811. #ifndef WOLFSSL_NO_MALLOC
  29812. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29813. #endif
  29814. return ret;
  29815. }
  29816. if (output == NULL) {
  29817. #ifndef WOLFSSL_NO_MALLOC
  29818. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29819. #endif
  29820. *outLen = pkcs8Sz;
  29821. return LENGTH_ONLY_E;
  29822. }
  29823. else if (*outLen < pkcs8Sz) {
  29824. #ifndef WOLFSSL_NO_MALLOC
  29825. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29826. #endif
  29827. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  29828. return BUFFER_E;
  29829. }
  29830. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  29831. algoID, curveOID, oidSz);
  29832. if (ret < 0) {
  29833. #ifndef WOLFSSL_NO_MALLOC
  29834. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29835. #endif
  29836. return ret;
  29837. }
  29838. #ifndef WOLFSSL_NO_MALLOC
  29839. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29840. #endif
  29841. *outLen = (word32)ret;
  29842. return ret;
  29843. }
  29844. /* Write only private ecc key to unencrypted PKCS#8 format.
  29845. *
  29846. * return length on success else < 0 */
  29847. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  29848. {
  29849. return eccToPKCS8(key, output, outLen, 0);
  29850. }
  29851. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  29852. *
  29853. * return length on success else < 0 */
  29854. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  29855. word32* outLen)
  29856. {
  29857. return eccToPKCS8(key, output, outLen, 1);
  29858. }
  29859. #endif /* HAVE_PKCS8 */
  29860. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  29861. #endif /* HAVE_ECC */
  29862. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  29863. #ifdef WOLFSSL_ASN_TEMPLATE
  29864. /* ASN.1 template for Ed25519 and Ed448 private key.
  29865. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  29866. */
  29867. static const ASNItem edKeyASN[] = {
  29868. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29869. /* Version */
  29870. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  29871. /* privateKeyAlgorithm */
  29872. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  29873. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  29874. /* privateKey */
  29875. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  29876. /* CurvePrivateKey */
  29877. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  29878. /* attributes */
  29879. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  29880. /* publicKey */
  29881. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  29882. };
  29883. enum {
  29884. EDKEYASN_IDX_SEQ = 0,
  29885. EDKEYASN_IDX_VER,
  29886. EDKEYASN_IDX_PKEYALGO_SEQ,
  29887. EDKEYASN_IDX_PKEYALGO_OID,
  29888. EDKEYASN_IDX_PKEY,
  29889. EDKEYASN_IDX_PKEY_CURVEPKEY,
  29890. EDKEYASN_IDX_ATTRS,
  29891. EDKEYASN_IDX_PUBKEY
  29892. };
  29893. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  29894. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  29895. #endif
  29896. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  29897. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  29898. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  29899. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  29900. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  29901. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  29902. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  29903. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  29904. byte* privKey, word32* privKeyLen,
  29905. byte* pubKey, word32* pubKeyLen, int keyType)
  29906. {
  29907. #ifndef WOLFSSL_ASN_TEMPLATE
  29908. word32 oid;
  29909. int version, length, endKeyIdx, privSz, pubSz;
  29910. const byte* priv;
  29911. const byte* pub;
  29912. #else
  29913. int ret = 0;
  29914. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  29915. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29916. #endif
  29917. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  29918. privKey == NULL || privKeyLen == NULL) {
  29919. return BAD_FUNC_ARG;
  29920. }
  29921. #ifndef WOLFSSL_ASN_TEMPLATE
  29922. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  29923. endKeyIdx = (int)*inOutIdx + length;
  29924. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  29925. return ASN_PARSE_E;
  29926. if (version != 0) {
  29927. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  29928. return ASN_PARSE_E;
  29929. }
  29930. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29931. return ASN_PARSE_E;
  29932. if (oid != (word32)keyType)
  29933. return ASN_PARSE_E;
  29934. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  29935. return ASN_PARSE_E;
  29936. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29937. return ASN_PARSE_E;
  29938. priv = input + *inOutIdx;
  29939. *inOutIdx += (word32)privSz;
  29940. }
  29941. else {
  29942. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29943. return ASN_PARSE_E;
  29944. priv = input + *inOutIdx;
  29945. *inOutIdx += (word32)privSz;
  29946. endKeyIdx = (int)*inOutIdx;
  29947. }
  29948. if ((word32)privSz > *privKeyLen)
  29949. return BUFFER_E;
  29950. if (endKeyIdx == (int)*inOutIdx) {
  29951. *privKeyLen = (word32)privSz;
  29952. XMEMCPY(privKey, priv, *privKeyLen);
  29953. if (pubKeyLen != NULL)
  29954. *pubKeyLen = 0;
  29955. }
  29956. else {
  29957. if (pubKeyLen == NULL) {
  29958. return BAD_FUNC_ARG;
  29959. }
  29960. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  29961. inOutIdx, &pubSz, inSz) < 0) {
  29962. return ASN_PARSE_E;
  29963. }
  29964. if ((word32)pubSz > *pubKeyLen)
  29965. return BUFFER_E;
  29966. pub = input + *inOutIdx;
  29967. *inOutIdx += (word32)pubSz;
  29968. *privKeyLen = (word32)privSz;
  29969. XMEMCPY(privKey, priv, *privKeyLen);
  29970. *pubKeyLen = (word32)pubSz;
  29971. if (pubKey != NULL)
  29972. XMEMCPY(pubKey, pub, *pubKeyLen);
  29973. }
  29974. if (endKeyIdx != (int)*inOutIdx)
  29975. return ASN_PARSE_E;
  29976. return 0;
  29977. #else
  29978. if (ret == 0) {
  29979. /* Require OID. */
  29980. word32 oidSz;
  29981. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  29982. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  29983. /* Parse full private key. */
  29984. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  29985. inOutIdx, inSz);
  29986. if (ret != 0) {
  29987. /* Parse just the OCTET_STRING. */
  29988. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  29989. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  29990. inOutIdx, inSz);
  29991. if (ret != 0) {
  29992. ret = ASN_PARSE_E;
  29993. }
  29994. }
  29995. }
  29996. /* Check the private value length is correct. */
  29997. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  29998. > *privKeyLen) {
  29999. ret = ASN_PARSE_E;
  30000. }
  30001. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  30002. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  30003. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  30004. *privKeyLen);
  30005. if (pubKeyLen != NULL)
  30006. *pubKeyLen = 0;
  30007. }
  30008. else if ((ret == 0) &&
  30009. (pubKeyLen != NULL) &&
  30010. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  30011. ret = ASN_PARSE_E;
  30012. }
  30013. else if (ret == 0) {
  30014. /* Import private and public value. */
  30015. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  30016. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  30017. *privKeyLen);
  30018. if (pubKeyLen != NULL)
  30019. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  30020. if (pubKey != NULL && pubKeyLen != NULL)
  30021. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  30022. *pubKeyLen);
  30023. }
  30024. FREE_ASNGETDATA(dataASN, NULL);
  30025. return ret;
  30026. #endif /* WOLFSSL_ASN_TEMPLATE */
  30027. }
  30028. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  30029. byte* pubKey, word32* pubKeyLen, int keyType)
  30030. {
  30031. int ret = 0;
  30032. #ifndef WOLFSSL_ASN_TEMPLATE
  30033. int length;
  30034. word32 oid;
  30035. #else
  30036. word32 len;
  30037. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  30038. #endif
  30039. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  30040. pubKey == NULL || pubKeyLen == NULL) {
  30041. return BAD_FUNC_ARG;
  30042. }
  30043. #ifndef WOLFSSL_ASN_TEMPLATE
  30044. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30045. return ASN_PARSE_E;
  30046. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30047. return ASN_PARSE_E;
  30048. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  30049. return ASN_PARSE_E;
  30050. if (oid != (word32)keyType)
  30051. return ASN_PARSE_E;
  30052. /* key header */
  30053. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  30054. if (ret != 0)
  30055. return ret;
  30056. /* check that the value found is not too large for pubKey buffer */
  30057. if ((word32)length > *pubKeyLen)
  30058. return ASN_PARSE_E;
  30059. /* check that input buffer is exhausted */
  30060. if (*inOutIdx + (word32)length != inSz)
  30061. return ASN_PARSE_E;
  30062. /* This is the raw point data compressed or uncompressed. */
  30063. *pubKeyLen = (word32)length;
  30064. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  30065. #else
  30066. len = inSz - *inOutIdx;
  30067. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  30068. if (ret == 0) {
  30069. /* Require OID. */
  30070. word32 oidSz;
  30071. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  30072. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  30073. /* Decode Ed25519 private key. */
  30074. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  30075. inOutIdx, inSz);
  30076. if (ret != 0)
  30077. ret = ASN_PARSE_E;
  30078. /* check that input buffer is exhausted */
  30079. if (*inOutIdx != inSz)
  30080. ret = ASN_PARSE_E;
  30081. }
  30082. /* Check the public value length is correct. */
  30083. if ((ret == 0) &&
  30084. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  30085. ret = ASN_PARSE_E;
  30086. }
  30087. /* Check that the all the buffer was used. */
  30088. if ((ret == 0) &&
  30089. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  30090. ret = ASN_PARSE_E;
  30091. }
  30092. if (ret == 0) {
  30093. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  30094. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  30095. *pubKeyLen);
  30096. }
  30097. FREE_ASNGETDATA(dataASN, NULL);
  30098. #endif /* WOLFSSL_ASN_TEMPLATE */
  30099. return ret;
  30100. }
  30101. #endif
  30102. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  30103. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  30104. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30105. ed25519_key* key, word32 inSz)
  30106. {
  30107. int ret;
  30108. byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
  30109. word32 privKeyLen = (word32)sizeof(privKey);
  30110. word32 pubKeyLen = (word32)sizeof(pubKey);
  30111. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30112. return BAD_FUNC_ARG;
  30113. }
  30114. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30115. pubKey, &pubKeyLen, ED25519k);
  30116. if (ret == 0) {
  30117. if (pubKeyLen == 0) {
  30118. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  30119. }
  30120. else {
  30121. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  30122. pubKey, pubKeyLen, key);
  30123. }
  30124. }
  30125. return ret;
  30126. }
  30127. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  30128. ed25519_key* key, word32 inSz)
  30129. {
  30130. int ret;
  30131. byte pubKey[ED25519_PUB_KEY_SIZE];
  30132. word32 pubKeyLen = (word32)sizeof(pubKey);
  30133. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30134. return BAD_FUNC_ARG;
  30135. }
  30136. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30137. pubKey, &pubKeyLen, ED25519k);
  30138. if (ret == 0) {
  30139. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  30140. }
  30141. return ret;
  30142. }
  30143. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  30144. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  30145. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30146. curve25519_key* key, word32 inSz)
  30147. {
  30148. int ret;
  30149. byte privKey[CURVE25519_KEYSIZE];
  30150. word32 privKeyLen = CURVE25519_KEYSIZE;
  30151. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30152. return BAD_FUNC_ARG;
  30153. }
  30154. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30155. NULL, NULL, X25519k);
  30156. if (ret == 0) {
  30157. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  30158. }
  30159. return ret;
  30160. }
  30161. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  30162. curve25519_key* key, word32 inSz)
  30163. {
  30164. int ret;
  30165. byte pubKey[CURVE25519_KEYSIZE];
  30166. word32 pubKeyLen = (word32)sizeof(pubKey);
  30167. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30168. return BAD_FUNC_ARG;
  30169. }
  30170. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30171. pubKey, &pubKeyLen, X25519k);
  30172. if (ret == 0) {
  30173. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  30174. }
  30175. return ret;
  30176. }
  30177. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  30178. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  30179. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  30180. *
  30181. * Pass NULL for output to get the size of the encoding.
  30182. *
  30183. * @param [in] privKey private key buffer
  30184. * @param [in] privKeyLen private ket buffer length
  30185. * @param [in] pubKey public key buffer (optional)
  30186. * @param [in] pubKeyLen public ket buffer length
  30187. * @param [out] output Buffer to put encoded data in (optional)
  30188. * @param [in] outLen Size of buffer in bytes
  30189. * @param [in] keyType is "enum Key_Sum" like ED25519k
  30190. * @return Size of encoded data in bytes on success
  30191. * @return BAD_FUNC_ARG when key is NULL.
  30192. * @return MEMORY_E when dynamic memory allocation failed.
  30193. */
  30194. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  30195. const byte* pubKey, word32 pubKeyLen,
  30196. byte* output, word32 outLen, int keyType)
  30197. {
  30198. int ret = 0;
  30199. #ifndef WOLFSSL_ASN_TEMPLATE
  30200. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  30201. #else
  30202. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  30203. int sz;
  30204. #endif
  30205. /* Validate parameters. */
  30206. if (privKey == NULL || outLen == 0) {
  30207. return BAD_FUNC_ARG;
  30208. }
  30209. #ifndef WOLFSSL_ASN_TEMPLATE
  30210. /* calculate size */
  30211. if (pubKey) {
  30212. pubSz = 2 + pubKeyLen;
  30213. }
  30214. privSz = 2 + 2 + privKeyLen;
  30215. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  30216. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  30217. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  30218. sz = seqSz + verSz + algoSz + privSz + pubSz;
  30219. /* checkout output size */
  30220. if (output != NULL && sz > outLen) {
  30221. ret = BAD_FUNC_ARG;
  30222. }
  30223. if (ret == 0 && output != NULL) {
  30224. /* write out */
  30225. /* seq */
  30226. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  30227. idx = seqSz;
  30228. /* ver */
  30229. SetMyVersion(0, output + idx, FALSE);
  30230. idx += verSz;
  30231. /* algo */
  30232. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  30233. idx += algoSz;
  30234. /* privKey */
  30235. idx += SetOctetString(2 + privKeyLen, output + idx);
  30236. idx += SetOctetString(privKeyLen, output + idx);
  30237. XMEMCPY(output + idx, privKey, privKeyLen);
  30238. idx += privKeyLen;
  30239. /* pubKey */
  30240. if (pubKey) {
  30241. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  30242. 1, pubKeyLen, output + idx);
  30243. XMEMCPY(output + idx, pubKey, pubKeyLen);
  30244. idx += pubKeyLen;
  30245. }
  30246. sz = idx;
  30247. }
  30248. if (ret == 0) {
  30249. /* Return size of encoding. */
  30250. ret = (int)sz;
  30251. }
  30252. #else
  30253. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  30254. if (ret == 0) {
  30255. /* Set version = 0 */
  30256. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  30257. /* Set OID. */
  30258. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
  30259. oidKeyType);
  30260. /* Leave space for private key. */
  30261. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  30262. /* Don't write out attributes. */
  30263. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  30264. if (pubKey) {
  30265. /* Leave space for public key. */
  30266. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  30267. }
  30268. else {
  30269. /* Don't put out public part. */
  30270. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  30271. edKeyASN_Length);
  30272. }
  30273. /* Calculate the size of encoding. */
  30274. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  30275. }
  30276. /* Check buffer is big enough. */
  30277. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30278. ret = BAD_FUNC_ARG;
  30279. }
  30280. if ((ret == 0) && (output != NULL)) {
  30281. /* Encode private key. */
  30282. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30283. /* Put private value into space provided. */
  30284. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30285. privKey, privKeyLen);
  30286. if (pubKey != NULL) {
  30287. /* Put public value into space provided. */
  30288. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30289. pubKey, pubKeyLen);
  30290. }
  30291. }
  30292. if (ret == 0) {
  30293. /* Return size of encoding. */
  30294. ret = sz;
  30295. }
  30296. FREE_ASNSETDATA(dataASN, NULL);
  30297. #endif
  30298. return ret;
  30299. }
  30300. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30301. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30302. /* Write a Private ED25519 key, including public to DER format,
  30303. * length on success else < 0 */
  30304. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30305. {
  30306. if (key == NULL) {
  30307. return BAD_FUNC_ARG;
  30308. }
  30309. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30310. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30311. }
  30312. /* Write only private ED25519 key to DER format,
  30313. * length on success else < 0 */
  30314. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30315. {
  30316. if (key == NULL) {
  30317. return BAD_FUNC_ARG;
  30318. }
  30319. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30320. NULL, 0, output, inLen, ED25519k);
  30321. }
  30322. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30323. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30324. /* Write only private Curve25519 key to DER format,
  30325. * length on success else < 0 */
  30326. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30327. {
  30328. int ret;
  30329. byte privKey[CURVE25519_KEYSIZE];
  30330. word32 privKeyLen = CURVE25519_KEYSIZE;
  30331. if (key == NULL) {
  30332. return BAD_FUNC_ARG;
  30333. }
  30334. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30335. if (ret == 0) {
  30336. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30337. X25519k);
  30338. }
  30339. return ret;
  30340. }
  30341. /* Write a public Curve25519 key to DER format,
  30342. * length on success else < 0 */
  30343. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30344. int withAlg)
  30345. {
  30346. int ret;
  30347. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30348. word32 pubKeyLen = (word32)sizeof(pubKey);
  30349. if (key == NULL || output == NULL) {
  30350. return BAD_FUNC_ARG;
  30351. }
  30352. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30353. if (ret == 0) {
  30354. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30355. X25519k, withAlg);
  30356. }
  30357. return ret;
  30358. }
  30359. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30360. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30361. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30362. ed448_key* key, word32 inSz)
  30363. {
  30364. int ret;
  30365. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30366. word32 privKeyLen = (word32)sizeof(privKey);
  30367. word32 pubKeyLen = (word32)sizeof(pubKey);
  30368. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30369. return BAD_FUNC_ARG;
  30370. }
  30371. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30372. pubKey, &pubKeyLen, ED448k);
  30373. if (ret == 0) {
  30374. if (pubKeyLen == 0) {
  30375. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30376. }
  30377. else {
  30378. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30379. pubKey, pubKeyLen, key);
  30380. }
  30381. }
  30382. return ret;
  30383. }
  30384. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30385. ed448_key* key, word32 inSz)
  30386. {
  30387. int ret;
  30388. byte pubKey[ED448_PUB_KEY_SIZE];
  30389. word32 pubKeyLen = (word32)sizeof(pubKey);
  30390. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30391. return BAD_FUNC_ARG;
  30392. }
  30393. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30394. pubKey, &pubKeyLen, ED448k);
  30395. if (ret == 0) {
  30396. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30397. }
  30398. return ret;
  30399. }
  30400. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30401. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30402. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30403. curve448_key* key, word32 inSz)
  30404. {
  30405. int ret;
  30406. byte privKey[CURVE448_KEY_SIZE];
  30407. word32 privKeyLen = CURVE448_KEY_SIZE;
  30408. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30409. return BAD_FUNC_ARG;
  30410. }
  30411. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30412. NULL, NULL, X448k);
  30413. if (ret == 0) {
  30414. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30415. }
  30416. return ret;
  30417. }
  30418. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30419. curve448_key* key, word32 inSz)
  30420. {
  30421. int ret;
  30422. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30423. word32 pubKeyLen = (word32)sizeof(pubKey);
  30424. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30425. return BAD_FUNC_ARG;
  30426. }
  30427. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30428. pubKey, &pubKeyLen, X448k);
  30429. if (ret == 0) {
  30430. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30431. }
  30432. return ret;
  30433. }
  30434. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30435. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30436. /* Write a Private ecc key, including public to DER format,
  30437. * length on success else < 0 */
  30438. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30439. {
  30440. if (key == NULL) {
  30441. return BAD_FUNC_ARG;
  30442. }
  30443. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30444. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30445. }
  30446. /* Write only private ecc key to DER format,
  30447. * length on success else < 0 */
  30448. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30449. {
  30450. if (key == NULL) {
  30451. return BAD_FUNC_ARG;
  30452. }
  30453. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30454. NULL, 0, output, inLen, ED448k);
  30455. }
  30456. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30457. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30458. /* Write private Curve448 key to DER format,
  30459. * length on success else < 0 */
  30460. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30461. {
  30462. int ret;
  30463. byte privKey[CURVE448_KEY_SIZE];
  30464. word32 privKeyLen = CURVE448_KEY_SIZE;
  30465. if (key == NULL) {
  30466. return BAD_FUNC_ARG;
  30467. }
  30468. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30469. if (ret == 0) {
  30470. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30471. X448k);
  30472. }
  30473. return ret;
  30474. }
  30475. /* Write a public Curve448 key to DER format,
  30476. * length on success else < 0 */
  30477. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30478. int withAlg)
  30479. {
  30480. int ret;
  30481. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30482. word32 pubKeyLen = (word32)sizeof(pubKey);
  30483. if (key == NULL || output == NULL) {
  30484. return BAD_FUNC_ARG;
  30485. }
  30486. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30487. if (ret == 0) {
  30488. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30489. X448k, withAlg);
  30490. }
  30491. return ret;
  30492. }
  30493. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30494. #ifndef WOLFSSL_ASN_TEMPLATE
  30495. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30496. /* Get raw Date only, no processing, 0 on success */
  30497. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30498. byte* format, int maxIdx)
  30499. {
  30500. int ret, length;
  30501. const byte *datePtr = NULL;
  30502. WOLFSSL_ENTER("GetBasicDate");
  30503. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30504. if (ret < 0)
  30505. return ret;
  30506. XMEMCPY(date, datePtr, length);
  30507. return 0;
  30508. }
  30509. #endif /* HAVE_OCSP || HAVE_CRL */
  30510. #endif /* WOLFSSL_ASN_TEMPLATE */
  30511. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30512. #ifndef WOLFSSL_ASN_TEMPLATE
  30513. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30514. int sz)
  30515. {
  30516. word32 idx = *inOutIdx;
  30517. word32 len;
  30518. byte tag;
  30519. WOLFSSL_ENTER("GetEnumerated");
  30520. *value = 0;
  30521. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30522. return ASN_PARSE_E;
  30523. if (tag != ASN_ENUMERATED)
  30524. return ASN_PARSE_E;
  30525. if ((int)idx >= sz)
  30526. return BUFFER_E;
  30527. len = input[idx++];
  30528. if (len > 4 || (int)(len + idx) > sz)
  30529. return ASN_PARSE_E;
  30530. while (len--) {
  30531. *value = *value << 8 | input[idx++];
  30532. }
  30533. *inOutIdx = idx;
  30534. return *value;
  30535. }
  30536. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30537. #ifdef WOLFSSL_ASN_TEMPLATE
  30538. /* ASN.1 template for OCSP single response.
  30539. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30540. */
  30541. static const ASNItem singleResponseASN[] = {
  30542. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30543. /* certId */
  30544. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30545. /* hashAlgorithm */
  30546. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30547. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30548. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30549. /* issuerNameHash */
  30550. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30551. /* issuerKeyHash */
  30552. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30553. /* serialNumber */
  30554. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30555. /* certStatus - CHOICE */
  30556. /* good [0] IMPLICIT NULL */
  30557. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30558. /* revoked [1] IMPLICIT RevokedInfo */
  30559. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30560. /* revocationTime */
  30561. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30562. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30563. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30564. /* crlReason */
  30565. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30566. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30567. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30568. /* thisUpdate */
  30569. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30570. /* nextUpdate */
  30571. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30572. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30573. /* singleExtensions */
  30574. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30575. };
  30576. enum {
  30577. SINGLERESPONSEASN_IDX_SEQ = 0,
  30578. SINGLERESPONSEASN_IDX_CID_SEQ,
  30579. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30580. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30581. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30582. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30583. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30584. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30585. SINGLERESPONSEASN_IDX_CS_GOOD,
  30586. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30587. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30588. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30589. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30590. SINGLERESPONSEASN_IDX_UNKNOWN,
  30591. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30592. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30593. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30594. SINGLERESPONSEASN_IDX_EXT,
  30595. };
  30596. /* Number of items in ASN.1 template for OCSP single response. */
  30597. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30598. #endif
  30599. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  30600. int wrapperSz, OcspEntry* single)
  30601. {
  30602. #ifndef WOLFSSL_ASN_TEMPLATE
  30603. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  30604. int length;
  30605. int ret;
  30606. byte tag;
  30607. WOLFSSL_ENTER("DecodeSingleResponse");
  30608. prevIndex = idx;
  30609. /* Wrapper around the Single Response */
  30610. if (GetSequence(source, &idx, &length, size) < 0)
  30611. return ASN_PARSE_E;
  30612. /* Wrapper around the CertID */
  30613. certIdIdx = idx;
  30614. if (GetSequence(source, &idx, &length, size) < 0)
  30615. return ASN_PARSE_E;
  30616. single->rawCertId = source + certIdIdx;
  30617. /* Hash algorithm */
  30618. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  30619. if (ret < 0)
  30620. return ret;
  30621. single->hashAlgoOID = oid;
  30622. /* Save reference to the hash of CN */
  30623. ret = GetOctetString(source, &idx, &length, size);
  30624. if (ret < 0)
  30625. return ret;
  30626. if (length > (int)sizeof(single->issuerHash))
  30627. return BUFFER_E;
  30628. XMEMCPY(single->issuerHash, source + idx, length);
  30629. idx += length;
  30630. /* Save reference to the hash of the issuer public key */
  30631. ret = GetOctetString(source, &idx, &length, size);
  30632. if (ret < 0)
  30633. return ret;
  30634. if (length > (int)sizeof(single->issuerKeyHash))
  30635. return BUFFER_E;
  30636. XMEMCPY(single->issuerKeyHash, source + idx, length);
  30637. idx += length;
  30638. /* Get serial number */
  30639. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  30640. &single->status->serialSz, size) < 0)
  30641. return ASN_PARSE_E;
  30642. single->rawCertIdSize = idx - certIdIdx;
  30643. if (idx >= size)
  30644. return BUFFER_E;
  30645. /* CertStatus */
  30646. switch (source[idx++])
  30647. {
  30648. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  30649. single->status->status = CERT_GOOD;
  30650. idx++;
  30651. break;
  30652. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  30653. single->status->status = CERT_REVOKED;
  30654. if (GetLength(source, &idx, &length, size) < 0)
  30655. return ASN_PARSE_E;
  30656. idx += length;
  30657. break;
  30658. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  30659. single->status->status = CERT_UNKNOWN;
  30660. idx++;
  30661. break;
  30662. default:
  30663. return ASN_PARSE_E;
  30664. }
  30665. if (idx >= size)
  30666. return BUFFER_E;
  30667. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30668. single->status->thisDateAsn = source + idx;
  30669. localIdx = 0;
  30670. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  30671. (byte*)&single->status->thisDateParsed.type,
  30672. &single->status->thisDateParsed.length, size - idx) < 0)
  30673. return ASN_PARSE_E;
  30674. if (idx + localIdx >= size)
  30675. return BUFFER_E;
  30676. XMEMCPY(single->status->thisDateParsed.data,
  30677. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  30678. single->status->thisDateParsed.length);
  30679. #endif
  30680. if (GetBasicDate(source, &idx, single->status->thisDate,
  30681. &single->status->thisDateFormat, size) < 0)
  30682. return ASN_PARSE_E;
  30683. #ifndef NO_ASN_TIME_CHECK
  30684. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30685. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  30686. return ASN_BEFORE_DATE_E;
  30687. #endif
  30688. #endif
  30689. /* The following items are optional. Only check for them if there is more
  30690. * unprocessed data in the singleResponse wrapper. */
  30691. localIdx = idx;
  30692. if (((int)(idx - prevIndex) < wrapperSz) &&
  30693. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30694. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  30695. {
  30696. idx++;
  30697. if (GetLength(source, &idx, &length, size) < 0)
  30698. return ASN_PARSE_E;
  30699. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30700. single->status->nextDateAsn = source + idx;
  30701. localIdx = 0;
  30702. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  30703. (byte*)&single->status->nextDateParsed.type,
  30704. &single->status->nextDateParsed.length, size - idx) < 0)
  30705. return ASN_PARSE_E;
  30706. if (idx + localIdx >= size)
  30707. return BUFFER_E;
  30708. XMEMCPY(single->status->nextDateParsed.data,
  30709. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  30710. single->status->nextDateParsed.length);
  30711. #endif
  30712. if (GetBasicDate(source, &idx, single->status->nextDate,
  30713. &single->status->nextDateFormat, size) < 0)
  30714. return ASN_PARSE_E;
  30715. #ifndef NO_ASN_TIME_CHECK
  30716. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30717. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  30718. return ASN_AFTER_DATE_E;
  30719. #endif
  30720. #endif
  30721. }
  30722. /* Skip the optional extensions in singleResponse. */
  30723. localIdx = idx;
  30724. if (((int)(idx - prevIndex) < wrapperSz) &&
  30725. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30726. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30727. {
  30728. idx++;
  30729. if (GetLength(source, &idx, &length, size) < 0)
  30730. return ASN_PARSE_E;
  30731. idx += length;
  30732. }
  30733. *ioIndex = idx;
  30734. return 0;
  30735. #else
  30736. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  30737. int ret = 0;
  30738. word32 ocspDigestSize = OCSP_DIGEST_SIZE;
  30739. CertStatus* cs = NULL;
  30740. word32 serialSz;
  30741. word32 issuerHashLen;
  30742. word32 issuerKeyHashLen;
  30743. word32 thisDateLen;
  30744. word32 nextDateLen;
  30745. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30746. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30747. WOLFSSL_ASN1_TIME *at;
  30748. #endif
  30749. (void)wrapperSz;
  30750. WOLFSSL_ENTER("DecodeSingleResponse");
  30751. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  30752. if (ret == 0) {
  30753. /* Certificate Status field. */
  30754. cs = single->status;
  30755. /* Set maximum lengths for data. */
  30756. issuerHashLen = OCSP_DIGEST_SIZE;
  30757. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  30758. serialSz = EXTERNAL_SERIAL_SIZE;
  30759. thisDateLen = MAX_DATE_SIZE;
  30760. nextDateLen = MAX_DATE_SIZE;
  30761. /* Set OID type, buffers to hold data and variables to hold size. */
  30762. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  30763. oidHashType);
  30764. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  30765. single->issuerHash, &issuerHashLen);
  30766. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  30767. single->issuerKeyHash, &issuerKeyHashLen);
  30768. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  30769. &serialSz);
  30770. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  30771. cs->thisDate, &thisDateLen);
  30772. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  30773. cs->nextDate, &nextDateLen);
  30774. /* TODO: decode revoked time and reason. */
  30775. /* Decode OCSP single response. */
  30776. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  30777. 1, source, ioIndex, size);
  30778. }
  30779. if (ret == 0) {
  30780. single->hashAlgoOID =
  30781. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  30782. ocspDigestSize = (word32)wc_HashGetDigestSize(
  30783. wc_OidGetHash((int)single->hashAlgoOID));
  30784. }
  30785. /* Validate the issuer hash length is the size required. */
  30786. if ((ret == 0) && (issuerHashLen != ocspDigestSize)) {
  30787. ret = ASN_PARSE_E;
  30788. }
  30789. /* Validate the issuer key hash length is the size required. */
  30790. if ((ret == 0) && (issuerKeyHashLen != ocspDigestSize)) {
  30791. ret = ASN_PARSE_E;
  30792. }
  30793. if (ret == 0) {
  30794. /* Store serial size. */
  30795. cs->serialSz = (int)serialSz;
  30796. /* Set the hash algorithm OID */
  30797. single->hashAlgoOID =
  30798. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  30799. /* Determine status by which item was found. */
  30800. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  30801. cs->status = CERT_GOOD;
  30802. }
  30803. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  30804. cs->status = CERT_REVOKED;
  30805. }
  30806. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  30807. cs->status = CERT_UNKNOWN;
  30808. }
  30809. /* Store the thisDate format - only one possible. */
  30810. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  30811. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30812. /* Check date is a valid string and BEFORE now. */
  30813. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  30814. ret = ASN_BEFORE_DATE_E;
  30815. }
  30816. }
  30817. if (ret == 0) {
  30818. #endif
  30819. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30820. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30821. /* Store ASN.1 version of thisDate. */
  30822. cs->thisDateAsn = GetASNItem_Addr(
  30823. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  30824. at = &cs->thisDateParsed;
  30825. at->type = ASN_GENERALIZED_TIME;
  30826. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  30827. at->length = (int)thisDateLen;
  30828. #endif
  30829. }
  30830. if ((ret == 0) &&
  30831. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30832. /* Store the nextDate format - only one possible. */
  30833. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  30834. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30835. /* Check date is a valid string and AFTER now. */
  30836. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  30837. ret = ASN_AFTER_DATE_E;
  30838. }
  30839. }
  30840. if ((ret == 0) &&
  30841. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30842. #endif
  30843. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30844. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30845. /* Store ASN.1 version of thisDate. */
  30846. cs->nextDateAsn = GetASNItem_Addr(
  30847. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  30848. at = &cs->nextDateParsed;
  30849. at->type = ASN_GENERALIZED_TIME;
  30850. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  30851. at->length = (int)nextDateLen;
  30852. #endif
  30853. }
  30854. if (ret == 0) {
  30855. /* OcspEntry now used. */
  30856. single->used = 1;
  30857. }
  30858. FREE_ASNGETDATA(dataASN, NULL);
  30859. return ret;
  30860. #endif
  30861. }
  30862. #ifdef WOLFSSL_ASN_TEMPLATE
  30863. /* ASN.1 template for OCSP response extension header.
  30864. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30865. */
  30866. static const ASNItem respExtHdrASN[] = {
  30867. /* responseExtensions */
  30868. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  30869. /* extensions */
  30870. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30871. };
  30872. enum {
  30873. RESPEXTHDRASN_IDX_EXT = 0,
  30874. RESPEXTHDRASN_IDX_EXT_SEQ,
  30875. };
  30876. /* Number of items in ASN.1 template for OCSP response extension header. */
  30877. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  30878. #endif
  30879. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  30880. OcspResponse* resp, word32 sz)
  30881. {
  30882. #ifndef WOLFSSL_ASN_TEMPLATE
  30883. word32 idx = *ioIndex;
  30884. int length;
  30885. int ext_bound; /* boundary index for the sequence of extensions */
  30886. word32 oid;
  30887. int ret;
  30888. byte tag;
  30889. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30890. if ((idx + 1) > sz)
  30891. return BUFFER_E;
  30892. if (GetASNTag(source, &idx, &tag, sz) < 0)
  30893. return ASN_PARSE_E;
  30894. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30895. return ASN_PARSE_E;
  30896. if (GetLength(source, &idx, &length, sz) < 0)
  30897. return ASN_PARSE_E;
  30898. if (GetSequence(source, &idx, &length, sz) < 0)
  30899. return ASN_PARSE_E;
  30900. ext_bound = idx + length;
  30901. while (idx < (word32)ext_bound) {
  30902. word32 localIdx;
  30903. if (GetSequence(source, &idx, &length, sz) < 0) {
  30904. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  30905. return ASN_PARSE_E;
  30906. }
  30907. oid = 0;
  30908. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  30909. WOLFSSL_MSG("\tfail: OBJECT ID");
  30910. return ASN_PARSE_E;
  30911. }
  30912. /* check for critical flag */
  30913. if ((idx + 1) > (word32)sz) {
  30914. WOLFSSL_MSG("\tfail: malformed buffer");
  30915. return BUFFER_E;
  30916. }
  30917. localIdx = idx;
  30918. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  30919. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  30920. ret = GetBoolean(source, &idx, sz);
  30921. if (ret < 0)
  30922. return ret;
  30923. }
  30924. ret = GetOctetString(source, &idx, &length, sz);
  30925. if (ret < 0)
  30926. return ret;
  30927. if (oid == OCSP_NONCE_OID) {
  30928. /* get data inside extra OCTET_STRING */
  30929. ret = GetOctetString(source, &idx, &length, sz);
  30930. if (ret < 0)
  30931. return ret;
  30932. resp->nonce = source + idx;
  30933. resp->nonceSz = length;
  30934. }
  30935. idx += length;
  30936. }
  30937. *ioIndex = idx;
  30938. return 0;
  30939. #else
  30940. /* certExtASN_Length is greater than respExtHdrASN_Length */
  30941. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  30942. int ret = 0;
  30943. word32 idx = *ioIndex;
  30944. word32 maxIdx = 0;
  30945. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30946. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  30947. if (ret == 0) {
  30948. /* Check for header and move past. */
  30949. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  30950. source, &idx, sz);
  30951. }
  30952. if (ret == 0) {
  30953. /* Keep end extensions index for total length check. */
  30954. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  30955. }
  30956. /* Step through all extensions. */
  30957. while ((ret == 0) && (idx < maxIdx)) {
  30958. /* Clear dynamic data, set OID type to expect. */
  30959. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  30960. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  30961. /* TODO: check criticality. */
  30962. /* Decode OCSP response extension. */
  30963. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  30964. source, &idx, sz);
  30965. if (ret == 0) {
  30966. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  30967. int length = (int)dataASN[CERTEXTASN_IDX_VAL].length;
  30968. if (oid == OCSP_NONCE_OID) {
  30969. /* Extract nonce data. */
  30970. ret = GetOctetString(source, &idx, &length, sz);
  30971. if (ret >= 0) {
  30972. ret = 0;
  30973. /* get data inside extra OCTET_STRING */
  30974. resp->nonce = source + idx;
  30975. resp->nonceSz = length;
  30976. }
  30977. }
  30978. /* Ignore all other extension types. */
  30979. /* Skip over rest of extension. */
  30980. idx += (word32)length;
  30981. }
  30982. }
  30983. /* Return index after extensions. */
  30984. *ioIndex = idx;
  30985. FREE_ASNGETDATA(dataASN, resp->heap);
  30986. return ret;
  30987. #endif
  30988. }
  30989. #ifdef WOLFSSL_ASN_TEMPLATE
  30990. /* ASN.1 template for OCSP ResponseData.
  30991. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30992. */
  30993. static const ASNItem ocspRespDataASN[] = {
  30994. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30995. /* version DEFAULT v1 */
  30996. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30997. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  30998. /* byName */
  30999. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  31000. /* byKey */
  31001. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  31002. /* producedAt */
  31003. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  31004. /* responses */
  31005. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  31006. /* responseExtensions */
  31007. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  31008. };
  31009. enum {
  31010. OCSPRESPDATAASN_IDX_SEQ = 0,
  31011. OCSPRESPDATAASN_IDX_VER_PRESENT,
  31012. OCSPRESPDATAASN_IDX_VER,
  31013. OCSPRESPDATAASN_IDX_BYNAME,
  31014. OCSPRESPDATAASN_IDX_BYKEY,
  31015. OCSPRESPDATAASN_IDX_PA,
  31016. OCSPRESPDATAASN_IDX_RESP,
  31017. OCSPRESPDATAASN_IDX_RESPEXT,
  31018. };
  31019. /* Number of items in ASN.1 template for OCSP ResponseData. */
  31020. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  31021. #endif
  31022. static int DecodeResponseData(byte* source, word32* ioIndex,
  31023. OcspResponse* resp, word32 size)
  31024. {
  31025. #ifndef WOLFSSL_ASN_TEMPLATE
  31026. word32 idx = *ioIndex, prev_idx, localIdx;
  31027. int length;
  31028. int version;
  31029. int ret;
  31030. byte tag;
  31031. int wrapperSz;
  31032. OcspEntry* single;
  31033. WOLFSSL_ENTER("DecodeResponseData");
  31034. resp->response = source + idx;
  31035. prev_idx = idx;
  31036. if (GetSequence(source, &idx, &length, size) < 0)
  31037. return ASN_PARSE_E;
  31038. resp->responseSz = length + idx - prev_idx;
  31039. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  31040. * item isn't an EXPLICIT[0], then set version to zero and move
  31041. * onto the next item.
  31042. */
  31043. localIdx = idx;
  31044. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31045. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  31046. {
  31047. idx += 2; /* Eat the value and length */
  31048. if (GetMyVersion(source, &idx, &version, size) < 0)
  31049. return ASN_PARSE_E;
  31050. } else
  31051. version = 0;
  31052. localIdx = idx;
  31053. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31054. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  31055. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  31056. {
  31057. idx++; /* advance past ASN tag */
  31058. if (GetLength(source, &idx, &length, size) < 0)
  31059. return ASN_PARSE_E;
  31060. idx += length;
  31061. }
  31062. else
  31063. return ASN_PARSE_E;
  31064. /* save pointer to the producedAt time */
  31065. if (GetBasicDate(source, &idx, resp->producedDate,
  31066. &resp->producedDateFormat, size) < 0)
  31067. return ASN_PARSE_E;
  31068. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  31069. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  31070. return ASN_PARSE_E;
  31071. localIdx = idx;
  31072. single = resp->single;
  31073. while (idx - localIdx < (word32)wrapperSz) {
  31074. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  31075. if (ret < 0)
  31076. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31077. if (idx - localIdx < (word32)wrapperSz) {
  31078. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  31079. DYNAMIC_TYPE_OCSP_ENTRY);
  31080. if (single->next == NULL) {
  31081. return MEMORY_E;
  31082. }
  31083. XMEMSET(single->next, 0, sizeof(OcspEntry));
  31084. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  31085. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31086. if (single->next->status == NULL) {
  31087. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31088. single->next = NULL;
  31089. return MEMORY_E;
  31090. }
  31091. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  31092. single->next->isDynamic = 1;
  31093. single = single->next;
  31094. }
  31095. }
  31096. /*
  31097. * Check the length of the ResponseData against the current index to
  31098. * see if there are extensions, they are optional.
  31099. */
  31100. if (idx - prev_idx < resp->responseSz)
  31101. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  31102. return ASN_PARSE_E;
  31103. *ioIndex = idx;
  31104. return 0;
  31105. #else
  31106. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  31107. int ret = 0;
  31108. byte version;
  31109. word32 dateSz, idx = *ioIndex;
  31110. OcspEntry* single = NULL;
  31111. WOLFSSL_ENTER("DecodeResponseData");
  31112. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  31113. if (ret == 0) {
  31114. resp->response = source + idx;
  31115. /* Default, not present, is v1 = 0. */
  31116. version = 0;
  31117. /* Max size of date supported. */
  31118. dateSz = MAX_DATE_SIZE;
  31119. /* Set the where to put version an produced date. */
  31120. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  31121. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  31122. &dateSz);
  31123. /* Decode the ResponseData. */
  31124. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  31125. 1, source, ioIndex, size);
  31126. }
  31127. /* Only support v1 == 0 */
  31128. if ((ret == 0) && (version != 0)) {
  31129. ret = ASN_PARSE_E;
  31130. }
  31131. /* Ensure date is a minimal size. */
  31132. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  31133. ret = ASN_PARSE_E;
  31134. }
  31135. if (ret == 0) {
  31136. /* TODO: use byName/byKey fields. */
  31137. /* Store size of response. */
  31138. resp->responseSz = *ioIndex - idx;
  31139. /* Store date format/tag. */
  31140. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  31141. /* Get the index of the responses SEQUENCE. */
  31142. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  31143. /* Start with the pre-existing OcspEntry. */
  31144. single = resp->single;
  31145. }
  31146. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  31147. /* Allocate and use a new OCSP entry if this is used. */
  31148. if (single->used) {
  31149. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  31150. DYNAMIC_TYPE_OCSP_ENTRY);
  31151. if (single->next == NULL) {
  31152. ret = MEMORY_E;
  31153. }
  31154. else {
  31155. XMEMSET(single->next, 0, sizeof(OcspEntry));
  31156. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  31157. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31158. if (single->next->status == NULL) {
  31159. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31160. single->next = NULL;
  31161. ret = MEMORY_E;
  31162. }
  31163. else {
  31164. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  31165. /* Entry to be freed. */
  31166. single->next->isDynamic = 1;
  31167. /* used will be 0 (false) */
  31168. single = single->next;
  31169. }
  31170. }
  31171. }
  31172. if (ret == 0) {
  31173. /* Decode SingleResponse into OcspEntry. */
  31174. ret = DecodeSingleResponse(source, &idx,
  31175. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  31176. (int)dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  31177. /* single->used set on successful decode. */
  31178. }
  31179. }
  31180. /* Check if there were extensions. */
  31181. if ((ret == 0) &&
  31182. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  31183. /* Get index of [1] */
  31184. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  31185. /* Decode the response extensions. */
  31186. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  31187. ret = ASN_PARSE_E;
  31188. }
  31189. }
  31190. FREE_ASNGETDATA(dataASN, resp->heap);
  31191. return ret;
  31192. #endif
  31193. }
  31194. #ifndef WOLFSSL_ASN_TEMPLATE
  31195. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31196. static int DecodeCerts(byte* source,
  31197. word32* ioIndex, OcspResponse* resp, word32 size)
  31198. {
  31199. word32 idx = *ioIndex;
  31200. byte tag;
  31201. WOLFSSL_ENTER("DecodeCerts");
  31202. if (GetASNTag(source, &idx, &tag, size) < 0)
  31203. return ASN_PARSE_E;
  31204. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  31205. {
  31206. int length;
  31207. if (GetLength(source, &idx, &length, size) < 0)
  31208. return ASN_PARSE_E;
  31209. if (GetSequence(source, &idx, &length, size) < 0)
  31210. return ASN_PARSE_E;
  31211. resp->cert = source + idx;
  31212. resp->certSz = length;
  31213. idx += length;
  31214. }
  31215. *ioIndex = idx;
  31216. return 0;
  31217. }
  31218. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31219. #endif /* !WOLFSSL_ASN_TEMPLATE */
  31220. #ifdef WOLFSSL_ASN_TEMPLATE
  31221. /* ASN.1 template for BasicOCSPResponse.
  31222. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31223. */
  31224. static const ASNItem ocspBasicRespASN[] = {
  31225. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31226. /* tbsResponseData */
  31227. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  31228. /* signatureAlgorithm */
  31229. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  31230. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  31231. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  31232. /* parameters */
  31233. #ifdef WC_RSA_PSS
  31234. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  31235. #endif
  31236. /* signature */
  31237. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  31238. /* certs */
  31239. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31240. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  31241. };
  31242. enum {
  31243. OCSPBASICRESPASN_IDX_SEQ = 0,
  31244. OCSPBASICRESPASN_IDX_TBS_SEQ,
  31245. OCSPBASICRESPASN_IDX_SIGALGO,
  31246. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  31247. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  31248. #ifdef WC_RSA_PSS
  31249. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  31250. #endif
  31251. OCSPBASICRESPASN_IDX_SIGNATURE,
  31252. OCSPBASICRESPASN_IDX_CERTS,
  31253. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  31254. };
  31255. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  31256. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  31257. #endif /* WOLFSSL_ASN_TEMPLATE */
  31258. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  31259. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  31260. {
  31261. #ifndef WOLFSSL_ASN_TEMPLATE
  31262. int length;
  31263. word32 idx = *ioIndex;
  31264. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31265. word32 end_index;
  31266. #endif
  31267. int ret;
  31268. int sigLength;
  31269. const byte* sigParams = NULL;
  31270. word32 sigParamsSz = 0;
  31271. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31272. (void)heap;
  31273. if (GetSequence(source, &idx, &length, size) < 0)
  31274. return ASN_PARSE_E;
  31275. if (idx + length > size)
  31276. return ASN_INPUT_E;
  31277. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31278. end_index = idx + length;
  31279. #endif
  31280. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  31281. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31282. /* Get the signature algorithm */
  31283. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  31284. return ASN_PARSE_E;
  31285. }
  31286. #ifdef WC_RSA_PSS
  31287. else if (resp->sigOID == CTC_RSASSAPSS) {
  31288. word32 sz;
  31289. int len;
  31290. const byte* params;
  31291. sz = idx;
  31292. params = source + idx;
  31293. if (GetSequence(source, &idx, &len, size) < 0)
  31294. ret = ASN_PARSE_E;
  31295. if (ret == 0) {
  31296. idx += len;
  31297. sigParams = params;
  31298. sigParamsSz = idx - sz;
  31299. }
  31300. }
  31301. #endif
  31302. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31303. if (ret != 0)
  31304. return ret;
  31305. resp->sigSz = sigLength;
  31306. resp->sig = source + idx;
  31307. idx += sigLength;
  31308. /*
  31309. * Check the length of the BasicOcspResponse against the current index to
  31310. * see if there are certificates, they are optional.
  31311. */
  31312. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31313. if (idx < end_index)
  31314. {
  31315. int cert_inited = 0;
  31316. #ifdef WOLFSSL_SMALL_STACK
  31317. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31318. DYNAMIC_TYPE_TMP_BUFFER);
  31319. if (cert == NULL)
  31320. return MEMORY_E;
  31321. #else
  31322. DecodedCert cert[1];
  31323. #endif
  31324. do {
  31325. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31326. ret = ASN_PARSE_E;
  31327. break;
  31328. }
  31329. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31330. cert_inited = 1;
  31331. /* Don't verify if we don't have access to Cert Manager. */
  31332. ret = ParseCertRelative(cert, CERT_TYPE,
  31333. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31334. cm);
  31335. if (ret < 0) {
  31336. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31337. break;
  31338. }
  31339. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31340. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31341. if (XMEMCMP(cert->subjectHash,
  31342. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31343. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31344. }
  31345. else {
  31346. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31347. #ifdef OPENSSL_EXTRA
  31348. resp->verifyError = OCSP_BAD_ISSUER;
  31349. #else
  31350. ret = BAD_OCSP_RESPONDER;
  31351. break;
  31352. #endif
  31353. }
  31354. }
  31355. #endif
  31356. /* ConfirmSignature is blocking here */
  31357. ret = ConfirmSignature(
  31358. &cert->sigCtx,
  31359. resp->response, resp->responseSz,
  31360. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31361. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31362. NULL);
  31363. if (ret != 0) {
  31364. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31365. ret = ASN_OCSP_CONFIRM_E;
  31366. break;
  31367. }
  31368. } while(0);
  31369. if (cert_inited)
  31370. FreeDecodedCert(cert);
  31371. #ifdef WOLFSSL_SMALL_STACK
  31372. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31373. #endif
  31374. if (ret != 0)
  31375. return ret;
  31376. }
  31377. else
  31378. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31379. {
  31380. Signer* ca;
  31381. int sigValid = -1;
  31382. #ifndef NO_SKID
  31383. ca = GetCA(cm, resp->single->issuerKeyHash);
  31384. #else
  31385. ca = GetCA(cm, resp->single->issuerHash);
  31386. #endif
  31387. if (ca) {
  31388. SignatureCtx sigCtx;
  31389. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31390. /* ConfirmSignature is blocking here */
  31391. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31392. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31393. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31394. NULL);
  31395. }
  31396. if (ca == NULL || sigValid != 0) {
  31397. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31398. return ASN_OCSP_CONFIRM_E;
  31399. }
  31400. (void)noVerify;
  31401. }
  31402. *ioIndex = idx;
  31403. return 0;
  31404. #else
  31405. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31406. int ret = 0;
  31407. word32 idx = *ioIndex;
  31408. const byte* sigParams = NULL;
  31409. word32 sigParamsSz = 0;
  31410. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31411. #ifdef WOLFSSL_SMALL_STACK
  31412. DecodedCert* cert = NULL;
  31413. #else
  31414. DecodedCert cert[1];
  31415. #endif
  31416. int certInit = 0;
  31417. #endif
  31418. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31419. (void)heap;
  31420. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31421. if (ret == 0) {
  31422. /* Set expecting signature OID. */
  31423. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31424. /* Decode BasicOCSPResponse. */
  31425. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31426. 1, source, &idx, size);
  31427. }
  31428. if (ret == 0) {
  31429. word32 dataIdx = 0;
  31430. /* Decode the response data. */
  31431. if (DecodeResponseData(
  31432. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31433. &dataIdx, resp,
  31434. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31435. ) < 0) {
  31436. ret = ASN_PARSE_E;
  31437. }
  31438. }
  31439. #ifdef WC_RSA_PSS
  31440. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31441. sigParams = GetASNItem_Addr(
  31442. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31443. source);
  31444. sigParamsSz =
  31445. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31446. source);
  31447. }
  31448. #endif
  31449. if (ret == 0) {
  31450. /* Get the signature OID and signature. */
  31451. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31452. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31453. &resp->sigSz);
  31454. }
  31455. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31456. if ((ret == 0) &&
  31457. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31458. /* TODO: support more than one certificate. */
  31459. /* Store reference to certificate BER data. */
  31460. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31461. &resp->certSz);
  31462. /* Allocate a certificate object to decode cert into. */
  31463. #ifdef WOLFSSL_SMALL_STACK
  31464. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31465. DYNAMIC_TYPE_TMP_BUFFER);
  31466. if (cert == NULL) {
  31467. ret = MEMORY_E;
  31468. }
  31469. }
  31470. if ((ret == 0) &&
  31471. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31472. #endif
  31473. /* Initialize the certificate object. */
  31474. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31475. certInit = 1;
  31476. /* Parse the certificate and don't verify if we don't have access to
  31477. * Cert Manager. */
  31478. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31479. cm);
  31480. if (ret < 0) {
  31481. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31482. }
  31483. }
  31484. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31485. if ((ret == 0) &&
  31486. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL) &&
  31487. !noVerify) {
  31488. ret = CheckOcspResponder(resp, cert, cm);
  31489. }
  31490. #endif /* WOLFSSL_NO_OCSP_ISSUER_CHECK */
  31491. if ((ret == 0) &&
  31492. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31493. /* TODO: ConfirmSignature is blocking here */
  31494. /* Check the signature of the response. */
  31495. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31496. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31497. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31498. if (ret != 0) {
  31499. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31500. ret = ASN_OCSP_CONFIRM_E;
  31501. }
  31502. }
  31503. if ((ret == 0) &&
  31504. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31505. #else
  31506. if (ret == 0)
  31507. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31508. {
  31509. Signer* ca;
  31510. int sigValid = -1;
  31511. /* Resonse didn't have a certificate - lookup CA. */
  31512. #ifndef NO_SKID
  31513. ca = GetCA(cm, resp->single->issuerKeyHash);
  31514. #else
  31515. ca = GetCA(cm, resp->single->issuerHash);
  31516. #endif
  31517. if (ca) {
  31518. SignatureCtx sigCtx;
  31519. /* Initialize he signature context. */
  31520. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31521. /* TODO: ConfirmSignature is blocking here */
  31522. /* Check the signature of the response CA public key. */
  31523. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31524. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31525. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31526. NULL);
  31527. }
  31528. if ((ca == NULL) || (sigValid != 0)) {
  31529. /* Didn't find certificate or signature verificate failed. */
  31530. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31531. ret = ASN_OCSP_CONFIRM_E;
  31532. }
  31533. }
  31534. if (ret == 0) {
  31535. /* Update the position to after response data. */
  31536. *ioIndex = idx;
  31537. }
  31538. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31539. if (certInit) {
  31540. FreeDecodedCert(cert);
  31541. }
  31542. #ifdef WOLFSSL_SMALL_STACK
  31543. if (cert != NULL) {
  31544. /* Dispose of certificate object. */
  31545. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31546. }
  31547. #endif
  31548. #endif
  31549. FREE_ASNGETDATA(dataASN, heap);
  31550. return ret;
  31551. #endif /* WOLFSSL_ASN_TEMPLATE */
  31552. }
  31553. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31554. byte* source, word32 inSz, void* heap)
  31555. {
  31556. WOLFSSL_ENTER("InitOcspResponse");
  31557. XMEMSET(status, 0, sizeof(CertStatus));
  31558. XMEMSET(single, 0, sizeof(OcspEntry));
  31559. XMEMSET(resp, 0, sizeof(OcspResponse));
  31560. single->status = status;
  31561. resp->responseStatus = -1;
  31562. resp->single = single;
  31563. resp->source = source;
  31564. resp->maxIdx = inSz;
  31565. resp->heap = heap;
  31566. }
  31567. void FreeOcspResponse(OcspResponse* resp)
  31568. {
  31569. OcspEntry *single, *next;
  31570. if (resp != NULL) {
  31571. for (single = resp->single; single; single = next) {
  31572. next = single->next;
  31573. if (single->isDynamic) {
  31574. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31575. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31576. }
  31577. }
  31578. }
  31579. }
  31580. #ifdef WOLFSSL_ASN_TEMPLATE
  31581. /* ASN.1 template for OCSPResponse.
  31582. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31583. */
  31584. static const ASNItem ocspResponseASN[] = {
  31585. /* OCSPResponse ::= SEQUENCE */
  31586. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31587. /* responseStatus OCSPResponseStatus */
  31588. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31589. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31590. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31591. /* ResponseBytes ::= SEQUENCE */
  31592. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31593. /* responseType OBJECT IDENTIFIER */
  31594. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31595. /* response OCTET STRING */
  31596. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  31597. };
  31598. enum {
  31599. OCSPRESPONSEASN_IDX_SEQ = 0,
  31600. OCSPRESPONSEASN_IDX_STATUS,
  31601. OCSPRESPONSEASN_IDX_BYTES,
  31602. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  31603. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  31604. OCSPRESPONSEASN_IDX_BYTES_VAL,
  31605. };
  31606. /* Number of items in ASN.1 template for OCSPResponse. */
  31607. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  31608. #endif /* WOLFSSL_ASN_TEMPLATE */
  31609. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  31610. {
  31611. #ifndef WOLFSSL_ASN_TEMPLATE
  31612. int ret;
  31613. int length = 0;
  31614. word32 idx = 0;
  31615. byte* source = resp->source;
  31616. word32 size = resp->maxIdx;
  31617. word32 oid;
  31618. byte tag;
  31619. WOLFSSL_ENTER("OcspResponseDecode");
  31620. /* peel the outer SEQUENCE wrapper */
  31621. if (GetSequence(source, &idx, &length, size) < 0) {
  31622. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31623. return ASN_PARSE_E;
  31624. }
  31625. /* First get the responseStatus, an ENUMERATED */
  31626. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  31627. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31628. return ASN_PARSE_E;
  31629. }
  31630. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  31631. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31632. return 0;
  31633. }
  31634. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  31635. if (idx >= size) {
  31636. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31637. return ASN_PARSE_E;
  31638. }
  31639. if (GetASNTag(source, &idx, &tag, size) < 0) {
  31640. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31641. return ASN_PARSE_E;
  31642. }
  31643. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  31644. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31645. return ASN_PARSE_E;
  31646. }
  31647. if (GetLength(source, &idx, &length, size) < 0) {
  31648. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31649. return ASN_PARSE_E;
  31650. }
  31651. /* Get the responseBytes SEQUENCE */
  31652. if (GetSequence(source, &idx, &length, size) < 0) {
  31653. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31654. return ASN_PARSE_E;
  31655. }
  31656. /* Check ObjectID for the resposeBytes */
  31657. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  31658. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31659. return ASN_PARSE_E;
  31660. }
  31661. if (oid != OCSP_BASIC_OID) {
  31662. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31663. return ASN_PARSE_E;
  31664. }
  31665. ret = GetOctetString(source, &idx, &length, size);
  31666. if (ret < 0) {
  31667. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31668. return ret;
  31669. }
  31670. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  31671. if (ret < 0) {
  31672. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31673. return ret;
  31674. }
  31675. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31676. return 0;
  31677. #else
  31678. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  31679. int ret = 0;
  31680. word32 idx = 0, size = resp->maxIdx;
  31681. byte* source = resp->source;
  31682. byte status;
  31683. byte* basic;
  31684. word32 basicSz;
  31685. WOLFSSL_ENTER("OcspResponseDecode");
  31686. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  31687. if (ret == 0) {
  31688. /* Set variable to put status in and expect OCSP OID. */
  31689. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  31690. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  31691. /* Decode OCSPResponse (and ResponseBytes). */
  31692. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  31693. source, &idx, size);
  31694. }
  31695. if (ret == 0) {
  31696. /* Get response. */
  31697. resp->responseStatus = status;
  31698. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  31699. == OCSP_BASIC_OID) {
  31700. /* Get reference to BasicOCSPResponse. */
  31701. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  31702. &basicSz);
  31703. idx = 0;
  31704. /* Decode BasicOCSPResponse. */
  31705. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  31706. noVerify);
  31707. }
  31708. /* Only support BasicOCSPResponse. */
  31709. else {
  31710. ret = ASN_PARSE_E;
  31711. }
  31712. }
  31713. FREE_ASNGETDATA(dataASN, resp->heap);
  31714. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31715. return ret;
  31716. #endif /* WOLFSSL_ASN_TEMPLATE */
  31717. }
  31718. #ifdef WOLFSSL_ASN_TEMPLATE
  31719. /* ASN.1 template for OCSP nonce extension.
  31720. * RFC 6960, 4.4.1 - Nonce
  31721. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  31722. */
  31723. static const ASNItem ocspNonceExtASN[] = {
  31724. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31725. /* Extension */
  31726. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31727. /* extnId */
  31728. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  31729. /* critcal not encoded. */
  31730. /* extnValue */
  31731. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  31732. /* nonce */
  31733. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  31734. };
  31735. enum {
  31736. OCSPNONCEEXTASN_IDX_SEQ = 0,
  31737. OCSPNONCEEXTASN_IDX_EXT,
  31738. OCSPNONCEEXTASN_IDX_EXT_OID,
  31739. OCSPNONCEEXTASN_IDX_EXT_VAL,
  31740. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  31741. };
  31742. /* Number of items in ASN.1 template for OCSP nonce extension. */
  31743. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  31744. #endif /* WOLFSSL_ASN_TEMPLATE */
  31745. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  31746. {
  31747. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  31748. 0x30, 0x01, 0x02 };
  31749. #ifndef WOLFSSL_ASN_TEMPLATE
  31750. byte seqArray[5][MAX_SEQ_SZ];
  31751. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  31752. WOLFSSL_ENTER("SetOcspReqExtensions");
  31753. if (!req || !output || !req->nonceSz)
  31754. return 0;
  31755. totalSz += req->nonceSz;
  31756. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  31757. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  31758. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  31759. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  31760. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  31761. if (totalSz > size)
  31762. return 0;
  31763. totalSz = 0;
  31764. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  31765. totalSz += seqSz[4];
  31766. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  31767. totalSz += seqSz[3];
  31768. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  31769. totalSz += seqSz[2];
  31770. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  31771. totalSz += (word32)sizeof(NonceObjId);
  31772. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  31773. totalSz += seqSz[1];
  31774. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  31775. totalSz += seqSz[0];
  31776. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  31777. totalSz += req->nonceSz;
  31778. return totalSz;
  31779. #else
  31780. int ret = 0;
  31781. WOLFSSL_ENTER("SetOcspReqExtensions");
  31782. /* Check request has nonce to write in extension. */
  31783. if (req != NULL && req->nonceSz != 0) {
  31784. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  31785. int sz;
  31786. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  31787. /* Set nonce extension OID and nonce. */
  31788. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  31789. sizeof(NonceObjId));
  31790. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  31791. (word32)req->nonceSz);
  31792. /* Calculate size of nonce extension. */
  31793. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31794. &sz);
  31795. /* Check buffer big enough for encoding if supplied. */
  31796. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31797. ret = BUFFER_E;
  31798. }
  31799. if ((ret == 0) && (output != NULL)) {
  31800. /* Encode nonce extension. */
  31801. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31802. output);
  31803. }
  31804. if (ret == 0) {
  31805. /* Return size of encoding. */
  31806. ret = sz;
  31807. }
  31808. FREE_ASNSETDATA(dataASN, req->heap);
  31809. }
  31810. return (word32)ret;
  31811. #endif /* WOLFSSL_ASN_TEMPLATE */
  31812. }
  31813. #ifdef WOLFSSL_ASN_TEMPLATE
  31814. /* ASN.1 template for OCSPRequest.
  31815. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  31816. */
  31817. static const ASNItem ocspRequestASN[] = {
  31818. /* OCSPRequest */
  31819. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31820. /* tbsRequest */
  31821. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31822. /* version not written - v1 */
  31823. /* requestorName not written */
  31824. /* requestList */
  31825. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31826. /* Request */
  31827. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  31828. /* reqCert */
  31829. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  31830. /* hashAlgorithm */
  31831. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  31832. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  31833. /* issuerNameHash */
  31834. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31835. /* issuerKeyHash */
  31836. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31837. /* serialNumber */
  31838. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  31839. /* requestExtensions */
  31840. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  31841. /* optionalSignature not written. */
  31842. };
  31843. enum {
  31844. OCSPREQUESTASN_IDX_SEQ = 0,
  31845. OCSPREQUESTASN_IDX_TBS,
  31846. OCSPREQUESTASN_IDX_TBS_SEQ,
  31847. OCSPREQUESTASN_IDX_TBS_LIST,
  31848. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  31849. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  31850. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  31851. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  31852. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  31853. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  31854. OCSPREQUESTASN_IDX_TBS_REQEXT,
  31855. };
  31856. /* Number of items in ASN.1 template for OCSPRequest. */
  31857. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  31858. #endif
  31859. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  31860. {
  31861. #ifndef WOLFSSL_ASN_TEMPLATE
  31862. byte seqArray[5][MAX_SEQ_SZ];
  31863. /* The ASN.1 of the OCSP Request is an onion of sequences */
  31864. byte algoArray[MAX_ALGO_SZ];
  31865. byte issuerArray[MAX_ENCODED_DIG_SZ];
  31866. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  31867. byte snArray[MAX_SN_SZ];
  31868. byte extArray[MAX_OCSP_EXT_SZ];
  31869. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  31870. int i, snSz;
  31871. int keyIdSz;
  31872. WOLFSSL_ENTER("EncodeOcspRequest");
  31873. #ifdef NO_SHA
  31874. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  31875. keyIdSz = WC_SHA256_DIGEST_SIZE;
  31876. #else
  31877. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  31878. keyIdSz = WC_SHA_DIGEST_SIZE;
  31879. #endif
  31880. issuerSz = SetDigest(req->issuerHash, keyIdSz, issuerArray);
  31881. issuerKeySz = SetDigest(req->issuerKeyHash, keyIdSz, issuerKeyArray);
  31882. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  31883. MAX_SN_SZ, MAX_SN_SZ);
  31884. extSz = 0;
  31885. if (snSz < 0)
  31886. return snSz;
  31887. if (req->nonceSz) {
  31888. /* TLS Extensions use this function too - put extensions after
  31889. * ASN.1: Context Specific [2].
  31890. */
  31891. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  31892. OCSP_NONCE_EXT_SZ);
  31893. extSz += SetExplicit(2, extSz, extArray);
  31894. }
  31895. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  31896. for (i = 4; i >= 0; i--) {
  31897. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  31898. totalSz += seqSz[i];
  31899. if (i == 2) totalSz += extSz;
  31900. }
  31901. if (output == NULL)
  31902. return totalSz;
  31903. if (totalSz > size)
  31904. return BUFFER_E;
  31905. totalSz = 0;
  31906. for (i = 0; i < 5; i++) {
  31907. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  31908. totalSz += seqSz[i];
  31909. }
  31910. XMEMCPY(output + totalSz, algoArray, algoSz);
  31911. totalSz += algoSz;
  31912. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  31913. totalSz += issuerSz;
  31914. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  31915. totalSz += issuerKeySz;
  31916. XMEMCPY(output + totalSz, snArray, snSz);
  31917. totalSz += snSz;
  31918. if (extSz != 0) {
  31919. XMEMCPY(output + totalSz, extArray, extSz);
  31920. totalSz += extSz;
  31921. }
  31922. return totalSz;
  31923. #else
  31924. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  31925. word32 extSz = 0;
  31926. int sz = 0;
  31927. int ret = 0;
  31928. word32 keyIdSz;
  31929. WOLFSSL_ENTER("EncodeOcspRequest");
  31930. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  31931. if (ret == 0) {
  31932. /* Set OID of hash algorithm use on issuer and key. */
  31933. #ifdef NO_SHA
  31934. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  31935. oidHashType);
  31936. keyIdSz = WC_SHA256_DIGEST_SIZE;
  31937. #else
  31938. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  31939. oidHashType);
  31940. keyIdSz = WC_SHA_DIGEST_SIZE;
  31941. #endif
  31942. /* Set issuer, issuer key hash and serial number of certificate being
  31943. * checked. */
  31944. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  31945. req->issuerHash, keyIdSz);
  31946. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  31947. req->issuerKeyHash, keyIdSz);
  31948. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  31949. req->serial, (word32)req->serialSz);
  31950. /* Only extension to write is nonce - check if one to encode. */
  31951. if (req->nonceSz) {
  31952. /* Get size of extensions and leave space for them in encoding. */
  31953. ret = (int)(extSz = EncodeOcspRequestExtensions(req, NULL, 0));
  31954. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  31955. if (ret > 0) {
  31956. ret = 0;
  31957. }
  31958. }
  31959. else {
  31960. /* Don't write out extensions. */
  31961. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  31962. }
  31963. }
  31964. if (ret == 0) {
  31965. /* Calculate size of encoding. */
  31966. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  31967. &sz);
  31968. }
  31969. /* Check buffer big enough for encoding if supplied. */
  31970. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31971. ret = BUFFER_E;
  31972. }
  31973. if ((ret == 0) && (output != NULL)) {
  31974. /* Encode OCSPRequest. */
  31975. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  31976. if (req->nonceSz) {
  31977. /* Encode extensions into space provided. */
  31978. ret = (int)EncodeOcspRequestExtensions(req,
  31979. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  31980. extSz);
  31981. if (ret > 0) {
  31982. ret = 0;
  31983. }
  31984. }
  31985. }
  31986. if (ret == 0) {
  31987. /* Return size of encoding. */
  31988. ret = sz;
  31989. }
  31990. FREE_ASNSETDATA(dataASN, req->heap);
  31991. return ret;
  31992. #endif /* WOLFSSL_ASN_TEMPLATE */
  31993. }
  31994. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  31995. void* heap)
  31996. {
  31997. int ret;
  31998. WOLFSSL_ENTER("InitOcspRequest");
  31999. if (req == NULL)
  32000. return BAD_FUNC_ARG;
  32001. XMEMSET(req, 0, sizeof(OcspRequest));
  32002. req->heap = heap;
  32003. if (cert) {
  32004. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  32005. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  32006. req->serial = (byte*)XMALLOC((size_t)cert->serialSz, req->heap,
  32007. DYNAMIC_TYPE_OCSP_REQUEST);
  32008. if (req->serial == NULL)
  32009. return MEMORY_E;
  32010. XMEMCPY(req->serial, cert->serial, (size_t)cert->serialSz);
  32011. req->serialSz = cert->serialSz;
  32012. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  32013. req->url = (byte*)XMALLOC((size_t)cert->extAuthInfoSz + 1,
  32014. req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32015. if (req->url == NULL) {
  32016. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  32017. req->serial = NULL;
  32018. return MEMORY_E;
  32019. }
  32020. XMEMCPY(req->url, cert->extAuthInfo, (size_t)cert->extAuthInfoSz);
  32021. req->urlSz = cert->extAuthInfoSz;
  32022. req->url[req->urlSz] = 0;
  32023. }
  32024. }
  32025. if (useNonce) {
  32026. WC_RNG rng;
  32027. #ifndef HAVE_FIPS
  32028. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  32029. #else
  32030. ret = wc_InitRng(&rng);
  32031. #endif
  32032. if (ret != 0) {
  32033. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  32034. } else {
  32035. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  32036. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  32037. else
  32038. req->nonceSz = MAX_OCSP_NONCE_SZ;
  32039. wc_FreeRng(&rng);
  32040. }
  32041. }
  32042. return 0;
  32043. }
  32044. void FreeOcspRequest(OcspRequest* req)
  32045. {
  32046. WOLFSSL_ENTER("FreeOcspRequest");
  32047. if (req) {
  32048. if (req->serial)
  32049. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32050. req->serial = NULL;
  32051. #ifdef OPENSSL_EXTRA
  32052. if (req->serialInt) {
  32053. if (req->serialInt->isDynamic) {
  32054. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  32055. }
  32056. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  32057. }
  32058. req->serialInt = NULL;
  32059. #endif
  32060. if (req->url)
  32061. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32062. req->url = NULL;
  32063. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  32064. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_APACHE_HTTPD) || \
  32065. defined(HAVE_LIGHTY)
  32066. if (req->cid != NULL)
  32067. wolfSSL_OCSP_CERTID_free((WOLFSSL_OCSP_CERTID*)req->cid);
  32068. req->cid = NULL;
  32069. #endif
  32070. }
  32071. }
  32072. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  32073. {
  32074. int cmp = -1; /* default as not matching, cmp gets set on each check */
  32075. int ocspDigestSize;
  32076. OcspEntry *single, *next, *prev = NULL, *top;
  32077. WOLFSSL_ENTER("CompareOcspReqResp");
  32078. if (req == NULL) {
  32079. WOLFSSL_MSG("\tReq missing");
  32080. return -1;
  32081. }
  32082. if (resp == NULL || resp->single == NULL) {
  32083. WOLFSSL_MSG("\tResp missing");
  32084. return 1;
  32085. }
  32086. /* Nonces are not critical. The responder may not necessarily add
  32087. * the nonce to the response. */
  32088. if (req->nonceSz && resp->nonce != NULL
  32089. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  32090. && resp->nonceSz != 0
  32091. #endif
  32092. ) {
  32093. cmp = req->nonceSz - resp->nonceSz;
  32094. if (cmp != 0) {
  32095. WOLFSSL_MSG("\tnonceSz mismatch");
  32096. return cmp;
  32097. }
  32098. cmp = XMEMCMP(req->nonce, resp->nonce, (size_t)req->nonceSz);
  32099. if (cmp != 0) {
  32100. WOLFSSL_MSG("\tnonce mismatch");
  32101. return cmp;
  32102. }
  32103. }
  32104. /* match based on found status and return */
  32105. for (single = resp->single; single; single = next) {
  32106. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  32107. ocspDigestSize = wc_HashGetDigestSize(
  32108. wc_OidGetHash(single->hashAlgoOID));
  32109. #else
  32110. ocspDigestSize = OCSP_DIGEST_SIZE;
  32111. #endif
  32112. cmp = req->serialSz - single->status->serialSz;
  32113. if (cmp == 0) {
  32114. cmp = XMEMCMP(req->serial, single->status->serial,
  32115. (size_t)req->serialSz)
  32116. || XMEMCMP(req->issuerHash, single->issuerHash,
  32117. (size_t)ocspDigestSize)
  32118. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash,
  32119. (size_t)ocspDigestSize);
  32120. if (cmp == 0) {
  32121. /* match found */
  32122. if (resp->single != single && prev) {
  32123. /* move to top of list */
  32124. top = resp->single;
  32125. resp->single = single;
  32126. prev->next = single->next;
  32127. single->next = top;
  32128. }
  32129. break;
  32130. }
  32131. }
  32132. next = single->next;
  32133. prev = single;
  32134. }
  32135. if (cmp != 0) {
  32136. WOLFSSL_MSG("\trequest and response mismatch");
  32137. return cmp;
  32138. }
  32139. return 0;
  32140. }
  32141. #endif /* HAVE_OCSP */
  32142. #ifdef WOLFSSL_ASN_TEMPLATE
  32143. /* ASN.1 template for certificate name hash. */
  32144. static const ASNItem nameHashASN[] = {
  32145. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  32146. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  32147. };
  32148. enum {
  32149. NAMEHASHASN_IDX_OID = 0,
  32150. NAMEHASHASN_IDX_NAME
  32151. };
  32152. /* Number of items in ASN.1 template for certificate name hash. */
  32153. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  32154. #endif /* WOLFSSL_ASN_TEMPLATE */
  32155. /* store WC_SHA hash of NAME */
  32156. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  32157. {
  32158. /* Use summy signature OID. */
  32159. return GetNameHash_ex(source, idx, hash, maxIdx, 0);
  32160. }
  32161. /* store WC_SHA hash of NAME */
  32162. int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx,
  32163. word32 sigOID)
  32164. {
  32165. #ifndef WOLFSSL_ASN_TEMPLATE
  32166. int length; /* length of all distinguished names */
  32167. int ret;
  32168. word32 dummy;
  32169. byte tag;
  32170. WOLFSSL_ENTER("GetNameHash");
  32171. dummy = *idx;
  32172. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  32173. tag == ASN_OBJECT_ID) {
  32174. WOLFSSL_MSG("Trying optional prefix...");
  32175. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  32176. return ASN_PARSE_E;
  32177. *idx += (word32)length;
  32178. WOLFSSL_MSG("Got optional prefix");
  32179. }
  32180. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  32181. * calculated over the entire DER encoding of the Name field, including
  32182. * the tag and length. */
  32183. dummy = *idx;
  32184. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  32185. return ASN_PARSE_E;
  32186. ret = CalcHashId_ex(source + dummy, (word32)length + *idx - dummy, hash,
  32187. HashIdAlg(sigOID));
  32188. *idx += (word32)length;
  32189. return ret;
  32190. #else
  32191. ASNGetData dataASN[nameHashASN_Length];
  32192. int ret;
  32193. XMEMSET(dataASN, 0, sizeof(dataASN));
  32194. /* Ignore the OID even when present. */
  32195. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  32196. /* Decode certificate name. */
  32197. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  32198. (word32)maxIdx);
  32199. if (ret == 0) {
  32200. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  32201. * calculated over the entire DER encoding of the Name field, including
  32202. * the tag and length. */
  32203. /* Calculate hash of complete name including SEQUENCE. */
  32204. ret = CalcHashId_ex(
  32205. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  32206. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  32207. hash, HashIdAlg(sigOID));
  32208. }
  32209. return ret;
  32210. #endif /* WOLFSSL_ASN_TEMPLATE */
  32211. }
  32212. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  32213. #ifdef OPENSSL_EXTRA
  32214. static char* GetNameFromDer(const byte* source, int sz)
  32215. {
  32216. char* out;
  32217. out = (char*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_OPENSSL);
  32218. if (out == NULL) {
  32219. WOLFSSL_MSG("Name malloc failed");
  32220. return NULL;
  32221. }
  32222. XMEMCPY(out, source, (size_t)sz);
  32223. return out;
  32224. }
  32225. #endif
  32226. /* initialize decoded CRL */
  32227. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  32228. {
  32229. WOLFSSL_MSG("InitDecodedCRL");
  32230. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  32231. dcrl->heap = heap;
  32232. #ifdef WOLFSSL_HEAP_TEST
  32233. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  32234. #endif
  32235. }
  32236. /* free decoded CRL resources */
  32237. void FreeDecodedCRL(DecodedCRL* dcrl)
  32238. {
  32239. RevokedCert* tmp = dcrl->certs;
  32240. WOLFSSL_MSG("FreeDecodedCRL");
  32241. while(tmp) {
  32242. RevokedCert* next = tmp->next;
  32243. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32244. tmp = next;
  32245. }
  32246. #ifdef OPENSSL_EXTRA
  32247. if (dcrl->issuer != NULL)
  32248. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  32249. #endif
  32250. }
  32251. #ifdef WOLFSSL_ASN_TEMPLATE
  32252. /* ASN.1 template for revoked certificates.
  32253. * X.509: RFC 5280, 5.1 - CRL Fields
  32254. */
  32255. static const ASNItem revokedASN[] = {
  32256. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32257. /* userCertificate CertificateSerialNumber */
  32258. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  32259. /* revocationDate Time */
  32260. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  32261. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32262. /* crlEntryExensions Extensions */
  32263. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  32264. };
  32265. enum {
  32266. REVOKEDASN_IDX_SEQ = 0,
  32267. REVOKEDASN_IDX_CERT,
  32268. REVOKEDASN_IDX_TIME_UTC,
  32269. REVOKEDASN_IDX_TIME_GT,
  32270. REVOKEDASN_IDX_TIME_EXT,
  32271. };
  32272. /* Number of items in ASN.1 template for revoked certificates. */
  32273. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  32274. #endif
  32275. /* Get Revoked Cert list, 0 on success */
  32276. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  32277. DecodedCRL* dcrl, word32 maxIdx)
  32278. {
  32279. #ifndef WOLFSSL_ASN_TEMPLATE
  32280. int ret;
  32281. int len;
  32282. word32 end;
  32283. RevokedCert* rc;
  32284. #ifdef CRL_STATIC_REVOKED_LIST
  32285. int totalCerts = 0;
  32286. #endif
  32287. WOLFSSL_ENTER("GetRevoked");
  32288. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  32289. return ASN_PARSE_E;
  32290. end = *idx + len;
  32291. #ifdef CRL_STATIC_REVOKED_LIST
  32292. totalCerts = dcrl->totalCerts;
  32293. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32294. return MEMORY_E;
  32295. }
  32296. rc = &rcert[totalCerts];
  32297. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32298. if (ret < 0) {
  32299. WOLFSSL_MSG("wc_GetSerialNumber error");
  32300. return ret;
  32301. }
  32302. #else
  32303. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32304. DYNAMIC_TYPE_REVOKED);
  32305. if (rc == NULL) {
  32306. WOLFSSL_MSG("Alloc Revoked Cert failed");
  32307. return MEMORY_E;
  32308. }
  32309. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32310. if (ret < 0) {
  32311. WOLFSSL_MSG("wc_GetSerialNumber error");
  32312. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32313. return ret;
  32314. }
  32315. /* add to list */
  32316. rc->next = dcrl->certs;
  32317. dcrl->certs = rc;
  32318. (void)rcert;
  32319. #endif /* CRL_STATIC_REVOKED_LIST */
  32320. dcrl->totalCerts++;
  32321. /* get date */
  32322. #ifndef NO_ASN_TIME
  32323. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  32324. if (ret < 0) {
  32325. WOLFSSL_MSG("Expecting Date");
  32326. return ret;
  32327. }
  32328. #endif
  32329. /* skip extensions */
  32330. *idx = end;
  32331. return 0;
  32332. #else
  32333. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32334. int ret = 0;
  32335. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32336. word32 revDateSz = MAX_DATE_SIZE;
  32337. RevokedCert* rc;
  32338. #ifdef CRL_STATIC_REVOKED_LIST
  32339. int totalCerts = dcrl->totalCerts;
  32340. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32341. return MEMORY_E;
  32342. }
  32343. rc = &rcert[totalCerts];
  32344. #else
  32345. /* Allocate a new revoked certificate object. */
  32346. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32347. DYNAMIC_TYPE_CRL);
  32348. if (rc == NULL) {
  32349. ret = MEMORY_E;
  32350. }
  32351. #endif /* CRL_STATIC_REVOKED_LIST */
  32352. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32353. if (ret == 0) {
  32354. /* Set buffer to place serial number into. */
  32355. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32356. &serialSz);
  32357. /* Set buffer to store revocation date. */
  32358. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32359. &revDateSz);
  32360. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32361. &revDateSz);
  32362. /* Decode the Revoked */
  32363. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32364. maxIdx);
  32365. }
  32366. if (ret == 0) {
  32367. /* Store size of serial number. */
  32368. rc->serialSz = (int)serialSz;
  32369. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32370. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32371. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32372. /* TODO: use extensions, only v2 */
  32373. /* Add revoked certificate to chain. */
  32374. #ifndef CRL_STATIC_REVOKED_LIST
  32375. rc->next = dcrl->certs;
  32376. dcrl->certs = rc;
  32377. #endif
  32378. dcrl->totalCerts++;
  32379. }
  32380. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32381. #ifndef CRL_STATIC_REVOKED_LIST
  32382. if ((ret != 0) && (rc != NULL)) {
  32383. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32384. }
  32385. (void)rcert;
  32386. #endif
  32387. return ret;
  32388. #endif /* WOLFSSL_ASN_TEMPLATE */
  32389. }
  32390. #ifdef WOLFSSL_ASN_TEMPLATE
  32391. /* Parse the revoked certificates of a CRL.
  32392. *
  32393. * @param [in] dcrl Decoded CRL object.
  32394. * @param [in] buff Buffer holding CRL.
  32395. * @param [in] idx Index into buffer of revoked certificates.
  32396. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32397. * @return 0 on success.
  32398. * @return ASN_PARSE_E on failure.
  32399. */
  32400. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32401. const byte* buff, word32 idx, word32 maxIdx)
  32402. {
  32403. int ret = 0;
  32404. /* Parse each revoked cerificate. */
  32405. while ((ret == 0) && (idx < maxIdx)) {
  32406. /* Parse a revoked certificate. */
  32407. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32408. ret = ASN_PARSE_E;
  32409. }
  32410. }
  32411. return ret;
  32412. }
  32413. #endif /* WOLFSSL_ASN_TEMPLATE */
  32414. #ifndef WOLFSSL_ASN_TEMPLATE
  32415. /* Get CRL Signature, 0 on success */
  32416. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32417. int maxIdx)
  32418. {
  32419. int length;
  32420. int ret;
  32421. WOLFSSL_ENTER("GetCRL_Signature");
  32422. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32423. if (ret != 0)
  32424. return ret;
  32425. dcrl->sigLength = length;
  32426. dcrl->signature = (byte*)&source[*idx];
  32427. *idx += dcrl->sigLength;
  32428. return 0;
  32429. }
  32430. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32431. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32432. word32 tbsSz, const byte* signature, word32 sigSz,
  32433. word32 signatureOID, Signer *ca, void* heap)
  32434. {
  32435. /* try to confirm/verify signature */
  32436. #ifndef IGNORE_KEY_EXTENSIONS
  32437. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32438. WOLFSSL_MSG("CA cannot sign CRLs");
  32439. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32440. return ASN_CRL_NO_SIGNER_E;
  32441. }
  32442. #endif /* IGNORE_KEY_EXTENSIONS */
  32443. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32444. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32445. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32446. signatureOID, NULL, 0, NULL) != 0) {
  32447. WOLFSSL_MSG("CRL Confirm signature failed");
  32448. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32449. return ASN_CRL_CONFIRM_E;
  32450. }
  32451. return 0;
  32452. }
  32453. #ifdef WOLFSSL_ASN_TEMPLATE
  32454. /* Find the signer for the CRL and verify the signature.
  32455. *
  32456. * @param [in] dcrl Decoded CRL object.
  32457. * @param [in] buff Buffer holding CRL.
  32458. * @param [in] cm Certificate manager object.
  32459. * @return 0 on success.
  32460. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32461. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32462. */
  32463. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32464. {
  32465. int ret = 0;
  32466. Signer* ca = NULL;
  32467. SignatureCtx sigCtx;
  32468. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32469. * If experiencing issues uncomment NO_SKID define in CRL section of
  32470. * wolfssl/wolfcrypt/settings.h */
  32471. #ifndef NO_SKID
  32472. if (dcrl->extAuthKeyIdSet) {
  32473. /* more unique than issuerHash */
  32474. ca = GetCA(cm, dcrl->extAuthKeyId);
  32475. }
  32476. /* Check issuerHash matched CA's subjectNameHash. */
  32477. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32478. KEYID_SIZE) != 0)) {
  32479. ca = NULL;
  32480. }
  32481. if (ca == NULL) {
  32482. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32483. /* If AKID is available then this CA doesn't have the public
  32484. * key required */
  32485. if (ca && dcrl->extAuthKeyIdSet) {
  32486. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32487. ca = NULL;
  32488. }
  32489. }
  32490. #else
  32491. ca = GetCA(cm, dcrl->issuerHash);
  32492. #endif /* !NO_SKID */
  32493. WOLFSSL_MSG("About to verify CRL signature");
  32494. if (ca == NULL) {
  32495. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32496. ret = ASN_CRL_NO_SIGNER_E;
  32497. WOLFSSL_ERROR_VERBOSE(ret);
  32498. }
  32499. if (ret == 0) {
  32500. WOLFSSL_MSG("Found CRL issuer CA");
  32501. /* Verify CRL signature with CA. */
  32502. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32503. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32504. dcrl->signatureOID, ca, dcrl->heap);
  32505. }
  32506. return ret;
  32507. }
  32508. #endif
  32509. #ifndef WOLFSSL_ASN_TEMPLATE
  32510. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32511. const byte* buf,word32* inOutIdx, int sz, int verify)
  32512. {
  32513. word32 oid, dateIdx, idx, checkIdx;
  32514. int length;
  32515. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32516. int doNextDate = 1;
  32517. #endif
  32518. byte tag;
  32519. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32520. return BAD_FUNC_ARG;
  32521. }
  32522. /* may have version */
  32523. idx = *inOutIdx;
  32524. checkIdx = idx;
  32525. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32526. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32527. return ASN_PARSE_E;
  32528. dcrl->version++;
  32529. }
  32530. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32531. return ASN_PARSE_E;
  32532. checkIdx = idx;
  32533. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32534. return ASN_PARSE_E;
  32535. }
  32536. #ifdef OPENSSL_EXTRA
  32537. dcrl->issuerSz = length + (checkIdx - idx);
  32538. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32539. #endif
  32540. if (GetNameHash_ex(buf, &idx, dcrl->issuerHash, sz, oid) < 0)
  32541. return ASN_PARSE_E;
  32542. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32543. return ASN_PARSE_E;
  32544. dateIdx = idx;
  32545. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32546. {
  32547. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32548. (void)dateIdx;
  32549. return ASN_PARSE_E;
  32550. #else
  32551. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32552. doNextDate = 0;
  32553. idx = dateIdx;
  32554. #endif
  32555. }
  32556. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32557. if (doNextDate)
  32558. #endif
  32559. {
  32560. #ifndef NO_ASN_TIME
  32561. if (verify != NO_VERIFY &&
  32562. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32563. WOLFSSL_MSG("CRL after date is no longer valid");
  32564. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32565. return CRL_CERT_DATE_ERR;
  32566. }
  32567. #else
  32568. (void)verify;
  32569. #endif
  32570. }
  32571. checkIdx = idx;
  32572. if (idx != dcrl->sigIndex &&
  32573. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32574. int len;
  32575. if (GetSequence(buf, &idx, &len, sz) < 0)
  32576. return ASN_PARSE_E;
  32577. len += idx;
  32578. while (idx < (word32)len) {
  32579. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32580. return ASN_PARSE_E;
  32581. }
  32582. }
  32583. *inOutIdx = idx;
  32584. return 0;
  32585. }
  32586. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32587. #ifndef NO_SKID
  32588. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32589. {
  32590. #ifndef WOLFSSL_ASN_TEMPLATE
  32591. word32 idx = 0;
  32592. int length = 0, ret = 0;
  32593. byte tag;
  32594. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32595. if (GetSequence(input, &idx, &length, sz) < 0) {
  32596. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32597. return ASN_PARSE_E;
  32598. }
  32599. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  32600. return ASN_PARSE_E;
  32601. }
  32602. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  32603. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32604. return 0;
  32605. }
  32606. if (GetLength(input, &idx, &length, sz) <= 0) {
  32607. WOLFSSL_MSG("\tfail: extension data length");
  32608. return ASN_PARSE_E;
  32609. }
  32610. dcrl->extAuthKeyIdSet = 1;
  32611. /* Get the hash or hash of the hash if wrong size. */
  32612. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId,
  32613. HashIdAlg(dcrl->signatureOID));
  32614. return ret;
  32615. #else
  32616. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  32617. int ret = 0;
  32618. word32 idx = 0;
  32619. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32620. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  32621. if (ret == 0) {
  32622. /* Parse an authority key identifier. */
  32623. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  32624. &idx, (word32)sz);
  32625. }
  32626. if (ret == 0) {
  32627. /* Key id is optional. */
  32628. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  32629. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32630. }
  32631. else {
  32632. /* Get the hash or hash of the hash if wrong size. */
  32633. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  32634. (int)dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  32635. dcrl->extAuthKeyId, HashIdAlg(dcrl->signatureOID));
  32636. }
  32637. }
  32638. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32639. return ret;
  32640. #endif /* WOLFSSL_ASN_TEMPLATE */
  32641. }
  32642. #endif
  32643. #ifndef WOLFSSL_ASN_TEMPLATE
  32644. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  32645. word32* inOutIdx, word32 sz)
  32646. {
  32647. int length;
  32648. word32 idx;
  32649. word32 ext_bound; /* boundary index for the sequence of extensions */
  32650. word32 oid;
  32651. byte tag;
  32652. WOLFSSL_ENTER("ParseCRL_Extensions");
  32653. (void)dcrl;
  32654. if (inOutIdx == NULL)
  32655. return BAD_FUNC_ARG;
  32656. idx = *inOutIdx;
  32657. /* CRL Extensions are optional */
  32658. if ((idx + 1) > sz)
  32659. return 0;
  32660. /* CRL Extensions are optional */
  32661. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  32662. return 0;
  32663. /* CRL Extensions are optional */
  32664. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  32665. return 0;
  32666. if (GetLength(buf, &idx, &length, sz) < 0)
  32667. return ASN_PARSE_E;
  32668. if (GetSequence(buf, &idx, &length, sz) < 0)
  32669. return ASN_PARSE_E;
  32670. ext_bound = idx + length;
  32671. while (idx < (word32)ext_bound) {
  32672. word32 localIdx;
  32673. int ret;
  32674. if (GetSequence(buf, &idx, &length, sz) < 0) {
  32675. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32676. return ASN_PARSE_E;
  32677. }
  32678. oid = 0;
  32679. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  32680. WOLFSSL_MSG("\tfail: OBJECT ID");
  32681. return ASN_PARSE_E;
  32682. }
  32683. /* check for critical flag */
  32684. if ((idx + 1) > (word32)sz) {
  32685. WOLFSSL_MSG("\tfail: malformed buffer");
  32686. return BUFFER_E;
  32687. }
  32688. localIdx = idx;
  32689. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32690. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32691. ret = GetBoolean(buf, &idx, sz);
  32692. if (ret < 0)
  32693. return ret;
  32694. }
  32695. ret = GetOctetString(buf, &idx, &length, sz);
  32696. if (ret < 0)
  32697. return ret;
  32698. if (oid == AUTH_KEY_OID) {
  32699. #ifndef NO_SKID
  32700. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32701. if (ret < 0) {
  32702. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32703. return ret;
  32704. }
  32705. #endif
  32706. }
  32707. else if (oid == CRL_NUMBER_OID) {
  32708. localIdx = idx;
  32709. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  32710. tag == ASN_INTEGER) {
  32711. ret = GetASNInt(buf, &idx, &length, sz);
  32712. if (ret < 0) {
  32713. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  32714. return ret;
  32715. }
  32716. else {
  32717. if (length > 1) {
  32718. int i;
  32719. #ifdef WOLFSSL_SMALL_STACK
  32720. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  32721. DYNAMIC_TYPE_BIGINT);
  32722. if (m == NULL) {
  32723. return MEMORY_E;
  32724. }
  32725. #else
  32726. mp_int m[1];
  32727. #endif
  32728. if (mp_init(m) != MP_OKAY) {
  32729. ret = MP_INIT_E;
  32730. }
  32731. if (ret == 0)
  32732. ret = mp_read_unsigned_bin(m, buf + idx, length);
  32733. if (ret != MP_OKAY)
  32734. ret = BUFFER_E;
  32735. if (ret == 0) {
  32736. dcrl->crlNumber = 0;
  32737. for (i = 0; i < (int)(*m).used; ++i) {
  32738. if (i > (CHAR_BIT *
  32739. (int)sizeof(word32) / DIGIT_BIT)) {
  32740. break;
  32741. }
  32742. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  32743. (DIGIT_BIT * i);
  32744. }
  32745. }
  32746. mp_free(m);
  32747. #ifdef WOLFSSL_SMALL_STACK
  32748. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  32749. #endif
  32750. if (ret != 0)
  32751. return ret;
  32752. }
  32753. else if (length == 1) {
  32754. dcrl->crlNumber = buf[idx];
  32755. }
  32756. }
  32757. }
  32758. }
  32759. idx += length;
  32760. }
  32761. *inOutIdx = idx;
  32762. return 0;
  32763. }
  32764. #else
  32765. /* Parse the extensions of a CRL.
  32766. *
  32767. * @param [in] dcrl Decoded CRL object.
  32768. * @param [in] buff Buffer holding CRL.
  32769. * @param [in] idx Index into buffer of extensions.
  32770. * @param [in] maxIdx Maximum index of extension data.
  32771. * @return 0 on success.
  32772. * @return ASN_PARSE_E on failure.
  32773. */
  32774. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  32775. word32 maxIdx)
  32776. {
  32777. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32778. int ret = 0;
  32779. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  32780. while ((ret == 0) && (idx < maxIdx)) {
  32781. byte critical = 0;
  32782. /* Clear dynamic data. */
  32783. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32784. /* Ensure OID is an extention type. */
  32785. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  32786. /* Set criticality variable. */
  32787. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  32788. /* Parse extension wrapper. */
  32789. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  32790. maxIdx);
  32791. if (ret == 0) {
  32792. /* OID in extension. */
  32793. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32794. /* Length of extension data. */
  32795. int length = (int)dataASN[CERTEXTASN_IDX_VAL].length;
  32796. if (oid == AUTH_KEY_OID) {
  32797. #ifndef NO_SKID
  32798. /* Parse Authority Key Id extesion.
  32799. * idx is at start of OCTET_STRING data. */
  32800. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32801. if (ret != 0) {
  32802. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32803. }
  32804. #endif
  32805. }
  32806. /* TODO: Parse CRL Number extension */
  32807. /* TODO: check criticality */
  32808. /* Move index on to next extension. */
  32809. idx += (word32)length;
  32810. }
  32811. }
  32812. if (ret < 0) {
  32813. ret = ASN_PARSE_E;
  32814. }
  32815. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32816. return ret;
  32817. }
  32818. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32819. #ifdef WOLFSSL_ASN_TEMPLATE
  32820. /* ASN.1 template for a CRL- CertificateList.
  32821. * X.509: RFC 5280, 5.1 - CRL Fields
  32822. */
  32823. static const ASNItem crlASN[] = {
  32824. /* CertificateList */
  32825. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32826. /* tbsCertList */
  32827. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32828. /* version Version OPTIONAL if present must be v2 */
  32829. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  32830. /* signature */
  32831. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32832. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32833. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  32834. /* issuer */
  32835. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  32836. /* thisUpdate */
  32837. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  32838. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32839. /* nextUpdate */
  32840. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  32841. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  32842. /* revokedCertificates */
  32843. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32844. /* crlExtensions */
  32845. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32846. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  32847. /* signatureAlgorithm */
  32848. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32849. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32850. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32851. /* signatureValue */
  32852. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32853. };
  32854. enum {
  32855. CRLASN_IDX_SEQ = 0,
  32856. CRLASN_IDX_TBS,
  32857. CRLASN_IDX_TBS_VER,
  32858. CRLASN_IDX_TBS_SIGALGO,
  32859. CRLASN_IDX_TBS_SIGALGO_OID,
  32860. CRLASN_IDX_TBS_SIGALGO_NULL,
  32861. CRLASN_IDX_TBS_ISSUER,
  32862. CRLASN_IDX_TBS_THISUPDATE_UTC,
  32863. CRLASN_IDX_TBS_THISUPDATE_GT,
  32864. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  32865. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  32866. CRLASN_IDX_TBS_REVOKEDCERTS,
  32867. CRLASN_IDX_TBS_EXT,
  32868. CRLASN_IDX_TBS_EXT_SEQ,
  32869. CRLASN_IDX_SIGALGO,
  32870. CRLASN_IDX_SIGALGO_OID,
  32871. CRLASN_IDX_SIGALGO_NULL,
  32872. CRLASN_IDX_SIGNATURE,
  32873. };
  32874. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  32875. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  32876. #endif
  32877. /* parse crl buffer into decoded state, 0 on success */
  32878. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  32879. int verify, void* cm)
  32880. {
  32881. #ifndef WOLFSSL_ASN_TEMPLATE
  32882. Signer* ca = NULL;
  32883. SignatureCtx sigCtx;
  32884. int ret = 0;
  32885. int len;
  32886. word32 idx = 0;
  32887. WOLFSSL_MSG("ParseCRL");
  32888. /* raw crl hash */
  32889. /* hash here if needed for optimized comparisons
  32890. * wc_Sha sha;
  32891. * wc_InitSha(&sha);
  32892. * wc_ShaUpdate(&sha, buff, sz);
  32893. * wc_ShaFinal(&sha, dcrl->crlHash); */
  32894. if (GetSequence(buff, &idx, &len, sz) < 0)
  32895. return ASN_PARSE_E;
  32896. dcrl->certBegin = idx;
  32897. /* Normalize sz for the length inside the outer sequence. */
  32898. sz = len + idx;
  32899. if (GetSequence(buff, &idx, &len, sz) < 0)
  32900. return ASN_PARSE_E;
  32901. dcrl->sigIndex = len + idx;
  32902. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  32903. return ASN_PARSE_E;
  32904. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  32905. return ASN_PARSE_E;
  32906. idx = dcrl->sigIndex;
  32907. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  32908. return ASN_PARSE_E;
  32909. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  32910. return ASN_PARSE_E;
  32911. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  32912. if experiencing issues uncomment NO_SKID define in CRL section of
  32913. wolfssl/wolfcrypt/settings.h */
  32914. #ifndef NO_SKID
  32915. if (dcrl->extAuthKeyIdSet) {
  32916. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  32917. }
  32918. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32919. KEYID_SIZE) != 0) {
  32920. ca = NULL;
  32921. }
  32922. if (ca == NULL) {
  32923. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32924. /* If AKID is available then this CA doesn't have the public
  32925. * key required */
  32926. if (ca && dcrl->extAuthKeyIdSet) {
  32927. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32928. ca = NULL;
  32929. }
  32930. }
  32931. #else
  32932. ca = GetCA(cm, dcrl->issuerHash);
  32933. #endif /* !NO_SKID */
  32934. WOLFSSL_MSG("About to verify CRL signature");
  32935. if (ca == NULL) {
  32936. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32937. ret = ASN_CRL_NO_SIGNER_E;
  32938. WOLFSSL_ERROR_VERBOSE(ret);
  32939. goto end;
  32940. }
  32941. WOLFSSL_MSG("Found CRL issuer CA");
  32942. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32943. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32944. dcrl->signatureOID, ca, dcrl->heap);
  32945. end:
  32946. return ret;
  32947. #else
  32948. DECL_ASNGETDATA(dataASN, crlASN_Length);
  32949. int ret = 0;
  32950. /* Default version - v1 = 0 */
  32951. byte version = 0;
  32952. word32 idx = 0;
  32953. /* Size of buffer for date. */
  32954. word32 lastDateSz = MAX_DATE_SIZE;
  32955. word32 nextDateSz = MAX_DATE_SIZE;
  32956. /* When NO_ASN_TIME is defined, verify not used. */
  32957. (void)verify;
  32958. WOLFSSL_MSG("ParseCRL");
  32959. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  32960. if (ret == 0) {
  32961. /* Set variable to store version. */
  32962. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  32963. /* Set expecting signature OID. */
  32964. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  32965. /* Set buffer to put last and next date into. */
  32966. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  32967. &lastDateSz);
  32968. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  32969. &lastDateSz);
  32970. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  32971. &nextDateSz);
  32972. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  32973. &nextDateSz);
  32974. /* Set expecting signature OID. */
  32975. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  32976. /* Decode the CRL. */
  32977. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  32978. }
  32979. /* Version must be v2 = 1 if present. */
  32980. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  32981. (version != 1)) {
  32982. ret = ASN_PARSE_E;
  32983. }
  32984. /* Check minimum size of last date. */
  32985. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  32986. ret = ASN_PARSE_E;
  32987. }
  32988. /* Check minimum size of next date. */
  32989. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  32990. ret = ASN_PARSE_E;
  32991. }
  32992. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  32993. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  32994. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  32995. ret = ASN_PARSE_E;
  32996. }
  32997. if (ret == 0) {
  32998. /* Store version */
  32999. dcrl->version = ++version;
  33000. /* Store offset of to be signed part. */
  33001. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  33002. /* Store index of signature. */
  33003. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  33004. /* Store address and length of signature data. */
  33005. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  33006. &dcrl->sigLength);
  33007. /* Get the signature OID. */
  33008. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  33009. /* Get the format/tag of the last and next date. */
  33010. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  33011. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  33012. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  33013. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  33014. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  33015. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  33016. #ifndef NO_ASN_TIME
  33017. if (dcrl->nextDateFormat != 0) {
  33018. /* Next date was set, so validate it. */
  33019. if (verify != NO_VERIFY &&
  33020. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  33021. WOLFSSL_MSG("CRL after date is no longer valid");
  33022. ret = CRL_CERT_DATE_ERR;
  33023. WOLFSSL_ERROR_VERBOSE(ret);
  33024. }
  33025. }
  33026. }
  33027. if (ret == 0) {
  33028. #endif
  33029. #ifdef OPENSSL_EXTRA
  33030. /* Parse and store the issuer name. */
  33031. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  33032. buff);
  33033. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  33034. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  33035. (int)dcrl->issuerSz);
  33036. #endif
  33037. /* Calculate the Hash id from the issuer name. */
  33038. ret = CalcHashId_ex(
  33039. GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  33040. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  33041. dcrl->issuerHash, HashIdAlg(dcrl->signatureOID));
  33042. if (ret < 0) {
  33043. ret = ASN_PARSE_E;
  33044. }
  33045. }
  33046. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  33047. /* Parse revoked cerificates - starting after SEQUENCE OF. */
  33048. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  33049. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  33050. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  33051. }
  33052. if (ret == 0) {
  33053. /* Parse the extensions - starting after SEQUENCE OF. */
  33054. ret = ParseCRL_Extensions(dcrl, buff,
  33055. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  33056. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  33057. }
  33058. if (ret == 0) {
  33059. /* Find signer and verify signature. */
  33060. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  33061. }
  33062. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33063. return ret;
  33064. #endif /* WOLFSSL_ASN_TEMPLATE */
  33065. }
  33066. #endif /* HAVE_CRL */
  33067. #ifdef WOLFSSL_CERT_PIV
  33068. #ifdef WOLFSSL_ASN_TEMPLATE
  33069. /* Template for PIV. */
  33070. static const ASNItem pivASN[] = {
  33071. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  33072. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  33073. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  33074. };
  33075. enum {
  33076. PIVASN_IDX_CERT = 0,
  33077. PIVASN_IDX_NONCE,
  33078. PIVASN_IDX_SIGNEDNONCE,
  33079. };
  33080. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  33081. static const ASNItem pivCertASN[] = {
  33082. /* 0x53 = 0x40 | 0x13 */
  33083. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  33084. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  33085. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  33086. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  33087. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  33088. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  33089. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  33090. };
  33091. enum {
  33092. PIVCERTASN_IDX_CERT,
  33093. PIVCERTASN_IDX_X509,
  33094. PIVCERTASN_IDX_INFO,
  33095. PIVCERTASN_IDX_ERR,
  33096. };
  33097. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  33098. #endif
  33099. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  33100. {
  33101. #ifndef WOLFSSL_ASN_TEMPLATE
  33102. int length = 0;
  33103. word32 idx = 0;
  33104. WOLFSSL_ENTER("wc_ParseCertPIV");
  33105. if (piv == NULL || buf == NULL || totalSz == 0)
  33106. return BAD_FUNC_ARG;
  33107. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  33108. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  33109. /* Certificate (0A 82 05FA) */
  33110. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  33111. /* Identiv Type PIV card */
  33112. piv->isIdentiv = 1;
  33113. piv->cert = &buf[idx];
  33114. piv->certSz = length;
  33115. idx += length;
  33116. /* Nonce (0B 14) */
  33117. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  33118. piv->nonce = &buf[idx];
  33119. piv->nonceSz = length;
  33120. idx += length;
  33121. }
  33122. /* Signed Nonce (0C 82 0100) */
  33123. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  33124. piv->signedNonce = &buf[idx];
  33125. piv->signedNonceSz = length;
  33126. }
  33127. idx = 0;
  33128. buf = piv->cert;
  33129. totalSz = piv->certSz;
  33130. }
  33131. /* Certificate Buffer Total Size (53 82 05F6) */
  33132. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  33133. &length, totalSz) < 0) {
  33134. return ASN_PARSE_E;
  33135. }
  33136. /* PIV Certificate (70 82 05ED) */
  33137. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  33138. totalSz) < 0) {
  33139. return ASN_PARSE_E;
  33140. }
  33141. /* Capture certificate buffer pointer and length */
  33142. piv->cert = &buf[idx];
  33143. piv->certSz = length;
  33144. idx += length;
  33145. /* PIV Certificate Info (71 01 00) */
  33146. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  33147. totalSz) >= 0) {
  33148. if (length >= 1) {
  33149. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  33150. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  33151. }
  33152. idx += length;
  33153. }
  33154. /* PIV Error Detection (FE 00) */
  33155. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  33156. totalSz) >= 0) {
  33157. piv->certErrDet = &buf[idx];
  33158. piv->certErrDetSz = length;
  33159. idx += length;
  33160. }
  33161. return 0;
  33162. #else
  33163. /* pivCertASN_Length is longer than pivASN_Length */
  33164. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  33165. int ret = 0;
  33166. word32 idx;
  33167. byte info;
  33168. WOLFSSL_ENTER("wc_ParseCertPIV");
  33169. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  33170. if (ret == 0) {
  33171. /* Clear dynamic data. */
  33172. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  33173. /* Start parsing from start of buffer. */
  33174. idx = 0;
  33175. /* Parse Identiv wrapper. */
  33176. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  33177. totalSz);
  33178. if (ret == 0) {
  33179. /* Identiv wrapper found. */
  33180. piv->isIdentiv = 1;
  33181. /* Get nonce reference. */
  33182. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  33183. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  33184. &piv->nonceSz);
  33185. }
  33186. /* Get signedNonce reference. */
  33187. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  33188. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  33189. &piv->signedNonce, &piv->signedNonceSz);
  33190. }
  33191. /* Get the certificate data for parsing. */
  33192. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  33193. }
  33194. ret = 0;
  33195. }
  33196. if (ret == 0) {
  33197. /* Clear dynamic data and set variable to put cert info into. */
  33198. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  33199. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  33200. /* Start parsing from start of buffer. */
  33201. idx = 0;
  33202. /* Parse PIV cetificate data. */
  33203. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  33204. totalSz);
  33205. if (ret == 0) {
  33206. /* Get X.509 certificate reference. */
  33207. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  33208. &piv->certSz);
  33209. /* Set the certificate info if available. */
  33210. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  33211. /* Bits 1 and 2 are compression. */
  33212. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  33213. /* Bits 3 is X509 flag. */
  33214. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  33215. }
  33216. /* Get X.509 certificate error detection reference. */
  33217. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  33218. &piv->certErrDetSz);
  33219. }
  33220. ret = 0;
  33221. }
  33222. FREE_ASNGETDATA(dataASN, NULL);
  33223. return ret;
  33224. #endif /* WOLFSSL_ASN_TEMPLATE */
  33225. }
  33226. #endif /* WOLFSSL_CERT_PIV */
  33227. #ifdef HAVE_SMIME
  33228. /*****************************************************************************
  33229. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  33230. * and parameters into headers. Will continue until in has no more content.
  33231. *
  33232. * RETURNS:
  33233. * returns zero on success, non-zero on error.
  33234. */
  33235. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  33236. {
  33237. MimeHdr* nextHdr = NULL;
  33238. MimeHdr* curHdr = NULL;
  33239. MimeParam* nextParam = NULL;
  33240. size_t start = 0;
  33241. size_t end = 0;
  33242. char* nameAttr = NULL;
  33243. char* bodyVal = NULL;
  33244. MimeTypes mimeType = MIME_HDR;
  33245. MimeStatus mimeStatus = MIME_NAMEATTR;
  33246. int ret = -1;
  33247. size_t pos = 0;
  33248. size_t lineLen = 0;
  33249. char* curLine = NULL;
  33250. char* ptr = NULL;
  33251. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  33252. ret = BAD_FUNC_ARG;
  33253. goto error;
  33254. }
  33255. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  33256. if (nextHdr == NULL) {
  33257. ret = MEMORY_E;
  33258. goto error;
  33259. }
  33260. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33261. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33262. DYNAMIC_TYPE_PKCS7);
  33263. if (nextParam == NULL) {
  33264. ret = MEMORY_E;
  33265. goto error;
  33266. }
  33267. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33268. curLine = XSTRTOK(in, "\r\n", &ptr);
  33269. if (curLine == NULL) {
  33270. ret = ASN_PARSE_E;
  33271. goto error;
  33272. }
  33273. while (curLine != NULL) {
  33274. /* Leftover from previous line, add params to previous header. */
  33275. if (curLine[0] == ' ' && curHdr) {
  33276. mimeType = MIME_PARAM;
  33277. }
  33278. else {
  33279. mimeType = MIME_HDR;
  33280. }
  33281. start = 0;
  33282. lineLen = XSTRLEN(curLine);
  33283. if (lineLen == 0) {
  33284. ret = BAD_FUNC_ARG;
  33285. goto error;
  33286. }
  33287. for (pos = 0; pos < lineLen; pos++) {
  33288. char cur = curLine[pos];
  33289. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  33290. mimeType == MIME_HDR) || (cur == '=' &&
  33291. mimeType == MIME_PARAM)) && pos >= 1) {
  33292. mimeStatus = MIME_BODYVAL;
  33293. end = pos-1;
  33294. if (nameAttr != NULL)
  33295. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33296. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  33297. if (ret) {
  33298. goto error;
  33299. }
  33300. start = pos+1;
  33301. }
  33302. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  33303. end = pos-1;
  33304. if (bodyVal != NULL)
  33305. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33306. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33307. if (ret) {
  33308. goto error;
  33309. }
  33310. if (mimeType == MIME_HDR) {
  33311. nextHdr->name = nameAttr;
  33312. nameAttr = NULL;
  33313. nextHdr->body = bodyVal;
  33314. bodyVal = NULL;
  33315. nextHdr->next = curHdr;
  33316. curHdr = nextHdr;
  33317. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33318. DYNAMIC_TYPE_PKCS7);
  33319. if (nextHdr == NULL) {
  33320. ret = MEMORY_E;
  33321. goto error;
  33322. }
  33323. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33324. }
  33325. else {
  33326. nextParam->attribute = nameAttr;
  33327. nameAttr = NULL;
  33328. nextParam->value = bodyVal;
  33329. bodyVal = NULL;
  33330. nextParam->next = curHdr->params;
  33331. curHdr->params = nextParam;
  33332. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33333. DYNAMIC_TYPE_PKCS7);
  33334. if (nextParam == NULL) {
  33335. ret = MEMORY_E;
  33336. goto error;
  33337. }
  33338. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33339. }
  33340. mimeType = MIME_PARAM;
  33341. mimeStatus = MIME_NAMEATTR;
  33342. start = pos+1;
  33343. }
  33344. }
  33345. end = lineLen-1;
  33346. /* Omit newline characters. */
  33347. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33348. end--;
  33349. }
  33350. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33351. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33352. if (ret) {
  33353. goto error;
  33354. }
  33355. if (mimeType == MIME_HDR) {
  33356. nextHdr->name = nameAttr;
  33357. nameAttr = NULL;
  33358. nextHdr->body = bodyVal;
  33359. bodyVal = NULL;
  33360. nextHdr->next = curHdr;
  33361. curHdr = nextHdr;
  33362. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33363. DYNAMIC_TYPE_PKCS7);
  33364. if (nextHdr == NULL) {
  33365. ret = MEMORY_E;
  33366. goto error;
  33367. }
  33368. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33369. } else {
  33370. nextParam->attribute = nameAttr;
  33371. nameAttr = NULL;
  33372. nextParam->value = bodyVal;
  33373. bodyVal = NULL;
  33374. nextParam->next = curHdr->params;
  33375. curHdr->params = nextParam;
  33376. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33377. DYNAMIC_TYPE_PKCS7);
  33378. if (nextParam == NULL) {
  33379. ret = MEMORY_E;
  33380. goto error;
  33381. }
  33382. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33383. }
  33384. }
  33385. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33386. mimeStatus = MIME_NAMEATTR;
  33387. }
  33388. *headers = curHdr;
  33389. ret = 0; /* success if at this point */
  33390. error:
  33391. if (ret != 0)
  33392. wc_MIME_free_hdrs(curHdr);
  33393. wc_MIME_free_hdrs(nextHdr);
  33394. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33395. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33396. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33397. return ret;
  33398. }
  33399. /*****************************************************************************
  33400. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33401. * out disallowed/separator characters and places the rest into *out.
  33402. *
  33403. * RETURNS:
  33404. * returns zero on success, non-zero on error.
  33405. */
  33406. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33407. {
  33408. size_t inPos = start;
  33409. size_t outPos = 0;
  33410. size_t inLen = 0;
  33411. if (end < start || in == NULL || out == NULL) {
  33412. return BAD_FUNC_ARG;
  33413. }
  33414. inLen = XSTRLEN(in);
  33415. if (start > inLen || end > inLen) {
  33416. return BAD_FUNC_ARG;
  33417. }
  33418. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33419. DYNAMIC_TYPE_PKCS7);
  33420. if (*out == NULL) {
  33421. return MEMORY_E;
  33422. }
  33423. while (inPos <= end) {
  33424. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33425. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33426. (*out)[outPos] = in[inPos];
  33427. outPos++;
  33428. }
  33429. inPos++;
  33430. }
  33431. (*out)[outPos] = '\0';
  33432. return 0;
  33433. }
  33434. /*****************************************************************************
  33435. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33436. * a name matching the provided name is found.
  33437. *
  33438. * RETURNS:
  33439. * returns a pointer to the found header, if no match was found, returns NULL.
  33440. */
  33441. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33442. {
  33443. while (header) {
  33444. if (!XSTRCMP(name, header->name)) {
  33445. return header;
  33446. }
  33447. header = header->next;
  33448. }
  33449. return header;
  33450. }
  33451. /*****************************************************************************
  33452. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33453. * with a attribute matching the provided attribute is found.
  33454. *
  33455. * RETURNS:
  33456. * returns a pointer to the found parameter, if no match was found,
  33457. * returns NULL.
  33458. */
  33459. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33460. MimeParam* param)
  33461. {
  33462. while (param) {
  33463. if (!XSTRCMP(attribute, param->attribute)) {
  33464. return param;
  33465. }
  33466. param = param->next;
  33467. }
  33468. return param;
  33469. }
  33470. /*****************************************************************************
  33471. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33472. * line ending to CRLF.
  33473. *
  33474. * line - input line to canonicalize
  33475. * len - length of line in chars on input, length of output array on return
  33476. *
  33477. * RETURNS:
  33478. * returns a pointer to a canonicalized line on success, NULL on error.
  33479. */
  33480. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33481. {
  33482. size_t end = 0;
  33483. char* canonLine = NULL;
  33484. if (line == NULL || len == NULL || *len == 0) {
  33485. return NULL;
  33486. }
  33487. end = *len;
  33488. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33489. end--;
  33490. }
  33491. /* Need 2 chars for \r\n and 1 for EOL */
  33492. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33493. if (canonLine == NULL) {
  33494. return NULL;
  33495. }
  33496. XMEMCPY(canonLine, line, end);
  33497. canonLine[end] = '\r';
  33498. canonLine[end+1] = '\n';
  33499. canonLine[end+2] = '\0';
  33500. *len = (word32)(end + 3);
  33501. return canonLine;
  33502. }
  33503. /*****************************************************************************
  33504. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33505. * the provided header pointer.
  33506. *
  33507. * RETURNS:
  33508. * returns zero on success, non-zero on error.
  33509. */
  33510. int wc_MIME_free_hdrs(MimeHdr* head)
  33511. {
  33512. MimeHdr* curHdr = NULL;
  33513. MimeParam* curParam = NULL;
  33514. while (head) {
  33515. while (head->params) {
  33516. curParam = head->params;
  33517. head->params = head->params->next;
  33518. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33519. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33520. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33521. }
  33522. curHdr = head;
  33523. head = head->next;
  33524. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33525. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33526. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33527. }
  33528. return 0;
  33529. }
  33530. #endif /* HAVE_SMIME */
  33531. #undef ERROR_OUT
  33532. #ifdef WOLFSSL_ASN_PRINT
  33533. /*******************************************************************************
  33534. * ASN.1 Parsing and Printing Implemenation
  33535. ******************************************************************************/
  33536. /* Initialize ASN.1 print options.
  33537. *
  33538. * @param [in, out] opts ASN.1 options for printing.
  33539. * @return 0 on success.
  33540. * @return BAD_FUNC_ARG when asn1 is NULL.
  33541. */
  33542. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  33543. {
  33544. int ret = 0;
  33545. if (opts == NULL) {
  33546. ret = BAD_FUNC_ARG;
  33547. }
  33548. else {
  33549. XMEMSET(opts, 0, sizeof(*opts));
  33550. }
  33551. return ret;
  33552. }
  33553. /* Set a print option into Asn1PrintOptions object.
  33554. *
  33555. * @param [in, out] opts ASN.1 options for printing.
  33556. * @param [in] opt Option to set value of.
  33557. * @param [in] val Value to set for option.
  33558. * @return 0 on success.
  33559. * @return BAD_FUNC_ARG when asn1 is NULL.
  33560. * @return BAD_FUNC_ARG when val is out of range for option.
  33561. */
  33562. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  33563. word32 val)
  33564. {
  33565. int ret = 0;
  33566. /* Validate parameters. */
  33567. if (opts == NULL) {
  33568. ret = BAD_FUNC_ARG;
  33569. }
  33570. if (ret == 0) {
  33571. switch (opt) {
  33572. /* Offset into DER/BER data to start decoding from. */
  33573. case ASN1_PRINT_OPT_OFFSET:
  33574. opts->offset = val;
  33575. break;
  33576. /* Length of DER/BER encoding to parse. */
  33577. case ASN1_PRINT_OPT_LENGTH:
  33578. opts->length = val;
  33579. break;
  33580. /* Number of spaces to indent for each change in depth. */
  33581. case ASN1_PRINT_OPT_INDENT:
  33582. /* Only 4 bits allowed for value. */
  33583. if (val >= (1 << 4)) {
  33584. ret = BAD_FUNC_ARG;
  33585. }
  33586. else {
  33587. opts->indent = (word8)val;
  33588. }
  33589. break;
  33590. /* Draw branches instead of indenting. */
  33591. case ASN1_PRINT_OPT_DRAW_BRANCH:
  33592. /* Boolean value. */
  33593. opts->draw_branch = (val > 0);
  33594. break;
  33595. /* Show raw data of primitive types as octets. */
  33596. case ASN1_PRINT_OPT_SHOW_DATA:
  33597. /* Boolean value. */
  33598. opts->show_data = (val > 0);
  33599. break;
  33600. /* Show header data as octets. */
  33601. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  33602. /* Boolean value. */
  33603. opts->show_header_data = (val > 0);
  33604. break;
  33605. /* Show the wolfSSL OID value for OBJECT_ID. */
  33606. case ASN1_PRINT_OPT_SHOW_OID:
  33607. /* Boolean value. */
  33608. opts->show_oid = (val > 0);
  33609. break;
  33610. /* Don't show text representations of primitive types. */
  33611. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  33612. /* Boolean value. */
  33613. opts->show_no_text = (val > 0);
  33614. break;
  33615. /* Don't show dump text representations of primitive types. */
  33616. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  33617. /* Boolean value. */
  33618. opts->show_no_dump_text = (val > 0);
  33619. break;
  33620. }
  33621. }
  33622. return ret;
  33623. }
  33624. /* Initialize an ASN.1 parse object.
  33625. *
  33626. * @param [in, out] asn1 ASN.1 parse object.
  33627. * @return 0 on success.
  33628. * @return BAD_FUNC_ARG when asn1 is NULL.
  33629. */
  33630. int wc_Asn1_Init(Asn1* asn1)
  33631. {
  33632. int ret = 0;
  33633. if (asn1 == NULL) {
  33634. ret = BAD_FUNC_ARG;
  33635. }
  33636. else {
  33637. XMEMSET(asn1, 0, sizeof(*asn1));
  33638. asn1->file = XBADFILE;
  33639. }
  33640. return ret;
  33641. }
  33642. /* Set the file to use when printing.
  33643. *
  33644. * @param [in, out] asn1 ASN.1 parse object.
  33645. * @param [in] file File to print to.
  33646. * @return 0 on success.
  33647. * @return BAD_FUNC_ARG when asn1 is NULL.
  33648. * @return BAD_FUNC_ARG when file is XBADFILE.
  33649. */
  33650. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  33651. {
  33652. int ret = 0;
  33653. if ((asn1 == NULL) || (file == XBADFILE)) {
  33654. ret = BAD_FUNC_ARG;
  33655. }
  33656. else {
  33657. asn1->file = file;
  33658. }
  33659. return ret;
  33660. }
  33661. /* Maximum OID dotted form size. */
  33662. #define ASN1_OID_DOTTED_MAX_SZ 16
  33663. /* Print OID in dotted form or as hex bytes.
  33664. *
  33665. * @param [in] file File pointer to write to.
  33666. * @param [in] oid OBJECT_ID data.
  33667. * @param [in] oid_len Length of OBJECT_ID data.
  33668. */
  33669. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  33670. {
  33671. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  33672. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  33673. word32 i;
  33674. /* Decode OBJECT_ID into dotted form array. */
  33675. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  33676. /* Print out each number of dotted form. */
  33677. for (i = 0; i < num; i++) {
  33678. XFPRINTF(file, "%d", dotted_nums[i]);
  33679. /* Add separetor. */
  33680. if (i < num - 1) {
  33681. XFPRINTF(file, ".");
  33682. }
  33683. }
  33684. }
  33685. else {
  33686. /* Print out bytes as we couldn't decode. */
  33687. for (i = 0; i < len; i++) {
  33688. XFPRINTF(file, "%02x", oid[i]);
  33689. /* Add separetor. */
  33690. if (i < len - 1) {
  33691. XFPRINTF(file, ":");
  33692. }
  33693. }
  33694. }
  33695. }
  33696. /* OID value to name mapping. */
  33697. typedef struct OidName {
  33698. /* wolfSSL OID value. */
  33699. word32 oid;
  33700. /* Long name to print when OID seen. */
  33701. const char* name;
  33702. } OidName;
  33703. /* Extra OID to name mappings. */
  33704. static const OidName extraOids[] = {
  33705. { 0x005c, "commonName" },
  33706. { 0x005d, "surname" },
  33707. { 0x005e, "serialNumber" },
  33708. { 0x005f, "countryName" },
  33709. { 0x0060, "localityName" },
  33710. { 0x0061, "stateOrProvinceName" },
  33711. { 0x0062, "streetAddress" },
  33712. { 0x0063, "organizationName" },
  33713. { 0x0064, "organizationUnitName" },
  33714. { 0x0065, "title" },
  33715. { 0x0086, "certificateExtension" },
  33716. { 0x028d, "emailAddress" },
  33717. { 0x0293, "challengePassword" },
  33718. { 0x029a, "extensionReq" },
  33719. };
  33720. /* Length of table of extra OID to name mappings. */
  33721. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  33722. /* Convert OID value to long name.
  33723. *
  33724. * @param [in] oid OID value.
  33725. * @param [out] name Long name for OID when known.
  33726. * @return 1 when OID known.
  33727. * @return 0 when OID not known.
  33728. */
  33729. static int Oid2LongName(word32 oid, const char** name)
  33730. {
  33731. int ret = 0;
  33732. int i;
  33733. /* Step through each entry in table. */
  33734. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  33735. if (extraOids[i].oid == oid) {
  33736. /* Return the name associated with the OID value. */
  33737. *name = extraOids[i].name;
  33738. ret = 1;
  33739. break;
  33740. }
  33741. }
  33742. return ret;
  33743. }
  33744. /* Print the text version of the OBJECT_ID.
  33745. *
  33746. * @param [in] asn1 ASN.1 parse object.
  33747. * @param [in] opts ASN.1 options for printing.
  33748. */
  33749. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  33750. {
  33751. word32 oid = (word32)-1;
  33752. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33753. int nid;
  33754. #endif
  33755. const char* ln = NULL;
  33756. word32 i = 0;
  33757. int known = 1;
  33758. /* Get the OID value for the OBJECT_ID. */
  33759. if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  33760. asn1->item.len + 2) == ASN_PARSE_E) {
  33761. known = 0;
  33762. }
  33763. else
  33764. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33765. /* Lookup NID for OID value. */
  33766. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  33767. /* Lookup long name for NID. */
  33768. ln = wolfSSL_OBJ_nid2ln(nid);
  33769. }
  33770. else
  33771. #endif
  33772. /* Lookup long name for extra known OID values. */
  33773. if (!Oid2LongName(oid, &ln)) {
  33774. /* Unknown OID value. */
  33775. ln = NULL;
  33776. known = 0;
  33777. }
  33778. XFPRINTF(asn1->file, ":");
  33779. /* Show OID value if not known or asked to. */
  33780. if ((!known) || opts->show_oid) {
  33781. XFPRINTF(asn1->file, "(0x%x) ", oid);
  33782. }
  33783. if (ln != NULL) {
  33784. /* Print long name. */
  33785. XFPRINTF(asn1->file, "%s", ln);
  33786. }
  33787. else {
  33788. /* Print out as numbers - either dotted or hex values. */
  33789. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  33790. asn1->item.len);
  33791. }
  33792. }
  33793. /* Print ASN.1 data as a character string.
  33794. *
  33795. * @param [in] asn1 ASN.1 parse object.
  33796. */
  33797. static void PrintText(Asn1* asn1)
  33798. {
  33799. word32 i;
  33800. XFPRINTF(asn1->file, ":");
  33801. /* Print all data bytes as characters. */
  33802. for (i = 0; i < asn1->item.len; i++) {
  33803. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  33804. }
  33805. }
  33806. /* Print data as a hex bytes.
  33807. *
  33808. * @param [in] file File pointer to write to.
  33809. * @param [in] data Data to print.
  33810. * @param [in] len Number of bytes to print.
  33811. */
  33812. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  33813. {
  33814. word32 i;
  33815. /* Print data bytes as hex numbers. */
  33816. for (i = 0; i < len; i++) {
  33817. XFPRINTF(file, "%02x", data[i]);
  33818. }
  33819. }
  33820. /* Print ASN.1 data as a hex bytes.
  33821. *
  33822. * @param [in] asn1 ASN.1 parse object.
  33823. */
  33824. static void PrintHexText(Asn1* asn1)
  33825. {
  33826. XFPRINTF(asn1->file, ":");
  33827. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  33828. }
  33829. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  33830. *
  33831. * @param [in] asn1 ASN.1 parse object.
  33832. */
  33833. static void PrintBitStringText(Asn1* asn1)
  33834. {
  33835. if (asn1->item.len > 0) {
  33836. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  33837. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  33838. asn1->item.len - 1);
  33839. }
  33840. }
  33841. /* Print ASN.1 BOOLEAN data as text with value.
  33842. *
  33843. * @param [in] asn1 ASN.1 parse object.
  33844. */
  33845. static void PrintBooleanText(Asn1* asn1)
  33846. {
  33847. /* Booleans should be 1 byte of data. */
  33848. if (asn1->item.len == 1) {
  33849. XFPRINTF(asn1->file, ":%s (%d)",
  33850. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  33851. asn1->data[asn1->item.data_idx]);
  33852. }
  33853. }
  33854. /* Print ASN.1 data as single byte +/- number.
  33855. *
  33856. * @param [in] asn1 ASN.1 parse object.
  33857. */
  33858. static void PrintNumberText(Asn1* asn1)
  33859. {
  33860. /* Only supporting 1 byte of data for now. */
  33861. if (asn1->item.len == 1) {
  33862. int num = asn1->data[asn1->item.data_idx];
  33863. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  33864. }
  33865. }
  33866. /* Print ASN.1 data as a text based on the tag.
  33867. *
  33868. * TODO: handle more tags.
  33869. *
  33870. * @param [in] asn1 ASN.1 parse object.
  33871. * @param [in] opts ASN.1 options for printing.
  33872. */
  33873. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  33874. {
  33875. /* Get the long name for OBJECT_ID where possible. */
  33876. if (asn1->item.tag == ASN_OBJECT_ID) {
  33877. PrintObjectIdText(asn1, opts);
  33878. }
  33879. /* Data is an array of printable characters. */
  33880. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  33881. (asn1->item.tag == ASN_IA5_STRING) ||
  33882. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  33883. (asn1->item.tag == ASN_T61STRING) ||
  33884. (asn1->item.tag == ASN_BMPSTRING) ||
  33885. (asn1->item.tag == ASN_UTC_TIME) ||
  33886. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  33887. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  33888. (asn1->item.tag == ASN_OBJECT_DESC) ||
  33889. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  33890. PrintText(asn1);
  33891. }
  33892. /* Show TRUE and FALSE with number. */
  33893. else if (asn1->item.tag == ASN_BOOLEAN) {
  33894. PrintBooleanText(asn1);
  33895. }
  33896. /* Show number. */
  33897. else if (asn1->item.tag == ASN_ENUMERATED) {
  33898. PrintNumberText(asn1);
  33899. }
  33900. /* Dumping potentially long string of hex digites. */
  33901. else if (!opts->show_no_dump_text) {
  33902. /* Dump all bytes. */
  33903. if ((asn1->item.tag == ASN_INTEGER) ||
  33904. (asn1->item.tag == ASN_OCTET_STRING) ||
  33905. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  33906. PrintHexText(asn1);
  33907. }
  33908. /* First byte is number of unused bits in last byte.
  33909. * Print first specially and dump rest of the bytes. */
  33910. else if (asn1->item.tag == ASN_BIT_STRING) {
  33911. PrintBitStringText(asn1);
  33912. }
  33913. }
  33914. }
  33915. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  33916. /* Dump data as hex bytes.
  33917. *
  33918. * @param [in] file File pointer to write to.
  33919. * @param [in] data Data to print.
  33920. * @param [in] len Number of bytes to print.
  33921. */
  33922. static void DumpData(XFILE file, unsigned char* data, word32 len)
  33923. {
  33924. word32 i;
  33925. word32 j;
  33926. for (i = 0; i < len; i += j) {
  33927. /* Print offset. */
  33928. XFPRINTF(file, " %04x:", i);
  33929. for (j = 0; (j < 16) && (i + j < len); j++) {
  33930. /* Print byte as hex number. */
  33931. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  33932. }
  33933. /* Print spaces between hex and characters. */
  33934. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  33935. for (j = 0; (j < 16) && (i + j < len); j++) {
  33936. /* Print byte as hex number. */
  33937. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  33938. }
  33939. XFPRINTF(file, "\n");
  33940. }
  33941. }
  33942. /* Update current depth based on the current position.
  33943. *
  33944. * @param [in, out] asn1 ASN.1 parse object.
  33945. */
  33946. static void UpdateDepth(Asn1* asn1)
  33947. {
  33948. /* If current index is greater than or equal end index then it is done. */
  33949. while ((asn1->depth > 0) &&
  33950. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  33951. /* Move up a depth. */
  33952. asn1->depth--;
  33953. }
  33954. }
  33955. /* Check validity of end index of constructed ASN.1 items.
  33956. *
  33957. * @param [in, out] asn1 ASN.1 parse object.
  33958. * @return 0 on success.
  33959. * @return ASN_DEPTH_E when end offset invalid.
  33960. */
  33961. static int CheckDepth(Asn1* asn1)
  33962. {
  33963. int ret = 0;
  33964. int i;
  33965. word32 curr_end = asn1->curr + asn1->item.len;
  33966. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  33967. /* Each end index must be at least as large as the current one. */
  33968. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  33969. ret = ASN_DEPTH_E;
  33970. }
  33971. /* Each end index must be at least as large as current index. */
  33972. if (asn1->end_idx[i] < curr_end) {
  33973. ret = ASN_DEPTH_E;
  33974. }
  33975. }
  33976. return ret;
  33977. }
  33978. /* Draw branching based on depth for an ASN.1 item.
  33979. *
  33980. * @param [in] asn1 ASN.1 parse object.
  33981. */
  33982. static void DrawBranch(Asn1* asn1)
  33983. {
  33984. int i;
  33985. word32 end = asn1->curr + asn1->item.len;
  33986. /* Write out the character for all depths but current. */
  33987. for (i = 0; i < asn1->depth; i++) {
  33988. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  33989. if (i < asn1->depth - 1) {
  33990. /* Constructed or not end index and not current depth: | */
  33991. XFPRINTF(asn1->file, "\xe2\x94\x82");
  33992. }
  33993. else {
  33994. /* Constructed or not end index and current depth: |- */
  33995. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  33996. }
  33997. }
  33998. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  33999. /* End index for previous: _|_ (in top half) */
  34000. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  34001. }
  34002. else {
  34003. /* End index but not for previous: L (in top half) */
  34004. XFPRINTF(asn1->file, "\xe2\x94\x94");
  34005. }
  34006. }
  34007. /* Prefix to tag name. */
  34008. if (asn1->item.cons) {
  34009. if (asn1->depth > 0) {
  34010. /* Have other line to connect to: T (in bottom half) */
  34011. XFPRINTF(asn1->file, "\xe2\x94\xac");
  34012. }
  34013. else {
  34014. /* Have no other line to connect to: r */
  34015. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  34016. }
  34017. }
  34018. else {
  34019. /* In a sequence: - */
  34020. XFPRINTF(asn1->file, "\xe2\x94\x80");
  34021. }
  34022. }
  34023. /* Print data as hex bytes separated by space.
  34024. *
  34025. * @param [in] file File pointer to write to.
  34026. * @param [in] data Data to print.
  34027. * @param [in] len Number of bytes to print.
  34028. */
  34029. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  34030. {
  34031. word32 i;
  34032. for (i = 0; i < len; i++) {
  34033. XFPRINTF(file, " %02x", data[i]);
  34034. }
  34035. }
  34036. /* Dump header data.
  34037. *
  34038. * @param [in] asn1 ASN.1 parse object.
  34039. * @param [in] opts ASN.1 options for printing.
  34040. */
  34041. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  34042. {
  34043. /* Put on same line when not showing data too and not showing text data. */
  34044. if ((!opts->show_data) && opts->show_no_text) {
  34045. XFPRINTF(asn1->file, "%10s", "");
  34046. }
  34047. else {
  34048. /* Align with start of data. */
  34049. XFPRINTF(asn1->file, "\n%12s", "");
  34050. }
  34051. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  34052. if (asn1->curr >= asn1->offset + 1) {
  34053. /* Print the header bytes as hex bytes separated by a space. */
  34054. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  34055. asn1->curr - (asn1->offset + 1));
  34056. }
  34057. }
  34058. /* Print ASN.1 item info based on header and indeces.
  34059. *
  34060. * @param [in] asn1 ASN.1 parse object.
  34061. * @param [in] opts ASN.1 options for printing.
  34062. */
  34063. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  34064. {
  34065. /* Print offset of this ASN.1 item. */
  34066. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  34067. /* Print length of header. */
  34068. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  34069. /* Print data length. */
  34070. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  34071. asn1->item.cons ? ']' : ' ');
  34072. /* Print depth. */
  34073. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  34074. if (!opts->draw_branch) {
  34075. /* Indent to depth as required. */
  34076. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  34077. if (!opts->indent) {
  34078. /* Indicate constructed if no indent. */
  34079. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  34080. }
  34081. }
  34082. else {
  34083. /* Draw branch structure for ASN.1 item. */
  34084. XFPRINTF(asn1->file, " ");
  34085. DrawBranch(asn1);
  34086. }
  34087. /* Print tag name. */
  34088. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  34089. }
  34090. /* Expecting tag part of ASN.1 item. */
  34091. #define ASN_PART_TAG 0
  34092. /* Expecting length part of ASN.1 item. */
  34093. #define ASN_PART_LENGTH 1
  34094. /* Expecting data part of ASN.1 item. */
  34095. #define ASN_PART_DATA 2
  34096. /* Print next ASN.1 item.
  34097. *
  34098. * @param [in, out] asn1 ASN.1 parse object.
  34099. * @param [in] opts ASN.1 print options.
  34100. * @return 0 on success.
  34101. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  34102. * @return ASN_LEN_E when ASN.1 item's length too long.
  34103. * @return ASN_DEPTH_E when end offset invalid.
  34104. */
  34105. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  34106. {
  34107. int ret = 0;
  34108. /* Process tag. */
  34109. if (asn1->part == ASN_PART_TAG) {
  34110. /* Recalculate which depth we are at. */
  34111. UpdateDepth(asn1);
  34112. /* Get tag. */
  34113. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  34114. /* Store whether tag indicates constructed. */
  34115. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  34116. ASN_CONSTRUCTED;
  34117. /* Start of ASN.1 item is current index. */
  34118. asn1->offset = asn1->curr;
  34119. /* Step over tag. */
  34120. asn1->curr++;
  34121. /* Next part is length. */
  34122. asn1->part = ASN_PART_LENGTH;
  34123. }
  34124. /* Process length. */
  34125. if (asn1->part == ASN_PART_LENGTH) {
  34126. int len;
  34127. /* Decode length and step over it. */
  34128. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  34129. ret = ASN_LEN_E;
  34130. }
  34131. else {
  34132. /* Store ASN.1 item data offset. */
  34133. asn1->item.data_idx = asn1->curr;
  34134. /* Store ASN.1 item data length. */
  34135. asn1->item.len = (word32)len;
  34136. /* Print info about ASN.1 item. */
  34137. PrintInfo(asn1, opts);
  34138. if (!asn1->item.cons) {
  34139. /* Move on to print data. */
  34140. asn1->part = ASN_PART_DATA;
  34141. }
  34142. else {
  34143. /* Print header now if not printing data. */
  34144. if (opts->show_header_data) {
  34145. DumpHeader(asn1, opts);
  34146. }
  34147. XFPRINTF(asn1->file, "\n");
  34148. /* Record end offset for this depth. */
  34149. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  34150. /* Done with this ASN.1 item. */
  34151. asn1->part = ASN_PART_TAG;
  34152. }
  34153. /* Check end indeces are valid. */
  34154. ret = CheckDepth(asn1);
  34155. }
  34156. }
  34157. /* Process data. */
  34158. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  34159. if (!opts->show_no_text) {
  34160. /* Print text representation of data. */
  34161. PrintAsn1Text(asn1, opts);
  34162. }
  34163. if (opts->show_header_data) {
  34164. /* Dump header bytes. */
  34165. DumpHeader(asn1, opts);
  34166. }
  34167. XFPRINTF(asn1->file, "\n");
  34168. if (opts->show_data) {
  34169. /* Dump data bytes. */
  34170. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  34171. asn1->item.len);
  34172. }
  34173. /* Step past data to next ASN.1 item. */
  34174. asn1->curr += asn1->item.len;
  34175. /* Update the depth based on end indeces. */
  34176. UpdateDepth(asn1);
  34177. /* Done with this ASN.1 item. */
  34178. asn1->part = ASN_PART_TAG;
  34179. }
  34180. /* Make ASN.1 item printing go out. */
  34181. fflush(asn1->file);
  34182. return ret;
  34183. }
  34184. /* Print all ASN.1 items.
  34185. *
  34186. * @param [in, out] asn1 ASN.1 parse object.
  34187. * @param [in] opts ASN.1 print options.
  34188. * @param [in] data BER/DER data to print.
  34189. * @param [in] len Length of data to print in bytes.
  34190. * @return 0 on success.
  34191. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  34192. * @return ASN_LEN_E when ASN.1 item's length too long.
  34193. * @return ASN_DEPTH_E when end offset invalid.
  34194. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  34195. */
  34196. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  34197. word32 len)
  34198. {
  34199. int ret = 0;
  34200. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  34201. ret = BAD_FUNC_ARG;
  34202. }
  34203. if (ret == 0) {
  34204. /* Initialize start position. */
  34205. asn1->curr = 0;
  34206. /* Start parsing at tag. */
  34207. asn1->part = ASN_PART_TAG;
  34208. /* Start depth at 0. */
  34209. asn1->depth = 0;
  34210. /* Store the starting point of the data to parse. */
  34211. asn1->data = data + opts->offset;
  34212. if (opts->length > 0) {
  34213. /* Use user specified maximum length. */
  34214. asn1->max = opts->length;
  34215. }
  34216. else {
  34217. /* Maximum length is up to end from offset. */
  34218. asn1->max = len - opts->offset;
  34219. }
  34220. /* Keep going while no error and have data to parse. */
  34221. while ((ret == 0) && (asn1->curr < asn1->max)) {
  34222. /* Print an ASN.1 item. */
  34223. ret = wc_Asn1_Print(asn1, opts);
  34224. }
  34225. }
  34226. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  34227. /* Stopped before finishing ASN.1 item. */
  34228. ret = ASN_PARSE_E;
  34229. }
  34230. if ((ret == 0) && (asn1->depth != 0)) {
  34231. /* Stopped without seeing all items in a constructed item. */
  34232. ret = ASN_DEPTH_E;
  34233. }
  34234. return ret;
  34235. }
  34236. #endif /* WOLFSSL_ASN_PRINT */
  34237. #endif /* !NO_ASN */
  34238. /* Functions that parse, but are not using ASN.1 */
  34239. #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  34240. (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  34241. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  34242. /* this function does not use any ASN.1 parsing */
  34243. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  34244. word32 eSz, RsaKey* key)
  34245. {
  34246. if (n == NULL || e == NULL || key == NULL)
  34247. return BAD_FUNC_ARG;
  34248. key->type = RSA_PUBLIC;
  34249. if (mp_init(&key->n) != MP_OKAY)
  34250. return MP_INIT_E;
  34251. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  34252. mp_clear(&key->n);
  34253. return ASN_GETINT_E;
  34254. }
  34255. #ifdef HAVE_WOLF_BIGINT
  34256. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  34257. mp_clear(&key->n);
  34258. return ASN_GETINT_E;
  34259. }
  34260. #endif /* HAVE_WOLF_BIGINT */
  34261. if (mp_init(&key->e) != MP_OKAY) {
  34262. mp_clear(&key->n);
  34263. return MP_INIT_E;
  34264. }
  34265. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  34266. mp_clear(&key->n);
  34267. mp_clear(&key->e);
  34268. return ASN_GETINT_E;
  34269. }
  34270. #ifdef HAVE_WOLF_BIGINT
  34271. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  34272. mp_clear(&key->n);
  34273. mp_clear(&key->e);
  34274. return ASN_GETINT_E;
  34275. }
  34276. #endif /* HAVE_WOLF_BIGINT */
  34277. #ifdef WOLFSSL_XILINX_CRYPT
  34278. if (wc_InitRsaHw(key) != 0) {
  34279. return BAD_STATE_E;
  34280. }
  34281. #endif
  34282. return 0;
  34283. }
  34284. #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  34285. #ifdef WOLFSSL_SEP
  34286. #endif /* WOLFSSL_SEP */