asn.c 1.2 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. /*
  22. * DESCRIPTION
  23. * This library provides the interface to Abstract Syntax Notation One (ASN.1)
  24. * objects.
  25. * ASN.1 is a standard interface description language for defining data
  26. * structures that can be serialized and deserialized in a cross-platform way.
  27. *
  28. * Encoding of ASN.1 is either using Basic Encoding Rules (BER) or
  29. * Distinguished Encoding Rules (DER). DER has only one possible encoding for a
  30. * ASN.1 description and the data.
  31. * Encode using DER and decode BER or DER.
  32. *
  33. * Provides routines to convert BER into DER. Replaces indefinite length
  34. * encoded items with explicit lengths.
  35. */
  36. #ifdef HAVE_CONFIG_H
  37. #include <config.h>
  38. #endif
  39. #include <wolfssl/wolfcrypt/settings.h>
  40. /*
  41. ASN Options:
  42. * NO_ASN_TIME_CHECK: Disables ASN time checks (avoiding the ASN_BEFORE_DATE_E
  43. * and ASN_AFTER_DATE_E errors). Safer ways to avoid date errors would be to
  44. * set the WOLFSSL_LOAD_FLAG_DATE_ERR_OKAY flag when calling the _ex versions of
  45. * cert loading functions or to define the WOLFSSL_NO_OCSP_DATE_CHECK macro to
  46. * skip OCSP date errors. Defining NO_ASN_TIME_CHECK will skip ALL date checks
  47. * and could pose a security risk.
  48. * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
  49. or wishing to save space.
  50. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  51. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  52. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  53. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  54. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
  55. restore 3.13.0 behavior.
  56. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  57. must still be trusted)
  58. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  59. chain is not loaded. This only matches on subject and public key and
  60. does not perform a PKI validation, so it is not a secure solution.
  61. Only enabled for OCSP.
  62. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  63. disable checking of OCSP subject hash with issuer hash.
  64. * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
  65. DecodedCert. Doubles up on some code but allows smaller dynamic memory
  66. usage.
  67. * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
  68. may be required when the system's real-time clock is not very accurate.
  69. It is recommended to enforce the nonce check instead if possible.
  70. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  71. responses. The nonces are optional and may not be supported by all
  72. responders. If it can be ensured that the used responder sends nonces this
  73. option may improve security.
  74. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  75. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  76. templates.
  77. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  78. type issues for testing
  79. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  80. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  81. Only supports copying full AKID from an existing certificate.
  82. * WOLFSSL_CUSTOM_OID: Enable custom OID support for subject and request
  83. extensions
  84. * WOLFSSL_HAVE_ISSUER_NAMES: Store pointers to issuer name components and their
  85. lengths and encodings.
  86. * WOLFSSL_SUBJ_DIR_ATTR: Enable support for SubjectDirectoryAttributes
  87. extension.
  88. * WOLFSSL_SUBJ_INFO_ACC: Enable support for SubjectInfoAccess extension.
  89. * WOLFSSL_FPKI: Enable support for FPKI (Federal PKI) extensions.
  90. * WOLFSSL_CERT_NAME_ALL: Adds more certificate name capability at the
  91. cost of taking up more memory. Adds initials, givenname, dnQualifer for
  92. example.
  93. * WC_ASN_HASH_SHA256: Force use of SHA2-256 for the internal hash ID calcs.
  94. */
  95. #include <wolfssl/wolfcrypt/error-crypt.h>
  96. #ifndef NO_RSA
  97. #include <wolfssl/wolfcrypt/rsa.h>
  98. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  99. extern int wc_InitRsaHw(RsaKey* key);
  100. #endif
  101. #endif
  102. #ifndef NO_ASN
  103. #include <wolfssl/wolfcrypt/asn.h>
  104. #include <wolfssl/wolfcrypt/coding.h>
  105. #include <wolfssl/wolfcrypt/md2.h>
  106. #include <wolfssl/wolfcrypt/hmac.h>
  107. #include <wolfssl/wolfcrypt/pwdbased.h>
  108. #include <wolfssl/wolfcrypt/des3.h>
  109. #include <wolfssl/wolfcrypt/aes.h>
  110. #include <wolfssl/wolfcrypt/rc2.h>
  111. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  112. #include <wolfssl/wolfcrypt/logging.h>
  113. #include <wolfssl/wolfcrypt/random.h>
  114. #include <wolfssl/wolfcrypt/hash.h>
  115. #ifdef NO_INLINE
  116. #include <wolfssl/wolfcrypt/misc.h>
  117. #else
  118. #define WOLFSSL_MISC_INCLUDED
  119. #include <wolfcrypt/src/misc.c>
  120. #endif
  121. #ifndef NO_RC4
  122. #include <wolfssl/wolfcrypt/arc4.h>
  123. #endif
  124. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  125. #include <wolfssl/wolfcrypt/sha512.h>
  126. #endif
  127. #ifndef NO_SHA256
  128. #include <wolfssl/wolfcrypt/sha256.h>
  129. #endif
  130. #ifdef HAVE_ECC
  131. #include <wolfssl/wolfcrypt/ecc.h>
  132. #endif
  133. #ifdef 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. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  174. #include <wolfssl/internal.h>
  175. #include <wolfssl/openssl/objects.h>
  176. #endif
  177. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  178. !defined(WOLFCRYPT_ONLY)
  179. #define WOLFSSL_X509_NAME_AVAILABLE
  180. #endif
  181. #ifdef _MSC_VER
  182. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  183. #pragma warning(disable: 4996)
  184. #endif
  185. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  186. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  187. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  188. (!defined(HAVE_SELFTEST_VERSION) || \
  189. HAVE_SELFTEST_VERSION < 2))
  190. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  191. #define WOLFSSL_AES_KEY_SIZE_ENUM
  192. enum Asn_Misc {
  193. AES_IV_SIZE = 16,
  194. AES_128_KEY_SIZE = 16,
  195. AES_192_KEY_SIZE = 24,
  196. AES_256_KEY_SIZE = 32
  197. };
  198. #endif
  199. #endif /* HAVE_SELFTEST */
  200. #endif
  201. #if defined(WOLFSSL_ASN_PRINT) || defined(WOLFSSL_DEBUG_ASN_TEMPLATE)
  202. /* String representations of tags. */
  203. static const char* tagString[4][32] = {
  204. /* Universal */
  205. {
  206. "EOC",
  207. "BOOLEAN",
  208. "INTEGER",
  209. "BIT STRING",
  210. "OCTET STRING",
  211. "NULL",
  212. "OBJECT ID",
  213. "ObjectDescriptor",
  214. "INSTANCE OF",
  215. "REAL",
  216. "ENUMERATED",
  217. "EMBEDDED PDV",
  218. "UT8String",
  219. "RELATIVE-OID",
  220. "(0x0e) 14",
  221. "(0x0f) 15",
  222. "SEQUENCE",
  223. "SET",
  224. "NumericString",
  225. "PrintableString",
  226. "T61String",
  227. "VideotexString",
  228. "IA5String",
  229. "UTCTime",
  230. "GeneralizedTime",
  231. "GraphicString",
  232. "ISO646String",
  233. "GeneralString",
  234. "UniversalString",
  235. "CHARACTER STRING",
  236. "BMPString",
  237. "(0x1f) 31",
  238. },
  239. /* Application */
  240. {
  241. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  242. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  243. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  244. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  245. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  246. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  247. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  248. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  249. },
  250. /* Context-Specific */
  251. {
  252. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  253. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  254. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  255. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  256. },
  257. /* Private */
  258. {
  259. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  260. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  261. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  262. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  263. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  264. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  265. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  266. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  267. }
  268. };
  269. /* Converts a tag byte to string.
  270. *
  271. * @param [in] tag BER tag value to interpret.
  272. * @return String corresponding to tag.
  273. */
  274. static const char* TagString(byte tag)
  275. {
  276. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  277. }
  278. #endif
  279. /* Calculates the minimum number of bytes required to encode the value.
  280. *
  281. * Only support up to 2^24-1.
  282. *
  283. * @param [in] value Value to be encoded.
  284. * @return Number of bytes to encode value.
  285. */
  286. static word32 BytePrecision(word32 value)
  287. {
  288. word32 i;
  289. for (i = (word32)sizeof(value) - 1; i; --i)
  290. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  291. break;
  292. return i;
  293. }
  294. /* DER encodes the length value in output buffer.
  295. *
  296. * 0 -> 2^7-1: <len byte>.
  297. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  298. *
  299. * @param [in] length Value to encode.
  300. * @param [in, out] output Buffer to encode into.
  301. * @return Number of bytes used in encoding.
  302. */
  303. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  304. {
  305. word32 i = 0;
  306. if (length < ASN_LONG_LENGTH)
  307. output[i++] = (byte)length;
  308. else {
  309. word32 j;
  310. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  311. for (j = BytePrecision(length); j; --j) {
  312. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  313. i++;
  314. }
  315. }
  316. return i;
  317. }
  318. #ifdef WOLFSSL_ASN_TEMPLATE
  319. /* Calculate the size of a DER encoded length value.
  320. *
  321. * 0 -> 2^7-1: <length byte>.
  322. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  323. *
  324. * @param [in] length Value to encode.
  325. * @return Number of bytes required to encode.
  326. */
  327. static word32 SizeASNLength(word32 length)
  328. {
  329. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  330. }
  331. /* Calculate the size of a DER encoded header.
  332. *
  333. * Header = Tag | Encoded length
  334. *
  335. * @param [in] length Length value to encode.
  336. * @return Number of bytes required to encode a DER header.
  337. */
  338. #define SizeASNHeader(length) \
  339. (1 + SizeASNLength(length))
  340. #endif
  341. #ifdef WOLFSSL_ASN_TEMPLATE
  342. #ifdef WOLFSSL_SMALL_STACK
  343. /* Declare the variable that is the dynamic data for decoding BER data.
  344. *
  345. * @param [in] name Variable name to declare.
  346. * @param [in] cnt Number of elements required.
  347. */
  348. #define DECL_ASNGETDATA(name, cnt) \
  349. ASNGetData* name = NULL
  350. /* Allocates the dynamic BER decoding data.
  351. *
  352. * @param [in] name Variable name to declare.
  353. * @param [in] cnt Number of elements required.
  354. * @param [in, out] err Error variable.
  355. * @param [in] heap Dynamic memory allocation hint.
  356. */
  357. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  358. do { \
  359. if ((err) == 0) { \
  360. (name) = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  361. DYNAMIC_TYPE_TMP_BUFFER); \
  362. if ((name) == NULL) { \
  363. (err) = MEMORY_E; \
  364. } \
  365. } \
  366. } \
  367. while (0)
  368. /* Allocates the dynamic BER decoding data and clears the memory.
  369. *
  370. * @param [in] name Variable name to declare.
  371. * @param [in] cnt Number of elements required.
  372. * @param [in, out] err Error variable.
  373. * @param [in] heap Dynamic memory allocation hint.
  374. */
  375. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  376. do { \
  377. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  378. if ((err) == 0) { \
  379. XMEMSET((name), 0, sizeof(ASNGetData) * (cnt)); \
  380. } \
  381. } \
  382. while (0)
  383. /* Disposes of the dynamic BER decoding data.
  384. *
  385. * @param [in] name Variable name to declare.
  386. * @param [in] heap Dynamic memory allocation hint.
  387. */
  388. #define FREE_ASNGETDATA(name, heap) \
  389. do { \
  390. if ((name) != NULL) { \
  391. XFREE((name), (heap), DYNAMIC_TYPE_TMP_BUFFER); \
  392. } \
  393. } \
  394. while (0)
  395. /* Declare the variable that is the dynamic data for encoding DER data.
  396. *
  397. * @param [in] name Variable name to declare.
  398. * @param [in] cnt Number of elements required.
  399. */
  400. #define DECL_ASNSETDATA(name, cnt) \
  401. ASNSetData* name = NULL
  402. /* Allocates the dynamic DER encoding data.
  403. *
  404. * @param [in] name Variable name to declare.
  405. * @param [in] cnt Number of elements required.
  406. * @param [in, out] err Error variable.
  407. * @param [in] heap Dynamic memory allocation hint.
  408. */
  409. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  410. do { \
  411. if ((err) == 0) { \
  412. (name) = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * (cnt), (heap), \
  413. DYNAMIC_TYPE_TMP_BUFFER); \
  414. if ((name) == NULL) { \
  415. (err) = MEMORY_E; \
  416. } \
  417. } \
  418. } \
  419. while (0)
  420. /* Allocates the dynamic DER encoding data and clears the memory.
  421. *
  422. * @param [in] name Variable name to declare.
  423. * @param [in] cnt Number of elements required.
  424. * @param [in, out] err Error variable.
  425. * @param [in] heap Dynamic memory allocation hint.
  426. */
  427. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  428. do { \
  429. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  430. if ((err) == 0) { \
  431. XMEMSET(name, 0, sizeof(ASNSetData) * (cnt)); \
  432. } \
  433. } \
  434. while (0)
  435. /* Disposes of the dynamic DER encoding data.
  436. *
  437. * @param [in] name Variable name to declare.
  438. * @param [in] heap Dynamic memory allocation hint.
  439. */
  440. #define FREE_ASNSETDATA(name, heap) \
  441. do { \
  442. if ((name) != NULL) { \
  443. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  444. } \
  445. } \
  446. while (0)
  447. #else
  448. /* Declare the variable that is the dynamic data for decoding BER data.
  449. *
  450. * @param [in] name Variable name to declare.
  451. * @param [in] cnt Number of elements required.
  452. */
  453. #define DECL_ASNGETDATA(name, cnt) \
  454. ASNGetData name[cnt]
  455. /* No implementation as declaration is static.
  456. *
  457. * @param [in] name Variable name to declare.
  458. * @param [in] cnt Number of elements required.
  459. * @param [in, out] err Error variable.
  460. * @param [in] heap Dynamic memory allocation hint.
  461. */
  462. #define ALLOC_ASNGETDATA(name, cnt, err, heap)
  463. /* Clears the memory of the dynamic BER encoding data.
  464. *
  465. * @param [in] name Variable name to declare.
  466. * @param [in] cnt Number of elements required.
  467. * @param [in, out] err Error variable.
  468. * @param [in] heap Dynamic memory allocation hint.
  469. */
  470. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  471. XMEMSET(name, 0, sizeof(name))
  472. /* No implementation as declaration is static.
  473. *
  474. * @param [in] name Variable name to declare.
  475. * @param [in] heap Dynamic memory allocation hint.
  476. */
  477. #define FREE_ASNGETDATA(name, heap)
  478. /* Declare the variable that is the dynamic data for encoding DER data.
  479. *
  480. * @param [in] name Variable name to declare.
  481. * @param [in] cnt Number of elements required.
  482. */
  483. #define DECL_ASNSETDATA(name, cnt) \
  484. ASNSetData name[cnt]
  485. /* No implementation as declaration is static.
  486. *
  487. * @param [in] name Variable name to declare.
  488. * @param [in] cnt Number of elements required.
  489. * @param [in, out] err Error variable.
  490. * @param [in] heap Dynamic memory allocation hint.
  491. */
  492. #define ALLOC_ASNSETDATA(name, cnt, err, heap)
  493. /* Clears the memory of the dynamic BER encoding data.
  494. *
  495. * @param [in] name Variable name to declare.
  496. * @param [in] cnt Number of elements required.
  497. * @param [in, out] err Error variable.
  498. * @param [in] heap Dynamic memory allocation hint.
  499. */
  500. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  501. XMEMSET(name, 0, sizeof(name))
  502. /* No implementation as declaration is static.
  503. *
  504. * @param [in] name Variable name to declare.
  505. * @param [in] heap Dynamic memory allocation hint.
  506. */
  507. #define FREE_ASNSETDATA(name, heap)
  508. #endif
  509. #ifdef DEBUG_WOLFSSL
  510. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  511. #if 0
  512. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  513. #endif
  514. #endif
  515. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  516. #include <stdarg.h>
  517. /* Log a message that has the printf format string.
  518. *
  519. * @param [in] <va_args> printf style arguments.
  520. */
  521. #define WOLFSSL_MSG_VSNPRINTF(...) \
  522. do { \
  523. char line[81]; \
  524. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  525. line[sizeof(line) - 1] = '\0'; \
  526. WOLFSSL_MSG(line); \
  527. } \
  528. while (0)
  529. #endif
  530. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  531. *
  532. * @param [in] asn ASN.1 items to encode.
  533. * @param [in] data_a Data to place in each item. Lengths set were not known.
  534. * @param [in] i Index of item to check.
  535. * @return 1 when ASN.1 item is an integer and MSB is 1.
  536. * @erturn 0 otherwise.
  537. */
  538. #define ASNIntMSBSet(asn, data_a, i) \
  539. (((asn)[i].tag == ASN_INTEGER) && \
  540. ((data_a)[i].data.buffer.data != NULL && \
  541. ((data_a)[i].data.buffer.data[0] & 0x80) == 0x80))
  542. /* Calculate the size of a DER encoded number.
  543. *
  544. * @param [in] n Number to be encoded.
  545. * @param [in] bits Maximum number of bits to encode.
  546. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  547. * @return Number of bytes to the ASN.1 item.
  548. */
  549. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  550. {
  551. int j;
  552. word32 len;
  553. len = 1 + 1 + (word32)bits / 8;
  554. /* Discover actual size by checking for high zeros. */
  555. for (j = bits - 8; j > 0; j -= 8) {
  556. if (n >> j)
  557. break;
  558. len--;
  559. }
  560. if (tag == ASN_BIT_STRING)
  561. len++;
  562. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  563. len++;
  564. return len;
  565. }
  566. /* Calculate the size of the data in the constructed item based on the
  567. * length of the ASN.1 items below.
  568. *
  569. * @param [in] asn ASN.1 items to encode.
  570. * @param [in, out] data Data to place in each item. Lengths set were not
  571. * known.
  572. * @param [in] idx Index of item working on.
  573. */
  574. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  575. int idx, int max)
  576. {
  577. int j;
  578. data[idx].data.buffer.length = 0;
  579. /* Sum the item length of all items underneath. */
  580. for (j = idx + 1; j < max; j++) {
  581. /* Stop looking if the next ASN.1 is same level or higher. */
  582. if (asn[j].depth <= asn[idx].depth)
  583. break;
  584. /* Only add in length if it is one level below. */
  585. if (asn[j].depth - 1 == asn[idx].depth) {
  586. data[idx].data.buffer.length += data[j].length;
  587. /* The length of a header only item doesn't include the data unless
  588. * a replacement buffer is supplied.
  589. */
  590. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  591. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  592. data[idx].data.buffer.length += data[j].data.buffer.length;
  593. }
  594. }
  595. }
  596. }
  597. /* Calculate the size of the DER encoding.
  598. *
  599. * Call SetASN_Items() to write encoding to a buffer.
  600. *
  601. * @param [in] asn ASN.1 items to encode.
  602. * @param [in, out] data Data to place in each item. Lengths set where not
  603. * known.
  604. * @param [in] count Count of items to encode.
  605. * @param [out] encSz Length of the DER encoding.
  606. * @return 0 on success.
  607. * @return BAD_STATE_E when the data type is not supported.
  608. */
  609. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  610. {
  611. int i;
  612. word32 sz = 0;
  613. word32 len;
  614. word32 dataLen;
  615. int length;
  616. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  617. WOLFSSL_ENTER("SizeASN_Items");
  618. #endif
  619. for (i = count - 1; i >= 0; i--) {
  620. /* Skip this ASN.1 item when encoding. */
  621. if (data[i].noOut) {
  622. /* Set the offset to the current size - used in writing DER. */
  623. data[i].offset = sz;
  624. continue;
  625. }
  626. len = 0;
  627. switch (data[i].dataType) {
  628. /* Calculate the size of the number of different sizes. */
  629. case ASN_DATA_TYPE_WORD8:
  630. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  631. break;
  632. case ASN_DATA_TYPE_WORD16:
  633. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  634. break;
  635. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  636. /* Not used yet! */
  637. case ASN_DATA_TYPE_WORD32:
  638. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  639. break;
  640. #endif
  641. case ASN_DATA_TYPE_MP:
  642. /* Calculate the size of the MP integer data. */
  643. length = mp_unsigned_bin_size(data[i].data.mp);
  644. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  645. len = (word32)SizeASNHeader((word32)length) + (word32)length;
  646. break;
  647. case ASN_DATA_TYPE_REPLACE_BUFFER:
  648. /* Buffer is put in directly - use the length. */
  649. len = data[i].data.buffer.length;
  650. break;
  651. case ASN_DATA_TYPE_NONE:
  652. /* Calculate the size based on the data to be included.
  653. * Mostly used for constructed items.
  654. */
  655. if (asn[i].headerOnly) {
  656. if (data[i].data.buffer.data != NULL) {
  657. /* Force all child nodes to be ignored. Buffer
  658. * overwrites children. */
  659. {
  660. int ii;
  661. for (ii = i + 1; ii < count; ii++) {
  662. if (asn[ii].depth <= asn[i].depth)
  663. break;
  664. sz -= data[ii].length;
  665. data[ii].noOut = 1;
  666. }
  667. }
  668. }
  669. else {
  670. /* Calculate data length from items below if no buffer
  671. * supplied. */
  672. SizeASN_CalcDataLength(asn, data, i, count);
  673. }
  674. }
  675. if (asn[i].tag == ASN_BOOLEAN) {
  676. dataLen = 1;
  677. }
  678. else {
  679. dataLen = data[i].data.buffer.length;
  680. }
  681. /* BIT_STRING and INTEGER have one byte prepended. */
  682. if ((asn[i].tag == ASN_BIT_STRING) ||
  683. ASNIntMSBSet(asn, data, i)) {
  684. dataLen++;
  685. /* ASN.1 items are below and cannot include extra byte. */
  686. if (asn[i].headerOnly) {
  687. len++;
  688. }
  689. }
  690. /* Add in the size of tag and length. */
  691. len += SizeASNHeader(dataLen);
  692. /* Include data in length if not header only or if
  693. * buffer supplied. */
  694. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  695. len += dataLen;
  696. }
  697. break;
  698. #ifdef DEBUG_WOLFSSL
  699. default:
  700. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  701. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  702. WOLFSSL_MSG("Bad data type");
  703. #endif
  704. return BAD_STATE_E;
  705. #endif
  706. }
  707. /* Set the total length of the item. */
  708. data[i].length = len;
  709. /* Add length to total size. */
  710. sz += len;
  711. /* Set the offset to the current size - used in writing DER. */
  712. data[i].offset = sz;
  713. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  714. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  715. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  716. asn[i].depth, "", TagString(asn[i].tag));
  717. #endif
  718. }
  719. *encSz = (int)sz;
  720. return 0;
  721. }
  722. /* Create the DER encoding of a number.
  723. *
  724. * Assumes that the out buffer is large enough for encoding.
  725. *
  726. * @param [in] n Number to be encoded.
  727. * @param [in] bits Maximum number of bits to encode.
  728. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  729. */
  730. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  731. {
  732. int j;
  733. word32 idx;
  734. byte len;
  735. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  736. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  737. idx = 2;
  738. /* Set the length of the number based on maximum bit length. */
  739. len = (byte)(bits / 8);
  740. /* Discover actual size by checking for leading zero bytes. */
  741. for (j = bits - 8; j > 0; j -= 8) {
  742. if ((n >> j) != 0) {
  743. break;
  744. }
  745. len--;
  746. }
  747. /* Keep j, index of first non-zero byte, for writing out. */
  748. /* A BIT_STRING has the number of unused bits in last byte prepended to
  749. * data.
  750. */
  751. if (tag == ASN_BIT_STRING) {
  752. byte unusedBits = 0;
  753. byte lastByte = (byte)(n >> j);
  754. /* Quick check last bit. */
  755. if ((lastByte & 0x01) == 0x00) {
  756. unusedBits++;
  757. /* Check each bit for first least significant bit set. */
  758. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  759. unusedBits++;
  760. }
  761. /* Add unused bits byte. */
  762. len++;
  763. out[idx++] = unusedBits;
  764. }
  765. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  766. * value positive. */
  767. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  768. len++;
  769. out[idx++] = 0;
  770. }
  771. /* Go back and put in length. */
  772. out[1] = len;
  773. /* Place in the required bytes of the number. */
  774. for (; j >= 0; j -= 8)
  775. out[idx++] = (byte)(n >> j);
  776. }
  777. /* Creates the DER encoding of the ASN.1 items.
  778. *
  779. * Assumes the output buffer is large enough to hold encoding.
  780. * Must call SizeASN_Items() to determine size of encoding and offsets.
  781. *
  782. * @param [in] asn ASN.1 items to encode.
  783. * @param [in] data Data to place in each item.
  784. * @param [in] count Count of items to encode.
  785. * @param [in, out] output Buffer to write encoding into.
  786. * @return Size of the DER encoding in bytes.
  787. */
  788. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  789. {
  790. int i;
  791. int length;
  792. int err;
  793. word32 sz;
  794. word32 idx;
  795. byte* out;
  796. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  797. WOLFSSL_ENTER("SetASN_Items");
  798. #endif
  799. /* Offset of first item is the total length.
  800. * SizeASN_Items() calculated this. */
  801. sz = data[0].offset;
  802. /* Write out each item. */
  803. for (i = 0; i < count; i++) {
  804. /* Skip items not writing out. */
  805. if (data[i].noOut)
  806. continue;
  807. /* Start position to write item based on reverse offsets. */
  808. out = output + sz - data[i].offset;
  809. /* Index from start of item out. */
  810. idx = 0;
  811. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  812. /* Put in the tag - not dumping in DER from buffer. */
  813. out[idx++] = asn[i].tag |
  814. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  815. }
  816. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  817. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  818. sz - data[i].offset,
  819. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  820. "", TagString(asn[i].tag));
  821. #endif
  822. switch (data[i].dataType) {
  823. /* Write out the length and data of a number. */
  824. case ASN_DATA_TYPE_WORD8:
  825. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  826. break;
  827. case ASN_DATA_TYPE_WORD16:
  828. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  829. break;
  830. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  831. /* Not used yet! */
  832. case ASN_DATA_TYPE_WORD32:
  833. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  834. break;
  835. #endif
  836. /* Write out the length and data of a multi-precision number. */
  837. case ASN_DATA_TYPE_MP:
  838. /* Get length in bytes. */
  839. length = mp_unsigned_bin_size(data[i].data.mp);
  840. /* Add one for leading zero to make encoding a positive num. */
  841. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  842. /* Write out length. */
  843. idx += SetASNLength((word32)length, out + idx);
  844. /* Write out leading zero to make positive. */
  845. if (mp_leading_bit(data[i].data.mp)) {
  846. out[idx++] = 0;
  847. }
  848. /* Encode number in big-endian byte array. */
  849. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  850. if (err != MP_OKAY) {
  851. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  852. return MP_TO_E;
  853. }
  854. break;
  855. case ASN_DATA_TYPE_REPLACE_BUFFER:
  856. if (data[i].data.buffer.data == NULL) {
  857. /* Return pointer for caller to use. */
  858. data[i].data.buffer.data = out + idx;
  859. }
  860. else {
  861. /* Dump in the DER encoded data. */
  862. XMEMCPY(out + idx, data[i].data.buffer.data,
  863. data[i].data.buffer.length);
  864. }
  865. break;
  866. case ASN_DATA_TYPE_NONE:
  867. if (asn[i].tag == ASN_BOOLEAN) {
  868. /* Always one byte of data. */
  869. out[idx++] = 1;
  870. /* TRUE = 0xff, FALSE = 0x00 */
  871. out[idx] = data[i].data.u8 ? 0xffU : 0x00U;
  872. }
  873. else if (asn[i].tag == ASN_TAG_NULL) {
  874. /* NULL tag is always a zero length item. */
  875. out[idx] = 0;
  876. }
  877. else {
  878. word32 dataLen = data[i].data.buffer.length;
  879. /* Add one to data length for BIT_STRING unused bits and
  880. * INTEGER leading zero to make positive.
  881. */
  882. if ((asn[i].tag == ASN_BIT_STRING) ||
  883. ASNIntMSBSet(asn, data, i)) {
  884. dataLen++;
  885. }
  886. /* Write out length. */
  887. idx += SetASNLength(dataLen, out + idx);
  888. if ((asn[i].tag == ASN_BIT_STRING) ||
  889. ASNIntMSBSet(asn, data, i)) {
  890. /* Write out leading byte. BIT_STRING has no unused bits
  891. * - use number data types if needed. */
  892. out[idx++] = 0x00;
  893. }
  894. /* Record pointer for caller if data not supplied. */
  895. if (data[i].data.buffer.data == NULL) {
  896. data[i].data.buffer.data = out + idx;
  897. }
  898. /* Copy supplied data if not putting out header only or
  899. * if buffer supplied. */
  900. else if (!asn[i].headerOnly ||
  901. data[i].data.buffer.data != NULL) {
  902. /* Allow data to come from output buffer. */
  903. XMEMMOVE(out + idx, data[i].data.buffer.data,
  904. data[i].data.buffer.length);
  905. }
  906. }
  907. break;
  908. #ifdef DEBUG_WOLFSSL
  909. default:
  910. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  911. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  912. #endif
  913. return BAD_STATE_E;
  914. #endif
  915. }
  916. }
  917. return (int)sz;
  918. }
  919. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  920. word32 oidType, int length);
  921. /* Maximum supported depth in ASN.1 description. */
  922. #define GET_ASN_MAX_DEPTH 7
  923. /* Maximum number of checked numbered choices. Only one of the items with the
  924. * number is allowed.
  925. */
  926. #define GET_ASN_MAX_CHOICES 2
  927. /* Use existing function to decode BER length encoding. */
  928. #define GetASN_Length GetLength_ex
  929. /* Check an INTEGER's first byte - must be a positive number.
  930. *
  931. * @param [in] input BER encoded data.
  932. * @param [in] idx Index of BIT_STRING data.
  933. * @param [in] length Length of input data.
  934. * @param [in] positive Indicates number must be positive.
  935. * @return 0 on success.
  936. * @return ASN_PARSE_E when 0 is not required but seen.
  937. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  938. */
  939. static int GetASN_Integer(const byte* input, word32 idx, int length,
  940. int positive)
  941. {
  942. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  943. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  944. /* Check contents consist of one or more octets. */
  945. if (length == 0) {
  946. WOLFSSL_MSG("Zero length INTEGER not allowed");
  947. return ASN_PARSE_E;
  948. }
  949. #endif
  950. if (input[idx] == 0) {
  951. /* Check leading zero byte required. */
  952. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  953. WOLFSSL_MSG("Zero not required on INTEGER");
  954. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  955. return ASN_PARSE_E;
  956. #endif
  957. }
  958. }
  959. /* Check whether a leading zero byte was required. */
  960. else if (positive && (input[idx] & 0x80)) {
  961. WOLFSSL_MSG("INTEGER is negative");
  962. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  963. return ASN_EXPECT_0_E;
  964. #endif /* WOLFSSL_ASN_INT_LEAD_0_ANY */
  965. }
  966. return 0;
  967. }
  968. /* Check a BIT_STRING's first byte - unused bits.
  969. *
  970. * @param [in] input BER encoded data.
  971. * @param [in] idx Index of BIT_STRING data.
  972. * @param [in] length Length of input data.
  973. * @return 0 on success.
  974. * @return ASN_PARSE_E when unused bits is invalid.
  975. */
  976. static int GetASN_BitString(const byte* input, word32 idx, int length)
  977. {
  978. #if !defined(HAVE_SELFTEST) && !defined(HAVE_FIPS) || \
  979. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  980. /* Check contents consist of one or more octets. */
  981. if (length == 0) {
  982. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  983. WOLFSSL_MSG("Zero length BIT STRING not allowed");
  984. #endif
  985. return ASN_PARSE_E;
  986. }
  987. #endif
  988. /* Ensure unused bits value is valid range. */
  989. if (input[idx] > 7) {
  990. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  991. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  992. input[idx]);
  993. #endif
  994. return ASN_PARSE_E;
  995. }
  996. /* Ensure unused bits are zero. */
  997. if ((byte)(input[idx + (word32)length - 1] << (8 - input[idx])) != 0) {
  998. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  999. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  1000. input[idx], input[idx + length - 1]);
  1001. #endif
  1002. return ASN_PARSE_E;
  1003. }
  1004. return 0;
  1005. }
  1006. /* Get the ASN.1 items from the BER encoding.
  1007. *
  1008. * @param [in] asn ASN.1 item expected.
  1009. * @param [in] data Data array to place found item into.
  1010. * @param [in] input BER encoded data.
  1011. * @param [in] idx Starting index of item data.
  1012. * @param [in] len Length of input buffer upto end of this item's data.
  1013. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  1014. * @return 0 on success.
  1015. * @return ASN_PARSE_E when BER encoded data is invalid.
  1016. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  1017. * @return MP_INIT_E when the unable to initialize an mp_int.
  1018. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1019. * @return BAD_STATE_E when the data type is not supported.
  1020. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1021. */
  1022. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  1023. const byte* input, word32 idx, int len,
  1024. int zeroPadded)
  1025. {
  1026. int i;
  1027. int err;
  1028. /* Parse data based on data type to extract. */
  1029. switch (data->dataType) {
  1030. /* Parse a data into a number of specified bits. */
  1031. case ASN_DATA_TYPE_WORD8:
  1032. /* Check data is small enough to fit. */
  1033. if (len != 1) {
  1034. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1035. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  1036. #endif
  1037. return ASN_PARSE_E;
  1038. }
  1039. /* Fill number with all of data. */
  1040. *data->data.u8 = input[idx];
  1041. break;
  1042. case ASN_DATA_TYPE_WORD16:
  1043. /* Check data is small enough to fit. */
  1044. if (len == 0 || len > 2) {
  1045. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1046. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  1047. #endif
  1048. return ASN_PARSE_E;
  1049. }
  1050. /* Fill number with all of data. */
  1051. *data->data.u16 = 0;
  1052. for (i = 0; i < len; i++) {
  1053. *data->data.u16 <<= 8;
  1054. *data->data.u16 |= input[idx + (word32)i] ;
  1055. }
  1056. break;
  1057. case ASN_DATA_TYPE_WORD32:
  1058. /* Check data is small enough to fit. */
  1059. if (len == 0 || len > 4) {
  1060. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1061. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1062. #endif
  1063. return ASN_PARSE_E;
  1064. }
  1065. /* Fill number with all of data. */
  1066. *data->data.u32 = 0;
  1067. for (i = 0; i < len; i++) {
  1068. *data->data.u32 <<= 8;
  1069. *data->data.u32 |= input[idx + (word32)i] ;
  1070. }
  1071. break;
  1072. case ASN_DATA_TYPE_BUFFER:
  1073. /* Check buffer is big enough to hold data. */
  1074. if (len > (int)*data->data.buffer.length) {
  1075. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1076. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1077. *data->data.buffer.length);
  1078. #endif
  1079. return ASN_PARSE_E;
  1080. }
  1081. /* Copy in data and record actual length seen. */
  1082. XMEMCPY(data->data.buffer.data, input + idx, (size_t)len);
  1083. *data->data.buffer.length = (word32)len;
  1084. break;
  1085. case ASN_DATA_TYPE_EXP_BUFFER:
  1086. /* Check data is same size expected. */
  1087. if (len != (int)data->data.ref.length) {
  1088. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1089. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1090. data->data.ref.length);
  1091. #endif
  1092. return ASN_PARSE_E;
  1093. }
  1094. /* Check data is same as expected. */
  1095. if (XMEMCMP(data->data.ref.data, input + idx, (size_t)len) != 0) {
  1096. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1097. WOLFSSL_MSG("Data not as expected");
  1098. #endif
  1099. return ASN_PARSE_E;
  1100. }
  1101. break;
  1102. case ASN_DATA_TYPE_MP:
  1103. case ASN_DATA_TYPE_MP_POS_NEG:
  1104. /* Initialize mp_int and read in big-endian byte array. */
  1105. if (mp_init(data->data.mp) != MP_OKAY) {
  1106. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1107. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1108. #endif
  1109. return MP_INIT_E;
  1110. }
  1111. FALL_THROUGH;
  1112. case ASN_DATA_TYPE_MP_INITED:
  1113. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx,
  1114. (word32)len);
  1115. if (err != 0) {
  1116. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1117. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1118. #endif
  1119. mp_clear(data->data.mp);
  1120. return ASN_GETINT_E;
  1121. }
  1122. #ifdef HAVE_WOLF_BIGINT
  1123. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1124. len);
  1125. if (err != 0) {
  1126. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1127. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1128. #endif
  1129. mp_clear(data->data.mp);
  1130. return ASN_GETINT_E;
  1131. }
  1132. #endif /* HAVE_WOLF_BIGINT */
  1133. #ifdef WOLFSSL_SP_INT_NEGATIVE
  1134. /* Don't always read as positive. */
  1135. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1136. (input[idx] & 0x80)) {
  1137. #ifdef MP_NEG
  1138. data->data.mp->sign = MP_NEG;
  1139. #else
  1140. #ifdef OPENSSL_EXTRA
  1141. /* public API wolfSSL_ASN1_INTEGER_get() depends
  1142. * indirectly on negative bignum handling here.
  1143. */
  1144. #error OPENSSL_EXTRA requires negative bignum support.
  1145. #endif
  1146. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1147. WOLFSSL_MSG_VSNPRINTF("ASN negative integer without bignum support.");
  1148. #endif
  1149. mp_clear(data->data.mp);
  1150. return ASN_GETINT_E;
  1151. #endif
  1152. }
  1153. #else
  1154. (void)zeroPadded;
  1155. #endif
  1156. break;
  1157. case ASN_DATA_TYPE_CHOICE:
  1158. /* Check if tag matched any of the choices specified. */
  1159. for (i = 0; data->data.choice[i] != 0; i++)
  1160. if (data->data.choice[i] == data->tag)
  1161. break;
  1162. if (data->data.choice[i] == 0) {
  1163. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1164. WOLFSSL_MSG("Tag didn't match a choice");
  1165. #endif
  1166. return ASN_PARSE_E;
  1167. }
  1168. /* Store data pointer and length for caller. */
  1169. data->data.ref.data = input + idx;
  1170. data->data.ref.length = (word32)len;
  1171. break;
  1172. case ASN_DATA_TYPE_NONE:
  1173. /* Default behaviour based on tag. */
  1174. if (asn->tag == ASN_BOOLEAN) {
  1175. /* BOOLEAN has only one byte of data in BER. */
  1176. if (len != 1) {
  1177. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1178. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1179. #endif
  1180. return ASN_PARSE_E;
  1181. }
  1182. if (data->data.u8 == NULL)
  1183. return BAD_STATE_E;
  1184. /* Store C boolean value. */
  1185. *data->data.u8 = (input[idx] != 0);
  1186. break;
  1187. }
  1188. if (asn->tag == ASN_TAG_NULL) {
  1189. /* NULL has no data in BER. */
  1190. if (len != 0) {
  1191. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1192. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1193. #endif
  1194. return ASN_EXPECT_0_E;
  1195. }
  1196. data->data.ref.data = input + idx;
  1197. break;
  1198. }
  1199. if (asn->tag == ASN_OBJECT_ID) {
  1200. word32 oidIdx = 0;
  1201. /* Store OID data pointer and length */
  1202. data->data.oid.data = input + idx;
  1203. data->data.oid.length = (word32)len;
  1204. /* Get the OID sum. */
  1205. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1206. data->data.oid.type, len);
  1207. if (err < 0) {
  1208. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1209. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1210. #endif
  1211. return err;
  1212. }
  1213. break;
  1214. }
  1215. /* Otherwise store data pointer and length. */
  1216. data->data.ref.data = input + idx;
  1217. data->data.ref.length = (word32)len;
  1218. break;
  1219. #ifdef DEBUG_WOLFSSL
  1220. default:
  1221. /* Bad ASN data type. */
  1222. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1223. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1224. #endif
  1225. return BAD_STATE_E;
  1226. #endif
  1227. }
  1228. return 0;
  1229. }
  1230. /* Get the ASN.1 items from the BER encoding.
  1231. *
  1232. * @param [in] asn ASN.1 items expected.
  1233. * @param [in] data Data array to place found items into.
  1234. * @param [in] count Count of items to parse.
  1235. * @param [in] complete Whether the whole buffer is to be used up.
  1236. * @param [in] input BER encoded data.
  1237. * @param [in, out] inOutIdx On in, starting index of data.
  1238. * On out, end of parsed data.
  1239. * @param [in] length Length of input buffer.
  1240. * @return 0 on success.
  1241. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1242. * is invalid.
  1243. * @return BUFFER_E when data in buffer is too small.
  1244. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1245. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1246. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1247. * non-zero length.
  1248. * @return MP_INIT_E when the unable to initialize an mp_int.
  1249. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1250. * @return BAD_STATE_E when the data type is not supported.
  1251. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1252. */
  1253. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1254. const byte* input, word32* inOutIdx, word32 length)
  1255. {
  1256. int i;
  1257. int j;
  1258. int err;
  1259. int len;
  1260. /* Current index into buffer. */
  1261. word32 idx = *inOutIdx;
  1262. /* Initialize the end index at each depth to be the length. */
  1263. word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
  1264. length, length };
  1265. /* Set choices to -1 to indicate they haven't been seen or found. */
  1266. signed char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1267. /* Not matching a choice right now. */
  1268. int choice = 0;
  1269. /* Current depth of ASN.1 item. */
  1270. int depth;
  1271. /* Minimum depth value seen. */
  1272. int minDepth;
  1273. /* Integer had a zero prepended. */
  1274. int zeroPadded;
  1275. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1276. WOLFSSL_ENTER("GetASN_Items");
  1277. #endif
  1278. /* Start depth at first items depth. */
  1279. minDepth = depth = asn[0].depth;
  1280. /* Check every ASN.1 item. */
  1281. for (i = 0; i < count; i++) {
  1282. /* Store offset of ASN.1 item. */
  1283. data[i].offset = idx;
  1284. /* Length of data in ASN.1 item starts empty. */
  1285. data[i].length = 0;
  1286. /* Get current item depth. */
  1287. depth = asn[i].depth;
  1288. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1289. if (depth > GET_ASN_MAX_DEPTH) {
  1290. WOLFSSL_MSG("Depth in template too large");
  1291. return ASN_PARSE_E;
  1292. }
  1293. #endif
  1294. /* Keep track of minimum depth. */
  1295. if (depth < minDepth) {
  1296. minDepth = depth;
  1297. }
  1298. /* Reset choice if different from previous. */
  1299. if (choice > 0 && asn[i].optional != choice) {
  1300. choice = 0;
  1301. }
  1302. /* Check if first of numbered choice. */
  1303. if (choice == 0 && asn[i].optional > 1) {
  1304. choice = asn[i].optional;
  1305. if (choiceMet[choice - 2] == -1) {
  1306. /* Choice seen but not found a match yet. */
  1307. choiceMet[choice - 2] = 0;
  1308. }
  1309. }
  1310. /* Check for end of data or not a choice and tag not matching. */
  1311. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1312. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1313. if (asn[i].optional) {
  1314. /* Skip over ASN.1 items underneath this optional item. */
  1315. for (j = i + 1; j < count; j++) {
  1316. if (asn[i].depth >= asn[j].depth)
  1317. break;
  1318. data[j].offset = idx;
  1319. data[j].length = 0;
  1320. }
  1321. i = j - 1;
  1322. continue;
  1323. }
  1324. /* Check for end of data. */
  1325. if (idx == length) {
  1326. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1327. WOLFSSL_MSG_VSNPRINTF(
  1328. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1329. i, data[i].offset, data[i].length,
  1330. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1331. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1332. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1333. length);
  1334. #endif
  1335. return BUFFER_E;
  1336. }
  1337. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1338. /* Show expected versus found. */
  1339. WOLFSSL_MSG_VSNPRINTF(
  1340. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1341. i, data[i].offset, data[i].length,
  1342. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1343. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1344. input[idx], TagString(input[idx]));
  1345. #endif
  1346. /* Check for end of data at this depth. */
  1347. if (idx == endIdx[depth]) {
  1348. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1349. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1350. endIdx[depth]);
  1351. #endif
  1352. return ASN_PARSE_E;
  1353. }
  1354. /* Expecting an OBJECT_ID */
  1355. if (asn[i].tag == ASN_OBJECT_ID) {
  1356. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1357. WOLFSSL_MSG("Expecting OBJECT ID");
  1358. #endif
  1359. return ASN_OBJECT_ID_E;
  1360. }
  1361. /* Expecting a BIT_STRING */
  1362. if (asn[i].tag == ASN_BIT_STRING) {
  1363. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1364. WOLFSSL_MSG("Expecting BIT STRING");
  1365. #endif
  1366. return ASN_BITSTR_E;
  1367. }
  1368. /* Not the expected tag. */
  1369. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1370. WOLFSSL_MSG("Bad tag");
  1371. #endif
  1372. return ASN_PARSE_E;
  1373. }
  1374. /* Store found tag in data. */
  1375. data[i].tag = input[idx];
  1376. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1377. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1378. /* Check constructed match expected for non-choice ASN.1 item. */
  1379. if (asn[i].constructed != constructed) {
  1380. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1381. WOLFSSL_MSG_VSNPRINTF(
  1382. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1383. i, data[i].offset, data[i].length,
  1384. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1385. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1386. input[idx], TagString(input[idx]));
  1387. if (!constructed) {
  1388. WOLFSSL_MSG("Not constructed");
  1389. }
  1390. else {
  1391. WOLFSSL_MSG("Not expected to be constructed");
  1392. }
  1393. #endif
  1394. return ASN_PARSE_E;
  1395. }
  1396. }
  1397. /* Move index to start of length. */
  1398. idx++;
  1399. /* Get the encoded length. */
  1400. if (GetASN_Length(input, &idx, &len, endIdx[depth], 1) < 0) {
  1401. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1402. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1403. endIdx[depth]);
  1404. #endif
  1405. return ASN_PARSE_E;
  1406. }
  1407. /* Store length of data. */
  1408. data[i].length = (word32)len;
  1409. /* Note the max length of items under this one. */
  1410. endIdx[depth + 1] = idx + (word32)len;
  1411. if (choice > 1) {
  1412. /* Note we found a number choice. */
  1413. choiceMet[choice - 2] = 1;
  1414. }
  1415. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1416. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1417. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1418. asn[i].depth, "", TagString(data[i].tag));
  1419. #endif
  1420. /* Assume no zero padding on INTEGER. */
  1421. zeroPadded = 0;
  1422. /* Check data types that prepended a byte. */
  1423. if (asn[i].tag == ASN_INTEGER) {
  1424. /* Check validity of first byte. */
  1425. err = GetASN_Integer(input, idx, len,
  1426. data[i].dataType == ASN_DATA_TYPE_MP ||
  1427. data[i].dataType == ASN_DATA_TYPE_MP_INITED);
  1428. if (err != 0)
  1429. return err;
  1430. if (len > 1 && input[idx] == 0) {
  1431. zeroPadded = 1;
  1432. /* Move over prepended byte. */
  1433. idx++;
  1434. len--;
  1435. }
  1436. }
  1437. else if (asn[i].tag == ASN_BIT_STRING) {
  1438. /* Check prepended byte is correct. */
  1439. err = GetASN_BitString(input, idx, len);
  1440. if (err != 0)
  1441. return err;
  1442. /* Move over prepended byte. */
  1443. idx++;
  1444. len--;
  1445. }
  1446. else if ((asn[i].tag == ASN_OBJECT_ID) && (len < 3)) {
  1447. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1448. WOLFSSL_MSG_VSNPRINTF("OID length must be 3 or more: %d", len);
  1449. #endif
  1450. return ASN_PARSE_E;
  1451. }
  1452. /* Don't parse data if only header required. */
  1453. if (asn[i].headerOnly) {
  1454. /* Store reference to data and length. */
  1455. data[i].data.ref.data = input + idx;
  1456. data[i].data.ref.length = (word32)len;
  1457. continue;
  1458. }
  1459. /* Store the data at idx in the ASN data item. */
  1460. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1461. if (err != 0) {
  1462. return err;
  1463. }
  1464. /* Move index to next item. */
  1465. idx += (word32)len;
  1466. /* When matched numbered choice ... */
  1467. if (asn[i].optional > 1) {
  1468. /* Skip over other ASN.1 items of the same number. */
  1469. for (j = i + 1; j < count; j++) {
  1470. if (asn[j].depth <= asn[i].depth &&
  1471. asn[j].optional != asn[i].optional) {
  1472. break;
  1473. }
  1474. }
  1475. i = j - 1;
  1476. }
  1477. }
  1478. if (complete) {
  1479. /* When expecting ASN.1 items to completely use data, check we did. */
  1480. for (j = depth; j > minDepth; j--) {
  1481. if (idx < endIdx[j]) {
  1482. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1483. WOLFSSL_MSG_VSNPRINTF(
  1484. "More data in constructed item at depth: %d", j - 1);
  1485. #endif
  1486. return ASN_PARSE_E;
  1487. }
  1488. }
  1489. }
  1490. /* Check all choices where met - found an item for them. */
  1491. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1492. if (choiceMet[j] == 0) {
  1493. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1494. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1495. #endif
  1496. return ASN_PARSE_E;
  1497. }
  1498. }
  1499. /* Return index after ASN.1 data has been parsed. */
  1500. *inOutIdx = idx;
  1501. return 0;
  1502. }
  1503. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1504. /* Calculate the size of the DER encoding.
  1505. *
  1506. * Call SetASN_Items() to write encoding to a buffer.
  1507. *
  1508. * @param [in] asn ASN.1 items to encode.
  1509. * @param [in, out] data Data to place in each item. Lengths set were not
  1510. * known.
  1511. * @param [in] count Count of items to encode.
  1512. * @param [out] len Length of the DER encoding.
  1513. * @return Size of the DER encoding in bytes.
  1514. */
  1515. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1516. ASNSetData *data, int count, int* encSz)
  1517. {
  1518. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1519. return SizeASN_Items(asn, data, count, encSz);
  1520. }
  1521. /* Creates the DER encoding of the ASN.1 items.
  1522. *
  1523. * Assumes the output buffer is large enough to hold encoding.
  1524. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1525. *
  1526. * Displays the template name first.
  1527. *
  1528. * @param [in] name Name of ASN.1 template.
  1529. * @param [in] asn ASN.1 items to encode.
  1530. * @param [in] data Data to place in each item.
  1531. * @param [in] count Count of items to encode.
  1532. * @param [in, out] output Buffer to write encoding into.
  1533. * @return Size of the DER encoding in bytes.
  1534. */
  1535. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1536. ASNSetData *data, int count, byte* output)
  1537. {
  1538. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1539. return SetASN_Items(asn, data, count, output);
  1540. }
  1541. /* Get the ASN.1 items from the BER encoding.
  1542. *
  1543. * Displays the template name first.
  1544. *
  1545. * @param [in] name Name of ASN.1 template.
  1546. * @param [in] asn ASN.1 items expected.
  1547. * @param [in] data Data array to place found items into.
  1548. * @param [in] count Count of items to parse.
  1549. * @param [in] complete Whether the whole buffer is to be used up.
  1550. * @param [in] input BER encoded data.
  1551. * @param [in, out] inOutIdx On in, starting index of data.
  1552. * On out, end of parsed data.
  1553. * @param [in] maxIdx Maximum index of input data.
  1554. * @return 0 on success.
  1555. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1556. * is invalid.
  1557. * @return BUFFER_E when data in buffer is too small.
  1558. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1559. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1560. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1561. * non-zero length.
  1562. * @return MP_INIT_E when the unable to initialize an mp_int.
  1563. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1564. * @return BAD_STATE_E when the data type is not supported.
  1565. */
  1566. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1567. ASNGetData *data, int count, int complete, const byte* input,
  1568. word32* inOutIdx, word32 maxIdx)
  1569. {
  1570. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1571. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1572. }
  1573. /* Calculate the size of the DER encoding.
  1574. *
  1575. * Call SetASN_Items() to write encoding to a buffer.
  1576. *
  1577. * @param [in] asn ASN.1 items to encode.
  1578. * @param [in, out] data Data to place in each item. Lengths set were not
  1579. * known.
  1580. * @param [in] count Count of items to encode.
  1581. * @param [out] len Length of the DER encoding.
  1582. * @return Size of the DER encoding in bytes.
  1583. */
  1584. #define SizeASN_Items(asn, data, count, encSz) \
  1585. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1586. /* Creates the DER encoding of the ASN.1 items.
  1587. *
  1588. * Assumes the output buffer is large enough to hold encoding.
  1589. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1590. *
  1591. * Displays the template name first.
  1592. *
  1593. * @param [in] name Name of ASN.1 template.
  1594. * @param [in] asn ASN.1 items to encode.
  1595. * @param [in] data Data to place in each item.
  1596. * @param [in] count Count of items to encode.
  1597. * @param [in, out] output Buffer to write encoding into.
  1598. * @return Size of the DER encoding in bytes.
  1599. */
  1600. #define SetASN_Items(asn, data, count, output) \
  1601. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1602. /* Get the ASN.1 items from the BER encoding.
  1603. *
  1604. * Displays the template name first.
  1605. *
  1606. * @param [in] name Name of ASN.1 template.
  1607. * @param [in] asn ASN.1 items expected.
  1608. * @param [in] data Data array to place found items into.
  1609. * @param [in] count Count of items to parse.
  1610. * @param [in] complete Whether the whole buffer is to be used up.
  1611. * @param [in] input BER encoded data.
  1612. * @param [in, out] inOutIdx On in, starting index of data.
  1613. * On out, end of parsed data.
  1614. * @param [in] maxIdx Maximum index of input data.
  1615. * @return 0 on success.
  1616. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1617. * is invalid.
  1618. * @return BUFFER_E when data in buffer is too small.
  1619. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1620. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1621. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1622. * non-zero length.
  1623. * @return MP_INIT_E when the unable to initialize an mp_int.
  1624. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1625. * @return BAD_STATE_E when the data type is not supported.
  1626. */
  1627. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1628. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1629. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1630. /* Decode a BER encoded constructed sequence.
  1631. *
  1632. * @param [in] input Buffer of BER encoded data.
  1633. * @param [in, out] inOutIdx On in, index to start decoding from.
  1634. * On out, index of next encoded byte.
  1635. * @param [out] len Length of data under SEQUENCE.
  1636. * @param [in] maxIdx Maximim index of data. Index of byte after SEQ.
  1637. * @param [in] complete All data used with SEQUENCE and data under.
  1638. * @return 0 on success.
  1639. * @return BUFFER_E when not enough data to complete decode.
  1640. * @return ASN_PARSE when decoding failed.
  1641. */
  1642. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1643. word32 maxIdx, int complete)
  1644. {
  1645. int ret = 0;
  1646. word32 idx = *inOutIdx;
  1647. /* Check buffer big enough for tag. */
  1648. if (idx + 1 > maxIdx) {
  1649. ret = BUFFER_E;
  1650. }
  1651. /* Check it is a constructed SEQUENCE. */
  1652. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1653. ret = ASN_PARSE_E;
  1654. }
  1655. /* Get the length. */
  1656. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1657. ret = ASN_PARSE_E;
  1658. }
  1659. /* Check all data used if complete set. */
  1660. if ((ret == 0) && complete && (idx + (word32)*len != maxIdx)) {
  1661. ret = ASN_PARSE_E;
  1662. }
  1663. if (ret == 0) {
  1664. /* Return index of next byte of encoded data. */
  1665. *inOutIdx = idx;
  1666. }
  1667. return ret;
  1668. }
  1669. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1670. /* Setup ASN data item to get an 8-bit number.
  1671. *
  1672. * @param [in] dataASN Dynamic ASN data item.
  1673. * @param [in] num Pointer to an 8-bit variable.
  1674. */
  1675. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1676. {
  1677. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1678. dataASN->data.u8 = num;
  1679. }
  1680. /* Setup ASN data item to get a 16-bit number.
  1681. *
  1682. * @param [in] dataASN Dynamic ASN data item.
  1683. * @param [in] num Pointer to a 16-bit variable.
  1684. */
  1685. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1686. {
  1687. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1688. dataASN->data.u16 = num;
  1689. }
  1690. /* Setup ASN data item to get a 32-bit number.
  1691. *
  1692. * @param [in] dataASN Dynamic ASN data item.
  1693. * @param [in] num Pointer to a 32-bit variable.
  1694. */
  1695. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1696. {
  1697. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1698. dataASN->data.u32 = num;
  1699. }
  1700. /* Setup ASN data item to get data into a buffer of a specific length.
  1701. *
  1702. * @param [in] dataASN Dynamic ASN data item.
  1703. * @param [in] data Buffer to hold data.
  1704. * @param [in] length Length of buffer in bytes.
  1705. */
  1706. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1707. {
  1708. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1709. dataASN->data.buffer.data = data;
  1710. dataASN->data.buffer.length = length;
  1711. }
  1712. /* Setup ASN data item to check parsed data against expected buffer.
  1713. *
  1714. * @param [in] dataASN Dynamic ASN data item.
  1715. * @param [in] data Buffer containing expected data.
  1716. * @param [in] length Length of buffer in bytes.
  1717. */
  1718. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1719. {
  1720. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1721. dataASN->data.ref.data = data;
  1722. dataASN->data.ref.length = length;
  1723. }
  1724. /* Setup ASN data item to get a number into an mp_int.
  1725. *
  1726. * @param [in] dataASN Dynamic ASN data item.
  1727. * @param [in] num Multi-precision number object.
  1728. */
  1729. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1730. {
  1731. dataASN->dataType = ASN_DATA_TYPE_MP;
  1732. dataASN->data.mp = num;
  1733. }
  1734. /* Setup ASN data item to get a number into an mp_int that is initialized.
  1735. *
  1736. * @param [in] dataASN Dynamic ASN data item.
  1737. * @param [in] num Multi-precision number object.
  1738. */
  1739. void GetASN_MP_Inited(ASNGetData *dataASN, mp_int* num)
  1740. {
  1741. dataASN->dataType = ASN_DATA_TYPE_MP_INITED;
  1742. dataASN->data.mp = num;
  1743. }
  1744. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1745. *
  1746. * @param [in] dataASN Dynamic ASN data item.
  1747. * @param [in] num Multi-precision number object.
  1748. */
  1749. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1750. {
  1751. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1752. dataASN->data.mp = num;
  1753. }
  1754. /* Setup ASN data item to be a choice of tags.
  1755. *
  1756. * @param [in] dataASN Dynamic ASN data item.
  1757. * @param [in] options 0 terminated list of tags that are valid.
  1758. */
  1759. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1760. {
  1761. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1762. dataASN->data.choice = options;
  1763. }
  1764. /* Setup ASN data item to get a boolean value.
  1765. *
  1766. * @param [in] dataASN Dynamic ASN data item.
  1767. * @param [in] num Pointer to an 8-bit variable.
  1768. */
  1769. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1770. {
  1771. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1772. dataASN->data.choice = num;
  1773. }
  1774. /* Setup ASN data item to be a an OID of a specific type.
  1775. *
  1776. * @param [in] dataASN Dynamic ASN data item.
  1777. * @param [in] oidType Type of OID to expect.
  1778. */
  1779. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1780. {
  1781. dataASN->data.oid.type = oidType;
  1782. }
  1783. /* Get the data and length from an ASN data item.
  1784. *
  1785. * @param [in] dataASN Dynamic ASN data item.
  1786. * @param [out] data Pointer to data of item.
  1787. * @param [out] length Length of buffer in bytes.
  1788. */
  1789. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1790. {
  1791. *data = dataASN->data.ref.data;
  1792. *length = dataASN->data.ref.length;
  1793. }
  1794. /* Get the data and length from an ASN data item.
  1795. *
  1796. * @param [in] dataASN Dynamic ASN data item.
  1797. * @param [out] data Pointer to data of item.
  1798. * @param [out] length Length of buffer in bytes.
  1799. */
  1800. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1801. {
  1802. *data = (byte*)dataASN->data.ref.data;
  1803. *length = dataASN->data.ref.length;
  1804. }
  1805. /* Get the data and length from an ASN data item that is an OID.
  1806. *
  1807. * @param [in] dataASN Dynamic ASN data item.
  1808. * @param [out] data Pointer to .
  1809. * @param [out] length Length of buffer in bytes.
  1810. */
  1811. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1812. {
  1813. *data = (byte*)dataASN->data.oid.data;
  1814. *length = dataASN->data.oid.length;
  1815. }
  1816. /* Setup an ASN data item to set a boolean.
  1817. *
  1818. * @param [in] dataASN Dynamic ASN data item.
  1819. * @param [in] val Boolean value.
  1820. */
  1821. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1822. {
  1823. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1824. dataASN->data.u8 = val;
  1825. }
  1826. /* Setup an ASN data item to set an 8-bit number.
  1827. *
  1828. * @param [in] dataASN Dynamic ASN data item.
  1829. * @param [in] num 8-bit number to set.
  1830. */
  1831. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1832. {
  1833. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1834. dataASN->data.u8 = num;
  1835. }
  1836. /* Setup an ASN data item to set a 16-bit number.
  1837. *
  1838. * @param [in] dataASN Dynamic ASN data item.
  1839. * @param [in] num 16-bit number to set.
  1840. */
  1841. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1842. {
  1843. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1844. dataASN->data.u16 = num;
  1845. }
  1846. /* Setup an ASN data item to set the data in a buffer.
  1847. *
  1848. * @param [in] dataASN Dynamic ASN data item.
  1849. * @param [in] data Buffer containing data to set.
  1850. * @param [in] length Length of data in buffer in bytes.
  1851. */
  1852. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1853. {
  1854. dataASN->data.buffer.data = data;
  1855. dataASN->data.buffer.length = length;
  1856. }
  1857. /* Setup an ASN data item to set the DER encode data in a buffer.
  1858. *
  1859. * @param [in] dataASN Dynamic ASN data item.
  1860. * @param [in] data Buffer containing BER encoded data to set.
  1861. * @param [in] length Length of data in buffer in bytes.
  1862. */
  1863. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1864. {
  1865. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1866. dataASN->data.buffer.data = data;
  1867. dataASN->data.buffer.length = length;
  1868. }
  1869. /* Setup an ASN data item to set an multi-precision number.
  1870. *
  1871. * @param [in] dataASN Dynamic ASN data item.
  1872. * @param [in] num Multi-precision number.
  1873. */
  1874. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1875. {
  1876. dataASN->dataType = ASN_DATA_TYPE_MP;
  1877. dataASN->data.mp = num;
  1878. }
  1879. /* Setup an ASN data item to set an OID based on id and type.
  1880. *
  1881. * oid and oidType pair are unique.
  1882. *
  1883. * @param [in] dataASN Dynamic ASN data item.
  1884. * @param [in] oid OID identifier.
  1885. * @param [in] oidType Type of OID.
  1886. */
  1887. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  1888. {
  1889. dataASN->data.buffer.data = OidFromId(oid, oidType,
  1890. &dataASN->data.buffer.length);
  1891. }
  1892. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  1893. #ifdef CRLDP_VALIDATE_DATA
  1894. /* Get the data of the BIT_STRING as a 16-bit number.
  1895. *
  1896. * @param [in] dataASN Dynamic ASN data item.
  1897. * @param [out] val ASN.1 item's data as a 16-bit number.
  1898. * @return 0 on success.
  1899. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  1900. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  1901. */
  1902. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  1903. {
  1904. int ret;
  1905. int i;
  1906. const byte* input = dataASN->data.ref.data;
  1907. int length = dataASN->data.ref.length;
  1908. /* Validate the BIT_STRING data. */
  1909. ret = GetASN_BitString(input, 0, length);
  1910. if (ret == 0) {
  1911. /* Skip unused bits byte. */
  1912. input++;
  1913. length--;
  1914. /* Check the data is usable. */
  1915. if (length == 0 || length > 2) {
  1916. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1917. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  1918. #endif
  1919. ret = ASN_PARSE_E;
  1920. }
  1921. }
  1922. if (ret == 0) {
  1923. /* Fill 16-bit var with all the data. */
  1924. *val = 0;
  1925. for (i = 0; i < length; i++) {
  1926. *val <<= 8;
  1927. *val |= input[i];
  1928. }
  1929. }
  1930. return ret;
  1931. }
  1932. #endif /* CRLDP_VALIDATE_DATA */
  1933. #endif /* WOLFSSL_ASN_TEMPLATE */
  1934. /* Decode the BER/DER length field.
  1935. *
  1936. * @param [in] input BER encoded data.
  1937. * @param [in, out] inOutIdx On in, starting index of length.
  1938. * On out, end of parsed length.
  1939. * @param [out] len Length value decoded.
  1940. * @param [in] maxIdx Maximum index of input data.
  1941. * @return Length on success.
  1942. * @return ASN_PARSE_E if the encoding is invalid.
  1943. * @return BUFFER_E when not enough data to complete decode.
  1944. */
  1945. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  1946. {
  1947. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  1948. }
  1949. /* Decode the BER/DER length field and check the length is valid on request.
  1950. *
  1951. * BER/DER has Type-Length-Value triplets.
  1952. * When requested will check that the Length decoded, indicating the number
  1953. * of bytes in the Value, is available in the buffer after the Length bytes.
  1954. *
  1955. * Only supporting a length upto INT_MAX.
  1956. *
  1957. * @param [in] input BER encoded data.
  1958. * @param [in, out] inOutIdx On in, starting index of length.
  1959. * On out, end of parsed length.
  1960. * @param [out] len Length value decoded.
  1961. * @param [in] maxIdx Maximum index of input data.
  1962. * @param [in] check Whether to check the buffer has at least the
  1963. * decoded length of bytes remaining.
  1964. * @return Length on success.
  1965. * @return ASN_PARSE_E if the encoding is invalid.
  1966. * @return BUFFER_E when not enough data to complete decode.
  1967. */
  1968. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  1969. int check)
  1970. {
  1971. int length = 0;
  1972. word32 idx = (word32)*inOutIdx;
  1973. byte b;
  1974. /* Ensure zero return length on error. */
  1975. *len = 0;
  1976. /* Check there is at least one byte available containing length information.
  1977. */
  1978. if ((idx + 1) > maxIdx) {
  1979. WOLFSSL_MSG("GetLength - bad index on input");
  1980. return BUFFER_E;
  1981. }
  1982. /* Get the first length byte. */
  1983. b = input[idx++];
  1984. /* Check if the first byte indicates the count of bytes. */
  1985. if (b >= ASN_LONG_LENGTH) {
  1986. /* Bottom 7 bits are the number of bytes to calculate length with.
  1987. * Note: 0 indicates indefinite length encoding *not* 0 bytes of length.
  1988. */
  1989. word32 bytes = (word32)b & 0x7FU;
  1990. int minLen;
  1991. /* Calculate minimum length to be encoded with bytes. */
  1992. if (b == ASN_INDEF_LENGTH) {
  1993. /* Indefinite length encoding - no length bytes. */
  1994. minLen = 0;
  1995. }
  1996. else if (bytes == 1) {
  1997. minLen = 0x80;
  1998. }
  1999. /* Only support up to the number of bytes that fit into return var. */
  2000. else if (bytes > sizeof(length)) {
  2001. WOLFSSL_MSG("GetLength - overlong data length spec");
  2002. return ASN_PARSE_E;
  2003. } else {
  2004. minLen = 1 << ((bytes - 1) * 8);
  2005. }
  2006. /* Check the number of bytes required are available. */
  2007. if ((idx + bytes) > maxIdx) {
  2008. WOLFSSL_MSG("GetLength - bad long length");
  2009. return BUFFER_E;
  2010. }
  2011. /* Big-endian encoding of number. */
  2012. while (bytes--) {
  2013. b = input[idx++];
  2014. length = (length << 8) | b;
  2015. }
  2016. /* Negative value indicates we overflowed the signed int. */
  2017. if (length < 0) {
  2018. return ASN_PARSE_E;
  2019. }
  2020. /* Don't allow lengths that are longer than strictly required. */
  2021. if (length < minLen) {
  2022. return ASN_PARSE_E;
  2023. }
  2024. }
  2025. else {
  2026. /* Length in first byte. */
  2027. length = b;
  2028. }
  2029. /* When requested, check the buffer has at least length bytes left. */
  2030. if (check && ((idx + (word32)length) > maxIdx)) {
  2031. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  2032. return BUFFER_E;
  2033. }
  2034. /* Return index after length encoding. */
  2035. *inOutIdx = idx;
  2036. /* Return length if valid. */
  2037. if (length > 0) {
  2038. *len = length;
  2039. }
  2040. /* Return length calculated or error code. */
  2041. return length;
  2042. }
  2043. /* Gets the tag of next BER/DER encoded item.
  2044. *
  2045. * Checks there is enough data in the buffer for the tag byte.
  2046. *
  2047. * @param [in] input BER encoded data.
  2048. * @param [in, out] inOutIdx On in, starting index of tag.
  2049. * On out, end of parsed tag.
  2050. * @param [out] tag Tag value found.
  2051. * @param [in] maxIdx Maximum index of input data.
  2052. *
  2053. * return 0 on success
  2054. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  2055. * return BUFFER_E when not enough space in buffer for tag.
  2056. */
  2057. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  2058. {
  2059. int ret = 0;
  2060. word32 idx = 0;
  2061. /* Check validity of parameters. */
  2062. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  2063. ret = BAD_FUNC_ARG;
  2064. }
  2065. if (ret == 0) {
  2066. /* Get index and ensure space for tag. */
  2067. idx = *inOutIdx;
  2068. if (idx + ASN_TAG_SZ > maxIdx) {
  2069. WOLFSSL_MSG("Buffer too small for ASN tag");
  2070. ret = BUFFER_E;
  2071. }
  2072. }
  2073. if (ret == 0) {
  2074. /* Return the tag and the index after tag. */
  2075. *tag = input[idx];
  2076. *inOutIdx = idx + ASN_TAG_SZ;
  2077. }
  2078. /* Return error code. */
  2079. return ret;
  2080. }
  2081. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  2082. *
  2083. * BER/DER has Type-Length-Value triplets.
  2084. * Check that the tag/type is the required value.
  2085. * When requested will check that the Length decoded, indicating the number
  2086. * of bytes in the Value, is available in the buffer after the Length bytes.
  2087. *
  2088. * Only supporting a length upto INT_MAX.
  2089. *
  2090. * @param [in] input Buffer holding DER/BER encoded data.
  2091. * @param [in] tag ASN.1 tag value expected in header.
  2092. * @param [in, out] inOutIdx On in, starting index of header.
  2093. * On out, end of parsed header.
  2094. * @param [out] len Number of bytes in the ASN.1 data.
  2095. * @param [in] maxIdx Length of data in buffer.
  2096. * @param [in] check Whether to check the buffer has at least the
  2097. * decoded length of bytes remaining.
  2098. * @return Number of bytes in the ASN.1 data on success.
  2099. * @return BUFFER_E when there is not enough data to parse.
  2100. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2101. */
  2102. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  2103. int* len, word32 maxIdx, int check)
  2104. {
  2105. int ret = 0;
  2106. word32 idx = *inOutIdx;
  2107. byte tagFound;
  2108. int length = 0;
  2109. /* Get tag/type. */
  2110. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2111. ret = ASN_PARSE_E;
  2112. }
  2113. /* Ensure tag is the expected value. */
  2114. if ((ret == 0) && (tagFound != tag)) {
  2115. ret = ASN_PARSE_E;
  2116. }
  2117. /* Get the encoded length. */
  2118. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2119. ret = ASN_PARSE_E;
  2120. }
  2121. if (ret == 0) {
  2122. /* Return the length of data and index after header. */
  2123. *len = length;
  2124. *inOutIdx = idx;
  2125. ret = length;
  2126. }
  2127. /* Return number of data bytes or error code. */
  2128. return ret;
  2129. }
  2130. /* Decode the DER/BER header (Type-Length) and check the length.
  2131. *
  2132. * BER/DER has Type-Length-Value triplets.
  2133. * Check that the tag/type is the required value.
  2134. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2135. * is available in the buffer after the Length bytes.
  2136. *
  2137. * @param [in] input Buffer holding DER/BER encoded data.
  2138. * @param [in] tag ASN.1 tag value expected in header.
  2139. * @param [in, out] inOutIdx On in, starting index of header.
  2140. * On out, end of parsed header.
  2141. * @param [out] len Number of bytes in the ASN.1 data.
  2142. * @param [in] maxIdx Length of data in buffer.
  2143. * @return Number of bytes in the ASN.1 data on success.
  2144. * @return BUFFER_E when there is not enough data to parse.
  2145. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2146. */
  2147. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2148. word32 maxIdx)
  2149. {
  2150. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2151. }
  2152. #ifndef WOLFSSL_ASN_TEMPLATE
  2153. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2154. word32 maxIdx, int check)
  2155. {
  2156. word32 idx = *inOutIdx;
  2157. int length;
  2158. if ((idx + 1) > maxIdx)
  2159. return BUFFER_E;
  2160. *tag = input[idx++];
  2161. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2162. return ASN_PARSE_E;
  2163. *len = length;
  2164. *inOutIdx = idx;
  2165. return length;
  2166. }
  2167. #endif
  2168. /* Decode the header of a BER/DER encoded SEQUENCE.
  2169. *
  2170. * @param [in] input Buffer holding DER/BER encoded data.
  2171. * @param [in, out] inOutIdx On in, starting index of header.
  2172. * On out, end of parsed header.
  2173. * @param [out] len Number of bytes in the ASN.1 data.
  2174. * @param [in] maxIdx Length of data in buffer.
  2175. * @return Number of bytes in the ASN.1 data on success.
  2176. * @return BUFFER_E when there is not enough data to parse.
  2177. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2178. */
  2179. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2180. word32 maxIdx)
  2181. {
  2182. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2183. maxIdx);
  2184. }
  2185. /* Decode the header of a BER/DER encoded SEQUENCE.
  2186. *
  2187. * @param [in] input Buffer holding DER/BER encoded data.
  2188. * @param [in, out] inOutIdx On in, starting index of header.
  2189. * On out, end of parsed header.
  2190. * @param [out] len Number of bytes in the ASN.1 data.
  2191. * @param [in] maxIdx Length of data in buffer.
  2192. * @param [in] check Whether to check the buffer has at least the
  2193. * decoded length of bytes remaining.
  2194. * @return Number of bytes in the ASN.1 data on success.
  2195. * @return BUFFER_E when there is not enough data to parse.
  2196. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2197. */
  2198. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2199. word32 maxIdx, int check)
  2200. {
  2201. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2202. maxIdx, check);
  2203. }
  2204. /* Decode the header of a BER/DER encoded SET.
  2205. *
  2206. * @param [in] input Buffer holding DER/BER encoded data.
  2207. * @param [in, out] inOutIdx On in, starting index of header.
  2208. * On out, end of parsed header.
  2209. * @param [out] len Number of bytes in the ASN.1 data.
  2210. * @param [in] maxIdx Length of data in buffer.
  2211. * @return Number of bytes in the ASN.1 data on success.
  2212. * @return BUFFER_E when there is not enough data to parse.
  2213. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2214. */
  2215. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2216. word32 maxIdx)
  2217. {
  2218. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2219. maxIdx);
  2220. }
  2221. /* Decode the header of a BER/DER encoded SET.
  2222. *
  2223. * @param [in] input Buffer holding DER/BER encoded data.
  2224. * @param [in, out] inOutIdx On in, starting index of header.
  2225. * On out, end of parsed header.
  2226. * @param [out] len Number of bytes in the ASN.1 data.
  2227. * @param [in] maxIdx Length of data in buffer.
  2228. * @param [in] check Whether to check the buffer has at least the
  2229. * decoded length of bytes remaining.
  2230. * @return Number of bytes in the ASN.1 data on success.
  2231. * @return BUFFER_E when there is not enough data to parse.
  2232. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2233. */
  2234. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2235. word32 maxIdx, int check)
  2236. {
  2237. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2238. maxIdx, check);
  2239. }
  2240. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2241. /* Decode the BER/DER encoded NULL.
  2242. *
  2243. * No data in a NULL ASN.1 item.
  2244. * Ensure that the all fields are as expected and move index past the element.
  2245. *
  2246. * @param [in] input Buffer holding DER/BER encoded data.
  2247. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2248. * On out, end of parsed NULL item.
  2249. * @param [in] maxIdx Length of data in buffer.
  2250. * @return 0 on success.
  2251. * @return BUFFER_E when there is not enough data to parse.
  2252. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2253. * @return ASN_EXPECT_0_E when the length is not zero.
  2254. */
  2255. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2256. {
  2257. int ret = 0;
  2258. word32 idx = *inOutIdx;
  2259. /* Check buffer has enough data for a NULL item. */
  2260. if ((idx + 2) > maxIdx) {
  2261. ret = BUFFER_E;
  2262. }
  2263. /* Check the tag is NULL. */
  2264. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2265. ret = ASN_TAG_NULL_E;
  2266. }
  2267. /* Check the length is zero. */
  2268. if ((ret == 0) && (input[idx++] != 0)) {
  2269. ret = ASN_EXPECT_0_E;
  2270. }
  2271. if (ret == 0) {
  2272. /* Return the index after NULL tag. */
  2273. *inOutIdx = idx;
  2274. }
  2275. /* Return error code. */
  2276. return ret;
  2277. }
  2278. #endif
  2279. #ifndef WOLFSSL_ASN_TEMPLATE
  2280. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2281. *
  2282. * output Buffer to write into.
  2283. * returns the number of bytes added to the buffer.
  2284. */
  2285. static int SetASNNull(byte* output)
  2286. {
  2287. output[0] = ASN_TAG_NULL;
  2288. output[1] = 0;
  2289. return 2;
  2290. }
  2291. #endif
  2292. #ifndef NO_CERTS
  2293. #ifndef WOLFSSL_ASN_TEMPLATE
  2294. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2295. *
  2296. * input Buffer holding DER/BER encoded data.
  2297. * inOutIdx Current index into buffer to parse.
  2298. * maxIdx Length of data in buffer.
  2299. * returns BUFFER_E when there is not enough data to parse.
  2300. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2301. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2302. */
  2303. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2304. {
  2305. word32 idx = *inOutIdx;
  2306. byte b;
  2307. if ((idx + 3) > maxIdx)
  2308. return BUFFER_E;
  2309. b = input[idx++];
  2310. if (b != ASN_BOOLEAN)
  2311. return ASN_PARSE_E;
  2312. if (input[idx++] != 1)
  2313. return ASN_PARSE_E;
  2314. b = input[idx++] != 0;
  2315. *inOutIdx = idx;
  2316. return b;
  2317. }
  2318. #endif
  2319. #endif /* !NO_CERTS*/
  2320. /* Decode the header of a BER/DER encoded OCTET STRING.
  2321. *
  2322. * @param [in] input Buffer holding DER/BER encoded data.
  2323. * @param [in, out] inOutIdx On in, starting index of header.
  2324. * On out, end of parsed header.
  2325. * @param [out] len Number of bytes in the ASN.1 data.
  2326. * @param [in] maxIdx Length of data in buffer.
  2327. * @return Number of bytes in the ASN.1 data on success.
  2328. * @return BUFFER_E when there is not enough data to parse.
  2329. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2330. */
  2331. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2332. {
  2333. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2334. }
  2335. #ifndef WOLFSSL_ASN_TEMPLATE
  2336. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2337. *
  2338. * Removes the leading zero byte when found.
  2339. *
  2340. * input Buffer holding DER/BER encoded data.
  2341. * inOutIdx Current index into buffer to parse.
  2342. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2343. * maxIdx Length of data in buffer.
  2344. * returns BUFFER_E when there is not enough data to parse.
  2345. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2346. * or invalid use of or missing leading zero.
  2347. * Otherwise, 0 to indicate success.
  2348. */
  2349. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2350. word32 maxIdx)
  2351. {
  2352. int ret;
  2353. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2354. if (ret < 0)
  2355. return ret;
  2356. if (*len > 0) {
  2357. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2358. /* check for invalid padding on negative integer.
  2359. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2360. */
  2361. if (*len > 1) {
  2362. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2363. return ASN_PARSE_E;
  2364. }
  2365. #endif
  2366. /* remove leading zero, unless there is only one 0x00 byte */
  2367. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2368. (*inOutIdx)++;
  2369. (*len)--;
  2370. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2371. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2372. return ASN_PARSE_E;
  2373. #endif
  2374. }
  2375. }
  2376. return 0;
  2377. }
  2378. #ifndef NO_CERTS
  2379. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2380. * 7 bits.
  2381. *
  2382. * input Buffer holding DER/BER encoded data.
  2383. * inOutIdx Current index into buffer to parse.
  2384. * maxIdx Length of data in buffer.
  2385. * returns BUFFER_E when there is not enough data to parse.
  2386. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2387. * Otherwise, the 7-bit value.
  2388. */
  2389. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2390. {
  2391. word32 idx = *inOutIdx;
  2392. byte b;
  2393. if ((idx + 3) > maxIdx)
  2394. return BUFFER_E;
  2395. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2396. return ASN_PARSE_E;
  2397. if (b != ASN_INTEGER)
  2398. return ASN_PARSE_E;
  2399. if (input[idx++] != 1)
  2400. return ASN_PARSE_E;
  2401. b = input[idx++];
  2402. *inOutIdx = idx;
  2403. return b;
  2404. }
  2405. #endif /* !NO_CERTS */
  2406. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  2407. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2408. * 16 bits.
  2409. *
  2410. * input Buffer holding DER/BER encoded data.
  2411. * inOutIdx Current index into buffer to parse.
  2412. * maxIdx Length of data in buffer.
  2413. * returns BUFFER_E when there is not enough data to parse.
  2414. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2415. * Otherwise, the 16-bit value.
  2416. */
  2417. static int GetInteger16Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2418. {
  2419. word32 idx = *inOutIdx;
  2420. byte tag;
  2421. word16 n;
  2422. if ((idx + 2) > maxIdx)
  2423. return BUFFER_E;
  2424. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2425. return ASN_PARSE_E;
  2426. if (tag != ASN_INTEGER)
  2427. return ASN_PARSE_E;
  2428. if (input[idx] == 1) {
  2429. idx++;
  2430. if ((idx + 1) > maxIdx) {
  2431. return ASN_PARSE_E;
  2432. }
  2433. n = input[idx++];
  2434. }
  2435. else if (input[idx] == 2) {
  2436. idx++;
  2437. if ((idx + 2) > maxIdx) {
  2438. return ASN_PARSE_E;
  2439. }
  2440. n = input[idx++];
  2441. n = (n << 8) | input[idx++];
  2442. }
  2443. else
  2444. return ASN_PARSE_E;
  2445. *inOutIdx = idx;
  2446. return n;
  2447. }
  2448. #endif /* WC_RSA_PSS && !NO_RSA */
  2449. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2450. #if !defined(NO_DSA) && !defined(NO_SHA)
  2451. static const char sigSha1wDsaName[] = "SHAwDSA";
  2452. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2453. #endif /* NO_DSA */
  2454. #ifndef NO_RSA
  2455. #ifdef WOLFSSL_MD2
  2456. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2457. #endif
  2458. #ifndef NO_MD5
  2459. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2460. #endif
  2461. #ifndef NO_SHA
  2462. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2463. #endif
  2464. #ifdef WOLFSSL_SHA224
  2465. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2466. #endif
  2467. #ifndef NO_SHA256
  2468. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2469. #endif
  2470. #ifdef WOLFSSL_SHA384
  2471. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2472. #endif
  2473. #ifdef WOLFSSL_SHA512
  2474. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2475. #endif
  2476. #ifdef WOLFSSL_SHA3
  2477. #ifndef WOLFSSL_NOSHA3_224
  2478. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2479. #endif
  2480. #ifndef WOLFSSL_NOSHA3_256
  2481. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2482. #endif
  2483. #ifndef WOLFSSL_NOSHA3_384
  2484. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2485. #endif
  2486. #ifndef WOLFSSL_NOSHA3_512
  2487. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2488. #endif
  2489. #endif
  2490. #ifdef WC_RSA_PSS
  2491. static const char sigRsaSsaPssName[] = "rsassaPss";
  2492. #endif
  2493. #endif /* NO_RSA */
  2494. #ifdef HAVE_ECC
  2495. #ifndef NO_SHA
  2496. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2497. #endif
  2498. #ifdef WOLFSSL_SHA224
  2499. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2500. #endif
  2501. #ifndef NO_SHA256
  2502. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2503. #endif
  2504. #ifdef WOLFSSL_SHA384
  2505. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2506. #endif
  2507. #ifdef WOLFSSL_SHA512
  2508. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2509. #endif
  2510. #ifdef WOLFSSL_SHA3
  2511. #ifndef WOLFSSL_NOSHA3_224
  2512. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2513. #endif
  2514. #ifndef WOLFSSL_NOSHA3_256
  2515. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2516. #endif
  2517. #ifndef WOLFSSL_NOSHA3_384
  2518. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2519. #endif
  2520. #ifndef WOLFSSL_NOSHA3_512
  2521. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2522. #endif
  2523. #endif
  2524. #endif /* HAVE_ECC */
  2525. static const char sigUnknownName[] = "Unknown";
  2526. /* Get the human readable string for a signature type
  2527. *
  2528. * oid Oid value for signature
  2529. */
  2530. const char* GetSigName(int oid) {
  2531. switch (oid) {
  2532. #if !defined(NO_DSA) && !defined(NO_SHA)
  2533. case CTC_SHAwDSA:
  2534. return sigSha1wDsaName;
  2535. case CTC_SHA256wDSA:
  2536. return sigSha256wDsaName;
  2537. #endif /* NO_DSA && NO_SHA */
  2538. #ifndef NO_RSA
  2539. #ifdef WOLFSSL_MD2
  2540. case CTC_MD2wRSA:
  2541. return sigMd2wRsaName;
  2542. #endif
  2543. #ifndef NO_MD5
  2544. case CTC_MD5wRSA:
  2545. return sigMd5wRsaName;
  2546. #endif
  2547. #ifndef NO_SHA
  2548. case CTC_SHAwRSA:
  2549. return sigSha1wRsaName;
  2550. #endif
  2551. #ifdef WOLFSSL_SHA224
  2552. case CTC_SHA224wRSA:
  2553. return sigSha224wRsaName;
  2554. #endif
  2555. #ifndef NO_SHA256
  2556. case CTC_SHA256wRSA:
  2557. return sigSha256wRsaName;
  2558. #endif
  2559. #ifdef WOLFSSL_SHA384
  2560. case CTC_SHA384wRSA:
  2561. return sigSha384wRsaName;
  2562. #endif
  2563. #ifdef WOLFSSL_SHA512
  2564. case CTC_SHA512wRSA:
  2565. return sigSha512wRsaName;
  2566. #endif
  2567. #ifdef WOLFSSL_SHA3
  2568. #ifndef WOLFSSL_NOSHA3_224
  2569. case CTC_SHA3_224wRSA:
  2570. return sigSha3_224wRsaName;
  2571. #endif
  2572. #ifndef WOLFSSL_NOSHA3_256
  2573. case CTC_SHA3_256wRSA:
  2574. return sigSha3_256wRsaName;
  2575. #endif
  2576. #ifndef WOLFSSL_NOSHA3_384
  2577. case CTC_SHA3_384wRSA:
  2578. return sigSha3_384wRsaName;
  2579. #endif
  2580. #ifndef WOLFSSL_NOSHA3_512
  2581. case CTC_SHA3_512wRSA:
  2582. return sigSha3_512wRsaName;
  2583. #endif
  2584. #endif
  2585. #ifdef WC_RSA_PSS
  2586. case CTC_RSASSAPSS:
  2587. return sigRsaSsaPssName;
  2588. #endif
  2589. #endif /* NO_RSA */
  2590. #ifdef HAVE_ECC
  2591. #ifndef NO_SHA
  2592. case CTC_SHAwECDSA:
  2593. return sigSha1wEcdsaName;
  2594. #endif
  2595. #ifdef WOLFSSL_SHA224
  2596. case CTC_SHA224wECDSA:
  2597. return sigSha224wEcdsaName;
  2598. #endif
  2599. #ifndef NO_SHA256
  2600. case CTC_SHA256wECDSA:
  2601. return sigSha256wEcdsaName;
  2602. #endif
  2603. #ifdef WOLFSSL_SHA384
  2604. case CTC_SHA384wECDSA:
  2605. return sigSha384wEcdsaName;
  2606. #endif
  2607. #ifdef WOLFSSL_SHA512
  2608. case CTC_SHA512wECDSA:
  2609. return sigSha512wEcdsaName;
  2610. #endif
  2611. #ifdef WOLFSSL_SHA3
  2612. #ifndef WOLFSSL_NOSHA3_224
  2613. case CTC_SHA3_224wECDSA:
  2614. return sigSha3_224wEcdsaName;
  2615. #endif
  2616. #ifndef WOLFSSL_NOSHA3_256
  2617. case CTC_SHA3_256wECDSA:
  2618. return sigSha3_256wEcdsaName;
  2619. #endif
  2620. #ifndef WOLFSSL_NOSHA3_384
  2621. case CTC_SHA3_384wECDSA:
  2622. return sigSha3_384wEcdsaName;
  2623. #endif
  2624. #ifndef WOLFSSL_NOSHA3_512
  2625. case CTC_SHA3_512wECDSA:
  2626. return sigSha3_512wEcdsaName;
  2627. #endif
  2628. #endif
  2629. #endif /* HAVE_ECC */
  2630. default:
  2631. return sigUnknownName;
  2632. }
  2633. }
  2634. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2635. defined(OPENSSL_EXTRA)
  2636. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2637. (!defined(NO_RSA) && \
  2638. (defined(WOLFSSL_CERT_GEN) || \
  2639. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  2640. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2641. *
  2642. * When output is NULL, calculate the header length only.
  2643. *
  2644. * @param [in] len Length of INTEGER data in bytes.
  2645. * @param [in] firstByte First byte of data, most significant byte of integer,
  2646. * to encode.
  2647. * @param [out] output Buffer to write into.
  2648. * @return Number of bytes added to the buffer.
  2649. */
  2650. int SetASNInt(int len, byte firstByte, byte* output)
  2651. {
  2652. int idx = 0;
  2653. if (output) {
  2654. /* Write out tag. */
  2655. output[idx] = ASN_INTEGER;
  2656. }
  2657. /* Step over tag. */
  2658. idx += ASN_TAG_SZ;
  2659. /* Check if first byte has top bit set in which case a 0 is needed to
  2660. * maintain positive value. */
  2661. if (firstByte & 0x80) {
  2662. /* Add pre-prepended byte to length of data in INTEGER. */
  2663. len++;
  2664. }
  2665. /* Encode length - passing NULL for output will not encode. */
  2666. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  2667. /* Put out pre-pended 0 as well. */
  2668. if (firstByte & 0x80) {
  2669. if (output) {
  2670. /* Write out 0 byte. */
  2671. output[idx] = 0x00;
  2672. }
  2673. /* Update index. */
  2674. idx++;
  2675. }
  2676. /* Return index after header. */
  2677. return idx;
  2678. }
  2679. #endif
  2680. #endif
  2681. #ifndef WOLFSSL_ASN_TEMPLATE
  2682. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2683. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2684. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2685. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  2686. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2687. * The number is assumed to be positive.
  2688. *
  2689. * n Multi-precision integer to encode.
  2690. * maxSz Maximum size of the encoded integer.
  2691. * A negative value indicates no check of length requested.
  2692. * output Buffer to write into.
  2693. * returns BUFFER_E when the data is too long for the buffer.
  2694. * MP_TO_E when encoding the integer fails.
  2695. * Otherwise, the number of bytes added to the buffer.
  2696. */
  2697. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2698. {
  2699. int idx = 0;
  2700. int leadingBit;
  2701. int length;
  2702. leadingBit = mp_leading_bit(n);
  2703. length = mp_unsigned_bin_size(n);
  2704. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2705. return BUFFER_E;
  2706. idx = SetASNInt(length, (byte)(leadingBit ? 0x80U : 0x00U), output);
  2707. if (maxSz >= 0 && (idx + length) > maxSz)
  2708. return BUFFER_E;
  2709. if (output) {
  2710. int err = mp_to_unsigned_bin(n, output + idx);
  2711. if (err != MP_OKAY)
  2712. return MP_TO_E;
  2713. }
  2714. idx += length;
  2715. return idx;
  2716. }
  2717. #endif
  2718. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2719. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2720. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2721. * an RSA key.
  2722. * The number is assumed to be positive.
  2723. *
  2724. * n Multi-precision integer to encode.
  2725. * output Buffer to write into.
  2726. * returns BUFFER_E when the data is too long for the buffer.
  2727. * MP_TO_E when encoding the integer fails.
  2728. * Otherwise, the number of bytes added to the buffer.
  2729. */
  2730. static int SetASNIntRSA(void* n, byte* output)
  2731. {
  2732. int idx = 0;
  2733. int leadingBit;
  2734. int length;
  2735. leadingBit = wc_Rsa_leading_bit(n);
  2736. length = wc_Rsa_unsigned_bin_size(n);
  2737. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2738. if ((idx + length) > MAX_RSA_INT_SZ)
  2739. return BUFFER_E;
  2740. if (output) {
  2741. int err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2742. if (err != MP_OKAY)
  2743. return MP_TO_E;
  2744. }
  2745. idx += length;
  2746. return idx;
  2747. }
  2748. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2749. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2750. #ifdef WOLFSSL_ASN_TEMPLATE
  2751. /* ASN.1 template for an INTEGER. */
  2752. static const ASNItem intASN[] = {
  2753. /* INT */ { 0, ASN_INTEGER, 0, 0, 0 }
  2754. };
  2755. enum {
  2756. INTASN_IDX_INT = 0
  2757. };
  2758. /* Number of items in ASN.1 template for an INTEGER. */
  2759. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2760. #endif /* WOLFSSL_ASN_TEMPLATE */
  2761. /* Windows header clash for WinCE using GetVersion */
  2762. /* Decode Version - one byte INTEGER.
  2763. *
  2764. * @param [in] input Buffer of BER data.
  2765. * @param [in, out] inOutIdx On in, start of encoded Version.
  2766. * On out, start of next encode ASN.1 item.
  2767. * @param [out] version Number encoded in INTEGER.
  2768. * @param [in] maxIdx Maximum index of data in buffer.
  2769. * @return 0 on success.
  2770. * @return ASN_PARSE_E when encoding is invalid.
  2771. * @return BUFFER_E when data in buffer is too small.
  2772. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2773. */
  2774. int GetMyVersion(const byte* input, word32* inOutIdx,
  2775. int* version, word32 maxIdx)
  2776. {
  2777. #ifndef WOLFSSL_ASN_TEMPLATE
  2778. word32 idx = *inOutIdx;
  2779. byte tag;
  2780. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2781. return ASN_PARSE_E;
  2782. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2783. return ASN_PARSE_E;
  2784. if (tag != ASN_INTEGER)
  2785. return ASN_PARSE_E;
  2786. if (input[idx++] != 0x01)
  2787. return ASN_VERSION_E;
  2788. *version = input[idx++];
  2789. *inOutIdx = idx;
  2790. return *version;
  2791. #else
  2792. ASNGetData dataASN[intASN_Length];
  2793. int ret;
  2794. byte num;
  2795. /* Clear dynamic data and set the version number variable. */
  2796. XMEMSET(dataASN, 0, sizeof(dataASN));
  2797. GetASN_Int8Bit(&dataASN[INTASN_IDX_INT], &num);
  2798. /* Decode the version (INTEGER). */
  2799. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2800. maxIdx);
  2801. if (ret == 0) {
  2802. /* Return version through variable and return value. */
  2803. *version = num;
  2804. ret = num;
  2805. }
  2806. return ret;
  2807. #endif /* WOLFSSL_ASN_TEMPLATE */
  2808. }
  2809. #ifndef NO_PWDBASED
  2810. /* Decode small integer, 32 bits or less.
  2811. *
  2812. * @param [in] input Buffer of BER data.
  2813. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2814. * On out, start of next encode ASN.1 item.
  2815. * @param [out] number Number encoded in INTEGER.
  2816. * @param [in] maxIdx Maximum index of data in buffer.
  2817. * @return 0 on success.
  2818. * @return ASN_PARSE_E when encoding is invalid.
  2819. * @return BUFFER_E when data in buffer is too small.
  2820. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2821. */
  2822. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2823. {
  2824. #ifndef WOLFSSL_ASN_TEMPLATE
  2825. word32 idx = *inOutIdx;
  2826. word32 len;
  2827. byte tag;
  2828. *number = 0;
  2829. /* check for type and length bytes */
  2830. if ((idx + 2) > maxIdx)
  2831. return BUFFER_E;
  2832. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2833. return ASN_PARSE_E;
  2834. if (tag != ASN_INTEGER)
  2835. return ASN_PARSE_E;
  2836. len = input[idx++];
  2837. if (len > 4)
  2838. return ASN_PARSE_E;
  2839. if (len + idx > maxIdx)
  2840. return ASN_PARSE_E;
  2841. while (len--) {
  2842. *number = *number << 8 | input[idx++];
  2843. }
  2844. *inOutIdx = idx;
  2845. return *number;
  2846. #else
  2847. ASNGetData dataASN[intASN_Length];
  2848. int ret;
  2849. word32 num;
  2850. /* Clear dynamic data and set the 32-bit number variable. */
  2851. XMEMSET(dataASN, 0, sizeof(dataASN));
  2852. GetASN_Int32Bit(&dataASN[INTASN_IDX_INT], &num);
  2853. /* Decode the short int (INTEGER). */
  2854. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2855. maxIdx);
  2856. if (ret == 0) {
  2857. /* Return number through variable and return value. */
  2858. *number = (int)num;
  2859. ret = (int)num;
  2860. }
  2861. return ret;
  2862. #endif
  2863. }
  2864. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS8) || \
  2865. defined(HAVE_PKCS12)
  2866. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2867. * returns total amount written including ASN tag and length byte on success */
  2868. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2869. {
  2870. word32 idx = *inOutIdx;
  2871. int len = 0;
  2872. int i;
  2873. byte ar[MAX_LENGTH_SZ];
  2874. /* check for room for type and length bytes */
  2875. if ((idx + 2) > maxIdx)
  2876. return BUFFER_E;
  2877. input[idx++] = ASN_INTEGER;
  2878. idx++; /* place holder for length byte */
  2879. if (MAX_LENGTH_SZ + idx > maxIdx)
  2880. return ASN_PARSE_E;
  2881. /* find first non zero byte */
  2882. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2883. c32toa(number, ar);
  2884. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2885. if (ar[i] != 0) {
  2886. break;
  2887. }
  2888. }
  2889. /* handle case of 0 */
  2890. if (i == MAX_LENGTH_SZ) {
  2891. input[idx++] = 0; len++;
  2892. }
  2893. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2894. input[idx++] = ar[i]; len++;
  2895. }
  2896. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2897. * and set number of bytes for integer, then update the index value */
  2898. input[*inOutIdx + 1] = (byte)len;
  2899. *inOutIdx = idx;
  2900. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2901. }
  2902. #endif /* !WOLFSSL_ASN_TEMPLATE || HAVE_PKCS8 || HAVE_PKCS12 */
  2903. #endif /* !NO_PWDBASED */
  2904. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  2905. /* May not have one, not an error */
  2906. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2907. word32 maxIdx)
  2908. {
  2909. word32 idx = *inOutIdx;
  2910. byte tag;
  2911. WOLFSSL_ENTER("GetExplicitVersion");
  2912. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2913. return ASN_PARSE_E;
  2914. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2915. int ret;
  2916. *inOutIdx = ++idx; /* skip header */
  2917. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2918. if (ret >= 0) {
  2919. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2920. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2921. WOLFSSL_MSG("Unexpected certificate version");
  2922. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  2923. ret = ASN_VERSION_E;
  2924. }
  2925. }
  2926. return ret;
  2927. }
  2928. /* go back as is */
  2929. *version = 0;
  2930. return 0;
  2931. }
  2932. #endif
  2933. /* Decode small integer, 32 bits or less.
  2934. *
  2935. * mp_int is initialized.
  2936. *
  2937. * @param [out] mpi mp_int to hold number.
  2938. * @param [in] input Buffer of BER data.
  2939. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2940. * On out, start of next encode ASN.1 item.
  2941. * @param [in] maxIdx Maximum index of data in buffer.
  2942. * @return 0 on success.
  2943. * @return ASN_PARSE_E when encoding is invalid.
  2944. * @return BUFFER_E when data in buffer is too small.
  2945. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2946. * @return MP_INIT_E when the unable to initialize an mp_int.
  2947. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  2948. */
  2949. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  2950. {
  2951. #ifndef WOLFSSL_ASN_TEMPLATE
  2952. word32 idx = *inOutIdx;
  2953. int ret;
  2954. int length;
  2955. ret = GetASNInt(input, &idx, &length, maxIdx);
  2956. if (ret != 0)
  2957. return ret;
  2958. if (mp_init(mpi) != MP_OKAY)
  2959. return MP_INIT_E;
  2960. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2961. mp_clear(mpi);
  2962. return ASN_GETINT_E;
  2963. }
  2964. #ifdef HAVE_WOLF_BIGINT
  2965. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2966. mp_clear(mpi);
  2967. return ASN_GETINT_E;
  2968. }
  2969. #endif /* HAVE_WOLF_BIGINT */
  2970. *inOutIdx = idx + (word32)length;
  2971. return 0;
  2972. #else
  2973. ASNGetData dataASN[intASN_Length];
  2974. /* Clear dynamic data and set the mp_int to fill with value. */
  2975. XMEMSET(dataASN, 0, sizeof(dataASN));
  2976. GetASN_MP_PosNeg(&dataASN[INTASN_IDX_INT], mpi);
  2977. /* Decode the big number (INTEGER). */
  2978. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2979. maxIdx);
  2980. #endif
  2981. }
  2982. #if (defined(HAVE_ECC) || !defined(NO_DSA)) && !defined(WOLFSSL_ASN_TEMPLATE)
  2983. static int GetIntPositive(mp_int* mpi, const byte* input, word32* inOutIdx,
  2984. word32 maxIdx, int initNum)
  2985. {
  2986. word32 idx = *inOutIdx;
  2987. int ret;
  2988. int length;
  2989. ret = GetASNInt(input, &idx, &length, maxIdx);
  2990. if (ret != 0)
  2991. return ret;
  2992. if (((input[idx] & 0x80) == 0x80) && (input[idx - 1] != 0x00))
  2993. return MP_INIT_E;
  2994. if (initNum) {
  2995. if (mp_init(mpi) != MP_OKAY)
  2996. return MP_INIT_E;
  2997. }
  2998. if (mp_read_unsigned_bin(mpi, input + idx, (word32)length) != 0) {
  2999. mp_clear(mpi);
  3000. return ASN_GETINT_E;
  3001. }
  3002. #ifdef HAVE_WOLF_BIGINT
  3003. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  3004. mp_clear(mpi);
  3005. return ASN_GETINT_E;
  3006. }
  3007. #endif /* HAVE_WOLF_BIGINT */
  3008. *inOutIdx = idx + (word32)length;
  3009. return 0;
  3010. }
  3011. #endif /* (ECC || !NO_DSA) && !WOLFSSL_ASN_TEMPLATE */
  3012. #ifndef WOLFSSL_ASN_TEMPLATE
  3013. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  3014. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  3015. {
  3016. word32 idx = *inOutIdx;
  3017. int ret;
  3018. int length;
  3019. ret = GetASNInt(input, &idx, &length, maxIdx);
  3020. if (ret != 0)
  3021. return ret;
  3022. *inOutIdx = idx + (word32)length;
  3023. return 0;
  3024. }
  3025. #endif
  3026. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3027. #ifdef WOLFSSL_ASN_TEMPLATE
  3028. /* ASN.1 template for a BIT_STRING. */
  3029. static const ASNItem bitStringASN[] = {
  3030. /* BIT_STR */ { 0, ASN_BIT_STRING, 0, 1, 0 }
  3031. };
  3032. enum {
  3033. BITSTRINGASN_IDX_BIT_STR = 0
  3034. };
  3035. /* Number of items in ASN.1 template for a BIT_STRING. */
  3036. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  3037. #endif
  3038. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  3039. *
  3040. * @param [in] input Buffer holding BER encoding.
  3041. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  3042. * On out, start of ASN.1 item after BIT_STRING.
  3043. * @param [out] len Length of BIT_STRING data.
  3044. * @param [in] maxIdx Maximum index of data in buffer.
  3045. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  3046. * @param [in] unusedBits Number of unused bits in last byte.
  3047. * @return 0 on success.
  3048. * @return ASN_PARSE_E when encoding is invalid.
  3049. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  3050. * @return BUFFER_E when data in buffer is too small.
  3051. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  3052. */
  3053. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  3054. word32 maxIdx, int zeroBits, byte* unusedBits)
  3055. {
  3056. #ifndef WOLFSSL_ASN_TEMPLATE
  3057. word32 idx = *inOutIdx;
  3058. int length;
  3059. byte b;
  3060. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  3061. return ASN_BITSTR_E;
  3062. }
  3063. if (b != ASN_BIT_STRING) {
  3064. return ASN_BITSTR_E;
  3065. }
  3066. if (GetLength(input, &idx, &length, maxIdx) < 0)
  3067. return ASN_PARSE_E;
  3068. /* extra sanity check that length is greater than 0 */
  3069. if (length <= 0) {
  3070. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  3071. return BUFFER_E;
  3072. }
  3073. if (idx + 1 > maxIdx) {
  3074. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  3075. return BUFFER_E;
  3076. }
  3077. b = input[idx];
  3078. if (zeroBits && b != 0x00)
  3079. return ASN_EXPECT_0_E;
  3080. if (b >= 0x08)
  3081. return ASN_PARSE_E;
  3082. if (b != 0) {
  3083. if ((byte)(input[idx + (word32)length - 1] << (8 - b)) != 0)
  3084. return ASN_PARSE_E;
  3085. }
  3086. idx++;
  3087. length--; /* length has been checked for greater than 0 */
  3088. *inOutIdx = idx;
  3089. if (len != NULL)
  3090. *len = length;
  3091. if (unusedBits != NULL)
  3092. *unusedBits = b;
  3093. return 0;
  3094. #else
  3095. ASNGetData dataASN[bitStringASN_Length];
  3096. int ret;
  3097. int bits;
  3098. /* Parse BIT_STRING and check validity of unused bits. */
  3099. XMEMSET(dataASN, 0, sizeof(dataASN));
  3100. /* Decode BIT_STRING. */
  3101. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  3102. inOutIdx, maxIdx);
  3103. if (ret == 0) {
  3104. /* Get unused bits from dynamic ASN.1 data. */
  3105. bits = GetASNItem_UnusedBits(dataASN[BITSTRINGASN_IDX_BIT_STR]);
  3106. /* Check unused bits is 0 when expected. */
  3107. if (zeroBits && (bits != 0)) {
  3108. ret = ASN_EXPECT_0_E;
  3109. }
  3110. }
  3111. if (ret == 0) {
  3112. /* Return length of data and unused bits if required. */
  3113. if (len != NULL) {
  3114. *len = (int)dataASN[BITSTRINGASN_IDX_BIT_STR].data.ref.length;
  3115. }
  3116. if (unusedBits != NULL) {
  3117. *unusedBits = (byte)bits;
  3118. }
  3119. }
  3120. return ret;
  3121. #endif
  3122. }
  3123. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  3124. * KeyGen) */
  3125. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  3126. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3127. defined(OPENSSL_EXTRA))) || \
  3128. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  3129. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  3130. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  3131. defined(OPENSSL_EXTRA))) || \
  3132. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  3133. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN)) || \
  3134. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  3135. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  3136. *
  3137. * When output is NULL, calculate the header length only.
  3138. *
  3139. * @param [in] len Length of BIT STRING data.
  3140. * That is, the number of least significant zero bits
  3141. * before a one.
  3142. * The last byte is the most-significant non-zero byte
  3143. * of a number.
  3144. * @param [out] output Buffer to write into.
  3145. * @return Number of bytes added to the buffer.
  3146. */
  3147. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  3148. {
  3149. word32 idx = 0;
  3150. if (output) {
  3151. /* Write out tag. */
  3152. output[idx] = ASN_BIT_STRING;
  3153. }
  3154. /* Step over tag. */
  3155. idx += ASN_TAG_SZ;
  3156. /* Encode length - passing NULL for output will not encode.
  3157. * Add one to length for unused bits. */
  3158. idx += SetLength(len + 1, output ? output + idx : NULL);
  3159. if (output) {
  3160. /* Write out unused bits. */
  3161. output[idx] = unusedBits;
  3162. }
  3163. /* Skip over unused bits. */
  3164. idx++;
  3165. /* Return index after header. */
  3166. return idx;
  3167. }
  3168. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  3169. #ifdef ASN_BER_TO_DER
  3170. /* Convert BER to DER */
  3171. /* Pull informtation from the ASN.1 BER encoded item header */
  3172. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  3173. byte* pTag, word32* pLen, int* indef)
  3174. {
  3175. int len = 0;
  3176. byte tag;
  3177. word32 i = *idx;
  3178. *indef = 0;
  3179. /* Check there is enough data for a minimal header */
  3180. if (i + 2 > maxIdx) {
  3181. return ASN_PARSE_E;
  3182. }
  3183. /* Retrieve tag */
  3184. tag = data[i++];
  3185. /* Indefinite length handled specially */
  3186. if (data[i] == ASN_INDEF_LENGTH) {
  3187. /* Check valid tag for indefinite */
  3188. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  3189. return ASN_PARSE_E;
  3190. }
  3191. i++;
  3192. *indef = 1;
  3193. }
  3194. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3195. return ASN_PARSE_E;
  3196. }
  3197. /* Return tag, length and index after BER item header */
  3198. *pTag = tag;
  3199. *pLen = (word32)len;
  3200. *idx = i;
  3201. return 0;
  3202. }
  3203. #ifndef INDEF_ITEMS_MAX
  3204. #define INDEF_ITEMS_MAX 20
  3205. #endif
  3206. /* Indef length item data */
  3207. typedef struct Indef {
  3208. word32 start;
  3209. int depth;
  3210. int headerLen;
  3211. word32 len;
  3212. } Indef;
  3213. /* Indef length items */
  3214. typedef struct IndefItems
  3215. {
  3216. Indef len[INDEF_ITEMS_MAX];
  3217. int cnt;
  3218. int idx;
  3219. int depth;
  3220. } IndefItems;
  3221. /* Get header length of current item */
  3222. static int IndefItems_HeaderLen(IndefItems* items)
  3223. {
  3224. return items->len[items->idx].headerLen;
  3225. }
  3226. /* Get data length of current item */
  3227. static word32 IndefItems_Len(IndefItems* items)
  3228. {
  3229. return items->len[items->idx].len;
  3230. }
  3231. /* Add a indefinite length item */
  3232. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3233. {
  3234. int ret = 0;
  3235. int i;
  3236. if (items->cnt == INDEF_ITEMS_MAX) {
  3237. ret = MEMORY_E;
  3238. }
  3239. else {
  3240. i = items->cnt++;
  3241. items->len[i].start = start;
  3242. items->len[i].depth = items->depth++;
  3243. items->len[i].headerLen = 1;
  3244. items->len[i].len = 0;
  3245. items->idx = i;
  3246. }
  3247. return ret;
  3248. }
  3249. /* Increase data length of current item */
  3250. static void IndefItems_AddData(IndefItems* items, word32 length)
  3251. {
  3252. items->len[items->idx].len += length;
  3253. }
  3254. /* Update header length of current item to reflect data length */
  3255. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3256. {
  3257. items->len[items->idx].headerLen +=
  3258. (int)SetLength(items->len[items->idx].len, NULL);
  3259. }
  3260. /* Go to indefinite parent of current item */
  3261. static void IndefItems_Up(IndefItems* items)
  3262. {
  3263. int i;
  3264. int depth = items->len[items->idx].depth - 1;
  3265. for (i = items->cnt - 1; i >= 0; i--) {
  3266. if (items->len[i].depth == depth) {
  3267. break;
  3268. }
  3269. }
  3270. items->idx = i;
  3271. items->depth = depth + 1;
  3272. }
  3273. /* Calculate final length by adding length of indefinite child items */
  3274. static void IndefItems_CalcLength(IndefItems* items)
  3275. {
  3276. int i;
  3277. int idx = items->idx;
  3278. for (i = idx + 1; i < items->cnt; i++) {
  3279. if (items->len[i].depth == items->depth) {
  3280. items->len[idx].len += (word32)items->len[i].headerLen;
  3281. items->len[idx].len += items->len[i].len;
  3282. }
  3283. }
  3284. items->len[idx].headerLen += (int)SetLength(items->len[idx].len, NULL);
  3285. }
  3286. /* Add more data to indefinite length item */
  3287. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3288. {
  3289. if (items->cnt > 0 && items->idx >= 0) {
  3290. items->len[items->idx].len += length;
  3291. }
  3292. }
  3293. /* Convert a BER encoding with indefinite length items to DER.
  3294. *
  3295. * ber BER encoded data.
  3296. * berSz Length of BER encoded data.
  3297. * der Buffer to hold DER encoded version of data.
  3298. * NULL indicates only the length is required.
  3299. * derSz The size of the buffer to hold the DER encoded data.
  3300. * Will be set if der is NULL, otherwise the value is checked as der is
  3301. * filled.
  3302. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3303. * derSz are NULL.
  3304. */
  3305. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3306. {
  3307. int ret = 0;
  3308. word32 i, j;
  3309. #ifdef WOLFSSL_SMALL_STACK
  3310. IndefItems* indefItems = NULL;
  3311. #else
  3312. IndefItems indefItems[1];
  3313. #endif
  3314. byte tag, basic;
  3315. word32 length;
  3316. int indef;
  3317. if (ber == NULL || derSz == NULL)
  3318. return BAD_FUNC_ARG;
  3319. #ifdef WOLFSSL_SMALL_STACK
  3320. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3321. DYNAMIC_TYPE_TMP_BUFFER);
  3322. if (indefItems == NULL) {
  3323. ret = MEMORY_E;
  3324. goto end;
  3325. }
  3326. #endif
  3327. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3328. /* Calculate indefinite item lengths */
  3329. for (i = 0; i < berSz; ) {
  3330. word32 start = i;
  3331. /* Get next BER item */
  3332. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3333. if (ret != 0) {
  3334. goto end;
  3335. }
  3336. if (indef) {
  3337. /* Indefinite item - add to list */
  3338. ret = IndefItems_AddItem(indefItems, i);
  3339. if (ret != 0) {
  3340. goto end;
  3341. }
  3342. if ((tag & 0xC0) == 0 &&
  3343. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3344. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3345. /* Constructed basic type - get repeating tag */
  3346. basic = (byte)(tag & (~ASN_CONSTRUCTED));
  3347. /* Add up lengths of each item below */
  3348. for (; i < berSz; ) {
  3349. /* Get next BER_item */
  3350. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3351. if (ret != 0) {
  3352. goto end;
  3353. }
  3354. /* End of content closes item */
  3355. if (tag == ASN_EOC) {
  3356. /* Must be zero length */
  3357. if (length != 0) {
  3358. ret = ASN_PARSE_E;
  3359. goto end;
  3360. }
  3361. break;
  3362. }
  3363. /* Must not be indefinite and tag must match parent */
  3364. if (indef || tag != basic) {
  3365. ret = ASN_PARSE_E;
  3366. goto end;
  3367. }
  3368. /* Add to length */
  3369. IndefItems_AddData(indefItems, length);
  3370. /* Skip data */
  3371. i += length;
  3372. }
  3373. /* Ensure we got an EOC and not end of data */
  3374. if (tag != ASN_EOC) {
  3375. ret = ASN_PARSE_E;
  3376. goto end;
  3377. }
  3378. /* Set the header length to include the length field */
  3379. IndefItems_UpdateHeaderLen(indefItems);
  3380. /* Go to indefinite parent item */
  3381. IndefItems_Up(indefItems);
  3382. }
  3383. }
  3384. else if (tag == ASN_EOC) {
  3385. /* End-of-content must be 0 length */
  3386. if (length != 0) {
  3387. ret = ASN_PARSE_E;
  3388. goto end;
  3389. }
  3390. /* Check there is an item to close - missing EOC */
  3391. if (indefItems->depth == 0) {
  3392. ret = ASN_PARSE_E;
  3393. goto end;
  3394. }
  3395. /* Finish calculation of data length for indefinite item */
  3396. IndefItems_CalcLength(indefItems);
  3397. /* Go to indefinite parent item */
  3398. IndefItems_Up(indefItems);
  3399. }
  3400. else {
  3401. /* Known length item to add in - make sure enough data for it */
  3402. if (i + length > berSz) {
  3403. ret = ASN_PARSE_E;
  3404. goto end;
  3405. }
  3406. /* Include all data - can't have indefinite inside definite */
  3407. i += length;
  3408. /* Add entire item to current indefinite item */
  3409. IndefItems_MoreData(indefItems, i - start);
  3410. }
  3411. }
  3412. /* Check we had a EOC for each indefinite item */
  3413. if (indefItems->depth != 0) {
  3414. ret = ASN_PARSE_E;
  3415. goto end;
  3416. }
  3417. /* Write out DER */
  3418. j = 0;
  3419. /* Reset index */
  3420. indefItems->idx = 0;
  3421. for (i = 0; i < berSz; ) {
  3422. word32 start = i;
  3423. /* Get item - checked above */
  3424. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3425. if (indef) {
  3426. if (der != NULL) {
  3427. /* Check enough space for header */
  3428. if (j + (word32)IndefItems_HeaderLen(indefItems) > *derSz) {
  3429. ret = BUFFER_E;
  3430. goto end;
  3431. }
  3432. if ((tag & 0xC0) == 0 &&
  3433. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3434. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3435. /* Remove constructed tag for basic types */
  3436. tag &= (byte)~ASN_CONSTRUCTED;
  3437. }
  3438. /* Add tag and length */
  3439. der[j] = tag;
  3440. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3441. }
  3442. /* Add header length of indefinite item */
  3443. j += (word32)IndefItems_HeaderLen(indefItems);
  3444. if ((tag & 0xC0) == 0 &&
  3445. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3446. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3447. /* For basic type - get each child item and add data */
  3448. for (; i < berSz; ) {
  3449. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3450. if (tag == ASN_EOC) {
  3451. break;
  3452. }
  3453. if (der != NULL) {
  3454. if (j + length > *derSz) {
  3455. ret = BUFFER_E;
  3456. goto end;
  3457. }
  3458. XMEMCPY(der + j, ber + i, length);
  3459. }
  3460. j += length;
  3461. i += length;
  3462. }
  3463. }
  3464. /* Move to next indef item in list */
  3465. indefItems->idx++;
  3466. }
  3467. else if (tag == ASN_EOC) {
  3468. /* End-Of-Content is not written out in DER */
  3469. }
  3470. else {
  3471. /* Write out definite length item as is. */
  3472. i += length;
  3473. if (der != NULL) {
  3474. /* Ensure space for item */
  3475. if (j + i - start > *derSz) {
  3476. ret = BUFFER_E;
  3477. goto end;
  3478. }
  3479. /* Copy item as is */
  3480. XMEMCPY(der + j, ber + start, i - start);
  3481. }
  3482. j += i - start;
  3483. }
  3484. }
  3485. /* Return the length of the DER encoded ASN.1 */
  3486. *derSz = j;
  3487. if (der == NULL) {
  3488. ret = LENGTH_ONLY_E;
  3489. }
  3490. end:
  3491. #ifdef WOLFSSL_SMALL_STACK
  3492. if (indefItems != NULL) {
  3493. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3494. }
  3495. #endif
  3496. return ret;
  3497. }
  3498. #endif
  3499. #ifndef WOLFSSL_ASN_TEMPLATE
  3500. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3501. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3502. *
  3503. * val 16-bit value to encode.
  3504. * output Buffer to write into.
  3505. * returns the number of bytes added to the buffer.
  3506. */
  3507. static word32 SetBitString16Bit(word16 val, byte* output)
  3508. {
  3509. word32 idx;
  3510. int len;
  3511. byte lastByte;
  3512. byte unusedBits = 0;
  3513. if ((val >> 8) != 0) {
  3514. len = 2;
  3515. lastByte = (byte)(val >> 8);
  3516. }
  3517. else {
  3518. len = 1;
  3519. lastByte = (byte)val;
  3520. }
  3521. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3522. unusedBits++;
  3523. idx = SetBitString((word32)len, unusedBits, output);
  3524. output[idx++] = (byte)val;
  3525. if (len > 1)
  3526. output[idx++] = (byte)(val >> 8);
  3527. return idx;
  3528. }
  3529. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3530. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3531. /* hashType */
  3532. #ifdef WOLFSSL_MD2
  3533. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3534. #endif
  3535. #ifndef NO_MD5
  3536. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3537. #endif
  3538. #ifndef NO_SHA
  3539. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3540. #endif
  3541. #ifdef WOLFSSL_SHA224
  3542. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3543. #endif
  3544. #ifndef NO_SHA256
  3545. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3546. #endif
  3547. #ifdef WOLFSSL_SHA384
  3548. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3549. #endif
  3550. #ifdef WOLFSSL_SHA512
  3551. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3552. #ifndef WOLFSSL_NOSHA512_224
  3553. static const byte hashSha512_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 5};
  3554. #endif
  3555. #ifndef WOLFSSL_NOSHA512_256
  3556. static const byte hashSha512_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 6};
  3557. #endif
  3558. #endif
  3559. #ifdef WOLFSSL_SHA3
  3560. #ifndef WOLFSSL_NOSHA3_224
  3561. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3562. #endif /* WOLFSSL_NOSHA3_224 */
  3563. #ifndef WOLFSSL_NOSHA3_256
  3564. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3565. #endif /* WOLFSSL_NOSHA3_256 */
  3566. #ifndef WOLFSSL_NOSHA3_384
  3567. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3568. #endif /* WOLFSSL_NOSHA3_384 */
  3569. #ifndef WOLFSSL_NOSHA3_512
  3570. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3571. #endif /* WOLFSSL_NOSHA3_512 */
  3572. #endif /* WOLFSSL_SHA3 */
  3573. /* hmacType */
  3574. #ifndef NO_HMAC
  3575. #ifdef WOLFSSL_SHA224
  3576. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3577. #endif
  3578. #ifndef NO_SHA256
  3579. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3580. #endif
  3581. #ifdef WOLFSSL_SHA384
  3582. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3583. #endif
  3584. #ifdef WOLFSSL_SHA512
  3585. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3586. #endif
  3587. #endif
  3588. /* sigType */
  3589. #if !defined(NO_DSA) && !defined(NO_SHA)
  3590. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3591. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3592. #endif /* NO_DSA */
  3593. #ifndef NO_RSA
  3594. #ifdef WOLFSSL_MD2
  3595. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3596. #endif
  3597. #ifndef NO_MD5
  3598. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3599. #endif
  3600. #ifndef NO_SHA
  3601. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3602. #endif
  3603. #ifdef WOLFSSL_SHA224
  3604. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3605. #endif
  3606. #ifndef NO_SHA256
  3607. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3608. #endif
  3609. #ifdef WOLFSSL_SHA384
  3610. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3611. #endif
  3612. #ifdef WOLFSSL_SHA512
  3613. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3614. #endif
  3615. #ifdef WOLFSSL_SHA3
  3616. #ifndef WOLFSSL_NOSHA3_224
  3617. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3618. #endif
  3619. #ifndef WOLFSSL_NOSHA3_256
  3620. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3621. #endif
  3622. #ifndef WOLFSSL_NOSHA3_384
  3623. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3624. #endif
  3625. #ifndef WOLFSSL_NOSHA3_512
  3626. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3627. #endif
  3628. #endif
  3629. #ifdef WC_RSA_PSS
  3630. static const byte sigRsaSsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3631. #endif
  3632. #endif /* NO_RSA */
  3633. #ifdef HAVE_ECC
  3634. #ifndef NO_SHA
  3635. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3636. #endif
  3637. #ifdef WOLFSSL_SHA224
  3638. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3639. #endif
  3640. #ifndef NO_SHA256
  3641. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3642. #endif
  3643. #ifdef WOLFSSL_SHA384
  3644. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3645. #endif
  3646. #ifdef WOLFSSL_SHA512
  3647. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3648. #endif
  3649. #ifdef WOLFSSL_SHA3
  3650. #ifndef WOLFSSL_NOSHA3_224
  3651. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3652. #endif
  3653. #ifndef WOLFSSL_NOSHA3_256
  3654. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3655. #endif
  3656. #ifndef WOLFSSL_NOSHA3_384
  3657. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3658. #endif
  3659. #ifndef WOLFSSL_NOSHA3_512
  3660. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3661. #endif
  3662. #endif
  3663. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  3664. /* 0x2A, 0x81, 0x1C, 0xCF, 0x55, 0x01, 0x83, 0x75 */
  3665. static const byte sigSm3wSm2Oid[] = {42, 129, 28, 207, 85, 1, 131, 117};
  3666. #endif
  3667. #endif /* HAVE_ECC */
  3668. #ifdef HAVE_ED25519
  3669. static const byte sigEd25519Oid[] = {43, 101, 112};
  3670. #endif /* HAVE_ED25519 */
  3671. #ifdef HAVE_ED448
  3672. static const byte sigEd448Oid[] = {43, 101, 113};
  3673. #endif /* HAVE_ED448 */
  3674. #ifdef HAVE_PQC
  3675. #ifdef HAVE_FALCON
  3676. /* Falcon Level 1: 1 3 9999 3 1 */
  3677. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3678. /* Falcon Level 5: 1 3 9999 3 4 */
  3679. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3680. #endif /* HAVE_FACON */
  3681. #ifdef HAVE_DILITHIUM
  3682. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3683. static const byte sigDilithium_Level2Oid[] =
  3684. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3685. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3686. static const byte sigDilithium_Level3Oid[] =
  3687. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3688. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3689. static const byte sigDilithium_Level5Oid[] =
  3690. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3691. #endif /* HAVE_DILITHIUM */
  3692. #ifdef HAVE_SPHINCS
  3693. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3694. static const byte sigSphincsFast_Level1Oid[] =
  3695. {43, 206, 15, 6, 7, 4};
  3696. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3697. static const byte sigSphincsFast_Level3Oid[] =
  3698. {43, 206, 15, 6, 8, 3};
  3699. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3700. static const byte sigSphincsFast_Level5Oid[] =
  3701. {43, 206, 15, 6, 9, 3};
  3702. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3703. static const byte sigSphincsSmall_Level1Oid[] =
  3704. {43, 206, 15, 6, 7, 10};
  3705. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3706. static const byte sigSphincsSmall_Level3Oid[] =
  3707. {43, 206, 15, 6, 8, 7};
  3708. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3709. static const byte sigSphincsSmall_Level5Oid[] =
  3710. {43, 206, 15, 6, 9, 7};
  3711. #endif /* HAVE_SPHINCS */
  3712. #endif /* HAVE_PQC */
  3713. /* keyType */
  3714. #ifndef NO_DSA
  3715. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3716. #endif /* NO_DSA */
  3717. #ifndef NO_RSA
  3718. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3719. #ifdef WC_RSA_PSS
  3720. static const byte keyRsaPssOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 10};
  3721. #endif
  3722. #endif /* NO_RSA */
  3723. #ifdef HAVE_ECC
  3724. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3725. #endif /* HAVE_ECC */
  3726. #ifdef HAVE_ED25519
  3727. static const byte keyEd25519Oid[] = {43, 101, 112};
  3728. #endif /* HAVE_ED25519 */
  3729. #ifdef HAVE_CURVE25519
  3730. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3731. #endif
  3732. #ifdef HAVE_ED448
  3733. static const byte keyEd448Oid[] = {43, 101, 113};
  3734. #endif /* HAVE_ED448 */
  3735. #ifdef HAVE_CURVE448
  3736. static const byte keyCurve448Oid[] = {43, 101, 111};
  3737. #endif /* HAVE_CURVE448 */
  3738. #ifndef NO_DH
  3739. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3740. #endif /* !NO_DH */
  3741. #ifdef HAVE_PQC
  3742. #ifdef HAVE_FALCON
  3743. /* Falcon Level 1: 1 3 9999 3 1 */
  3744. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3745. /* Falcon Level 5: 1 3 9999 3 4 */
  3746. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3747. #endif /* HAVE_FALCON */
  3748. #ifdef HAVE_DILITHIUM
  3749. /* Dilithium Level 2: 1.3.6.1.4.1.2.267.7.4.4 */
  3750. static const byte keyDilithium_Level2Oid[] =
  3751. {43, 6, 1, 4, 1, 2, 130, 11, 7, 4, 4};
  3752. /* Dilithium Level 3: 1.3.6.1.4.1.2.267.7.6.5 */
  3753. static const byte keyDilithium_Level3Oid[] =
  3754. {43, 6, 1, 4, 1, 2, 130, 11, 7, 6, 5};
  3755. /* Dilithium Level 5: 1.3.6.1.4.1.2.267.7.8.7 */
  3756. static const byte keyDilithium_Level5Oid[] =
  3757. {43, 6, 1, 4, 1, 2, 130, 11, 7, 8, 7};
  3758. #endif /* HAVE_DILITHIUM */
  3759. #ifdef HAVE_SPHINCS
  3760. /* Sphincs Fast Level 1: 1 3 9999 6 7 4 */
  3761. static const byte keySphincsFast_Level1Oid[] =
  3762. {43, 206, 15, 6, 7, 4};
  3763. /* Sphincs Fast Level 3: 1 3 9999 6 8 3 */
  3764. static const byte keySphincsFast_Level3Oid[] =
  3765. {43, 206, 15, 6, 8, 3};
  3766. /* Sphincs Fast Level 5: 1 3 9999 6 9 3 */
  3767. static const byte keySphincsFast_Level5Oid[] =
  3768. {43, 206, 15, 6, 9, 3};
  3769. /* Sphincs Small Level 1: 1 3 9999 6 7 10 */
  3770. static const byte keySphincsSmall_Level1Oid[] =
  3771. {43, 206, 15, 6, 7, 10};
  3772. /* Sphincs Small Level 3: 1 3 9999 6 8 7 */
  3773. static const byte keySphincsSmall_Level3Oid[] =
  3774. {43, 206, 15, 6, 8, 7};
  3775. /* Sphincs Small Level 5: 1 3 9999 6 9 7 */
  3776. static const byte keySphincsSmall_Level5Oid[] =
  3777. {43, 206, 15, 6, 9, 7};
  3778. #endif /* HAVE_SPHINCS */
  3779. #endif /* HAVE_PQC */
  3780. /* curveType */
  3781. #ifdef HAVE_ECC
  3782. /* See "ecc_sets" table in ecc.c */
  3783. #endif /* HAVE_ECC */
  3784. #ifdef HAVE_AES_CBC
  3785. /* blkType */
  3786. #ifdef WOLFSSL_AES_128
  3787. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3788. #endif
  3789. #ifdef WOLFSSL_AES_192
  3790. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3791. #endif
  3792. #ifdef WOLFSSL_AES_256
  3793. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3794. #endif
  3795. #endif /* HAVE_AES_CBC */
  3796. #ifdef HAVE_AESGCM
  3797. #ifdef WOLFSSL_AES_128
  3798. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3799. #endif
  3800. #ifdef WOLFSSL_AES_192
  3801. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3802. #endif
  3803. #ifdef WOLFSSL_AES_256
  3804. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3805. #endif
  3806. #endif /* HAVE_AESGCM */
  3807. #ifdef HAVE_AESCCM
  3808. #ifdef WOLFSSL_AES_128
  3809. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3810. #endif
  3811. #ifdef WOLFSSL_AES_192
  3812. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3813. #endif
  3814. #ifdef WOLFSSL_AES_256
  3815. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3816. #endif
  3817. #endif /* HAVE_AESCCM */
  3818. #ifndef NO_DES3
  3819. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3820. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3821. #endif
  3822. /* keyWrapType */
  3823. #ifdef WOLFSSL_AES_128
  3824. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3825. #endif
  3826. #ifdef WOLFSSL_AES_192
  3827. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3828. #endif
  3829. #ifdef WOLFSSL_AES_256
  3830. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3831. #endif
  3832. #ifdef HAVE_PKCS7
  3833. /* From RFC 3211 */
  3834. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3835. #endif
  3836. /* cmsKeyAgreeType */
  3837. #ifndef NO_SHA
  3838. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3839. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3840. #endif
  3841. #ifdef WOLFSSL_SHA224
  3842. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3843. #endif
  3844. #ifndef NO_SHA256
  3845. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3846. #endif
  3847. #ifdef WOLFSSL_SHA384
  3848. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3849. #endif
  3850. #ifdef WOLFSSL_SHA512
  3851. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3852. #endif
  3853. /* ocspType */
  3854. #ifdef HAVE_OCSP
  3855. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3856. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3857. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3858. #endif /* HAVE_OCSP */
  3859. /* certExtType */
  3860. static const byte extBasicCaOid[] = {85, 29, 19};
  3861. static const byte extAltNamesOid[] = {85, 29, 17};
  3862. static const byte extCrlDistOid[] = {85, 29, 31};
  3863. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3864. static const byte extAuthKeyOid[] = {85, 29, 35};
  3865. static const byte extSubjKeyOid[] = {85, 29, 14};
  3866. static const byte extCertPolicyOid[] = {85, 29, 32};
  3867. static const byte extKeyUsageOid[] = {85, 29, 15};
  3868. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3869. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3870. #ifndef IGNORE_NAME_CONSTRAINTS
  3871. static const byte extNameConsOid[] = {85, 29, 30};
  3872. #endif
  3873. #ifdef HAVE_CRL
  3874. static const byte extCrlNumberOid[] = {85, 29, 20};
  3875. #endif
  3876. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3877. static const byte extSubjDirAttrOid[] = {85, 29, 9};
  3878. #endif
  3879. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3880. static const byte extSubjInfoAccessOid[] = {43, 6, 1, 5, 5, 7, 1, 11};
  3881. #endif
  3882. /* certAuthInfoType */
  3883. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3884. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3885. #ifdef WOLFSSL_SUBJ_INFO_ACC
  3886. static const byte extAuthInfoCaRespOid[] = {43, 6, 1, 5, 5, 7, 48, 5};
  3887. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  3888. /* certPolicyType */
  3889. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3890. #ifdef WOLFSSL_FPKI
  3891. #define CERT_POLICY_TYPE_OID_BASE(num) {96, 134, 72, 1, 101, 3, 2, 1, 3, num}
  3892. static const byte extCertPolicyFpkiCommonAuthOid[] =
  3893. CERT_POLICY_TYPE_OID_BASE(13);
  3894. static const byte extCertPolicyFpkiPivAuthOid[] =
  3895. CERT_POLICY_TYPE_OID_BASE(40);
  3896. static const byte extCertPolicyFpkiPivAuthHwOid[] =
  3897. CERT_POLICY_TYPE_OID_BASE(41);
  3898. static const byte extCertPolicyFpkiPiviAuthOid[] =
  3899. CERT_POLICY_TYPE_OID_BASE(45);
  3900. #endif /* WOLFSSL_FPKI */
  3901. /* certAltNameType */
  3902. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3903. /* certKeyUseType */
  3904. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3905. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3906. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3907. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3908. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3909. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3910. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3911. #ifdef WOLFSSL_WOLFSSH
  3912. #define EXT_KEY_USAGE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 3, num}
  3913. static const byte extExtKeyUsageSshClientAuthOid[] =
  3914. EXT_KEY_USAGE_OID_BASE(21);
  3915. static const byte extExtKeyUsageSshMSCLOid[] =
  3916. {43, 6, 1, 4, 1, 130, 55, 20, 2, 2};
  3917. static const byte extExtKeyUsageSshKpClientAuthOid[] =
  3918. {43, 6, 1, 5, 2, 3, 4};
  3919. #endif /* WOLFSSL_WOLFSSH */
  3920. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  3921. #define SUBJ_DIR_ATTR_TYPE_OID_BASE(num) {43, 6, 1, 5, 5, 7, 9, num}
  3922. static const byte extSubjDirAttrDobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(1);
  3923. static const byte extSubjDirAttrPobOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(2);
  3924. static const byte extSubjDirAttrGenderOid[] =
  3925. SUBJ_DIR_ATTR_TYPE_OID_BASE(3);
  3926. static const byte extSubjDirAttrCocOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(4);
  3927. static const byte extSubjDirAttrCorOid[] = SUBJ_DIR_ATTR_TYPE_OID_BASE(5);
  3928. #endif
  3929. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3930. defined(WOLFSSL_ASN_TEMPLATE) || defined(OPENSSL_EXTRA) || \
  3931. defined(OPENSSL_EXTRA_X509_SMALL)
  3932. /* csrAttrType */
  3933. #define CSR_ATTR_TYPE_OID_BASE(num) {42, 134, 72, 134, 247, 13, 1, 9, num}
  3934. #if !defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3935. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3936. defined(WOLFSSL_ASN_TEMPLATE)
  3937. static const byte attrEmailOid[] = CSR_ATTR_TYPE_OID_BASE(1);
  3938. #endif
  3939. #ifdef WOLFSSL_CERT_REQ
  3940. static const byte attrUnstructuredNameOid[] = CSR_ATTR_TYPE_OID_BASE(2);
  3941. static const byte attrPkcs9ContentTypeOid[] = CSR_ATTR_TYPE_OID_BASE(3);
  3942. static const byte attrChallengePasswordOid[] = CSR_ATTR_TYPE_OID_BASE(7);
  3943. static const byte attrExtensionRequestOid[] = CSR_ATTR_TYPE_OID_BASE(14);
  3944. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3945. static const byte attrDnQualifier[] = {85, 4, 46};
  3946. static const byte attrInitals[] = {85, 4, 43};
  3947. static const byte attrSurname[] = {85, 4, 4};
  3948. static const byte attrGivenName[] = {85, 4, 42};
  3949. #endif
  3950. #endif
  3951. /* kdfType */
  3952. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3953. /* PKCS5 */
  3954. #if !defined(NO_DES3) && !defined(NO_MD5)
  3955. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3956. #endif
  3957. #if !defined(NO_DES3) && !defined(NO_SHA)
  3958. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3959. #endif
  3960. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3961. /* PKCS12 */
  3962. #if !defined(NO_RC4) && !defined(NO_SHA)
  3963. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3964. #endif
  3965. #if !defined(NO_DES3) && !defined(NO_SHA)
  3966. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3967. #endif
  3968. #if defined(WC_RC2) && !defined(NO_SHA)
  3969. static const byte pbe40Rc2Cbc[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 6};
  3970. #endif
  3971. #ifdef HAVE_LIBZ
  3972. /* zlib compression */
  3973. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3974. #endif
  3975. #ifdef WOLFSSL_APACHE_HTTPD
  3976. /* tlsExtType */
  3977. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3978. /* certNameType */
  3979. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3980. #endif
  3981. #if defined(WOLFSSL_CERT_REQ) || defined(WOLFSSL_CERT_GEN) || \
  3982. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3983. defined(WOLFSSL_ASN_TEMPLATE)
  3984. /* Pilot attribute types (0.9.2342.19200300.100.1.*) */
  3985. #define PLT_ATTR_TYPE_OID_BASE(num) {9, 146, 38, 137, 147, 242, 44, 100, 1, num}
  3986. static const byte uidOid[] = PLT_ATTR_TYPE_OID_BASE(1); /* user id */
  3987. static const byte fvrtDrk[] = PLT_ATTR_TYPE_OID_BASE(5);/* favourite drink*/
  3988. #endif
  3989. #if defined(WOLFSSL_CERT_GEN) || \
  3990. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL) || \
  3991. defined(WOLFSSL_ASN_TEMPLATE)
  3992. static const byte dcOid[] = {9, 146, 38, 137, 147, 242, 44, 100, 1, 25}; /* domain component */
  3993. #endif
  3994. /* Looks up the ID/type of an OID.
  3995. *
  3996. * When known returns the OID as a byte array and its length.
  3997. * ID-type are unique.
  3998. *
  3999. * Use oidIgnoreType to autofail.
  4000. *
  4001. * @param [in] id OID id.
  4002. * @param [in] type Type of OID (enum Oid_Types).
  4003. * @param [out] oidSz Length of OID byte array returned.
  4004. * @return Array of bytes for the OID.
  4005. * @return NULL when ID/type not recognized.
  4006. */
  4007. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  4008. {
  4009. const byte* oid = NULL;
  4010. *oidSz = 0;
  4011. switch (type) {
  4012. case oidHashType:
  4013. switch (id) {
  4014. #ifdef WOLFSSL_MD2
  4015. case MD2h:
  4016. oid = hashMd2hOid;
  4017. *oidSz = sizeof(hashMd2hOid);
  4018. break;
  4019. #endif
  4020. #ifndef NO_MD5
  4021. case MD5h:
  4022. oid = hashMd5hOid;
  4023. *oidSz = sizeof(hashMd5hOid);
  4024. break;
  4025. #endif
  4026. #ifndef NO_SHA
  4027. case SHAh:
  4028. oid = hashSha1hOid;
  4029. *oidSz = sizeof(hashSha1hOid);
  4030. break;
  4031. #endif
  4032. #ifdef WOLFSSL_SHA224
  4033. case SHA224h:
  4034. oid = hashSha224hOid;
  4035. *oidSz = sizeof(hashSha224hOid);
  4036. break;
  4037. #endif
  4038. #ifndef NO_SHA256
  4039. case SHA256h:
  4040. oid = hashSha256hOid;
  4041. *oidSz = sizeof(hashSha256hOid);
  4042. break;
  4043. #endif
  4044. #ifdef WOLFSSL_SHA384
  4045. case SHA384h:
  4046. oid = hashSha384hOid;
  4047. *oidSz = sizeof(hashSha384hOid);
  4048. break;
  4049. #endif
  4050. #ifdef WOLFSSL_SHA512
  4051. #ifndef WOLFSSL_NOSHA512_224
  4052. case SHA512_224h:
  4053. oid = hashSha512_224hOid;
  4054. *oidSz = sizeof(hashSha512_224hOid);
  4055. break;
  4056. #endif
  4057. #ifndef WOLFSSL_NOSHA512_256
  4058. case SHA512_256h:
  4059. oid = hashSha512_256hOid;
  4060. *oidSz = sizeof(hashSha512_256hOid);
  4061. break;
  4062. #endif
  4063. case SHA512h:
  4064. oid = hashSha512hOid;
  4065. *oidSz = sizeof(hashSha512hOid);
  4066. break;
  4067. #endif
  4068. #ifdef WOLFSSL_SHA3
  4069. #ifndef WOLFSSL_NOSHA3_224
  4070. case SHA3_224h:
  4071. oid = hashSha3_224hOid;
  4072. *oidSz = sizeof(hashSha3_224hOid);
  4073. break;
  4074. #endif /* WOLFSSL_NOSHA3_224 */
  4075. #ifndef WOLFSSL_NOSHA3_256
  4076. case SHA3_256h:
  4077. oid = hashSha3_256hOid;
  4078. *oidSz = sizeof(hashSha3_256hOid);
  4079. break;
  4080. #endif /* WOLFSSL_NOSHA3_256 */
  4081. #ifndef WOLFSSL_NOSHA3_384
  4082. case SHA3_384h:
  4083. oid = hashSha3_384hOid;
  4084. *oidSz = sizeof(hashSha3_384hOid);
  4085. break;
  4086. #endif /* WOLFSSL_NOSHA3_384 */
  4087. #ifndef WOLFSSL_NOSHA3_512
  4088. case SHA3_512h:
  4089. oid = hashSha3_512hOid;
  4090. *oidSz = sizeof(hashSha3_512hOid);
  4091. break;
  4092. #endif /* WOLFSSL_NOSHA3_512 */
  4093. #endif /* WOLFSSL_SHA3 */
  4094. default:
  4095. break;
  4096. }
  4097. break;
  4098. case oidSigType:
  4099. switch (id) {
  4100. #if !defined(NO_DSA) && !defined(NO_SHA)
  4101. case CTC_SHAwDSA:
  4102. oid = sigSha1wDsaOid;
  4103. *oidSz = sizeof(sigSha1wDsaOid);
  4104. break;
  4105. case CTC_SHA256wDSA:
  4106. oid = sigSha256wDsaOid;
  4107. *oidSz = sizeof(sigSha256wDsaOid);
  4108. break;
  4109. #endif /* NO_DSA */
  4110. #ifndef NO_RSA
  4111. #ifdef WOLFSSL_MD2
  4112. case CTC_MD2wRSA:
  4113. oid = sigMd2wRsaOid;
  4114. *oidSz = sizeof(sigMd2wRsaOid);
  4115. break;
  4116. #endif
  4117. #ifndef NO_MD5
  4118. case CTC_MD5wRSA:
  4119. oid = sigMd5wRsaOid;
  4120. *oidSz = sizeof(sigMd5wRsaOid);
  4121. break;
  4122. #endif
  4123. #ifndef NO_SHA
  4124. case CTC_SHAwRSA:
  4125. oid = sigSha1wRsaOid;
  4126. *oidSz = sizeof(sigSha1wRsaOid);
  4127. break;
  4128. #endif
  4129. #ifdef WOLFSSL_SHA224
  4130. case CTC_SHA224wRSA:
  4131. oid = sigSha224wRsaOid;
  4132. *oidSz = sizeof(sigSha224wRsaOid);
  4133. break;
  4134. #endif
  4135. #ifndef NO_SHA256
  4136. case CTC_SHA256wRSA:
  4137. oid = sigSha256wRsaOid;
  4138. *oidSz = sizeof(sigSha256wRsaOid);
  4139. break;
  4140. #endif
  4141. #ifdef WOLFSSL_SHA384
  4142. case CTC_SHA384wRSA:
  4143. oid = sigSha384wRsaOid;
  4144. *oidSz = sizeof(sigSha384wRsaOid);
  4145. break;
  4146. #endif
  4147. #ifdef WOLFSSL_SHA512
  4148. case CTC_SHA512wRSA:
  4149. oid = sigSha512wRsaOid;
  4150. *oidSz = sizeof(sigSha512wRsaOid);
  4151. break;
  4152. #endif /* WOLFSSL_SHA512 */
  4153. #ifdef WOLFSSL_SHA3
  4154. #ifndef WOLFSSL_NOSHA3_224
  4155. case CTC_SHA3_224wRSA:
  4156. oid = sigSha3_224wRsaOid;
  4157. *oidSz = sizeof(sigSha3_224wRsaOid);
  4158. break;
  4159. #endif
  4160. #ifndef WOLFSSL_NOSHA3_256
  4161. case CTC_SHA3_256wRSA:
  4162. oid = sigSha3_256wRsaOid;
  4163. *oidSz = sizeof(sigSha3_256wRsaOid);
  4164. break;
  4165. #endif
  4166. #ifndef WOLFSSL_NOSHA3_384
  4167. case CTC_SHA3_384wRSA:
  4168. oid = sigSha3_384wRsaOid;
  4169. *oidSz = sizeof(sigSha3_384wRsaOid);
  4170. break;
  4171. #endif
  4172. #ifndef WOLFSSL_NOSHA3_512
  4173. case CTC_SHA3_512wRSA:
  4174. oid = sigSha3_512wRsaOid;
  4175. *oidSz = sizeof(sigSha3_512wRsaOid);
  4176. break;
  4177. #endif
  4178. #endif
  4179. #ifdef WC_RSA_PSS
  4180. case CTC_RSASSAPSS:
  4181. oid = sigRsaSsaPssOid;
  4182. *oidSz = sizeof(sigRsaSsaPssOid);
  4183. break;
  4184. #endif
  4185. #endif /* NO_RSA */
  4186. #ifdef HAVE_ECC
  4187. #ifndef NO_SHA
  4188. case CTC_SHAwECDSA:
  4189. oid = sigSha1wEcdsaOid;
  4190. *oidSz = sizeof(sigSha1wEcdsaOid);
  4191. break;
  4192. #endif
  4193. #ifdef WOLFSSL_SHA224
  4194. case CTC_SHA224wECDSA:
  4195. oid = sigSha224wEcdsaOid;
  4196. *oidSz = sizeof(sigSha224wEcdsaOid);
  4197. break;
  4198. #endif
  4199. #ifndef NO_SHA256
  4200. case CTC_SHA256wECDSA:
  4201. oid = sigSha256wEcdsaOid;
  4202. *oidSz = sizeof(sigSha256wEcdsaOid);
  4203. break;
  4204. #endif
  4205. #ifdef WOLFSSL_SHA384
  4206. case CTC_SHA384wECDSA:
  4207. oid = sigSha384wEcdsaOid;
  4208. *oidSz = sizeof(sigSha384wEcdsaOid);
  4209. break;
  4210. #endif
  4211. #ifdef WOLFSSL_SHA512
  4212. case CTC_SHA512wECDSA:
  4213. oid = sigSha512wEcdsaOid;
  4214. *oidSz = sizeof(sigSha512wEcdsaOid);
  4215. break;
  4216. #endif
  4217. #ifdef WOLFSSL_SHA3
  4218. #ifndef WOLFSSL_NOSHA3_224
  4219. case CTC_SHA3_224wECDSA:
  4220. oid = sigSha3_224wEcdsaOid;
  4221. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  4222. break;
  4223. #endif
  4224. #ifndef WOLFSSL_NOSHA3_256
  4225. case CTC_SHA3_256wECDSA:
  4226. oid = sigSha3_256wEcdsaOid;
  4227. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  4228. break;
  4229. #endif
  4230. #ifndef WOLFSSL_NOSHA3_384
  4231. case CTC_SHA3_384wECDSA:
  4232. oid = sigSha3_384wEcdsaOid;
  4233. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  4234. break;
  4235. #endif
  4236. #ifndef WOLFSSL_NOSHA3_512
  4237. case CTC_SHA3_512wECDSA:
  4238. oid = sigSha3_512wEcdsaOid;
  4239. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  4240. break;
  4241. #endif
  4242. #endif
  4243. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  4244. case CTC_SM3wSM2:
  4245. oid = sigSm3wSm2Oid;
  4246. *oidSz = sizeof(sigSm3wSm2Oid);
  4247. break;
  4248. #endif
  4249. #endif /* HAVE_ECC */
  4250. #ifdef HAVE_ED25519
  4251. case CTC_ED25519:
  4252. oid = sigEd25519Oid;
  4253. *oidSz = sizeof(sigEd25519Oid);
  4254. break;
  4255. #endif
  4256. #ifdef HAVE_ED448
  4257. case CTC_ED448:
  4258. oid = sigEd448Oid;
  4259. *oidSz = sizeof(sigEd448Oid);
  4260. break;
  4261. #endif
  4262. #ifdef HAVE_PQC
  4263. #ifdef HAVE_FALCON
  4264. case CTC_FALCON_LEVEL1:
  4265. oid = sigFalcon_Level1Oid;
  4266. *oidSz = sizeof(sigFalcon_Level1Oid);
  4267. break;
  4268. case CTC_FALCON_LEVEL5:
  4269. oid = sigFalcon_Level5Oid;
  4270. *oidSz = sizeof(sigFalcon_Level5Oid);
  4271. break;
  4272. #endif /* HAVE_FALCON */
  4273. #ifdef HAVE_DILITHIUM
  4274. case CTC_DILITHIUM_LEVEL2:
  4275. oid = sigDilithium_Level2Oid;
  4276. *oidSz = sizeof(sigDilithium_Level2Oid);
  4277. break;
  4278. case CTC_DILITHIUM_LEVEL3:
  4279. oid = sigDilithium_Level3Oid;
  4280. *oidSz = sizeof(sigDilithium_Level3Oid);
  4281. break;
  4282. case CTC_DILITHIUM_LEVEL5:
  4283. oid = sigDilithium_Level5Oid;
  4284. *oidSz = sizeof(sigDilithium_Level5Oid);
  4285. break;
  4286. #endif /* HAVE_DILITHIUM */
  4287. #ifdef HAVE_SPHINCS
  4288. case CTC_SPHINCS_FAST_LEVEL1:
  4289. oid = sigSphincsFast_Level1Oid;
  4290. *oidSz = sizeof(sigSphincsFast_Level1Oid);
  4291. break;
  4292. case CTC_SPHINCS_FAST_LEVEL3:
  4293. oid = sigSphincsFast_Level3Oid;
  4294. *oidSz = sizeof(sigSphincsFast_Level3Oid);
  4295. break;
  4296. case CTC_SPHINCS_FAST_LEVEL5:
  4297. oid = sigSphincsFast_Level5Oid;
  4298. *oidSz = sizeof(sigSphincsFast_Level5Oid);
  4299. break;
  4300. case CTC_SPHINCS_SMALL_LEVEL1:
  4301. oid = sigSphincsSmall_Level1Oid;
  4302. *oidSz = sizeof(sigSphincsSmall_Level1Oid);
  4303. break;
  4304. case CTC_SPHINCS_SMALL_LEVEL3:
  4305. oid = sigSphincsSmall_Level3Oid;
  4306. *oidSz = sizeof(sigSphincsSmall_Level3Oid);
  4307. break;
  4308. case CTC_SPHINCS_SMALL_LEVEL5:
  4309. oid = sigSphincsSmall_Level5Oid;
  4310. *oidSz = sizeof(sigSphincsSmall_Level5Oid);
  4311. break;
  4312. #endif /* HAVE_SPHINCS */
  4313. #endif /* HAVE_PQC */
  4314. default:
  4315. break;
  4316. }
  4317. break;
  4318. case oidKeyType:
  4319. switch (id) {
  4320. #ifndef NO_DSA
  4321. case DSAk:
  4322. oid = keyDsaOid;
  4323. *oidSz = sizeof(keyDsaOid);
  4324. break;
  4325. #endif /* NO_DSA */
  4326. #ifndef NO_RSA
  4327. case RSAk:
  4328. oid = keyRsaOid;
  4329. *oidSz = sizeof(keyRsaOid);
  4330. break;
  4331. #ifdef WC_RSA_PSS
  4332. case RSAPSSk:
  4333. oid = keyRsaPssOid;
  4334. *oidSz = sizeof(keyRsaPssOid);
  4335. break;
  4336. #endif
  4337. #endif /* NO_RSA */
  4338. #ifdef HAVE_ECC
  4339. case ECDSAk:
  4340. oid = keyEcdsaOid;
  4341. *oidSz = sizeof(keyEcdsaOid);
  4342. break;
  4343. #endif /* HAVE_ECC */
  4344. #ifdef HAVE_ED25519
  4345. case ED25519k:
  4346. oid = keyEd25519Oid;
  4347. *oidSz = sizeof(keyEd25519Oid);
  4348. break;
  4349. #endif /* HAVE_ED25519 */
  4350. #ifdef HAVE_CURVE25519
  4351. case X25519k:
  4352. oid = keyCurve25519Oid;
  4353. *oidSz = sizeof(keyCurve25519Oid);
  4354. break;
  4355. #endif /* HAVE_CURVE25519 */
  4356. #ifdef HAVE_ED448
  4357. case ED448k:
  4358. oid = keyEd448Oid;
  4359. *oidSz = sizeof(keyEd448Oid);
  4360. break;
  4361. #endif /* HAVE_ED448 */
  4362. #ifdef HAVE_CURVE448
  4363. case X448k:
  4364. oid = keyCurve448Oid;
  4365. *oidSz = sizeof(keyCurve448Oid);
  4366. break;
  4367. #endif /* HAVE_CURVE448 */
  4368. #ifndef NO_DH
  4369. case DHk:
  4370. oid = keyDhOid;
  4371. *oidSz = sizeof(keyDhOid);
  4372. break;
  4373. #endif /* !NO_DH */
  4374. #ifdef HAVE_PQC
  4375. #ifdef HAVE_FALCON
  4376. case FALCON_LEVEL1k:
  4377. oid = keyFalcon_Level1Oid;
  4378. *oidSz = sizeof(keyFalcon_Level1Oid);
  4379. break;
  4380. case FALCON_LEVEL5k:
  4381. oid = keyFalcon_Level5Oid;
  4382. *oidSz = sizeof(keyFalcon_Level5Oid);
  4383. break;
  4384. #endif /* HAVE_FALCON */
  4385. #ifdef HAVE_DILITHIUM
  4386. case DILITHIUM_LEVEL2k:
  4387. oid = keyDilithium_Level2Oid;
  4388. *oidSz = sizeof(keyDilithium_Level2Oid);
  4389. break;
  4390. case DILITHIUM_LEVEL3k:
  4391. oid = keyDilithium_Level3Oid;
  4392. *oidSz = sizeof(keyDilithium_Level3Oid);
  4393. break;
  4394. case DILITHIUM_LEVEL5k:
  4395. oid = keyDilithium_Level5Oid;
  4396. *oidSz = sizeof(keyDilithium_Level5Oid);
  4397. break;
  4398. #endif /* HAVE_DILITHIUM */
  4399. #ifdef HAVE_SPHINCS
  4400. case SPHINCS_FAST_LEVEL1k:
  4401. oid = keySphincsFast_Level1Oid;
  4402. *oidSz = sizeof(keySphincsFast_Level1Oid);
  4403. break;
  4404. case SPHINCS_FAST_LEVEL3k:
  4405. oid = keySphincsFast_Level3Oid;
  4406. *oidSz = sizeof(keySphincsFast_Level3Oid);
  4407. break;
  4408. case SPHINCS_FAST_LEVEL5k:
  4409. oid = keySphincsFast_Level5Oid;
  4410. *oidSz = sizeof(keySphincsFast_Level5Oid);
  4411. break;
  4412. case SPHINCS_SMALL_LEVEL1k:
  4413. oid = keySphincsSmall_Level1Oid;
  4414. *oidSz = sizeof(keySphincsSmall_Level1Oid);
  4415. break;
  4416. case SPHINCS_SMALL_LEVEL3k:
  4417. oid = keySphincsSmall_Level3Oid;
  4418. *oidSz = sizeof(keySphincsSmall_Level3Oid);
  4419. break;
  4420. case SPHINCS_SMALL_LEVEL5k:
  4421. oid = keySphincsSmall_Level5Oid;
  4422. *oidSz = sizeof(keySphincsSmall_Level5Oid);
  4423. break;
  4424. #endif /* HAVE_SPHINCS */
  4425. #endif /* HAVE_PQC */
  4426. default:
  4427. break;
  4428. }
  4429. break;
  4430. #ifdef HAVE_ECC
  4431. case oidCurveType:
  4432. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  4433. WOLFSSL_MSG("ECC OID not found");
  4434. }
  4435. break;
  4436. #endif /* HAVE_ECC */
  4437. case oidBlkType:
  4438. switch (id) {
  4439. #ifdef HAVE_AES_CBC
  4440. #ifdef WOLFSSL_AES_128
  4441. case AES128CBCb:
  4442. oid = blkAes128CbcOid;
  4443. *oidSz = sizeof(blkAes128CbcOid);
  4444. break;
  4445. #endif
  4446. #ifdef WOLFSSL_AES_192
  4447. case AES192CBCb:
  4448. oid = blkAes192CbcOid;
  4449. *oidSz = sizeof(blkAes192CbcOid);
  4450. break;
  4451. #endif
  4452. #ifdef WOLFSSL_AES_256
  4453. case AES256CBCb:
  4454. oid = blkAes256CbcOid;
  4455. *oidSz = sizeof(blkAes256CbcOid);
  4456. break;
  4457. #endif
  4458. #endif /* HAVE_AES_CBC */
  4459. #ifdef HAVE_AESGCM
  4460. #ifdef WOLFSSL_AES_128
  4461. case AES128GCMb:
  4462. oid = blkAes128GcmOid;
  4463. *oidSz = sizeof(blkAes128GcmOid);
  4464. break;
  4465. #endif
  4466. #ifdef WOLFSSL_AES_192
  4467. case AES192GCMb:
  4468. oid = blkAes192GcmOid;
  4469. *oidSz = sizeof(blkAes192GcmOid);
  4470. break;
  4471. #endif
  4472. #ifdef WOLFSSL_AES_256
  4473. case AES256GCMb:
  4474. oid = blkAes256GcmOid;
  4475. *oidSz = sizeof(blkAes256GcmOid);
  4476. break;
  4477. #endif
  4478. #endif /* HAVE_AESGCM */
  4479. #ifdef HAVE_AESCCM
  4480. #ifdef WOLFSSL_AES_128
  4481. case AES128CCMb:
  4482. oid = blkAes128CcmOid;
  4483. *oidSz = sizeof(blkAes128CcmOid);
  4484. break;
  4485. #endif
  4486. #ifdef WOLFSSL_AES_192
  4487. case AES192CCMb:
  4488. oid = blkAes192CcmOid;
  4489. *oidSz = sizeof(blkAes192CcmOid);
  4490. break;
  4491. #endif
  4492. #ifdef WOLFSSL_AES_256
  4493. case AES256CCMb:
  4494. oid = blkAes256CcmOid;
  4495. *oidSz = sizeof(blkAes256CcmOid);
  4496. break;
  4497. #endif
  4498. #endif /* HAVE_AESCCM */
  4499. #ifndef NO_DES3
  4500. case DESb:
  4501. oid = blkDesCbcOid;
  4502. *oidSz = sizeof(blkDesCbcOid);
  4503. break;
  4504. case DES3b:
  4505. oid = blkDes3CbcOid;
  4506. *oidSz = sizeof(blkDes3CbcOid);
  4507. break;
  4508. #endif /* !NO_DES3 */
  4509. default:
  4510. break;
  4511. }
  4512. break;
  4513. #ifdef HAVE_OCSP
  4514. case oidOcspType:
  4515. switch (id) {
  4516. case OCSP_BASIC_OID:
  4517. oid = ocspBasicOid;
  4518. *oidSz = sizeof(ocspBasicOid);
  4519. break;
  4520. case OCSP_NONCE_OID:
  4521. oid = ocspNonceOid;
  4522. *oidSz = sizeof(ocspNonceOid);
  4523. break;
  4524. default:
  4525. break;
  4526. }
  4527. break;
  4528. #endif /* HAVE_OCSP */
  4529. case oidCertExtType:
  4530. switch (id) {
  4531. case BASIC_CA_OID:
  4532. oid = extBasicCaOid;
  4533. *oidSz = sizeof(extBasicCaOid);
  4534. break;
  4535. case ALT_NAMES_OID:
  4536. oid = extAltNamesOid;
  4537. *oidSz = sizeof(extAltNamesOid);
  4538. break;
  4539. case CRL_DIST_OID:
  4540. oid = extCrlDistOid;
  4541. *oidSz = sizeof(extCrlDistOid);
  4542. break;
  4543. case AUTH_INFO_OID:
  4544. oid = extAuthInfoOid;
  4545. *oidSz = sizeof(extAuthInfoOid);
  4546. break;
  4547. case AUTH_KEY_OID:
  4548. oid = extAuthKeyOid;
  4549. *oidSz = sizeof(extAuthKeyOid);
  4550. break;
  4551. case SUBJ_KEY_OID:
  4552. oid = extSubjKeyOid;
  4553. *oidSz = sizeof(extSubjKeyOid);
  4554. break;
  4555. case CERT_POLICY_OID:
  4556. oid = extCertPolicyOid;
  4557. *oidSz = sizeof(extCertPolicyOid);
  4558. break;
  4559. case KEY_USAGE_OID:
  4560. oid = extKeyUsageOid;
  4561. *oidSz = sizeof(extKeyUsageOid);
  4562. break;
  4563. case INHIBIT_ANY_OID:
  4564. oid = extInhibitAnyOid;
  4565. *oidSz = sizeof(extInhibitAnyOid);
  4566. break;
  4567. case EXT_KEY_USAGE_OID:
  4568. oid = extExtKeyUsageOid;
  4569. *oidSz = sizeof(extExtKeyUsageOid);
  4570. break;
  4571. #ifndef IGNORE_NAME_CONSTRAINTS
  4572. case NAME_CONS_OID:
  4573. oid = extNameConsOid;
  4574. *oidSz = sizeof(extNameConsOid);
  4575. break;
  4576. #endif
  4577. #ifdef HAVE_OCSP
  4578. case OCSP_NOCHECK_OID:
  4579. oid = ocspNoCheckOid;
  4580. *oidSz = sizeof(ocspNoCheckOid);
  4581. break;
  4582. #endif
  4583. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4584. case SUBJ_DIR_ATTR_OID:
  4585. oid = extSubjDirAttrOid;
  4586. *oidSz = sizeof(extSubjDirAttrOid);
  4587. break;
  4588. #endif
  4589. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4590. case SUBJ_INFO_ACC_OID:
  4591. oid = extSubjInfoAccessOid;
  4592. *oidSz = sizeof(extSubjInfoAccessOid);
  4593. break;
  4594. #endif
  4595. default:
  4596. break;
  4597. }
  4598. break;
  4599. case oidCrlExtType:
  4600. #ifdef HAVE_CRL
  4601. switch (id) {
  4602. case AUTH_KEY_OID:
  4603. oid = extAuthKeyOid;
  4604. *oidSz = sizeof(extAuthKeyOid);
  4605. break;
  4606. case CRL_NUMBER_OID:
  4607. oid = extCrlNumberOid;
  4608. *oidSz = sizeof(extCrlNumberOid);
  4609. break;
  4610. default:
  4611. break;
  4612. }
  4613. #endif
  4614. break;
  4615. case oidCertAuthInfoType:
  4616. switch (id) {
  4617. case AIA_OCSP_OID:
  4618. oid = extAuthInfoOcspOid;
  4619. *oidSz = sizeof(extAuthInfoOcspOid);
  4620. break;
  4621. case AIA_CA_ISSUER_OID:
  4622. oid = extAuthInfoCaIssuerOid;
  4623. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4624. break;
  4625. #ifdef WOLFSSL_SUBJ_INFO_ACC
  4626. case AIA_CA_REPO_OID:
  4627. oid = extAuthInfoCaRespOid;
  4628. *oidSz = sizeof(extAuthInfoCaRespOid);
  4629. break;
  4630. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  4631. default:
  4632. break;
  4633. }
  4634. break;
  4635. case oidCertPolicyType:
  4636. switch (id) {
  4637. case CP_ANY_OID:
  4638. oid = extCertPolicyAnyOid;
  4639. *oidSz = sizeof(extCertPolicyAnyOid);
  4640. break;
  4641. #if defined(WOLFSSL_FPKI)
  4642. case CP_FPKI_COMMON_AUTH_OID:
  4643. oid = extCertPolicyFpkiCommonAuthOid;
  4644. *oidSz = sizeof(extCertPolicyFpkiCommonAuthOid);
  4645. break;
  4646. case CP_FPKI_PIV_AUTH_OID:
  4647. oid = extCertPolicyFpkiPivAuthOid;
  4648. *oidSz = sizeof(extCertPolicyFpkiPivAuthOid);
  4649. break;
  4650. case CP_FPKI_PIV_AUTH_HW_OID: /* collision with AES256CBCb */
  4651. oid = extCertPolicyFpkiPivAuthHwOid;
  4652. *oidSz = sizeof(extCertPolicyFpkiPivAuthHwOid);
  4653. break;
  4654. case CP_FPKI_PIVI_AUTH_OID:
  4655. oid = extCertPolicyFpkiPiviAuthOid;
  4656. *oidSz = sizeof(extCertPolicyFpkiPiviAuthOid);
  4657. break;
  4658. #endif /* WOLFSSL_FPKI */
  4659. default:
  4660. break;
  4661. }
  4662. break;
  4663. case oidCertAltNameType:
  4664. switch (id) {
  4665. case HW_NAME_OID:
  4666. oid = extAltNamesHwNameOid;
  4667. *oidSz = sizeof(extAltNamesHwNameOid);
  4668. break;
  4669. default:
  4670. break;
  4671. }
  4672. break;
  4673. case oidCertKeyUseType:
  4674. switch (id) {
  4675. case EKU_ANY_OID:
  4676. oid = extExtKeyUsageAnyOid;
  4677. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4678. break;
  4679. case EKU_SERVER_AUTH_OID:
  4680. oid = extExtKeyUsageServerAuthOid;
  4681. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4682. break;
  4683. case EKU_CLIENT_AUTH_OID:
  4684. oid = extExtKeyUsageClientAuthOid;
  4685. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4686. break;
  4687. case EKU_CODESIGNING_OID:
  4688. oid = extExtKeyUsageCodeSigningOid;
  4689. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4690. break;
  4691. case EKU_EMAILPROTECT_OID:
  4692. oid = extExtKeyUsageEmailProtectOid;
  4693. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4694. break;
  4695. case EKU_TIMESTAMP_OID:
  4696. oid = extExtKeyUsageTimestampOid;
  4697. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4698. break;
  4699. case EKU_OCSP_SIGN_OID:
  4700. oid = extExtKeyUsageOcspSignOid;
  4701. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4702. break;
  4703. #ifdef WOLFSSL_WOLFSSH
  4704. case EKU_SSH_CLIENT_AUTH_OID:
  4705. oid = extExtKeyUsageSshClientAuthOid;
  4706. *oidSz = sizeof(extExtKeyUsageSshClientAuthOid);
  4707. break;
  4708. case EKU_SSH_MSCL_OID:
  4709. oid = extExtKeyUsageSshMSCLOid;
  4710. *oidSz = sizeof(extExtKeyUsageSshMSCLOid);
  4711. break;
  4712. case EKU_SSH_KP_CLIENT_AUTH_OID:
  4713. oid = extExtKeyUsageSshKpClientAuthOid;
  4714. *oidSz = sizeof(extExtKeyUsageSshKpClientAuthOid);
  4715. break;
  4716. #endif /* WOLFSSL_WOLFSSH */
  4717. default:
  4718. break;
  4719. }
  4720. break;
  4721. case oidKdfType:
  4722. switch (id) {
  4723. case PBKDF2_OID:
  4724. oid = pbkdf2Oid;
  4725. *oidSz = sizeof(pbkdf2Oid);
  4726. break;
  4727. default:
  4728. break;
  4729. }
  4730. break;
  4731. case oidPBEType:
  4732. switch (id) {
  4733. #if !defined(NO_SHA) && !defined(NO_RC4)
  4734. case PBE_SHA1_RC4_128_SUM:
  4735. case PBE_SHA1_RC4_128:
  4736. oid = pbeSha1RC4128;
  4737. *oidSz = sizeof(pbeSha1RC4128);
  4738. break;
  4739. #endif
  4740. #if !defined(NO_MD5) && !defined(NO_DES3)
  4741. case PBE_MD5_DES_SUM:
  4742. case PBE_MD5_DES:
  4743. oid = pbeMd5Des;
  4744. *oidSz = sizeof(pbeMd5Des);
  4745. break;
  4746. #endif
  4747. #if !defined(NO_SHA) && !defined(NO_DES3)
  4748. case PBE_SHA1_DES_SUM:
  4749. case PBE_SHA1_DES:
  4750. oid = pbeSha1Des;
  4751. *oidSz = sizeof(pbeSha1Des);
  4752. break;
  4753. #endif
  4754. #if !defined(NO_SHA) && !defined(NO_DES3)
  4755. case PBE_SHA1_DES3_SUM:
  4756. case PBE_SHA1_DES3:
  4757. oid = pbeSha1Des3;
  4758. *oidSz = sizeof(pbeSha1Des3);
  4759. break;
  4760. #endif
  4761. #if !defined(NO_SHA) && defined(WC_RC2)
  4762. case PBE_SHA1_40RC2_CBC_SUM:
  4763. case PBE_SHA1_40RC2_CBC:
  4764. oid = pbe40Rc2Cbc;
  4765. *oidSz = sizeof(pbe40Rc2Cbc);
  4766. break;
  4767. #endif
  4768. case PBES2_SUM:
  4769. case PBES2:
  4770. oid = pbes2;
  4771. *oidSz = sizeof(pbes2);
  4772. break;
  4773. default:
  4774. break;
  4775. }
  4776. break;
  4777. case oidKeyWrapType:
  4778. switch (id) {
  4779. #ifdef WOLFSSL_AES_128
  4780. case AES128_WRAP:
  4781. oid = wrapAes128Oid;
  4782. *oidSz = sizeof(wrapAes128Oid);
  4783. break;
  4784. #endif
  4785. #ifdef WOLFSSL_AES_192
  4786. case AES192_WRAP:
  4787. oid = wrapAes192Oid;
  4788. *oidSz = sizeof(wrapAes192Oid);
  4789. break;
  4790. #endif
  4791. #ifdef WOLFSSL_AES_256
  4792. case AES256_WRAP:
  4793. oid = wrapAes256Oid;
  4794. *oidSz = sizeof(wrapAes256Oid);
  4795. break;
  4796. #endif
  4797. #ifdef HAVE_PKCS7
  4798. case PWRI_KEK_WRAP:
  4799. oid = wrapPwriKekOid;
  4800. *oidSz = sizeof(wrapPwriKekOid);
  4801. break;
  4802. #endif
  4803. default:
  4804. break;
  4805. }
  4806. break;
  4807. case oidCmsKeyAgreeType:
  4808. switch (id) {
  4809. #ifndef NO_SHA
  4810. case dhSinglePass_stdDH_sha1kdf_scheme:
  4811. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4812. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4813. break;
  4814. #endif
  4815. #ifdef WOLFSSL_SHA224
  4816. case dhSinglePass_stdDH_sha224kdf_scheme:
  4817. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4818. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4819. break;
  4820. #endif
  4821. #ifndef NO_SHA256
  4822. case dhSinglePass_stdDH_sha256kdf_scheme:
  4823. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4824. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4825. break;
  4826. #endif
  4827. #ifdef WOLFSSL_SHA384
  4828. case dhSinglePass_stdDH_sha384kdf_scheme:
  4829. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4830. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4831. break;
  4832. #endif
  4833. #ifdef WOLFSSL_SHA512
  4834. case dhSinglePass_stdDH_sha512kdf_scheme:
  4835. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4836. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4837. break;
  4838. #endif
  4839. default:
  4840. break;
  4841. }
  4842. break;
  4843. #ifndef NO_HMAC
  4844. case oidHmacType:
  4845. switch (id) {
  4846. #ifdef WOLFSSL_SHA224
  4847. case HMAC_SHA224_OID:
  4848. oid = hmacSha224Oid;
  4849. *oidSz = sizeof(hmacSha224Oid);
  4850. break;
  4851. #endif
  4852. #ifndef NO_SHA256
  4853. case HMAC_SHA256_OID:
  4854. oid = hmacSha256Oid;
  4855. *oidSz = sizeof(hmacSha256Oid);
  4856. break;
  4857. #endif
  4858. #ifdef WOLFSSL_SHA384
  4859. case HMAC_SHA384_OID:
  4860. oid = hmacSha384Oid;
  4861. *oidSz = sizeof(hmacSha384Oid);
  4862. break;
  4863. #endif
  4864. #ifdef WOLFSSL_SHA512
  4865. case HMAC_SHA512_OID:
  4866. oid = hmacSha512Oid;
  4867. *oidSz = sizeof(hmacSha512Oid);
  4868. break;
  4869. #endif
  4870. default:
  4871. break;
  4872. }
  4873. break;
  4874. #endif /* !NO_HMAC */
  4875. #ifdef HAVE_LIBZ
  4876. case oidCompressType:
  4877. switch (id) {
  4878. case ZLIBc:
  4879. oid = zlibCompress;
  4880. *oidSz = sizeof(zlibCompress);
  4881. break;
  4882. default:
  4883. break;
  4884. }
  4885. break;
  4886. #endif /* HAVE_LIBZ */
  4887. #ifdef WOLFSSL_APACHE_HTTPD
  4888. case oidCertNameType:
  4889. switch (id) {
  4890. case NID_id_on_dnsSRV:
  4891. oid = dnsSRVOid;
  4892. *oidSz = sizeof(dnsSRVOid);
  4893. break;
  4894. default:
  4895. break;
  4896. }
  4897. break;
  4898. case oidTlsExtType:
  4899. switch (id) {
  4900. case TLS_FEATURE_OID:
  4901. oid = tlsFeatureOid;
  4902. *oidSz = sizeof(tlsFeatureOid);
  4903. break;
  4904. default:
  4905. break;
  4906. }
  4907. break;
  4908. #endif /* WOLFSSL_APACHE_HTTPD */
  4909. #ifdef WOLFSSL_CERT_REQ
  4910. case oidCsrAttrType:
  4911. switch (id) {
  4912. case GIVEN_NAME_OID:
  4913. oid = attrGivenName;
  4914. *oidSz = sizeof(attrGivenName);
  4915. break;
  4916. case SURNAME_OID:
  4917. oid = attrSurname;
  4918. *oidSz = sizeof(attrSurname);
  4919. break;
  4920. case INITIALS_OID:
  4921. oid = attrInitals;
  4922. *oidSz = sizeof(attrInitals);
  4923. break;
  4924. case DNQUALIFIER_OID:
  4925. oid = attrDnQualifier;
  4926. *oidSz = sizeof(attrDnQualifier);
  4927. break;
  4928. case UNSTRUCTURED_NAME_OID:
  4929. oid = attrUnstructuredNameOid;
  4930. *oidSz = sizeof(attrUnstructuredNameOid);
  4931. break;
  4932. case PKCS9_CONTENT_TYPE_OID:
  4933. oid = attrPkcs9ContentTypeOid;
  4934. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4935. break;
  4936. case CHALLENGE_PASSWORD_OID:
  4937. oid = attrChallengePasswordOid;
  4938. *oidSz = sizeof(attrChallengePasswordOid);
  4939. break;
  4940. case SERIAL_NUMBER_OID:
  4941. oid = attrSerialNumberOid;
  4942. *oidSz = sizeof(attrSerialNumberOid);
  4943. break;
  4944. case USER_ID_OID:
  4945. oid = uidOid;
  4946. *oidSz = sizeof(uidOid);
  4947. break;
  4948. case EXTENSION_REQUEST_OID:
  4949. oid = attrExtensionRequestOid;
  4950. *oidSz = sizeof(attrExtensionRequestOid);
  4951. break;
  4952. default:
  4953. break;
  4954. }
  4955. break;
  4956. #endif
  4957. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  4958. case oidSubjDirAttrType:
  4959. switch (id) {
  4960. case SDA_DOB_OID:
  4961. oid = extSubjDirAttrDobOid;
  4962. *oidSz = sizeof(extSubjDirAttrDobOid);
  4963. break;
  4964. case SDA_POB_OID:
  4965. oid = extSubjDirAttrPobOid;
  4966. *oidSz = sizeof(extSubjDirAttrPobOid);
  4967. break;
  4968. case SDA_GENDER_OID:
  4969. oid = extSubjDirAttrGenderOid;
  4970. *oidSz = sizeof(extSubjDirAttrGenderOid);
  4971. break;
  4972. case SDA_COC_OID:
  4973. oid = extSubjDirAttrCocOid;
  4974. *oidSz = sizeof(extSubjDirAttrCocOid);
  4975. break;
  4976. case SDA_COR_OID:
  4977. oid = extSubjDirAttrCorOid;
  4978. *oidSz = sizeof(extSubjDirAttrCorOid);
  4979. break;
  4980. default:
  4981. break;
  4982. }
  4983. break;
  4984. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  4985. case oidIgnoreType:
  4986. default:
  4987. break;
  4988. }
  4989. return oid;
  4990. }
  4991. #ifdef HAVE_ECC
  4992. /* Check the OID id is for a known elliptic curve.
  4993. *
  4994. * @param [in] oid OID id.
  4995. * @return ECC set id on success.
  4996. * @return ECC_CURVE_OID_E when OID id is 0 or not supported.
  4997. */
  4998. static int CheckCurve(word32 oid)
  4999. {
  5000. int ret;
  5001. word32 oidSz;
  5002. /* Lookup OID id. */
  5003. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  5004. /* Check for error or zero length OID size (can't get OID for encoding). */
  5005. if ((ret < 0) || (oidSz == 0)) {
  5006. WOLFSSL_MSG("CheckCurve not found");
  5007. WOLFSSL_ERROR_VERBOSE(ECC_CURVE_OID_E);
  5008. ret = ECC_CURVE_OID_E;
  5009. }
  5010. /* Return ECC set id or error code. */
  5011. return ret;
  5012. }
  5013. #endif
  5014. #ifdef HAVE_OID_ENCODING
  5015. /* Encode dotted form of OID into byte array version.
  5016. *
  5017. * @param [in] in Dotted form of OID.
  5018. * @param [in] inSz Count of numbers in dotted form.
  5019. * @param [in] out Buffer to hold OID.
  5020. * @param [in, out] outSz On in, size of buffer.
  5021. * On out, number of bytes in buffer.
  5022. * @return 0 on success
  5023. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5024. * @return BUFFER_E when buffer too small.
  5025. */
  5026. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  5027. {
  5028. int i, x, len;
  5029. word32 d, t;
  5030. /* check args */
  5031. if (in == NULL || outSz == NULL) {
  5032. return BAD_FUNC_ARG;
  5033. }
  5034. /* compute length of encoded OID */
  5035. d = (in[0] * 40) + in[1];
  5036. len = 0;
  5037. for (i = 1; i < (int)inSz; i++) {
  5038. x = 0;
  5039. t = d;
  5040. while (t) {
  5041. x++;
  5042. t >>= 1;
  5043. }
  5044. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  5045. if (i < (int)inSz - 1) {
  5046. d = in[i + 1];
  5047. }
  5048. }
  5049. if (out) {
  5050. /* verify length */
  5051. if ((int)*outSz < len) {
  5052. return BUFFER_E; /* buffer provided is not large enough */
  5053. }
  5054. /* calc first byte */
  5055. d = (in[0] * 40) + in[1];
  5056. /* encode bytes */
  5057. x = 0;
  5058. for (i = 1; i < (int)inSz; i++) {
  5059. if (d) {
  5060. int y = x, z;
  5061. byte mask = 0;
  5062. while (d) {
  5063. out[x++] = (byte)((d & 0x7F) | mask);
  5064. d >>= 7;
  5065. mask |= 0x80; /* upper bit is set on all but the last byte */
  5066. }
  5067. /* now swap bytes y...x-1 */
  5068. z = x - 1;
  5069. while (y < z) {
  5070. mask = out[y];
  5071. out[y] = out[z];
  5072. out[z] = mask;
  5073. ++y;
  5074. --z;
  5075. }
  5076. }
  5077. else {
  5078. out[x++] = 0x00; /* zero value */
  5079. }
  5080. /* next word */
  5081. if (i < (int)inSz - 1) {
  5082. d = in[i + 1];
  5083. }
  5084. }
  5085. }
  5086. /* return length */
  5087. *outSz = len;
  5088. return 0;
  5089. }
  5090. #endif /* HAVE_OID_ENCODING */
  5091. #if defined(HAVE_OID_DECODING) || defined(WOLFSSL_ASN_PRINT)
  5092. /* Encode dotted form of OID into byte array version.
  5093. *
  5094. * @param [in] in Byte array containing OID.
  5095. * @param [in] inSz Size of OID in bytes.
  5096. * @param [in] out Array to hold dotted form of OID.
  5097. * @param [in, out] outSz On in, number of elements in array.
  5098. * On out, count of numbers in dotted form.
  5099. * @return 0 on success
  5100. * @return BAD_FUNC_ARG when in or outSz is NULL.
  5101. * @return BUFFER_E when dotted form buffer too small.
  5102. */
  5103. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  5104. {
  5105. int x = 0, y = 0;
  5106. word32 t = 0;
  5107. /* check args */
  5108. if (in == NULL || outSz == NULL) {
  5109. return BAD_FUNC_ARG;
  5110. }
  5111. /* decode bytes */
  5112. while (inSz--) {
  5113. t = (t << 7) | (in[x] & 0x7F);
  5114. if (!(in[x] & 0x80)) {
  5115. if (y >= (int)*outSz) {
  5116. return BUFFER_E;
  5117. }
  5118. if (y == 0) {
  5119. out[0] = (word16)(t / 40);
  5120. out[1] = (word16)(t % 40);
  5121. y = 2;
  5122. }
  5123. else {
  5124. out[y++] = (word16)t;
  5125. }
  5126. t = 0; /* reset tmp */
  5127. }
  5128. x++;
  5129. }
  5130. /* return length */
  5131. *outSz = (word32)y;
  5132. return 0;
  5133. }
  5134. #endif /* HAVE_OID_DECODING */
  5135. /* Decode the header of a BER/DER encoded OBJECT ID.
  5136. *
  5137. * @param [in] input Buffer holding DER/BER encoded data.
  5138. * @param [in, out] inOutIdx On in, starting index of header.
  5139. * On out, end of parsed header.
  5140. * @param [out] len Number of bytes in the ASN.1 data.
  5141. * @param [in] maxIdx Length of data in buffer.
  5142. * @return 0 on success.
  5143. * @return BUFFER_E when there is not enough data to parse.
  5144. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  5145. */
  5146. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  5147. {
  5148. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  5149. if (ret > 0) {
  5150. /* Only return 0 on success. */
  5151. ret = 0;
  5152. }
  5153. return ret;
  5154. }
  5155. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  5156. *
  5157. * When output is NULL, calculate the header length only.
  5158. *
  5159. * @param [in] len Length of OBJECT ID data in bytes.
  5160. * @param [out] output Buffer to write into.
  5161. * @return Number of bytes added to the buffer.
  5162. */
  5163. int SetObjectId(int len, byte* output)
  5164. {
  5165. int idx = 0;
  5166. if (output) {
  5167. /* Write out tag. */
  5168. output[idx] = ASN_OBJECT_ID;
  5169. }
  5170. /* Skip tag. */
  5171. idx += ASN_TAG_SZ;
  5172. /* Encode length - passing NULL for output will not encode. */
  5173. idx += (int)SetLength((word32)len, output ? output + idx : NULL);
  5174. /* Return index after header. */
  5175. return idx;
  5176. }
  5177. #ifdef ASN_DUMP_OID
  5178. /* Dump the OID information.
  5179. *
  5180. * Decode the OID too if function available.
  5181. *
  5182. * @param [in] oidData OID data from buffer.
  5183. * @param [in] oidSz Size of OID data in buffer.
  5184. * @param [in] oid OID id.
  5185. * @param [in] oidType Type of OID.
  5186. * @return 0 on success.
  5187. * @return BUFFER_E when not enough bytes for proper decode.
  5188. * (HAVE_OID_DECODING)
  5189. */
  5190. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  5191. word32 oidType)
  5192. {
  5193. int ret = 0;
  5194. word32 i;
  5195. /* support for dumping OID information */
  5196. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  5197. /* Dump bytes in decimal. */
  5198. for (i = 0; i < oidSz; i++) {
  5199. printf("%d, ", oidData[i]);
  5200. }
  5201. printf("\n");
  5202. /* Dump bytes in hexadecimal. */
  5203. for (i = 0; i < oidSz; i++) {
  5204. printf("%02x, ", oidData[i]);
  5205. }
  5206. printf("\n");
  5207. #ifdef HAVE_OID_DECODING
  5208. {
  5209. word16 decOid[MAX_OID_SZ];
  5210. word32 decOidSz = sizeof(decOid);
  5211. /* Decode the OID into dotted form. */
  5212. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  5213. if (ret == 0) {
  5214. printf(" Decoded (Sz %d): ", decOidSz);
  5215. for (i=0; i<decOidSz; i++) {
  5216. printf("%d.", decOid[i]);
  5217. }
  5218. printf("\n");
  5219. }
  5220. else {
  5221. printf("DecodeObjectId failed: %d\n", ret);
  5222. }
  5223. }
  5224. #endif /* HAVE_OID_DECODING */
  5225. return ret;
  5226. }
  5227. #endif /* ASN_DUMP_OID */
  5228. /* Get the OID data and verify it is of the type specified when compiled in.
  5229. *
  5230. * @param [in] input Buffer holding OID.
  5231. * @param [in, out] inOutIdx On in, starting index of OID.
  5232. * On out, end of parsed OID.
  5233. * @param [out] oid OID id.
  5234. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  5235. * not compile in check.
  5236. * @param [in] length Length of OID data in buffer.
  5237. * @return 0 on success.
  5238. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  5239. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  5240. * HAVE_OID_DECODING)
  5241. */
  5242. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  5243. word32 oidType, int length)
  5244. {
  5245. int ret = 0;
  5246. word32 idx = *inOutIdx;
  5247. #ifndef NO_VERIFY_OID
  5248. word32 actualOidSz;
  5249. const byte* actualOid;
  5250. const byte* checkOid = NULL;
  5251. word32 checkOidSz;
  5252. #endif /* NO_VERIFY_OID */
  5253. #ifdef HAVE_PQC
  5254. word32 found_collision = 0;
  5255. #endif
  5256. (void)oidType;
  5257. *oid = 0;
  5258. #ifndef NO_VERIFY_OID
  5259. /* Keep references to OID data and length for check. */
  5260. actualOid = &input[idx];
  5261. actualOidSz = (word32)length;
  5262. #endif /* NO_VERIFY_OID */
  5263. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  5264. /* Since we are summing it up, there could be collisions...and indeed there
  5265. * are: SPHINCS_FAST_LEVEL1 and SPHINCS_FAST_LEVEL3.
  5266. *
  5267. * We will look for the special case of SPHINCS_FAST_LEVEL3 and set *oid to
  5268. * 283 instead of 281; 282 is taken.
  5269. *
  5270. * These hacks will hopefully disappear when new standardized OIDs appear.
  5271. */
  5272. if (memcmp(&input[idx], sigSphincsFast_Level3Oid,
  5273. sizeof(sigSphincsFast_Level3Oid)) == 0) {
  5274. found_collision = SPHINCS_FAST_LEVEL3k;
  5275. }
  5276. #endif /* HAVE_PQC */
  5277. /* Sum it up for now. */
  5278. while (length--) {
  5279. /* odd HC08 compiler behavior here when input[idx++] */
  5280. *oid += (word32)input[idx];
  5281. idx++;
  5282. }
  5283. #ifdef HAVE_PQC
  5284. if (found_collision) {
  5285. *oid = found_collision;
  5286. }
  5287. #endif /* HAVE_PQC */
  5288. /* Return the index after the OID data. */
  5289. *inOutIdx = idx;
  5290. #ifndef NO_VERIFY_OID
  5291. /* 'Ignore' type means we don't care which OID it is. */
  5292. if (oidType != oidIgnoreType) {
  5293. /* Get the OID data for the id-type. */
  5294. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  5295. #if defined(WOLFSSL_FPKI)
  5296. /* Handle OID sum collision of
  5297. AES256CBCb (454) 2.16.840.1.101.3.4.1.42
  5298. CP_FPKI_PIV_AUTH_HW_OID (454) 2.16.840.1.101.3.2.1.3.41
  5299. */
  5300. #if defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  5301. if ((actualOidSz == (word32)sizeof(blkAes256CbcOid)) &&
  5302. (XMEMCMP(actualOid, blkAes256CbcOid,
  5303. sizeof(blkAes256CbcOid)) == 0)) {
  5304. checkOid = blkAes256CbcOid;
  5305. checkOidSz = sizeof(blkAes256CbcOid);
  5306. }
  5307. #endif /* HAVE_AES_CBC */
  5308. #endif /* WOLFSSL_FPKI */
  5309. #ifdef ASN_DUMP_OID
  5310. /* Dump out the data for debug. */
  5311. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  5312. #endif
  5313. /* TODO: Want to fail when checkOid is NULL.
  5314. * Can't as too many situations where unknown OID is to be
  5315. * supported. Extra parameter for must not be NULL?
  5316. */
  5317. /* Check that the OID data matches what we found for the OID id. */
  5318. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  5319. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  5320. WOLFSSL_MSG("OID Check Failed");
  5321. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  5322. ret = ASN_UNKNOWN_OID_E;
  5323. }
  5324. }
  5325. #endif /* NO_VERIFY_OID */
  5326. return ret;
  5327. }
  5328. #ifdef WOLFSSL_ASN_TEMPLATE
  5329. /* ASN.1 template for an OBJECT_ID. */
  5330. static const ASNItem objectIdASN[] = {
  5331. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 }
  5332. };
  5333. enum {
  5334. OBJECTIDASN_IDX_OID = 0
  5335. };
  5336. /* Number of items in ASN.1 template for an OBJECT_ID. */
  5337. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  5338. #endif
  5339. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  5340. *
  5341. * @param [in] input Buffer holding BER encoded data.
  5342. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  5343. * On out, start of ASN.1 item after OBJECT_ID.
  5344. * @param [out] oid Id of OID in OBJECT_ID data.
  5345. * @param [in] oidType Type of OID to expect.
  5346. * @param [in] maxIdx Maximum index of data in buffer.
  5347. * @return 0 on success.
  5348. * @return ASN_PARSE_E when encoding is invalid.
  5349. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5350. */
  5351. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  5352. word32 oidType, word32 maxIdx)
  5353. {
  5354. #ifndef WOLFSSL_ASN_TEMPLATE
  5355. int ret, length;
  5356. WOLFSSL_ENTER("GetObjectId");
  5357. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  5358. if (ret != 0)
  5359. return ret;
  5360. return GetOID(input, inOutIdx, oid, oidType, length);
  5361. #else
  5362. ASNGetData dataASN[objectIdASN_Length];
  5363. int ret;
  5364. WOLFSSL_ENTER("GetObjectId");
  5365. /* Clear dynamic data and set OID type expected. */
  5366. XMEMSET(dataASN, 0, sizeof(dataASN));
  5367. GetASN_OID(&dataASN[OBJECTIDASN_IDX_OID], oidType);
  5368. /* Decode OBJECT_ID. */
  5369. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  5370. inOutIdx, maxIdx);
  5371. if (ret == 0) {
  5372. /* Return the id/sum. */
  5373. *oid = dataASN[OBJECTIDASN_IDX_OID].data.oid.sum;
  5374. }
  5375. return ret;
  5376. #endif /* WOLFSSL_ASN_TEMPLATE */
  5377. }
  5378. #ifndef WOLFSSL_ASN_TEMPLATE
  5379. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  5380. {
  5381. word32 idx = *inOutIdx;
  5382. int length;
  5383. int ret;
  5384. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  5385. if (ret != 0)
  5386. return ret;
  5387. idx += (word32)length;
  5388. *inOutIdx = idx;
  5389. return 0;
  5390. }
  5391. #endif
  5392. #ifdef WOLFSSL_ASN_TEMPLATE
  5393. /* ASN.1 template for an algorithm identifier. */
  5394. static const ASNItem algoIdASN[] = {
  5395. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5396. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  5397. /* NULL */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  5398. };
  5399. enum {
  5400. ALGOIDASN_IDX_SEQ = 0,
  5401. ALGOIDASN_IDX_OID,
  5402. ALGOIDASN_IDX_NULL
  5403. };
  5404. /* Number of items in ASN.1 template for an algorithm identifier. */
  5405. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  5406. #endif
  5407. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  5408. *
  5409. * NULL tag is skipped if present.
  5410. *
  5411. * @param [in] input Buffer holding BER encoded data.
  5412. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  5413. * On out, start of ASN.1 item after algorithm id.
  5414. * @param [out] oid Id of OID in algorithm identifier data.
  5415. * @param [in] oidType Type of OID to expect.
  5416. * @param [in] maxIdx Maximum index of data in buffer.
  5417. * @return 0 on success.
  5418. * @return ASN_PARSE_E when encoding is invalid.
  5419. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  5420. */
  5421. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  5422. word32 oidType, word32 maxIdx)
  5423. {
  5424. #ifndef WOLFSSL_ASN_TEMPLATE
  5425. int length;
  5426. word32 idx = *inOutIdx;
  5427. int ret;
  5428. *oid = 0;
  5429. WOLFSSL_ENTER("GetAlgoId");
  5430. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  5431. return ASN_PARSE_E;
  5432. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  5433. return ASN_OBJECT_ID_E;
  5434. /* could have NULL tag and 0 terminator, but may not */
  5435. if (idx < maxIdx) {
  5436. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  5437. byte tag;
  5438. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  5439. if (tag == ASN_TAG_NULL) {
  5440. ret = GetASNNull(input, &idx, maxIdx);
  5441. if (ret != 0)
  5442. return ret;
  5443. }
  5444. }
  5445. }
  5446. *inOutIdx = idx;
  5447. return 0;
  5448. #else
  5449. DECL_ASNGETDATA(dataASN, algoIdASN_Length);
  5450. int ret = 0;
  5451. WOLFSSL_ENTER("GetAlgoId");
  5452. CALLOC_ASNGETDATA(dataASN, algoIdASN_Length, ret, NULL);
  5453. if (ret == 0) {
  5454. /* Set OID type expected. */
  5455. GetASN_OID(&dataASN[ALGOIDASN_IDX_OID], oidType);
  5456. /* Decode the algorithm identifier. */
  5457. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input,
  5458. inOutIdx, maxIdx);
  5459. }
  5460. if (ret == 0) {
  5461. /* Return the OID id/sum. */
  5462. *oid = dataASN[ALGOIDASN_IDX_OID].data.oid.sum;
  5463. }
  5464. FREE_ASNGETDATA(dataASN, NULL);
  5465. return ret;
  5466. #endif /* WOLFSSL_ASN_TEMPLATE */
  5467. }
  5468. #ifndef NO_RSA
  5469. #ifdef WC_RSA_PSS
  5470. /* RFC 8017 - PKCS #1 has RSA PSS parameter ASN definition. */
  5471. /* Convert a hash OID to a hash type.
  5472. *
  5473. * @param [in] oid Hash OID.
  5474. * @param [out] type Hash type.
  5475. * @return 0 on success.
  5476. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5477. */
  5478. static int RsaPssHashOidToType(word32 oid, enum wc_HashType* type)
  5479. {
  5480. int ret = 0;
  5481. switch (oid) {
  5482. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5483. #ifdef WOLFSSL_SHA224
  5484. case SHA224h:
  5485. *type = WC_HASH_TYPE_SHA224;
  5486. break;
  5487. #endif
  5488. #ifndef NO_SHA256
  5489. case SHA256h:
  5490. *type = WC_HASH_TYPE_SHA256;
  5491. break;
  5492. #endif
  5493. #ifdef WOLFSSL_SHA384
  5494. case SHA384h:
  5495. *type = WC_HASH_TYPE_SHA384;
  5496. break;
  5497. #endif
  5498. #ifdef WOLFSSL_SHA512
  5499. case SHA512h:
  5500. *type = WC_HASH_TYPE_SHA512;
  5501. break;
  5502. /* TODO: SHA512_224h */
  5503. /* TODO: SHA512_256h */
  5504. #endif
  5505. default:
  5506. ret = ASN_PARSE_E;
  5507. break;
  5508. }
  5509. return ret;
  5510. }
  5511. /* Convert a hash OID to a MGF1 type.
  5512. *
  5513. * @param [in] oid Hash OID.
  5514. * @param [out] mgf MGF type.
  5515. * @return 0 on success.
  5516. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5517. */
  5518. static int RsaPssHashOidToMgf1(word32 oid, int* mgf)
  5519. {
  5520. int ret = 0;
  5521. switch (oid) {
  5522. /* SHA-1 is missing as it is the default is not allowed to appear. */
  5523. #ifdef WOLFSSL_SHA224
  5524. case SHA224h:
  5525. *mgf = WC_MGF1SHA224;
  5526. break;
  5527. #endif
  5528. #ifndef NO_SHA256
  5529. case SHA256h:
  5530. *mgf = WC_MGF1SHA256;
  5531. break;
  5532. #endif
  5533. #ifdef WOLFSSL_SHA384
  5534. case SHA384h:
  5535. *mgf = WC_MGF1SHA384;
  5536. break;
  5537. #endif
  5538. #ifdef WOLFSSL_SHA512
  5539. case SHA512h:
  5540. *mgf = WC_MGF1SHA512;
  5541. break;
  5542. /* TODO: SHA512_224h */
  5543. /* TODO: SHA512_256h */
  5544. #endif
  5545. default:
  5546. ret = ASN_PARSE_E;
  5547. break;
  5548. }
  5549. return ret;
  5550. }
  5551. #ifndef NO_CERTS
  5552. /* Convert a hash OID to a fake signature OID.
  5553. *
  5554. * @param [in] oid Hash OID.
  5555. * @param [out] sigOid Signature OID to pass wto HashForSignature().
  5556. * @return 0 on success.
  5557. * @return ASN_PARSE_E when hash OID not supported for RSA PSS.
  5558. */
  5559. static int RsaPssHashOidToSigOid(word32 oid, word32* sigOid)
  5560. {
  5561. int ret = 0;
  5562. switch (oid) {
  5563. #ifndef NO_SHA
  5564. case WC_HASH_TYPE_SHA:
  5565. *sigOid = CTC_SHAwRSA;
  5566. break;
  5567. #endif
  5568. #ifdef WOLFSSL_SHA224
  5569. case WC_HASH_TYPE_SHA224:
  5570. *sigOid = CTC_SHA224wRSA;
  5571. break;
  5572. #endif
  5573. #ifndef NO_SHA256
  5574. case WC_HASH_TYPE_SHA256:
  5575. *sigOid = CTC_SHA256wRSA;
  5576. break;
  5577. #endif
  5578. #ifdef WOLFSSL_SHA384
  5579. case WC_HASH_TYPE_SHA384:
  5580. *sigOid = CTC_SHA384wRSA;
  5581. break;
  5582. #endif
  5583. #ifdef WOLFSSL_SHA512
  5584. case WC_HASH_TYPE_SHA512:
  5585. *sigOid = CTC_SHA512wRSA;
  5586. break;
  5587. #endif
  5588. /* TODO: SHA512_224h */
  5589. /* TODO: SHA512_256h */
  5590. /* Not supported by HashForSignature() */
  5591. default:
  5592. ret = ASN_PARSE_E;
  5593. break;
  5594. }
  5595. return ret;
  5596. }
  5597. #endif
  5598. #ifdef WOLFSSL_ASN_TEMPLATE
  5599. /* ASN tag for hashAlgorigthm. */
  5600. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | 0)
  5601. /* ASN tag for maskGenAlgorithm. */
  5602. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | 1)
  5603. /* ASN tag for saltLength. */
  5604. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | 2)
  5605. /* ASN tag for trailerField. */
  5606. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | 3)
  5607. /* ASN.1 template for RSA PSS parameters. */
  5608. static const ASNItem rsaPssParamsASN[] = {
  5609. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5610. /* HASH */ { 1, ASN_TAG_RSA_PSS_HASH, 1, 1, 1 },
  5611. /* HASHSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5612. /* HASHOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5613. /* HASHNULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  5614. /* MGF */ { 1, ASN_TAG_RSA_PSS_MGF, 1, 1, 1 },
  5615. /* MGFSEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  5616. /* MGFOID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  5617. /* MGFPARAM */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  5618. /* MGFHOID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  5619. /* MGFHNULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  5620. /* SALTLEN */ { 1, ASN_TAG_RSA_PSS_SALTLEN, 1, 1, 1 },
  5621. /* SALTLENINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5622. /* TRAILER */ { 1, ASN_TAG_RSA_PSS_TRAILER, 1, 1, 1 },
  5623. /* TRAILERINT */ { 2, ASN_INTEGER, 0, 0, 0 },
  5624. };
  5625. enum {
  5626. RSAPSSPARAMSASN_IDX_SEQ = 0,
  5627. RSAPSSPARAMSASN_IDX_HASH,
  5628. RSAPSSPARAMSASN_IDX_HASHSEQ,
  5629. RSAPSSPARAMSASN_IDX_HASHOID,
  5630. RSAPSSPARAMSASN_IDX_HASHNULL,
  5631. RSAPSSPARAMSASN_IDX_MGF,
  5632. RSAPSSPARAMSASN_IDX_MGFSEQ,
  5633. RSAPSSPARAMSASN_IDX_MGFOID,
  5634. RSAPSSPARAMSASN_IDX_MGFPARAM,
  5635. RSAPSSPARAMSASN_IDX_MGFHOID,
  5636. RSAPSSPARAMSASN_IDX_MGFHNULL,
  5637. RSAPSSPARAMSASN_IDX_SALTLEN,
  5638. RSAPSSPARAMSASN_IDX_SALTLENINT,
  5639. RSAPSSPARAMSASN_IDX_TRAILER,
  5640. RSAPSSPARAMSASN_IDX_TRAILERINT,
  5641. };
  5642. /* Number of items in ASN.1 template for an algorithm identifier. */
  5643. #define rsaPssParamsASN_Length (sizeof(rsaPssParamsASN) / sizeof(ASNItem))
  5644. #else
  5645. /* ASN tag for hashAlgorigthm. */
  5646. #define ASN_TAG_RSA_PSS_HASH (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0)
  5647. /* ASN tag for maskGenAlgorithm. */
  5648. #define ASN_TAG_RSA_PSS_MGF (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)
  5649. /* ASN tag for saltLength. */
  5650. #define ASN_TAG_RSA_PSS_SALTLEN (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)
  5651. /* ASN tag for trailerField. */
  5652. #define ASN_TAG_RSA_PSS_TRAILER (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)
  5653. #endif
  5654. /* Decode the RSA PSS parameters.
  5655. *
  5656. * @param [in] params Buffer holding BER encoded RSA PSS parameters.
  5657. * @param [in] sz Size of data in buffer in bytes.
  5658. * @param [out] hash Hash algorithm to use on message.
  5659. * @param [out] mgf MGF algorithm to use with PSS padding.
  5660. * @param [out] saltLen Length of salt in PSS padding.
  5661. * @return BAD_FUNC_ARG when the params is NULL.
  5662. * @return ASN_PARSE_E when the decoding fails.
  5663. * @return 0 on success.
  5664. */
  5665. static int DecodeRsaPssParams(const byte* params, word32 sz,
  5666. enum wc_HashType* hash, int* mgf, int* saltLen)
  5667. {
  5668. #ifndef WOLFSSL_ASN_TEMPLATE
  5669. int ret = 0;
  5670. word32 idx = 0;
  5671. int len = 0;
  5672. word32 oid = 0;
  5673. byte tag;
  5674. int length;
  5675. if (params == NULL) {
  5676. ret = BAD_FUNC_ARG;
  5677. }
  5678. if ((ret == 0) && (GetSequence_ex(params, &idx, &len, sz, 1) < 0)) {
  5679. ret = ASN_PARSE_E;
  5680. }
  5681. if (ret == 0) {
  5682. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_HASH)) {
  5683. /* Hash algorithm to use on message. */
  5684. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5685. ret = ASN_PARSE_E;
  5686. }
  5687. if (ret == 0) {
  5688. if (GetAlgoId(params, &idx, &oid, oidHashType, sz) < 0) {
  5689. ret = ASN_PARSE_E;
  5690. }
  5691. }
  5692. if (ret == 0) {
  5693. ret = RsaPssHashOidToType(oid, hash);
  5694. }
  5695. }
  5696. else {
  5697. /* Default hash algorithm. */
  5698. *hash = WC_HASH_TYPE_SHA;
  5699. }
  5700. }
  5701. if (ret == 0) {
  5702. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_MGF)) {
  5703. /* MGF and hash algorithm to use with padding. */
  5704. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5705. ret = ASN_PARSE_E;
  5706. }
  5707. if (ret == 0) {
  5708. if (GetAlgoId(params, &idx, &oid, oidIgnoreType, sz) < 0) {
  5709. ret = ASN_PARSE_E;
  5710. }
  5711. }
  5712. if ((ret == 0) && (oid != MGF1_OID)) {
  5713. ret = ASN_PARSE_E;
  5714. }
  5715. if (ret == 0) {
  5716. ret = GetAlgoId(params, &idx, &oid, oidHashType, sz);
  5717. if (ret == 0) {
  5718. ret = RsaPssHashOidToMgf1(oid, mgf);
  5719. }
  5720. }
  5721. }
  5722. else {
  5723. /* Default MGF/Hash algorithm. */
  5724. *mgf = WC_MGF1SHA1;
  5725. }
  5726. }
  5727. if (ret == 0) {
  5728. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_SALTLEN)) {
  5729. /* Salt length to use with padding. */
  5730. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5731. ret = ASN_PARSE_E;
  5732. }
  5733. if (ret == 0) {
  5734. ret = GetInteger16Bit(params, &idx, sz);
  5735. if (ret >= 0) {
  5736. *saltLen = ret;
  5737. ret = 0;
  5738. }
  5739. }
  5740. }
  5741. else {
  5742. /* Default salt length. */
  5743. *saltLen = 20;
  5744. }
  5745. }
  5746. if (ret == 0) {
  5747. if ((idx < sz) && (params[idx] == ASN_TAG_RSA_PSS_TRAILER)) {
  5748. /* Unused - trialerField. */
  5749. if (GetHeader(params, &tag, &idx, &length, sz, 0) < 0) {
  5750. ret = ASN_PARSE_E;
  5751. }
  5752. if (ret == 0) {
  5753. ret = GetInteger16Bit(params, &idx, sz);
  5754. if (ret > 0) {
  5755. ret = 0;
  5756. }
  5757. }
  5758. }
  5759. }
  5760. if ((ret == 0) && (idx != sz)) {
  5761. ret = ASN_PARSE_E;
  5762. }
  5763. return ret;
  5764. #else
  5765. DECL_ASNGETDATA(dataASN, rsaPssParamsASN_Length);
  5766. int ret = 0;
  5767. word16 sLen = 20;
  5768. if (params == NULL) {
  5769. ret = BAD_FUNC_ARG;
  5770. }
  5771. CALLOC_ASNGETDATA(dataASN, rsaPssParamsASN_Length, ret, NULL);
  5772. if (ret == 0) {
  5773. word32 inOutIdx = 0;
  5774. /* Default values. */
  5775. *hash = WC_HASH_TYPE_SHA;
  5776. *mgf = WC_MGF1SHA1;
  5777. /* Set OID type expected. */
  5778. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_HASHOID], oidHashType);
  5779. GetASN_OID(&dataASN[RSAPSSPARAMSASN_IDX_MGFHOID], oidHashType);
  5780. /* Place the salt length into 16-bit var sLen. */
  5781. GetASN_Int16Bit(&dataASN[RSAPSSPARAMSASN_IDX_SALTLENINT], &sLen);
  5782. /* Decode the algorithm identifier. */
  5783. ret = GetASN_Items(rsaPssParamsASN, dataASN, rsaPssParamsASN_Length, 1,
  5784. params, &inOutIdx, sz);
  5785. }
  5786. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_HASHOID].tag != 0)) {
  5787. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_HASHOID].data.oid.sum;
  5788. ret = RsaPssHashOidToType(oid, hash);
  5789. }
  5790. if ((ret == 0) && (dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].tag != 0)) {
  5791. word32 oid = dataASN[RSAPSSPARAMSASN_IDX_MGFHOID].data.oid.sum;
  5792. ret = RsaPssHashOidToMgf1(oid, mgf);
  5793. }
  5794. if (ret == 0) {
  5795. *saltLen = sLen;
  5796. }
  5797. FREE_ASNGETDATA(dataASN, NULL);
  5798. return ret;
  5799. #endif /* WOLFSSL_ASN_TEMPLATE */
  5800. }
  5801. #endif /* WC_RSA_PSS */
  5802. #ifndef HAVE_USER_RSA
  5803. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  5804. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5805. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)))
  5806. /* Byte offset of numbers in RSA key. */
  5807. size_t rsaIntOffset[] = {
  5808. OFFSETOF(RsaKey, n),
  5809. OFFSETOF(RsaKey, e),
  5810. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5811. OFFSETOF(RsaKey, d),
  5812. OFFSETOF(RsaKey, p),
  5813. OFFSETOF(RsaKey, q),
  5814. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  5815. OFFSETOF(RsaKey, dP),
  5816. OFFSETOF(RsaKey, dQ),
  5817. OFFSETOF(RsaKey, u)
  5818. #endif
  5819. #endif
  5820. };
  5821. /* Get a number from the RSA key based on an index.
  5822. *
  5823. * Order: { n, e, d, p, q, dP, dQ, u }
  5824. *
  5825. * Caller must ensure index is not invalid!
  5826. *
  5827. * @param [in] key RSA key object.
  5828. * @param [in] idx Index of number.
  5829. * @return A pointer to an mp_int when valid index.
  5830. * @return NULL when invalid index.
  5831. */
  5832. static mp_int* GetRsaInt(RsaKey* key, int idx)
  5833. {
  5834. /* Cast key to byte array to and use offset to get to mp_int field. */
  5835. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  5836. }
  5837. #endif
  5838. #ifdef WOLFSSL_ASN_TEMPLATE
  5839. /* ASN.1 template for an RSA private key.
  5840. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5841. */
  5842. static const ASNItem rsaKeyASN[] = {
  5843. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5844. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  5845. /* Integers need to be in this specific order
  5846. * as asn code depends on this. */
  5847. /* N */ { 1, ASN_INTEGER, 0, 0, 0 },
  5848. /* E */ { 1, ASN_INTEGER, 0, 0, 0 },
  5849. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5850. /* D */ { 1, ASN_INTEGER, 0, 0, 0 },
  5851. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  5852. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  5853. /* DP */ { 1, ASN_INTEGER, 0, 0, 0 },
  5854. /* DQ */ { 1, ASN_INTEGER, 0, 0, 0 },
  5855. /* U */ { 1, ASN_INTEGER, 0, 0, 0 },
  5856. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  5857. * v2 - multiprime */
  5858. #endif
  5859. };
  5860. enum {
  5861. RSAKEYASN_IDX_SEQ = 0,
  5862. RSAKEYASN_IDX_VER,
  5863. /* Integers need to be in this specific order
  5864. * as asn code depends on this. */
  5865. RSAKEYASN_IDX_N,
  5866. RSAKEYASN_IDX_E,
  5867. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  5868. RSAKEYASN_IDX_D,
  5869. RSAKEYASN_IDX_P,
  5870. RSAKEYASN_IDX_Q,
  5871. RSAKEYASN_IDX_DP,
  5872. RSAKEYASN_IDX_DQ,
  5873. RSAKEYASN_IDX_U,
  5874. #endif
  5875. WOLF_ENUM_DUMMY_LAST_ELEMENT(RSAKEYASN_IDX)
  5876. };
  5877. /* Number of items in ASN.1 template for an RSA private key. */
  5878. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  5879. #endif
  5880. /* Decode RSA private key.
  5881. *
  5882. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  5883. *
  5884. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  5885. * being extracted.
  5886. *
  5887. * @param [in] input Buffer holding BER encoded data.
  5888. * @param [in, out] inOutIdx On in, start of RSA private key.
  5889. * On out, start of ASN.1 item after RSA private key.
  5890. * @param [in, out] key RSA key object. May be NULL.
  5891. * @param [out] keySz Size of key in bytes. May be NULL.
  5892. * @param [in] inSz Number of bytes in buffer.
  5893. * @return 0 on success.
  5894. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  5895. * @return BAD_FUNC_ARG when key and keySz are NULL.
  5896. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5897. * is invalid.
  5898. * @return BUFFER_E when data in buffer is too small.
  5899. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5900. * non-zero length.
  5901. * @return MP_INIT_E when the unable to initialize an mp_int.
  5902. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  5903. */
  5904. static int _RsaPrivateKeyDecode(const byte* input, word32* inOutIdx,
  5905. RsaKey* key, int* keySz, word32 inSz)
  5906. {
  5907. #ifndef WOLFSSL_ASN_TEMPLATE
  5908. int version, length;
  5909. word32 algId = 0;
  5910. if (inOutIdx == NULL || input == NULL || (key == NULL && keySz == NULL)) {
  5911. return BAD_FUNC_ARG;
  5912. }
  5913. /* if has pkcs8 header skip it */
  5914. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5915. /* ignore error, did not have pkcs8 header */
  5916. }
  5917. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  5918. return ASN_PARSE_E;
  5919. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  5920. return ASN_PARSE_E;
  5921. if (key == NULL) {
  5922. int i;
  5923. /* Modulus */
  5924. if (GetASNInt(input, inOutIdx, keySz, inSz) < 0) {
  5925. return ASN_PARSE_E;
  5926. }
  5927. *inOutIdx += (word32)*keySz;
  5928. for (i = 1; i < RSA_INTS; i++) {
  5929. if (SkipInt(input, inOutIdx, inSz) < 0) {
  5930. return ASN_RSA_KEY_E;
  5931. }
  5932. }
  5933. }
  5934. else {
  5935. key->type = RSA_PRIVATE;
  5936. #ifdef WOLFSSL_CHECK_MEM_ZERO
  5937. mp_memzero_add("Decode RSA key d", &key->d);
  5938. mp_memzero_add("Decode RSA key p", &key->p);
  5939. mp_memzero_add("Decode RSA key q", &key->q);
  5940. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  5941. !defined(RSA_LOW_MEM)) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5942. mp_memzero_add("Decode RSA key dP", &key->dP);
  5943. mp_memzero_add("Decode RSA key dQ", &key->dQ);
  5944. mp_memzero_add("Decode RSA key u", &key->u);
  5945. #endif
  5946. #endif
  5947. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  5948. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  5949. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  5950. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  5951. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  5952. GetInt(&key->q, input, inOutIdx, inSz) < 0
  5953. #else
  5954. SkipInt(input, inOutIdx, inSz) < 0 ||
  5955. SkipInt(input, inOutIdx, inSz) < 0 ||
  5956. SkipInt(input, inOutIdx, inSz) < 0
  5957. #endif
  5958. ) {
  5959. return ASN_RSA_KEY_E;
  5960. }
  5961. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  5962. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5963. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  5964. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  5965. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5966. #else
  5967. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  5968. SkipInt(input, inOutIdx, inSz) < 0 ||
  5969. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  5970. #endif
  5971. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  5972. if (wc_InitRsaHw(key) != 0) {
  5973. return BAD_STATE_E;
  5974. }
  5975. #endif
  5976. }
  5977. return 0;
  5978. #else
  5979. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  5980. int ret = 0;
  5981. byte version = (byte)-1;
  5982. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5983. word32 algId = 0;
  5984. #endif
  5985. void* heap = NULL;
  5986. /* Check validity of parameters. */
  5987. if ((inOutIdx == NULL) || (input == NULL) || ((key == NULL) &&
  5988. (keySz == NULL))) {
  5989. ret = BAD_FUNC_ARG;
  5990. }
  5991. if ((ret == 0) && (key != NULL)) {
  5992. heap = key->heap;
  5993. }
  5994. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5995. if (ret == 0) {
  5996. /* if has pkcs8 header skip it */
  5997. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  5998. /* ignore error, did not have pkcs8 header */
  5999. }
  6000. }
  6001. #endif
  6002. (void)heap;
  6003. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, heap);
  6004. if (ret == 0) {
  6005. /* Register variable to hold version field. */
  6006. GetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], &version);
  6007. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  6008. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6009. #define RSA_ASN_INTS RSA_PUB_INTS
  6010. /* Not extracting all data from BER encoding. */
  6011. #define RSA_ASN_COMPLETE 0
  6012. #else
  6013. #define RSA_ASN_INTS RSA_INTS
  6014. /* Extracting all data from BER encoding. */
  6015. #define RSA_ASN_COMPLETE 1
  6016. #endif
  6017. if (key != NULL) {
  6018. int i;
  6019. /* Extract all public fields. */
  6020. for (i = 0; i < RSA_ASN_INTS; i++) {
  6021. GetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i],
  6022. GetRsaInt(key, i));
  6023. }
  6024. }
  6025. /* Parse BER encoding for RSA private key. */
  6026. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  6027. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  6028. }
  6029. /* Check version: 0 - two prime, 1 - multi-prime
  6030. * Multi-prime has optional sequence after coefficient for extra primes.
  6031. * If extra primes, parsing will fail as not all the buffer was used.
  6032. */
  6033. if ((ret == 0) && (version > PKCS1v1)) {
  6034. ret = ASN_PARSE_E;
  6035. }
  6036. if ((ret == 0) && (key != NULL)) {
  6037. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  6038. /* RSA key object has all private key values. */
  6039. key->type = RSA_PRIVATE;
  6040. #else
  6041. /* RSA key object has all public key values. */
  6042. key->type = RSA_PUBLIC;
  6043. #endif
  6044. #ifdef WOLFSSL_XILINX_CRYPT
  6045. if (wc_InitRsaHw(key) != 0)
  6046. ret = BAD_STATE_E;
  6047. #endif
  6048. }
  6049. else if (ret == 0) {
  6050. /* Not filling in key but do want key size. */
  6051. *keySz = (int)dataASN[(byte)RSAKEYASN_IDX_N].length;
  6052. /* Check whether first byte of data is 0x00 and drop it. */
  6053. if (input[(int)dataASN[RSAKEYASN_IDX_E].offset - *keySz] == 0) {
  6054. (*keySz)--;
  6055. }
  6056. }
  6057. FREE_ASNGETDATA(dataASN, heap);
  6058. return ret;
  6059. #endif /* WOLFSSL_ASN_TEMPLATE */
  6060. }
  6061. /* Decode RSA private key.
  6062. *
  6063. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6064. *
  6065. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6066. * being extracted.
  6067. *
  6068. * @param [in] input Buffer holding BER encoded data.
  6069. * @param [in, out] inOutIdx On in, start of RSA private key.
  6070. * On out, start of ASN.1 item after RSA private key.
  6071. * @param [in, out] key RSA key object.
  6072. * @param [in] inSz Number of bytes in buffer.
  6073. * @return 0 on success.
  6074. * @return BAD_FUNC_ARG when input, inOutIdx or key is NULL.
  6075. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6076. * is invalid.
  6077. * @return BUFFER_E when data in buffer is too small.
  6078. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6079. * non-zero length.
  6080. * @return MP_INIT_E when the unable to initialize an mp_int.
  6081. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6082. */
  6083. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  6084. word32 inSz)
  6085. {
  6086. if (key == NULL) {
  6087. return BAD_FUNC_ARG;
  6088. }
  6089. return _RsaPrivateKeyDecode(input, inOutIdx, key, NULL, inSz);
  6090. }
  6091. /* Valdidate RSA private key ASN.1 encoding.
  6092. *
  6093. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  6094. *
  6095. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  6096. * being extracted.
  6097. *
  6098. * @param [in] input Buffer holding BER encoded data.
  6099. * @param [in, out] inOutIdx On in, start of RSA private key.
  6100. * On out, start of ASN.1 item after RSA private key.
  6101. * @param [in] inSz Number of bytes in buffer.
  6102. * @return 0 on success.
  6103. * @return BAD_FUNC_ARG when input, inOutIdx or keySz is NULL.
  6104. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6105. * is invalid.
  6106. * @return BUFFER_E when data in buffer is too small.
  6107. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6108. * non-zero length.
  6109. * @return MP_INIT_E when the unable to initialize an mp_int.
  6110. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  6111. */
  6112. int wc_RsaPrivateKeyValidate(const byte* input, word32* inOutIdx, int* keySz,
  6113. word32 inSz)
  6114. {
  6115. return _RsaPrivateKeyDecode(input, inOutIdx, NULL, keySz, inSz);
  6116. }
  6117. #endif /* HAVE_USER_RSA */
  6118. #endif /* NO_RSA */
  6119. #ifdef WOLFSSL_ASN_TEMPLATE
  6120. /* ASN.1 template for a PKCS #8 key.
  6121. * Ignoring optional attributes and public key.
  6122. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  6123. */
  6124. static const ASNItem pkcs8KeyASN[] = {
  6125. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6126. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  6127. /* PKEY_ALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6128. /* PKEY_ALGO_OID_KEY */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6129. /* PKEY_ALGO_OID_CURVE */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  6130. /* PKEY_ALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  6131. #ifdef WC_RSA_PSS
  6132. /* PKEY_ALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  6133. #endif
  6134. /* PKEY_DATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6135. /* attributes [0] Attributes OPTIONAL */
  6136. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  6137. };
  6138. enum {
  6139. PKCS8KEYASN_IDX_SEQ = 0,
  6140. PKCS8KEYASN_IDX_VER,
  6141. PKCS8KEYASN_IDX_PKEY_ALGO_SEQ,
  6142. PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY,
  6143. PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE,
  6144. PKCS8KEYASN_IDX_PKEY_ALGO_NULL,
  6145. #ifdef WC_RSA_PSS
  6146. PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ,
  6147. #endif
  6148. PKCS8KEYASN_IDX_PKEY_DATA,
  6149. WOLF_ENUM_DUMMY_LAST_ELEMENT(PKCS8KEYASN_IDX)
  6150. };
  6151. /* Number of items in ASN.1 template for a PKCS #8 key. */
  6152. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  6153. #endif
  6154. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, or Ed448.
  6155. *
  6156. * @param [in] input Buffer holding BER data.
  6157. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  6158. * On out, start of encoded key.
  6159. * @param [in] sz Size of data in buffer.
  6160. * @param [out] algId Key's algorithm id from PKCS #8 header.
  6161. * @return Length of key data on success.
  6162. * @return BAD_FUNC_ARG when input or inOutIdx is NULL.
  6163. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6164. * is invalid.
  6165. * @return BUFFER_E when data in buffer is too small.
  6166. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6167. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  6168. * non-zero length.
  6169. */
  6170. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  6171. word32* algId)
  6172. {
  6173. #ifndef WOLFSSL_ASN_TEMPLATE
  6174. word32 idx;
  6175. int version, length;
  6176. int ret;
  6177. byte tag;
  6178. if (input == NULL || inOutIdx == NULL)
  6179. return BAD_FUNC_ARG;
  6180. idx = *inOutIdx;
  6181. if (GetSequence(input, &idx, &length, sz) < 0)
  6182. return ASN_PARSE_E;
  6183. if (GetMyVersion(input, &idx, &version, sz) < 0)
  6184. return ASN_PARSE_E;
  6185. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  6186. return ASN_PARSE_E;
  6187. if (GetASNTag(input, &idx, &tag, sz) < 0)
  6188. return ASN_PARSE_E;
  6189. idx = idx - 1; /* reset idx after finding tag */
  6190. #if defined(WC_RSA_PSS) && !defined(NO_RSA)
  6191. if (*algId == RSAPSSk && tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  6192. word32 seqIdx = idx;
  6193. int seqLen;
  6194. /* Not set when -1. */
  6195. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  6196. int mgf = -1;
  6197. int saltLen = 0;
  6198. if (GetSequence(input, &idx, &seqLen, sz) < 0) {
  6199. return ASN_PARSE_E;
  6200. }
  6201. /* Get the private key parameters. */
  6202. ret = DecodeRsaPssParams(input + seqIdx,
  6203. seqLen + idx - seqIdx, &hash, &mgf, &saltLen);
  6204. if (ret != 0) {
  6205. return ASN_PARSE_E;
  6206. }
  6207. /* TODO: store parameters so that usage can be checked. */
  6208. idx += seqLen;
  6209. }
  6210. #endif /* WC_RSA_PSS && !NO_RSA */
  6211. if (tag == ASN_OBJECT_ID) {
  6212. if (SkipObjectId(input, &idx, sz) < 0)
  6213. return ASN_PARSE_E;
  6214. }
  6215. ret = GetOctetString(input, &idx, &length, sz);
  6216. if (ret < 0) {
  6217. if (ret == BUFFER_E)
  6218. return ASN_PARSE_E;
  6219. /* Some private keys don't expect an octet string */
  6220. WOLFSSL_MSG("Couldn't find Octet string");
  6221. }
  6222. *inOutIdx = idx;
  6223. return length;
  6224. #else
  6225. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  6226. int ret = 0;
  6227. word32 oid = 9;
  6228. byte version;
  6229. word32 idx;
  6230. /* Check validity of parameters. */
  6231. if (input == NULL || inOutIdx == NULL) {
  6232. return BAD_FUNC_ARG;
  6233. }
  6234. idx = *inOutIdx;
  6235. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6236. if (ret == 0) {
  6237. /* Get version, check key type and curve type. */
  6238. GetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], &version);
  6239. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], oidKeyType);
  6240. GetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE], oidCurveType);
  6241. /* Parse data. */
  6242. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  6243. &idx, sz);
  6244. }
  6245. if (ret == 0) {
  6246. /* Key type OID. */
  6247. oid = dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY].data.oid.sum;
  6248. /* Version 1 includes an optional public key.
  6249. * If public key is included then the parsing will fail as it did not
  6250. * use all the data.
  6251. */
  6252. if (version > PKCS8v1) {
  6253. ret = ASN_PARSE_E;
  6254. }
  6255. }
  6256. if (ret == 0) {
  6257. switch (oid) {
  6258. #ifndef NO_RSA
  6259. case RSAk:
  6260. /* Must have NULL item but not OBJECT_ID item. */
  6261. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag == 0) ||
  6262. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6263. ret = ASN_PARSE_E;
  6264. }
  6265. break;
  6266. #ifdef WC_RSA_PSS
  6267. case RSAPSSk:
  6268. /* Must not have NULL item. */
  6269. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6270. ret = ASN_PARSE_E;
  6271. }
  6272. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].tag != 0) {
  6273. enum wc_HashType hash;
  6274. int mgf;
  6275. int saltLen;
  6276. const byte* params = GetASNItem_Addr(
  6277. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6278. word32 paramsSz = GetASNItem_Length(
  6279. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ], input);
  6280. /* Validate the private key parameters. */
  6281. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf,
  6282. &saltLen);
  6283. if (ret != 0) {
  6284. return ASN_PARSE_E;
  6285. }
  6286. /* TODO: store parameters so that usage can be checked. */
  6287. }
  6288. break;
  6289. #endif
  6290. #endif
  6291. #ifdef HAVE_ECC
  6292. case ECDSAk:
  6293. /* Must not have NULL item. */
  6294. if (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) {
  6295. ret = ASN_PARSE_E;
  6296. }
  6297. break;
  6298. #endif
  6299. #ifdef HAVE_ED25519
  6300. case ED25519k:
  6301. /* Neither NULL item nor OBJECT_ID item allowed. */
  6302. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6303. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6304. ret = ASN_PARSE_E;
  6305. }
  6306. break;
  6307. #endif
  6308. #ifdef HAVE_CURVE25519
  6309. case X25519k:
  6310. /* Neither NULL item nor OBJECT_ID item allowed. */
  6311. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6312. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6313. ret = ASN_PARSE_E;
  6314. }
  6315. break;
  6316. #endif
  6317. #ifdef HAVE_ED448
  6318. case ED448k:
  6319. /* Neither NULL item nor OBJECT_ID item allowed. */
  6320. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6321. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6322. ret = ASN_PARSE_E;
  6323. }
  6324. break;
  6325. #endif
  6326. #ifdef HAVE_CURVE448
  6327. case X448k:
  6328. /* Neither NULL item nor OBJECT_ID item allowed. */
  6329. if ((dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].tag != 0) ||
  6330. (dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].tag != 0)) {
  6331. ret = ASN_PARSE_E;
  6332. }
  6333. break;
  6334. #endif
  6335. /* DSAk not supported. */
  6336. /* Falcon, Dilithium and Sphincs not supported. */
  6337. /* Ignore OID lookup failures. */
  6338. default:
  6339. break;
  6340. }
  6341. }
  6342. if (ret == 0) {
  6343. /* Return algorithm id of internal key. */
  6344. *algId = oid;
  6345. /* Return index to start of internal key. */
  6346. *inOutIdx = GetASNItem_DataIdx(dataASN[PKCS8KEYASN_IDX_PKEY_DATA], input);
  6347. /* Return value is length of internal key. */
  6348. ret = (int)dataASN[PKCS8KEYASN_IDX_PKEY_DATA].data.ref.length;
  6349. }
  6350. FREE_ASNGETDATA(dataASN, NULL);
  6351. return ret;
  6352. #endif
  6353. }
  6354. /* TODO: test case */
  6355. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  6356. {
  6357. word32 oid;
  6358. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  6359. }
  6360. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6361. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  6362. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  6363. {
  6364. word32 inOutIdx = 0;
  6365. int length;
  6366. if (input == NULL)
  6367. return BAD_FUNC_ARG;
  6368. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  6369. if (length < 0)
  6370. return length;
  6371. if ((word32)length + inOutIdx > sz)
  6372. return BUFFER_E;
  6373. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  6374. return length;
  6375. }
  6376. int ToTraditional(byte* input, word32 sz)
  6377. {
  6378. word32 oid;
  6379. return ToTraditional_ex(input, sz, &oid);
  6380. }
  6381. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6382. #if defined(HAVE_PKCS8)
  6383. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  6384. {
  6385. int length;
  6386. word32 algId;
  6387. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  6388. return BAD_FUNC_ARG;
  6389. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  6390. return length;
  6391. }
  6392. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  6393. int algoID, const byte* curveOID, word32 oidSz)
  6394. {
  6395. #ifndef WOLFSSL_ASN_TEMPLATE
  6396. word32 keyIdx = 0;
  6397. word32 tmpSz = 0;
  6398. word32 sz;
  6399. word32 tmpAlgId = 0;
  6400. /* If out is NULL then return the max size needed
  6401. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  6402. if (out == NULL && outSz != NULL) {
  6403. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6404. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  6405. if (curveOID != NULL)
  6406. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  6407. WOLFSSL_MSG("Checking size of PKCS8");
  6408. return LENGTH_ONLY_E;
  6409. }
  6410. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6411. if (key == NULL || out == NULL || outSz == NULL) {
  6412. return BAD_FUNC_ARG;
  6413. }
  6414. /* check the buffer has enough room for largest possible size */
  6415. if (curveOID != NULL) {
  6416. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6417. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  6418. return BUFFER_E;
  6419. }
  6420. else {
  6421. oidSz = 0; /* with no curveOID oid size must be 0 */
  6422. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  6423. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  6424. return BUFFER_E;
  6425. }
  6426. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  6427. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6428. (void)tmpAlgId;
  6429. return ASN_PARSE_E;
  6430. }
  6431. /* PrivateKeyInfo ::= SEQUENCE */
  6432. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  6433. /* version Version
  6434. * no header information just INTEGER */
  6435. sz = (word32)SetMyVersion(PKCS8v0, out + keyIdx, 0);
  6436. tmpSz += sz; keyIdx += sz;
  6437. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  6438. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  6439. if (curveOID != NULL && oidSz > 0) {
  6440. byte buf[MAX_LENGTH_SZ];
  6441. sz = SetLength(oidSz, buf);
  6442. sz += 1; /* plus one for ASN object id */
  6443. }
  6444. sz = (word32)SetAlgoID(algoID, out + keyIdx, oidKeyType, (int)(oidSz + sz));
  6445. tmpSz += sz; keyIdx += sz;
  6446. /* privateKey PrivateKey *
  6447. * pkcs8 ecc uses slightly different format. Places curve oid in
  6448. * buffer */
  6449. if (curveOID != NULL && oidSz > 0) {
  6450. sz = (word32)SetObjectId((int)oidSz, out + keyIdx);
  6451. keyIdx += sz; tmpSz += sz;
  6452. XMEMCPY(out + keyIdx, curveOID, oidSz);
  6453. keyIdx += oidSz; tmpSz += oidSz;
  6454. }
  6455. sz = (word32)SetOctetString(keySz, out + keyIdx);
  6456. keyIdx += sz; tmpSz += sz;
  6457. XMEMCPY(out + keyIdx, key, keySz);
  6458. tmpSz += keySz;
  6459. /* attributes optional
  6460. * No attributes currently added */
  6461. /* rewind and add sequence */
  6462. sz = SetSequence(tmpSz, out);
  6463. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  6464. *outSz = tmpSz + sz;
  6465. return (int)(tmpSz + sz);
  6466. #else
  6467. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  6468. int sz;
  6469. int ret = 0;
  6470. word32 keyIdx = 0;
  6471. word32 tmpAlgId = 0;
  6472. WOLFSSL_ENTER("wc_CreatePKCS8Key");
  6473. /* Check validity of parameters. */
  6474. if (out == NULL && outSz != NULL) {
  6475. }
  6476. else if (key == NULL || out == NULL || outSz == NULL) {
  6477. ret = BAD_FUNC_ARG;
  6478. }
  6479. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  6480. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  6481. (void)tmpAlgId;
  6482. ret = ASN_PARSE_E;
  6483. }
  6484. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  6485. if (ret == 0) {
  6486. /* Only support default PKCS #8 format - v0. */
  6487. SetASN_Int8Bit(&dataASN[PKCS8KEYASN_IDX_VER], PKCS8v0);
  6488. /* Set key OID that corresponds to key data. */
  6489. SetASN_OID(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_KEY], (word32)algoID,
  6490. oidKeyType);
  6491. if (curveOID != NULL && oidSz > 0) {
  6492. /* ECC key and curveOID set to write. */
  6493. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE],
  6494. curveOID, oidSz);
  6495. }
  6496. else {
  6497. /* EC curve OID to encode. */
  6498. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_OID_CURVE].noOut = 1;
  6499. }
  6500. /* Only RSA keys have NULL tagged item after OID. */
  6501. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_NULL].noOut = (algoID != RSAk);
  6502. #ifdef WC_RSA_PSS
  6503. dataASN[PKCS8KEYASN_IDX_PKEY_ALGO_PARAM_SEQ].noOut = 1;
  6504. #endif
  6505. /* Set key data to encode. */
  6506. SetASN_Buffer(&dataASN[PKCS8KEYASN_IDX_PKEY_DATA], key, keySz);
  6507. /* Get the size of the DER encoding. */
  6508. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  6509. }
  6510. if (ret == 0) {
  6511. /* Always return the calculated size. */
  6512. *outSz = (word32)sz;
  6513. }
  6514. /* Check for buffer to encoded into. */
  6515. if ((ret == 0) && (out == NULL)) {
  6516. WOLFSSL_MSG("Checking size of PKCS8");
  6517. ret = LENGTH_ONLY_E;
  6518. }
  6519. if (ret == 0) {
  6520. /* Encode PKCS #8 key into buffer. */
  6521. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  6522. ret = sz;
  6523. }
  6524. FREE_ASNSETDATA(dataASN, NULL);
  6525. return ret;
  6526. #endif /* WOLFSSL_ASN_TEMPLATE */
  6527. }
  6528. #endif /* HAVE_PKCS8 */
  6529. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  6530. /* check that the private key is a pair for the public key
  6531. * return 1 (true) on match
  6532. * return 0 or negative value on failure/error
  6533. *
  6534. * privKey : buffer holding DER format private key
  6535. * privKeySz : size of private key buffer
  6536. * pubKey : buffer holding DER format public key
  6537. * pubKeySz : size of public key buffer
  6538. * ks : type of key */
  6539. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  6540. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  6541. {
  6542. int ret;
  6543. (void)privKeySz;
  6544. (void)pubKeySz;
  6545. (void)ks;
  6546. if (privKey == NULL || pubKey == NULL) {
  6547. return BAD_FUNC_ARG;
  6548. }
  6549. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  6550. /* test if RSA key */
  6551. if (ks == RSAk
  6552. #ifdef WC_RSA_PSS
  6553. || ks == RSAPSSk
  6554. #endif
  6555. ) {
  6556. #ifdef WOLFSSL_SMALL_STACK
  6557. RsaKey* a;
  6558. RsaKey* b = NULL;
  6559. #else
  6560. RsaKey a[1], b[1];
  6561. #endif
  6562. word32 keyIdx = 0;
  6563. #ifdef WOLFSSL_SMALL_STACK
  6564. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6565. if (a == NULL)
  6566. return MEMORY_E;
  6567. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  6568. if (b == NULL) {
  6569. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6570. return MEMORY_E;
  6571. }
  6572. #endif
  6573. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  6574. #ifdef WOLFSSL_SMALL_STACK
  6575. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6576. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6577. #endif
  6578. return ret;
  6579. }
  6580. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  6581. wc_FreeRsaKey(a);
  6582. #ifdef WOLFSSL_SMALL_STACK
  6583. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6584. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6585. #endif
  6586. return ret;
  6587. }
  6588. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  6589. WOLFSSL_MSG("Checking RSA key pair");
  6590. keyIdx = 0; /* reset to 0 for parsing public key */
  6591. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  6592. pubKeySz)) == 0) {
  6593. /* limit for user RSA crypto because of RsaKey
  6594. * dereference. */
  6595. #if defined(HAVE_USER_RSA)
  6596. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  6597. ret = 1; /* return first RSA cert as match */
  6598. #else
  6599. /* both keys extracted successfully now check n and e
  6600. * values are the same. This is dereferencing RsaKey */
  6601. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  6602. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  6603. ret = MP_CMP_E;
  6604. WOLFSSL_ERROR_VERBOSE(ret);
  6605. }
  6606. else
  6607. ret = 1;
  6608. #endif
  6609. }
  6610. else {
  6611. WOLFSSL_ERROR_VERBOSE(ret);
  6612. }
  6613. }
  6614. wc_FreeRsaKey(b);
  6615. wc_FreeRsaKey(a);
  6616. #ifdef WOLFSSL_SMALL_STACK
  6617. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  6618. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  6619. #endif
  6620. }
  6621. else
  6622. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  6623. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  6624. if (ks == ECDSAk) {
  6625. #ifdef WOLFSSL_SMALL_STACK
  6626. ecc_key* key_pair;
  6627. byte* privDer;
  6628. #else
  6629. ecc_key key_pair[1];
  6630. byte privDer[MAX_ECC_BYTES];
  6631. #endif
  6632. word32 privSz = MAX_ECC_BYTES;
  6633. word32 keyIdx = 0;
  6634. #ifdef WOLFSSL_SMALL_STACK
  6635. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  6636. if (key_pair == NULL)
  6637. return MEMORY_E;
  6638. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6639. if (privDer == NULL) {
  6640. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6641. return MEMORY_E;
  6642. }
  6643. #endif
  6644. if ((ret = wc_ecc_init(key_pair)) < 0) {
  6645. #ifdef WOLFSSL_SMALL_STACK
  6646. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6647. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6648. #endif
  6649. return ret;
  6650. }
  6651. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  6652. privKeySz)) == 0) {
  6653. WOLFSSL_MSG("Checking ECC key pair");
  6654. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  6655. == 0) {
  6656. #ifdef WOLFSSL_CHECK_MEM_ZERO
  6657. wc_MemZero_Add("wc_CheckPrivateKey privDer", privDer, privSz);
  6658. #endif
  6659. wc_ecc_free(key_pair);
  6660. ret = wc_ecc_init(key_pair);
  6661. if (ret == 0) {
  6662. ret = wc_ecc_import_private_key(privDer,
  6663. privSz, pubKey,
  6664. pubKeySz, key_pair);
  6665. }
  6666. /* public and private extracted successfully now check if is
  6667. * a pair and also do sanity checks on key. wc_ecc_check_key
  6668. * checks that private * base generator equals pubkey */
  6669. if (ret == 0) {
  6670. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  6671. ret = 1;
  6672. }
  6673. else {
  6674. WOLFSSL_ERROR_VERBOSE(ret);
  6675. }
  6676. }
  6677. ForceZero(privDer, privSz);
  6678. }
  6679. }
  6680. else {
  6681. WOLFSSL_ERROR_VERBOSE(ret);
  6682. }
  6683. wc_ecc_free(key_pair);
  6684. #ifdef WOLFSSL_SMALL_STACK
  6685. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6686. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  6687. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  6688. wc_MemZero_Check(privDer, MAX_ECC_BYTES);
  6689. #endif
  6690. }
  6691. else
  6692. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  6693. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6694. if (ks == ED25519k) {
  6695. #ifdef WOLFSSL_SMALL_STACK
  6696. ed25519_key* key_pair;
  6697. #else
  6698. ed25519_key key_pair[1];
  6699. #endif
  6700. word32 keyIdx = 0;
  6701. #ifdef WOLFSSL_SMALL_STACK
  6702. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  6703. DYNAMIC_TYPE_ED25519);
  6704. if (key_pair == NULL)
  6705. return MEMORY_E;
  6706. #endif
  6707. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  6708. #ifdef WOLFSSL_SMALL_STACK
  6709. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6710. #endif
  6711. return ret;
  6712. }
  6713. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6714. privKeySz)) == 0) {
  6715. WOLFSSL_MSG("Checking ED25519 key pair");
  6716. keyIdx = 0;
  6717. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  6718. key_pair)) == 0) {
  6719. /* public and private extracted successfully no check if is
  6720. * a pair and also do sanity checks on key. wc_ecc_check_key
  6721. * checks that private * base generator equals pubkey */
  6722. if ((ret = wc_ed25519_check_key(key_pair)) == 0) {
  6723. ret = 1;
  6724. }
  6725. else {
  6726. WOLFSSL_ERROR_VERBOSE(ret);
  6727. }
  6728. }
  6729. }
  6730. else {
  6731. WOLFSSL_ERROR_VERBOSE(ret);
  6732. }
  6733. wc_ed25519_free(key_pair);
  6734. #ifdef WOLFSSL_SMALL_STACK
  6735. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  6736. #endif
  6737. }
  6738. else
  6739. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  6740. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  6741. if (ks == ED448k) {
  6742. #ifdef WOLFSSL_SMALL_STACK
  6743. ed448_key* key_pair = NULL;
  6744. #else
  6745. ed448_key key_pair[1];
  6746. #endif
  6747. word32 keyIdx = 0;
  6748. #ifdef WOLFSSL_SMALL_STACK
  6749. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  6750. DYNAMIC_TYPE_ED448);
  6751. if (key_pair == NULL)
  6752. return MEMORY_E;
  6753. #endif
  6754. if ((ret = wc_ed448_init(key_pair)) < 0) {
  6755. #ifdef WOLFSSL_SMALL_STACK
  6756. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6757. #endif
  6758. return ret;
  6759. }
  6760. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6761. privKeySz)) == 0) {
  6762. WOLFSSL_MSG("Checking ED448 key pair");
  6763. keyIdx = 0;
  6764. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  6765. key_pair)) == 0) {
  6766. /* public and private extracted successfully no check if is
  6767. * a pair and also do sanity checks on key. wc_ecc_check_key
  6768. * checks that private * base generator equals pubkey */
  6769. if ((ret = wc_ed448_check_key(key_pair)) == 0) {
  6770. ret = 1;
  6771. }
  6772. else {
  6773. WOLFSSL_ERROR_VERBOSE(ret);
  6774. }
  6775. }
  6776. }
  6777. else {
  6778. WOLFSSL_ERROR_VERBOSE(ret);
  6779. }
  6780. wc_ed448_free(key_pair);
  6781. #ifdef WOLFSSL_SMALL_STACK
  6782. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  6783. #endif
  6784. }
  6785. else
  6786. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  6787. #if defined(HAVE_PQC)
  6788. #if defined(HAVE_FALCON)
  6789. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  6790. #ifdef WOLFSSL_SMALL_STACK
  6791. falcon_key* key_pair = NULL;
  6792. #else
  6793. falcon_key key_pair[1];
  6794. #endif
  6795. word32 keyIdx = 0;
  6796. #ifdef WOLFSSL_SMALL_STACK
  6797. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  6798. DYNAMIC_TYPE_FALCON);
  6799. if (key_pair == NULL)
  6800. return MEMORY_E;
  6801. #endif
  6802. ret = wc_falcon_init(key_pair);
  6803. if (ret < 0) {
  6804. #ifdef WOLFSSL_SMALL_STACK
  6805. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6806. #endif
  6807. return ret;
  6808. }
  6809. if (ks == FALCON_LEVEL1k) {
  6810. ret = wc_falcon_set_level(key_pair, 1);
  6811. }
  6812. else if (ks == FALCON_LEVEL5k) {
  6813. ret = wc_falcon_set_level(key_pair, 5);
  6814. }
  6815. if (ret < 0) {
  6816. #ifdef WOLFSSL_SMALL_STACK
  6817. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6818. #endif
  6819. return ret;
  6820. }
  6821. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6822. privKeySz)) == 0) {
  6823. WOLFSSL_MSG("Checking Falcon key pair");
  6824. keyIdx = 0;
  6825. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  6826. key_pair)) == 0) {
  6827. /* Public and private extracted successfully. Sanity check. */
  6828. if ((ret = wc_falcon_check_key(key_pair)) == 0) {
  6829. ret = 1;
  6830. }
  6831. else {
  6832. WOLFSSL_ERROR_VERBOSE(ret);
  6833. }
  6834. }
  6835. }
  6836. else {
  6837. WOLFSSL_ERROR_VERBOSE(ret);
  6838. }
  6839. wc_falcon_free(key_pair);
  6840. #ifdef WOLFSSL_SMALL_STACK
  6841. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  6842. #endif
  6843. }
  6844. else
  6845. #endif /* HAVE_FALCON */
  6846. #if defined(HAVE_DILITHIUM)
  6847. if ((ks == DILITHIUM_LEVEL2k) ||
  6848. (ks == DILITHIUM_LEVEL3k) ||
  6849. (ks == DILITHIUM_LEVEL5k)) {
  6850. #ifdef WOLFSSL_SMALL_STACK
  6851. dilithium_key* key_pair = NULL;
  6852. #else
  6853. dilithium_key key_pair[1];
  6854. #endif
  6855. word32 keyIdx = 0;
  6856. #ifdef WOLFSSL_SMALL_STACK
  6857. key_pair = (dilithium_key*)XMALLOC(sizeof(dilithium_key), NULL,
  6858. DYNAMIC_TYPE_DILITHIUM);
  6859. if (key_pair == NULL)
  6860. return MEMORY_E;
  6861. #endif
  6862. ret = wc_dilithium_init(key_pair);
  6863. if (ret < 0) {
  6864. #ifdef WOLFSSL_SMALL_STACK
  6865. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6866. #endif
  6867. return ret;
  6868. }
  6869. if (ks == DILITHIUM_LEVEL2k) {
  6870. ret = wc_dilithium_set_level(key_pair, 2);
  6871. }
  6872. else if (ks == DILITHIUM_LEVEL3k) {
  6873. ret = wc_dilithium_set_level(key_pair, 3);
  6874. }
  6875. else if (ks == DILITHIUM_LEVEL5k) {
  6876. ret = wc_dilithium_set_level(key_pair, 5);
  6877. }
  6878. if (ret < 0) {
  6879. #ifdef WOLFSSL_SMALL_STACK
  6880. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6881. #endif
  6882. return ret;
  6883. }
  6884. if ((ret = wc_Dilithium_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6885. privKeySz)) == 0) {
  6886. WOLFSSL_MSG("Checking Dilithium key pair");
  6887. keyIdx = 0;
  6888. if ((ret = wc_dilithium_import_public(pubKey, pubKeySz,
  6889. key_pair)) == 0) {
  6890. /* Public and private extracted successfully. Sanity check. */
  6891. if ((ret = wc_dilithium_check_key(key_pair)) == 0)
  6892. ret = 1;
  6893. }
  6894. }
  6895. wc_dilithium_free(key_pair);
  6896. #ifdef WOLFSSL_SMALL_STACK
  6897. XFREE(key_pair, NULL, DYNAMIC_TYPE_DILITHIUM);
  6898. #endif
  6899. }
  6900. else
  6901. #endif /* HAVE_DILITHIUM */
  6902. #if defined(HAVE_SPHINCS)
  6903. if ((ks == SPHINCS_FAST_LEVEL1k) ||
  6904. (ks == SPHINCS_FAST_LEVEL3k) ||
  6905. (ks == SPHINCS_FAST_LEVEL5k) ||
  6906. (ks == SPHINCS_SMALL_LEVEL1k) ||
  6907. (ks == SPHINCS_SMALL_LEVEL3k) ||
  6908. (ks == SPHINCS_SMALL_LEVEL5k)) {
  6909. #ifdef WOLFSSL_SMALL_STACK
  6910. sphincs_key* key_pair = NULL;
  6911. #else
  6912. sphincs_key key_pair[1];
  6913. #endif
  6914. word32 keyIdx = 0;
  6915. #ifdef WOLFSSL_SMALL_STACK
  6916. key_pair = (sphincs_key*)XMALLOC(sizeof(sphincs_key), NULL,
  6917. DYNAMIC_TYPE_SPHINCS);
  6918. if (key_pair == NULL)
  6919. return MEMORY_E;
  6920. #endif
  6921. ret = wc_sphincs_init(key_pair);
  6922. if (ret < 0) {
  6923. #ifdef WOLFSSL_SMALL_STACK
  6924. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6925. #endif
  6926. return ret;
  6927. }
  6928. if (ks == SPHINCS_FAST_LEVEL1k) {
  6929. ret = wc_sphincs_set_level_and_optim(key_pair, 1, FAST_VARIANT);
  6930. }
  6931. else if (ks == SPHINCS_FAST_LEVEL3k) {
  6932. ret = wc_sphincs_set_level_and_optim(key_pair, 3, FAST_VARIANT);
  6933. }
  6934. else if (ks == SPHINCS_FAST_LEVEL5k) {
  6935. ret = wc_sphincs_set_level_and_optim(key_pair, 5, FAST_VARIANT);
  6936. }
  6937. else if (ks == SPHINCS_SMALL_LEVEL1k) {
  6938. ret = wc_sphincs_set_level_and_optim(key_pair, 1, SMALL_VARIANT);
  6939. }
  6940. else if (ks == SPHINCS_SMALL_LEVEL3k) {
  6941. ret = wc_sphincs_set_level_and_optim(key_pair, 3, SMALL_VARIANT);
  6942. }
  6943. else if (ks == SPHINCS_SMALL_LEVEL5k) {
  6944. ret = wc_sphincs_set_level_and_optim(key_pair, 5, SMALL_VARIANT);
  6945. }
  6946. if (ret < 0) {
  6947. #ifdef WOLFSSL_SMALL_STACK
  6948. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6949. #endif
  6950. return ret;
  6951. }
  6952. if ((ret = wc_Sphincs_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  6953. privKeySz)) == 0) {
  6954. WOLFSSL_MSG("Checking Sphincs key pair");
  6955. keyIdx = 0;
  6956. if ((ret = wc_sphincs_import_public(pubKey, pubKeySz,
  6957. key_pair)) == 0) {
  6958. /* Public and private extracted successfully. Sanity check. */
  6959. if ((ret = wc_sphincs_check_key(key_pair)) == 0)
  6960. ret = 1;
  6961. }
  6962. }
  6963. wc_sphincs_free(key_pair);
  6964. #ifdef WOLFSSL_SMALL_STACK
  6965. XFREE(key_pair, NULL, DYNAMIC_TYPE_SPHINCS);
  6966. #endif
  6967. }
  6968. else
  6969. #endif /* HAVE_SPHINCS */
  6970. #endif /* HAVE_PQC */
  6971. {
  6972. ret = 0;
  6973. }
  6974. (void)ks;
  6975. return ret;
  6976. }
  6977. /* check that the private key is a pair for the public key in certificate
  6978. * return 1 (true) on match
  6979. * return 0 or negative value on failure/error
  6980. *
  6981. * key : buffer holding DER format key
  6982. * keySz : size of key buffer
  6983. * der : a initialized and parsed DecodedCert holding a certificate */
  6984. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  6985. {
  6986. if (key == NULL || der == NULL) {
  6987. return BAD_FUNC_ARG;
  6988. }
  6989. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  6990. der->pubKeySize, (enum Key_Sum) der->keyOID);
  6991. }
  6992. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  6993. #ifndef NO_PWDBASED
  6994. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  6995. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  6996. * size of encryption algorithm.
  6997. *
  6998. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  6999. * blockSz based on encryption algorithm.
  7000. *
  7001. * @param [in] first First byte of OID to use in check.
  7002. * @param [in] second Second byte of OID to use in check.
  7003. * @param [out] id wolfSSL id for PBE algorithm.
  7004. * @param [out] version Version of PBE OID:
  7005. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7006. * @param [out] blockSz Block size of encryption algorithm.
  7007. * @return 0 on success.
  7008. * @return ALGO_ID_E when OID not supported.
  7009. * @return ASN_INPUT_E when first byte is invalid.
  7010. */
  7011. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  7012. {
  7013. int ret = 0;
  7014. (void)id;
  7015. (void)blockSz;
  7016. *version = -1;
  7017. /* pkcs-12 1 = pkcs-12PbeIds */
  7018. if (first == 1) {
  7019. /* PKCS #12: Appendix C */
  7020. switch (second) {
  7021. #if !defined(NO_SHA)
  7022. #ifndef NO_RC4
  7023. case PBE_SHA1_RC4_128:
  7024. *id = PBE_SHA1_RC4_128;
  7025. *version = PKCS12v1;
  7026. if (blockSz != NULL) {
  7027. *blockSz = 1;
  7028. }
  7029. break;
  7030. #endif
  7031. #ifndef NO_DES3
  7032. case PBE_SHA1_DES3:
  7033. *id = PBE_SHA1_DES3;
  7034. *version = PKCS12v1;
  7035. if (blockSz != NULL) {
  7036. *blockSz = DES_BLOCK_SIZE;
  7037. }
  7038. break;
  7039. #endif
  7040. #ifdef WC_RC2
  7041. case PBE_SHA1_40RC2_CBC:
  7042. *id = PBE_SHA1_40RC2_CBC;
  7043. *version = PKCS12v1;
  7044. if (blockSz != NULL) {
  7045. *blockSz = RC2_BLOCK_SIZE;
  7046. }
  7047. break;
  7048. #endif
  7049. #endif /* !NO_SHA */
  7050. default:
  7051. ret = ALGO_ID_E;
  7052. break;
  7053. }
  7054. }
  7055. else if (first != PKCS5) {
  7056. /* Bad OID. */
  7057. ret = ASN_INPUT_E;
  7058. }
  7059. /* PKCS #5 PBES2: Appendix A.4
  7060. * pkcs-5 13 = id-PBES2 */
  7061. else if (second == PBES2) {
  7062. *version = PKCS5v2;
  7063. /* Id and block size come from CheckAlgoV2() */
  7064. }
  7065. else {
  7066. /* PKCS #5 PBES1: Appendix A.3 */
  7067. /* see RFC 2898 for ids */
  7068. switch (second) {
  7069. #ifndef NO_DES3
  7070. #ifndef NO_MD5
  7071. case PBES1_MD5_DES:
  7072. *id = PBE_MD5_DES;
  7073. *version = PKCS5;
  7074. if (blockSz != NULL) {
  7075. *blockSz = DES_BLOCK_SIZE;
  7076. }
  7077. break;
  7078. #endif
  7079. #ifndef NO_SHA
  7080. case PBES1_SHA1_DES:
  7081. *id = PBE_SHA1_DES;
  7082. *version = PKCS5;
  7083. if (blockSz != NULL) {
  7084. *blockSz = DES_BLOCK_SIZE;
  7085. }
  7086. break;
  7087. #endif
  7088. #endif /* !NO_DES3 */
  7089. default:
  7090. ret = ALGO_ID_E;
  7091. break;
  7092. }
  7093. }
  7094. /* Return error code. */
  7095. return ret;
  7096. }
  7097. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7098. #ifdef HAVE_PKCS8
  7099. /* Check the encryption algorithm with PBES2 is supported and return block size
  7100. * and wolfSSL id for the PBE.
  7101. *
  7102. * @param [in] oid Encryption algorithm OID id.
  7103. * @param [out] id wolfSSL id for PBE algorithm.
  7104. * @param [out] version Version of PBE OID:
  7105. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  7106. * @return 0 on success.
  7107. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  7108. */
  7109. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  7110. {
  7111. int ret = 0;
  7112. (void)id;
  7113. (void)blockSz;
  7114. switch (oid) {
  7115. #if !defined(NO_DES3) && !defined(NO_SHA)
  7116. case DESb:
  7117. *id = PBE_SHA1_DES;
  7118. if (blockSz != NULL) {
  7119. *blockSz = DES_BLOCK_SIZE;
  7120. }
  7121. break;
  7122. case DES3b:
  7123. *id = PBE_SHA1_DES3;
  7124. if (blockSz != NULL) {
  7125. *blockSz = DES_BLOCK_SIZE;
  7126. }
  7127. break;
  7128. #endif
  7129. #ifdef WOLFSSL_AES_256
  7130. case AES256CBCb:
  7131. *id = PBE_AES256_CBC;
  7132. if (blockSz != NULL) {
  7133. *blockSz = AES_BLOCK_SIZE;
  7134. }
  7135. break;
  7136. #endif
  7137. #ifdef WOLFSSL_AES_128
  7138. case AES128CBCb:
  7139. *id = PBE_AES128_CBC;
  7140. if (blockSz != NULL) {
  7141. *blockSz = AES_BLOCK_SIZE;
  7142. }
  7143. break;
  7144. #endif
  7145. default:
  7146. WOLFSSL_MSG("No PKCS v2 algo found");
  7147. ret = ALGO_ID_E;
  7148. break;
  7149. }
  7150. /* Return error code. */
  7151. return ret;
  7152. }
  7153. #endif /* HAVE_PKCS8 */
  7154. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7155. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  7156. int* algoID, void* heap)
  7157. {
  7158. word32 tmpIdx = 0;
  7159. if (key == NULL || algoID == NULL)
  7160. return BAD_FUNC_ARG;
  7161. *algoID = 0;
  7162. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  7163. {
  7164. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7165. if (rsa == NULL)
  7166. return MEMORY_E;
  7167. wc_InitRsaKey(rsa, heap);
  7168. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  7169. *algoID = RSAk;
  7170. }
  7171. else {
  7172. WOLFSSL_MSG("Not RSA DER key");
  7173. }
  7174. wc_FreeRsaKey(rsa);
  7175. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7176. }
  7177. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  7178. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  7179. if (*algoID == 0) {
  7180. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7181. if (ecc == NULL)
  7182. return MEMORY_E;
  7183. tmpIdx = 0;
  7184. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  7185. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  7186. *algoID = ECDSAk;
  7187. /* now find oid */
  7188. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  7189. WOLFSSL_MSG("Error getting ECC curve OID");
  7190. wc_ecc_free(ecc);
  7191. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7192. return BAD_FUNC_ARG;
  7193. }
  7194. }
  7195. else {
  7196. WOLFSSL_MSG("Not ECC DER key either");
  7197. }
  7198. wc_ecc_free(ecc);
  7199. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7200. }
  7201. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  7202. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7203. if (*algoID == 0) {
  7204. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  7205. DYNAMIC_TYPE_TMP_BUFFER);
  7206. if (ed25519 == NULL)
  7207. return MEMORY_E;
  7208. tmpIdx = 0;
  7209. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  7210. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  7211. *algoID = ED25519k;
  7212. }
  7213. else {
  7214. WOLFSSL_MSG("Not ED25519 DER key");
  7215. }
  7216. wc_ed25519_free(ed25519);
  7217. }
  7218. else {
  7219. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  7220. }
  7221. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7222. }
  7223. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  7224. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  7225. if (*algoID == 0) {
  7226. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  7227. DYNAMIC_TYPE_TMP_BUFFER);
  7228. if (ed448 == NULL)
  7229. return MEMORY_E;
  7230. tmpIdx = 0;
  7231. if (wc_ed448_init(ed448) == 0) {
  7232. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  7233. *algoID = ED448k;
  7234. }
  7235. else {
  7236. WOLFSSL_MSG("Not ED448 DER key");
  7237. }
  7238. wc_ed448_free(ed448);
  7239. }
  7240. else {
  7241. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  7242. }
  7243. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7244. }
  7245. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  7246. #if defined(HAVE_PQC)
  7247. #if defined(HAVE_FALCON)
  7248. if (*algoID == 0) {
  7249. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  7250. DYNAMIC_TYPE_TMP_BUFFER);
  7251. if (falcon == NULL)
  7252. return MEMORY_E;
  7253. if (wc_falcon_init(falcon) != 0) {
  7254. tmpIdx = 0;
  7255. if (wc_falcon_set_level(falcon, 1) == 0) {
  7256. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7257. == 0) {
  7258. *algoID = FALCON_LEVEL1k;
  7259. }
  7260. else {
  7261. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  7262. }
  7263. }
  7264. else if (wc_falcon_set_level(falcon, 5) == 0) {
  7265. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  7266. == 0) {
  7267. *algoID = FALCON_LEVEL5k;
  7268. }
  7269. else {
  7270. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  7271. }
  7272. }
  7273. else {
  7274. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  7275. }
  7276. wc_falcon_free(falcon);
  7277. }
  7278. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7279. }
  7280. #endif /* HAVE_FALCON */
  7281. #if defined(HAVE_DILITHIUM)
  7282. if (*algoID == 0) {
  7283. dilithium_key *dilithium = (dilithium_key *)XMALLOC(sizeof(*dilithium),
  7284. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7285. if (dilithium == NULL)
  7286. return MEMORY_E;
  7287. if (wc_dilithium_init(dilithium) != 0) {
  7288. tmpIdx = 0;
  7289. if (wc_dilithium_set_level(dilithium, 2)
  7290. == 0) {
  7291. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7292. keySz) == 0) {
  7293. *algoID = DILITHIUM_LEVEL2k;
  7294. }
  7295. else {
  7296. WOLFSSL_MSG("Not Dilithium Level 2 DER key");
  7297. }
  7298. }
  7299. else if (wc_dilithium_set_level(dilithium, 3)
  7300. == 0) {
  7301. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7302. keySz) == 0) {
  7303. *algoID = DILITHIUM_LEVEL3k;
  7304. }
  7305. else {
  7306. WOLFSSL_MSG("Not Dilithium Level 3 DER key");
  7307. }
  7308. }
  7309. else if (wc_dilithium_set_level(dilithium, 5)
  7310. == 0) {
  7311. if (wc_Dilithium_PrivateKeyDecode(key, &tmpIdx, dilithium,
  7312. keySz) == 0) {
  7313. *algoID = DILITHIUM_LEVEL5k;
  7314. }
  7315. else {
  7316. WOLFSSL_MSG("Not Dilithium Level 5 DER key");
  7317. }
  7318. }
  7319. else {
  7320. WOLFSSL_MSG("GetKeyOID dilithium initialization failed");
  7321. }
  7322. wc_dilithium_free(dilithium);
  7323. }
  7324. XFREE(dilithium, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7325. }
  7326. #endif /* HAVE_DILITHIUM */
  7327. #if defined(HAVE_SPHINCS)
  7328. if (*algoID == 0) {
  7329. sphincs_key *sphincs = (sphincs_key *)XMALLOC(sizeof(*sphincs),
  7330. heap, DYNAMIC_TYPE_TMP_BUFFER);
  7331. if (sphincs == NULL)
  7332. return MEMORY_E;
  7333. if (wc_sphincs_init(sphincs) != 0) {
  7334. tmpIdx = 0;
  7335. if (wc_sphincs_set_level_and_optim(sphincs, 1, FAST_VARIANT)
  7336. == 0) {
  7337. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7338. keySz) == 0) {
  7339. *algoID = SPHINCS_FAST_LEVEL1k;
  7340. }
  7341. else {
  7342. WOLFSSL_MSG("Not Sphincs-fast Level 1 DER key");
  7343. }
  7344. }
  7345. else if (wc_sphincs_set_level_and_optim(sphincs, 3, FAST_VARIANT)
  7346. == 0) {
  7347. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7348. keySz) == 0) {
  7349. *algoID = SPHINCS_FAST_LEVEL3k;
  7350. }
  7351. else {
  7352. WOLFSSL_MSG("Not Sphincs-fast Level 3 DER key");
  7353. }
  7354. }
  7355. else if (wc_sphincs_set_level_and_optim(sphincs, 5, FAST_VARIANT)
  7356. == 0) {
  7357. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7358. keySz) == 0) {
  7359. *algoID = SPHINCS_FAST_LEVEL5k;
  7360. }
  7361. else {
  7362. WOLFSSL_MSG("Not Sphincs-fast Level 5 DER key");
  7363. }
  7364. }
  7365. else if (wc_sphincs_set_level_and_optim(sphincs, 1, SMALL_VARIANT)
  7366. == 0) {
  7367. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7368. keySz) == 0) {
  7369. *algoID = SPHINCS_SMALL_LEVEL1k;
  7370. }
  7371. else {
  7372. WOLFSSL_MSG("Not Sphincs-small Level 1 DER key");
  7373. }
  7374. }
  7375. else if (wc_sphincs_set_level_and_optim(sphincs, 3, SMALL_VARIANT)
  7376. == 0) {
  7377. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7378. keySz) == 0) {
  7379. *algoID = SPHINCS_SMALL_LEVEL3k;
  7380. }
  7381. else {
  7382. WOLFSSL_MSG("Not Sphincs-small Level 3 DER key");
  7383. }
  7384. }
  7385. else if (wc_sphincs_set_level_and_optim(sphincs, 5, SMALL_VARIANT)
  7386. == 0) {
  7387. if (wc_Sphincs_PrivateKeyDecode(key, &tmpIdx, sphincs,
  7388. keySz) == 0) {
  7389. *algoID = SPHINCS_SMALL_LEVEL5k;
  7390. }
  7391. else {
  7392. WOLFSSL_MSG("Not Sphincs-small Level 5 DER key");
  7393. }
  7394. }
  7395. else {
  7396. WOLFSSL_MSG("GetKeyOID sphincs initialization failed");
  7397. }
  7398. wc_sphincs_free(sphincs);
  7399. }
  7400. XFREE(sphincs, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7401. }
  7402. #endif /* HAVE_SPHINCS */
  7403. #endif /* HAVE_PQC */
  7404. /* if flag is not set then this is not a key that we understand. */
  7405. if (*algoID == 0) {
  7406. WOLFSSL_MSG("Bad key DER or compile options");
  7407. return BAD_FUNC_ARG;
  7408. }
  7409. (void)tmpIdx;
  7410. (void)curveOID;
  7411. (void)oidSz;
  7412. (void)keySz;
  7413. (void)heap;
  7414. return 1;
  7415. }
  7416. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7417. #ifdef WOLFSSL_ASN_TEMPLATE
  7418. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  7419. /* ASN.1 template for PBES2 parameters.
  7420. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  7421. * A.2 - PBKDF2-params
  7422. * B.2 - Encryption schemes
  7423. * C - AlgorithmIdentifier
  7424. */
  7425. static const ASNItem pbes2ParamsASN[] = {
  7426. /* KDF_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7427. /* PBKDF2 */
  7428. /* KDF_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7429. /* PBKDF2_PARAMS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7430. /* Salt */
  7431. /* PBKDF2_PARAMS_SALT */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  7432. /* Iteration count */
  7433. /* PBKDF2_PARAMS_ITER */ { 2, ASN_INTEGER, 0, 0, 0 },
  7434. /* Key length */
  7435. /* PBKDF2_PARAMS_KEYLEN */ { 2, ASN_INTEGER, 0, 0, 1 },
  7436. /* PRF - default is HMAC-SHA1 */
  7437. /* PBKDF2_PARAMS_PRF */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  7438. /* PBKDF2_PARAMS_PRF_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  7439. /* PBKDF2_PARAMS_PRF_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  7440. /* ENCS_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7441. /* Encryption algorithm */
  7442. /* ENCS_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  7443. /* IV for CBC */
  7444. /* ENCS_PARAMS */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  7445. };
  7446. enum {
  7447. PBES2PARAMSASN_IDX_KDF_SEQ = 0,
  7448. PBES2PARAMSASN_IDX_KDF_OID,
  7449. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SEQ,
  7450. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT,
  7451. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER,
  7452. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_KEYLEN,
  7453. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF,
  7454. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID,
  7455. PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_NULL,
  7456. PBES2PARAMSASN_IDX_ENCS_SEQ,
  7457. PBES2PARAMSASN_IDX_ENCS_OID,
  7458. PBES2PARAMSASN_IDX_ENCS_PARAMS
  7459. };
  7460. /* Number of items in ASN.1 template for PBES2 parameters. */
  7461. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  7462. /* ASN.1 template for PBES1 parameters.
  7463. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  7464. */
  7465. static const ASNItem pbes1ParamsASN[] = {
  7466. /* Salt */
  7467. /* SALT */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  7468. /* Iteration count */
  7469. /* ITER */ { 0, ASN_INTEGER, 0, 0, 0 },
  7470. };
  7471. enum {
  7472. PBES1PARAMSASN_IDX_SALT = 0,
  7473. PBES1PARAMSASN_IDX_ITER
  7474. };
  7475. /* Number of items in ASN.1 template for PBES1 parameters. */
  7476. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  7477. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  7478. #endif /* WOLFSSL_ASN_TEMPLATE */
  7479. #ifdef HAVE_PKCS8
  7480. /*
  7481. * Equivalent to calling TraditionalEnc with the same parameters but with
  7482. * encAlgId set to 0. This function must be kept alive because it's sometimes
  7483. * part of the API (WOLFSSL_ASN_API).
  7484. */
  7485. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7486. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7487. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  7488. {
  7489. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  7490. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  7491. }
  7492. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  7493. int *blkSz)
  7494. {
  7495. int ret = 0;
  7496. switch (encAlgId) {
  7497. #if !defined(NO_DES3) && !defined(NO_SHA)
  7498. case DESb:
  7499. *len = sizeof(blkDesCbcOid);
  7500. *oid = blkDesCbcOid;
  7501. *id = PBE_SHA1_DES;
  7502. *blkSz = 8;
  7503. break;
  7504. case DES3b:
  7505. *len = sizeof(blkDes3CbcOid);
  7506. *oid = blkDes3CbcOid;
  7507. *id = PBE_SHA1_DES3;
  7508. *blkSz = 8;
  7509. break;
  7510. #endif
  7511. #if defined(WOLFSSL_AES_128) && defined(HAVE_AES_CBC)
  7512. case AES128CBCb:
  7513. *len = sizeof(blkAes128CbcOid);
  7514. *oid = blkAes128CbcOid;
  7515. *id = PBE_AES128_CBC;
  7516. *blkSz = 16;
  7517. break;
  7518. #endif
  7519. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  7520. case AES256CBCb:
  7521. *len = sizeof(blkAes256CbcOid);
  7522. *oid = blkAes256CbcOid;
  7523. *id = PBE_AES256_CBC;
  7524. *blkSz = 16;
  7525. break;
  7526. #endif
  7527. default:
  7528. (void)len;
  7529. (void)oid;
  7530. (void)id;
  7531. (void)blkSz;
  7532. ret = ALGO_ID_E;
  7533. }
  7534. return ret;
  7535. }
  7536. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  7537. const char* password, int passwordSz, int vPKCS, int pbeOid,
  7538. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7539. void* heap)
  7540. {
  7541. #ifdef WOLFSSL_SMALL_STACK
  7542. byte* saltTmp = NULL;
  7543. #else
  7544. byte saltTmp[MAX_SALT_SIZE];
  7545. #endif
  7546. int genSalt = 0;
  7547. int ret = 0;
  7548. int version = 0;
  7549. int pbeId = 0;
  7550. int blockSz = 0;
  7551. const byte* encOid = NULL;
  7552. int encOidSz = 0;
  7553. word32 padSz = 0;
  7554. word32 innerLen = 0;
  7555. const byte* pbeOidBuf = NULL;
  7556. word32 pbeOidBufSz = 0;
  7557. word32 pbeLen = 0;
  7558. word32 kdfLen = 0;
  7559. word32 encLen = 0;
  7560. byte cbcIv[MAX_IV_SIZE];
  7561. word32 idx = 0;
  7562. word32 encIdx = 0;
  7563. (void)heap;
  7564. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  7565. if (key == NULL || outSz == NULL || password == NULL) {
  7566. ret = BAD_FUNC_ARG;
  7567. }
  7568. if (ret == 0) {
  7569. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  7570. }
  7571. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  7572. genSalt = 1;
  7573. saltSz = 8;
  7574. }
  7575. if (ret == 0 && version == PKCS5v2) {
  7576. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  7577. }
  7578. if (ret == 0) {
  7579. padSz = (word32)((blockSz - ((int)keySz & (blockSz - 1))) &
  7580. (blockSz - 1));
  7581. /* inner = OCT salt INT itt */
  7582. innerLen = 2 + saltSz + 2 + ((itt < 256) ? 1 : ((itt < 65536) ? 2 : 3));
  7583. if (version != PKCS5v2) {
  7584. pbeOidBuf = OidFromId((word32)pbeId, oidPBEType, &pbeOidBufSz);
  7585. /* pbe = OBJ pbse1 SEQ [ inner ] */
  7586. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  7587. }
  7588. else {
  7589. pbeOidBuf = pbes2;
  7590. pbeOidBufSz = sizeof(pbes2);
  7591. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  7592. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  7593. /* enc = OBJ enc_alg OCT iv */
  7594. encLen = 2 + (word32)encOidSz + 2 + (word32)blockSz;
  7595. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  7596. pbeLen = (word32)(2 + sizeof(pbes2) + 2 + 2 + (size_t)kdfLen + 2 +
  7597. (size_t)encLen);
  7598. ret = wc_RNG_GenerateBlock(rng, cbcIv, (word32)blockSz);
  7599. }
  7600. }
  7601. if (ret == 0) {
  7602. /* outerLen = length of PBE encoding + octet string data */
  7603. /* Plus 2 for tag and length for pbe */
  7604. word32 outerLen = 2 + pbeLen;
  7605. /* Octet string tag, length */
  7606. outerLen += 1 + SetLength(keySz + padSz, NULL);
  7607. /* Octet string bytes */
  7608. outerLen += keySz + padSz;
  7609. if (out == NULL) {
  7610. /* Sequence tag, length */
  7611. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  7612. return LENGTH_ONLY_E;
  7613. }
  7614. SetOctetString(keySz + padSz, out);
  7615. idx += SetSequence(outerLen, out + idx);
  7616. encIdx = idx + outerLen - keySz - padSz;
  7617. /* Put Encrypted content in place. */
  7618. XMEMCPY(out + encIdx, key, keySz);
  7619. if (padSz > 0) {
  7620. XMEMSET(out + encIdx + keySz, (int)padSz, padSz);
  7621. keySz += padSz;
  7622. }
  7623. if (genSalt == 1) {
  7624. #ifdef WOLFSSL_SMALL_STACK
  7625. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7626. if (saltTmp == NULL) {
  7627. ret = MEMORY_E;
  7628. }
  7629. else
  7630. #endif
  7631. {
  7632. salt = saltTmp;
  7633. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  7634. WOLFSSL_MSG("Error generating random salt");
  7635. }
  7636. }
  7637. }
  7638. }
  7639. if (ret == 0) {
  7640. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, pbeId,
  7641. out + encIdx, (int)keySz, version, cbcIv, 1, 0);
  7642. }
  7643. if (ret == 0) {
  7644. if (version != PKCS5v2) {
  7645. /* PBE algorithm */
  7646. idx += SetSequence(pbeLen, out + idx);
  7647. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7648. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7649. idx += pbeOidBufSz;
  7650. }
  7651. else {
  7652. /* PBES2 algorithm identifier */
  7653. idx += SetSequence(pbeLen, out + idx);
  7654. idx += (word32)SetObjectId((int)pbeOidBufSz, out + idx);
  7655. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  7656. idx += pbeOidBufSz;
  7657. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  7658. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  7659. /* KDF Algorithm Identifier */
  7660. idx += SetSequence(kdfLen, out + idx);
  7661. idx += (word32)SetObjectId((int)sizeof(pbkdf2Oid), out + idx);
  7662. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  7663. idx += sizeof(pbkdf2Oid);
  7664. }
  7665. idx += SetSequence(innerLen, out + idx);
  7666. idx += SetOctetString(saltSz, out + idx);
  7667. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  7668. ret = SetShortInt(out, &idx, (word32)itt, *outSz);
  7669. if (ret > 0)
  7670. ret = 0;
  7671. }
  7672. if (ret == 0) {
  7673. if (version == PKCS5v2) {
  7674. /* Encryption Algorithm Identifier */
  7675. idx += SetSequence(encLen, out + idx);
  7676. idx += (word32)SetObjectId(encOidSz, out + idx);
  7677. XMEMCPY(out + idx, encOid, (size_t)encOidSz);
  7678. idx += (word32)encOidSz;
  7679. /* Encryption Algorithm Parameter: CBC IV */
  7680. idx += SetOctetString((word32)blockSz, out + idx);
  7681. XMEMCPY(out + idx, cbcIv, (size_t)blockSz);
  7682. idx += (word32)blockSz;
  7683. }
  7684. idx += SetOctetString(keySz, out + idx);
  7685. /* Default PRF - no need to write out OID */
  7686. idx += keySz;
  7687. ret = (int)idx;
  7688. }
  7689. #ifdef WOLFSSL_SMALL_STACK
  7690. if (saltTmp != NULL) {
  7691. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7692. }
  7693. #endif
  7694. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  7695. return ret;
  7696. }
  7697. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  7698. int passwordSz)
  7699. {
  7700. int ret;
  7701. int length;
  7702. word32 inOutIdx = 0;
  7703. if (input == NULL || password == NULL) {
  7704. return BAD_FUNC_ARG;
  7705. }
  7706. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7707. ret = ASN_PARSE_E;
  7708. }
  7709. else {
  7710. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  7711. passwordSz);
  7712. if (ret > 0) {
  7713. XMEMMOVE(input, input + inOutIdx, (size_t)ret);
  7714. }
  7715. }
  7716. if (ret > 0) {
  7717. /* DecryptContent will decrypt the data, but it will leave any padding
  7718. * bytes intact. This code calculates the length without the padding
  7719. * and we return that to the user. */
  7720. inOutIdx = 0;
  7721. if (GetSequence(input, &inOutIdx, &length, (word32)ret) < 0) {
  7722. ret = ASN_PARSE_E;
  7723. }
  7724. else {
  7725. ret = (int)inOutIdx + length;
  7726. }
  7727. }
  7728. return ret;
  7729. }
  7730. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  7731. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  7732. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  7733. * buffer size. */
  7734. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  7735. const char* password, int passwordSz, int vPKCS, int vAlgo,
  7736. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  7737. void* heap)
  7738. {
  7739. int ret = 0;
  7740. byte *pkcs8Key = NULL;
  7741. word32 pkcs8KeySz = 0;
  7742. int algId = 0;
  7743. const byte* curveOid = NULL;
  7744. word32 curveOidSz = 0;
  7745. if (ret == 0) {
  7746. /* check key type and get OID if ECC */
  7747. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  7748. if (ret == 1)
  7749. ret = 0;
  7750. }
  7751. if (ret == 0) {
  7752. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  7753. curveOidSz);
  7754. if (ret == LENGTH_ONLY_E)
  7755. ret = 0;
  7756. }
  7757. if (ret == 0) {
  7758. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7759. if (pkcs8Key == NULL)
  7760. ret = MEMORY_E;
  7761. }
  7762. if (ret == 0) {
  7763. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  7764. curveOid, curveOidSz);
  7765. if (ret >= 0) {
  7766. pkcs8KeySz = (word32)ret;
  7767. ret = 0;
  7768. }
  7769. }
  7770. #ifdef WOLFSSL_CHECK_MEM_ZERO
  7771. if (ret == 0) {
  7772. wc_MemZero_Add("TraditionalEnc pkcs8Key", pkcs8Key, pkcs8KeySz);
  7773. }
  7774. #endif
  7775. if (ret == 0) {
  7776. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  7777. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  7778. }
  7779. if (pkcs8Key != NULL) {
  7780. ForceZero(pkcs8Key, pkcs8KeySz);
  7781. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7782. }
  7783. (void)rng;
  7784. return ret;
  7785. }
  7786. /* Same as TraditionalEnc, but in the public API. */
  7787. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  7788. word32* outSz, const char* password, int passwordSz, int vPKCS,
  7789. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  7790. WC_RNG* rng, void* heap)
  7791. {
  7792. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  7793. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  7794. }
  7795. #ifdef WOLFSSL_ASN_TEMPLATE
  7796. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  7797. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7798. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7799. */
  7800. static const ASNItem pkcs8DecASN[] = {
  7801. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7802. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7803. /* ENCALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  7804. /* PKCS #7 */
  7805. /* ENCCONTENT */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ENC_CONTENT,
  7806. 0, 0, 2 },
  7807. /* PKCS #8 */
  7808. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  7809. };
  7810. enum {
  7811. PKCS8DECASN_IDX_ENCALGO_SEQ = 0,
  7812. PKCS8DECASN_IDX_ENCALGO_OID,
  7813. PKCS8DECASN_IDX_ENCALGO_PARAMS,
  7814. PKCS8DECASN_IDX_ENCCONTENT,
  7815. PKCS8DECASN_IDX_ENCDATA
  7816. };
  7817. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  7818. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  7819. #endif
  7820. /* Decrypt data using PBE algorithm.
  7821. *
  7822. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  7823. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  7824. *
  7825. * Note: input buffer is overwritten with decrypted data!
  7826. *
  7827. * Salt is in KDF parameters and IV is PBE parameters when needed.
  7828. *
  7829. * @param [in] input Data to decrypt and unwrap.
  7830. * @param [in] sz Size of encrypted data.
  7831. * @param [in] password Password to derive encryption key with.
  7832. * @param [in] passwordSz Size of password in bytes.
  7833. * @return Length of decrypted data on success.
  7834. * @return MEMORY_E when dynamic memory allocation fails.
  7835. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7836. * is invalid.
  7837. * @return BUFFER_E when data in buffer is too small.
  7838. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7839. * @return Other when decryption fails.
  7840. */
  7841. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  7842. {
  7843. #ifndef WOLFSSL_ASN_TEMPLATE
  7844. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  7845. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  7846. int iterations = 0, keySz = 0;
  7847. #ifdef WOLFSSL_SMALL_STACK
  7848. byte* salt = NULL;
  7849. byte* cbcIv = NULL;
  7850. #else
  7851. byte salt[MAX_SALT_SIZE];
  7852. byte cbcIv[MAX_IV_SIZE];
  7853. #endif
  7854. byte tag;
  7855. if (passwordSz < 0) {
  7856. WOLFSSL_MSG("Bad password size");
  7857. return BAD_FUNC_ARG;
  7858. }
  7859. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  7860. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7861. }
  7862. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  7863. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  7864. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  7865. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  7866. }
  7867. if (version == PKCS5v2) {
  7868. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  7869. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7870. }
  7871. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  7872. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7873. }
  7874. if (oid != PBKDF2_OID) {
  7875. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7876. }
  7877. }
  7878. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  7879. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7880. }
  7881. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  7882. * DEFAULT items. */
  7883. seqEnd = inOutIdx + (word32)length;
  7884. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  7885. if (ret < 0)
  7886. goto exit_dc;
  7887. if (saltSz > MAX_SALT_SIZE) {
  7888. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7889. }
  7890. #ifdef WOLFSSL_SMALL_STACK
  7891. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7892. if (salt == NULL) {
  7893. ERROR_OUT(MEMORY_E, exit_dc);
  7894. }
  7895. #endif
  7896. XMEMCPY(salt, &input[inOutIdx], (size_t)saltSz);
  7897. inOutIdx += (word32)saltSz;
  7898. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  7899. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7900. }
  7901. /* OPTIONAL key length */
  7902. if (seqEnd > inOutIdx) {
  7903. word32 localIdx = inOutIdx;
  7904. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  7905. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7906. }
  7907. if (tag == ASN_INTEGER &&
  7908. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  7909. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7910. }
  7911. }
  7912. /* DEFAULT HMAC is SHA-1 */
  7913. if (seqEnd > inOutIdx) {
  7914. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  7915. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7916. }
  7917. shaOid = oid;
  7918. }
  7919. #ifdef WOLFSSL_SMALL_STACK
  7920. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7921. if (cbcIv == NULL) {
  7922. ERROR_OUT(MEMORY_E, exit_dc);
  7923. }
  7924. #endif
  7925. if (version == PKCS5v2) {
  7926. /* get encryption algo */
  7927. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  7928. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7929. }
  7930. if (CheckAlgoV2((int)oid, &id, NULL) < 0) {
  7931. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  7932. }
  7933. if (shaOid == 0)
  7934. shaOid = oid;
  7935. ret = GetOctetString(input, &inOutIdx, &length, sz);
  7936. if (ret < 0)
  7937. goto exit_dc;
  7938. if (length > MAX_IV_SIZE) {
  7939. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7940. }
  7941. XMEMCPY(cbcIv, &input[inOutIdx], (size_t)length);
  7942. inOutIdx += (word32)length;
  7943. }
  7944. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  7945. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7946. }
  7947. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  7948. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7949. }
  7950. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  7951. ERROR_OUT(ASN_PARSE_E, exit_dc);
  7952. }
  7953. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  7954. input + inOutIdx, length, version, cbcIv, 0, (int)shaOid);
  7955. exit_dc:
  7956. #ifdef WOLFSSL_SMALL_STACK
  7957. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7958. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7959. #endif
  7960. if (ret == 0) {
  7961. XMEMMOVE(input, input + inOutIdx, (size_t)length);
  7962. ret = length;
  7963. }
  7964. return ret;
  7965. #else
  7966. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  7967. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  7968. int ret = 0;
  7969. int id = 0;
  7970. int version;
  7971. word32 idx = 0;
  7972. word32 pIdx = 0;
  7973. word32 iterations;
  7974. word32 keySz = 0;
  7975. word32 saltSz = 0;
  7976. word32 shaOid = 0;
  7977. byte* salt = NULL;
  7978. byte* key = NULL;
  7979. byte cbcIv[MAX_IV_SIZE];
  7980. byte* params = NULL;
  7981. WOLFSSL_ENTER("DecryptContent");
  7982. CALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  7983. if (ret == 0) {
  7984. /* Check OID is a PBE Type */
  7985. GetASN_OID(&dataASN[PKCS8DECASN_IDX_ENCALGO_OID], oidPBEType);
  7986. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  7987. &idx, sz);
  7988. }
  7989. if (ret == 0) {
  7990. /* Check the PBE algorithm and get the version and id. */
  7991. idx = dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.length;
  7992. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  7993. * Last byte: Alg or PBES2 */
  7994. ret = CheckAlgo(dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 2],
  7995. dataASN[PKCS8DECASN_IDX_ENCALGO_OID].data.oid.data[idx - 1],
  7996. &id, &version, NULL);
  7997. }
  7998. if (ret == 0) {
  7999. /* Get the parameters data. */
  8000. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCALGO_PARAMS], &params, &sz);
  8001. /* Having a numbered choice means none or both will have errored out. */
  8002. if (dataASN[PKCS8DECASN_IDX_ENCCONTENT].tag != 0)
  8003. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCCONTENT], &key, &keySz);
  8004. else if (dataASN[PKCS8DECASN_IDX_ENCDATA].tag != 0)
  8005. GetASN_GetRef(&dataASN[PKCS8DECASN_IDX_ENCDATA], &key, &keySz);
  8006. else
  8007. ret = ASN_RSA_KEY_E;
  8008. }
  8009. if (ret == 0) {
  8010. if (version != PKCS5v2) {
  8011. /* Initialize for PBES1 parameters and put iterations in var. */
  8012. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  8013. GetASN_Int32Bit(&dataASN[PBES1PARAMSASN_IDX_ITER], &iterations);
  8014. /* Parse the PBES1 parameters. */
  8015. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  8016. 0, params, &pIdx, sz);
  8017. if (ret == 0) {
  8018. /* Get the salt data. */
  8019. GetASN_GetRef(&dataASN[PBES1PARAMSASN_IDX_SALT], &salt, &saltSz);
  8020. }
  8021. }
  8022. else {
  8023. word32 ivSz = MAX_IV_SIZE;
  8024. /* Initialize for PBES2 parameters. Put iterations in var; match
  8025. * KDF, HMAC and cipher, and copy CBC into buffer. */
  8026. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  8027. GetASN_ExpBuffer(&dataASN[PBES2PARAMSASN_IDX_KDF_OID], pbkdf2Oid, sizeof(pbkdf2Oid));
  8028. GetASN_Int32Bit(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_ITER], &iterations);
  8029. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID], oidHmacType);
  8030. GetASN_OID(&dataASN[PBES2PARAMSASN_IDX_ENCS_OID], oidBlkType);
  8031. GetASN_Buffer(&dataASN[PBES2PARAMSASN_IDX_ENCS_PARAMS], cbcIv, &ivSz);
  8032. /* Parse the PBES2 parameters */
  8033. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  8034. 0, params, &pIdx, sz);
  8035. if (ret == 0) {
  8036. /* Get the salt data. */
  8037. GetASN_GetRef(&dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_SALT], &salt, &saltSz);
  8038. /* Get the digest and encryption algorithm id. */
  8039. shaOid = dataASN[PBES2PARAMSASN_IDX_PBKDF2_PARAMS_PRF_OID].data.oid.sum; /* Default HMAC-SHA1 */
  8040. id = (int)dataASN[PBES2PARAMSASN_IDX_ENCS_OID].data.oid.sum;
  8041. /* Convert encryption algorithm to a PBE algorithm if needed. */
  8042. CheckAlgoV2(id, &id, NULL);
  8043. }
  8044. }
  8045. }
  8046. if (ret == 0) {
  8047. /* Decrypt the key. */
  8048. ret = wc_CryptKey(
  8049. password, passwordSz, salt, (int)saltSz, (int)iterations, id, key,
  8050. (int)keySz, version, cbcIv, 0, (int)shaOid);
  8051. }
  8052. if (ret == 0) {
  8053. /* Copy the decrypted key into the input (inline). */
  8054. XMEMMOVE(input, key, keySz);
  8055. ret = (int)keySz;
  8056. }
  8057. FREE_ASNGETDATA(dataASN, NULL);
  8058. return ret;
  8059. #endif
  8060. }
  8061. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  8062. *
  8063. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8064. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  8065. *
  8066. * Note: input buffer is overwritten with decrypted key!
  8067. *
  8068. * Salt is in KDF parameters and IV is PBE parameters when needed.
  8069. *
  8070. * @param [in] input Data to decrypt and unwrap.
  8071. * @param [in] sz Size of encrypted data.
  8072. * @param [in] password Password to derive encryption key with.
  8073. * @param [in] passwordSz Size of password in bytes.
  8074. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  8075. * @return Length of decrypted data on success.
  8076. * @return MEMORY_E when dynamic memory allocation fails.
  8077. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8078. * is invalid.
  8079. * @return BUFFER_E when data in buffer is too small.
  8080. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8081. * @return Other when decryption fails.
  8082. */
  8083. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  8084. int passwordSz, word32* algId)
  8085. {
  8086. int ret;
  8087. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  8088. if (ret > 0) {
  8089. ret = ToTraditional_ex(input, (word32)ret, algId);
  8090. }
  8091. return ret;
  8092. }
  8093. #endif /* HAVE_PKCS8 */
  8094. #ifdef HAVE_PKCS12
  8095. #define PKCS8_MIN_BLOCK_SIZE 8
  8096. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  8097. {
  8098. int padSz;
  8099. /* calculate pad size */
  8100. padSz = blockSz - (sz & (blockSz - 1));
  8101. /* pad with padSz value */
  8102. if (buf) {
  8103. int i;
  8104. for (i = 0; i < padSz; i++) {
  8105. buf[sz+i] = (byte)(padSz & 0xFF);
  8106. }
  8107. }
  8108. /* return adjusted length */
  8109. return sz + padSz;
  8110. }
  8111. #ifdef WOLFSSL_ASN_TEMPLATE
  8112. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  8113. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  8114. * PKCS #5: RFC 8018, A.3 - PBEParameter
  8115. */
  8116. static const ASNItem p8EncPbes1ASN[] = {
  8117. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8118. /* ENCALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8119. /* PBE algorithm */
  8120. /* ENCALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8121. /* ENCALGO_PBEPARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8122. /* Salt */
  8123. /* ENCALGO_PBEPARAM_SALT */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  8124. /* Iteration Count */
  8125. /* ENCALGO_PBEPARAM_ITER */ { 3, ASN_INTEGER, 0, 0, 0 },
  8126. /* ENCDATA */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  8127. };
  8128. enum {
  8129. P8ENCPBES1ASN_IDX_SEQ = 0,
  8130. P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8131. P8ENCPBES1ASN_IDX_ENCALGO_OID,
  8132. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SEQ,
  8133. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT,
  8134. P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER,
  8135. P8ENCPBES1ASN_IDX_ENCDATA
  8136. };
  8137. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  8138. #endif
  8139. /* Wrap a private key in PKCS#8 and encrypt.
  8140. *
  8141. * Used for PKCS#12 and PKCS#7.
  8142. * vPKCS is the version of PKCS to use.
  8143. * vAlgo is the algorithm version to use.
  8144. *
  8145. * When salt is NULL, a random number is generated.
  8146. *
  8147. * data returned is :
  8148. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  8149. *
  8150. * @param [in] input Data to encrypt.
  8151. * @param [in] inputSz Length of data in bytes.
  8152. * @param [out] out Buffer to write wrapped encrypted data into.
  8153. * @param [out] outSz Length of encrypted data in bytes.
  8154. * @param [in] password Password used to create encryption key.
  8155. * @param [in] passwordSz Length of password in bytes.
  8156. * @param [in] vPKCS First byte used to determine PBE algorithm.
  8157. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  8158. * @param [in] salt Salt to use with KDF.
  8159. * @param [in] saltSz Length of salt in bytes.
  8160. * @param [in] itt Number of iterations to use in KDF.
  8161. * @param [in] rng Random number generator to use to generate salt.
  8162. * @param [in] heap Dynamic memory allocator hint.
  8163. * @return The size of encrypted data on success
  8164. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  8165. * @return ASN_PARSE_E when the salt size is too large.
  8166. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  8167. * TraditionalEnc).
  8168. * @return MEMORY_E when dynamic memory allocation fails.
  8169. * @return Other when encryption or random number generation fails.
  8170. */
  8171. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  8172. const char* password, int passwordSz, int vPKCS, int vAlgo,
  8173. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  8174. {
  8175. #ifndef WOLFSSL_ASN_TEMPLATE
  8176. word32 sz;
  8177. word32 inOutIdx = 0;
  8178. word32 tmpIdx = 0;
  8179. word32 totalSz = 0;
  8180. word32 seqSz;
  8181. word32 innerSz;
  8182. int ret;
  8183. int version, id, blockSz = 0;
  8184. #ifdef WOLFSSL_SMALL_STACK
  8185. byte* saltTmp = NULL;
  8186. byte* cbcIv = NULL;
  8187. #else
  8188. byte saltTmp[MAX_SALT_SIZE];
  8189. byte cbcIv[MAX_IV_SIZE];
  8190. #endif
  8191. byte seq[MAX_SEQ_SZ];
  8192. byte shr[MAX_SHORT_SZ];
  8193. word32 maxShr = MAX_SHORT_SZ;
  8194. word32 algoSz;
  8195. const byte* algoName;
  8196. (void)heap;
  8197. WOLFSSL_ENTER("EncryptContent");
  8198. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  8199. return ASN_INPUT_E; /* Algo ID error */
  8200. if (version == PKCS5v2) {
  8201. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  8202. return BAD_FUNC_ARG;
  8203. }
  8204. if (saltSz > MAX_SALT_SIZE)
  8205. return ASN_PARSE_E;
  8206. if (outSz == NULL) {
  8207. return BAD_FUNC_ARG;
  8208. }
  8209. /* calculate size */
  8210. /* size of constructed string at end */
  8211. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8212. totalSz = ASN_TAG_SZ;
  8213. totalSz += SetLength(sz, seq);
  8214. totalSz += sz;
  8215. /* size of sequence holding object id and sub sequence of salt and itt */
  8216. algoName = OidFromId((word32)id, oidPBEType, &algoSz);
  8217. if (algoName == NULL) {
  8218. WOLFSSL_MSG("Unknown Algorithm");
  8219. return 0;
  8220. }
  8221. innerSz = (word32)SetObjectId((int)algoSz, seq);
  8222. innerSz += algoSz;
  8223. /* get subsequence of salt and itt */
  8224. if (salt == NULL || saltSz == 0) {
  8225. sz = 8;
  8226. }
  8227. else {
  8228. sz = saltSz;
  8229. }
  8230. seqSz = SetOctetString(sz, seq);
  8231. seqSz += sz;
  8232. tmpIdx = 0;
  8233. ret = SetShortInt(shr, &tmpIdx, (word32)itt, maxShr);
  8234. if (ret >= 0) {
  8235. seqSz += (word32)ret;
  8236. }
  8237. else {
  8238. return ret;
  8239. }
  8240. innerSz += seqSz + SetSequence(seqSz, seq);
  8241. totalSz += innerSz + SetSequence(innerSz, seq);
  8242. if (out == NULL) {
  8243. *outSz = totalSz;
  8244. return LENGTH_ONLY_E;
  8245. }
  8246. inOutIdx = 0;
  8247. if (totalSz > *outSz)
  8248. return BUFFER_E;
  8249. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  8250. inOutIdx += (word32)SetObjectId((int)algoSz, out + inOutIdx);
  8251. XMEMCPY(out + inOutIdx, algoName, algoSz);
  8252. inOutIdx += algoSz;
  8253. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  8254. /* create random salt if one not provided */
  8255. if (salt == NULL || saltSz == 0) {
  8256. saltSz = 8;
  8257. #ifdef WOLFSSL_SMALL_STACK
  8258. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8259. if (saltTmp == NULL)
  8260. return MEMORY_E;
  8261. #endif
  8262. salt = saltTmp;
  8263. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  8264. WOLFSSL_MSG("Error generating random salt");
  8265. #ifdef WOLFSSL_SMALL_STACK
  8266. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8267. #endif
  8268. return ret;
  8269. }
  8270. }
  8271. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  8272. if (saltSz + inOutIdx > *outSz) {
  8273. #ifdef WOLFSSL_SMALL_STACK
  8274. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8275. #endif
  8276. return BUFFER_E;
  8277. }
  8278. XMEMCPY(out + inOutIdx, salt, saltSz);
  8279. inOutIdx += saltSz;
  8280. /* place iteration setting in buffer */
  8281. ret = SetShortInt(out, &inOutIdx, (word32)itt, *outSz);
  8282. if (ret < 0) {
  8283. #ifdef WOLFSSL_SMALL_STACK
  8284. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8285. #endif
  8286. return ret;
  8287. }
  8288. if (inOutIdx + 1 > *outSz) {
  8289. #ifdef WOLFSSL_SMALL_STACK
  8290. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8291. #endif
  8292. return BUFFER_E;
  8293. }
  8294. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  8295. /* get pad size and verify buffer room */
  8296. sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8297. if (sz + inOutIdx > *outSz) {
  8298. #ifdef WOLFSSL_SMALL_STACK
  8299. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8300. #endif
  8301. return BUFFER_E;
  8302. }
  8303. inOutIdx += SetLength(sz, out + inOutIdx);
  8304. /* copy input to output buffer and pad end */
  8305. XMEMCPY(out + inOutIdx, input, inputSz);
  8306. sz = (word32)Pkcs8Pad(out + inOutIdx, (int)inputSz, blockSz);
  8307. #ifdef WOLFSSL_SMALL_STACK
  8308. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8309. if (cbcIv == NULL) {
  8310. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8311. return MEMORY_E;
  8312. }
  8313. #endif
  8314. /* encrypt */
  8315. if ((ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8316. out + inOutIdx, (int)sz, version, cbcIv, 1, 0)) < 0) {
  8317. #ifdef WOLFSSL_SMALL_STACK
  8318. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8319. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8320. #endif
  8321. return ret; /* encrypt failure */
  8322. }
  8323. #ifdef WOLFSSL_SMALL_STACK
  8324. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8325. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  8326. #endif
  8327. (void)rng;
  8328. return (int)(inOutIdx + sz);
  8329. #else
  8330. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  8331. int ret = 0;
  8332. int sz = 0;
  8333. int version = 0;
  8334. int id = -1;
  8335. int blockSz = 0;
  8336. word32 pkcs8Sz = 0;
  8337. (void)heap;
  8338. WOLFSSL_ENTER("EncryptContent");
  8339. /* Must have a output size to return or check. */
  8340. if (outSz == NULL) {
  8341. ret = BAD_FUNC_ARG;
  8342. }
  8343. /* Check salt size is valid. */
  8344. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  8345. ret = ASN_PARSE_E;
  8346. }
  8347. /* Get algorithm parameters for algorithm identifier. */
  8348. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  8349. ret = ASN_INPUT_E;
  8350. }
  8351. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  8352. if ((ret == 0) && (version == PKCS5v2)) {
  8353. ret = BAD_FUNC_ARG;
  8354. }
  8355. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  8356. if (ret == 0) {
  8357. /* Setup data to go into encoding including PBE algorithm, salt,
  8358. * iteration count, and padded key length. */
  8359. SetASN_OID(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_OID], (word32)id,
  8360. oidPBEType);
  8361. if (salt == NULL || saltSz == 0) {
  8362. salt = NULL;
  8363. saltSz = PKCS5_SALT_SZ;
  8364. /* Salt generated into encoding below. */
  8365. }
  8366. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT],
  8367. salt, saltSz);
  8368. SetASN_Int16Bit(&dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_ITER],
  8369. (word16)itt);
  8370. pkcs8Sz = (word32)Pkcs8Pad(NULL, (int)inputSz, blockSz);
  8371. SetASN_Buffer(&dataASN[P8ENCPBES1ASN_IDX_ENCDATA], NULL, pkcs8Sz);
  8372. /* Calculate size of encoding. */
  8373. ret = SizeASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8374. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8375. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8376. &sz);
  8377. }
  8378. /* Return size when no output buffer. */
  8379. if ((ret == 0) && (out == NULL)) {
  8380. *outSz = (word32)sz;
  8381. ret = LENGTH_ONLY_E;
  8382. }
  8383. /* Check output buffer is big enough for encoded data. */
  8384. if ((ret == 0) && (sz > (int)*outSz)) {
  8385. ret = BAD_FUNC_ARG;
  8386. }
  8387. if (ret == 0) {
  8388. /* Encode PKCS#8 key. */
  8389. SetASN_Items(p8EncPbes1ASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8390. dataASN + P8ENCPBES1ASN_IDX_ENCALGO_SEQ,
  8391. (int)(p8EncPbes1ASN_Length - P8ENCPBES1ASN_IDX_ENCALGO_SEQ),
  8392. out);
  8393. if (salt == NULL) {
  8394. /* Generate salt into encoding. */
  8395. salt = (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCALGO_PBEPARAM_SALT].
  8396. data.buffer.data;
  8397. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  8398. }
  8399. }
  8400. if (ret == 0) {
  8401. byte cbcIv[MAX_IV_SIZE];
  8402. /* Store PKCS#8 key in output buffer. */
  8403. byte* pkcs8 =
  8404. (byte*)dataASN[P8ENCPBES1ASN_IDX_ENCDATA].data.buffer.data;
  8405. XMEMCPY(pkcs8, input, inputSz);
  8406. Pkcs8Pad(pkcs8, (int)inputSz, blockSz);
  8407. /* Encrypt PKCS#8 key inline. */
  8408. ret = wc_CryptKey(password, passwordSz, salt, (int)saltSz, itt, id,
  8409. pkcs8, (int)pkcs8Sz, version, cbcIv, 1, 0);
  8410. }
  8411. if (ret == 0) {
  8412. /* Returning size on success. */
  8413. ret = sz;
  8414. }
  8415. FREE_ASNSETDATA(dataASN, heap);
  8416. return ret;
  8417. #endif /* WOLFSSL_ASN_TEMPLATE */
  8418. }
  8419. #endif /* HAVE_PKCS12 */
  8420. #endif /* NO_PWDBASED */
  8421. #ifndef NO_RSA
  8422. #ifndef HAVE_USER_RSA
  8423. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  8424. /* This function is to retrieve key position information in a cert.*
  8425. * The information will be used to call TSIP TLS-linked API for *
  8426. * certificate verification. */
  8427. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  8428. word32 inSz, word32* key_n,
  8429. word32* key_n_len, word32* key_e,
  8430. word32* key_e_len)
  8431. {
  8432. int ret = 0;
  8433. int length = 0;
  8434. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8435. byte b;
  8436. #endif
  8437. if (input == NULL || inOutIdx == NULL)
  8438. return BAD_FUNC_ARG;
  8439. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8440. return ASN_PARSE_E;
  8441. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8442. if ((*inOutIdx + 1) > inSz)
  8443. return BUFFER_E;
  8444. b = input[*inOutIdx];
  8445. if (b != ASN_INTEGER) {
  8446. /* not from decoded cert, will have algo id, skip past */
  8447. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8448. return ASN_PARSE_E;
  8449. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8450. return ASN_PARSE_E;
  8451. /* Option NULL ASN.1 tag */
  8452. if (*inOutIdx >= inSz) {
  8453. return BUFFER_E;
  8454. }
  8455. if (input[*inOutIdx] == ASN_TAG_NULL) {
  8456. ret = GetASNNull(input, inOutIdx, inSz);
  8457. if (ret != 0)
  8458. return ret;
  8459. }
  8460. /* TODO: support RSA PSS */
  8461. /* should have bit tag length and seq next */
  8462. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8463. if (ret != 0)
  8464. return ret;
  8465. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8466. return ASN_PARSE_E;
  8467. }
  8468. #endif /* OPENSSL_EXTRA */
  8469. /* Get modulus */
  8470. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8471. *key_n += *inOutIdx;
  8472. if (ret < 0) {
  8473. return ASN_RSA_KEY_E;
  8474. }
  8475. if (key_n_len)
  8476. *key_n_len = length;
  8477. *inOutIdx += length;
  8478. /* Get exponent */
  8479. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8480. *key_e += *inOutIdx;
  8481. if (ret < 0) {
  8482. return ASN_RSA_KEY_E;
  8483. }
  8484. if (key_e_len)
  8485. *key_e_len = length;
  8486. return ret;
  8487. }
  8488. #endif /* WOLFSSL_RENESAS_TSIP */
  8489. #ifdef WOLFSSL_ASN_TEMPLATE
  8490. /* ASN.1 template for an RSA public key.
  8491. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8492. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8493. */
  8494. static const ASNItem rsaPublicKeyASN[] = {
  8495. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8496. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8497. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8498. /* ALGOID_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  8499. #ifdef WC_RSA_PSS
  8500. /* ALGOID_P_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  8501. #endif
  8502. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  8503. /* RSAPublicKey */
  8504. /* PUBKEY_RSA_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8505. /* PUBKEY_RSA_N */ { 3, ASN_INTEGER, 0, 0, 0 },
  8506. /* PUBKEY_RSA_E */ { 3, ASN_INTEGER, 0, 0, 0 },
  8507. };
  8508. enum {
  8509. RSAPUBLICKEYASN_IDX_SEQ = 0,
  8510. RSAPUBLICKEYASN_IDX_ALGOID_SEQ,
  8511. RSAPUBLICKEYASN_IDX_ALGOID_OID,
  8512. RSAPUBLICKEYASN_IDX_ALGOID_NULL,
  8513. #ifdef WC_RSA_PSS
  8514. RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ,
  8515. #endif
  8516. RSAPUBLICKEYASN_IDX_PUBKEY,
  8517. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ,
  8518. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N,
  8519. RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E
  8520. };
  8521. /* Number of items in ASN.1 template for an RSA public key. */
  8522. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  8523. #endif
  8524. /* Decode RSA public key.
  8525. *
  8526. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8527. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8528. *
  8529. * @param [in] input Buffer holding BER encoded data.
  8530. * @param [in, out] inOutIdx On in, start of RSA public key.
  8531. * On out, start of ASN.1 item after RSA public key.
  8532. * @param [in] inSz Number of bytes in buffer.
  8533. * @param [out] n Pointer to modulus in buffer.
  8534. * @param [out] nSz Size of modulus in bytes.
  8535. * @param [out] e Pointer to exponent in buffer.
  8536. * @param [out] eSz Size of exponent in bytes.
  8537. * @return 0 on success.
  8538. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8539. * is invalid.
  8540. * @return BUFFER_E when data in buffer is too small.
  8541. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8542. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8543. * non-zero length.
  8544. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8545. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8546. */
  8547. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  8548. const byte** n, word32* nSz, const byte** e, word32* eSz)
  8549. {
  8550. #ifndef WOLFSSL_ASN_TEMPLATE
  8551. int ret = 0;
  8552. int length = 0;
  8553. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8554. word32 localIdx;
  8555. byte tag;
  8556. #endif
  8557. if (input == NULL || inOutIdx == NULL)
  8558. return BAD_FUNC_ARG;
  8559. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8560. return ASN_PARSE_E;
  8561. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  8562. localIdx = *inOutIdx;
  8563. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8564. return BUFFER_E;
  8565. if (tag != ASN_INTEGER) {
  8566. /* not from decoded cert, will have algo id, skip past */
  8567. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8568. return ASN_PARSE_E;
  8569. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  8570. return ASN_PARSE_E;
  8571. /* Option NULL ASN.1 tag */
  8572. if (*inOutIdx >= inSz) {
  8573. return BUFFER_E;
  8574. }
  8575. localIdx = *inOutIdx;
  8576. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  8577. return ASN_PARSE_E;
  8578. if (tag == ASN_TAG_NULL) {
  8579. ret = GetASNNull(input, inOutIdx, inSz);
  8580. if (ret != 0)
  8581. return ret;
  8582. }
  8583. #ifdef WC_RSA_PSS
  8584. /* Skip RSA PSS parameters. */
  8585. else if (tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8586. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8587. return ASN_PARSE_E;
  8588. *inOutIdx += length;
  8589. }
  8590. #endif
  8591. /* should have bit tag length and seq next */
  8592. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8593. if (ret != 0)
  8594. return ret;
  8595. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8596. return ASN_PARSE_E;
  8597. }
  8598. #endif /* OPENSSL_EXTRA */
  8599. /* Get modulus */
  8600. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8601. if (ret < 0) {
  8602. return ASN_RSA_KEY_E;
  8603. }
  8604. if (nSz)
  8605. *nSz = (word32)length;
  8606. if (n)
  8607. *n = &input[*inOutIdx];
  8608. *inOutIdx += (word32)length;
  8609. /* Get exponent */
  8610. ret = GetASNInt(input, inOutIdx, &length, inSz);
  8611. if (ret < 0) {
  8612. return ASN_RSA_KEY_E;
  8613. }
  8614. if (eSz)
  8615. *eSz = (word32)length;
  8616. if (e)
  8617. *e = &input[*inOutIdx];
  8618. *inOutIdx += (word32)length;
  8619. return ret;
  8620. #else
  8621. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  8622. int ret = 0;
  8623. #ifdef WC_RSA_PSS
  8624. word32 oid = RSAk;
  8625. #endif
  8626. /* Check validity of parameters. */
  8627. if (input == NULL || inOutIdx == NULL) {
  8628. ret = BAD_FUNC_ARG;
  8629. }
  8630. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  8631. if (ret == 0) {
  8632. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  8633. ret = GetASN_Items(&rsaPublicKeyASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8634. &dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ],
  8635. (int)(rsaPublicKeyASN_Length - RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ),
  8636. 0, input, inOutIdx, inSz);
  8637. if (ret != 0) {
  8638. /* Didn't work - try whole SubjectKeyInfo instead. */
  8639. #ifdef WC_RSA_PSS
  8640. /* Could be RSA or RSA PSS key. */
  8641. GetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  8642. #else
  8643. /* Set the OID to expect. */
  8644. GetASN_ExpBuffer(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID],
  8645. keyRsaOid, sizeof(keyRsaOid));
  8646. #endif
  8647. /* Decode SubjectKeyInfo. */
  8648. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  8649. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  8650. inSz);
  8651. }
  8652. }
  8653. #ifdef WC_RSA_PSS
  8654. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].tag != 0)) {
  8655. /* Two possible OIDs supported - RSA and RSA PSS. */
  8656. oid = dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  8657. if ((oid != RSAk) && (oid != RSAPSSk)) {
  8658. ret = ASN_PARSE_E;
  8659. }
  8660. }
  8661. if ((ret == 0) && (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].tag != 0)) {
  8662. /* Can't have NULL and SEQ. */
  8663. if (dataASN[RSAPUBLICKEYASN_IDX_ALGOID_NULL].tag != 0) {
  8664. ret = ASN_PARSE_E;
  8665. }
  8666. /* SEQ present only with RSA PSS. */
  8667. if ((ret == 0) && (oid != RSAPSSk)) {
  8668. ret = ASN_PARSE_E;
  8669. }
  8670. if (ret == 0) {
  8671. enum wc_HashType hash;
  8672. int mgf;
  8673. int saltLen;
  8674. const byte* params = GetASNItem_Addr(
  8675. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8676. word32 paramsSz = GetASNItem_Length(
  8677. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ], input);
  8678. /* Validate the private key parameters. */
  8679. ret = DecodeRsaPssParams(params, paramsSz, &hash, &mgf, &saltLen);
  8680. /* TODO: store parameters so that usage can be checked. */
  8681. }
  8682. }
  8683. #endif
  8684. if (ret == 0) {
  8685. /* Return the buffers and lengths asked for. */
  8686. if (n != NULL) {
  8687. *n = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.data;
  8688. }
  8689. if (nSz != NULL) {
  8690. *nSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N].data.ref.length;
  8691. }
  8692. if (e != NULL) {
  8693. *e = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.data;
  8694. }
  8695. if (eSz != NULL) {
  8696. *eSz = dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E].data.ref.length;
  8697. }
  8698. }
  8699. FREE_ASNGETDATA(dataASN, NULL);
  8700. return ret;
  8701. #endif /* WOLFSSL_ASN_TEMPLATE */
  8702. }
  8703. /* Decode RSA public key.
  8704. *
  8705. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8706. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  8707. *
  8708. * @param [in] input Buffer holding BER encoded data.
  8709. * @param [in, out] inOutIdx On in, start of RSA public key.
  8710. * On out, start of ASN.1 item after RSA public key.
  8711. * @param [in, out] key RSA key object.
  8712. * @param [in] inSz Number of bytes in buffer.
  8713. * @return 0 on success.
  8714. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8715. * is invalid.
  8716. * @return BUFFER_E when data in buffer is too small.
  8717. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8718. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8719. * non-zero length.
  8720. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8721. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8722. */
  8723. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  8724. word32 inSz)
  8725. {
  8726. int ret;
  8727. const byte *n = NULL, *e = NULL;
  8728. word32 nSz = 0, eSz = 0;
  8729. if (key == NULL)
  8730. return BAD_FUNC_ARG;
  8731. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  8732. if (ret == 0) {
  8733. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  8734. }
  8735. return ret;
  8736. }
  8737. #endif /* HAVE_USER_RSA */
  8738. #endif /* !NO_RSA */
  8739. #ifndef NO_DH
  8740. #if defined(WOLFSSL_DH_EXTRA)
  8741. /*
  8742. * Decodes DH public key to fill specified DhKey.
  8743. *
  8744. * return 0 on success, negative on failure
  8745. */
  8746. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  8747. DhKey* key, word32 inSz)
  8748. {
  8749. int ret = 0;
  8750. int length;
  8751. word32 oid = 0;
  8752. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8753. return BAD_FUNC_ARG;
  8754. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8755. return ASN_PARSE_E;
  8756. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8757. return ASN_PARSE_E;
  8758. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8759. if (oid != DHk || ret < 0)
  8760. return ASN_DH_KEY_E;
  8761. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8762. return ASN_PARSE_E;
  8763. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  8764. return ASN_DH_KEY_E;
  8765. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8766. mp_clear(&key->p);
  8767. return ASN_DH_KEY_E;
  8768. }
  8769. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8770. if (ret > 0) {
  8771. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  8772. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  8773. mp_clear(&key->p);
  8774. mp_clear(&key->g);
  8775. return ASN_DH_KEY_E;
  8776. }
  8777. }
  8778. else {
  8779. mp_clear(&key->p);
  8780. mp_clear(&key->g);
  8781. return ASN_DH_KEY_E;
  8782. }
  8783. return 0;
  8784. }
  8785. #endif /* WOLFSSL_DH_EXTRA */
  8786. #ifdef WOLFSSL_ASN_TEMPLATE
  8787. /* ASN.1 template for DH key.
  8788. * PKCS #3, 9 - DHParameter.
  8789. * (Also in: RFC 2786, 3)
  8790. */
  8791. static const ASNItem dhParamASN[] = {
  8792. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8793. /* prime */
  8794. /* PRIME */ { 1, ASN_INTEGER, 0, 0, 0 },
  8795. /* base */
  8796. /* BASE */ { 1, ASN_INTEGER, 0, 0, 0 },
  8797. /* privateValueLength */
  8798. /* PRIVLEN */ { 1, ASN_INTEGER, 0, 0, 1 },
  8799. };
  8800. enum {
  8801. DHPARAMASN_IDX_SEQ = 0,
  8802. DHPARAMASN_IDX_PRIME,
  8803. DHPARAMASN_IDX_BASE,
  8804. DHPARAMASN_IDX_PRIVLEN
  8805. };
  8806. /* Number of items in ASN.1 template for DH key. */
  8807. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  8808. #ifdef WOLFSSL_DH_EXTRA
  8809. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  8810. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  8811. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8812. * RFC 3279, 2.3.3 - DH in SubjectPublicKeyInfo
  8813. */
  8814. static const ASNItem dhKeyPkcs8ASN[] = {
  8815. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  8816. /* VER */ { 1, ASN_INTEGER, 0, 0, 1 },
  8817. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8818. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  8819. /* DHParameter */
  8820. /* PKEYALGO_PARAM_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  8821. /* p */
  8822. /* PKEYALGO_PARAM_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  8823. /* g */
  8824. /* PKEYALGO_PARAM_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  8825. /* q - factor of p-1 */
  8826. /* PKEYALGO_PARAM_Q */ { 3, ASN_INTEGER, 0, 0, 1 },
  8827. /* j - subgroup factor */
  8828. /* PKEYALGO_PARAM_J */ { 3, ASN_INTEGER, 0, 0, 1 },
  8829. /* ValidationParms */
  8830. /* PKEYALGO_PARAM_VALID */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  8831. /* PrivateKey - PKCS #8 */
  8832. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  8833. /* PKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8834. /* PublicKey - SubjectPublicKeyInfo. */
  8835. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  8836. /* PUBKEY_INT */ { 2, ASN_INTEGER, 0, 0, 0 },
  8837. };
  8838. enum {
  8839. DHKEYPKCS8ASN_IDX_SEQ = 0,
  8840. DHKEYPKCS8ASN_IDX_VER,
  8841. DHKEYPKCS8ASN_IDX_PKEYALGO_SEQ,
  8842. DHKEYPKCS8ASN_IDX_PKEYALGO_OID,
  8843. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_SEQ,
  8844. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P,
  8845. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G,
  8846. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q,
  8847. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J,
  8848. DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID,
  8849. DHKEYPKCS8ASN_IDX_PKEY_STR,
  8850. DHKEYPKCS8ASN_IDX_PKEY_INT,
  8851. DHKEYPKCS8ASN_IDX_PUBKEY_STR,
  8852. DHKEYPKCS8ASN_IDX_PUBKEY_INT
  8853. };
  8854. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  8855. #endif
  8856. #endif
  8857. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  8858. *
  8859. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  8860. * object.
  8861. *
  8862. * @param [in] input BER/DER encoded data.
  8863. * @param [in, out] inOutIdx On in, start of DH key data.
  8864. * On out, end of DH key data.
  8865. * @param [in, out] key DH key object.
  8866. * @param [in] inSz Size of data in bytes.
  8867. * @return 0 on success.
  8868. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  8869. * @return MEMORY_E when dynamic memory allocation fails.
  8870. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8871. * is invalid.
  8872. * @return BUFFER_E when data in buffer is too small.
  8873. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8874. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8875. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8876. * non-zero length.
  8877. * @return MP_INIT_E when the unable to initialize an mp_int.
  8878. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  8879. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8880. */
  8881. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  8882. {
  8883. #ifndef WOLFSSL_ASN_TEMPLATE
  8884. int ret = 0;
  8885. int length;
  8886. #ifdef WOLFSSL_DH_EXTRA
  8887. #if !defined(HAVE_FIPS) || \
  8888. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8889. word32 oid = 0, temp = 0;
  8890. #endif
  8891. #endif
  8892. WOLFSSL_ENTER("wc_DhKeyDecode");
  8893. if (inOutIdx == NULL)
  8894. return BAD_FUNC_ARG;
  8895. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8896. return ASN_PARSE_E;
  8897. #ifdef WOLFSSL_DH_EXTRA
  8898. #if !defined(HAVE_FIPS) || \
  8899. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8900. temp = *inOutIdx;
  8901. #endif
  8902. #endif
  8903. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  8904. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8905. ret = ASN_DH_KEY_E;
  8906. }
  8907. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8908. mp_clear(&key->p);
  8909. ret = ASN_DH_KEY_E;
  8910. }
  8911. #ifdef WOLFSSL_DH_EXTRA
  8912. #if !defined(HAVE_FIPS) || \
  8913. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  8914. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  8915. if (ret == ASN_DH_KEY_E) {
  8916. *inOutIdx = temp;
  8917. /* the version (0) - private only (for public skip) */
  8918. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  8919. *inOutIdx += (word32)length;
  8920. }
  8921. /* Size of dhKeyAgreement section */
  8922. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8923. return ASN_PARSE_E;
  8924. /* Check for dhKeyAgreement */
  8925. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  8926. if (oid != DHk || ret < 0)
  8927. return ASN_DH_KEY_E;
  8928. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8929. return ASN_PARSE_E;
  8930. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  8931. return ASN_DH_KEY_E;
  8932. }
  8933. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  8934. mp_clear(&key->p);
  8935. return ASN_DH_KEY_E;
  8936. }
  8937. }
  8938. temp = *inOutIdx;
  8939. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  8940. if (ret > 0) {
  8941. /* Found Bit String */
  8942. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  8943. WOLFSSL_MSG("Found Public Key");
  8944. ret = 0;
  8945. }
  8946. } else {
  8947. *inOutIdx = temp;
  8948. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  8949. if (ret > 0) {
  8950. /* Found Octet String */
  8951. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  8952. WOLFSSL_MSG("Found Private Key");
  8953. /* Compute public */
  8954. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  8955. }
  8956. } else {
  8957. /* Don't use length from failed CheckBitString/GetOctetString */
  8958. *inOutIdx = temp;
  8959. ret = 0;
  8960. }
  8961. }
  8962. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  8963. #endif /* WOLFSSL_DH_EXTRA */
  8964. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  8965. return ret;
  8966. #else
  8967. #ifdef WOLFSSL_DH_EXTRA
  8968. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  8969. #else
  8970. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  8971. #endif
  8972. int ret = 0;
  8973. /* Check input parameters are valid. */
  8974. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8975. ret = BAD_FUNC_ARG;
  8976. }
  8977. #ifdef WOLFSSL_DH_EXTRA
  8978. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  8979. #else
  8980. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  8981. #endif
  8982. if (ret == 0) {
  8983. /* Initialize data and set mp_ints to hold p and g. */
  8984. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  8985. GetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  8986. GetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  8987. /* Try simple PKCS #3 template. */
  8988. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  8989. inOutIdx, inSz);
  8990. #ifdef WOLFSSL_DH_EXTRA
  8991. if (ret != 0) {
  8992. mp_free(&key->p);
  8993. mp_free(&key->g);
  8994. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  8995. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  8996. GetASN_ExpBuffer(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID],
  8997. keyDhOid, sizeof(keyDhOid));
  8998. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  8999. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9000. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q], &key->q);
  9001. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9002. GetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9003. /* Try PKCS #8 wrapped template. */
  9004. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  9005. input, inOutIdx, inSz);
  9006. if (ret == 0) {
  9007. /* VERSION only present in PKCS #8 private key structure */
  9008. if ((dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].length != 0) &&
  9009. (dataASN[DHKEYPKCS8ASN_IDX_VER].length == 0)) {
  9010. ret = ASN_PARSE_E;
  9011. }
  9012. else if ((dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].length != 0) &&
  9013. (dataASN[DHKEYPKCS8ASN_IDX_VER].length != 0)) {
  9014. ret = ASN_PARSE_E;
  9015. }
  9016. }
  9017. if ((ret == 0) && mp_iszero(&key->pub)) {
  9018. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  9019. }
  9020. }
  9021. #endif
  9022. }
  9023. FREE_ASNGETDATA(dataASN, key->heap);
  9024. return ret;
  9025. #endif /* WOLFSSL_ASN_TEMPLATE */
  9026. }
  9027. #ifdef WOLFSSL_DH_EXTRA
  9028. /* Export DH Key (private or public) */
  9029. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  9030. {
  9031. #ifndef WOLFSSL_ASN_TEMPLATE
  9032. int ret, privSz = 0, pubSz = 0;
  9033. word32 keySz, idx, len, total;
  9034. if (key == NULL || outSz == NULL) {
  9035. return BAD_FUNC_ARG;
  9036. }
  9037. /* determine size */
  9038. if (exportPriv) {
  9039. /* octect string: priv */
  9040. privSz = SetASNIntMP(&key->priv, -1, NULL);
  9041. if (privSz < 0)
  9042. return privSz;
  9043. idx = 1 + SetLength((word32)privSz, NULL) +
  9044. (word32)privSz; /* +1 for ASN_OCTET_STRING */
  9045. }
  9046. else {
  9047. /* bit string: public */
  9048. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  9049. if (pubSz < 0)
  9050. return pubSz;
  9051. idx = SetBitString((word32)pubSz, 0, NULL) + (word32)pubSz;
  9052. }
  9053. keySz = idx;
  9054. /* DH Parameters sequence with P and G */
  9055. total = 0;
  9056. ret = wc_DhParamsToDer(key, NULL, &total);
  9057. if (ret != LENGTH_ONLY_E)
  9058. return ret;
  9059. idx += total;
  9060. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9061. idx += (word32)SetObjectId(sizeof(keyDhOid), NULL);
  9062. idx += (word32)sizeof(keyDhOid);
  9063. len = idx - keySz;
  9064. /* sequence - all but pub/priv */
  9065. idx += SetSequence(len, NULL);
  9066. if (exportPriv) {
  9067. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  9068. idx += 3;
  9069. }
  9070. /* sequence */
  9071. total = idx + SetSequence(idx, NULL);
  9072. /* if no output, then just getting size */
  9073. if (output == NULL) {
  9074. *outSz = total;
  9075. return LENGTH_ONLY_E;
  9076. }
  9077. /* make sure output fits in buffer */
  9078. if (total > *outSz) {
  9079. return BUFFER_E;
  9080. }
  9081. total = idx;
  9082. /* sequence */
  9083. idx = SetSequence(total, output);
  9084. if (exportPriv) {
  9085. /* version: 0 */
  9086. idx += (word32)SetMyVersion(0, output + idx, 0);
  9087. }
  9088. /* sequence - all but pub/priv */
  9089. idx += SetSequence(len, output + idx);
  9090. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  9091. idx += (word32)SetObjectId(sizeof(keyDhOid), output + idx);
  9092. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  9093. idx += sizeof(keyDhOid);
  9094. /* DH Parameters sequence with P and G */
  9095. total = *outSz - idx;
  9096. ret = wc_DhParamsToDer(key, output + idx, &total);
  9097. if (ret < 0)
  9098. return ret;
  9099. idx += total;
  9100. /* octect string: priv */
  9101. if (exportPriv) {
  9102. idx += (word32)SetOctetString((word32)privSz, output + idx);
  9103. idx += (word32)SetASNIntMP(&key->priv, -1, output + idx);
  9104. }
  9105. else {
  9106. /* bit string: public */
  9107. idx += (word32)SetBitString((word32)pubSz, 0, output + idx);
  9108. idx += (word32)SetASNIntMP(&key->pub, -1, output + idx);
  9109. }
  9110. *outSz = idx;
  9111. return (int)idx;
  9112. #else
  9113. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  9114. int ret = 0;
  9115. int sz;
  9116. WOLFSSL_ENTER("wc_DhKeyToDer");
  9117. XMEMSET(dataASN, 0, sizeof(dataASN));
  9118. SetASN_Int8Bit(&dataASN[DHKEYPKCS8ASN_IDX_VER], 0);
  9119. SetASN_OID(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_OID], DHk, oidKeyType);
  9120. /* Set mp_int containing p and g. */
  9121. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_P], &key->p);
  9122. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_G], &key->g);
  9123. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_Q].noOut = 1;
  9124. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_J].noOut = 1;
  9125. dataASN[DHKEYPKCS8ASN_IDX_PKEYALGO_PARAM_VALID].noOut = 1;
  9126. if (exportPriv) {
  9127. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT], &key->priv);
  9128. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_STR].noOut = 1;
  9129. dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT].noOut = 1;
  9130. }
  9131. else {
  9132. dataASN[DHKEYPKCS8ASN_IDX_VER].noOut = 1;
  9133. dataASN[DHKEYPKCS8ASN_IDX_PKEY_STR].noOut = 1;
  9134. dataASN[DHKEYPKCS8ASN_IDX_PKEY_INT].noOut = 1;
  9135. SetASN_MP(&dataASN[DHKEYPKCS8ASN_IDX_PUBKEY_INT], &key->pub);
  9136. }
  9137. /* Calculate the size of the DH parameters. */
  9138. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  9139. if (output == NULL) {
  9140. *outSz = (word32)sz;
  9141. ret = LENGTH_ONLY_E;
  9142. }
  9143. /* Check buffer is big enough for encoding. */
  9144. if ((ret == 0) && ((int)*outSz < sz)) {
  9145. ret = BUFFER_E;
  9146. }
  9147. if (ret == 0) {
  9148. /* Encode the DH parameters into buffer. */
  9149. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  9150. /* Set the actual encoding size. */
  9151. *outSz = (word32)sz;
  9152. /* Return the actual encoding size. */
  9153. ret = sz;
  9154. }
  9155. return ret;
  9156. #endif
  9157. }
  9158. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  9159. {
  9160. return wc_DhKeyToDer(key, out, outSz, 0);
  9161. }
  9162. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  9163. {
  9164. return wc_DhKeyToDer(key, out, outSz, 1);
  9165. }
  9166. /* Convert DH key parameters to DER format, write to output (outSz)
  9167. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  9168. * returned.
  9169. *
  9170. * Note : static function due to redefinition complications with DhKey and FIPS
  9171. * version 2 build.
  9172. *
  9173. * return bytes written on success */
  9174. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  9175. {
  9176. #ifndef WOLFSSL_ASN_TEMPLATE
  9177. int ret;
  9178. word32 idx, total;
  9179. if (key == NULL || outSz == NULL) {
  9180. return BAD_FUNC_ARG;
  9181. }
  9182. /* determine size */
  9183. /* integer - g */
  9184. ret = SetASNIntMP(&key->g, -1, NULL);
  9185. if (ret < 0)
  9186. return ret;
  9187. idx = (word32)ret;
  9188. /* integer - p */
  9189. ret = SetASNIntMP(&key->p, -1, NULL);
  9190. if (ret < 0)
  9191. return ret;
  9192. idx += (word32)ret;
  9193. total = idx;
  9194. /* sequence */
  9195. idx += SetSequence(idx, NULL);
  9196. if (output == NULL) {
  9197. *outSz = idx;
  9198. return LENGTH_ONLY_E;
  9199. }
  9200. /* make sure output fits in buffer */
  9201. if (idx > *outSz) {
  9202. return BUFFER_E;
  9203. }
  9204. /* write DH parameters */
  9205. /* sequence - for P and G only */
  9206. idx = SetSequence(total, output);
  9207. /* integer - p */
  9208. ret = SetASNIntMP(&key->p, -1, output + idx);
  9209. if (ret < 0)
  9210. return ret;
  9211. idx += (word32)ret;
  9212. /* integer - g */
  9213. ret = SetASNIntMP(&key->g, -1, output + idx);
  9214. if (ret < 0)
  9215. return ret;
  9216. idx += (word32)ret;
  9217. *outSz = idx;
  9218. return (int)idx;
  9219. #else
  9220. ASNSetData dataASN[dhParamASN_Length];
  9221. int ret = 0;
  9222. int sz = 0;
  9223. WOLFSSL_ENTER("wc_DhParamsToDer");
  9224. if (key == NULL || outSz == NULL) {
  9225. ret = BAD_FUNC_ARG;
  9226. }
  9227. if (ret == 0) {
  9228. XMEMSET(dataASN, 0, sizeof(dataASN));
  9229. /* Set mp_int containing p and g. */
  9230. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], &key->p);
  9231. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], &key->g);
  9232. /* privateValueLength not encoded. */
  9233. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  9234. /* Calculate the size of the DH parameters. */
  9235. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  9236. }
  9237. if ((ret == 0) && (output == NULL)) {
  9238. *outSz = (word32)sz;
  9239. ret = LENGTH_ONLY_E;
  9240. }
  9241. /* Check buffer is big enough for encoding. */
  9242. if ((ret == 0) && (*outSz < (word32)sz)) {
  9243. ret = BUFFER_E;
  9244. }
  9245. if (ret == 0) {
  9246. /* Encode the DH parameters into buffer. */
  9247. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  9248. /* Set the actual encoding size. */
  9249. *outSz = (word32)sz;
  9250. /* Return count of bytes written. */
  9251. ret = sz;
  9252. }
  9253. return ret;
  9254. #endif
  9255. }
  9256. #endif /* WOLFSSL_DH_EXTRA */
  9257. /* Decode DH parameters.
  9258. *
  9259. * PKCS #3, 9 - DHParameter.
  9260. * (Also in: RFC 2786, 3)
  9261. *
  9262. * @param [in] input Buffer holding BER encoded data.
  9263. * @param [in, out] inOutIdx On in, start of RSA public key.
  9264. * On out, start of ASN.1 item after RSA public key.
  9265. * @param [in] inSz Number of bytes in buffer.
  9266. * @param [in, out] p Buffer to hold prime.
  9267. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  9268. * On out, size of prime in bytes.
  9269. * @param [in, out] g Buffer to hold base.
  9270. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  9271. * On out, size of base in bytes.
  9272. * @return 0 on success.
  9273. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9274. * is invalid.
  9275. * @return BUFFER_E when data in buffer is too small.
  9276. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  9277. */
  9278. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  9279. byte* g, word32* gInOutSz)
  9280. {
  9281. #ifndef WOLFSSL_ASN_TEMPLATE
  9282. word32 idx = 0;
  9283. int ret;
  9284. int length;
  9285. if (GetSequence(input, &idx, &length, inSz) <= 0)
  9286. return ASN_PARSE_E;
  9287. ret = GetASNInt(input, &idx, &length, inSz);
  9288. if (ret != 0)
  9289. return ret;
  9290. if (length <= (int)*pInOutSz) {
  9291. XMEMCPY(p, &input[idx], (size_t)length);
  9292. *pInOutSz = (word32)length;
  9293. }
  9294. else {
  9295. return BUFFER_E;
  9296. }
  9297. idx += (word32)length;
  9298. ret = GetASNInt(input, &idx, &length, inSz);
  9299. if (ret != 0)
  9300. return ret;
  9301. if (length <= (int)*gInOutSz) {
  9302. XMEMCPY(g, &input[idx], (size_t)length);
  9303. *gInOutSz = (word32)length;
  9304. }
  9305. else {
  9306. return BUFFER_E;
  9307. }
  9308. return 0;
  9309. #else
  9310. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  9311. word32 idx = 0;
  9312. int ret = 0;
  9313. /* Make sure pointers are valid before use. */
  9314. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  9315. (gInOutSz == NULL)) {
  9316. ret = BAD_FUNC_ARG;
  9317. }
  9318. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  9319. if (ret == 0) {
  9320. /* Set the buffers to copy p and g into. */
  9321. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_PRIME], p, pInOutSz);
  9322. GetASN_Buffer(&dataASN[DHPARAMASN_IDX_BASE], g, gInOutSz);
  9323. /* Decode the DH Parameters. */
  9324. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  9325. &idx, inSz);
  9326. }
  9327. FREE_ASNGETDATA(dataASN, NULL);
  9328. return ret;
  9329. #endif /* WOLFSSL_ASN_TEMPLATE */
  9330. }
  9331. #endif /* !NO_DH */
  9332. #ifndef NO_DSA
  9333. static mp_int* GetDsaInt(DsaKey* key, int idx)
  9334. {
  9335. if (idx == 0)
  9336. return &key->p;
  9337. if (idx == 1)
  9338. return &key->q;
  9339. if (idx == 2)
  9340. return &key->g;
  9341. if (idx == 3)
  9342. return &key->y;
  9343. if (idx == 4)
  9344. return &key->x;
  9345. return NULL;
  9346. }
  9347. #ifdef WOLFSSL_ASN_TEMPLATE
  9348. /* ASN.1 template for DSA public and private keys.
  9349. * Public key: seq, p, q, g, y
  9350. * Private key: seq, version, p, q, g, y, x
  9351. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9352. */
  9353. static const ASNItem dsaKeyASN[] = {
  9354. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9355. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  9356. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9357. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9358. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9359. /* Y */ { 1, ASN_INTEGER, 0, 0, 0 },
  9360. /* X */ { 1, ASN_INTEGER, 0, 0, 0 },
  9361. };
  9362. enum {
  9363. DSAKEYASN_IDX_SEQ = 0,
  9364. DSAKEYASN_IDX_VER,
  9365. DSAKEYASN_IDX_P,
  9366. DSAKEYASN_IDX_Q,
  9367. DSAKEYASN_IDX_G,
  9368. DSAKEYASN_IDX_Y,
  9369. DSAKEYASN_IDX_X
  9370. };
  9371. /* Number of items in ASN.1 template for DSA private key. */
  9372. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  9373. /* Number of items in ASN.1 template for DSA public key. */
  9374. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  9375. /* ASN.1 template for PublicKeyInfo with DSA.
  9376. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9377. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9378. */
  9379. static const ASNItem dsaPubKeyASN[] = {
  9380. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9381. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  9382. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  9383. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9384. /* p */
  9385. /* ALGOID_PARAMS_P */ { 3, ASN_INTEGER, 0, 0, 0 },
  9386. /* q */
  9387. /* ALGOID_PARAMS_Q */ { 3, ASN_INTEGER, 0, 0, 0 },
  9388. /* g */
  9389. /* ALGOID_PARAMS_G */ { 3, ASN_INTEGER, 0, 0, 0 },
  9390. /* PUBKEY_STR */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  9391. /* y */
  9392. /* PUBKEY_Y */ { 2, ASN_INTEGER, 0, 0, 0 },
  9393. };
  9394. enum {
  9395. DSAPUBKEYASN_IDX_SEQ = 0,
  9396. DSAPUBKEYASN_IDX_ALGOID_SEQ,
  9397. DSAPUBKEYASN_IDX_ALGOID_OID,
  9398. DSAPUBKEYASN_IDX_ALGOID_PARAMS,
  9399. DSAPUBKEYASN_IDX_ALGOID_PARAMS_P,
  9400. DSAPUBKEYASN_IDX_ALGOID_PARAMS_Q,
  9401. DSAPUBKEYASN_IDX_ALGOID_PARAMS_G,
  9402. DSAPUBKEYASN_IDX_PUBKEY_STR,
  9403. DSAPUBKEYASN_IDX_PUBKEY_Y
  9404. };
  9405. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  9406. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  9407. #endif /* WOLFSSL_ASN_TEMPLATE */
  9408. /* Decode DSA public key.
  9409. *
  9410. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  9411. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  9412. *
  9413. * @param [in] input Buffer holding BER encoded data.
  9414. * @param [in, out] inOutIdx On in, start of DSA public key.
  9415. * On out, start of ASN.1 item after DSA public key.
  9416. * @param [in, out] key DSA key object.
  9417. * @param [in] inSz Number of bytes in buffer.
  9418. * @return 0 on success.
  9419. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9420. * is invalid.
  9421. * @return BUFFER_E when data in buffer is too small.
  9422. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9423. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9424. * non-zero length.
  9425. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  9426. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9427. */
  9428. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9429. word32 inSz)
  9430. {
  9431. #ifndef WOLFSSL_ASN_TEMPLATE
  9432. int length;
  9433. int ret = 0;
  9434. word32 oid;
  9435. word32 maxIdx;
  9436. if (input == NULL || inOutIdx == NULL || key == NULL)
  9437. return BAD_FUNC_ARG;
  9438. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9439. return ASN_PARSE_E;
  9440. maxIdx = (word32)(*inOutIdx + (word32)length);
  9441. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9442. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9443. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  9444. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  9445. ret = ASN_DH_KEY_E;
  9446. if (ret != 0) {
  9447. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9448. return ASN_PARSE_E;
  9449. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  9450. if (ret != 0)
  9451. return ret;
  9452. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9453. return ASN_PARSE_E;
  9454. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9455. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9456. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  9457. return ASN_DH_KEY_E;
  9458. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  9459. return ASN_PARSE_E;
  9460. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  9461. return ASN_DH_KEY_E;
  9462. ret = 0;
  9463. }
  9464. key->type = DSA_PUBLIC;
  9465. return ret;
  9466. #else
  9467. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  9468. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  9469. int ret = 0;
  9470. /* Validated parameters. */
  9471. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9472. ret = BAD_FUNC_ARG;
  9473. }
  9474. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9475. if (ret == 0) {
  9476. int i;
  9477. /* Clear dynamic data items. */
  9478. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  9479. /* seq
  9480. * p, q, g, y
  9481. * Start DSA ints from DSAKEYASN_IDX_VER instead of DSAKEYASN_IDX_P */
  9482. for (i = 0; i < DSA_INTS - 1; i++)
  9483. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i], GetDsaInt(key, i));
  9484. /* Parse as simple form. */
  9485. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 0, input,
  9486. inOutIdx, inSz);
  9487. if (ret != 0) {
  9488. /* Clear dynamic data items. */
  9489. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  9490. /* Set DSA OID to expect. */
  9491. GetASN_ExpBuffer(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID],
  9492. keyDsaOid, sizeof(keyDsaOid));
  9493. /* p, q, g */
  9494. for (i = 0; i < DSA_INTS - 2; i++)
  9495. GetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9496. GetDsaInt(key, i));
  9497. /* y */
  9498. GetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9499. /* Parse as SubjectPublicKeyInfo. */
  9500. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  9501. input, inOutIdx, inSz);
  9502. }
  9503. }
  9504. if (ret == 0) {
  9505. /* Data parsed - set type of key parsed. */
  9506. key->type = DSA_PUBLIC;
  9507. }
  9508. FREE_ASNGETDATA(dataASN, key->heap);
  9509. return ret;
  9510. #endif
  9511. }
  9512. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9513. word32 inSz)
  9514. {
  9515. int length;
  9516. word32 maxIdx;
  9517. if (input == NULL || inOutIdx == NULL || key == NULL)
  9518. return BAD_FUNC_ARG;
  9519. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9520. return ASN_PARSE_E;
  9521. maxIdx = (word32)(*inOutIdx + (word32)length);
  9522. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  9523. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  9524. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  9525. return ASN_DH_KEY_E;
  9526. return 0;
  9527. }
  9528. #ifdef WOLFSSL_ASN_TEMPLATE
  9529. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  9530. static const ASNItem dsaKeyOctASN[] = {
  9531. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  9532. /* p */
  9533. /* P */ { 1, ASN_INTEGER, 0, 0, 0 },
  9534. /* q */
  9535. /* Q */ { 1, ASN_INTEGER, 0, 0, 0 },
  9536. /* g */
  9537. /* G */ { 1, ASN_INTEGER, 0, 0, 0 },
  9538. /* Private key */
  9539. /* PKEY_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  9540. /* x */
  9541. /* X */ { 2, ASN_INTEGER, 0, 0, 0 },
  9542. };
  9543. enum {
  9544. DSAKEYOCTASN_IDX_SEQ = 0,
  9545. DSAKEYOCTASN_IDX_P,
  9546. DSAKEYOCTASN_IDX_Q,
  9547. DSAKEYOCTASN_IDX_G,
  9548. DSAKEYOCTASN_IDX_PKEY_STR,
  9549. DSAKEYOCTASN_IDX_X
  9550. };
  9551. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  9552. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  9553. #endif
  9554. /* Decode DSA private key.
  9555. *
  9556. * @param [in] input Buffer holding BER encoded data.
  9557. * @param [in, out] inOutIdx On in, start of DSA public key.
  9558. * On out, start of ASN.1 item after DSA public key.
  9559. * @param [in, out] key DSA key object.
  9560. * @param [in] inSz Number of bytes in buffer.
  9561. * @return 0 on success.
  9562. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9563. * is invalid.
  9564. * @return BUFFER_E when data in buffer is too small.
  9565. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  9566. * non-zero length.
  9567. */
  9568. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  9569. word32 inSz)
  9570. {
  9571. #ifndef WOLFSSL_ASN_TEMPLATE
  9572. int length, version, ret = 0, temp = 0;
  9573. word32 algId = 0;
  9574. /* Sanity checks on input */
  9575. if (input == NULL || inOutIdx == NULL || key == NULL) {
  9576. return BAD_FUNC_ARG;
  9577. }
  9578. /* if has pkcs8 header skip it */
  9579. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  9580. /* ignore error, did not have pkcs8 header */
  9581. }
  9582. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9583. return ASN_PARSE_E;
  9584. temp = (int)*inOutIdx;
  9585. /* Default case expects a certificate with OctetString but no version ID */
  9586. ret = GetInt(&key->p, input, inOutIdx, inSz);
  9587. if (ret < 0) {
  9588. mp_clear(&key->p);
  9589. ret = ASN_PARSE_E;
  9590. }
  9591. else {
  9592. ret = GetInt(&key->q, input, inOutIdx, inSz);
  9593. if (ret < 0) {
  9594. mp_clear(&key->p);
  9595. mp_clear(&key->q);
  9596. ret = ASN_PARSE_E;
  9597. }
  9598. else {
  9599. ret = GetInt(&key->g, input, inOutIdx, inSz);
  9600. if (ret < 0) {
  9601. mp_clear(&key->p);
  9602. mp_clear(&key->q);
  9603. mp_clear(&key->g);
  9604. ret = ASN_PARSE_E;
  9605. }
  9606. else {
  9607. ret = GetOctetString(input, inOutIdx, &length, inSz);
  9608. if (ret < 0) {
  9609. mp_clear(&key->p);
  9610. mp_clear(&key->q);
  9611. mp_clear(&key->g);
  9612. ret = ASN_PARSE_E;
  9613. }
  9614. else {
  9615. ret = GetInt(&key->y, input, inOutIdx, inSz);
  9616. if (ret < 0) {
  9617. mp_clear(&key->p);
  9618. mp_clear(&key->q);
  9619. mp_clear(&key->g);
  9620. mp_clear(&key->y);
  9621. ret = ASN_PARSE_E;
  9622. }
  9623. }
  9624. }
  9625. }
  9626. }
  9627. /* An alternate pass if default certificate fails parsing */
  9628. if (ret == ASN_PARSE_E) {
  9629. *inOutIdx = (word32)temp;
  9630. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9631. return ASN_PARSE_E;
  9632. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  9633. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  9634. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  9635. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  9636. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  9637. return ASN_DH_KEY_E;
  9638. }
  9639. key->type = DSA_PRIVATE;
  9640. return 0;
  9641. #else
  9642. /* dsaKeyASN is longer than dsaKeyOctASN. */
  9643. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  9644. int ret = 0;
  9645. byte version = 0;
  9646. /* Sanity checks on input */
  9647. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  9648. ret = BAD_FUNC_ARG;
  9649. }
  9650. CALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  9651. if (ret == 0) {
  9652. int i;
  9653. /* Try dsaKeyOctASN */
  9654. /* Initialize key data and set mp_ints for params */
  9655. for (i = 0; i < DSA_INTS - 2; i++) {
  9656. GetASN_MP(&dataASN[(int)DSAKEYOCTASN_IDX_P + i], GetDsaInt(key, i));
  9657. }
  9658. /* and priv */
  9659. GetASN_MP(&dataASN[DSAKEYOCTASN_IDX_X], GetDsaInt(key, i));
  9660. /* Try simple form. */
  9661. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  9662. inOutIdx, inSz);
  9663. if (ret != 0) {
  9664. /* Try dsaKeyASN */
  9665. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  9666. GetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], &version);
  9667. for (i = 0; i < DSA_INTS; i++) {
  9668. mp_int* n = GetDsaInt(key, i);
  9669. mp_clear(n);
  9670. GetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], n);
  9671. }
  9672. /* Try simple OCTET_STRING form. */
  9673. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  9674. inOutIdx, inSz);
  9675. }
  9676. }
  9677. if (ret == 0) {
  9678. /* Set the contents to be a private key. */
  9679. key->type = DSA_PRIVATE;
  9680. }
  9681. FREE_ASNGETDATA(dataASN, key->heap);
  9682. return ret;
  9683. #endif
  9684. }
  9685. #ifndef WOLFSSL_ASN_TEMPLATE
  9686. /* Release Tmp DSA resources */
  9687. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  9688. {
  9689. int i;
  9690. for (i = 0; i < ints; i++)
  9691. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  9692. (void)heap;
  9693. }
  9694. #endif /* !WOLFSSL_ASN_TEMPLATE */
  9695. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  9696. defined(WOLFSSL_CERT_GEN))
  9697. /* Encode a DSA public key into buffer.
  9698. *
  9699. * @param [out] output Buffer to hold encoded data.
  9700. * @param [in] key DSA key object.
  9701. * @param [out] outLen Length of buffer.
  9702. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9703. * @return Size of encoded data in bytes on success.
  9704. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9705. * than a minimal size (5 bytes), or buffer size is smaller than
  9706. * encoding size.
  9707. * @return MEMORY_E when dynamic memory allocation fails.
  9708. */
  9709. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  9710. {
  9711. #ifndef WOLFSSL_ASN_TEMPLATE
  9712. /* p, g, q = DSA params, y = public exponent */
  9713. #ifdef WOLFSSL_SMALL_STACK
  9714. byte* p = NULL;
  9715. byte* g = NULL;
  9716. byte* q = NULL;
  9717. byte* y = NULL;
  9718. #else
  9719. byte p[MAX_DSA_INT_SZ];
  9720. byte g[MAX_DSA_INT_SZ];
  9721. byte q[MAX_DSA_INT_SZ];
  9722. byte y[MAX_DSA_INT_SZ];
  9723. #endif
  9724. byte innerSeq[MAX_SEQ_SZ];
  9725. byte outerSeq[MAX_SEQ_SZ];
  9726. byte bitString[1 + MAX_LENGTH_SZ + 1];
  9727. int pSz, gSz, qSz, ySz;
  9728. word32 idx, innerSeqSz, outerSeqSz, bitStringSz = 0;
  9729. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9730. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  9731. return BAD_FUNC_ARG;
  9732. }
  9733. /* p */
  9734. #ifdef WOLFSSL_SMALL_STACK
  9735. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9736. if (p == NULL)
  9737. return MEMORY_E;
  9738. #endif
  9739. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  9740. WOLFSSL_MSG("SetASNIntMP Error with p");
  9741. #ifdef WOLFSSL_SMALL_STACK
  9742. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9743. #endif
  9744. return pSz;
  9745. }
  9746. /* q */
  9747. #ifdef WOLFSSL_SMALL_STACK
  9748. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9749. if (q == NULL)
  9750. return MEMORY_E;
  9751. #endif
  9752. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  9753. WOLFSSL_MSG("SetASNIntMP Error with q");
  9754. #ifdef WOLFSSL_SMALL_STACK
  9755. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9756. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9757. #endif
  9758. return qSz;
  9759. }
  9760. /* g */
  9761. #ifdef WOLFSSL_SMALL_STACK
  9762. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9763. if (g == NULL)
  9764. return MEMORY_E;
  9765. #endif
  9766. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  9767. WOLFSSL_MSG("SetASNIntMP Error with g");
  9768. #ifdef WOLFSSL_SMALL_STACK
  9769. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9770. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9771. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9772. #endif
  9773. return gSz;
  9774. }
  9775. /* y */
  9776. #ifdef WOLFSSL_SMALL_STACK
  9777. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9778. if (y == NULL)
  9779. return MEMORY_E;
  9780. #endif
  9781. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  9782. WOLFSSL_MSG("SetASNIntMP Error with y");
  9783. #ifdef WOLFSSL_SMALL_STACK
  9784. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9785. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9786. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9787. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9788. #endif
  9789. return ySz;
  9790. }
  9791. if (with_header) {
  9792. word32 algoSz;
  9793. #ifdef WOLFSSL_SMALL_STACK
  9794. byte* algo = NULL;
  9795. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9796. if (algo == NULL) {
  9797. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9798. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9799. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9800. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9801. return MEMORY_E;
  9802. }
  9803. #else
  9804. byte algo[MAX_ALGO_SZ];
  9805. #endif
  9806. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz), innerSeq);
  9807. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  9808. bitStringSz = SetBitString((word32)ySz, 0, bitString);
  9809. outerSeqSz = SetSequence(algoSz + innerSeqSz +
  9810. (word32)(pSz + qSz + gSz), outerSeq);
  9811. idx = SetSequence(algoSz + innerSeqSz + (word32)(pSz + qSz + gSz) +
  9812. bitStringSz + (word32)ySz + outerSeqSz, output);
  9813. /* check output size */
  9814. if ((idx + algoSz + bitStringSz + innerSeqSz +
  9815. (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen)
  9816. {
  9817. #ifdef WOLFSSL_SMALL_STACK
  9818. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9819. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9820. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9821. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9822. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9823. #endif
  9824. WOLFSSL_MSG("Error, output size smaller than outlen");
  9825. return BUFFER_E;
  9826. }
  9827. /* outerSeq */
  9828. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  9829. idx += outerSeqSz;
  9830. /* algo */
  9831. XMEMCPY(output + idx, algo, algoSz);
  9832. idx += algoSz;
  9833. #ifdef WOLFSSL_SMALL_STACK
  9834. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9835. #endif
  9836. } else {
  9837. innerSeqSz = SetSequence((word32)(pSz + qSz + gSz + ySz), innerSeq);
  9838. /* check output size */
  9839. if ((innerSeqSz + (word32)(pSz + qSz + gSz + ySz)) > (word32)outLen) {
  9840. #ifdef WOLFSSL_SMALL_STACK
  9841. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9842. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9843. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9844. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9845. #endif
  9846. WOLFSSL_MSG("Error, output size smaller than outlen");
  9847. return BUFFER_E;
  9848. }
  9849. idx = 0;
  9850. }
  9851. /* innerSeq */
  9852. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  9853. idx += innerSeqSz;
  9854. /* p */
  9855. XMEMCPY(output + idx, p, (size_t)pSz);
  9856. idx += (word32)pSz;
  9857. /* q */
  9858. XMEMCPY(output + idx, q, (size_t)qSz);
  9859. idx += (word32)qSz;
  9860. /* g */
  9861. XMEMCPY(output + idx, g, (size_t)gSz);
  9862. idx += (word32)gSz;
  9863. /* bit string */
  9864. if (bitStringSz > 0) {
  9865. XMEMCPY(output + idx, bitString, bitStringSz);
  9866. idx += bitStringSz;
  9867. }
  9868. /* y */
  9869. XMEMCPY(output + idx, y, (size_t)ySz);
  9870. idx += (word32)ySz;
  9871. #ifdef WOLFSSL_SMALL_STACK
  9872. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9873. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9874. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9875. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9876. #endif
  9877. return (int)idx;
  9878. #else
  9879. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  9880. int ret = 0;
  9881. int i;
  9882. int sz = 0;
  9883. const ASNItem *data = NULL;
  9884. int count = 0;
  9885. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  9886. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  9887. ret = BAD_FUNC_ARG;
  9888. }
  9889. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  9890. if (ret == 0) {
  9891. if (with_header) {
  9892. /* Using dsaPubKeyASN */
  9893. data = dsaPubKeyASN;
  9894. count = dsaPubKeyASN_Length;
  9895. /* Set the algorithm OID to write out. */
  9896. SetASN_OID(&dataASN[DSAPUBKEYASN_IDX_ALGOID_OID], DSAk, oidKeyType);
  9897. /* Set the mp_ints to encode - parameters and public value. */
  9898. for (i = 0; i < DSA_INTS - 2; i++) {
  9899. SetASN_MP(&dataASN[(int)DSAPUBKEYASN_IDX_ALGOID_PARAMS_P + i],
  9900. GetDsaInt(key, i));
  9901. }
  9902. SetASN_MP(&dataASN[DSAPUBKEYASN_IDX_PUBKEY_Y], GetDsaInt(key, i));
  9903. }
  9904. else {
  9905. /* Using dsaKeyASN */
  9906. data = dsaKeyASN;
  9907. count = dsaPublicKeyASN_Length;
  9908. /* Set the mp_ints to encode - parameters and public value. */
  9909. for (i = 0; i < DSA_INTS - 1; i++) {
  9910. /* Move all DSA ints up one slot (ignore VERSION so now
  9911. * it means P) */
  9912. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_VER + i],
  9913. GetDsaInt(key, i));
  9914. }
  9915. }
  9916. ret = SizeASN_Items(data, dataASN, count, &sz);
  9917. }
  9918. /* Check buffer is big enough for encoding. */
  9919. if ((ret == 0) && (sz > (int)outLen)) {
  9920. ret = BAD_FUNC_ARG;
  9921. }
  9922. /* Encode the DSA public key into output buffer. */
  9923. if (ret == 0) {
  9924. ret = SetASN_Items(data, dataASN, count, output);
  9925. }
  9926. FREE_ASNSETDATA(dataASN, key->heap);
  9927. return ret;
  9928. #endif /* WOLFSSL_ASN_TEMPLATE */
  9929. }
  9930. /* Encode a DSA public key into buffer.
  9931. *
  9932. * @param [out] output Buffer to hold encoded data.
  9933. * @param [in] key DSA key object.
  9934. * @param [out] outLen Length of buffer.
  9935. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  9936. * @return Size of encoded data in bytes on success.
  9937. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  9938. * than a minimal size (5 bytes), or buffer size is smaller than
  9939. * encoding size.
  9940. * @return MEMORY_E when dynamic memory allocation fails.
  9941. */
  9942. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  9943. {
  9944. return wc_SetDsaPublicKey(output, key, (int)inLen, 1);
  9945. }
  9946. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  9947. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  9948. int ints, int includeVersion)
  9949. {
  9950. #ifndef WOLFSSL_ASN_TEMPLATE
  9951. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen, j;
  9952. word32 sizes[DSA_INTS];
  9953. int i, ret = 0;
  9954. byte seq[MAX_SEQ_SZ];
  9955. byte ver[MAX_VERSION_SZ];
  9956. byte* tmps[DSA_INTS];
  9957. if (ints > DSA_INTS || inLen == NULL)
  9958. return BAD_FUNC_ARG;
  9959. XMEMSET(sizes, 0, sizeof(sizes));
  9960. for (i = 0; i < ints; i++)
  9961. tmps[i] = NULL;
  9962. /* write all big ints from key to DER tmps */
  9963. for (i = 0; i < ints; i++) {
  9964. int mpSz;
  9965. mp_int* keyInt = GetDsaInt(key, i);
  9966. word32 rawLen = (word32)mp_unsigned_bin_size(keyInt) + 1;
  9967. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  9968. DYNAMIC_TYPE_DSA);
  9969. if (tmps[i] == NULL) {
  9970. ret = MEMORY_E;
  9971. break;
  9972. }
  9973. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  9974. if (mpSz < 0) {
  9975. ret = mpSz;
  9976. break;
  9977. }
  9978. sizes[i] = (word32)mpSz;
  9979. intTotalLen += (word32)mpSz;
  9980. }
  9981. if (ret != 0) {
  9982. FreeTmpDsas(tmps, key->heap, ints);
  9983. return ret;
  9984. }
  9985. /* make headers */
  9986. if (includeVersion)
  9987. verSz = (word32)SetMyVersion(0, ver, FALSE);
  9988. seqSz = SetSequence(verSz + intTotalLen, seq);
  9989. outLen = seqSz + verSz + intTotalLen;
  9990. *inLen = outLen;
  9991. if (output == NULL) {
  9992. FreeTmpDsas(tmps, key->heap, ints);
  9993. return LENGTH_ONLY_E;
  9994. }
  9995. if (outLen > *inLen) {
  9996. FreeTmpDsas(tmps, key->heap, ints);
  9997. return BAD_FUNC_ARG;
  9998. }
  9999. /* write to output */
  10000. XMEMCPY(output, seq, seqSz);
  10001. j = seqSz;
  10002. if (includeVersion) {
  10003. XMEMCPY(output + j, ver, verSz);
  10004. j += verSz;
  10005. }
  10006. for (i = 0; i < ints; i++) {
  10007. XMEMCPY(output + j, tmps[i], sizes[i]);
  10008. j += sizes[i];
  10009. }
  10010. FreeTmpDsas(tmps, key->heap, ints);
  10011. return (int)outLen;
  10012. #else
  10013. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  10014. int ret = 0;
  10015. int sz = 0;
  10016. (void)ints;
  10017. if ((key == NULL) || (inLen == NULL)) {
  10018. ret = BAD_FUNC_ARG;
  10019. }
  10020. if ((ret == 0) && (ints > DSA_INTS)) {
  10021. ret = BAD_FUNC_ARG;
  10022. }
  10023. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  10024. if (ret == 0) {
  10025. int i;
  10026. if (includeVersion) {
  10027. /* Set the version. */
  10028. SetASN_Int8Bit(&dataASN[DSAKEYASN_IDX_VER], 0);
  10029. }
  10030. else {
  10031. dataASN[DSAKEYASN_IDX_VER].noOut = 1;
  10032. }
  10033. dataASN[DSAKEYASN_IDX_Y].noOut = mp_iszero(&key->y);
  10034. dataASN[DSAKEYASN_IDX_X].noOut = mp_iszero(&key->x);
  10035. /* Set the mp_ints to encode - params, public and private value. */
  10036. for (i = 0; i < DSA_INTS; i++) {
  10037. if (i < ints)
  10038. SetASN_MP(&dataASN[(int)DSAKEYASN_IDX_P + i], GetDsaInt(key, i));
  10039. else
  10040. dataASN[(int)DSAKEYASN_IDX_P + i].noOut = 1;
  10041. }
  10042. /* Calculate size of the encoding. */
  10043. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  10044. }
  10045. if ((ret == 0) && (output == NULL)) {
  10046. *inLen = (word32)sz;
  10047. ret = LENGTH_ONLY_E;
  10048. }
  10049. /* Check buffer is big enough for encoding. */
  10050. if ((ret == 0) && (sz > (int)*inLen)) {
  10051. ret = BAD_FUNC_ARG;
  10052. }
  10053. if (ret == 0) {
  10054. /* Encode the DSA private key into output buffer. */
  10055. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  10056. /* Return the size of the encoding. */
  10057. ret = sz;
  10058. }
  10059. FREE_ASNSETDATA(dataASN, key->heap);
  10060. return ret;
  10061. #endif /* WOLFSSL_ASN_TEMPLATE */
  10062. }
  10063. /* Encode a DSA private key into buffer.
  10064. *
  10065. * @param [in] key DSA key object.
  10066. * @param [out] output Buffer to hold encoded data.
  10067. * @param [out] inLen Length of buffer.
  10068. * @return Size of encoded data in bytes on success.
  10069. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  10070. * or, buffer size is smaller than encoding size.
  10071. * @return MEMORY_E when dynamic memory allocation fails.
  10072. */
  10073. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  10074. {
  10075. if (!key || !output)
  10076. return BAD_FUNC_ARG;
  10077. if (key->type != DSA_PRIVATE)
  10078. return BAD_FUNC_ARG;
  10079. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  10080. }
  10081. /* Convert DsaKey parameters to DER format, write to output (inLen),
  10082. return bytes written. Version is excluded to be compatible with
  10083. OpenSSL d2i_DSAparams */
  10084. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  10085. {
  10086. if (!key || !output)
  10087. return BAD_FUNC_ARG;
  10088. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  10089. }
  10090. /* This version of the function allows output to be NULL. In that case, the
  10091. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  10092. size will be pointed to by inLen. */
  10093. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  10094. {
  10095. if (!key || !inLen)
  10096. return BAD_FUNC_ARG;
  10097. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  10098. }
  10099. #endif /* NO_DSA */
  10100. #ifndef NO_CERTS
  10101. /* Initialize decoded certificate object with buffer of DER encoding.
  10102. *
  10103. * @param [in, out] cert Decoded certificate object.
  10104. * @param [in] source Buffer containing DER encoded certificate.
  10105. * @param [in] inSz Size of DER data in buffer in bytes.
  10106. * @param [in] heap Dynamic memory hint.
  10107. */
  10108. void InitDecodedCert(DecodedCert* cert,
  10109. const byte* source, word32 inSz, void* heap)
  10110. {
  10111. InitDecodedCert_ex(cert, source, inSz, heap, INVALID_DEVID);
  10112. }
  10113. /* Initialize decoded certificate object with buffer of DER encoding.
  10114. *
  10115. * @param [in, out] cert Decoded certificate object.
  10116. * @param [in] source Buffer containing DER encoded certificate.
  10117. * @param [in] inSz Size of DER data in buffer in bytes.
  10118. * @param [in] heap Dynamic memory hint.
  10119. * @param [in] devId Crypto callback ID to use.
  10120. */
  10121. void InitDecodedCert_ex(DecodedCert* cert,
  10122. const byte* source, word32 inSz, void* heap, int devId)
  10123. {
  10124. if (cert != NULL) {
  10125. XMEMSET(cert, 0, sizeof(DecodedCert));
  10126. cert->subjectCNEnc = CTC_UTF8;
  10127. cert->issuer[0] = '\0';
  10128. cert->subject[0] = '\0';
  10129. cert->source = source; /* don't own */
  10130. cert->maxIdx = inSz; /* can't go over this index */
  10131. cert->heap = heap;
  10132. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  10133. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  10134. #ifdef WOLFSSL_CERT_NAME_ALL
  10135. cert->subjectNEnc = CTC_UTF8;
  10136. cert->subjectIEnc = CTC_UTF8;
  10137. cert->subjectDNQEnc = CTC_UTF8;
  10138. cert->subjectGNEnc = CTC_UTF8;
  10139. #endif
  10140. cert->subjectSNEnc = CTC_UTF8;
  10141. cert->subjectCEnc = CTC_PRINTABLE;
  10142. cert->subjectLEnc = CTC_UTF8;
  10143. cert->subjectSTEnc = CTC_UTF8;
  10144. cert->subjectOEnc = CTC_UTF8;
  10145. cert->subjectOUEnc = CTC_UTF8;
  10146. #ifdef WOLFSSL_HAVE_ISSUER_NAMES
  10147. cert->issuerSNEnc = CTC_UTF8;
  10148. cert->issuerCEnc = CTC_PRINTABLE;
  10149. cert->issuerLEnc = CTC_UTF8;
  10150. cert->issuerSTEnc = CTC_UTF8;
  10151. cert->issuerOEnc = CTC_UTF8;
  10152. cert->issuerOUEnc = CTC_UTF8;
  10153. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  10154. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  10155. InitSignatureCtx(&cert->sigCtx, heap, devId);
  10156. }
  10157. }
  10158. void wc_InitDecodedCert(DecodedCert* cert, const byte* source, word32 inSz,
  10159. void* heap)
  10160. {
  10161. InitDecodedCert(cert, source, inSz, heap);
  10162. }
  10163. /* Free the alternative names object.
  10164. *
  10165. * Frees each linked list items and its name.
  10166. *
  10167. * @param [in, out] altNames Alternative names.
  10168. * @param [in] heap Dynamic memory hint.
  10169. */
  10170. void FreeAltNames(DNS_entry* altNames, void* heap)
  10171. {
  10172. (void)heap;
  10173. while (altNames) {
  10174. DNS_entry* tmp = altNames->next;
  10175. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  10176. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  10177. XFREE(altNames->ipString, heap, DYNAMIC_TYPE_ALTNAME);
  10178. #endif
  10179. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  10180. altNames = tmp;
  10181. }
  10182. }
  10183. /* malloc and initialize a new alt name structure */
  10184. DNS_entry* AltNameNew(void* heap)
  10185. {
  10186. DNS_entry* ret;
  10187. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  10188. if (ret != NULL) {
  10189. XMEMSET(ret, 0, sizeof(DNS_entry));
  10190. }
  10191. (void)heap;
  10192. return ret;
  10193. }
  10194. #ifndef IGNORE_NAME_CONSTRAINTS
  10195. /* Free the subtree names object.
  10196. *
  10197. * Frees each linked list items and its name.
  10198. *
  10199. * @param [in, out] names Subtree names.
  10200. * @param [in] heap Dynamic memory hint.
  10201. */
  10202. void FreeNameSubtrees(Base_entry* names, void* heap)
  10203. {
  10204. (void)heap;
  10205. while (names) {
  10206. Base_entry* tmp = names->next;
  10207. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  10208. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  10209. names = tmp;
  10210. }
  10211. }
  10212. #endif /* IGNORE_NAME_CONSTRAINTS */
  10213. /* Free the decoded cert object's dynamic data.
  10214. *
  10215. * @param [in, out] cert Decoded certificate object.
  10216. */
  10217. void FreeDecodedCert(DecodedCert* cert)
  10218. {
  10219. if (cert == NULL)
  10220. return;
  10221. if (cert->subjectCNStored == 1) {
  10222. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  10223. }
  10224. if (cert->pubKeyStored == 1) {
  10225. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10226. }
  10227. if (cert->weOwnAltNames && cert->altNames)
  10228. FreeAltNames(cert->altNames, cert->heap);
  10229. #ifndef IGNORE_NAME_CONSTRAINTS
  10230. if (cert->altEmailNames)
  10231. FreeAltNames(cert->altEmailNames, cert->heap);
  10232. if (cert->altDirNames)
  10233. FreeAltNames(cert->altDirNames, cert->heap);
  10234. if (cert->permittedNames)
  10235. FreeNameSubtrees(cert->permittedNames, cert->heap);
  10236. if (cert->excludedNames)
  10237. FreeNameSubtrees(cert->excludedNames, cert->heap);
  10238. #endif /* IGNORE_NAME_CONSTRAINTS */
  10239. #ifdef WOLFSSL_SEP
  10240. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10241. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10242. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  10243. #endif /* WOLFSSL_SEP */
  10244. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10245. if (cert->issuerName != NULL)
  10246. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  10247. if (cert->subjectName != NULL)
  10248. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  10249. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10250. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10251. if (cert->sce_tsip_encRsaKeyIdx != NULL)
  10252. XFREE(cert->sce_tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  10253. #endif
  10254. FreeSignatureCtx(&cert->sigCtx);
  10255. }
  10256. void wc_FreeDecodedCert(DecodedCert* cert)
  10257. {
  10258. FreeDecodedCert(cert);
  10259. }
  10260. #ifndef WOLFSSL_ASN_TEMPLATE
  10261. static int GetCertHeader(DecodedCert* cert)
  10262. {
  10263. int ret = 0, len;
  10264. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10265. return ASN_PARSE_E;
  10266. /* Reset the max index for the size indicated in the outer wrapper. */
  10267. cert->maxIdx = (word32)len + cert->srcIdx;
  10268. cert->certBegin = cert->srcIdx;
  10269. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  10270. return ASN_PARSE_E;
  10271. cert->sigIndex = (word32)len + cert->srcIdx;
  10272. if (cert->sigIndex > cert->maxIdx)
  10273. return ASN_PARSE_E;
  10274. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  10275. cert->sigIndex) < 0)
  10276. return ASN_PARSE_E;
  10277. if (wc_GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  10278. &cert->serialSz, cert->sigIndex) < 0)
  10279. return ASN_PARSE_E;
  10280. return ret;
  10281. }
  10282. #endif
  10283. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || (defined(HAVE_PQC) && \
  10284. defined(HAVE_LIBOQS))
  10285. /* Store the key data under the BIT_STRING in dynamicly allocated data.
  10286. *
  10287. * @param [in, out] cert Certificate object.
  10288. * @param [in] source Buffer containing encoded key.
  10289. * @param [in, out] srcIdx On in, start of key data.
  10290. * On out, start of element after key data.
  10291. * @param [in] maxIdx Maximum index of certificate data.
  10292. */
  10293. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10294. word32 maxIdx)
  10295. {
  10296. int ret;
  10297. int length;
  10298. byte* publicKey;
  10299. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10300. if (ret == 0) {
  10301. #ifdef HAVE_OCSP
  10302. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10303. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10304. }
  10305. if (ret == 0) {
  10306. #endif
  10307. publicKey = (byte*)XMALLOC((size_t)length, cert->heap,
  10308. DYNAMIC_TYPE_PUBLIC_KEY);
  10309. if (publicKey == NULL) {
  10310. ret = MEMORY_E;
  10311. }
  10312. else {
  10313. XMEMCPY(publicKey, &source[*srcIdx], (size_t)length);
  10314. cert->publicKey = publicKey;
  10315. cert->pubKeyStored = 1;
  10316. cert->pubKeySize = (word32)length;
  10317. *srcIdx += (word32)length;
  10318. }
  10319. }
  10320. return ret;
  10321. }
  10322. #endif /* HAVE_ED25519 || HAVE_ED448 */
  10323. #endif
  10324. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10325. static int SetCurve(ecc_key* key, byte* output, size_t outSz)
  10326. {
  10327. #ifdef HAVE_OID_ENCODING
  10328. int ret;
  10329. #endif
  10330. int idx;
  10331. word32 oidSz = 0;
  10332. /* validate key */
  10333. if (key == NULL || key->dp == NULL) {
  10334. return BAD_FUNC_ARG;
  10335. }
  10336. #ifdef HAVE_OID_ENCODING
  10337. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  10338. if (ret != 0) {
  10339. return ret;
  10340. }
  10341. #else
  10342. oidSz = key->dp->oidSz;
  10343. #endif
  10344. idx = SetObjectId((int)oidSz, output);
  10345. /* length only */
  10346. if (output == NULL) {
  10347. return idx + (int)oidSz;
  10348. }
  10349. /* verify output buffer has room */
  10350. if (oidSz > outSz)
  10351. return BUFFER_E;
  10352. #ifdef HAVE_OID_ENCODING
  10353. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  10354. if (ret != 0) {
  10355. return ret;
  10356. }
  10357. #else
  10358. XMEMCPY(output+idx, key->dp->oid, oidSz);
  10359. #endif
  10360. idx += (int)oidSz;
  10361. return idx;
  10362. }
  10363. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10364. #ifdef HAVE_ECC
  10365. #ifdef WOLFSSL_ASN_TEMPLATE
  10366. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  10367. * RFC 5480, 2 - Subject Public Key Information Fields
  10368. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10369. * X9.62 ECC point format.
  10370. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  10371. */
  10372. static const ASNItem eccPublicKeyASN[] = {
  10373. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10374. /* AlgorithmIdentifier */
  10375. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10376. /* algorithm */
  10377. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  10378. /* namedCurve */
  10379. /* ALGOID_CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  10380. /* specifiedCurve - explicit parameters */
  10381. /* ALGOID_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  10382. /* Public Key */
  10383. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10384. };
  10385. enum {
  10386. ECCPUBLICKEYASN_IDX_SEQ = 0,
  10387. ECCPUBLICKEYASN_IDX_ALGOID_SEQ,
  10388. ECCPUBLICKEYASN_IDX_ALGOID_OID,
  10389. ECCPUBLICKEYASN_IDX_ALGOID_CURVEID,
  10390. ECCPUBLICKEYASN_IDX_ALGOID_PARAMS,
  10391. ECCPUBLICKEYASN_IDX_PUBKEY
  10392. };
  10393. /* Number of items in ASN.1 template for ECC public key. */
  10394. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  10395. #endif /* WOLFSSL_ASN_TEMPLATE */
  10396. #endif /* HAVE_ECC */
  10397. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10398. /* Encode public ECC key in DER format.
  10399. *
  10400. * RFC 5480, 2 - Subject Public Key Information Fields
  10401. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  10402. * X9.62 ECC point format.
  10403. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  10404. *
  10405. * @param [out] output Buffer to put encoded data in.
  10406. * @param [in] key ECC key object.
  10407. * @param [in] outLen Size of buffer in bytes.
  10408. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  10409. * @return Size of encoded data in bytes on success.
  10410. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10411. * @return MEMORY_E when dynamic memory allocation failed.
  10412. */
  10413. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  10414. int with_header, int comp)
  10415. {
  10416. #ifndef WOLFSSL_ASN_TEMPLATE
  10417. int ret;
  10418. word32 idx = 0, curveSz, algoSz, pubSz, bitStringSz;
  10419. byte bitString[1 + MAX_LENGTH_SZ + 1]; /* 6 */
  10420. byte algo[MAX_ALGO_SZ]; /* 20 */
  10421. /* public size */
  10422. pubSz = key->dp ? (word32)key->dp->size : MAX_ECC_BYTES;
  10423. if (comp)
  10424. pubSz = 1 + pubSz;
  10425. else
  10426. pubSz = 1 + 2 * pubSz;
  10427. /* check for buffer overflow */
  10428. if (output != NULL && pubSz > (word32)outLen) {
  10429. return BUFFER_E;
  10430. }
  10431. /* headers */
  10432. if (with_header) {
  10433. ret = SetCurve(key, NULL, 0);
  10434. if (ret <= 0) {
  10435. return ret;
  10436. }
  10437. curveSz = (word32)ret;
  10438. ret = 0;
  10439. /* calculate size */
  10440. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, (int)curveSz);
  10441. bitStringSz = SetBitString(pubSz, 0, bitString);
  10442. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, NULL);
  10443. /* check for buffer overflow */
  10444. if (output != NULL &&
  10445. curveSz + algoSz + bitStringSz + idx + pubSz > (word32)outLen) {
  10446. return BUFFER_E;
  10447. }
  10448. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz,
  10449. output);
  10450. /* algo */
  10451. if (output)
  10452. XMEMCPY(output + idx, algo, algoSz);
  10453. idx += algoSz;
  10454. /* curve */
  10455. if (output)
  10456. (void)SetCurve(key, output + idx, curveSz);
  10457. idx += curveSz;
  10458. /* bit string */
  10459. if (output)
  10460. XMEMCPY(output + idx, bitString, bitStringSz);
  10461. idx += bitStringSz;
  10462. }
  10463. /* pub */
  10464. if (output) {
  10465. PRIVATE_KEY_UNLOCK();
  10466. ret = wc_ecc_export_x963_ex(key, output + idx, &pubSz, comp);
  10467. PRIVATE_KEY_LOCK();
  10468. if (ret != 0) {
  10469. return ret;
  10470. }
  10471. }
  10472. idx += pubSz;
  10473. return (int)idx;
  10474. #else
  10475. word32 pubSz = 0;
  10476. int sz = 0;
  10477. int ret = 0;
  10478. int curveIdSz = 0;
  10479. byte* curveOid = NULL;
  10480. /* Check key validity. */
  10481. if ((key == NULL) || (key->dp == NULL)) {
  10482. ret = BAD_FUNC_ARG;
  10483. }
  10484. if (ret == 0) {
  10485. /* Calculate the size of the encoded public point. */
  10486. PRIVATE_KEY_UNLOCK();
  10487. #if defined(HAVE_COMP_KEY) && defined(HAVE_FIPS) && \
  10488. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  10489. /* in earlier versions of FIPS the get length functionality is not
  10490. * available with compressed keys */
  10491. pubSz = key->dp ? key->dp->size : MAX_ECC_BYTES;
  10492. if (comp)
  10493. pubSz = 1 + pubSz;
  10494. else
  10495. pubSz = 1 + 2 * pubSz;
  10496. ret = LENGTH_ONLY_E;
  10497. #else
  10498. ret = wc_ecc_export_x963_ex(key, NULL, &pubSz, comp);
  10499. #endif
  10500. PRIVATE_KEY_LOCK();
  10501. /* LENGTH_ONLY_E on success. */
  10502. if (ret == LENGTH_ONLY_E) {
  10503. ret = 0;
  10504. }
  10505. }
  10506. if ((ret == 0) && with_header) {
  10507. /* Including SubjectPublicKeyInfo header. */
  10508. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  10509. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  10510. /* Get the length of the named curve OID to put into the encoding. */
  10511. curveIdSz = SetCurve(key, NULL, 0);
  10512. if (curveIdSz < 0) {
  10513. ret = curveIdSz;
  10514. }
  10515. if (ret == 0) {
  10516. /* Set the key type OID. */
  10517. SetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], ECDSAk,
  10518. oidKeyType);
  10519. /* Set the curve OID. */
  10520. SetASN_ReplaceBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID],
  10521. NULL, (word32)curveIdSz);
  10522. /* Don't try to write out explicit parameters. */
  10523. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_PARAMS].noOut = 1;
  10524. /* Set size of public point to ensure space is made for it. */
  10525. SetASN_Buffer(&dataASN[ECCPUBLICKEYASN_IDX_PUBKEY], NULL, pubSz);
  10526. /* Calculate size of ECC public key. */
  10527. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  10528. eccPublicKeyASN_Length, &sz);
  10529. }
  10530. /* Check buffer, if passed in, is big enough for encoded data. */
  10531. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  10532. ret = BUFFER_E;
  10533. }
  10534. if ((ret == 0) && (output != NULL)) {
  10535. /* Encode ECC public key. */
  10536. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  10537. output);
  10538. /* Skip to where public point is to be encoded. */
  10539. output += sz - (int)pubSz;
  10540. /* Cache the location to place the name curve OID. */
  10541. curveOid = (byte*)
  10542. dataASN[ECCPUBLICKEYASN_IDX_ALGOID_CURVEID].data.buffer.data;
  10543. }
  10544. FREE_ASNSETDATA(dataASN, key->heap);
  10545. }
  10546. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  10547. ret = BUFFER_E;
  10548. }
  10549. else {
  10550. /* Total size is the public point size. */
  10551. sz = (int)pubSz;
  10552. }
  10553. if ((ret == 0) && (output != NULL)) {
  10554. /* Put named curve OID data into encoding. */
  10555. curveIdSz = SetCurve(key, curveOid, (size_t)curveIdSz);
  10556. if (curveIdSz < 0) {
  10557. ret = curveIdSz;
  10558. }
  10559. }
  10560. if ((ret == 0) && (output != NULL)) {
  10561. /* Encode public point. */
  10562. PRIVATE_KEY_UNLOCK();
  10563. ret = wc_ecc_export_x963_ex(key, output, &pubSz, comp);
  10564. PRIVATE_KEY_LOCK();
  10565. }
  10566. if (ret == 0) {
  10567. /* Return the size of the encoding. */
  10568. ret = sz;
  10569. }
  10570. return ret;
  10571. #endif
  10572. }
  10573. /* Encode the public part of an ECC key in a DER.
  10574. *
  10575. * Pass NULL for output to get the size of the encoding.
  10576. *
  10577. * @param [in] key ECC key object.
  10578. * @param [out] output Buffer to hold DER encoding.
  10579. * @param [in] inLen Size of buffer in bytes.
  10580. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  10581. * @return Size of encoded data in bytes on success.
  10582. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  10583. * @return MEMORY_E when dynamic memory allocation failed.
  10584. */
  10585. WOLFSSL_ABI
  10586. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  10587. int with_AlgCurve)
  10588. {
  10589. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, 0);
  10590. }
  10591. int wc_EccPublicKeyToDer_ex(ecc_key* key, byte* output, word32 inLen,
  10592. int with_AlgCurve, int comp)
  10593. {
  10594. return SetEccPublicKey(output, key, (int)inLen, with_AlgCurve, comp);
  10595. }
  10596. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  10597. {
  10598. return SetEccPublicKey(NULL, key, 0, with_AlgCurve, 0);
  10599. }
  10600. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10601. #ifdef WOLFSSL_ASN_TEMPLATE
  10602. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  10603. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  10604. * RFC 8410, 4 - Subject Public Key Fields
  10605. */
  10606. static const ASNItem edPubKeyASN[] = {
  10607. /* SubjectPublicKeyInfo */
  10608. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  10609. /* AlgorithmIdentifier */
  10610. /* ALGOID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  10611. /* Ed25519/Ed448 OID */
  10612. /* ALGOID_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  10613. /* Public key stream */
  10614. /* PUBKEY */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  10615. };
  10616. enum {
  10617. EDPUBKEYASN_IDX_SEQ = 0,
  10618. EDPUBKEYASN_IDX_ALGOID_SEQ,
  10619. EDPUBKEYASN_IDX_ALGOID_OID,
  10620. EDPUBKEYASN_IDX_PUBKEY
  10621. };
  10622. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  10623. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  10624. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  10625. #endif /* WOLFSSL_ASN_TEMPLATE */
  10626. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  10627. /* Build ASN.1 formatted public key based on RFC 8410
  10628. *
  10629. * Pass NULL for output to get the size of the encoding.
  10630. *
  10631. * @param [in] pubKey public key buffer
  10632. * @param [in] pubKeyLen public ket buffer length
  10633. * @param [out] output Buffer to put encoded data in (optional)
  10634. * @param [in] outLen Size of buffer in bytes
  10635. * @param [in] keyType is "enum Key_Sum" like ED25519k
  10636. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  10637. * @return Size of encoded data in bytes on success
  10638. * @return BAD_FUNC_ARG when key is NULL.
  10639. * @return MEMORY_E when dynamic memory allocation failed.
  10640. */
  10641. int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  10642. byte* output, word32 outLen, int keyType, int withHeader)
  10643. {
  10644. int ret = 0;
  10645. #ifndef WOLFSSL_ASN_TEMPLATE
  10646. word32 idx = 0;
  10647. word32 seqDataSz = 0;
  10648. word32 sz;
  10649. #else
  10650. int sz = 0;
  10651. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  10652. #endif
  10653. if (pubKey == NULL) {
  10654. return BAD_FUNC_ARG;
  10655. }
  10656. #ifndef WOLFSSL_ASN_TEMPLATE
  10657. /* calculate size */
  10658. if (withHeader) {
  10659. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  10660. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  10661. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  10662. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  10663. }
  10664. else {
  10665. sz = pubKeyLen;
  10666. }
  10667. /* checkout output size */
  10668. if (output != NULL && sz > outLen) {
  10669. ret = BUFFER_E;
  10670. }
  10671. /* headers */
  10672. if (ret == 0 && output != NULL && withHeader) {
  10673. /* sequence */
  10674. idx = SetSequence(seqDataSz, output);
  10675. /* algo */
  10676. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  10677. /* bit string */
  10678. idx += SetBitString(pubKeyLen, 0, output + idx);
  10679. }
  10680. if (ret == 0 && output != NULL) {
  10681. /* pub */
  10682. XMEMCPY(output + idx, pubKey, pubKeyLen);
  10683. idx += pubKeyLen;
  10684. sz = idx;
  10685. }
  10686. if (ret == 0) {
  10687. ret = (int)sz;
  10688. }
  10689. #else
  10690. if (withHeader) {
  10691. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  10692. if (ret == 0) {
  10693. /* Set the OID. */
  10694. SetASN_OID(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], (word32)keyType,
  10695. oidKeyType);
  10696. /* Leave space for public point. */
  10697. SetASN_Buffer(&dataASN[EDPUBKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  10698. /* Calculate size of public key encoding. */
  10699. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  10700. }
  10701. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  10702. ret = BUFFER_E;
  10703. }
  10704. if ((ret == 0) && (output != NULL)) {
  10705. /* Encode public key. */
  10706. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  10707. /* Set location to encode public point. */
  10708. output = (byte*)dataASN[EDPUBKEYASN_IDX_PUBKEY].data.buffer.data;
  10709. }
  10710. FREE_ASNSETDATA(dataASN, NULL);
  10711. }
  10712. else if ((output != NULL) && (pubKeyLen > outLen)) {
  10713. ret = BUFFER_E;
  10714. }
  10715. else if (ret == 0) {
  10716. sz = (int)pubKeyLen;
  10717. }
  10718. if ((ret == 0) && (output != NULL)) {
  10719. /* Put public key into space provided. */
  10720. XMEMCPY(output, pubKey, pubKeyLen);
  10721. }
  10722. if (ret == 0) {
  10723. ret = sz;
  10724. }
  10725. #endif /* WOLFSSL_ASN_TEMPLATE */
  10726. return ret;
  10727. }
  10728. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  10729. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  10730. /* Encode the public part of an Ed25519 key in DER.
  10731. *
  10732. * Pass NULL for output to get the size of the encoding.
  10733. *
  10734. * @param [in] key Ed25519 key object.
  10735. * @param [out] output Buffer to put encoded data in.
  10736. * @param [in] outLen Size of buffer in bytes.
  10737. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10738. * @return Size of encoded data in bytes on success.
  10739. * @return BAD_FUNC_ARG when key is NULL.
  10740. * @return MEMORY_E when dynamic memory allocation failed.
  10741. */
  10742. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  10743. int withAlg)
  10744. {
  10745. int ret;
  10746. byte pubKey[ED25519_PUB_KEY_SIZE];
  10747. word32 pubKeyLen = (word32)sizeof(pubKey);
  10748. if (key == NULL) {
  10749. return BAD_FUNC_ARG;
  10750. }
  10751. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  10752. if (ret == 0) {
  10753. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10754. ED25519k, withAlg);
  10755. }
  10756. return ret;
  10757. }
  10758. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  10759. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  10760. /* Encode the public part of an Ed448 key in DER.
  10761. *
  10762. * Pass NULL for output to get the size of the encoding.
  10763. *
  10764. * @param [in] key Ed448 key object.
  10765. * @param [out] output Buffer to put encoded data in.
  10766. * @param [in] outLen Size of buffer in bytes.
  10767. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  10768. * @return Size of encoded data in bytes on success.
  10769. * @return BAD_FUNC_ARG when key is NULL.
  10770. * @return MEMORY_E when dynamic memory allocation failed.
  10771. */
  10772. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  10773. int withAlg)
  10774. {
  10775. int ret;
  10776. byte pubKey[ED448_PUB_KEY_SIZE];
  10777. word32 pubKeyLen = (word32)sizeof(pubKey);
  10778. if (key == NULL) {
  10779. return BAD_FUNC_ARG;
  10780. }
  10781. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  10782. if (ret == 0) {
  10783. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  10784. ED448k, withAlg);
  10785. }
  10786. return ret;
  10787. }
  10788. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  10789. #if !defined(NO_RSA) && !defined(NO_CERTS)
  10790. #ifdef WOLFSSL_ASN_TEMPLATE
  10791. /* ASN.1 template for header before RSA key in certificate. */
  10792. static const ASNItem rsaCertKeyASN[] = {
  10793. /* STR */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  10794. /* SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  10795. };
  10796. enum {
  10797. RSACERTKEYASN_IDX_STR = 0,
  10798. RSACERTKEYASN_IDX_SEQ
  10799. };
  10800. /* Number of items in ASN.1 template for header before RSA key in cert. */
  10801. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  10802. #endif
  10803. /* Store RSA key pointer and length in certificate object.
  10804. *
  10805. * @param [in, out] cert Certificate object.
  10806. * @param [in] source Buffer containing encoded key.
  10807. * @param [in, out] srcIdx On in, start of RSA key data.
  10808. * On out, start of element after RSA key data.
  10809. * @param [in] maxIdx Maximum index of key data.
  10810. * @return 0 on success.
  10811. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10812. * is invalid.
  10813. * @return BUFFER_E when data in buffer is too small.
  10814. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10815. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10816. * non-zero length.
  10817. */
  10818. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10819. word32 maxIdx)
  10820. {
  10821. #ifndef WOLFSSL_ASN_TEMPLATE
  10822. int length;
  10823. int pubLen;
  10824. word32 pubIdx;
  10825. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  10826. return ASN_PARSE_E;
  10827. pubIdx = *srcIdx;
  10828. if (GetSequence(source, srcIdx, &length, pubIdx + (word32)pubLen) < 0)
  10829. return ASN_PARSE_E;
  10830. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10831. cert->sigCtx.CertAtt.pubkey_n_start =
  10832. cert->sigCtx.CertAtt.pubkey_e_start = pubIdx;
  10833. #endif
  10834. cert->pubKeySize = (word32)pubLen;
  10835. cert->publicKey = source + pubIdx;
  10836. #ifdef WOLFSSL_MAXQ10XX_TLS
  10837. cert->publicKeyIndex = pubIdx;
  10838. #endif
  10839. *srcIdx += (word32)length;
  10840. #ifdef HAVE_OCSP
  10841. return CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10842. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10843. #else
  10844. return 0;
  10845. #endif
  10846. #else
  10847. ASNGetData dataASN[rsaCertKeyASN_Length];
  10848. int ret;
  10849. /* No dynamic data. */
  10850. XMEMSET(dataASN, 0, sizeof(dataASN));
  10851. /* Decode the header before the key data. */
  10852. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  10853. srcIdx, maxIdx);
  10854. if (ret == 0) {
  10855. /* Store the pointer and length in certificate object starting at
  10856. * SEQUENCE. */
  10857. GetASN_GetConstRef(&dataASN[RSACERTKEYASN_IDX_STR],
  10858. &cert->publicKey, &cert->pubKeySize);
  10859. #ifdef WOLFSSL_MAXQ10XX_TLS
  10860. cert->publicKeyIndex = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10861. #endif
  10862. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  10863. /* Start of SEQUENCE. */
  10864. cert->sigCtx.CertAtt.pubkey_n_start =
  10865. cert->sigCtx.CertAtt.pubkey_e_start = dataASN[RSACERTKEYASN_IDX_SEQ].offset;
  10866. #endif
  10867. #ifdef HAVE_OCSP
  10868. /* Calculate the hash of the public key for OCSP. */
  10869. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  10870. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10871. #endif
  10872. }
  10873. return ret;
  10874. #endif /* WOLFSSL_ASN_TEMPLATE */
  10875. }
  10876. #endif /* !NO_RSA && !NO_CERTS */
  10877. #if defined(HAVE_ECC) && !defined(NO_CERTS)
  10878. #ifdef WOLFSSL_ASN_TEMPLATE
  10879. /* ASN.1 template for header before ECC key in certificate. */
  10880. static const ASNItem eccCertKeyASN[] = {
  10881. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  10882. /* Algo parameters */
  10883. /* PARAMS */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  10884. /* Subject public key */
  10885. /* SUBJPUBKEY */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  10886. };
  10887. enum {
  10888. ECCCERTKEYASN_IDX_OID = 0,
  10889. ECCCERTKEYASN_IDX_PARAMS,
  10890. ECCCERTKEYASN_IDX_SUBJPUBKEY
  10891. };
  10892. /* Number of items in ASN.1 template for header before ECC key in cert. */
  10893. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  10894. #endif /* WOLFSSL_ASN_TEMPLATE */
  10895. /* Store public ECC key in certificate object.
  10896. *
  10897. * Parse parameters and store public key data.
  10898. *
  10899. * @param [in, out] cert Certificate object.
  10900. * @param [in] source Buffer containing encoded key.
  10901. * @param [in, out] srcIdx On in, start of ECC key data.
  10902. * On out, start of element after ECC key data.
  10903. * @param [in] maxIdx Maximum index of key data.
  10904. * @param [in] pubKey Buffer holding encoded public key.
  10905. * @param [in] pubKeyLen Length of encoded public key in bytes.
  10906. * @return 0 on success.
  10907. * @return BAD_FUNC_ARG when pubKey is NULL.
  10908. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10909. * is invalid.
  10910. * @return BUFFER_E when data in buffer is too small.
  10911. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10912. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  10913. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  10914. * non-zero length.
  10915. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10916. */
  10917. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  10918. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  10919. {
  10920. #ifndef WOLFSSL_ASN_TEMPLATE
  10921. int ret;
  10922. word32 localIdx;
  10923. byte* publicKey;
  10924. byte tag;
  10925. int length;
  10926. if (pubKey == NULL) {
  10927. return BAD_FUNC_ARG;
  10928. }
  10929. localIdx = *srcIdx;
  10930. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  10931. return ASN_PARSE_E;
  10932. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  10933. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  10934. maxIdx) < 0)
  10935. return ASN_PARSE_E;
  10936. if ((ret = CheckCurve(cert->pkCurveOID)) < 0)
  10937. return ECC_CURVE_OID_E;
  10938. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10939. cert->sigCtx.CertAtt.curve_id = ret;
  10940. #else
  10941. (void)ret;
  10942. #endif
  10943. /* key header */
  10944. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  10945. if (ret != 0)
  10946. return ret;
  10947. #if defined(WOLFSSL_RENESAS_SCEPROTECT) || defined(WOLFSSL_RENESAS_TSIP_TLS)
  10948. cert->sigCtx.CertAtt.pubkey_n_start =
  10949. cert->sigCtx.CertAtt.pubkey_e_start = (*srcIdx + 1);
  10950. cert->sigCtx.CertAtt.pubkey_n_len = ((length - 1) >> 1);
  10951. cert->sigCtx.CertAtt.pubkey_e_start +=
  10952. cert->sigCtx.CertAtt.pubkey_n_len;
  10953. cert->sigCtx.CertAtt.pubkey_e_len =
  10954. cert->sigCtx.CertAtt.pubkey_n_len;
  10955. #endif
  10956. #ifdef WOLFSSL_MAXQ10XX_TLS
  10957. cert->publicKeyIndex = *srcIdx + 1;
  10958. #endif
  10959. #ifdef HAVE_OCSP
  10960. ret = CalcHashId_ex(source + *srcIdx, (word32)length,
  10961. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  10962. if (ret != 0)
  10963. return ret;
  10964. #endif
  10965. *srcIdx += (word32)length;
  10966. }
  10967. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  10968. if (publicKey == NULL)
  10969. return MEMORY_E;
  10970. XMEMCPY(publicKey, pubKey, pubKeyLen);
  10971. cert->publicKey = publicKey;
  10972. cert->pubKeyStored = 1;
  10973. cert->pubKeySize = pubKeyLen;
  10974. return 0;
  10975. #else
  10976. int ret = 0;
  10977. DECL_ASNGETDATA(dataASN, eccCertKeyASN_Length);
  10978. byte* publicKey;
  10979. /* Validate parameters. */
  10980. if (pubKey == NULL) {
  10981. ret = BAD_FUNC_ARG;
  10982. }
  10983. /* Clear dynamic data and check OID is a curve. */
  10984. CALLOC_ASNGETDATA(dataASN, eccCertKeyASN_Length, ret, cert->heap);
  10985. if (ret == 0) {
  10986. GetASN_OID(&dataASN[ECCCERTKEYASN_IDX_OID], oidCurveType);
  10987. /* Parse ECC public key header. */
  10988. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1,
  10989. source, srcIdx, maxIdx);
  10990. }
  10991. if (ret == 0) {
  10992. if (dataASN[ECCCERTKEYASN_IDX_OID].tag != 0) {
  10993. /* Store curve OID. */
  10994. cert->pkCurveOID = dataASN[ECCCERTKEYASN_IDX_OID].data.oid.sum;
  10995. }
  10996. /* Ignore explicit parameters. */
  10997. #ifdef WOLFSSL_MAXQ10XX_TLS
  10998. cert->publicKeyIndex =
  10999. GetASNItem_DataIdx(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY], source)
  11000. + 1;
  11001. #endif
  11002. #ifdef HAVE_OCSP
  11003. /* Calculate the hash of the subject public key for OCSP. */
  11004. ret = CalcHashId_ex(dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.data,
  11005. dataASN[ECCCERTKEYASN_IDX_SUBJPUBKEY].data.ref.length,
  11006. cert->subjectKeyHash, HashIdAlg(cert->signatureOID));
  11007. }
  11008. if (ret == 0) {
  11009. #endif
  11010. /* Store public key data length. */
  11011. cert->pubKeySize = pubKeyLen;
  11012. /* Must allocated space for key.
  11013. * Don't memcpy into constant pointer so use temp. */
  11014. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  11015. DYNAMIC_TYPE_PUBLIC_KEY);
  11016. if (publicKey == NULL) {
  11017. ret = MEMORY_E;
  11018. }
  11019. else {
  11020. /* Copy in whole public key and store pointer. */
  11021. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  11022. cert->publicKey = publicKey;
  11023. /* Indicate publicKey needs to be freed. */
  11024. cert->pubKeyStored = 1;
  11025. }
  11026. }
  11027. FREE_ASNGETDATA(dataASN, cert->heap);
  11028. return ret;
  11029. #endif /* WOLFSSL_ASN_TEMPLATE */
  11030. }
  11031. #endif /* HAVE_ECC && !NO_CERTS */
  11032. #ifndef NO_CERTS
  11033. #if !defined(NO_DSA)
  11034. #ifdef WOLFSSL_ASN_TEMPLATE
  11035. /* ASN.1 template for DSA key in certificate.
  11036. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  11037. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  11038. */
  11039. static const ASNItem dsaCertKeyASN[] = {
  11040. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  11041. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11042. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11043. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  11044. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  11045. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  11046. };
  11047. /* Number of items in ASN.1 template for DSA key in certificate. */
  11048. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  11049. #endif /* WOLFSSL_ASN_TEMPLATE */
  11050. /* Parse DSA parameters to ensure valid.
  11051. *
  11052. * @param [in] source Buffer containing encoded key.
  11053. * @param [in, out] srcIdx On in, start of DSA key data.
  11054. * On out, start of element after DSA key data.
  11055. * @param [in] maxIdx Maximum index of key data.
  11056. * @param [in] heap Dynamic memory hint.
  11057. * @return 0 on success.
  11058. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11059. * is invalid.
  11060. * @return BUFFER_E when data in buffer is too small.
  11061. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11062. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  11063. * non-zero length.
  11064. */
  11065. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  11066. void* heap)
  11067. {
  11068. #ifndef WOLFSSL_ASN_TEMPLATE
  11069. int ret;
  11070. int length;
  11071. (void)heap;
  11072. ret = GetSequence(source, srcIdx, &length, maxIdx);
  11073. if (ret < 0)
  11074. return ret;
  11075. ret = SkipInt(source, srcIdx, maxIdx);
  11076. if (ret != 0)
  11077. return ret;
  11078. ret = SkipInt(source, srcIdx, maxIdx);
  11079. if (ret != 0)
  11080. return ret;
  11081. ret = SkipInt(source, srcIdx, maxIdx);
  11082. if (ret != 0)
  11083. return ret;
  11084. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  11085. if (ret != 0)
  11086. return ret;
  11087. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  11088. if (ret != 0)
  11089. return ASN_PARSE_E;
  11090. *srcIdx += (word32)length;
  11091. return 0;
  11092. #else
  11093. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  11094. int ret = 0;
  11095. (void)heap;
  11096. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  11097. if (ret == 0) {
  11098. /* Parse the DSA key data to ensure valid. */
  11099. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  11100. source, srcIdx, maxIdx);
  11101. }
  11102. FREE_ASNGETDATA(dataASN, heap);
  11103. return ret;
  11104. #endif /* WOLFSSL_ASN_TEMPLATE */
  11105. }
  11106. #endif /* !NO_DSA */
  11107. /* Decode the SubjectPublicKeyInfo block in a certificate.
  11108. *
  11109. * Stores the public key in fields of the certificate object.
  11110. * Validates the BER/DER items and does not store in a key object.
  11111. *
  11112. * @param [in, out] cert Decoded certificate oject.
  11113. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  11114. * @param [in, out] inOutIdx On in, start of public key.
  11115. * On out, start of ASN.1 item after public key.
  11116. * @param [in] maxIdx Maximum index of key data.
  11117. * @return 0 on success.
  11118. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11119. * is invalid.
  11120. * @return BUFFER_E when data in buffer is too small.
  11121. */
  11122. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  11123. word32 maxIdx)
  11124. {
  11125. word32 srcIdx = *inOutIdx;
  11126. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11127. int pubLen;
  11128. #endif
  11129. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11130. int pubIdx = (int)srcIdx;
  11131. #endif
  11132. int ret = 0;
  11133. int length;
  11134. /* Validate paramaters. */
  11135. if (source == NULL) {
  11136. return ASN_PARSE_E;
  11137. }
  11138. #ifndef WOLFSSL_ASN_TEMPLATE
  11139. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  11140. #else
  11141. /* Get SEQUENCE and expect all data to be accounted for. */
  11142. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  11143. #endif
  11144. {
  11145. return ASN_PARSE_E;
  11146. }
  11147. #if defined(HAVE_ECC) || !defined(NO_DSA)
  11148. pubLen = (int)srcIdx - pubIdx + length;
  11149. #endif
  11150. maxIdx = srcIdx + (word32)length;
  11151. /* Decode the algorithm identifier for the key. */
  11152. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  11153. return ASN_PARSE_E;
  11154. }
  11155. (void)length;
  11156. /* Parse each type of public key. */
  11157. switch (cert->keyOID) {
  11158. #ifndef NO_RSA
  11159. #ifdef WC_RSA_PSS
  11160. case RSAPSSk:
  11161. if (srcIdx != maxIdx &&
  11162. source[srcIdx] == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  11163. word32 seqIdx = srcIdx;
  11164. int seqLen;
  11165. /* Not set when -1. */
  11166. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  11167. int mgf = -1;
  11168. int saltLen = 0;
  11169. /* Defaults for sig algorithm parameters. */
  11170. enum wc_HashType sigHash = WC_HASH_TYPE_SHA;
  11171. int sigMgf = WC_MGF1SHA1;
  11172. int sigSaltLen = 20;
  11173. if (GetSequence(source, &srcIdx, &seqLen, maxIdx) < 0) {
  11174. return ASN_PARSE_E;
  11175. }
  11176. /* Get the pubic key parameters. */
  11177. ret = DecodeRsaPssParams(source + seqIdx,
  11178. (word32)seqLen + srcIdx - seqIdx, &hash, &mgf, &saltLen);
  11179. if (ret != 0) {
  11180. return ASN_PARSE_E;
  11181. }
  11182. /* Get the signature parameters. */
  11183. ret = DecodeRsaPssParams(source + cert->sigParamsIndex,
  11184. cert->sigParamsLength, &sigHash, &sigMgf, &sigSaltLen);
  11185. if (ret != 0) {
  11186. return ASN_PARSE_E;
  11187. }
  11188. /* Validated signature params match public key params. */
  11189. if (hash != WC_HASH_TYPE_NONE && hash != sigHash) {
  11190. WOLFSSL_MSG("RSA PSS: hash not matching signature hash");
  11191. return ASN_PARSE_E;
  11192. }
  11193. if (mgf != -1 && mgf != sigMgf) {
  11194. WOLFSSL_MSG("RSA PSS: MGF not matching signature MGF");
  11195. return ASN_PARSE_E;
  11196. }
  11197. if (saltLen > sigSaltLen) {
  11198. WOLFSSL_MSG("RSA PSS: sig salt length too small");
  11199. return ASN_PARSE_E;
  11200. }
  11201. srcIdx += (word32)seqLen;
  11202. }
  11203. FALL_THROUGH;
  11204. #endif /* WC_RSA_PSS */
  11205. case RSAk:
  11206. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  11207. break;
  11208. #endif /* NO_RSA */
  11209. #ifdef HAVE_ECC
  11210. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11211. case SM2k:
  11212. #endif
  11213. case ECDSAk:
  11214. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  11215. (word32)pubLen);
  11216. break;
  11217. #endif /* HAVE_ECC */
  11218. #ifdef HAVE_ED25519
  11219. case ED25519k:
  11220. cert->pkCurveOID = ED25519k;
  11221. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11222. break;
  11223. #endif /* HAVE_ED25519 */
  11224. #ifdef HAVE_ED448
  11225. case ED448k:
  11226. cert->pkCurveOID = ED448k;
  11227. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11228. break;
  11229. #endif /* HAVE_ED448 */
  11230. #if defined(HAVE_PQC) && defined(HAVE_LIBOQS)
  11231. #ifdef HAVE_FALCON
  11232. case FALCON_LEVEL1k:
  11233. cert->pkCurveOID = FALCON_LEVEL1k;
  11234. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11235. break;
  11236. case FALCON_LEVEL5k:
  11237. cert->pkCurveOID = FALCON_LEVEL5k;
  11238. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11239. break;
  11240. #endif /* HAVE_FALCON */
  11241. #ifdef HAVE_DILITHIUM
  11242. case DILITHIUM_LEVEL2k:
  11243. cert->pkCurveOID = DILITHIUM_LEVEL2k;
  11244. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11245. break;
  11246. case DILITHIUM_LEVEL3k:
  11247. cert->pkCurveOID = DILITHIUM_LEVEL3k;
  11248. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11249. break;
  11250. case DILITHIUM_LEVEL5k:
  11251. cert->pkCurveOID = DILITHIUM_LEVEL5k;
  11252. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11253. break;
  11254. #endif /* HAVE_DILITHIUM */
  11255. #ifdef HAVE_SPHINCS
  11256. case SPHINCS_FAST_LEVEL1k:
  11257. cert->pkCurveOID = SPHINCS_FAST_LEVEL1k;
  11258. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11259. break;
  11260. case SPHINCS_FAST_LEVEL3k:
  11261. cert->pkCurveOID = SPHINCS_FAST_LEVEL3k;
  11262. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11263. break;
  11264. case SPHINCS_FAST_LEVEL5k:
  11265. cert->pkCurveOID = SPHINCS_FAST_LEVEL5k;
  11266. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11267. break;
  11268. case SPHINCS_SMALL_LEVEL1k:
  11269. cert->pkCurveOID = SPHINCS_SMALL_LEVEL1k;
  11270. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11271. break;
  11272. case SPHINCS_SMALL_LEVEL3k:
  11273. cert->pkCurveOID = SPHINCS_SMALL_LEVEL3k;
  11274. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11275. break;
  11276. case SPHINCS_SMALL_LEVEL5k:
  11277. cert->pkCurveOID = SPHINCS_SMALL_LEVEL5k;
  11278. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  11279. break;
  11280. #endif /* HAVE_SPHINCS */
  11281. #endif /* HAVE_PQC */
  11282. #ifndef NO_DSA
  11283. case DSAk:
  11284. cert->publicKey = source + pubIdx;
  11285. cert->pubKeySize = (word32)pubLen;
  11286. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  11287. break;
  11288. #endif /* NO_DSA */
  11289. default:
  11290. WOLFSSL_MSG("Unknown or not compiled in key OID");
  11291. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  11292. ret = ASN_UNKNOWN_OID_E;
  11293. }
  11294. /* Return index after public key. */
  11295. *inOutIdx = srcIdx;
  11296. /* Return error code. */
  11297. return ret;
  11298. }
  11299. #endif
  11300. /* Return the hash algorithm to use with the signature algorithm.
  11301. *
  11302. * @param [in] oidSum Signature id.
  11303. * @return Hash algorithm id.
  11304. */
  11305. int HashIdAlg(int oidSum)
  11306. {
  11307. (void)oidSum;
  11308. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11309. if (oidSum == CTC_SM3wSM2) {
  11310. return WC_SM3;
  11311. }
  11312. if (oidSum == SM2k) {
  11313. return WC_SM3;
  11314. }
  11315. #endif
  11316. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11317. return WC_SHA256;
  11318. #else
  11319. return WC_SHA;
  11320. #endif
  11321. }
  11322. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11323. *
  11324. * @param [in] data Data to hash.
  11325. * @param [in] len Length of data to hash.
  11326. * @param [out] hash Buffer to hold hash.
  11327. * @return 0 on success.
  11328. * @return MEMORY_E when dynamic memory allocation fails.
  11329. */
  11330. int CalcHashId(const byte* data, word32 len, byte* hash)
  11331. {
  11332. /* Use default hash algorithm. */
  11333. return CalcHashId_ex(data, len, hash,
  11334. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11335. WC_SHA256
  11336. #else
  11337. WC_SHA
  11338. #endif
  11339. );
  11340. }
  11341. /* Calculate hash of the id using the SHA-1 or SHA-256.
  11342. *
  11343. * @param [in] data Data to hash.
  11344. * @param [in] len Length of data to hash.
  11345. * @param [out] hash Buffer to hold hash.
  11346. * @return 0 on success.
  11347. * @return MEMORY_E when dynamic memory allocation fails.
  11348. */
  11349. int CalcHashId_ex(const byte* data, word32 len, byte* hash, int hashAlg)
  11350. {
  11351. int ret;
  11352. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11353. if (hashAlg == WC_SM3) {
  11354. ret = wc_Sm3Hash(data, len, hash);
  11355. }
  11356. else
  11357. #endif
  11358. #if defined(NO_SHA) || (!defined(NO_SHA256) && defined(WC_ASN_HASH_SHA256))
  11359. if (hashAlg == WC_SHA256) {
  11360. ret = wc_Sha256Hash(data, len, hash);
  11361. }
  11362. else
  11363. #elif !defined(NO_SHA)
  11364. if (hashAlg == WC_SHA) {
  11365. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11366. XMEMSET(hash + WC_SHA_DIGEST_SIZE, 0, KEYID_SIZE - WC_SHA_DIGEST_SIZE);
  11367. #endif
  11368. ret = wc_ShaHash(data, len, hash);
  11369. }
  11370. else
  11371. #else
  11372. (void)data;
  11373. (void)len;
  11374. (void)hash;
  11375. #endif
  11376. {
  11377. ret = NOT_COMPILED_IN;
  11378. }
  11379. return ret;
  11380. }
  11381. #ifndef NO_CERTS
  11382. /* Get the hash of the id using the SHA-1 or SHA-256.
  11383. *
  11384. * If the id is not the length of the hash, then hash it.
  11385. *
  11386. * @param [in] id Id to get hash for.
  11387. * @param [in] len Length of id in bytes.
  11388. * @param [out] hash Buffer to hold hash.
  11389. * @return 0 on success.
  11390. * @return MEMORY_E when dynamic memory allocation fails.
  11391. */
  11392. static int GetHashId(const byte* id, int length, byte* hash, int hashAlg)
  11393. {
  11394. int ret;
  11395. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11396. if (length == wc_HashGetDigestSize(wc_HashTypeConvert(hashAlg)))
  11397. #else
  11398. if (length == KEYID_SIZE)
  11399. #endif
  11400. {
  11401. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  11402. XMEMSET(hash + length, 0, KEYID_SIZE - length);
  11403. #endif
  11404. XMEMCPY(hash, id, (size_t)length);
  11405. ret = 0;
  11406. }
  11407. else {
  11408. ret = CalcHashId_ex(id, (word32)length, hash, hashAlg);
  11409. }
  11410. return ret;
  11411. }
  11412. #endif /* !NO_CERTS */
  11413. #ifdef WOLFSSL_ASN_TEMPLATE
  11414. /* Id for email address. */
  11415. #define ASN_EMAIL 0x100
  11416. /* Id for domain component. */
  11417. #define ASN_DC 0x102
  11418. /* Id for jurisdiction country. */
  11419. #define ASN_JURIS_C 0x203
  11420. /* Id for jurisdiction state. */
  11421. #define ASN_JURIS_ST 0x202
  11422. /* Set the string for a name component into the subject name. */
  11423. #define SetCertNameSubject(cert, id, val) \
  11424. *((char**)(((byte *)(cert)) + certNameSubject[(id) - 3].data)) = (val)
  11425. /* Set the string length for a name component into the subject name. */
  11426. #define SetCertNameSubjectLen(cert, id, val) \
  11427. *((int*)(((byte *)(cert)) + certNameSubject[(id) - 3].len)) = (int)(val)
  11428. /* Set the encoding for a name component into the subject name. */
  11429. #define SetCertNameSubjectEnc(cert, id, val) \
  11430. *((byte*)(((byte *)(cert)) + certNameSubject[(id) - 3].enc)) = (val)
  11431. /* Get the string of a name component from the subject name. */
  11432. #define GetCertNameSubjectStr(id) \
  11433. (certNameSubject[(id) - 3].str)
  11434. /* Get the string length of a name component from the subject name. */
  11435. #define GetCertNameSubjectStrLen(id) \
  11436. (certNameSubject[(id) - 3].strLen)
  11437. /* Get the NID of a name component from the subject name. */
  11438. #define GetCertNameSubjectNID(id) \
  11439. (certNameSubject[(id) - 3].nid)
  11440. #define ValidCertNameSubject(id) \
  11441. (((id) - 3) >= 0 && ((id) - 3) < certNameSubjectSz && \
  11442. (certNameSubject[(id) - 3].strLen > 0))
  11443. /* Mapping of certificate name component to useful information. */
  11444. typedef struct CertNameData {
  11445. /* Type string of name component. */
  11446. const char* str;
  11447. /* Length of type string of name component. */
  11448. byte strLen;
  11449. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11450. /* Offset of data in subject name component. */
  11451. size_t data;
  11452. /* Offset of length in subject name component. */
  11453. size_t len;
  11454. /* Offset of encoding in subject name component. */
  11455. size_t enc;
  11456. #endif
  11457. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11458. /* NID of type for subject name component. */
  11459. int nid;
  11460. #endif
  11461. } CertNameData;
  11462. /* List of data for common name components. */
  11463. static const CertNameData certNameSubject[] = {
  11464. /* Common Name */
  11465. {
  11466. "/CN=", 4,
  11467. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11468. OFFSETOF(DecodedCert, subjectCN),
  11469. OFFSETOF(DecodedCert, subjectCNLen),
  11470. OFFSETOF(DecodedCert, subjectCNEnc),
  11471. #endif
  11472. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11473. NID_commonName
  11474. #endif
  11475. },
  11476. /* Surname */
  11477. {
  11478. "/SN=", 4,
  11479. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11480. OFFSETOF(DecodedCert, subjectSN),
  11481. OFFSETOF(DecodedCert, subjectSNLen),
  11482. OFFSETOF(DecodedCert, subjectSNEnc),
  11483. #endif
  11484. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11485. NID_surname
  11486. #endif
  11487. },
  11488. /* Serial Number */
  11489. {
  11490. "/serialNumber=", 14,
  11491. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11492. OFFSETOF(DecodedCert, subjectSND),
  11493. OFFSETOF(DecodedCert, subjectSNDLen),
  11494. OFFSETOF(DecodedCert, subjectSNDEnc),
  11495. #endif
  11496. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11497. NID_serialNumber
  11498. #endif
  11499. },
  11500. /* Country Name */
  11501. {
  11502. "/C=", 3,
  11503. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11504. OFFSETOF(DecodedCert, subjectC),
  11505. OFFSETOF(DecodedCert, subjectCLen),
  11506. OFFSETOF(DecodedCert, subjectCEnc),
  11507. #endif
  11508. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11509. NID_countryName
  11510. #endif
  11511. },
  11512. /* Locality Name */
  11513. {
  11514. "/L=", 3,
  11515. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11516. OFFSETOF(DecodedCert, subjectL),
  11517. OFFSETOF(DecodedCert, subjectLLen),
  11518. OFFSETOF(DecodedCert, subjectLEnc),
  11519. #endif
  11520. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11521. NID_localityName
  11522. #endif
  11523. },
  11524. /* State Name */
  11525. {
  11526. "/ST=", 4,
  11527. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11528. OFFSETOF(DecodedCert, subjectST),
  11529. OFFSETOF(DecodedCert, subjectSTLen),
  11530. OFFSETOF(DecodedCert, subjectSTEnc),
  11531. #endif
  11532. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11533. NID_stateOrProvinceName
  11534. #endif
  11535. },
  11536. /* Street Address */
  11537. {
  11538. "/street=", 8,
  11539. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11540. OFFSETOF(DecodedCert, subjectStreet),
  11541. OFFSETOF(DecodedCert, subjectStreetLen),
  11542. OFFSETOF(DecodedCert, subjectStreetEnc),
  11543. #endif
  11544. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11545. NID_streetAddress
  11546. #endif
  11547. },
  11548. /* Organization Name */
  11549. {
  11550. "/O=", 3,
  11551. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11552. OFFSETOF(DecodedCert, subjectO),
  11553. OFFSETOF(DecodedCert, subjectOLen),
  11554. OFFSETOF(DecodedCert, subjectOEnc),
  11555. #endif
  11556. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11557. NID_organizationName
  11558. #endif
  11559. },
  11560. /* Organization Unit Name */
  11561. {
  11562. "/OU=", 4,
  11563. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11564. OFFSETOF(DecodedCert, subjectOU),
  11565. OFFSETOF(DecodedCert, subjectOULen),
  11566. OFFSETOF(DecodedCert, subjectOUEnc),
  11567. #endif
  11568. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11569. NID_organizationalUnitName
  11570. #endif
  11571. },
  11572. /* Title */
  11573. {
  11574. NULL, 0,
  11575. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11576. 0,
  11577. 0,
  11578. 0,
  11579. #endif
  11580. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11581. 0,
  11582. #endif
  11583. },
  11584. /* Undefined */
  11585. {
  11586. NULL, 0,
  11587. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11588. 0,
  11589. 0,
  11590. 0,
  11591. #endif
  11592. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11593. 0,
  11594. #endif
  11595. },
  11596. /* Undefined */
  11597. {
  11598. NULL, 0,
  11599. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11600. 0,
  11601. 0,
  11602. 0,
  11603. #endif
  11604. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11605. 0,
  11606. #endif
  11607. },
  11608. /* Business Category */
  11609. {
  11610. "/businessCategory=", 18,
  11611. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11612. OFFSETOF(DecodedCert, subjectBC),
  11613. OFFSETOF(DecodedCert, subjectBCLen),
  11614. OFFSETOF(DecodedCert, subjectBCEnc),
  11615. #endif
  11616. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11617. NID_businessCategory
  11618. #endif
  11619. },
  11620. /* Undefined */
  11621. {
  11622. NULL, 0,
  11623. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11624. 0,
  11625. 0,
  11626. 0,
  11627. #endif
  11628. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11629. 0,
  11630. #endif
  11631. },
  11632. /* Postal Code */
  11633. {
  11634. "/postalCode=", 12,
  11635. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11636. OFFSETOF(DecodedCert, subjectPC),
  11637. OFFSETOF(DecodedCert, subjectPCLen),
  11638. OFFSETOF(DecodedCert, subjectPCEnc),
  11639. #endif
  11640. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11641. NID_postalCode
  11642. #endif
  11643. },
  11644. /* User Id */
  11645. {
  11646. "/userid=", 8,
  11647. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11648. OFFSETOF(DecodedCert, subjectUID),
  11649. OFFSETOF(DecodedCert, subjectUIDLen),
  11650. OFFSETOF(DecodedCert, subjectUIDEnc),
  11651. #endif
  11652. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11653. NID_userId
  11654. #endif
  11655. },
  11656. #ifdef WOLFSSL_CERT_NAME_ALL
  11657. /* Name, id 41 */
  11658. {
  11659. "/N=", 3,
  11660. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11661. OFFSETOF(DecodedCert, subjectN),
  11662. OFFSETOF(DecodedCert, subjectNLen),
  11663. OFFSETOF(DecodedCert, subjectNEnc),
  11664. #endif
  11665. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11666. NID_name
  11667. #endif
  11668. },
  11669. /* Given Name, id 42 */
  11670. {
  11671. "/GN=", 4,
  11672. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11673. OFFSETOF(DecodedCert, subjectGN),
  11674. OFFSETOF(DecodedCert, subjectGNLen),
  11675. OFFSETOF(DecodedCert, subjectGNEnc),
  11676. #endif
  11677. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11678. NID_givenName
  11679. #endif
  11680. },
  11681. /* initials, id 43 */
  11682. {
  11683. "/initials=", 10,
  11684. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11685. OFFSETOF(DecodedCert, subjectI),
  11686. OFFSETOF(DecodedCert, subjectILen),
  11687. OFFSETOF(DecodedCert, subjectIEnc),
  11688. #endif
  11689. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11690. NID_initials
  11691. #endif
  11692. },
  11693. /* DN Qualifier Name, id 46 */
  11694. {
  11695. "/dnQualifier=", 13,
  11696. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11697. OFFSETOF(DecodedCert, subjectDNQ),
  11698. OFFSETOF(DecodedCert, subjectDNQLen),
  11699. OFFSETOF(DecodedCert, subjectDNQEnc),
  11700. #endif
  11701. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11702. NID_dnQualifier
  11703. #endif
  11704. },
  11705. #endif /* WOLFSSL_CERT_NAME_ALL */
  11706. };
  11707. static const int certNameSubjectSz =
  11708. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  11709. /* ASN.1 template for an RDN.
  11710. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  11711. */
  11712. static const ASNItem rdnASN[] = {
  11713. /* SET */ { 1, ASN_SET, 1, 1, 0 },
  11714. /* AttributeTypeAndValue */
  11715. /* ATTR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  11716. /* AttributeType */
  11717. /* ATTR_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  11718. /* AttributeValue: Choice of tags - rdnChoice. */
  11719. /* ATTR_VAL */ { 3, 0, 0, 0, 0 },
  11720. };
  11721. enum {
  11722. RDNASN_IDX_SET = 0,
  11723. RDNASN_IDX_ATTR_SEQ,
  11724. RDNASN_IDX_ATTR_TYPE,
  11725. RDNASN_IDX_ATTR_VAL
  11726. };
  11727. /* Number of items in ASN.1 template for an RDN. */
  11728. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  11729. /* Supported types of encodings (tags) for RDN strings.
  11730. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  11731. * (IA5 String not listed in RFC but required for alternative types)
  11732. */
  11733. static const byte rdnChoice[] = {
  11734. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  11735. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  11736. };
  11737. #endif
  11738. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11739. /* used to set the human readable string for the IP address with a ASN_IP_TYPE
  11740. * DNS entry
  11741. * return 0 on success
  11742. */
  11743. static int GenerateDNSEntryIPString(DNS_entry* entry, void* heap)
  11744. {
  11745. int ret = 0;
  11746. int nameSz;
  11747. char tmpName[WOLFSSL_MAX_IPSTR] = {0};
  11748. char* ip;
  11749. if (entry == NULL || entry->type != ASN_IP_TYPE) {
  11750. return BAD_FUNC_ARG;
  11751. }
  11752. if (entry->len != WOLFSSL_IP4_ADDR_LEN &&
  11753. entry->len != WOLFSSL_IP6_ADDR_LEN) {
  11754. WOLFSSL_MSG("Unexpected IP size");
  11755. return BAD_FUNC_ARG;
  11756. }
  11757. ip = entry->name;
  11758. /* store IP addresses as a string */
  11759. if (entry->len == WOLFSSL_IP4_ADDR_LEN) {
  11760. if (XSNPRINTF(tmpName, sizeof(tmpName), "%u.%u.%u.%u", 0xFFU & ip[0],
  11761. 0xFFU & ip[1], 0xFFU & ip[2], 0xFFU & ip[3])
  11762. >= (int)sizeof(tmpName))
  11763. {
  11764. WOLFSSL_MSG("IP buffer overrun");
  11765. return BUFFER_E;
  11766. }
  11767. }
  11768. if (entry->len == WOLFSSL_IP6_ADDR_LEN) {
  11769. int i;
  11770. for (i = 0; i < 8; i++) {
  11771. if (XSNPRINTF(tmpName + i * 5, sizeof(tmpName) - i * 5,
  11772. "%02X%02X%s", 0xFF & ip[2 * i], 0xFF & ip[2 * i + 1],
  11773. (i < 7) ? ":" : "")
  11774. >= (int)sizeof(tmpName))
  11775. {
  11776. WOLFSSL_MSG("IPv6 buffer overrun");
  11777. return BUFFER_E;
  11778. }
  11779. }
  11780. }
  11781. nameSz = (int)XSTRLEN(tmpName);
  11782. entry->ipString = (char*)XMALLOC(nameSz + 1, heap, DYNAMIC_TYPE_ALTNAME);
  11783. if (entry->ipString == NULL) {
  11784. ret = MEMORY_E;
  11785. }
  11786. if (ret == 0) {
  11787. XMEMCPY(entry->ipString, tmpName, nameSz);
  11788. entry->ipString[nameSz] = '\0';
  11789. }
  11790. (void)heap;
  11791. return ret;
  11792. }
  11793. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  11794. #ifdef WOLFSSL_ASN_TEMPLATE
  11795. #if defined(WOLFSSL_CERT_GEN) || !defined(NO_CERTS)
  11796. /* Adds a DNS entry to a list of DNS entries
  11797. *
  11798. * @param [in, out] lst Linked list of DNS name entries.
  11799. * @param [in] entry Entry to add to the list
  11800. * @return 0 on success.
  11801. */
  11802. static int AddDNSEntryToList(DNS_entry** lst, DNS_entry* entry)
  11803. {
  11804. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  11805. entry->next = NULL;
  11806. if (*lst == NULL) {
  11807. /* First on list */
  11808. *lst = entry;
  11809. }
  11810. else {
  11811. DNS_entry* temp = *lst;
  11812. /* Find end */
  11813. for (; (temp->next != NULL); temp = temp->next);
  11814. /* Add to end */
  11815. temp->next = entry;
  11816. }
  11817. #else
  11818. /* Prepend entry to linked list. */
  11819. entry->next = *lst;
  11820. *lst = entry;
  11821. #endif
  11822. return 0;
  11823. }
  11824. /* Allocate a DNS entry and set the fields.
  11825. *
  11826. * @param [in] cert Certificate object.
  11827. * @param [in] str DNS name string.
  11828. * @param [in] strLen Length of DNS name string.
  11829. * @param [in] type Type of DNS name string.
  11830. * @param [in, out] entries Linked list of DNS name entries.
  11831. * @return 0 on success.
  11832. * @return MEMORY_E when dynamic memory allocation fails.
  11833. */
  11834. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  11835. int type, DNS_entry** entries)
  11836. {
  11837. DNS_entry* dnsEntry;
  11838. int ret = 0;
  11839. /* Only used for heap. */
  11840. (void)cert;
  11841. /* TODO: consider one malloc. */
  11842. /* Allocate DNS Entry object. */
  11843. dnsEntry = AltNameNew(cert->heap);
  11844. if (dnsEntry == NULL) {
  11845. ret = MEMORY_E;
  11846. }
  11847. if (ret == 0) {
  11848. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  11849. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  11850. DYNAMIC_TYPE_ALTNAME);
  11851. if (dnsEntry->name == NULL) {
  11852. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11853. ret = MEMORY_E;
  11854. }
  11855. }
  11856. if (ret == 0) {
  11857. /* Set tag type, name length, name and NUL terminate name. */
  11858. dnsEntry->type = type;
  11859. dnsEntry->len = strLen;
  11860. XMEMCPY(dnsEntry->name, str, (size_t)strLen);
  11861. dnsEntry->name[strLen] = '\0';
  11862. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  11863. /* store IP addresses as a string */
  11864. if (type == ASN_IP_TYPE) {
  11865. if ((ret = GenerateDNSEntryIPString(dnsEntry, cert->heap)) != 0) {
  11866. XFREE(dnsEntry->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11867. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  11868. }
  11869. }
  11870. }
  11871. if (ret == 0) {
  11872. #endif
  11873. ret = AddDNSEntryToList(entries, dnsEntry);
  11874. }
  11875. return ret;
  11876. }
  11877. #endif
  11878. /* Set the details of a subject name component into a certificate.
  11879. *
  11880. * @param [in, out] cert Certificate object.
  11881. * @param [in] id Id of component.
  11882. * @param [in] str String for component.
  11883. * @param [in] strLen Length of string.
  11884. * @param [in] tag BER tag representing encoding of string.
  11885. * @return 0 on success, negative values on failure.
  11886. */
  11887. static int SetSubject(DecodedCert* cert, int id, byte* str, int strLen,
  11888. byte tag)
  11889. {
  11890. int ret = 0;
  11891. /* Put string and encoding into certificate. */
  11892. if (id == ASN_COMMON_NAME) {
  11893. cert->subjectCN = (char *)str;
  11894. cert->subjectCNLen = (int)strLen;
  11895. cert->subjectCNEnc = (char)tag;
  11896. }
  11897. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11898. else if (id > ASN_COMMON_NAME && id <= ASN_USER_ID) {
  11899. /* Use table and offsets to put data into appropriate fields. */
  11900. SetCertNameSubject(cert, id, (char*)str);
  11901. SetCertNameSubjectLen(cert, id, strLen);
  11902. SetCertNameSubjectEnc(cert, id, tag);
  11903. }
  11904. #endif
  11905. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  11906. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  11907. else if (id == ASN_EMAIL) {
  11908. cert->subjectEmail = (char*)str;
  11909. cert->subjectEmailLen = strLen;
  11910. }
  11911. #endif
  11912. #ifdef WOLFSSL_CERT_EXT
  11913. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  11914. else if (id == ASN_JURIS_C) {
  11915. cert->subjectJC = (char*)str;
  11916. cert->subjectJCLen = strLen;
  11917. cert->subjectJCEnc = (char)tag;
  11918. }
  11919. else if (id == ASN_JURIS_ST) {
  11920. cert->subjectJS = (char*)str;
  11921. cert->subjectJSLen = strLen;
  11922. cert->subjectJSEnc = (char)tag;
  11923. }
  11924. #endif
  11925. return ret;
  11926. }
  11927. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  11928. *
  11929. * @param [in, out] cert Certificate object.
  11930. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  11931. * @param [in, out] idx Index int full name to place next component.
  11932. * @param [in, out] nid NID of component type.
  11933. * @param [in] isSubject Whether this data is for a subject name.
  11934. * @param [in] dataASN Decoded data of RDN. Expected rdnASN type.
  11935. * @return 0 on success.
  11936. * @return MEMORY_E when dynamic memory allocation fails.
  11937. * @return ASN_PARSE_E when type not supported.
  11938. */
  11939. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  11940. int isSubject, ASNGetData* dataASN)
  11941. {
  11942. int ret = 0;
  11943. const char* typeStr = NULL;
  11944. byte typeStrLen = 0;
  11945. byte* oid;
  11946. word32 oidSz;
  11947. int id = 0;
  11948. (void)nid;
  11949. /* Get name type OID from data items. */
  11950. GetASN_OIDData(&dataASN[RDNASN_IDX_ATTR_TYPE], &oid, &oidSz);
  11951. /* v1 name types */
  11952. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  11953. id = oid[2];
  11954. /* Check range of supported ids in table. */
  11955. if (ValidCertNameSubject(id)) {
  11956. /* Get the type string, length and NID from table. */
  11957. typeStr = GetCertNameSubjectStr(id);
  11958. typeStrLen = GetCertNameSubjectStrLen(id);
  11959. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11960. *nid = GetCertNameSubjectNID(id);
  11961. #endif
  11962. }
  11963. }
  11964. else if (oidSz == sizeof(attrEmailOid) && XMEMCMP(oid, attrEmailOid, oidSz) == 0) {
  11965. /* Set the email id, type string, length and NID. */
  11966. id = ASN_EMAIL;
  11967. typeStr = WOLFSSL_EMAIL_ADDR;
  11968. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  11969. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11970. *nid = NID_emailAddress;
  11971. #endif
  11972. }
  11973. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  11974. /* Set the user id, type string, length and NID. */
  11975. id = ASN_USER_ID;
  11976. typeStr = WOLFSSL_USER_ID;
  11977. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  11978. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11979. *nid = NID_userId;
  11980. #endif
  11981. }
  11982. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  11983. /* Set the domain component, type string, length and NID. */
  11984. id = ASN_DC;
  11985. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  11986. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  11987. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11988. *nid = NID_domainComponent;
  11989. #endif
  11990. }
  11991. else if (oidSz == sizeof(fvrtDrk) && XMEMCMP(oid, fvrtDrk, oidSz) == 0) {
  11992. /* Set the favourite drink, type string, length and NID. */
  11993. id = ASN_FAVOURITE_DRINK;
  11994. typeStr = WOLFSSL_FAVOURITE_DRINK;
  11995. typeStrLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  11996. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  11997. *nid = NID_favouriteDrink;
  11998. #endif
  11999. }
  12000. /* Other OIDs that start with the same values. */
  12001. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  12002. WOLFSSL_MSG("Unknown pilot attribute type");
  12003. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  12004. ret = ASN_PARSE_E;
  12005. }
  12006. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  12007. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  12008. /* Set the jurisdiction id. */
  12009. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  12010. /* Set the jurisdiction type string, length and NID if known. */
  12011. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  12012. typeStr = WOLFSSL_JOI_C;
  12013. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  12014. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12015. *nid = NID_jurisdictionCountryName;
  12016. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12017. }
  12018. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  12019. typeStr = WOLFSSL_JOI_ST;
  12020. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12021. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12022. *nid = NID_jurisdictionStateOrProvinceName;
  12023. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12024. }
  12025. else {
  12026. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  12027. }
  12028. }
  12029. if ((ret == 0) && (typeStr != NULL)) {
  12030. /* OID type to store for subject name and add to full string. */
  12031. byte* str;
  12032. word32 strLen;
  12033. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12034. /* Get the string reference and length. */
  12035. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12036. if (isSubject) {
  12037. /* Store subject field components. */
  12038. ret = SetSubject(cert, id, str, (int)strLen, tag);
  12039. }
  12040. if (ret == 0) {
  12041. /* Check there is space for this in the full name string and
  12042. * terminating NUL character. */
  12043. if ((typeStrLen + strLen) < (word32)(WC_ASN_NAME_MAX - *idx))
  12044. {
  12045. /* Add RDN to full string. */
  12046. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  12047. *idx += typeStrLen;
  12048. XMEMCPY(&full[*idx], str, strLen);
  12049. *idx += strLen;
  12050. }
  12051. else {
  12052. WOLFSSL_MSG("ASN Name too big, skipping");
  12053. }
  12054. }
  12055. }
  12056. return ret;
  12057. }
  12058. #endif /* WOLFSSL_ASN_TEMPLATE */
  12059. /* Get a certificate name into the certificate object.
  12060. *
  12061. * @param [in, out] cert Decoded certificate object.
  12062. * @param [out] full Buffer to hold full name as a string.
  12063. * @param [out] hash Buffer to hold hash of name.
  12064. * @param [in] nameType ISSUER or SUBJECT.
  12065. * @param [in] input Buffer holding certificate name.
  12066. * @param [in, out] inOutIdx On in, start of certificate name.
  12067. * On out, start of ASN.1 item after cert name.
  12068. * @param [in] maxIdx Index of next item after certificate name.
  12069. * @return 0 on success.
  12070. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12071. * is invalid.
  12072. * @return BUFFER_E when data in buffer is too small.
  12073. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12074. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12075. * @return MEMORY_E when dynamic memory allocation fails.
  12076. */
  12077. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  12078. const byte* input, word32* inOutIdx, word32 maxIdx)
  12079. {
  12080. #ifndef WOLFSSL_ASN_TEMPLATE
  12081. int length; /* length of all distinguished names */
  12082. int dummy;
  12083. int ret;
  12084. word32 idx;
  12085. word32 srcIdx = *inOutIdx;
  12086. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12087. !defined(WOLFCRYPT_ONLY)
  12088. WOLFSSL_X509_NAME* dName = NULL;
  12089. #endif
  12090. WOLFSSL_MSG("Getting Cert Name");
  12091. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12092. * calculated over the entire DER encoding of the Name field, including
  12093. * the tag and length. */
  12094. if (CalcHashId_ex(input + *inOutIdx, maxIdx - *inOutIdx, hash,
  12095. HashIdAlg(cert->signatureOID)) != 0) {
  12096. return ASN_PARSE_E;
  12097. }
  12098. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12099. !defined(WOLFCRYPT_ONLY)
  12100. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12101. if (dName == NULL) {
  12102. return MEMORY_E;
  12103. }
  12104. #endif /* OPENSSL_EXTRA */
  12105. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  12106. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12107. !defined(WOLFCRYPT_ONLY)
  12108. wolfSSL_X509_NAME_free(dName);
  12109. #endif /* OPENSSL_EXTRA */
  12110. return ASN_PARSE_E;
  12111. }
  12112. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12113. /* store pointer to raw issuer */
  12114. if (nameType == ISSUER) {
  12115. cert->issuerRaw = &input[srcIdx];
  12116. cert->issuerRawLen = length;
  12117. }
  12118. #endif
  12119. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12120. if (nameType == SUBJECT) {
  12121. cert->subjectRaw = &input[srcIdx];
  12122. cert->subjectRawLen = length;
  12123. }
  12124. #endif
  12125. length += (int)srcIdx;
  12126. idx = 0;
  12127. while (srcIdx < (word32)length) {
  12128. byte b = 0;
  12129. byte joint[3];
  12130. byte tooBig = FALSE;
  12131. int oidSz;
  12132. const char* copy = NULL;
  12133. int copyLen = 0;
  12134. int strLen = 0;
  12135. byte id = 0;
  12136. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12137. && !defined(WOLFCRYPT_ONLY)
  12138. int nid = NID_undef;
  12139. int enc;
  12140. #endif /* OPENSSL_EXTRA */
  12141. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  12142. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  12143. }
  12144. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  12145. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12146. !defined(WOLFCRYPT_ONLY)
  12147. wolfSSL_X509_NAME_free(dName);
  12148. #endif /* OPENSSL_EXTRA */
  12149. return ASN_PARSE_E;
  12150. }
  12151. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  12152. if (ret != 0) {
  12153. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12154. !defined(WOLFCRYPT_ONLY)
  12155. wolfSSL_X509_NAME_free(dName);
  12156. #endif /* OPENSSL_EXTRA */
  12157. return ret;
  12158. }
  12159. /* make sure there is room for joint */
  12160. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  12161. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12162. !defined(WOLFCRYPT_ONLY)
  12163. wolfSSL_X509_NAME_free(dName);
  12164. #endif /* OPENSSL_EXTRA */
  12165. return ASN_PARSE_E;
  12166. }
  12167. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  12168. /* v1 name types */
  12169. if (joint[0] == 0x55 && joint[1] == 0x04) {
  12170. srcIdx += 3;
  12171. id = joint[2];
  12172. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  12173. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12174. !defined(WOLFCRYPT_ONLY)
  12175. wolfSSL_X509_NAME_free(dName);
  12176. #endif /* OPENSSL_EXTRA */
  12177. return ASN_PARSE_E;
  12178. }
  12179. if (id == ASN_COMMON_NAME) {
  12180. if (nameType == SUBJECT) {
  12181. cert->subjectCN = (char *)&input[srcIdx];
  12182. cert->subjectCNLen = strLen;
  12183. cert->subjectCNEnc = (char)b;
  12184. }
  12185. #if (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)) && \
  12186. defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12187. else if (nameType == ISSUER) {
  12188. cert->issuerCN = (char*)&input[srcIdx];
  12189. cert->issuerCNLen = strLen;
  12190. cert->issuerCNEnc = (char)b;
  12191. }
  12192. #endif
  12193. copy = WOLFSSL_COMMON_NAME;
  12194. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  12195. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12196. && !defined(WOLFCRYPT_ONLY)
  12197. nid = NID_commonName;
  12198. #endif /* OPENSSL_EXTRA */
  12199. }
  12200. #ifdef WOLFSSL_CERT_NAME_ALL
  12201. else if (id == ASN_NAME) {
  12202. copy = WOLFSSL_NAME;
  12203. copyLen = sizeof(WOLFSSL_NAME) - 1;
  12204. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12205. if (nameType == SUBJECT) {
  12206. cert->subjectN = (char*)&input[srcIdx];
  12207. cert->subjectNLen = strLen;
  12208. cert->subjectNEnc = b;
  12209. }
  12210. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12211. #if (defined(OPENSSL_EXTRA) || \
  12212. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12213. && !defined(WOLFCRYPT_ONLY)
  12214. nid = NID_name;
  12215. #endif /* OPENSSL_EXTRA */
  12216. }
  12217. else if (id == ASN_INITIALS) {
  12218. copy = WOLFSSL_INITIALS;
  12219. copyLen = sizeof(WOLFSSL_INITIALS) - 1;
  12220. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12221. if (nameType == SUBJECT) {
  12222. cert->subjectI = (char*)&input[srcIdx];
  12223. cert->subjectILen = strLen;
  12224. cert->subjectIEnc = b;
  12225. }
  12226. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12227. #if (defined(OPENSSL_EXTRA) || \
  12228. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12229. && !defined(WOLFCRYPT_ONLY)
  12230. nid = NID_initials;
  12231. #endif /* OPENSSL_EXTRA */
  12232. }
  12233. else if (id == ASN_GIVEN_NAME) {
  12234. copy = WOLFSSL_GIVEN_NAME;
  12235. copyLen = sizeof(WOLFSSL_GIVEN_NAME) - 1;
  12236. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12237. if (nameType == SUBJECT) {
  12238. cert->subjectGN = (char*)&input[srcIdx];
  12239. cert->subjectGNLen = strLen;
  12240. cert->subjectGNEnc = b;
  12241. }
  12242. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12243. #if (defined(OPENSSL_EXTRA) || \
  12244. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12245. && !defined(WOLFCRYPT_ONLY)
  12246. nid = NID_givenName;
  12247. #endif /* OPENSSL_EXTRA */
  12248. }
  12249. else if (id == ASN_DNQUALIFIER) {
  12250. copy = WOLFSSL_DNQUALIFIER;
  12251. copyLen = sizeof(WOLFSSL_DNQUALIFIER) - 1;
  12252. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12253. if (nameType == SUBJECT) {
  12254. cert->subjectDNQ = (char*)&input[srcIdx];
  12255. cert->subjectDNQLen = strLen;
  12256. cert->subjectDNQEnc = b;
  12257. }
  12258. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12259. #if (defined(OPENSSL_EXTRA) || \
  12260. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12261. && !defined(WOLFCRYPT_ONLY)
  12262. nid = NID_dnQualifier;
  12263. #endif /* OPENSSL_EXTRA */
  12264. }
  12265. #endif /* WOLFSSL_CERT_NAME_ALL */
  12266. else if (id == ASN_SUR_NAME) {
  12267. copy = WOLFSSL_SUR_NAME;
  12268. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  12269. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12270. if (nameType == SUBJECT) {
  12271. cert->subjectSN = (char*)&input[srcIdx];
  12272. cert->subjectSNLen = strLen;
  12273. cert->subjectSNEnc = (char)b;
  12274. }
  12275. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12276. else if (nameType == ISSUER) {
  12277. cert->issuerSN = (char*)&input[srcIdx];
  12278. cert->issuerSNLen = strLen;
  12279. cert->issuerSNEnc = (char)b;
  12280. }
  12281. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12282. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12283. #if (defined(OPENSSL_EXTRA) || \
  12284. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12285. && !defined(WOLFCRYPT_ONLY)
  12286. nid = NID_surname;
  12287. #endif /* OPENSSL_EXTRA */
  12288. }
  12289. else if (id == ASN_COUNTRY_NAME) {
  12290. copy = WOLFSSL_COUNTRY_NAME;
  12291. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  12292. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12293. if (nameType == SUBJECT) {
  12294. cert->subjectC = (char*)&input[srcIdx];
  12295. cert->subjectCLen = strLen;
  12296. cert->subjectCEnc = (char)b;
  12297. }
  12298. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12299. else if (nameType == ISSUER) {
  12300. cert->issuerC = (char*)&input[srcIdx];
  12301. cert->issuerCLen = strLen;
  12302. cert->issuerCEnc = (char)b;
  12303. }
  12304. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12305. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12306. #if (defined(OPENSSL_EXTRA) || \
  12307. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12308. && !defined(WOLFCRYPT_ONLY)
  12309. nid = NID_countryName;
  12310. #endif /* OPENSSL_EXTRA */
  12311. }
  12312. else if (id == ASN_LOCALITY_NAME) {
  12313. copy = WOLFSSL_LOCALITY_NAME;
  12314. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  12315. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12316. if (nameType == SUBJECT) {
  12317. cert->subjectL = (char*)&input[srcIdx];
  12318. cert->subjectLLen = strLen;
  12319. cert->subjectLEnc = (char)b;
  12320. }
  12321. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12322. else if (nameType == ISSUER) {
  12323. cert->issuerL = (char*)&input[srcIdx];
  12324. cert->issuerLLen = strLen;
  12325. cert->issuerLEnc = (char)b;
  12326. }
  12327. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12328. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12329. #if (defined(OPENSSL_EXTRA) || \
  12330. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12331. && !defined(WOLFCRYPT_ONLY)
  12332. nid = NID_localityName;
  12333. #endif /* OPENSSL_EXTRA */
  12334. }
  12335. else if (id == ASN_STATE_NAME) {
  12336. copy = WOLFSSL_STATE_NAME;
  12337. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  12338. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12339. if (nameType == SUBJECT) {
  12340. cert->subjectST = (char*)&input[srcIdx];
  12341. cert->subjectSTLen = strLen;
  12342. cert->subjectSTEnc = (char)b;
  12343. }
  12344. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12345. else if (nameType == ISSUER) {
  12346. cert->issuerST = (char*)&input[srcIdx];
  12347. cert->issuerSTLen = strLen;
  12348. cert->issuerSTEnc = (char)b;
  12349. }
  12350. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12351. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12352. #if (defined(OPENSSL_EXTRA) || \
  12353. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12354. && !defined(WOLFCRYPT_ONLY)
  12355. nid = NID_stateOrProvinceName;
  12356. #endif /* OPENSSL_EXTRA */
  12357. }
  12358. else if (id == ASN_ORG_NAME) {
  12359. copy = WOLFSSL_ORG_NAME;
  12360. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  12361. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12362. if (nameType == SUBJECT) {
  12363. cert->subjectO = (char*)&input[srcIdx];
  12364. cert->subjectOLen = strLen;
  12365. cert->subjectOEnc = (char)b;
  12366. }
  12367. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12368. else if (nameType == ISSUER) {
  12369. cert->issuerO = (char*)&input[srcIdx];
  12370. cert->issuerOLen = strLen;
  12371. cert->issuerOEnc = (char)b;
  12372. }
  12373. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12374. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12375. #if (defined(OPENSSL_EXTRA) || \
  12376. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12377. && !defined(WOLFCRYPT_ONLY)
  12378. nid = NID_organizationName;
  12379. #endif /* OPENSSL_EXTRA */
  12380. }
  12381. else if (id == ASN_ORGUNIT_NAME) {
  12382. copy = WOLFSSL_ORGUNIT_NAME;
  12383. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  12384. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12385. if (nameType == SUBJECT) {
  12386. cert->subjectOU = (char*)&input[srcIdx];
  12387. cert->subjectOULen = strLen;
  12388. cert->subjectOUEnc = (char)b;
  12389. }
  12390. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12391. else if (nameType == ISSUER) {
  12392. cert->issuerOU = (char*)&input[srcIdx];
  12393. cert->issuerOULen = strLen;
  12394. cert->issuerOUEnc = (char)b;
  12395. }
  12396. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12397. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12398. #if (defined(OPENSSL_EXTRA) || \
  12399. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12400. && !defined(WOLFCRYPT_ONLY)
  12401. nid = NID_organizationalUnitName;
  12402. #endif /* OPENSSL_EXTRA */
  12403. }
  12404. else if (id == ASN_SERIAL_NUMBER) {
  12405. copy = WOLFSSL_SERIAL_NUMBER;
  12406. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  12407. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12408. if (nameType == SUBJECT) {
  12409. cert->subjectSND = (char*)&input[srcIdx];
  12410. cert->subjectSNDLen = strLen;
  12411. cert->subjectSNDEnc = (char)b;
  12412. }
  12413. #if defined(WOLFSSL_HAVE_ISSUER_NAMES)
  12414. else if (nameType == ISSUER) {
  12415. cert->issuerSND = (char*)&input[srcIdx];
  12416. cert->issuerSNDLen = strLen;
  12417. cert->issuerSNDEnc = (char)b;
  12418. }
  12419. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12420. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12421. #if (defined(OPENSSL_EXTRA) || \
  12422. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12423. && !defined(WOLFCRYPT_ONLY)
  12424. nid = NID_serialNumber;
  12425. #endif /* OPENSSL_EXTRA */
  12426. }
  12427. else if (id == ASN_USER_ID) {
  12428. copy = WOLFSSL_USER_ID;
  12429. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12430. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12431. if (nameType == SUBJECT) {
  12432. cert->subjectUID = (char*)&input[srcIdx];
  12433. cert->subjectUIDLen = strLen;
  12434. cert->subjectUIDEnc = (char)b;
  12435. }
  12436. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12437. #if (defined(OPENSSL_EXTRA) || \
  12438. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12439. && !defined(WOLFCRYPT_ONLY)
  12440. nid = NID_userId;
  12441. #endif /* OPENSSL_EXTRA */
  12442. }
  12443. #ifdef WOLFSSL_CERT_EXT
  12444. else if (id == ASN_STREET_ADDR) {
  12445. copy = WOLFSSL_STREET_ADDR_NAME;
  12446. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  12447. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12448. if (nameType == SUBJECT) {
  12449. cert->subjectStreet = (char*)&input[srcIdx];
  12450. cert->subjectStreetLen = strLen;
  12451. cert->subjectStreetEnc = (char)b;
  12452. }
  12453. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12454. #if (defined(OPENSSL_EXTRA) || \
  12455. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12456. && !defined(WOLFCRYPT_ONLY)
  12457. nid = NID_streetAddress;
  12458. #endif /* OPENSSL_EXTRA */
  12459. }
  12460. else if (id == ASN_BUS_CAT) {
  12461. copy = WOLFSSL_BUS_CAT;
  12462. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  12463. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12464. if (nameType == SUBJECT) {
  12465. cert->subjectBC = (char*)&input[srcIdx];
  12466. cert->subjectBCLen = strLen;
  12467. cert->subjectBCEnc = (char)b;
  12468. }
  12469. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12470. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  12471. && !defined(WOLFCRYPT_ONLY)
  12472. nid = NID_businessCategory;
  12473. #endif /* OPENSSL_EXTRA */
  12474. }
  12475. else if (id == ASN_POSTAL_CODE) {
  12476. copy = WOLFSSL_POSTAL_NAME;
  12477. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  12478. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12479. if (nameType == SUBJECT) {
  12480. cert->subjectPC = (char*)&input[srcIdx];
  12481. cert->subjectPCLen = strLen;
  12482. cert->subjectPCEnc = (char)b;
  12483. }
  12484. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT*/
  12485. #if (defined(OPENSSL_EXTRA) || \
  12486. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12487. && !defined(WOLFCRYPT_ONLY)
  12488. nid = NID_postalCode;
  12489. #endif /* OPENSSL_EXTRA */
  12490. }
  12491. #endif /* WOLFSSL_CERT_EXT */
  12492. }
  12493. #ifdef WOLFSSL_CERT_EXT
  12494. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  12495. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  12496. ASN_JOI_PREFIX_SZ)) &&
  12497. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  12498. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  12499. {
  12500. srcIdx += ASN_JOI_PREFIX_SZ;
  12501. id = input[srcIdx++];
  12502. b = input[srcIdx++]; /* encoding */
  12503. if (GetLength(input, &srcIdx, &strLen,
  12504. maxIdx) < 0) {
  12505. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12506. !defined(WOLFCRYPT_ONLY)
  12507. wolfSSL_X509_NAME_free(dName);
  12508. #endif /* OPENSSL_EXTRA */
  12509. return ASN_PARSE_E;
  12510. }
  12511. /* Check for jurisdiction of incorporation country name */
  12512. if (id == ASN_JOI_C) {
  12513. copy = WOLFSSL_JOI_C;
  12514. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  12515. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12516. if (nameType == SUBJECT) {
  12517. cert->subjectJC = (char*)&input[srcIdx];
  12518. cert->subjectJCLen = strLen;
  12519. cert->subjectJCEnc = (char)b;
  12520. }
  12521. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12522. #if (defined(OPENSSL_EXTRA) || \
  12523. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12524. && !defined(WOLFCRYPT_ONLY)
  12525. nid = NID_jurisdictionCountryName;
  12526. #endif /* OPENSSL_EXTRA */
  12527. }
  12528. /* Check for jurisdiction of incorporation state name */
  12529. else if (id == ASN_JOI_ST) {
  12530. copy = WOLFSSL_JOI_ST;
  12531. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  12532. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12533. if (nameType == SUBJECT) {
  12534. cert->subjectJS = (char*)&input[srcIdx];
  12535. cert->subjectJSLen = strLen;
  12536. cert->subjectJSEnc = (char)b;
  12537. }
  12538. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12539. #if (defined(OPENSSL_EXTRA) || \
  12540. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12541. && !defined(WOLFCRYPT_ONLY)
  12542. nid = NID_jurisdictionStateOrProvinceName;
  12543. #endif /* OPENSSL_EXTRA */
  12544. }
  12545. if ((strLen + copyLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12546. WOLFSSL_MSG("ASN Name too big, skipping");
  12547. tooBig = TRUE;
  12548. }
  12549. }
  12550. #endif /* WOLFSSL_CERT_EXT */
  12551. else {
  12552. /* skip */
  12553. byte email = FALSE;
  12554. byte pilot = FALSE;
  12555. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr 42.134.* */
  12556. id = ASN_EMAIL_NAME;
  12557. email = TRUE;
  12558. }
  12559. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr 9.146.* */
  12560. /* last value of OID is the type of pilot attribute */
  12561. id = input[srcIdx + (word32)oidSz - 1];
  12562. if (id == 0x01)
  12563. id = ASN_USER_ID;
  12564. pilot = TRUE;
  12565. }
  12566. srcIdx += (word32)oidSz + 1;
  12567. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  12568. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12569. !defined(WOLFCRYPT_ONLY)
  12570. wolfSSL_X509_NAME_free(dName);
  12571. #endif /* OPENSSL_EXTRA */
  12572. return ASN_PARSE_E;
  12573. }
  12574. if (strLen > (int)(WC_ASN_NAME_MAX - idx)) {
  12575. WOLFSSL_MSG("ASN name too big, skipping");
  12576. tooBig = TRUE;
  12577. }
  12578. if (email) {
  12579. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  12580. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx)) {
  12581. WOLFSSL_MSG("ASN name too big, skipping");
  12582. tooBig = TRUE;
  12583. }
  12584. else {
  12585. copy = WOLFSSL_EMAIL_ADDR;
  12586. }
  12587. #if !defined(IGNORE_NAME_CONSTRAINTS) || \
  12588. defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  12589. if (nameType == SUBJECT) {
  12590. cert->subjectEmail = (char*)&input[srcIdx];
  12591. cert->subjectEmailLen = strLen;
  12592. }
  12593. #if defined(WOLFSSL_HAVE_ISSUER_NAMES) && \
  12594. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  12595. else if (nameType == ISSUER) {
  12596. cert->issuerEmail = (char*)&input[srcIdx];
  12597. cert->issuerEmailLen = strLen;
  12598. }
  12599. #endif /* WOLFSSL_HAVE_ISSUER_NAMES */
  12600. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_CERT_EXT */
  12601. #if (defined(OPENSSL_EXTRA) || \
  12602. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12603. && !defined(WOLFCRYPT_ONLY)
  12604. nid = NID_emailAddress;
  12605. #endif /* OPENSSL_EXTRA */
  12606. }
  12607. if (pilot) {
  12608. switch (id) {
  12609. case ASN_USER_ID:
  12610. copy = WOLFSSL_USER_ID;
  12611. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  12612. #if (defined(OPENSSL_EXTRA) || \
  12613. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12614. && !defined(WOLFCRYPT_ONLY)
  12615. nid = NID_userId;
  12616. #endif /* OPENSSL_EXTRA */
  12617. break;
  12618. case ASN_DOMAIN_COMPONENT:
  12619. copy = WOLFSSL_DOMAIN_COMPONENT;
  12620. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  12621. #if (defined(OPENSSL_EXTRA) || \
  12622. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12623. && !defined(WOLFCRYPT_ONLY)
  12624. nid = NID_domainComponent;
  12625. #endif /* OPENSSL_EXTRA */
  12626. break;
  12627. case ASN_FAVOURITE_DRINK:
  12628. copy = WOLFSSL_FAVOURITE_DRINK;
  12629. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  12630. #if (defined(OPENSSL_EXTRA) || \
  12631. defined(OPENSSL_EXTRA_X509_SMALL)) \
  12632. && !defined(WOLFCRYPT_ONLY)
  12633. nid = NID_favouriteDrink;
  12634. #endif /* OPENSSL_EXTRA */
  12635. break;
  12636. default:
  12637. WOLFSSL_MSG("Unknown pilot attribute type");
  12638. #if (defined(OPENSSL_EXTRA) || \
  12639. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12640. !defined(WOLFCRYPT_ONLY)
  12641. wolfSSL_X509_NAME_free(dName);
  12642. #endif /* OPENSSL_EXTRA */
  12643. return ASN_PARSE_E;
  12644. }
  12645. }
  12646. }
  12647. if ((copyLen + strLen) > (int)(WC_ASN_NAME_MAX - idx))
  12648. {
  12649. WOLFSSL_MSG("ASN Name too big, skipping");
  12650. tooBig = TRUE;
  12651. }
  12652. if ((copy != NULL) && !tooBig) {
  12653. XMEMCPY(&full[idx], copy, (size_t)copyLen);
  12654. idx += (word32)copyLen;
  12655. XMEMCPY(&full[idx], &input[srcIdx], (size_t)strLen);
  12656. idx += (word32)strLen;
  12657. }
  12658. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12659. !defined(WOLFCRYPT_ONLY)
  12660. switch (b) {
  12661. case CTC_UTF8:
  12662. enc = MBSTRING_UTF8;
  12663. break;
  12664. case CTC_PRINTABLE:
  12665. enc = V_ASN1_PRINTABLESTRING;
  12666. break;
  12667. default:
  12668. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  12669. enc = MBSTRING_UTF8;
  12670. }
  12671. if (nid != NID_undef) {
  12672. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  12673. &input[srcIdx], strLen, -1, -1) !=
  12674. WOLFSSL_SUCCESS) {
  12675. wolfSSL_X509_NAME_free(dName);
  12676. return ASN_PARSE_E;
  12677. }
  12678. }
  12679. #endif /* OPENSSL_EXTRA */
  12680. srcIdx += (word32)strLen;
  12681. }
  12682. full[idx++] = 0;
  12683. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  12684. !defined(WOLFCRYPT_ONLY)
  12685. if (nameType == ISSUER) {
  12686. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  12687. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12688. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12689. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12690. #endif
  12691. cert->issuerName = dName;
  12692. }
  12693. else {
  12694. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12695. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12696. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12697. #endif
  12698. cert->subjectName = dName;
  12699. }
  12700. #endif
  12701. *inOutIdx = srcIdx;
  12702. return 0;
  12703. #else
  12704. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  12705. int ret = 0;
  12706. word32 idx = 0;
  12707. int len;
  12708. word32 srcIdx = *inOutIdx;
  12709. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12710. WOLFSSL_X509_NAME* dName = NULL;
  12711. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12712. WOLFSSL_MSG("Getting Cert Name");
  12713. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  12714. * calculated over the entire DER encoding of the Name field, including
  12715. * the tag and length. */
  12716. if (CalcHashId_ex(input + srcIdx, maxIdx - srcIdx, hash,
  12717. HashIdAlg(cert->signatureOID)) != 0) {
  12718. ret = ASN_PARSE_E;
  12719. }
  12720. CALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  12721. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12722. if (ret == 0) {
  12723. /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
  12724. dName = wolfSSL_X509_NAME_new_ex(cert->heap);
  12725. if (dName == NULL) {
  12726. ret = MEMORY_E;
  12727. }
  12728. }
  12729. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  12730. if (ret == 0) {
  12731. /* Expecting a SEQUENCE using up all data. */
  12732. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  12733. }
  12734. if (ret == 0) {
  12735. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  12736. /* Store pointer and length to raw issuer. */
  12737. if (nameType == ISSUER) {
  12738. cert->issuerRaw = &input[srcIdx];
  12739. cert->issuerRawLen = len;
  12740. }
  12741. #endif
  12742. #if !defined(IGNORE_NAME_CONSTRAINTS) || defined(WOLFSSL_CERT_EXT)
  12743. /* Store pointer and length to raw subject. */
  12744. if (nameType == SUBJECT) {
  12745. cert->subjectRaw = &input[srcIdx];
  12746. cert->subjectRawLen = len;
  12747. }
  12748. #endif
  12749. /* Process all RDNs in name. */
  12750. while ((ret == 0) && (srcIdx < maxIdx)) {
  12751. int nid = 0;
  12752. /* Initialize for data and setup RDN choice. */
  12753. GetASN_Choice(&dataASN[RDNASN_IDX_ATTR_VAL], rdnChoice);
  12754. /* Ignore type OID as too many to store in table. */
  12755. GetASN_OID(&dataASN[RDNASN_IDX_ATTR_TYPE], oidIgnoreType);
  12756. /* Parse RDN. */
  12757. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  12758. &srcIdx, maxIdx);
  12759. if (ret == 0) {
  12760. /* Put RDN data into certificate. */
  12761. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  12762. dataASN);
  12763. }
  12764. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12765. /* TODO: push this back up to ssl.c
  12766. * (do parsing for WOLFSSL_X509_NAME on demand) */
  12767. if (ret == 0) {
  12768. int enc;
  12769. byte* str;
  12770. word32 strLen;
  12771. byte tag = dataASN[RDNASN_IDX_ATTR_VAL].tag;
  12772. /* Get string reference. */
  12773. GetASN_GetRef(&dataASN[RDNASN_IDX_ATTR_VAL], &str, &strLen);
  12774. /* Convert BER tag to a OpenSSL type. */
  12775. switch (tag) {
  12776. case CTC_UTF8:
  12777. enc = MBSTRING_UTF8;
  12778. break;
  12779. case CTC_PRINTABLE:
  12780. enc = V_ASN1_PRINTABLESTRING;
  12781. break;
  12782. default:
  12783. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  12784. enc = MBSTRING_UTF8;
  12785. }
  12786. if (nid != 0) {
  12787. /* Add an entry to the X509_NAME. */
  12788. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  12789. strLen, -1, -1) != WOLFSSL_SUCCESS) {
  12790. ret = ASN_PARSE_E;
  12791. }
  12792. }
  12793. }
  12794. #endif
  12795. }
  12796. }
  12797. if (ret == 0) {
  12798. /* Terminate string. */
  12799. full[idx] = 0;
  12800. /* Return index into encoding after name. */
  12801. *inOutIdx = srcIdx;
  12802. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  12803. /* Store X509_NAME in certificate. */
  12804. if (nameType == ISSUER) {
  12805. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  12806. defined(HAVE_LIGHTY)) && \
  12807. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  12808. dName->rawLen = min(cert->issuerRawLen, WC_ASN_NAME_MAX);
  12809. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  12810. #endif
  12811. cert->issuerName = dName;
  12812. }
  12813. else {
  12814. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  12815. dName->rawLen = min(cert->subjectRawLen, WC_ASN_NAME_MAX);
  12816. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  12817. #endif
  12818. cert->subjectName = dName;
  12819. }
  12820. }
  12821. else {
  12822. /* Dispose of unused X509_NAME. */
  12823. wolfSSL_X509_NAME_free(dName);
  12824. #endif
  12825. }
  12826. FREE_ASNGETDATA(dataASN, cert->heap);
  12827. return ret;
  12828. #endif /* WOLFSSL_ASN_TEMPLATE */
  12829. }
  12830. #ifdef WOLFSSL_ASN_TEMPLATE
  12831. /* ASN.1 template for certificate name. */
  12832. static const ASNItem certNameASN[] = {
  12833. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  12834. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  12835. };
  12836. enum {
  12837. CERTNAMEASN_IDX_OID = 0,
  12838. CERTNAMEASN_IDX_NAME
  12839. };
  12840. /* Number of items in ASN.1 template for certificate name. */
  12841. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  12842. #endif
  12843. /* Get a certificate name into the certificate object.
  12844. *
  12845. * Either the issuer or subject name.
  12846. *
  12847. * @param [in, out] cert Decoded certificate object.
  12848. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  12849. * @param [in] maxIdx Index of next item after certificate name.
  12850. * @return 0 on success.
  12851. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12852. * is invalid.
  12853. * @return BUFFER_E when data in buffer is too small.
  12854. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  12855. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12856. * @return MEMORY_E when dynamic memory allocation fails.
  12857. */
  12858. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  12859. {
  12860. #ifndef WOLFSSL_ASN_TEMPLATE
  12861. char* full;
  12862. byte* hash;
  12863. int length;
  12864. word32 localIdx;
  12865. byte tag;
  12866. WOLFSSL_MSG("Getting Name");
  12867. if (nameType == ISSUER) {
  12868. full = cert->issuer;
  12869. hash = cert->issuerHash;
  12870. }
  12871. else {
  12872. full = cert->subject;
  12873. hash = cert->subjectHash;
  12874. }
  12875. if (cert->srcIdx >= (word32)maxIdx) {
  12876. return BUFFER_E;
  12877. }
  12878. localIdx = cert->srcIdx;
  12879. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12880. return ASN_PARSE_E;
  12881. }
  12882. if (tag == ASN_OBJECT_ID) {
  12883. WOLFSSL_MSG("Trying optional prefix...");
  12884. if (SkipObjectId(cert->source, &cert->srcIdx, (word32)maxIdx) < 0)
  12885. return ASN_PARSE_E;
  12886. WOLFSSL_MSG("Got optional prefix");
  12887. }
  12888. localIdx = cert->srcIdx;
  12889. if (GetASNTag(cert->source, &localIdx, &tag, (word32)maxIdx) < 0) {
  12890. return ASN_PARSE_E;
  12891. }
  12892. localIdx = cert->srcIdx + 1;
  12893. if (GetLength(cert->source, &localIdx, &length, (word32)maxIdx) < 0) {
  12894. return ASN_PARSE_E;
  12895. }
  12896. length += (int)(localIdx - cert->srcIdx);
  12897. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  12898. cert->srcIdx + (word32)length);
  12899. #else
  12900. ASNGetData dataASN[certNameASN_Length];
  12901. word32 idx = cert->srcIdx;
  12902. int ret = 0;
  12903. WOLFSSL_MSG("Getting Name");
  12904. XMEMSET(dataASN, 0, sizeof(dataASN));
  12905. /* Initialize for data and don't check optional prefix OID. */
  12906. GetASN_OID(&dataASN[CERTNAMEASN_IDX_OID], oidIgnoreType);
  12907. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  12908. cert->source, &idx, (word32)maxIdx);
  12909. if (ret == 0) {
  12910. char* full;
  12911. byte* hash;
  12912. /* Store offset of SEQUENCE that is start of name. */
  12913. cert->srcIdx = dataASN[CERTNAMEASN_IDX_NAME].offset;
  12914. /* Get fields to fill in based on name type. */
  12915. if (nameType == ISSUER) {
  12916. full = cert->issuer;
  12917. hash = cert->issuerHash;
  12918. }
  12919. else {
  12920. full = cert->subject;
  12921. hash = cert->subjectHash;
  12922. }
  12923. /* Parse certificate name. */
  12924. ret = GetCertName(cert, full, hash, nameType, cert->source,
  12925. &cert->srcIdx, idx);
  12926. }
  12927. return ret;
  12928. #endif
  12929. }
  12930. #ifndef NO_ASN_TIME
  12931. /* two byte date/time, add to value */
  12932. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  12933. {
  12934. int i = *idx;
  12935. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12936. date[i+1] > 0x39) {
  12937. return ASN_PARSE_E;
  12938. }
  12939. *value += (int)btoi(date[i++]) * 10;
  12940. *value += (int)btoi(date[i++]);
  12941. *idx = i;
  12942. return 0;
  12943. }
  12944. #ifdef WOLFSSL_LINUXKM
  12945. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  12946. {
  12947. int i = *idx;
  12948. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  12949. date[i+1] > 0x39) {
  12950. return ASN_PARSE_E;
  12951. }
  12952. *value += (long)btoi(date[i++]) * 10;
  12953. *value += (long)btoi(date[i++]);
  12954. *idx = i;
  12955. return 0;
  12956. }
  12957. #endif
  12958. int ExtractDate(const unsigned char* date, unsigned char format,
  12959. struct tm* certTime, int* idx)
  12960. {
  12961. XMEMSET(certTime, 0, sizeof(struct tm));
  12962. if (format == ASN_UTC_TIME) {
  12963. if (btoi(date[*idx]) >= 5)
  12964. certTime->tm_year = 1900;
  12965. else
  12966. certTime->tm_year = 2000;
  12967. }
  12968. else { /* format == GENERALIZED_TIME */
  12969. #ifdef WOLFSSL_LINUXKM
  12970. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  12971. #else
  12972. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  12973. #endif
  12974. certTime->tm_year *= 100;
  12975. }
  12976. #ifdef AVR
  12977. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  12978. /* AVR libc stores these as uint8_t instead of int */
  12979. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  12980. int tm_year = certTime->tm_year - 2000;
  12981. int tm_mon = certTime->tm_mon - 1;
  12982. int tm_mday = certTime->tm_mday;
  12983. int tm_hour = certTime->tm_hour;
  12984. int tm_min = certTime->tm_min;
  12985. int tm_sec = certTime->tm_sec;
  12986. #ifdef WOLFSSL_LINUXKM
  12987. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  12988. #else
  12989. if (GetTime(&tm_year, date, idx) != 0) return 0;
  12990. #endif
  12991. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  12992. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  12993. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  12994. if (GetTime(&tm_min , date, idx) != 0) return 0;
  12995. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  12996. /* Re-populate certTime with computed values */
  12997. certTime->tm_year = tm_year;
  12998. certTime->tm_mon = tm_mon;
  12999. certTime->tm_mday = tm_mday;
  13000. certTime->tm_hour = tm_hour;
  13001. certTime->tm_min = tm_min;
  13002. certTime->tm_sec = tm_sec;
  13003. #else
  13004. /* adjust tm_year, tm_mon */
  13005. #ifdef WOLFSSL_LINUXKM
  13006. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  13007. #else
  13008. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  13009. #endif
  13010. certTime->tm_year -= 1900;
  13011. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  13012. certTime->tm_mon -= 1;
  13013. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  13014. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  13015. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  13016. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  13017. #endif
  13018. return 1;
  13019. }
  13020. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  13021. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  13022. int GetTimeString(byte* date, int format, char* buf, int len)
  13023. {
  13024. struct tm t;
  13025. int idx = 0;
  13026. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  13027. return 0;
  13028. }
  13029. if (date[idx] != 'Z') {
  13030. WOLFSSL_MSG("UTCtime, not Zulu") ;
  13031. return 0;
  13032. }
  13033. /* place month in buffer */
  13034. buf[0] = '\0';
  13035. switch(t.tm_mon) {
  13036. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  13037. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  13038. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  13039. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  13040. case 4: XSTRNCAT(buf, "May ", 5); break;
  13041. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  13042. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  13043. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  13044. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  13045. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  13046. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  13047. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  13048. default:
  13049. return 0;
  13050. }
  13051. idx = 4; /* use idx now for char buffer */
  13052. if (XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  13053. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900)
  13054. >= len - idx)
  13055. {
  13056. WOLFSSL_MSG("buffer overrun in GetTimeString");
  13057. return 0;
  13058. }
  13059. return 1;
  13060. }
  13061. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  13062. #if !defined(NO_ASN_TIME) && !defined(USER_TIME) && \
  13063. !defined(TIME_OVERRIDES) && (defined(OPENSSL_EXTRA) || defined(HAVE_PKCS7))
  13064. /* Set current time string, either UTC or GeneralizedTime.
  13065. * (void*) tm should be a pointer to time_t, output is placed in buf.
  13066. *
  13067. * Return time string length placed in buf on success, negative on error */
  13068. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  13069. {
  13070. byte* data_ptr = buf;
  13071. byte uf_time[ASN_GENERALIZED_TIME_SIZE];
  13072. int data_len = 0;
  13073. WOLFSSL_ENTER("GetAsnTimeString");
  13074. if (buf == NULL || len == 0)
  13075. return BAD_FUNC_ARG;
  13076. XMEMSET(uf_time, 0, sizeof(uf_time));
  13077. /* GetFormattedTime returns length with null terminator */
  13078. data_len = GetFormattedTime(currTime, uf_time, (word32)sizeof(uf_time));
  13079. if (data_len <= 0) {
  13080. return ASN_TIME_E;
  13081. }
  13082. /* ensure room to add 2 bytes (ASN type and length) before proceeding */
  13083. else if (len < (word32)data_len + 2) {
  13084. return BUFFER_E;
  13085. }
  13086. if (data_len == ASN_UTC_TIME_SIZE-1) {
  13087. /* increment data_len for ASN length byte after adding the data_ptr */
  13088. *data_ptr = (byte)ASN_UTC_TIME; data_ptr++; data_len++;
  13089. /* -1 below excludes null terminator */
  13090. *data_ptr = (byte)ASN_UTC_TIME_SIZE - 1; data_ptr++; data_len++;
  13091. XMEMCPY(data_ptr, (byte *)uf_time, ASN_UTC_TIME_SIZE - 1);
  13092. data_ptr += ASN_UTC_TIME_SIZE - 1;
  13093. }
  13094. else if (data_len == ASN_GENERALIZED_TIME_SIZE-1) {
  13095. /* increment data_len for ASN length byte after adding the data_ptr */
  13096. *data_ptr = (byte)ASN_GENERALIZED_TIME; data_ptr++; data_len++;
  13097. /* -1 below excludes null terminator */
  13098. *data_ptr = (byte)ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++; data_len++;
  13099. XMEMCPY(data_ptr, (byte*)uf_time, ASN_GENERALIZED_TIME_SIZE - 1);
  13100. data_ptr += ASN_GENERALIZED_TIME_SIZE - 1;
  13101. }
  13102. else {
  13103. WOLFSSL_MSG("Invalid time size returned");
  13104. return ASN_TIME_E;
  13105. }
  13106. /* append null terminator */
  13107. *data_ptr = 0;
  13108. /* return length without null terminator */
  13109. return data_len;
  13110. }
  13111. /* return just the time string as either UTC or Generalized Time*/
  13112. int GetFormattedTime(void* currTime, byte* buf, word32 len)
  13113. {
  13114. struct tm* ts = NULL;
  13115. struct tm* tmpTime = NULL;
  13116. int year, mon, day, hour, mini, sec;
  13117. int ret;
  13118. #if defined(NEED_TMP_TIME)
  13119. struct tm tmpTimeStorage;
  13120. tmpTime = &tmpTimeStorage;
  13121. #endif
  13122. /* Needed in case XGMTIME does not use the tmpTime argument. */
  13123. (void)tmpTime;
  13124. WOLFSSL_ENTER("GetFormattedTime");
  13125. if (buf == NULL || len == 0)
  13126. return BAD_FUNC_ARG;
  13127. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  13128. if (ts == NULL) {
  13129. WOLFSSL_MSG("failed to get time data.");
  13130. return ASN_TIME_E;
  13131. }
  13132. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  13133. * the null terminator. ASN encoded values leave off the terminator. */
  13134. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  13135. /* UTC Time */
  13136. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  13137. year = ts->tm_year;
  13138. }
  13139. else {
  13140. year = ts->tm_year - 100;
  13141. }
  13142. mon = ts->tm_mon + 1;
  13143. day = ts->tm_mday;
  13144. hour = ts->tm_hour;
  13145. mini = ts->tm_min;
  13146. sec = ts->tm_sec;
  13147. #if defined(WOLF_C89)
  13148. if (len < ASN_UTC_TIME_SIZE) {
  13149. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13150. return BUFFER_E;
  13151. }
  13152. ret = XSPRINTF((char*)buf,
  13153. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13154. hour, mini, sec);
  13155. #else
  13156. ret = XSNPRINTF((char*)buf, len,
  13157. "%02d%02d%02d%02d%02d%02dZ", year, mon, day,
  13158. hour, mini, sec);
  13159. #endif
  13160. }
  13161. else {
  13162. /* GeneralizedTime */
  13163. year = ts->tm_year + 1900;
  13164. mon = ts->tm_mon + 1;
  13165. day = ts->tm_mday;
  13166. hour = ts->tm_hour;
  13167. mini = ts->tm_min;
  13168. sec = ts->tm_sec;
  13169. #if defined(WOLF_C89)
  13170. if (len < ASN_GENERALIZED_TIME_SIZE) {
  13171. WOLFSSL_MSG("buffer for GetFormattedTime is too short.");
  13172. return BUFFER_E;
  13173. }
  13174. ret = XSPRINTF((char*)buf,
  13175. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13176. hour, mini, sec);
  13177. #else
  13178. ret = XSNPRINTF((char*)buf, len,
  13179. "%4d%02d%02d%02d%02d%02dZ", year, mon, day,
  13180. hour, mini, sec);
  13181. #endif
  13182. }
  13183. return ret;
  13184. }
  13185. #endif /* !NO_ASN_TIME && !USER_TIME && !TIME_OVERRIDES &&
  13186. * (OPENSSL_EXTRA || HAVE_PKCS7) */
  13187. #if defined(USE_WOLF_VALIDDATE)
  13188. /* to the second */
  13189. int DateGreaterThan(const struct tm* a, const struct tm* b)
  13190. {
  13191. if (a->tm_year > b->tm_year)
  13192. return 1;
  13193. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  13194. return 1;
  13195. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13196. a->tm_mday > b->tm_mday)
  13197. return 1;
  13198. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13199. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  13200. return 1;
  13201. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13202. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13203. a->tm_min > b->tm_min)
  13204. return 1;
  13205. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  13206. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  13207. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  13208. return 1;
  13209. return 0; /* false */
  13210. }
  13211. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  13212. {
  13213. return DateGreaterThan(b,a);
  13214. }
  13215. /* like atoi but only use first byte */
  13216. /* Make sure before and after dates are valid */
  13217. int wc_ValidateDate(const byte* date, byte format, int dateType)
  13218. {
  13219. time_t ltime;
  13220. struct tm certTime;
  13221. struct tm* localTime;
  13222. struct tm* tmpTime;
  13223. int i = 0;
  13224. int timeDiff = 0;
  13225. int diffHH = 0, diffMM = 0;
  13226. #if defined(NEED_TMP_TIME)
  13227. struct tm tmpTimeStorage;
  13228. tmpTime = &tmpTimeStorage;
  13229. #else
  13230. tmpTime = NULL;
  13231. #endif
  13232. (void)tmpTime;
  13233. ltime = wc_Time(0);
  13234. if (sizeof(ltime) == sizeof(word32) && (int)ltime < 0){
  13235. /* A negative response here could be due to a 32-bit time_t
  13236. * where the year is 2038 or later. */
  13237. WOLFSSL_MSG("wc_Time failed to return a valid value");
  13238. return 0;
  13239. }
  13240. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  13241. if (dateType == BEFORE) {
  13242. WOLFSSL_MSG("Skewing local time for before date check");
  13243. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  13244. }
  13245. #endif
  13246. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  13247. if (dateType == AFTER) {
  13248. WOLFSSL_MSG("Skewing local time for after date check");
  13249. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  13250. }
  13251. #endif
  13252. if (!ExtractDate(date, format, &certTime, &i)) {
  13253. WOLFSSL_MSG("Error extracting the date");
  13254. return 0;
  13255. }
  13256. if ((date[i] == '+') || (date[i] == '-')) {
  13257. int diffSign;
  13258. WOLFSSL_MSG("Using time differential, not Zulu") ;
  13259. diffSign = date[i++] == '+' ? 1 : -1 ;
  13260. if (GetTime(&diffHH, date, &i) != 0)
  13261. return 0;
  13262. if (GetTime(&diffMM, date, &i) != 0)
  13263. return 0;
  13264. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  13265. } else if (date[i] != 'Z') {
  13266. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  13267. return 0;
  13268. }
  13269. ltime -= (time_t)timeDiff;
  13270. localTime = XGMTIME(&ltime, tmpTime);
  13271. if (localTime == NULL) {
  13272. WOLFSSL_MSG("XGMTIME failed");
  13273. return 0;
  13274. }
  13275. if (dateType == BEFORE) {
  13276. if (DateLessThan(localTime, &certTime)) {
  13277. WOLFSSL_MSG("Date BEFORE check failed");
  13278. return 0;
  13279. }
  13280. }
  13281. else { /* dateType == AFTER */
  13282. if (DateGreaterThan(localTime, &certTime)) {
  13283. WOLFSSL_MSG("Date AFTER check failed");
  13284. return 0;
  13285. }
  13286. }
  13287. return 1;
  13288. }
  13289. #endif /* USE_WOLF_VALIDDATE */
  13290. int wc_GetTime(void* timePtr, word32 timeSize)
  13291. {
  13292. time_t* ltime = (time_t*)timePtr;
  13293. if (timePtr == NULL) {
  13294. return BAD_FUNC_ARG;
  13295. }
  13296. if ((word32)sizeof(time_t) > timeSize) {
  13297. return BUFFER_E;
  13298. }
  13299. *ltime = wc_Time(0);
  13300. return 0;
  13301. }
  13302. #ifdef TIME_OVERRIDES
  13303. #ifndef HAVE_TIME_T_TYPE
  13304. typedef long time_t;
  13305. #endif
  13306. extern time_t XTIME(time_t* t);
  13307. #endif
  13308. static wc_time_cb timeFunc = NULL;
  13309. int wc_SetTimeCb(wc_time_cb f)
  13310. {
  13311. timeFunc = f;
  13312. return 0;
  13313. }
  13314. time_t wc_Time(time_t* t)
  13315. {
  13316. if (timeFunc != NULL) {
  13317. return timeFunc(t);
  13318. }
  13319. return XTIME(t);
  13320. }
  13321. #endif /* !NO_ASN_TIME */
  13322. #ifdef WOLFSSL_ASN_TEMPLATE
  13323. /* TODO: use a CHOICE instead of two items? */
  13324. /* ASN.1 template for a date - either UTC or Generalized Time. */
  13325. static const ASNItem dateASN[] = {
  13326. /* UTC */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  13327. /* GT */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  13328. };
  13329. enum {
  13330. DATEASN_IDX_UTC = 0,
  13331. DATEASN_IDX_GT
  13332. };
  13333. /* Number of items in ASN.1 template for a date. */
  13334. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  13335. #endif /* WOLFSSL_ASN_TEMPLATE */
  13336. /* Get date buffer, format and length. Returns 0=success or error */
  13337. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  13338. *
  13339. * @param [in] source Buffer containing encoded date.
  13340. * @param [in, out] idx On in, the index of the date.
  13341. * On out, index after date.
  13342. * @param [out] pDate Pointer into buffer of data bytes.
  13343. * @param [out] pFormat Format of date - BER/DER tag.
  13344. * @param [out] pLength Length of date bytes.
  13345. * @param [in] maxIdx Index of next item after date.
  13346. * @return 0 on success.
  13347. * @return BAD_FUNC_ARG when source or idx is NULL.
  13348. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13349. * is invalid.
  13350. * @return BUFFER_E when data in buffer is too small.
  13351. */
  13352. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  13353. byte* pFormat, int* pLength, word32 maxIdx)
  13354. {
  13355. #ifndef WOLFSSL_ASN_TEMPLATE
  13356. int length;
  13357. byte format;
  13358. if (source == NULL || idx == NULL)
  13359. return BAD_FUNC_ARG;
  13360. /* get ASN format header */
  13361. if (*idx+1 > maxIdx)
  13362. return BUFFER_E;
  13363. format = source[*idx];
  13364. *idx += 1;
  13365. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME) {
  13366. WOLFSSL_ERROR_VERBOSE(ASN_TIME_E);
  13367. return ASN_TIME_E;
  13368. }
  13369. /* get length */
  13370. if (GetLength(source, idx, &length, maxIdx) < 0)
  13371. return ASN_PARSE_E;
  13372. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  13373. return ASN_DATE_SZ_E;
  13374. /* return format, date and length */
  13375. if (pFormat)
  13376. *pFormat = format;
  13377. if (pDate)
  13378. *pDate = &source[*idx];
  13379. if (pLength)
  13380. *pLength = length;
  13381. *idx += (word32)length;
  13382. return 0;
  13383. #else
  13384. ASNGetData dataASN[dateASN_Length];
  13385. int ret = 0;
  13386. if ((source == NULL) || (idx == NULL)) {
  13387. ret = BAD_FUNC_ARG;
  13388. }
  13389. if (ret == 0) {
  13390. /* Initialize data. */
  13391. XMEMSET(dataASN, 0, sizeof(dataASN));
  13392. /* Parse date. */
  13393. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  13394. maxIdx);
  13395. }
  13396. if (ret == 0) {
  13397. /* Determine which tag was seen. */
  13398. int i = (dataASN[DATEASN_IDX_UTC].tag != 0) ? DATEASN_IDX_UTC
  13399. : DATEASN_IDX_GT;
  13400. /* Return data from seen item. */
  13401. if (pFormat != NULL) {
  13402. *pFormat = dataASN[i].tag;
  13403. }
  13404. if (pDate != NULL) {
  13405. *pDate = dataASN[i].data.ref.data;
  13406. }
  13407. if (pLength != NULL) {
  13408. *pLength = (int)dataASN[i].data.ref.length;
  13409. }
  13410. }
  13411. return ret;
  13412. #endif
  13413. }
  13414. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  13415. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  13416. {
  13417. int ret, length;
  13418. const byte *datePtr = NULL;
  13419. byte date[MAX_DATE_SIZE];
  13420. byte format;
  13421. word32 startIdx = 0;
  13422. if (dateType == BEFORE)
  13423. cert->beforeDate = &cert->source[cert->srcIdx];
  13424. else
  13425. cert->afterDate = &cert->source[cert->srcIdx];
  13426. startIdx = cert->srcIdx;
  13427. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  13428. &length, (word32)maxIdx);
  13429. if (ret < 0)
  13430. return ret;
  13431. XMEMSET(date, 0, MAX_DATE_SIZE);
  13432. XMEMCPY(date, datePtr, (size_t)length);
  13433. if (dateType == BEFORE)
  13434. cert->beforeDateLen = (int)(cert->srcIdx - startIdx);
  13435. else
  13436. cert->afterDateLen = (int)(cert->srcIdx - startIdx);
  13437. #ifndef NO_ASN_TIME_CHECK
  13438. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  13439. !XVALIDATE_DATE(date, format, dateType)) {
  13440. if (dateType == BEFORE) {
  13441. WOLFSSL_ERROR_VERBOSE(ASN_BEFORE_DATE_E);
  13442. return ASN_BEFORE_DATE_E;
  13443. }
  13444. else {
  13445. WOLFSSL_ERROR_VERBOSE(ASN_AFTER_DATE_E);
  13446. return ASN_AFTER_DATE_E;
  13447. }
  13448. }
  13449. #else
  13450. (void)verify;
  13451. #endif
  13452. return 0;
  13453. }
  13454. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  13455. {
  13456. int length;
  13457. int badDate = 0;
  13458. if (GetSequence(cert->source, &cert->srcIdx, &length, (word32)maxIdx) < 0)
  13459. return ASN_PARSE_E;
  13460. maxIdx = (int)cert->srcIdx + length;
  13461. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  13462. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  13463. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  13464. return ASN_AFTER_DATE_E;
  13465. if (badDate != 0)
  13466. return badDate;
  13467. return 0;
  13468. }
  13469. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  13470. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  13471. byte* format, int* length)
  13472. {
  13473. int ret;
  13474. word32 idx = 0;
  13475. ret = GetDateInfo(certDate, &idx, date, format, length, (word32)certDateSz);
  13476. return ret;
  13477. }
  13478. #ifndef NO_ASN_TIME
  13479. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  13480. struct tm* timearg)
  13481. {
  13482. int idx = 0;
  13483. (void)length;
  13484. if (!ExtractDate(date, format, timearg, &idx))
  13485. return ASN_TIME_E;
  13486. return 0;
  13487. }
  13488. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  13489. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  13490. {
  13491. int ret = 0;
  13492. const byte* date;
  13493. byte format;
  13494. int length;
  13495. if (cert == NULL)
  13496. return BAD_FUNC_ARG;
  13497. if (before && cert->beforeDateSz > 0) {
  13498. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  13499. &format, &length);
  13500. if (ret == 0)
  13501. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  13502. }
  13503. if (after && cert->afterDateSz > 0) {
  13504. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  13505. &format, &length);
  13506. if (ret == 0)
  13507. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  13508. }
  13509. return ret;
  13510. }
  13511. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  13512. #endif /* !NO_ASN_TIME */
  13513. #if !defined(WOLFSSL_ASN_TEMPLATE) && !defined(NO_CERTS)
  13514. static int GetSigAlg(DecodedCert* cert, word32* sigOid, word32 maxIdx)
  13515. {
  13516. int length;
  13517. word32 endSeqIdx;
  13518. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  13519. return ASN_PARSE_E;
  13520. endSeqIdx = cert->srcIdx + (word32)length;
  13521. if (GetObjectId(cert->source, &cert->srcIdx, sigOid, oidSigType,
  13522. maxIdx) < 0) {
  13523. return ASN_OBJECT_ID_E;
  13524. }
  13525. if (cert->srcIdx != endSeqIdx) {
  13526. #ifdef WC_RSA_PSS
  13527. if (*sigOid == CTC_RSASSAPSS) {
  13528. cert->sigParamsIndex = cert->srcIdx;
  13529. cert->sigParamsLength = endSeqIdx - cert->srcIdx;
  13530. }
  13531. else
  13532. #endif
  13533. /* Only allowed a ASN NULL header with zero length. */
  13534. if (endSeqIdx - cert->srcIdx != 2)
  13535. return ASN_PARSE_E;
  13536. else {
  13537. byte tag;
  13538. if (GetASNTag(cert->source, &cert->srcIdx, &tag, endSeqIdx) != 0)
  13539. return ASN_PARSE_E;
  13540. if (tag != ASN_TAG_NULL)
  13541. return ASN_PARSE_E;
  13542. }
  13543. }
  13544. cert->srcIdx = endSeqIdx;
  13545. return 0;
  13546. }
  13547. #endif
  13548. #ifndef NO_CERTS
  13549. #ifdef WOLFSSL_ASN_TEMPLATE
  13550. /* TODO: move code around to not require this. */
  13551. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  13552. int* badDateRet, int stopAtPubKey,
  13553. int stopAfterPubKey);
  13554. #endif
  13555. /* Parse the certificate up to the X.509 public key.
  13556. *
  13557. * If cert data is invalid then badDate get set to error value.
  13558. *
  13559. * @param [in, out] cert Decoded certificate object.
  13560. * @param [in] verify Whether to verify dates.
  13561. * @param [out] badDate Error code when verify dates.
  13562. * @return 0 on success.
  13563. * @return BAD_FUNC_ARG when cert or badDate is NULL.
  13564. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13565. * @return ASN_DATE_SZ_E when time data is not supported.
  13566. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13567. * is invalid.
  13568. * @return BUFFER_E when data in buffer is too small.
  13569. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13570. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13571. */
  13572. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  13573. {
  13574. #ifndef WOLFSSL_ASN_TEMPLATE
  13575. int ret;
  13576. if (cert == NULL || badDate == NULL)
  13577. return BAD_FUNC_ARG;
  13578. *badDate = 0;
  13579. if ( (ret = GetCertHeader(cert)) < 0)
  13580. return ret;
  13581. WOLFSSL_MSG("Got Cert Header");
  13582. #ifdef WOLFSSL_CERT_REQ
  13583. if (!cert->isCSR) {
  13584. #endif
  13585. /* Using the sigIndex as the upper bound because that's where the
  13586. * actual certificate data ends. */
  13587. if ((ret = GetSigAlg(cert, &cert->signatureOID, cert->sigIndex)) < 0)
  13588. return ret;
  13589. WOLFSSL_MSG("Got Algo ID");
  13590. if ( (ret = GetName(cert, ISSUER, (int)cert->sigIndex)) < 0)
  13591. return ret;
  13592. if ( (ret = GetValidity(cert, verify, (int)cert->sigIndex)) < 0)
  13593. *badDate = ret;
  13594. #ifdef WOLFSSL_CERT_REQ
  13595. }
  13596. #endif
  13597. if ( (ret = GetName(cert, SUBJECT, (int)cert->sigIndex)) < 0)
  13598. return ret;
  13599. WOLFSSL_MSG("Got Subject Name");
  13600. return ret;
  13601. #else
  13602. /* Use common decode routine and stop at public key. */
  13603. int ret;
  13604. *badDate = 0;
  13605. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  13606. if (ret >= 0) {
  13607. /* Store current index: public key. */
  13608. cert->srcIdx = (word32)ret;
  13609. }
  13610. return ret;
  13611. #endif /* WOLFSSL_ASN_TEMPLATE */
  13612. }
  13613. /* Parse the certificate up to and including X.509 public key.
  13614. *
  13615. * @param [in, out] cert Decoded certificate object.
  13616. * @param [in] verify Whether to verify dates.
  13617. * @return 0 on success.
  13618. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  13619. * @return ASN_DATE_SZ_E when time data is not supported.
  13620. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  13621. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  13622. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13623. * is invalid.
  13624. * @return BUFFER_E when data in buffer is too small.
  13625. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13626. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13627. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  13628. */
  13629. int DecodeToKey(DecodedCert* cert, int verify)
  13630. {
  13631. #ifndef WOLFSSL_ASN_TEMPLATE
  13632. int badDate = 0;
  13633. int ret;
  13634. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  13635. return ret;
  13636. /* Determine if self signed */
  13637. #ifdef WOLFSSL_CERT_REQ
  13638. if (cert->isCSR)
  13639. cert->selfSigned = 1;
  13640. else
  13641. #endif
  13642. {
  13643. cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
  13644. KEYID_SIZE) == 0 ? 1 : 0;
  13645. }
  13646. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  13647. if (ret != 0)
  13648. return ret;
  13649. WOLFSSL_MSG("Got Key");
  13650. if (badDate != 0)
  13651. return badDate;
  13652. return ret;
  13653. #else
  13654. int ret;
  13655. int badDate = 0;
  13656. /* Call internal version and stop after public key. */
  13657. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  13658. /* Always return date errors. */
  13659. if (ret == 0) {
  13660. ret = badDate;
  13661. }
  13662. return ret;
  13663. #endif /* WOLFSSL_ASN_TEMPLATE */
  13664. }
  13665. #if !defined(WOLFSSL_ASN_TEMPLATE)
  13666. static int GetSignature(DecodedCert* cert)
  13667. {
  13668. int length;
  13669. int ret;
  13670. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  13671. NULL);
  13672. if (ret != 0)
  13673. return ret;
  13674. cert->sigLength = (word32)length;
  13675. cert->signature = &cert->source[cert->srcIdx];
  13676. cert->srcIdx += cert->sigLength;
  13677. if (cert->srcIdx != cert->maxIdx)
  13678. return ASN_PARSE_E;
  13679. return 0;
  13680. }
  13681. #endif /* !WOLFSSL_ASN_TEMPLATE */
  13682. #endif /* !NO_CERTS */
  13683. #ifndef WOLFSSL_ASN_TEMPLATE
  13684. static word32 SetOctetString8Bit(word32 len, byte* output)
  13685. {
  13686. output[0] = ASN_OCTET_STRING;
  13687. output[1] = (byte)len;
  13688. return 2;
  13689. }
  13690. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  13691. {
  13692. word32 idx = SetOctetString8Bit(digSz, output);
  13693. XMEMCPY(&output[idx], digest, digSz);
  13694. return idx + digSz;
  13695. }
  13696. #endif
  13697. /* Encode a length for DER.
  13698. *
  13699. * @param [in] length Value to encode.
  13700. * @param [out] output Buffer to encode into.
  13701. * @return Number of bytes encoded.
  13702. */
  13703. word32 SetLength(word32 length, byte* output)
  13704. {
  13705. /* Start encoding at start of buffer. */
  13706. word32 i = 0;
  13707. if (length < ASN_LONG_LENGTH) {
  13708. /* Only one byte needed to encode. */
  13709. if (output) {
  13710. /* Write out length value. */
  13711. output[i] = (byte)length;
  13712. }
  13713. /* Skip over length. */
  13714. i++;
  13715. }
  13716. else {
  13717. /* Calculate the number of bytes required to encode value. */
  13718. byte j = (byte)BytePrecision(length);
  13719. if (output) {
  13720. /* Encode count byte. */
  13721. output[i] = (byte)(j | ASN_LONG_LENGTH);
  13722. }
  13723. /* Skip over count byte. */
  13724. i++;
  13725. /* Encode value as a big-endian byte array. */
  13726. for (; j > 0; --j) {
  13727. if (output) {
  13728. /* Encode next most-significant byte. */
  13729. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  13730. }
  13731. /* Skip over byte. */
  13732. i++;
  13733. }
  13734. }
  13735. /* Return number of bytes in encoded length. */
  13736. return i;
  13737. }
  13738. /* Encode a DER header - type/tag and length.
  13739. *
  13740. * @param [in] tag DER tag of ASN.1 item.
  13741. * @param [in] len Length of data in ASN.1 item.
  13742. * @param [out] output Buffer to encode into.
  13743. * @return Number of bytes encoded.
  13744. */
  13745. static word32 SetHeader(byte tag, word32 len, byte* output)
  13746. {
  13747. if (output) {
  13748. /* Encode tag first. */
  13749. output[0] = tag;
  13750. }
  13751. /* Encode the length. */
  13752. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  13753. }
  13754. /* Encode a SEQUENCE header in DER.
  13755. *
  13756. * @param [in] len Length of data in SEQUENCE.
  13757. * @param [out] output Buffer to encode into.
  13758. * @return Number of bytes encoded.
  13759. */
  13760. word32 SetSequence(word32 len, byte* output)
  13761. {
  13762. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  13763. }
  13764. /* Encode an OCTET STRING header in DER.
  13765. *
  13766. * @param [in] len Length of data in OCTET STRING.
  13767. * @param [out] output Buffer to encode into.
  13768. * @return Number of bytes encoded.
  13769. */
  13770. word32 SetOctetString(word32 len, byte* output)
  13771. {
  13772. return SetHeader(ASN_OCTET_STRING, len, output);
  13773. }
  13774. /* Encode a SET header in DER.
  13775. *
  13776. * @param [in] len Length of data in SET.
  13777. * @param [out] output Buffer to encode into.
  13778. * @return Number of bytes encoded.
  13779. */
  13780. word32 SetSet(word32 len, byte* output)
  13781. {
  13782. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  13783. }
  13784. /* Encode an implicit context specific header in DER.
  13785. *
  13786. * Implicit means that it is constructed only if the included ASN.1 item is.
  13787. *
  13788. * @param [in] tag Tag for the implicit ASN.1 item.
  13789. * @param [in] number Context specific number.
  13790. * @param [in] len Length of data in SET.
  13791. * @param [out] output Buffer to encode into.
  13792. * @return Number of bytes encoded.
  13793. */
  13794. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  13795. {
  13796. tag = (byte)(((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  13797. | ASN_CONTEXT_SPECIFIC | number);
  13798. return SetHeader(tag, len, output);
  13799. }
  13800. /* Encode an explicit context specific header in DER.
  13801. *
  13802. * Explicit means that there will be an ASN.1 item underneath.
  13803. *
  13804. * @param [in] number Context specific number.
  13805. * @param [in] len Length of data in SET.
  13806. * @param [out] output Buffer to encode into.
  13807. * @return Number of bytes encoded.
  13808. */
  13809. word32 SetExplicit(byte number, word32 len, byte* output)
  13810. {
  13811. return SetHeader((byte)(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number),
  13812. len, output);
  13813. }
  13814. #if defined(OPENSSL_EXTRA)
  13815. /* Encode an Othername into DER.
  13816. *
  13817. * @param [in] name Pointer to the WOLFSSL_ASN1_OTHERNAME to be encoded.
  13818. * @param [out] output Buffer to encode into. If NULL, don't encode.
  13819. * @return Number of bytes encoded or WOLFSSL_FAILURE if name parameter is bad.
  13820. */
  13821. word32 SetOthername(void *name, byte *output)
  13822. {
  13823. WOLFSSL_ASN1_OTHERNAME *nm = (WOLFSSL_ASN1_OTHERNAME *)name;
  13824. char *nameStr = NULL;
  13825. int nameSz = 0;
  13826. word32 len = 0;
  13827. if ((nm == NULL) || (nm->value == NULL)) {
  13828. WOLFSSL_MSG("otherName value is NULL");
  13829. return WOLFSSL_FAILURE;
  13830. }
  13831. nameStr = nm->value->value.utf8string->data;
  13832. nameSz = nm->value->value.utf8string->length;
  13833. len = nm->type_id->objSz +
  13834. SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2, NULL) +
  13835. SetHeader(CTC_UTF8, nameSz, NULL) + nameSz;
  13836. if (output != NULL) {
  13837. /* otherName OID */
  13838. XMEMCPY(output, nm->type_id->obj, nm->type_id->objSz);
  13839. output += nm->type_id->objSz;
  13840. output += SetHeader(ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC, nameSz + 2,
  13841. output);
  13842. output += SetHeader(CTC_UTF8, nameSz, output);
  13843. XMEMCPY(output, nameStr, nameSz);
  13844. }
  13845. return len;
  13846. }
  13847. #endif /* OPENSSL_EXTRA */
  13848. #ifdef HAVE_ECC
  13849. /* Determines whether the signature algorithm is using ECDSA.
  13850. *
  13851. * @param [in] algoOID Signature algorithm identifier.
  13852. * @return 1 when algorithm is using ECDSA.
  13853. * @return 0 otherwise.
  13854. */
  13855. static WC_INLINE int IsSigAlgoECDSA(word32 algoOID)
  13856. {
  13857. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  13858. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  13859. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  13860. return 1;
  13861. }
  13862. return 0;
  13863. }
  13864. #endif
  13865. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA
  13866. * and post-quantum algorithms.
  13867. *
  13868. * @param [in] algoOID Algorithm OID.
  13869. * @return 1 when is EC signing algorithm.
  13870. * @return 0 otherwise.
  13871. */
  13872. static WC_INLINE int IsSigAlgoECC(word32 algoOID)
  13873. {
  13874. (void)algoOID;
  13875. return (0
  13876. #ifdef HAVE_ECC
  13877. || IsSigAlgoECDSA(algoOID)
  13878. #endif
  13879. #ifdef WOLFSSL_SM2
  13880. || (algoOID == SM2k)
  13881. #endif
  13882. #ifdef HAVE_ED25519
  13883. || (algoOID == ED25519k)
  13884. #endif
  13885. #ifdef HAVE_CURVE25519
  13886. || (algoOID == X25519k)
  13887. #endif
  13888. #ifdef HAVE_ED448
  13889. || (algoOID == ED448k)
  13890. #endif
  13891. #ifdef HAVE_CURVE448
  13892. || (algoOID == X448k)
  13893. #endif
  13894. #ifdef HAVE_PQC
  13895. #ifdef HAVE_FACON
  13896. || (algoOID == FALCON_LEVEL1k)
  13897. || (algoOID == FALCON_LEVEL5k)
  13898. #endif
  13899. #ifdef HAVE_DILITHIUM
  13900. || (algoOID == DILITHIUM_LEVEL2k)
  13901. || (algoOID == DILITHIUM_LEVEL3k)
  13902. || (algoOID == DILITHIUM_LEVEL5k)
  13903. #endif
  13904. #ifdef HAVE_SPHINCS
  13905. || (algoOID == SPHINCS_FAST_LEVEL1k)
  13906. || (algoOID == SPHINCS_FAST_LEVEL3k)
  13907. || (algoOID == SPHINCS_FAST_LEVEL5k)
  13908. || (algoOID == SPHINCS_SMALL_LEVEL1k)
  13909. || (algoOID == SPHINCS_SMALL_LEVEL3k)
  13910. || (algoOID == SPHINCS_SMALL_LEVEL5k)
  13911. #endif
  13912. #endif /* HAVE_PQC */
  13913. );
  13914. }
  13915. /* Encode an algorithm identifier.
  13916. *
  13917. * [algoOID, type] is unique.
  13918. *
  13919. * @param [in] algoOID Algorithm identifier.
  13920. * @param [out] output Buffer to hold encoding.
  13921. * @param [in] type Type of OID being encoded.
  13922. * @param [in] curveSz Add extra space for curve data.
  13923. * @return Encoded data size on success.
  13924. * @return 0 when dynamic memory allocation fails.
  13925. */
  13926. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  13927. {
  13928. #ifndef WOLFSSL_ASN_TEMPLATE
  13929. word32 tagSz, idSz, seqSz, algoSz = 0;
  13930. const byte* algoName = 0;
  13931. byte ID_Length[1 + MAX_LENGTH_SZ];
  13932. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  13933. word32 length = 0;
  13934. tagSz = (type == oidHashType ||
  13935. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13936. (type == oidKeyType && algoOID == RSAk)) ? 2U : 0U;
  13937. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13938. if (algoName == NULL) {
  13939. WOLFSSL_MSG("Unknown Algorithm");
  13940. return 0;
  13941. }
  13942. idSz = (word32)SetObjectId((int)algoSz, ID_Length);
  13943. seqSz = SetSequence(idSz + algoSz + tagSz + (word32)curveSz, seqArray);
  13944. /* Copy only algo to output for DSA keys */
  13945. if (algoOID == DSAk && output) {
  13946. XMEMCPY(output, ID_Length, idSz);
  13947. XMEMCPY(output + idSz, algoName, algoSz);
  13948. if (tagSz == 2)
  13949. SetASNNull(&output[seqSz + idSz + algoSz]);
  13950. }
  13951. else if (output) {
  13952. XMEMCPY(output, seqArray, seqSz);
  13953. XMEMCPY(output + seqSz, ID_Length, idSz);
  13954. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  13955. if (tagSz == 2)
  13956. SetASNNull(&output[seqSz + idSz + algoSz]);
  13957. }
  13958. if (algoOID == DSAk)
  13959. length = idSz + algoSz + tagSz;
  13960. else
  13961. length = seqSz + idSz + algoSz + tagSz;
  13962. return length;
  13963. #else
  13964. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  13965. int ret = 0;
  13966. const byte* algoName = 0;
  13967. word32 algoSz = 0;
  13968. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  13969. algoName = OidFromId((word32)algoOID, (word32)type, &algoSz);
  13970. if (algoName == NULL) {
  13971. WOLFSSL_MSG("Unknown Algorithm");
  13972. }
  13973. else {
  13974. int sz;
  13975. int o = 0;
  13976. /* Set the OID and OID type to encode. */
  13977. SetASN_OID(&dataASN[ALGOIDASN_IDX_OID], (word32)algoOID, (word32)type);
  13978. /* Hashes, signatures not ECC and keys not RSA output NULL tag. */
  13979. if (!(type == oidHashType ||
  13980. (type == oidSigType && !IsSigAlgoECC((word32)algoOID)) ||
  13981. (type == oidKeyType && algoOID == RSAk))) {
  13982. /* Don't put out NULL DER item. */
  13983. dataASN[ALGOIDASN_IDX_NULL].noOut = 1;
  13984. }
  13985. if (algoOID == DSAk) {
  13986. /* Don't include SEQUENCE for DSA keys. */
  13987. o = 1;
  13988. }
  13989. else if (curveSz > 0) {
  13990. /* Don't put out NULL DER item. */
  13991. dataASN[ALGOIDASN_IDX_NULL].noOut = 0;
  13992. /* Include space for extra data of length curveSz.
  13993. * Subtract 1 for sequence and 1 for length encoding. */
  13994. SetASN_Buffer(&dataASN[ALGOIDASN_IDX_NULL], NULL,
  13995. (word32)curveSz - 2);
  13996. }
  13997. /* Calculate size of encoding. */
  13998. ret = SizeASN_Items(algoIdASN + o, dataASN + o,
  13999. (int)algoIdASN_Length - (int)o, &sz);
  14000. if (ret == 0 && output != NULL) {
  14001. /* Encode into buffer. */
  14002. SetASN_Items(algoIdASN + o, dataASN + o,
  14003. (int)algoIdASN_Length - (int)o, output);
  14004. if (curveSz > 0) {
  14005. /* Return size excluding curve data. */
  14006. sz = (int)(dataASN[o].offset -
  14007. dataASN[ALGOIDASN_IDX_NULL].offset);
  14008. }
  14009. }
  14010. if (ret == 0) {
  14011. /* Return encoded size. */
  14012. ret = sz;
  14013. }
  14014. else {
  14015. /* Unsigned return type so 0 indicates error. */
  14016. ret = 0;
  14017. }
  14018. }
  14019. FREE_ASNSETDATA(dataASN, NULL);
  14020. return (word32)ret;
  14021. #endif /* WOLFSSL_ASN_TEMPLATE */
  14022. }
  14023. #ifdef WOLFSSL_ASN_TEMPLATE
  14024. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  14025. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  14026. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  14027. */
  14028. static const ASNItem digestInfoASN[] = {
  14029. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14030. /* digestAlgorithm */
  14031. /* DIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14032. /* DIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  14033. /* DIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  14034. /* digest */
  14035. /* DIGEST */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  14036. };
  14037. enum {
  14038. DIGESTINFOASN_IDX_SEQ = 0,
  14039. DIGESTINFOASN_IDX_DIGALGO_SEQ,
  14040. DIGESTINFOASN_IDX_DIGALGO_OID,
  14041. DIGESTINFOASN_IDX_DIGALGO_NULL,
  14042. DIGESTINFOASN_IDX_DIGEST
  14043. };
  14044. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  14045. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  14046. #endif
  14047. /* Encode signature.
  14048. *
  14049. * @param [out] out Buffer to hold encoding.
  14050. * @param [in] digest Buffer holding digest.
  14051. * @param [in] digSz Length of digest in bytes.
  14052. * @return Encoded data size on success.
  14053. * @return 0 when dynamic memory allocation fails.
  14054. */
  14055. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  14056. int hashOID)
  14057. {
  14058. #ifndef WOLFSSL_ASN_TEMPLATE
  14059. byte digArray[MAX_ENCODED_DIG_SZ];
  14060. byte algoArray[MAX_ALGO_SZ];
  14061. byte seqArray[MAX_SEQ_SZ];
  14062. word32 encDigSz, algoSz, seqSz;
  14063. encDigSz = SetDigest(digest, digSz, digArray);
  14064. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  14065. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  14066. XMEMCPY(out, seqArray, seqSz);
  14067. XMEMCPY(out + seqSz, algoArray, algoSz);
  14068. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  14069. return encDigSz + algoSz + seqSz;
  14070. #else
  14071. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  14072. int ret = 0;
  14073. int sz;
  14074. unsigned char dgst[WC_MAX_DIGEST_SIZE];
  14075. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  14076. if (ret == 0) {
  14077. /* Set hash OID and type. */
  14078. SetASN_OID(&dataASN[DIGESTINFOASN_IDX_DIGALGO_OID], (word32)hashOID,
  14079. oidHashType);
  14080. /* Set digest. */
  14081. if (digest == out) {
  14082. XMEMCPY(dgst, digest, digSz);
  14083. digest = dgst;
  14084. }
  14085. SetASN_Buffer(&dataASN[DIGESTINFOASN_IDX_DIGEST], digest, digSz);
  14086. /* Calculate size of encoding. */
  14087. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  14088. }
  14089. if (ret == 0) {
  14090. /* Encode PKCS#1 v1.5 RSA signature. */
  14091. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  14092. ret = sz;
  14093. }
  14094. else {
  14095. /* Unsigned return type so 0 indicates error. */
  14096. ret = 0;
  14097. }
  14098. FREE_ASNSETDATA(dataASN, NULL);
  14099. return (word32)ret;
  14100. #endif
  14101. }
  14102. #ifndef NO_CERTS
  14103. int wc_GetCTC_HashOID(int type)
  14104. {
  14105. int ret;
  14106. enum wc_HashType hType;
  14107. hType = wc_HashTypeConvert(type);
  14108. ret = wc_HashGetOID(hType);
  14109. if (ret < 0) {
  14110. ret = 0; /* backwards compatibility */
  14111. }
  14112. return ret;
  14113. }
  14114. /* Initialize a signature context object.
  14115. *
  14116. * Object used for signing and verifying a certificate signature.
  14117. *
  14118. * @param [in, out] sigCtx Signature context object.
  14119. * @param [in] heap Dynamic memory hint.
  14120. * @param [in] devId Hardware device identifier.
  14121. */
  14122. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  14123. {
  14124. if (sigCtx) {
  14125. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  14126. sigCtx->devId = devId;
  14127. sigCtx->heap = heap;
  14128. }
  14129. }
  14130. /* Free dynamic data in a signature context object.
  14131. *
  14132. * @param [in, out] sigCtx Signature context object.
  14133. */
  14134. void FreeSignatureCtx(SignatureCtx* sigCtx)
  14135. {
  14136. if (sigCtx == NULL)
  14137. return;
  14138. if (sigCtx->digest) {
  14139. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  14140. sigCtx->digest = NULL;
  14141. }
  14142. #if !(defined(NO_RSA) && defined(NO_DSA))
  14143. if (sigCtx->sigCpy) {
  14144. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14145. sigCtx->sigCpy = NULL;
  14146. }
  14147. #endif
  14148. #ifndef NO_ASN_CRYPT
  14149. if (sigCtx->key.ptr) {
  14150. switch (sigCtx->keyOID) {
  14151. #ifndef NO_RSA
  14152. #ifdef WC_RSA_PSS
  14153. case RSAPSSk:
  14154. #endif
  14155. case RSAk:
  14156. wc_FreeRsaKey(sigCtx->key.rsa);
  14157. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  14158. sigCtx->key.rsa = NULL;
  14159. break;
  14160. #endif /* !NO_RSA */
  14161. #ifndef NO_DSA
  14162. case DSAk:
  14163. wc_FreeDsaKey(sigCtx->key.dsa);
  14164. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  14165. sigCtx->key.dsa = NULL;
  14166. break;
  14167. #endif
  14168. #ifdef HAVE_ECC
  14169. case ECDSAk:
  14170. #ifdef WOLFSSL_SM2
  14171. case SM2k:
  14172. #endif
  14173. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14174. defined(WC_ASYNC_ENABLE_ECC)
  14175. if (sigCtx->key.ecc->nb_ctx != NULL) {
  14176. XFREE(sigCtx->key.ecc->nb_ctx, sigCtx->heap,
  14177. DYNAMIC_TYPE_TMP_BUFFER);
  14178. }
  14179. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14180. WC_ASYNC_ENABLE_ECC */
  14181. wc_ecc_free(sigCtx->key.ecc);
  14182. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  14183. sigCtx->key.ecc = NULL;
  14184. break;
  14185. #endif /* HAVE_ECC */
  14186. #ifdef HAVE_ED25519
  14187. case ED25519k:
  14188. wc_ed25519_free(sigCtx->key.ed25519);
  14189. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  14190. sigCtx->key.ed25519 = NULL;
  14191. break;
  14192. #endif /* HAVE_ED25519 */
  14193. #ifdef HAVE_ED448
  14194. case ED448k:
  14195. wc_ed448_free(sigCtx->key.ed448);
  14196. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  14197. sigCtx->key.ed448 = NULL;
  14198. break;
  14199. #endif /* HAVE_ED448 */
  14200. #if defined(HAVE_PQC)
  14201. #if defined(HAVE_FALCON)
  14202. case FALCON_LEVEL1k:
  14203. case FALCON_LEVEL5k:
  14204. wc_falcon_free(sigCtx->key.falcon);
  14205. XFREE(sigCtx->key.falcon, sigCtx->heap,
  14206. DYNAMIC_TYPE_FALCON);
  14207. sigCtx->key.falcon = NULL;
  14208. break;
  14209. #endif /* HAVE_FALCON */
  14210. #if defined(HAVE_DILITHIUM)
  14211. case DILITHIUM_LEVEL2k:
  14212. case DILITHIUM_LEVEL3k:
  14213. case DILITHIUM_LEVEL5k:
  14214. wc_dilithium_free(sigCtx->key.dilithium);
  14215. XFREE(sigCtx->key.dilithium, sigCtx->heap,
  14216. DYNAMIC_TYPE_DILITHIUM);
  14217. sigCtx->key.dilithium = NULL;
  14218. break;
  14219. #endif /* HAVE_DILITHIUM */
  14220. #if defined(HAVE_SPHINCS)
  14221. case SPHINCS_FAST_LEVEL1k:
  14222. case SPHINCS_FAST_LEVEL3k:
  14223. case SPHINCS_FAST_LEVEL5k:
  14224. case SPHINCS_SMALL_LEVEL1k:
  14225. case SPHINCS_SMALL_LEVEL3k:
  14226. case SPHINCS_SMALL_LEVEL5k:
  14227. wc_sphincs_free(sigCtx->key.sphincs);
  14228. XFREE(sigCtx->key.sphincs, sigCtx->heap,
  14229. DYNAMIC_TYPE_SPHINCS);
  14230. sigCtx->key.sphincs = NULL;
  14231. break;
  14232. #endif /* HAVE_SPHINCS */
  14233. #endif /* HAVE_PQC */
  14234. default:
  14235. break;
  14236. } /* switch (keyOID) */
  14237. sigCtx->key.ptr = NULL;
  14238. }
  14239. #endif
  14240. /* reset state, we are done */
  14241. sigCtx->state = SIG_STATE_BEGIN;
  14242. }
  14243. #if !defined(NO_ASN_CRYPT) && !defined(NO_HASH_WRAPPER)
  14244. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  14245. byte* digest, int* typeH, int* digestSz, int verify)
  14246. {
  14247. int ret = 0;
  14248. switch (sigOID) {
  14249. #if defined(WOLFSSL_MD2)
  14250. case CTC_MD2wRSA:
  14251. if (!verify) {
  14252. ret = HASH_TYPE_E;
  14253. WOLFSSL_MSG("MD2 not supported for signing");
  14254. }
  14255. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  14256. *typeH = MD2h;
  14257. *digestSz = MD2_DIGEST_SIZE;
  14258. }
  14259. break;
  14260. #endif
  14261. #ifndef NO_MD5
  14262. case CTC_MD5wRSA:
  14263. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  14264. *typeH = MD5h;
  14265. *digestSz = WC_MD5_DIGEST_SIZE;
  14266. }
  14267. break;
  14268. #endif
  14269. #ifndef NO_SHA
  14270. case CTC_SHAwRSA:
  14271. case CTC_SHAwDSA:
  14272. case CTC_SHAwECDSA:
  14273. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  14274. *typeH = SHAh;
  14275. *digestSz = WC_SHA_DIGEST_SIZE;
  14276. }
  14277. break;
  14278. #endif
  14279. #ifdef WOLFSSL_SHA224
  14280. case CTC_SHA224wRSA:
  14281. case CTC_SHA224wECDSA:
  14282. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  14283. *typeH = SHA224h;
  14284. *digestSz = WC_SHA224_DIGEST_SIZE;
  14285. }
  14286. break;
  14287. #endif
  14288. #ifndef NO_SHA256
  14289. case CTC_SHA256wRSA:
  14290. case CTC_SHA256wECDSA:
  14291. case CTC_SHA256wDSA:
  14292. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  14293. *typeH = SHA256h;
  14294. *digestSz = WC_SHA256_DIGEST_SIZE;
  14295. }
  14296. break;
  14297. #endif
  14298. #ifdef WOLFSSL_SHA384
  14299. case CTC_SHA384wRSA:
  14300. case CTC_SHA384wECDSA:
  14301. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  14302. *typeH = SHA384h;
  14303. *digestSz = WC_SHA384_DIGEST_SIZE;
  14304. }
  14305. break;
  14306. #endif
  14307. #ifdef WOLFSSL_SHA512
  14308. case CTC_SHA512wRSA:
  14309. case CTC_SHA512wECDSA:
  14310. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  14311. *typeH = SHA512h;
  14312. *digestSz = WC_SHA512_DIGEST_SIZE;
  14313. }
  14314. break;
  14315. #endif
  14316. #ifdef WOLFSSL_SHA3
  14317. #ifndef WOLFSSL_NOSHA3_224
  14318. case CTC_SHA3_224wRSA:
  14319. case CTC_SHA3_224wECDSA:
  14320. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  14321. *typeH = SHA3_224h;
  14322. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  14323. }
  14324. break;
  14325. #endif
  14326. #ifndef WOLFSSL_NOSHA3_256
  14327. case CTC_SHA3_256wRSA:
  14328. case CTC_SHA3_256wECDSA:
  14329. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  14330. *typeH = SHA3_256h;
  14331. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  14332. }
  14333. break;
  14334. #endif
  14335. #ifndef WOLFSSL_NOSHA3_384
  14336. case CTC_SHA3_384wRSA:
  14337. case CTC_SHA3_384wECDSA:
  14338. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  14339. *typeH = SHA3_384h;
  14340. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  14341. }
  14342. break;
  14343. #endif
  14344. #ifndef WOLFSSL_NOSHA3_512
  14345. case CTC_SHA3_512wRSA:
  14346. case CTC_SHA3_512wECDSA:
  14347. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  14348. *typeH = SHA3_512h;
  14349. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  14350. }
  14351. break;
  14352. #endif
  14353. #endif
  14354. #if defined(WOLFSSL_SM2) & defined(WOLFSSL_SM3)
  14355. case CTC_SM3wSM2:
  14356. if ((ret = wc_Sm3Hash(buf, bufSz, digest)) == 0) {
  14357. *typeH = SM3h;
  14358. *digestSz = WC_SM3_DIGEST_SIZE;
  14359. }
  14360. break;
  14361. #endif
  14362. #ifdef HAVE_ED25519
  14363. case CTC_ED25519:
  14364. /* Hashes done in signing operation.
  14365. * Two dependent hashes with prefixes performed.
  14366. */
  14367. break;
  14368. #endif
  14369. #ifdef HAVE_ED448
  14370. case CTC_ED448:
  14371. /* Hashes done in signing operation.
  14372. * Two dependent hashes with prefixes performed.
  14373. */
  14374. break;
  14375. #endif
  14376. #ifdef HAVE_PQC
  14377. #ifdef HAVE_FALCON
  14378. case CTC_FALCON_LEVEL1:
  14379. case CTC_FALCON_LEVEL5:
  14380. /* Hashes done in signing operation. */
  14381. break;
  14382. #endif
  14383. #ifdef HAVE_DILITHIUM
  14384. case CTC_DILITHIUM_LEVEL2:
  14385. case CTC_DILITHIUM_LEVEL3:
  14386. case CTC_DILITHIUM_LEVEL5:
  14387. /* Hashes done in signing operation. */
  14388. break;
  14389. #endif
  14390. #ifdef HAVE_SPHINCS
  14391. case CTC_SPHINCS_FAST_LEVEL1:
  14392. case CTC_SPHINCS_FAST_LEVEL3:
  14393. case CTC_SPHINCS_FAST_LEVEL5:
  14394. case CTC_SPHINCS_SMALL_LEVEL1:
  14395. case CTC_SPHINCS_SMALL_LEVEL3:
  14396. case CTC_SPHINCS_SMALL_LEVEL5:
  14397. /* Hashes done in signing operation. */
  14398. break;
  14399. #endif
  14400. #endif /* HAVE_PQC */
  14401. default:
  14402. ret = HASH_TYPE_E;
  14403. WOLFSSL_MSG("Hash for Signature has unsupported type");
  14404. }
  14405. (void)buf;
  14406. (void)bufSz;
  14407. (void)sigOID;
  14408. (void)digest;
  14409. (void)digestSz;
  14410. (void)typeH;
  14411. (void)verify;
  14412. return ret;
  14413. }
  14414. #endif /* !NO_ASN_CRYPT && !NO_HASH_WRAPPER */
  14415. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  14416. static int ConfirmSignature(SignatureCtx* sigCtx,
  14417. const byte* buf, word32 bufSz,
  14418. const byte* key, word32 keySz, word32 keyOID,
  14419. const byte* sig, word32 sigSz, word32 sigOID,
  14420. const byte* sigParams, word32 sigParamsSz,
  14421. byte* rsaKeyIdx)
  14422. {
  14423. int ret = 0;
  14424. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  14425. CertAttribute* certatt = NULL;
  14426. #endif
  14427. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  14428. keySz == 0 || sig == NULL || sigSz == 0) {
  14429. return BAD_FUNC_ARG;
  14430. }
  14431. (void)key;
  14432. (void)keySz;
  14433. (void)sig;
  14434. (void)sigSz;
  14435. (void)sigParams;
  14436. (void)sigParamsSz;
  14437. WOLFSSL_ENTER("ConfirmSignature");
  14438. #if !defined(WOLFSSL_RENESAS_TSIP_TLS) && !defined(WOLFSSL_RENESAS_SCEPROTECT)
  14439. (void)rsaKeyIdx;
  14440. #else
  14441. #if !defined(NO_RSA) || defined(HAVE_ECC)
  14442. certatt = (CertAttribute*)&sigCtx->CertAtt;
  14443. #endif
  14444. if (certatt) {
  14445. certatt->keyIndex = rsaKeyIdx;
  14446. certatt->cert = buf;
  14447. certatt->certSz = bufSz;
  14448. }
  14449. #endif
  14450. #ifndef NO_ASN_CRYPT
  14451. switch (sigCtx->state) {
  14452. case SIG_STATE_BEGIN:
  14453. {
  14454. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  14455. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  14456. DYNAMIC_TYPE_DIGEST);
  14457. if (sigCtx->digest == NULL) {
  14458. ERROR_OUT(MEMORY_E, exit_cs);
  14459. }
  14460. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14461. /* RSA PSS Defaults */
  14462. sigCtx->hash = WC_HASH_TYPE_SHA;
  14463. sigCtx->mgf = WC_MGF1SHA1;
  14464. sigCtx->saltLen = 20;
  14465. #endif
  14466. sigCtx->state = SIG_STATE_HASH;
  14467. } /* SIG_STATE_BEGIN */
  14468. FALL_THROUGH;
  14469. case SIG_STATE_HASH:
  14470. {
  14471. #if !defined(NO_RSA) && defined(WC_RSA_PSS)
  14472. if (sigOID == RSAPSSk) {
  14473. word32 fakeSigOID = 0;
  14474. ret = DecodeRsaPssParams(sigParams, sigParamsSz, &sigCtx->hash,
  14475. &sigCtx->mgf, &sigCtx->saltLen);
  14476. if (ret != 0) {
  14477. goto exit_cs;
  14478. }
  14479. ret = RsaPssHashOidToSigOid(sigCtx->hash, &fakeSigOID);
  14480. if (ret != 0) {
  14481. goto exit_cs;
  14482. }
  14483. /* Decode parameters. */
  14484. ret = HashForSignature(buf, bufSz, fakeSigOID, sigCtx->digest,
  14485. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14486. if (ret != 0) {
  14487. goto exit_cs;
  14488. }
  14489. }
  14490. else
  14491. #endif
  14492. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14493. if (sigOID == CTC_SM3wSM2) {
  14494. ; /* SM2 hash requires public key. Done later. */
  14495. }
  14496. else
  14497. #endif
  14498. {
  14499. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  14500. &sigCtx->typeH, &sigCtx->digestSz, 1);
  14501. if (ret != 0) {
  14502. goto exit_cs;
  14503. }
  14504. }
  14505. sigCtx->state = SIG_STATE_KEY;
  14506. } /* SIG_STATE_HASH */
  14507. FALL_THROUGH;
  14508. case SIG_STATE_KEY:
  14509. {
  14510. switch (keyOID) {
  14511. #ifndef NO_RSA
  14512. #ifdef WC_RSA_PSS
  14513. case RSAPSSk:
  14514. #endif
  14515. case RSAk:
  14516. {
  14517. word32 idx = 0;
  14518. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  14519. sigCtx->heap, DYNAMIC_TYPE_RSA);
  14520. if (sigCtx->key.rsa == NULL) {
  14521. ERROR_OUT(MEMORY_E, exit_cs);
  14522. }
  14523. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  14524. sigCtx->devId)) != 0) {
  14525. goto exit_cs;
  14526. }
  14527. sigCtx->sigCpy = (byte*)XMALLOC(sigSz, sigCtx->heap,
  14528. DYNAMIC_TYPE_SIGNATURE);
  14529. if (sigCtx->sigCpy == NULL) {
  14530. ERROR_OUT(MEMORY_E, exit_cs);
  14531. }
  14532. if (sigSz > MAX_ENCODED_SIG_SZ) {
  14533. WOLFSSL_MSG("Verify Signature is too big");
  14534. ERROR_OUT(BUFFER_E, exit_cs);
  14535. }
  14536. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  14537. keySz)) != 0) {
  14538. WOLFSSL_MSG("ASN Key decode error RSA");
  14539. WOLFSSL_ERROR_VERBOSE(ret);
  14540. goto exit_cs;
  14541. }
  14542. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14543. sigCtx->out = NULL;
  14544. #ifdef WOLFSSL_ASYNC_CRYPT
  14545. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  14546. #endif
  14547. break;
  14548. }
  14549. #endif /* !NO_RSA */
  14550. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  14551. case DSAk:
  14552. {
  14553. word32 idx = 0;
  14554. if (sigSz < DSA_MIN_SIG_SIZE) {
  14555. WOLFSSL_MSG("Verify Signature is too small");
  14556. ERROR_OUT(BUFFER_E, exit_cs);
  14557. }
  14558. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  14559. sigCtx->heap, DYNAMIC_TYPE_DSA);
  14560. if (sigCtx->key.dsa == NULL) {
  14561. ERROR_OUT(MEMORY_E, exit_cs);
  14562. }
  14563. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  14564. WOLFSSL_MSG("wc_InitDsaKey_h error");
  14565. goto exit_cs;
  14566. }
  14567. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  14568. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  14569. if (sigCtx->sigCpy == NULL) {
  14570. ERROR_OUT(MEMORY_E, exit_cs);
  14571. }
  14572. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  14573. keySz)) != 0) {
  14574. WOLFSSL_MSG("ASN Key decode error DSA");
  14575. WOLFSSL_ERROR_VERBOSE(ret);
  14576. goto exit_cs;
  14577. }
  14578. if (sigSz != DSA_160_SIG_SIZE &&
  14579. sigSz != DSA_256_SIG_SIZE) {
  14580. /* Try to parse it as the contents of a bitstring */
  14581. #ifdef WOLFSSL_SMALL_STACK
  14582. mp_int* r;
  14583. mp_int* s;
  14584. #else
  14585. mp_int r[1];
  14586. mp_int s[1];
  14587. #endif
  14588. int rSz;
  14589. int sSz;
  14590. #ifdef WOLFSSL_SMALL_STACK
  14591. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  14592. DYNAMIC_TYPE_TMP_BUFFER);
  14593. if (r == NULL) {
  14594. ERROR_OUT(MEMORY_E, exit_cs);
  14595. }
  14596. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  14597. DYNAMIC_TYPE_TMP_BUFFER);
  14598. if (s == NULL) {
  14599. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14600. ERROR_OUT(MEMORY_E, exit_cs);
  14601. }
  14602. #endif
  14603. if ((ret = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  14604. goto exit_cs;
  14605. }
  14606. idx = 0;
  14607. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  14608. != 0) {
  14609. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14610. "incorrect format");
  14611. mp_free(r);
  14612. mp_free(s);
  14613. #ifdef WOLFSSL_SMALL_STACK
  14614. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14615. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14616. #endif
  14617. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14618. }
  14619. rSz = mp_unsigned_bin_size(r);
  14620. sSz = mp_unsigned_bin_size(s);
  14621. if (rSz + sSz > (int)sigSz) {
  14622. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14623. "incorrect format");
  14624. mp_free(r);
  14625. mp_free(s);
  14626. #ifdef WOLFSSL_SMALL_STACK
  14627. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14628. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14629. #endif
  14630. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14631. }
  14632. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  14633. mp_to_unsigned_bin(s,
  14634. sigCtx->sigCpy + rSz) != MP_OKAY) {
  14635. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  14636. "incorrect format");
  14637. mp_free(r);
  14638. mp_free(s);
  14639. #ifdef WOLFSSL_SMALL_STACK
  14640. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14641. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14642. #endif
  14643. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  14644. }
  14645. mp_free(r);
  14646. mp_free(s);
  14647. #ifdef WOLFSSL_SMALL_STACK
  14648. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14649. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14650. #endif
  14651. }
  14652. else {
  14653. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  14654. }
  14655. break;
  14656. }
  14657. #endif /* !NO_DSA && !HAVE_SELFTEST */
  14658. #ifdef HAVE_ECC
  14659. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  14660. case SM2k:
  14661. #endif
  14662. case ECDSAk:
  14663. {
  14664. word32 idx = 0;
  14665. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14666. defined(WC_ASYNC_ENABLE_ECC)
  14667. ecc_nb_ctx_t* nbCtx;
  14668. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14669. WC_ASYNC_ENABLE_ECC */
  14670. sigCtx->verify = 0;
  14671. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  14672. sigCtx->heap, DYNAMIC_TYPE_ECC);
  14673. if (sigCtx->key.ecc == NULL) {
  14674. ERROR_OUT(MEMORY_E, exit_cs);
  14675. }
  14676. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  14677. sigCtx->devId)) < 0) {
  14678. goto exit_cs;
  14679. }
  14680. #if defined(WC_ECC_NONBLOCK) && defined(WOLFSSL_ASYNC_CRYPT_SW) && \
  14681. defined(WC_ASYNC_ENABLE_ECC)
  14682. nbCtx = (ecc_nb_ctx_t*)XMALLOC(sizeof(ecc_nb_ctx_t),
  14683. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14684. if (nbCtx == NULL) {
  14685. ERROR_OUT(MEMORY_E, exit_cs);
  14686. }
  14687. else {
  14688. ret = wc_ecc_set_nonblock(sigCtx->key.ecc, nbCtx);
  14689. if (ret != 0) {
  14690. goto exit_cs;
  14691. }
  14692. }
  14693. #endif /* WC_ECC_NONBLOCK && WOLFSSL_ASYNC_CRYPT_SW &&
  14694. WC_ASYNC_ENABLE_ECC */
  14695. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  14696. keySz);
  14697. if (ret < 0) {
  14698. WOLFSSL_MSG("ASN Key import error ECC");
  14699. WOLFSSL_ERROR_VERBOSE(ret);
  14700. goto exit_cs;
  14701. }
  14702. #ifdef WOLFSSL_ASYNC_CRYPT
  14703. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  14704. #endif
  14705. break;
  14706. }
  14707. #endif /* HAVE_ECC */
  14708. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  14709. case ED25519k:
  14710. {
  14711. sigCtx->verify = 0;
  14712. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  14713. sizeof(ed25519_key), sigCtx->heap,
  14714. DYNAMIC_TYPE_ED25519);
  14715. if (sigCtx->key.ed25519 == NULL) {
  14716. ERROR_OUT(MEMORY_E, exit_cs);
  14717. }
  14718. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  14719. sigCtx->heap, sigCtx->devId)) < 0) {
  14720. goto exit_cs;
  14721. }
  14722. if ((ret = wc_ed25519_import_public(key, keySz,
  14723. sigCtx->key.ed25519)) < 0) {
  14724. WOLFSSL_MSG("ASN Key import error ED25519");
  14725. WOLFSSL_ERROR_VERBOSE(ret);
  14726. goto exit_cs;
  14727. }
  14728. #ifdef WOLFSSL_ASYNC_CRYPT
  14729. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  14730. #endif
  14731. break;
  14732. }
  14733. #endif
  14734. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  14735. case ED448k:
  14736. {
  14737. sigCtx->verify = 0;
  14738. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  14739. sizeof(ed448_key), sigCtx->heap,
  14740. DYNAMIC_TYPE_ED448);
  14741. if (sigCtx->key.ed448 == NULL) {
  14742. ERROR_OUT(MEMORY_E, exit_cs);
  14743. }
  14744. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  14745. goto exit_cs;
  14746. }
  14747. if ((ret = wc_ed448_import_public(key, keySz,
  14748. sigCtx->key.ed448)) < 0) {
  14749. WOLFSSL_MSG("ASN Key import error ED448");
  14750. WOLFSSL_ERROR_VERBOSE(ret);
  14751. goto exit_cs;
  14752. }
  14753. #ifdef WOLFSSL_ASYNC_CRYPT
  14754. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  14755. #endif
  14756. break;
  14757. }
  14758. #endif
  14759. #if defined(HAVE_PQC)
  14760. #if defined(HAVE_FALCON)
  14761. case FALCON_LEVEL1k:
  14762. {
  14763. sigCtx->verify = 0;
  14764. sigCtx->key.falcon =
  14765. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14766. sigCtx->heap,
  14767. DYNAMIC_TYPE_FALCON);
  14768. if (sigCtx->key.falcon == NULL) {
  14769. ERROR_OUT(MEMORY_E, exit_cs);
  14770. }
  14771. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14772. goto exit_cs;
  14773. }
  14774. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  14775. < 0) {
  14776. goto exit_cs;
  14777. }
  14778. if ((ret = wc_falcon_import_public(key, keySz,
  14779. sigCtx->key.falcon)) < 0) {
  14780. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  14781. WOLFSSL_ERROR_VERBOSE(ret);
  14782. goto exit_cs;
  14783. }
  14784. break;
  14785. }
  14786. case FALCON_LEVEL5k:
  14787. {
  14788. sigCtx->verify = 0;
  14789. sigCtx->key.falcon =
  14790. (falcon_key*)XMALLOC(sizeof(falcon_key),
  14791. sigCtx->heap,
  14792. DYNAMIC_TYPE_FALCON);
  14793. if (sigCtx->key.falcon == NULL) {
  14794. ERROR_OUT(MEMORY_E, exit_cs);
  14795. }
  14796. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  14797. goto exit_cs;
  14798. }
  14799. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  14800. < 0) {
  14801. goto exit_cs;
  14802. }
  14803. if ((ret = wc_falcon_import_public(key, keySz,
  14804. sigCtx->key.falcon)) < 0) {
  14805. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  14806. WOLFSSL_ERROR_VERBOSE(ret);
  14807. goto exit_cs;
  14808. }
  14809. break;
  14810. }
  14811. #endif /* HAVE_FALCON */
  14812. #if defined(HAVE_DILITHIUM)
  14813. case DILITHIUM_LEVEL2k:
  14814. {
  14815. sigCtx->verify = 0;
  14816. sigCtx->key.dilithium =
  14817. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14818. sigCtx->heap,
  14819. DYNAMIC_TYPE_DILITHIUM);
  14820. if (sigCtx->key.dilithium == NULL) {
  14821. ERROR_OUT(MEMORY_E, exit_cs);
  14822. }
  14823. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14824. goto exit_cs;
  14825. }
  14826. if ((ret = wc_dilithium_set_level(
  14827. sigCtx->key.dilithium, 2))
  14828. < 0) {
  14829. goto exit_cs;
  14830. }
  14831. if ((ret = wc_dilithium_import_public(key, keySz,
  14832. sigCtx->key.dilithium)) < 0) {
  14833. WOLFSSL_MSG("ASN Key import error Dilithium Level 2");
  14834. goto exit_cs;
  14835. }
  14836. break;
  14837. }
  14838. case DILITHIUM_LEVEL3k:
  14839. {
  14840. sigCtx->verify = 0;
  14841. sigCtx->key.dilithium =
  14842. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14843. sigCtx->heap,
  14844. DYNAMIC_TYPE_DILITHIUM);
  14845. if (sigCtx->key.dilithium == NULL) {
  14846. ERROR_OUT(MEMORY_E, exit_cs);
  14847. }
  14848. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14849. goto exit_cs;
  14850. }
  14851. if ((ret = wc_dilithium_set_level(
  14852. sigCtx->key.dilithium, 3))
  14853. < 0) {
  14854. goto exit_cs;
  14855. }
  14856. if ((ret = wc_dilithium_import_public(key, keySz,
  14857. sigCtx->key.dilithium)) < 0) {
  14858. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14859. goto exit_cs;
  14860. }
  14861. break;
  14862. }
  14863. case DILITHIUM_LEVEL5k:
  14864. {
  14865. sigCtx->verify = 0;
  14866. sigCtx->key.dilithium =
  14867. (dilithium_key*)XMALLOC(sizeof(dilithium_key),
  14868. sigCtx->heap,
  14869. DYNAMIC_TYPE_DILITHIUM);
  14870. if (sigCtx->key.dilithium == NULL) {
  14871. ERROR_OUT(MEMORY_E, exit_cs);
  14872. }
  14873. if ((ret = wc_dilithium_init(sigCtx->key.dilithium)) < 0) {
  14874. goto exit_cs;
  14875. }
  14876. if ((ret = wc_dilithium_set_level(
  14877. sigCtx->key.dilithium, 5))
  14878. < 0) {
  14879. goto exit_cs;
  14880. }
  14881. if ((ret = wc_dilithium_import_public(key, keySz,
  14882. sigCtx->key.dilithium)) < 0) {
  14883. WOLFSSL_MSG("ASN Key import error Dilithium Level 5");
  14884. goto exit_cs;
  14885. }
  14886. break;
  14887. }
  14888. #endif /* HAVE_DILITHIUM */
  14889. #if defined(HAVE_SPHINCS)
  14890. case SPHINCS_FAST_LEVEL1k:
  14891. {
  14892. sigCtx->verify = 0;
  14893. sigCtx->key.sphincs =
  14894. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14895. sigCtx->heap,
  14896. DYNAMIC_TYPE_SPHINCS);
  14897. if (sigCtx->key.sphincs == NULL) {
  14898. ERROR_OUT(MEMORY_E, exit_cs);
  14899. }
  14900. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14901. goto exit_cs;
  14902. }
  14903. if ((ret = wc_sphincs_set_level_and_optim(
  14904. sigCtx->key.sphincs, 1, FAST_VARIANT))
  14905. < 0) {
  14906. goto exit_cs;
  14907. }
  14908. if ((ret = wc_sphincs_import_public(key, keySz,
  14909. sigCtx->key.sphincs)) < 0) {
  14910. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14911. goto exit_cs;
  14912. }
  14913. break;
  14914. }
  14915. case SPHINCS_FAST_LEVEL3k:
  14916. {
  14917. sigCtx->verify = 0;
  14918. sigCtx->key.sphincs =
  14919. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14920. sigCtx->heap,
  14921. DYNAMIC_TYPE_SPHINCS);
  14922. if (sigCtx->key.sphincs == NULL) {
  14923. ERROR_OUT(MEMORY_E, exit_cs);
  14924. }
  14925. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14926. goto exit_cs;
  14927. }
  14928. if ((ret = wc_sphincs_set_level_and_optim(
  14929. sigCtx->key.sphincs, 3, FAST_VARIANT))
  14930. < 0) {
  14931. goto exit_cs;
  14932. }
  14933. if ((ret = wc_sphincs_import_public(key, keySz,
  14934. sigCtx->key.sphincs)) < 0) {
  14935. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  14936. goto exit_cs;
  14937. }
  14938. break;
  14939. }
  14940. case SPHINCS_FAST_LEVEL5k:
  14941. {
  14942. sigCtx->verify = 0;
  14943. sigCtx->key.sphincs =
  14944. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14945. sigCtx->heap,
  14946. DYNAMIC_TYPE_SPHINCS);
  14947. if (sigCtx->key.sphincs == NULL) {
  14948. ERROR_OUT(MEMORY_E, exit_cs);
  14949. }
  14950. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14951. goto exit_cs;
  14952. }
  14953. if ((ret = wc_sphincs_set_level_and_optim(
  14954. sigCtx->key.sphincs, 5, FAST_VARIANT))
  14955. < 0) {
  14956. goto exit_cs;
  14957. }
  14958. if ((ret = wc_sphincs_import_public(key, keySz,
  14959. sigCtx->key.sphincs)) < 0) {
  14960. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  14961. goto exit_cs;
  14962. }
  14963. break;
  14964. }
  14965. case SPHINCS_SMALL_LEVEL1k:
  14966. {
  14967. sigCtx->verify = 0;
  14968. sigCtx->key.sphincs =
  14969. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14970. sigCtx->heap,
  14971. DYNAMIC_TYPE_SPHINCS);
  14972. if (sigCtx->key.sphincs == NULL) {
  14973. ERROR_OUT(MEMORY_E, exit_cs);
  14974. }
  14975. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  14976. goto exit_cs;
  14977. }
  14978. if ((ret = wc_sphincs_set_level_and_optim(
  14979. sigCtx->key.sphincs, 1, SMALL_VARIANT))
  14980. < 0) {
  14981. goto exit_cs;
  14982. }
  14983. if ((ret = wc_sphincs_import_public(key, keySz,
  14984. sigCtx->key.sphincs)) < 0) {
  14985. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level1");
  14986. goto exit_cs;
  14987. }
  14988. break;
  14989. }
  14990. case SPHINCS_SMALL_LEVEL3k:
  14991. {
  14992. sigCtx->verify = 0;
  14993. sigCtx->key.sphincs =
  14994. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  14995. sigCtx->heap,
  14996. DYNAMIC_TYPE_SPHINCS);
  14997. if (sigCtx->key.sphincs == NULL) {
  14998. ERROR_OUT(MEMORY_E, exit_cs);
  14999. }
  15000. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15001. goto exit_cs;
  15002. }
  15003. if ((ret = wc_sphincs_set_level_and_optim(
  15004. sigCtx->key.sphincs, 3, SMALL_VARIANT))
  15005. < 0) {
  15006. goto exit_cs;
  15007. }
  15008. if ((ret = wc_sphincs_import_public(key, keySz,
  15009. sigCtx->key.sphincs)) < 0) {
  15010. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level3");
  15011. goto exit_cs;
  15012. }
  15013. break;
  15014. }
  15015. case SPHINCS_SMALL_LEVEL5k:
  15016. {
  15017. sigCtx->verify = 0;
  15018. sigCtx->key.sphincs =
  15019. (sphincs_key*)XMALLOC(sizeof(sphincs_key),
  15020. sigCtx->heap,
  15021. DYNAMIC_TYPE_SPHINCS);
  15022. if (sigCtx->key.sphincs == NULL) {
  15023. ERROR_OUT(MEMORY_E, exit_cs);
  15024. }
  15025. if ((ret = wc_sphincs_init(sigCtx->key.sphincs)) < 0) {
  15026. goto exit_cs;
  15027. }
  15028. if ((ret = wc_sphincs_set_level_and_optim(
  15029. sigCtx->key.sphincs, 5, SMALL_VARIANT))
  15030. < 0) {
  15031. goto exit_cs;
  15032. }
  15033. if ((ret = wc_sphincs_import_public(key, keySz,
  15034. sigCtx->key.sphincs)) < 0) {
  15035. WOLFSSL_MSG("ASN Key import err: Sphincs-fast Level5");
  15036. goto exit_cs;
  15037. }
  15038. break;
  15039. }
  15040. #endif /* HAVE_SPHINCS */
  15041. #endif /* HAVE_PQC */
  15042. default:
  15043. WOLFSSL_MSG("Verify Key type unknown");
  15044. ret = ASN_UNKNOWN_OID_E;
  15045. WOLFSSL_ERROR_VERBOSE(ret);
  15046. break;
  15047. } /* switch (keyOID) */
  15048. if (ret != 0) {
  15049. goto exit_cs;
  15050. }
  15051. sigCtx->state = SIG_STATE_DO;
  15052. #ifdef WOLFSSL_ASYNC_CRYPT
  15053. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  15054. /* make sure event is initialized */
  15055. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  15056. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  15057. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  15058. }
  15059. #endif
  15060. } /* SIG_STATE_KEY */
  15061. FALL_THROUGH;
  15062. case SIG_STATE_DO:
  15063. {
  15064. switch (keyOID) {
  15065. #ifndef NO_RSA
  15066. case RSAk:
  15067. #ifdef WC_RSA_PSS
  15068. case RSAPSSk:
  15069. if (sigOID == RSAPSSk) {
  15070. /* TODO: pkCbRsaPss - RSA PSS callback. */
  15071. ret = wc_RsaPSS_VerifyInline_ex(sigCtx->sigCpy, sigSz,
  15072. &sigCtx->out, sigCtx->hash, sigCtx->mgf,
  15073. sigCtx->saltLen, sigCtx->key.rsa);
  15074. }
  15075. else
  15076. #endif
  15077. {
  15078. #if defined(HAVE_PK_CALLBACKS)
  15079. if (sigCtx->pkCbRsa) {
  15080. ret = sigCtx->pkCbRsa(
  15081. sigCtx->sigCpy, sigSz, &sigCtx->out,
  15082. key, keySz,
  15083. sigCtx->pkCtxRsa);
  15084. }
  15085. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  15086. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15087. else
  15088. #else
  15089. if (!sigCtx->pkCbRsa || ret == CRYPTOCB_UNAVAILABLE)
  15090. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  15091. #endif /* HAVE_PK_CALLBACKS */
  15092. {
  15093. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  15094. &sigCtx->out, sigCtx->key.rsa);
  15095. }
  15096. }
  15097. break;
  15098. #endif /* !NO_RSA */
  15099. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15100. case DSAk:
  15101. {
  15102. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  15103. sigCtx->key.dsa, &sigCtx->verify);
  15104. break;
  15105. }
  15106. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15107. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15108. case SM2k:
  15109. {
  15110. /* OpenSSL creates signature without CERT_SIG_ID. */
  15111. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID, 0, buf, bufSz,
  15112. WC_HASH_TYPE_SM3, sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15113. sigCtx->key.ecc);
  15114. if (ret == 0) {
  15115. sigCtx->typeH = SM3h;
  15116. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15117. }
  15118. else {
  15119. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15120. WOLFSSL_ERROR_VERBOSE(ret);
  15121. goto exit_cs;
  15122. }
  15123. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15124. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15125. break;
  15126. }
  15127. #endif
  15128. #if defined(HAVE_ECC) && defined(HAVE_ECC_VERIFY)
  15129. case ECDSAk:
  15130. {
  15131. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15132. if (sigOID == CTC_SM3wSM2) {
  15133. ret = wc_ecc_sm2_create_digest(CERT_SIG_ID,
  15134. CERT_SIG_ID_SZ, buf, bufSz, WC_HASH_TYPE_SM3,
  15135. sigCtx->digest, WC_SM3_DIGEST_SIZE,
  15136. sigCtx->key.ecc);
  15137. if (ret == 0) {
  15138. sigCtx->typeH = SM3h;
  15139. sigCtx->digestSz = WC_SM3_DIGEST_SIZE;
  15140. }
  15141. else {
  15142. WOLFSSL_MSG("SM2wSM3 create digest failed");
  15143. WOLFSSL_ERROR_VERBOSE(ret);
  15144. goto exit_cs;
  15145. }
  15146. ret = wc_ecc_sm2_verify_hash(sig, sigSz, sigCtx->digest,
  15147. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  15148. }
  15149. else
  15150. #endif
  15151. #if defined(HAVE_PK_CALLBACKS)
  15152. if (sigCtx->pkCbEcc) {
  15153. ret = sigCtx->pkCbEcc(
  15154. sig, sigSz,
  15155. sigCtx->digest, (unsigned int)sigCtx->digestSz,
  15156. key, keySz, &sigCtx->verify,
  15157. sigCtx->pkCtxEcc);
  15158. }
  15159. #if !defined(WOLFSSL_RENESAS_SCEPROTECT) && \
  15160. !defined(WOLFSSL_RENESAS_TSIP_TLS)
  15161. else
  15162. #else
  15163. if (!sigCtx->pkCbEcc || ret == CRYPTOCB_UNAVAILABLE)
  15164. #endif /* WOLFSSL_RENESAS_SCEPROTECT */
  15165. #endif /* HAVE_PK_CALLBACKS */
  15166. {
  15167. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  15168. (word32)sigCtx->digestSz, &sigCtx->verify,
  15169. sigCtx->key.ecc);
  15170. }
  15171. break;
  15172. }
  15173. #endif /* HAVE_ECC */
  15174. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  15175. case ED25519k:
  15176. {
  15177. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  15178. &sigCtx->verify, sigCtx->key.ed25519);
  15179. break;
  15180. }
  15181. #endif
  15182. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  15183. case ED448k:
  15184. {
  15185. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  15186. &sigCtx->verify, sigCtx->key.ed448,
  15187. NULL, 0);
  15188. break;
  15189. }
  15190. #endif
  15191. #if defined(HAVE_PQC)
  15192. #if defined(HAVE_FALCON)
  15193. case FALCON_LEVEL1k:
  15194. case FALCON_LEVEL5k:
  15195. {
  15196. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  15197. &sigCtx->verify,
  15198. sigCtx->key.falcon);
  15199. break;
  15200. }
  15201. #endif /* HAVE_FALCON */
  15202. #if defined(HAVE_DILITHIUM)
  15203. case DILITHIUM_LEVEL2k:
  15204. case DILITHIUM_LEVEL3k:
  15205. case DILITHIUM_LEVEL5k:
  15206. {
  15207. ret = wc_dilithium_verify_msg(sig, sigSz, buf, bufSz,
  15208. &sigCtx->verify,
  15209. sigCtx->key.dilithium);
  15210. break;
  15211. }
  15212. #endif /* HAVE_DILITHIUM */
  15213. #if defined(HAVE_SPHINCS)
  15214. case SPHINCS_FAST_LEVEL1k:
  15215. case SPHINCS_FAST_LEVEL3k:
  15216. case SPHINCS_FAST_LEVEL5k:
  15217. case SPHINCS_SMALL_LEVEL1k:
  15218. case SPHINCS_SMALL_LEVEL3k:
  15219. case SPHINCS_SMALL_LEVEL5k:
  15220. {
  15221. ret = wc_sphincs_verify_msg(sig, sigSz, buf, bufSz,
  15222. &sigCtx->verify,
  15223. sigCtx->key.sphincs);
  15224. break;
  15225. }
  15226. #endif /* HAVE_SPHINCS */
  15227. #endif /* HAVE_PQC */
  15228. default:
  15229. break;
  15230. } /* switch (keyOID) */
  15231. #ifdef WOLFSSL_ASYNC_CRYPT
  15232. if (ret == WC_PENDING_E) {
  15233. goto exit_cs;
  15234. }
  15235. #endif
  15236. if (ret < 0) {
  15237. /* treat all errors as ASN_SIG_CONFIRM_E */
  15238. ret = ASN_SIG_CONFIRM_E;
  15239. WOLFSSL_ERROR_VERBOSE(ret);
  15240. goto exit_cs;
  15241. }
  15242. sigCtx->state = SIG_STATE_CHECK;
  15243. } /* SIG_STATE_DO */
  15244. FALL_THROUGH;
  15245. case SIG_STATE_CHECK:
  15246. {
  15247. switch (keyOID) {
  15248. #ifndef NO_RSA
  15249. case RSAk:
  15250. #ifdef WC_RSA_PSS
  15251. case RSAPSSk:
  15252. if (sigOID == RSAPSSk) {
  15253. #if (defined(HAVE_SELFTEST) && \
  15254. (!defined(HAVE_SELFTEST_VERSION) || \
  15255. (HAVE_SELFTEST_VERSION < 2))) || \
  15256. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15257. (HAVE_FIPS_VERSION < 2))
  15258. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15259. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15260. sigCtx->saltLen);
  15261. #elif (defined(HAVE_SELFTEST) && \
  15262. (HAVE_SELFTEST_VERSION == 2)) || \
  15263. (defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && \
  15264. (HAVE_FIPS_VERSION == 2))
  15265. ret = wc_RsaPSS_CheckPadding_ex(sigCtx->digest,
  15266. sigCtx->digestSz, sigCtx->out, ret, sigCtx->hash,
  15267. sigCtx->saltLen, 0);
  15268. #else
  15269. ret = wc_RsaPSS_CheckPadding_ex2(sigCtx->digest,
  15270. (word32)sigCtx->digestSz, sigCtx->out, (word32)ret, sigCtx->hash,
  15271. sigCtx->saltLen, wc_RsaEncryptSize(sigCtx->key.rsa) * 8,
  15272. sigCtx->heap);
  15273. #endif
  15274. break;
  15275. }
  15276. else
  15277. #endif
  15278. {
  15279. int encodedSigSz, verifySz;
  15280. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || \
  15281. defined(WOLFSSL_RENESAS_SCEPROTECT)
  15282. if (sigCtx->CertAtt.verifyByTSIP_SCE == 1) break;
  15283. #endif
  15284. #ifdef WOLFSSL_SMALL_STACK
  15285. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  15286. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15287. if (encodedSig == NULL) {
  15288. ERROR_OUT(MEMORY_E, exit_cs);
  15289. }
  15290. #else
  15291. byte encodedSig[MAX_ENCODED_SIG_SZ];
  15292. #endif
  15293. verifySz = ret;
  15294. /* make sure we're right justified */
  15295. encodedSigSz = (int)wc_EncodeSignature(encodedSig,
  15296. sigCtx->digest, (word32)sigCtx->digestSz,
  15297. sigCtx->typeH);
  15298. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  15299. XMEMCMP(sigCtx->out, encodedSig,
  15300. (size_t)encodedSigSz) == 0) {
  15301. ret = 0;
  15302. }
  15303. else {
  15304. WOLFSSL_MSG("RSA SSL verify match encode error");
  15305. ret = ASN_SIG_CONFIRM_E;
  15306. WOLFSSL_ERROR_VERBOSE(ret);
  15307. }
  15308. #ifdef WOLFSSL_SMALL_STACK
  15309. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  15310. #endif
  15311. break;
  15312. }
  15313. #endif /* NO_RSA */
  15314. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  15315. case DSAk:
  15316. {
  15317. if (sigCtx->verify == 1) {
  15318. ret = 0;
  15319. }
  15320. else {
  15321. WOLFSSL_MSG("DSA Verify didn't match");
  15322. ret = ASN_SIG_CONFIRM_E;
  15323. WOLFSSL_ERROR_VERBOSE(ret);
  15324. }
  15325. break;
  15326. }
  15327. #endif /* !NO_DSA && !HAVE_SELFTEST */
  15328. #ifdef HAVE_ECC
  15329. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  15330. case SM2k:
  15331. #endif
  15332. case ECDSAk:
  15333. {
  15334. if (sigCtx->verify == 1) {
  15335. ret = 0;
  15336. }
  15337. else {
  15338. WOLFSSL_MSG("ECC Verify didn't match");
  15339. ret = ASN_SIG_CONFIRM_E;
  15340. WOLFSSL_ERROR_VERBOSE(ret);
  15341. }
  15342. break;
  15343. }
  15344. #endif /* HAVE_ECC */
  15345. #ifdef HAVE_ED25519
  15346. case ED25519k:
  15347. {
  15348. if (sigCtx->verify == 1) {
  15349. ret = 0;
  15350. }
  15351. else {
  15352. WOLFSSL_MSG("ED25519 Verify didn't match");
  15353. ret = ASN_SIG_CONFIRM_E;
  15354. WOLFSSL_ERROR_VERBOSE(ret);
  15355. }
  15356. break;
  15357. }
  15358. #endif /* HAVE_ED25519 */
  15359. #ifdef HAVE_ED448
  15360. case ED448k:
  15361. {
  15362. if (sigCtx->verify == 1) {
  15363. ret = 0;
  15364. }
  15365. else {
  15366. WOLFSSL_MSG("ED448 Verify didn't match");
  15367. ret = ASN_SIG_CONFIRM_E;
  15368. WOLFSSL_ERROR_VERBOSE(ret);
  15369. }
  15370. break;
  15371. }
  15372. #endif /* HAVE_ED448 */
  15373. #ifdef HAVE_PQC
  15374. #ifdef HAVE_FALCON
  15375. case FALCON_LEVEL1k:
  15376. {
  15377. if (sigCtx->verify == 1) {
  15378. ret = 0;
  15379. }
  15380. else {
  15381. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  15382. ret = ASN_SIG_CONFIRM_E;
  15383. WOLFSSL_ERROR_VERBOSE(ret);
  15384. }
  15385. break;
  15386. }
  15387. case FALCON_LEVEL5k:
  15388. {
  15389. if (sigCtx->verify == 1) {
  15390. ret = 0;
  15391. }
  15392. else {
  15393. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  15394. ret = ASN_SIG_CONFIRM_E;
  15395. WOLFSSL_ERROR_VERBOSE(ret);
  15396. }
  15397. break;
  15398. }
  15399. #endif /* HAVE_FALCON */
  15400. #ifdef HAVE_DILITHIUM
  15401. case DILITHIUM_LEVEL2k:
  15402. {
  15403. if (sigCtx->verify == 1) {
  15404. ret = 0;
  15405. }
  15406. else {
  15407. WOLFSSL_MSG("DILITHIUM_LEVEL2 Verify didn't match");
  15408. ret = ASN_SIG_CONFIRM_E;
  15409. }
  15410. break;
  15411. }
  15412. case DILITHIUM_LEVEL3k:
  15413. {
  15414. if (sigCtx->verify == 1) {
  15415. ret = 0;
  15416. }
  15417. else {
  15418. WOLFSSL_MSG("DILITHIUM_LEVEL3 Verify didn't match");
  15419. ret = ASN_SIG_CONFIRM_E;
  15420. }
  15421. break;
  15422. }
  15423. case DILITHIUM_LEVEL5k:
  15424. {
  15425. if (sigCtx->verify == 1) {
  15426. ret = 0;
  15427. }
  15428. else {
  15429. WOLFSSL_MSG("DILITHIUM_LEVEL5 Verify didn't match");
  15430. ret = ASN_SIG_CONFIRM_E;
  15431. }
  15432. break;
  15433. }
  15434. #endif /* HAVE_DILITHIUM */
  15435. #ifdef HAVE_SPHINCS
  15436. case SPHINCS_FAST_LEVEL1k:
  15437. {
  15438. if (sigCtx->verify == 1) {
  15439. ret = 0;
  15440. }
  15441. else {
  15442. WOLFSSL_MSG("SPHINCS_FAST_LEVEL1 Verify didn't match");
  15443. ret = ASN_SIG_CONFIRM_E;
  15444. }
  15445. break;
  15446. }
  15447. case SPHINCS_FAST_LEVEL3k:
  15448. {
  15449. if (sigCtx->verify == 1) {
  15450. ret = 0;
  15451. }
  15452. else {
  15453. WOLFSSL_MSG("SPHINCS_FAST_LEVEL3 Verify didn't match");
  15454. ret = ASN_SIG_CONFIRM_E;
  15455. }
  15456. break;
  15457. }
  15458. case SPHINCS_FAST_LEVEL5k:
  15459. {
  15460. if (sigCtx->verify == 1) {
  15461. ret = 0;
  15462. }
  15463. else {
  15464. WOLFSSL_MSG("SPHINCS_FAST_LEVEL5 Verify didn't match");
  15465. ret = ASN_SIG_CONFIRM_E;
  15466. }
  15467. break;
  15468. }
  15469. case SPHINCS_SMALL_LEVEL1k:
  15470. {
  15471. if (sigCtx->verify == 1) {
  15472. ret = 0;
  15473. }
  15474. else {
  15475. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL1 Verify didn't match");
  15476. ret = ASN_SIG_CONFIRM_E;
  15477. }
  15478. break;
  15479. }
  15480. case SPHINCS_SMALL_LEVEL3k:
  15481. {
  15482. if (sigCtx->verify == 1) {
  15483. ret = 0;
  15484. }
  15485. else {
  15486. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL3 Verify didn't match");
  15487. ret = ASN_SIG_CONFIRM_E;
  15488. }
  15489. break;
  15490. }
  15491. case SPHINCS_SMALL_LEVEL5k:
  15492. {
  15493. if (sigCtx->verify == 1) {
  15494. ret = 0;
  15495. }
  15496. else {
  15497. WOLFSSL_MSG("SPHINCS_SMALL_LEVEL5 Verify didn't match");
  15498. ret = ASN_SIG_CONFIRM_E;
  15499. }
  15500. break;
  15501. }
  15502. #endif /* HAVE_SPHINCS */
  15503. #endif /* HAVE_PQC */
  15504. default:
  15505. break;
  15506. } /* switch (keyOID) */
  15507. break;
  15508. } /* SIG_STATE_CHECK */
  15509. default:
  15510. break;
  15511. } /* switch (sigCtx->state) */
  15512. exit_cs:
  15513. #endif /* !NO_ASN_CRYPT */
  15514. (void)keyOID;
  15515. (void)sigOID;
  15516. WOLFSSL_LEAVE("ConfirmSignature", ret);
  15517. #ifdef WOLFSSL_ASYNC_CRYPT
  15518. if (ret == WC_PENDING_E)
  15519. return ret;
  15520. #endif
  15521. FreeSignatureCtx(sigCtx);
  15522. return ret;
  15523. }
  15524. #ifndef IGNORE_NAME_CONSTRAINTS
  15525. static int MatchBaseName(int type, const char* name, int nameSz,
  15526. const char* base, int baseSz)
  15527. {
  15528. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  15529. name[0] == '.' || nameSz < baseSz ||
  15530. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  15531. type != ASN_DIR_TYPE)) {
  15532. return 0;
  15533. }
  15534. if (type == ASN_DIR_TYPE)
  15535. return XMEMCMP(name, base, (size_t)baseSz) == 0;
  15536. /* If an email type, handle special cases where the base is only
  15537. * a domain, or is an email address itself. */
  15538. if (type == ASN_RFC822_TYPE) {
  15539. const char* p = NULL;
  15540. int count = 0;
  15541. if (base[0] != '.') {
  15542. p = base;
  15543. count = 0;
  15544. /* find the '@' in the base */
  15545. while (*p != '@' && count < baseSz) {
  15546. count++;
  15547. p++;
  15548. }
  15549. /* No '@' in base, reset p to NULL */
  15550. if (count >= baseSz)
  15551. p = NULL;
  15552. }
  15553. if (p == NULL) {
  15554. /* Base isn't an email address, it is a domain name,
  15555. * wind the name forward one character past its '@'. */
  15556. p = name;
  15557. count = 0;
  15558. while (*p != '@' && count < baseSz) {
  15559. count++;
  15560. p++;
  15561. }
  15562. if (count < baseSz && *p == '@') {
  15563. name = p + 1;
  15564. nameSz -= count + 1;
  15565. }
  15566. }
  15567. }
  15568. /* RFC 5280 section 4.2.1.10
  15569. * "...Any DNS name that can be constructed by simply adding zero or more
  15570. * labels to the left-hand side of the name satisfies the name constraint."
  15571. * i.e www.host.example.com works for host.example.com name constraint and
  15572. * host1.example.com does not. */
  15573. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  15574. int szAdjust = nameSz - baseSz;
  15575. name += szAdjust;
  15576. nameSz -= szAdjust;
  15577. }
  15578. while (nameSz > 0) {
  15579. if (XTOLOWER((unsigned char)*name++) !=
  15580. XTOLOWER((unsigned char)*base++))
  15581. return 0;
  15582. nameSz--;
  15583. }
  15584. return 1;
  15585. }
  15586. /* Search through the list to find if the name is permitted.
  15587. * name The DNS name to search for
  15588. * dnsList The list to search through
  15589. * nameType Type of DNS name to currently searching
  15590. * return 1 if found in list or if not needed
  15591. * return 0 if not found in the list but is needed
  15592. */
  15593. static int PermittedListOk(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15594. {
  15595. Base_entry* current = dnsList;
  15596. int match = 0;
  15597. int need = 0;
  15598. int ret = 1; /* is ok unless needed and no match found */
  15599. while (current != NULL) {
  15600. if (current->type == nameType) {
  15601. need = 1; /* restriction on permitted names is set for this type */
  15602. if (name->len >= current->nameSz &&
  15603. MatchBaseName(nameType, name->name, name->len,
  15604. current->name, current->nameSz)) {
  15605. match = 1; /* found the current name in the permitted list*/
  15606. break;
  15607. }
  15608. }
  15609. current = current->next;
  15610. }
  15611. /* check if permitted name restriction was set and no matching name found */
  15612. if (need && !match)
  15613. ret = 0;
  15614. return ret;
  15615. }
  15616. /* Search through the list to find if the name is excluded.
  15617. * name The DNS name to search for
  15618. * dnsList The list to search through
  15619. * nameType Type of DNS name to currently searching
  15620. * return 1 if found in list and 0 if not found in the list
  15621. */
  15622. static int IsInExcludedList(DNS_entry* name, Base_entry* dnsList, byte nameType)
  15623. {
  15624. int ret = 0; /* default of not found in the list */
  15625. Base_entry* current = dnsList;
  15626. while (current != NULL) {
  15627. if (current->type == nameType) {
  15628. if (name->len >= current->nameSz &&
  15629. MatchBaseName(nameType, name->name, name->len,
  15630. current->name, current->nameSz)) {
  15631. ret = 1;
  15632. break;
  15633. }
  15634. }
  15635. current = current->next;
  15636. }
  15637. return ret;
  15638. }
  15639. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  15640. {
  15641. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  15642. int i;
  15643. if (signer == NULL || cert == NULL)
  15644. return 0;
  15645. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  15646. return 1;
  15647. for (i=0; i < (int)sizeof(nameTypes); i++) {
  15648. byte nameType = nameTypes[i];
  15649. DNS_entry* name = NULL;
  15650. DNS_entry subjectDnsName; /* temporary node used for subject name */
  15651. XMEMSET(&subjectDnsName, 0, sizeof(DNS_entry));
  15652. switch (nameType) {
  15653. case ASN_DNS_TYPE:
  15654. /* Should it also consider CN in subject? It could use
  15655. * subjectDnsName too */
  15656. name = cert->altNames;
  15657. break;
  15658. case ASN_RFC822_TYPE:
  15659. /* Shouldn't it validade E= in subject as well? */
  15660. name = cert->altEmailNames;
  15661. /* Add subject email for checking. */
  15662. if (cert->subjectEmail != NULL) {
  15663. /* RFC 5280 section 4.2.1.10
  15664. * "When constraints are imposed on the rfc822Name name
  15665. * form, but the certificate does not include a subject
  15666. * alternative name, the rfc822Name constraint MUST be
  15667. * applied to the attribute of type emailAddress in the
  15668. * subject distinguished name" */
  15669. subjectDnsName.next = NULL;
  15670. subjectDnsName.type = ASN_RFC822_TYPE;
  15671. subjectDnsName.len = cert->subjectEmailLen;
  15672. subjectDnsName.name = (char *)cert->subjectEmail;
  15673. }
  15674. break;
  15675. case ASN_DIR_TYPE:
  15676. #ifndef WOLFSSL_NO_ASN_STRICT
  15677. name = cert->altDirNames;
  15678. #endif
  15679. /* RFC 5280 section 4.2.1.10
  15680. "Restrictions of the form directoryName MUST be
  15681. applied to the subject field .... and to any names
  15682. of type directoryName in the subjectAltName
  15683. extension"
  15684. */
  15685. if (cert->subjectRaw != NULL) {
  15686. subjectDnsName.next = NULL;
  15687. subjectDnsName.type = ASN_DIR_TYPE;
  15688. subjectDnsName.len = cert->subjectRawLen;
  15689. subjectDnsName.name = (char *)cert->subjectRaw;
  15690. }
  15691. break;
  15692. default:
  15693. /* Other types of names are ignored for now.
  15694. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  15695. * and signer->extNameConstraintCrit is set? */
  15696. return 0;
  15697. }
  15698. while (name != NULL) {
  15699. if (IsInExcludedList(name, signer->excludedNames, nameType) == 1) {
  15700. WOLFSSL_MSG("Excluded name was found!");
  15701. return 0;
  15702. }
  15703. /* Check against the permitted list */
  15704. if (PermittedListOk(name, signer->permittedNames, nameType) != 1) {
  15705. WOLFSSL_MSG("Permitted name was not found!");
  15706. return 0;
  15707. }
  15708. name = name->next;
  15709. }
  15710. /* handle comparing against subject name too */
  15711. if (subjectDnsName.len > 0 && subjectDnsName.name != NULL) {
  15712. if (IsInExcludedList(&subjectDnsName, signer->excludedNames,
  15713. nameType) == 1) {
  15714. WOLFSSL_MSG("Excluded name was found!");
  15715. return 0;
  15716. }
  15717. /* Check against the permitted list */
  15718. if (PermittedListOk(&subjectDnsName, signer->permittedNames,
  15719. nameType) != 1) {
  15720. WOLFSSL_MSG("Permitted name was not found!");
  15721. return 0;
  15722. }
  15723. }
  15724. }
  15725. return 1;
  15726. }
  15727. #endif /* IGNORE_NAME_CONSTRAINTS */
  15728. #ifndef WOLFSSL_ASN_TEMPLATE
  15729. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  15730. {
  15731. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  15732. dnsEntry->next = NULL;
  15733. if (cert->altNames == NULL) {
  15734. /* First on list */
  15735. cert->altNames = dnsEntry;
  15736. }
  15737. else {
  15738. DNS_entry* temp = cert->altNames;
  15739. /* Find end */
  15740. for (; (temp->next != NULL); temp = temp->next);
  15741. /* Add to end */
  15742. temp->next = dnsEntry;
  15743. }
  15744. #else
  15745. dnsEntry->next = cert->altNames;
  15746. cert->altNames = dnsEntry;
  15747. #endif
  15748. }
  15749. #endif
  15750. #ifdef WOLFSSL_ASN_TEMPLATE
  15751. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  15752. /* ASN.1 template for OtherName of an X.509 certificate.
  15753. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  15754. * HW Name: RFC 4108, 5 - Hardware Module Name
  15755. * Only support HW Name where the type is a HW serial number.
  15756. *
  15757. * Other Names handled for FPKI (Federal PKI) use:
  15758. * UPN (Universal Principal Name), a non-standard Other Name
  15759. * (RFC3280 sec 4.2.1.7). Often used with FIPS 201 smartcard login.
  15760. * FASC-N (Federal Agency Smart Credential Number), defined in the document
  15761. * fpki-x509-cert-policy-common.pdf. Used for a smart card ID.
  15762. */
  15763. static const ASNItem otherNameASN[] = {
  15764. /* TYPEID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  15765. /* VALUE */ { 0, ASN_CONTEXT_SPECIFIC | ASN_OTHERNAME_VALUE, 1, 1, 0 },
  15766. /* UPN */ { 1, ASN_UTF8STRING, 0, 0, 2 },
  15767. /* FASC-N */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  15768. /* HWN_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  15769. /* HWN_TYPE */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15770. /* HWN_NUM */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  15771. };
  15772. enum {
  15773. OTHERNAMEASN_IDX_TYPEID = 0,
  15774. OTHERNAMEASN_IDX_VALUE,
  15775. OTHERNAMEASN_IDX_UPN,
  15776. OTHERNAMEASN_IDX_FASCN,
  15777. OTHERNAMEASN_IDX_HWN_SEQ,
  15778. OTHERNAMEASN_IDX_HWN_TYPE,
  15779. OTHERNAMEASN_IDX_HWN_NUM
  15780. };
  15781. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  15782. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  15783. #ifdef WOLFSSL_SEP
  15784. static int DecodeSEP(ASNGetData* dataASN, DecodedCert* cert)
  15785. {
  15786. int ret = 0;
  15787. word32 oidLen, serialLen;
  15788. oidLen = dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.length;
  15789. serialLen = dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.length;
  15790. /* Allocate space for HW type OID. */
  15791. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  15792. DYNAMIC_TYPE_X509_EXT);
  15793. if (cert->hwType == NULL)
  15794. ret = MEMORY_E;
  15795. if (ret == 0) {
  15796. /* Copy, into cert HW type OID */
  15797. XMEMCPY(cert->hwType,
  15798. dataASN[OTHERNAMEASN_IDX_HWN_TYPE].data.oid.data, oidLen);
  15799. cert->hwTypeSz = (int)oidLen;
  15800. /* TODO: check this is the HW serial number OID - no test data. */
  15801. /* Allocate space for HW serial number, +1 for null terminator. */
  15802. cert->hwSerialNum = (byte*)XMALLOC(serialLen + 1, cert->heap,
  15803. DYNAMIC_TYPE_X509_EXT);
  15804. if (cert->hwSerialNum == NULL) {
  15805. WOLFSSL_MSG("\tOut of Memory");
  15806. ret = MEMORY_E;
  15807. }
  15808. }
  15809. if (ret == 0) {
  15810. /* Copy into cert HW serial number. */
  15811. XMEMCPY(cert->hwSerialNum,
  15812. dataASN[OTHERNAMEASN_IDX_HWN_NUM].data.ref.data, serialLen);
  15813. cert->hwSerialNum[serialLen] = '\0';
  15814. cert->hwSerialNumSz = (int)serialLen;
  15815. }
  15816. return ret;
  15817. }
  15818. #endif /* WOLFSSL_SEP */
  15819. static int DecodeOtherHelper(ASNGetData* dataASN, DecodedCert* cert, int oid)
  15820. {
  15821. DNS_entry* entry = NULL;
  15822. int ret = 0;
  15823. word32 bufLen = 0;
  15824. const char* buf = NULL;
  15825. switch (oid) {
  15826. #ifdef WOLFSSL_FPKI
  15827. case FASCN_OID:
  15828. bufLen = dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.length;
  15829. buf = (const char*)dataASN[OTHERNAMEASN_IDX_FASCN].data.ref.data;
  15830. break;
  15831. #endif /* WOLFSSL_FPKI */
  15832. case UPN_OID:
  15833. bufLen = dataASN[OTHERNAMEASN_IDX_UPN].data.ref.length;
  15834. buf = (const char*)dataASN[OTHERNAMEASN_IDX_UPN].data.ref.data;
  15835. break;
  15836. default:
  15837. WOLFSSL_ERROR_VERBOSE(ASN_UNKNOWN_OID_E);
  15838. ret = ASN_UNKNOWN_OID_E;
  15839. break;
  15840. }
  15841. if (ret == 0) {
  15842. ret = SetDNSEntry(cert, buf, (int)bufLen, ASN_OTHER_TYPE, &entry);
  15843. if (ret == 0) {
  15844. #ifdef WOLFSSL_FPKI
  15845. entry->oidSum = oid;
  15846. #endif
  15847. AddDNSEntryToList(&cert->altNames, entry);
  15848. }
  15849. }
  15850. return ret;
  15851. }
  15852. /* Decode data with OtherName format from after implicit SEQUENCE.
  15853. *
  15854. * @param [in, out] cert Certificate object.
  15855. * @param [in] input Buffer containing encoded OtherName.
  15856. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15857. * On out, index after OtherName.
  15858. * @param [in] maxIdx Maximum index of data in buffer.
  15859. * @return 0 on success.
  15860. * @return MEMORY_E on dynamic memory allocation failure.
  15861. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15862. * is invalid.
  15863. * @return ASN_PARSE_E when OID does is not HW Name.
  15864. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15865. * @return BUFFER_E when data in buffer is too small.
  15866. */
  15867. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  15868. word32* inOutIdx, word32 maxIdx)
  15869. {
  15870. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  15871. int ret = 0;
  15872. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  15873. if (ret == 0) {
  15874. /* Check the first OID is a recognized Alt Cert Name type. */
  15875. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_TYPEID], oidCertAltNameType);
  15876. /* Parse OtherName. */
  15877. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  15878. inOutIdx, maxIdx);
  15879. }
  15880. if (ret == 0) {
  15881. /* Ensure expected OID. */
  15882. switch (dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum) {
  15883. #ifdef WOLFSSL_SEP
  15884. case HW_NAME_OID:
  15885. /* Only support HW serial number. */
  15886. GetASN_OID(&dataASN[OTHERNAMEASN_IDX_HWN_TYPE], oidIgnoreType);
  15887. ret = DecodeSEP(dataASN, cert);
  15888. break;
  15889. #endif /* WOLFSSL_SEP */
  15890. #ifdef WOLFSSL_FPKI
  15891. case FASCN_OID:
  15892. #endif /* WOLFSSL_FPKI */
  15893. case UPN_OID:
  15894. ret = DecodeOtherHelper(dataASN, cert,
  15895. (int)dataASN[OTHERNAMEASN_IDX_TYPEID].data.oid.sum);
  15896. break;
  15897. default:
  15898. WOLFSSL_MSG("\tunsupported OID skipping");
  15899. break;
  15900. }
  15901. }
  15902. FREE_ASNGETDATA(dataASN, cert->heap);
  15903. return ret;
  15904. }
  15905. #endif /* WOLFSSL_SEP || WOLFSSL_FPKI */
  15906. /* Decode a GeneralName.
  15907. *
  15908. * @param [in] input Buffer containing encoded OtherName.
  15909. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  15910. * On out, index after OtherName.
  15911. * @param [in] len Length of data in buffer.
  15912. * @param [in] cert Decoded certificate object.
  15913. * @return 0 on success.
  15914. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15915. * is invalid.
  15916. * @return BUFFER_E when data in buffer is too small.
  15917. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15918. * @return MEMORY_E when dynamic memory allocation fails.
  15919. */
  15920. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  15921. int len, DecodedCert* cert)
  15922. {
  15923. int ret = 0;
  15924. word32 idx = *inOutIdx;
  15925. /* GeneralName choice: dnsName */
  15926. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  15927. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  15928. &cert->altNames);
  15929. if (ret == 0) {
  15930. idx += (word32)len;
  15931. }
  15932. }
  15933. #ifndef IGNORE_NAME_CONSTRAINTS
  15934. /* GeneralName choice: directoryName */
  15935. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  15936. int strLen;
  15937. word32 idxDir = idx;
  15938. /* Expecting a SEQUENCE using up all data. */
  15939. if (GetASN_Sequence(input, &idxDir, &strLen, idx + (word32)len, 1) < 0)
  15940. {
  15941. WOLFSSL_MSG("\tfail: seq length");
  15942. return ASN_PARSE_E;
  15943. }
  15944. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  15945. ASN_DIR_TYPE, &cert->altDirNames);
  15946. if (ret == 0) {
  15947. idx += (word32)len;
  15948. }
  15949. }
  15950. /* GeneralName choice: rfc822Name */
  15951. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  15952. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  15953. ASN_RFC822_TYPE, &cert->altEmailNames);
  15954. if (ret == 0) {
  15955. idx += (word32)len;
  15956. }
  15957. }
  15958. /* GeneralName choice: uniformResourceIdentifier */
  15959. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  15960. WOLFSSL_MSG("\tPutting URI into list but not using");
  15961. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  15962. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  15963. "The name MUST NOT be a relative URI"
  15964. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  15965. a scheme and hier-part. So the only strict requirement is a ':'
  15966. being present after the scheme. If a '/' is present as part of the
  15967. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  15968. {
  15969. int i;
  15970. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  15971. for (i = 0; i < len; i++) {
  15972. if (input[idx + (word32)i] == ':') {
  15973. break;
  15974. }
  15975. if (input[idx + (word32)i] == '/') {
  15976. i = len; /* error, found relative path since '/' was
  15977. * encountered before ':'. Returning error
  15978. * value in next if statement. */
  15979. }
  15980. }
  15981. /* test hier-part is empty */
  15982. if (i == 0 || i == len) {
  15983. WOLFSSL_MSG("\tEmpty or malformed URI");
  15984. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15985. return ASN_ALT_NAME_E;
  15986. }
  15987. /* test if scheme is missing */
  15988. if (input[idx + (word32)i] != ':') {
  15989. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  15990. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  15991. return ASN_ALT_NAME_E;
  15992. }
  15993. }
  15994. #endif
  15995. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  15996. &cert->altNames);
  15997. if (ret == 0) {
  15998. idx += (word32)len;
  15999. }
  16000. }
  16001. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  16002. defined(WOLFSSL_IP_ALT_NAME)
  16003. /* GeneralName choice: iPAddress */
  16004. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16005. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  16006. &cert->altNames);
  16007. if (ret == 0) {
  16008. idx += len;
  16009. }
  16010. }
  16011. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16012. #endif /* IGNORE_NAME_CONSTRAINTS */
  16013. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_FPKI)
  16014. /* GeneralName choice: otherName */
  16015. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16016. /* TODO: test data for code path */
  16017. ret = DecodeOtherName(cert, input, &idx, idx + (word32)len);
  16018. }
  16019. #endif
  16020. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  16021. * registeredID */
  16022. else {
  16023. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16024. idx += (word32)len;
  16025. }
  16026. if (ret == 0) {
  16027. /* Return index of next encoded byte. */
  16028. *inOutIdx = idx;
  16029. }
  16030. return ret;
  16031. }
  16032. /* ASN.1 choices for GeneralName.
  16033. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16034. */
  16035. static const byte generalNameChoice[] = {
  16036. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  16037. ASN_CONTEXT_SPECIFIC | 1,
  16038. ASN_CONTEXT_SPECIFIC | 2,
  16039. ASN_CONTEXT_SPECIFIC | 3,
  16040. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  16041. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  16042. ASN_CONTEXT_SPECIFIC | 6,
  16043. ASN_CONTEXT_SPECIFIC | 7,
  16044. ASN_CONTEXT_SPECIFIC | 8,
  16045. 0
  16046. };
  16047. /* ASN.1 template for GeneralName.
  16048. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  16049. */
  16050. static const ASNItem altNameASN[] = {
  16051. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  16052. };
  16053. enum {
  16054. ALTNAMEASN_IDX_GN = 0
  16055. };
  16056. /* Number of items in ASN.1 template for GeneralName. */
  16057. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  16058. #endif /* WOLFSSL_ASN_TEMPLATE */
  16059. #if defined(WOLFSSL_SEP) && !defined(WOLFSSL_ASN_TEMPLATE)
  16060. /* return 0 on success */
  16061. static int DecodeSepHwAltName(DecodedCert* cert, const byte* input,
  16062. word32* idxIn, word32 sz)
  16063. {
  16064. word32 idx = *idxIn;
  16065. int strLen;
  16066. int ret;
  16067. byte tag;
  16068. /* Certificates issued with this OID in the subject alt name are for
  16069. * verifying signatures created on a module.
  16070. * RFC 4108 Section 5. */
  16071. if (cert->hwType != NULL) {
  16072. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  16073. return ASN_PARSE_E;
  16074. }
  16075. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  16076. return ASN_PARSE_E;
  16077. }
  16078. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  16079. WOLFSSL_MSG("\twrong type");
  16080. return ASN_PARSE_E;
  16081. }
  16082. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16083. WOLFSSL_MSG("\tfail: str len");
  16084. return ASN_PARSE_E;
  16085. }
  16086. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16087. WOLFSSL_MSG("\tBad Sequence");
  16088. return ASN_PARSE_E;
  16089. }
  16090. ret = GetASNObjectId(input, &idx, &strLen, sz);
  16091. if (ret != 0) {
  16092. WOLFSSL_MSG("\tbad OID");
  16093. return ret;
  16094. }
  16095. cert->hwType = (byte*)XMALLOC((size_t)strLen, cert->heap,
  16096. DYNAMIC_TYPE_X509_EXT);
  16097. if (cert->hwType == NULL) {
  16098. WOLFSSL_MSG("\tOut of Memory");
  16099. return MEMORY_E;
  16100. }
  16101. XMEMCPY(cert->hwType, &input[idx], (size_t)strLen);
  16102. cert->hwTypeSz = strLen;
  16103. idx += (word32)strLen;
  16104. ret = GetOctetString(input, &idx, &strLen, sz);
  16105. if (ret < 0) {
  16106. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16107. cert->hwType = NULL;
  16108. return ret;
  16109. }
  16110. cert->hwSerialNum = (byte*)XMALLOC((size_t)strLen + 1, cert->heap,
  16111. DYNAMIC_TYPE_X509_EXT);
  16112. if (cert->hwSerialNum == NULL) {
  16113. WOLFSSL_MSG("\tOut of Memory");
  16114. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  16115. cert->hwType = NULL;
  16116. return MEMORY_E;
  16117. }
  16118. XMEMCPY(cert->hwSerialNum, &input[idx], (size_t)strLen);
  16119. cert->hwSerialNum[strLen] = '\0';
  16120. cert->hwSerialNumSz = strLen;
  16121. idx += (word32)strLen;
  16122. *idxIn = idx;
  16123. return 0;
  16124. }
  16125. #endif /* WOLFSSL_SEP */
  16126. #if !defined(WOLFSSL_ASN_TEMPLATE)
  16127. /* return 0 on success */
  16128. static int DecodeConstructedOtherName(DecodedCert* cert, const byte* input,
  16129. word32* idx, word32 sz, int oid)
  16130. {
  16131. int ret = 0;
  16132. int strLen = 0;
  16133. byte tag;
  16134. DNS_entry* dnsEntry = NULL;
  16135. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16136. ret = ASN_PARSE_E;
  16137. }
  16138. if (ret == 0 && (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))) {
  16139. ret = ASN_PARSE_E;
  16140. }
  16141. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16142. ret = ASN_PARSE_E;
  16143. }
  16144. if (ret == 0) {
  16145. dnsEntry = AltNameNew(cert->heap);
  16146. if (dnsEntry == NULL) {
  16147. WOLFSSL_MSG("\tOut of Memory");
  16148. return MEMORY_E;
  16149. }
  16150. switch (oid) {
  16151. #ifdef WOLFSSL_FPKI
  16152. case FASCN_OID:
  16153. ret = GetOctetString(input, idx, &strLen, sz);
  16154. if (ret > 0) {
  16155. ret = 0;
  16156. }
  16157. break;
  16158. #endif /* WOLFSSL_FPKI */
  16159. case UPN_OID:
  16160. if (GetASNTag(input, idx, &tag, sz) < 0) {
  16161. ret = ASN_PARSE_E;
  16162. }
  16163. if (ret == 0 &&
  16164. tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16165. tag != ASN_IA5_STRING) {
  16166. WOLFSSL_MSG("Was expecting a string for UPN");
  16167. ret = ASN_PARSE_E;
  16168. }
  16169. if (ret == 0 && (GetLength(input, idx, &strLen, sz) < 0)) {
  16170. WOLFSSL_MSG("Was expecting a string for UPN");
  16171. ret = ASN_PARSE_E;
  16172. }
  16173. break;
  16174. default:
  16175. WOLFSSL_MSG("Unknown constructed other name, skipping");
  16176. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16177. dnsEntry = NULL;
  16178. }
  16179. }
  16180. if (ret == 0 && dnsEntry != NULL) {
  16181. dnsEntry->type = ASN_OTHER_TYPE;
  16182. dnsEntry->len = strLen;
  16183. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16184. DYNAMIC_TYPE_ALTNAME);
  16185. #ifdef WOLFSSL_FPKI
  16186. dnsEntry->oidSum = oid;
  16187. #endif /* WOLFSSL_FPKI */
  16188. if (dnsEntry->name == NULL) {
  16189. WOLFSSL_MSG("\tOut of Memory");
  16190. ret = MEMORY_E;
  16191. }
  16192. else {
  16193. XMEMCPY(dnsEntry->name, &input[*idx], (size_t)strLen);
  16194. dnsEntry->name[strLen] = '\0';
  16195. AddAltName(cert, dnsEntry);
  16196. }
  16197. }
  16198. if (ret == 0) {
  16199. *idx += (word32)strLen;
  16200. }
  16201. else {
  16202. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16203. }
  16204. return ret;
  16205. }
  16206. #endif
  16207. /* Decode subject alternative names extension.
  16208. *
  16209. * RFC 5280 4.2.1.6. Subject Alternative Name
  16210. *
  16211. * @param [in] input Buffer holding encoded data.
  16212. * @param [in] sz Size of encoded data in bytes.
  16213. * @param [in, out] cert Decoded certificate object.
  16214. * @return 0 on success.
  16215. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16216. * is invalid.
  16217. * @return BUFFER_E when data in buffer is too small.
  16218. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16219. * @return MEMORY_E when dynamic memory allocation fails.
  16220. */
  16221. static int DecodeAltNames(const byte* input, word32 sz, DecodedCert* cert)
  16222. {
  16223. #ifndef WOLFSSL_ASN_TEMPLATE
  16224. word32 idx = 0;
  16225. int length = 0;
  16226. WOLFSSL_ENTER("DecodeAltNames");
  16227. if (GetSequence(input, &idx, &length, sz) < 0) {
  16228. WOLFSSL_MSG("\tBad Sequence");
  16229. return ASN_PARSE_E;
  16230. }
  16231. if (length == 0) {
  16232. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16233. If the subjectAltName extension is present, the sequence MUST
  16234. contain at least one entry. */
  16235. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16236. return ASN_PARSE_E;
  16237. }
  16238. #ifdef OPENSSL_ALL
  16239. cert->extSubjAltNameSrc = input;
  16240. cert->extSubjAltNameSz = sz;
  16241. #endif
  16242. cert->weOwnAltNames = 1;
  16243. while (length > 0) {
  16244. byte current_byte;
  16245. /* Verify idx can't overflow input buffer */
  16246. if (idx >= (word32)sz) {
  16247. WOLFSSL_MSG("\tBad Index");
  16248. return BUFFER_E;
  16249. }
  16250. current_byte = input[idx++];
  16251. length--;
  16252. /* Save DNS Type names in the altNames list. */
  16253. /* Save Other Type names in the cert's OidMap */
  16254. if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  16255. DNS_entry* dnsEntry;
  16256. int strLen;
  16257. word32 lenStartIdx = idx;
  16258. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16259. WOLFSSL_MSG("\tfail: str length");
  16260. return ASN_PARSE_E;
  16261. }
  16262. length -= (int)(idx - lenStartIdx);
  16263. dnsEntry = AltNameNew(cert->heap);
  16264. if (dnsEntry == NULL) {
  16265. WOLFSSL_MSG("\tOut of Memory");
  16266. return MEMORY_E;
  16267. }
  16268. dnsEntry->type = ASN_DNS_TYPE;
  16269. dnsEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16270. DYNAMIC_TYPE_ALTNAME);
  16271. if (dnsEntry->name == NULL) {
  16272. WOLFSSL_MSG("\tOut of Memory");
  16273. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16274. return MEMORY_E;
  16275. }
  16276. dnsEntry->len = strLen;
  16277. XMEMCPY(dnsEntry->name, &input[idx], (size_t)strLen);
  16278. dnsEntry->name[strLen] = '\0';
  16279. AddAltName(cert, dnsEntry);
  16280. length -= strLen;
  16281. idx += (word32)strLen;
  16282. }
  16283. #ifndef IGNORE_NAME_CONSTRAINTS
  16284. else if (current_byte ==
  16285. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  16286. DNS_entry* dirEntry;
  16287. int strLen;
  16288. word32 lenStartIdx = idx;
  16289. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16290. WOLFSSL_MSG("\tfail: str length");
  16291. return ASN_PARSE_E;
  16292. }
  16293. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  16294. WOLFSSL_MSG("\tfail: seq length");
  16295. return ASN_PARSE_E;
  16296. }
  16297. length -= (int)(idx - lenStartIdx);
  16298. dirEntry = AltNameNew(cert->heap);
  16299. if (dirEntry == NULL) {
  16300. WOLFSSL_MSG("\tOut of Memory");
  16301. return MEMORY_E;
  16302. }
  16303. dirEntry->type = ASN_DIR_TYPE;
  16304. dirEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16305. DYNAMIC_TYPE_ALTNAME);
  16306. if (dirEntry->name == NULL) {
  16307. WOLFSSL_MSG("\tOut of Memory");
  16308. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16309. return MEMORY_E;
  16310. }
  16311. dirEntry->len = strLen;
  16312. XMEMCPY(dirEntry->name, &input[idx], (size_t)strLen);
  16313. dirEntry->name[strLen] = '\0';
  16314. dirEntry->next = cert->altDirNames;
  16315. cert->altDirNames = dirEntry;
  16316. length -= strLen;
  16317. idx += (word32)strLen;
  16318. }
  16319. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  16320. DNS_entry* emailEntry;
  16321. int strLen;
  16322. word32 lenStartIdx = idx;
  16323. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16324. WOLFSSL_MSG("\tfail: str length");
  16325. return ASN_PARSE_E;
  16326. }
  16327. length -= (int)(idx - lenStartIdx);
  16328. emailEntry = AltNameNew(cert->heap);
  16329. if (emailEntry == NULL) {
  16330. WOLFSSL_MSG("\tOut of Memory");
  16331. return MEMORY_E;
  16332. }
  16333. emailEntry->type = ASN_RFC822_TYPE;
  16334. emailEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16335. DYNAMIC_TYPE_ALTNAME);
  16336. if (emailEntry->name == NULL) {
  16337. WOLFSSL_MSG("\tOut of Memory");
  16338. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16339. return MEMORY_E;
  16340. }
  16341. emailEntry->len = strLen;
  16342. XMEMCPY(emailEntry->name, &input[idx], (size_t)strLen);
  16343. emailEntry->name[strLen] = '\0';
  16344. emailEntry->next = cert->altEmailNames;
  16345. cert->altEmailNames = emailEntry;
  16346. length -= strLen;
  16347. idx += (word32)strLen;
  16348. }
  16349. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  16350. DNS_entry* uriEntry;
  16351. int strLen;
  16352. word32 lenStartIdx = idx;
  16353. WOLFSSL_MSG("\tPutting URI into list but not using");
  16354. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16355. WOLFSSL_MSG("\tfail: str length");
  16356. return ASN_PARSE_E;
  16357. }
  16358. length -= (int)(idx - lenStartIdx);
  16359. /* check that strLen at index is not past input buffer */
  16360. if ((word32)strLen + idx > sz) {
  16361. return BUFFER_E;
  16362. }
  16363. #if !defined(WOLFSSL_NO_ASN_STRICT) && !defined(WOLFSSL_FPKI)
  16364. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  16365. "The name MUST NOT be a relative URI"
  16366. As per RFC 3986 Sec 4.3, an absolute URI is only required to contain
  16367. a scheme and hier-part. So the only strict requirement is a ':'
  16368. being present after the scheme. If a '/' is present as part of the
  16369. hier-part, it must come after the ':' (see RFC 3986 Sec 3). */
  16370. {
  16371. word32 i;
  16372. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  16373. for (i = 0; i < (word32)strLen; i++) {
  16374. if (input[idx + i] == ':') {
  16375. break;
  16376. }
  16377. if (input[idx + i] == '/') {
  16378. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16379. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16380. return ASN_ALT_NAME_E;
  16381. }
  16382. }
  16383. /* test hier-part is empty */
  16384. if (i == 0 || i == (word32)strLen) {
  16385. WOLFSSL_MSG("\tEmpty or malformed URI");
  16386. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16387. return ASN_ALT_NAME_E;
  16388. }
  16389. /* test if scheme is missing */
  16390. if (input[idx + i] != ':') {
  16391. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  16392. WOLFSSL_ERROR_VERBOSE(ASN_ALT_NAME_E);
  16393. return ASN_ALT_NAME_E;
  16394. }
  16395. }
  16396. #endif
  16397. uriEntry = AltNameNew(cert->heap);
  16398. if (uriEntry == NULL) {
  16399. WOLFSSL_MSG("\tOut of Memory");
  16400. return MEMORY_E;
  16401. }
  16402. uriEntry->type = ASN_URI_TYPE;
  16403. uriEntry->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16404. DYNAMIC_TYPE_ALTNAME);
  16405. if (uriEntry->name == NULL) {
  16406. WOLFSSL_MSG("\tOut of Memory");
  16407. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16408. return MEMORY_E;
  16409. }
  16410. uriEntry->len = strLen;
  16411. XMEMCPY(uriEntry->name, &input[idx], (size_t)strLen);
  16412. uriEntry->name[strLen] = '\0';
  16413. AddAltName(cert, uriEntry);
  16414. length -= strLen;
  16415. idx += (word32)strLen;
  16416. }
  16417. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16418. else if (current_byte == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  16419. DNS_entry* ipAddr;
  16420. int strLen;
  16421. word32 lenStartIdx = idx;
  16422. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  16423. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16424. WOLFSSL_MSG("\tfail: str length");
  16425. return ASN_PARSE_E;
  16426. }
  16427. length -= (idx - lenStartIdx);
  16428. /* check that strLen at index is not past input buffer */
  16429. if (strLen + idx > sz) {
  16430. return BUFFER_E;
  16431. }
  16432. ipAddr = AltNameNew(cert->heap);
  16433. if (ipAddr == NULL) {
  16434. WOLFSSL_MSG("\tOut of Memory");
  16435. return MEMORY_E;
  16436. }
  16437. ipAddr->type = ASN_IP_TYPE;
  16438. ipAddr->name = (char*)XMALLOC((size_t)strLen + 1, cert->heap,
  16439. DYNAMIC_TYPE_ALTNAME);
  16440. if (ipAddr->name == NULL) {
  16441. WOLFSSL_MSG("\tOut of Memory");
  16442. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16443. return MEMORY_E;
  16444. }
  16445. ipAddr->len = strLen;
  16446. XMEMCPY(ipAddr->name, &input[idx], strLen);
  16447. ipAddr->name[strLen] = '\0';
  16448. #if defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  16449. if (GenerateDNSEntryIPString(ipAddr, cert->heap) != 0) {
  16450. WOLFSSL_MSG("\tOut of Memory for IP string");
  16451. XFREE(ipAddr->name, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16452. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  16453. return MEMORY_E;
  16454. }
  16455. #endif /* OPENSSL_ALL || WOLFSSL_IP_ALT_NAME */
  16456. AddAltName(cert, ipAddr);
  16457. length -= strLen;
  16458. idx += (word32)strLen;
  16459. }
  16460. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  16461. #endif /* IGNORE_NAME_CONSTRAINTS */
  16462. else if (current_byte ==
  16463. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  16464. int strLen;
  16465. word32 lenStartIdx = idx;
  16466. word32 oid = 0;
  16467. int ret = 0;
  16468. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16469. WOLFSSL_MSG("\tfail: other name length");
  16470. return ASN_PARSE_E;
  16471. }
  16472. /* Consume the rest of this sequence. */
  16473. length -= (int)(((word32)strLen + idx - lenStartIdx));
  16474. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  16475. WOLFSSL_MSG("\tbad OID");
  16476. return ASN_PARSE_E;
  16477. }
  16478. /* handle parsing other type alt names */
  16479. switch (oid) {
  16480. #ifdef WOLFSSL_SEP
  16481. case HW_NAME_OID:
  16482. ret = DecodeSepHwAltName(cert, input, &idx, sz);
  16483. if (ret != 0)
  16484. return ret;
  16485. break;
  16486. #endif /* WOLFSSL_SEP */
  16487. #ifdef WOLFSSL_FPKI
  16488. case FASCN_OID:
  16489. case UPN_OID:
  16490. ret = DecodeConstructedOtherName(cert, input, &idx, sz,
  16491. oid);
  16492. if (ret != 0)
  16493. return ret;
  16494. break;
  16495. #endif /* WOLFSSL_FPKI */
  16496. default:
  16497. WOLFSSL_MSG("\tUnsupported other name type, skipping");
  16498. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16499. /* check to skip constructed other names too */
  16500. if (DecodeConstructedOtherName(cert, input, &idx, sz,
  16501. (int)oid) != 0) {
  16502. WOLFSSL_MSG("\tfail: unsupported other name length");
  16503. return ASN_PARSE_E;
  16504. }
  16505. }
  16506. else {
  16507. idx += (word32)strLen;
  16508. }
  16509. }
  16510. (void)ret;
  16511. }
  16512. else {
  16513. int strLen;
  16514. word32 lenStartIdx = idx;
  16515. WOLFSSL_MSG("\tUnsupported name type, skipping");
  16516. if (GetLength(input, &idx, &strLen, sz) < 0) {
  16517. WOLFSSL_MSG("\tfail: unsupported name length");
  16518. return ASN_PARSE_E;
  16519. }
  16520. length -= (int)((word32)strLen + idx - lenStartIdx);
  16521. idx += (word32)strLen;
  16522. }
  16523. }
  16524. return 0;
  16525. #else
  16526. word32 idx = 0;
  16527. int length = 0;
  16528. int ret = 0;
  16529. WOLFSSL_ENTER("DecodeAltNames");
  16530. /* Get SEQUENCE and expect all data to be accounted for. */
  16531. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  16532. WOLFSSL_MSG("\tBad Sequence");
  16533. ret = ASN_PARSE_E;
  16534. }
  16535. if ((ret == 0) && (length == 0)) {
  16536. /* RFC 5280 4.2.1.6. Subject Alternative Name
  16537. If the subjectAltName extension is present, the sequence MUST
  16538. contain at least one entry. */
  16539. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16540. ret = ASN_PARSE_E;
  16541. }
  16542. if (ret == 0) {
  16543. #ifdef OPENSSL_ALL
  16544. cert->extSubjAltNameSrc = input;
  16545. cert->extSubjAltNameSz = sz;
  16546. #endif
  16547. cert->weOwnAltNames = 1;
  16548. if ((word32)length + idx != sz) {
  16549. ret = ASN_PARSE_E;
  16550. }
  16551. }
  16552. while ((ret == 0) && (idx < sz)) {
  16553. ASNGetData dataASN[altNameASN_Length];
  16554. /* Clear dynamic data items. */
  16555. XMEMSET(dataASN, 0, sizeof(dataASN));
  16556. /* Parse GeneralName with the choices supported. */
  16557. GetASN_Choice(&dataASN[ALTNAMEASN_IDX_GN], generalNameChoice);
  16558. /* Decode a GeneralName choice. */
  16559. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  16560. &idx, sz);
  16561. if (ret == 0) {
  16562. ret = DecodeGeneralName(input, &idx, dataASN[ALTNAMEASN_IDX_GN].tag,
  16563. (int)dataASN[ALTNAMEASN_IDX_GN].length, cert);
  16564. }
  16565. }
  16566. return ret;
  16567. #endif
  16568. }
  16569. #ifdef WOLFSSL_ASN_TEMPLATE
  16570. /* ASN.1 template for BasicContraints.
  16571. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16572. */
  16573. static const ASNItem basicConsASN[] = {
  16574. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16575. /* CA */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  16576. /* PLEN */ { 1, ASN_INTEGER, 0, 0, 1 }
  16577. };
  16578. enum {
  16579. BASICCONSASN_IDX_SEQ = 0,
  16580. BASICCONSASN_IDX_CA,
  16581. BASICCONSASN_IDX_PLEN
  16582. };
  16583. /* Number of items in ASN.1 template for BasicContraints. */
  16584. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  16585. #endif
  16586. /* Decode basic constraints extension in a certificate.
  16587. *
  16588. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  16589. *
  16590. * @param [in] input Buffer holding data.
  16591. * @param [in] sz Size of data in buffer.
  16592. * @param [in, out] cert Certificate object.
  16593. * @return 0 on success.
  16594. * @return MEMORY_E on dynamic memory allocation failure.
  16595. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  16596. * @return ASN_PARSE_E when CA boolean is not present unless
  16597. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  16598. * @return ASN_PARSE_E when path length more than 7 bits.
  16599. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16600. * is invalid.
  16601. * @return BUFFER_E when data in buffer is too small.
  16602. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  16603. * non-zero length.
  16604. */
  16605. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  16606. {
  16607. #ifndef WOLFSSL_ASN_TEMPLATE
  16608. word32 idx = 0;
  16609. int length = 0;
  16610. int ret;
  16611. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  16612. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16613. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16614. return ASN_PARSE_E;
  16615. }
  16616. if (length == 0)
  16617. return 0;
  16618. /* If the basic ca constraint is false, this extension may be named, but
  16619. * left empty. So, if the length is 0, just return. */
  16620. ret = GetBoolean(input, &idx, (word32)sz);
  16621. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  16622. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  16623. * When CA Boolean not asserted use the default value "False" */
  16624. if (ret < 0) {
  16625. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  16626. ret = 0;
  16627. }
  16628. cert->isCA = ret ? 1 : 0;
  16629. /* If there isn't any more data, return. */
  16630. if (idx >= (word32)sz) {
  16631. return 0;
  16632. }
  16633. ret = GetInteger7Bit(input, &idx, (word32)sz);
  16634. if (ret < 0)
  16635. return ret;
  16636. cert->pathLength = (byte)ret;
  16637. cert->pathLengthSet = 1;
  16638. return 0;
  16639. #else
  16640. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  16641. int ret = 0;
  16642. word32 idx = 0;
  16643. byte isCA = 0;
  16644. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  16645. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  16646. if (ret == 0) {
  16647. /* Get the CA boolean and path length when present. */
  16648. GetASN_Boolean(&dataASN[BASICCONSASN_IDX_CA], &isCA);
  16649. GetASN_Int8Bit(&dataASN[BASICCONSASN_IDX_PLEN], &cert->pathLength);
  16650. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  16651. &idx, (word32)sz);
  16652. }
  16653. /* Empty SEQUENCE is OK - nothing to store. */
  16654. if ((ret == 0) && (dataASN[BASICCONSASN_IDX_SEQ].length != 0)) {
  16655. /* Bad encoding when CA Boolean is false
  16656. * (default when not present). */
  16657. if ((dataASN[BASICCONSASN_IDX_CA].length != 0) && (!isCA)) {
  16658. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16659. ret = ASN_PARSE_E;
  16660. }
  16661. /* Path length must be a 7-bit value. */
  16662. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  16663. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16664. ret = ASN_PARSE_E;
  16665. }
  16666. /* Store CA boolean and whether a path length was seen. */
  16667. if (ret == 0) {
  16668. /* isCA in certificate is a 1 bit of a byte. */
  16669. cert->isCA = isCA ? 1 : 0;
  16670. cert->pathLengthSet = (dataASN[BASICCONSASN_IDX_PLEN].length > 0);
  16671. }
  16672. }
  16673. FREE_ASNGETDATA(dataASN, cert->heap);
  16674. return ret;
  16675. #endif
  16676. }
  16677. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  16678. {
  16679. word32 idx = 0;
  16680. int length = 0;
  16681. int skipLength = 0;
  16682. int ret;
  16683. byte tag;
  16684. WOLFSSL_ENTER("DecodePolicyConstraints");
  16685. if (GetSequence(input, &idx, &length, (word32)sz) < 0) {
  16686. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  16687. return ASN_PARSE_E;
  16688. }
  16689. if (length == 0)
  16690. return ASN_PARSE_E;
  16691. if (GetASNTag(input, &idx, &tag, (word32)sz) < 0) {
  16692. WOLFSSL_MSG("\tfail: bad TAG");
  16693. return ASN_PARSE_E;
  16694. }
  16695. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  16696. /* requireExplicitPolicy */
  16697. cert->extPolicyConstRxpSet = 1;
  16698. }
  16699. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  16700. /* inhibitPolicyMapping */
  16701. cert->extPolicyConstIpmSet = 1;
  16702. }
  16703. else {
  16704. WOLFSSL_MSG("\tfail: invalid TAG");
  16705. return ASN_PARSE_E;
  16706. }
  16707. ret = GetLength(input, &idx, &skipLength, (word32)sz);
  16708. if (ret < 0) {
  16709. WOLFSSL_MSG("\tfail: invalid length");
  16710. return ret;
  16711. }
  16712. if (skipLength > 1) {
  16713. WOLFSSL_MSG("\tfail: skip value too big");
  16714. return BUFFER_E;
  16715. }
  16716. if (idx >= (word32)sz) {
  16717. WOLFSSL_MSG("\tfail: no policy const skip to read");
  16718. return BUFFER_E;
  16719. }
  16720. cert->policyConstSkip = input[idx];
  16721. return 0;
  16722. }
  16723. /* Context-Specific value for: DistributionPoint.distributionPoint
  16724. * From RFC5280 SS4.2.1.13, Distribution Point */
  16725. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  16726. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  16727. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  16728. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  16729. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  16730. * From RFC3280 SS4.2.1.7, GeneralName */
  16731. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  16732. #ifdef WOLFSSL_ASN_TEMPLATE
  16733. /* ASN.1 template for CRL distribution points.
  16734. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16735. */
  16736. static const ASNItem crlDistASN[] = {
  16737. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16738. /* DP_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  16739. /* Distribution point name */
  16740. /* DP_DISTPOINT */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  16741. /* fullName */
  16742. /* DP_DISTPOINT_FN */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  16743. /* DP_DISTPOINT_FN_GN */ { 4, GENERALNAME_URI, 0, 0, 0 },
  16744. /* nameRelativeToCRLIssuer */
  16745. /* DP_DISTPOINT_RN */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  16746. /* reasons: IMPLICIT BIT STRING */
  16747. /* DP_REASONS */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  16748. /* cRLIssuer */
  16749. /* DP_CRLISSUER */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  16750. };
  16751. enum {
  16752. CRLDISTASN_IDX_SEQ = 0,
  16753. CRLDISTASN_IDX_DP_SEQ,
  16754. CRLDISTASN_IDX_DP_DISTPOINT,
  16755. CRLDISTASN_IDX_DP_DISTPOINT_FN,
  16756. CRLDISTASN_IDX_DP_DISTPOINT_FN_GN,
  16757. CRLDISTASN_IDX_DP_DISTPOINT_RN, /* Relative name */
  16758. CRLDISTASN_IDX_DP_REASONS,
  16759. CRLDISTASN_IDX_DP_CRLISSUER
  16760. };
  16761. /* Number of items in ASN.1 template for CRL distribution points. */
  16762. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  16763. #endif
  16764. /* Decode CRL distribution point extension in a certificate.
  16765. *
  16766. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  16767. *
  16768. * @param [in] input Buffer holding data.
  16769. * @param [in] sz Size of data in buffer.
  16770. * @param [in, out] cert Certificate object.
  16771. * @return 0 on success.
  16772. * @return MEMORY_E on dynamic memory allocation failure.
  16773. * @return ASN_PARSE_E when invalid bits of reason are set.
  16774. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  16775. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  16776. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16777. * is invalid.
  16778. * @return BUFFER_E when data in buffer is too small.
  16779. */
  16780. static int DecodeCrlDist(const byte* input, word32 sz, DecodedCert* cert)
  16781. {
  16782. #ifndef WOLFSSL_ASN_TEMPLATE
  16783. word32 idx = 0, localIdx;
  16784. int length = 0;
  16785. byte tag = 0;
  16786. WOLFSSL_ENTER("DecodeCrlDist");
  16787. cert->extCrlInfoRaw = input;
  16788. cert->extCrlInfoRawSz = (int)sz;
  16789. /* Unwrap the list of Distribution Points*/
  16790. if (GetSequence(input, &idx, &length, sz) < 0)
  16791. return ASN_PARSE_E;
  16792. /* Unwrap a single Distribution Point */
  16793. if (GetSequence(input, &idx, &length, sz) < 0)
  16794. return ASN_PARSE_E;
  16795. /* The Distribution Point has three explicit optional members
  16796. * First check for a DistributionPointName
  16797. */
  16798. localIdx = idx;
  16799. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16800. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  16801. {
  16802. idx++;
  16803. if (GetLength(input, &idx, &length, sz) < 0)
  16804. return ASN_PARSE_E;
  16805. localIdx = idx;
  16806. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16807. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  16808. {
  16809. idx++;
  16810. if (GetLength(input, &idx, &length, sz) < 0)
  16811. return ASN_PARSE_E;
  16812. localIdx = idx;
  16813. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16814. tag == GENERALNAME_URI)
  16815. {
  16816. idx++;
  16817. if (GetLength(input, &idx, &length, sz) < 0)
  16818. return ASN_PARSE_E;
  16819. cert->extCrlInfoSz = length;
  16820. cert->extCrlInfo = input + idx;
  16821. idx += (word32)length;
  16822. }
  16823. else
  16824. /* This isn't a URI, skip it. */
  16825. idx += (word32)length;
  16826. }
  16827. else {
  16828. /* This isn't a FULLNAME, skip it. */
  16829. idx += (word32)length;
  16830. }
  16831. }
  16832. /* Check for reasonFlags */
  16833. localIdx = idx;
  16834. if (idx < (word32)sz &&
  16835. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16836. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  16837. {
  16838. idx++;
  16839. if (GetLength(input, &idx, &length, sz) < 0)
  16840. return ASN_PARSE_E;
  16841. idx += (word32)length;
  16842. }
  16843. /* Check for cRLIssuer */
  16844. localIdx = idx;
  16845. if (idx < (word32)sz &&
  16846. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  16847. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  16848. {
  16849. idx++;
  16850. if (GetLength(input, &idx, &length, sz) < 0)
  16851. return ASN_PARSE_E;
  16852. idx += (word32)length;
  16853. }
  16854. if (idx < (word32)sz)
  16855. {
  16856. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16857. "but we only use the first one.");
  16858. }
  16859. return 0;
  16860. #else
  16861. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  16862. word32 idx = 0;
  16863. int ret = 0;
  16864. #ifdef CRLDP_VALIDATE_DATA
  16865. word16 reason;
  16866. #endif
  16867. WOLFSSL_ENTER("DecodeCrlDist");
  16868. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  16869. cert->extCrlInfoRaw = input;
  16870. cert->extCrlInfoRawSz = (int)sz;
  16871. if (ret == 0) {
  16872. /* Get the GeneralName choice */
  16873. GetASN_Choice(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN], generalNameChoice);
  16874. /* Parse CRL distribtion point. */
  16875. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  16876. &idx, sz);
  16877. }
  16878. if (ret == 0) {
  16879. /* If the choice was a URI, store it in certificate. */
  16880. if (dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN].tag == GENERALNAME_URI) {
  16881. word32 sz32;
  16882. GetASN_GetConstRef(&dataASN[CRLDISTASN_IDX_DP_DISTPOINT_FN_GN],
  16883. &cert->extCrlInfo, &sz32);
  16884. cert->extCrlInfoSz = (int)sz32;
  16885. }
  16886. #ifdef CRLDP_VALIDATE_DATA
  16887. if (dataASN[CRLDISTASN_IDX_DP_REASONS].data.ref.data != NULL) {
  16888. /* TODO: test case */
  16889. /* Validate ReasonFlags. */
  16890. ret = GetASN_BitString_Int16Bit(&dataASN[CRLDISTASN_IDX_DP_REASONS],
  16891. &reason);
  16892. /* First bit (LSB) unused and eight other bits defined. */
  16893. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  16894. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  16895. ret = ASN_PARSE_E;
  16896. }
  16897. }
  16898. #endif
  16899. }
  16900. /* Only parsing the first one. */
  16901. if (ret == 0 && idx < (word32)sz) {
  16902. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  16903. "but we only use the first one.");
  16904. }
  16905. /* TODO: validate other points. */
  16906. FREE_ASNGETDATA(dataASN, cert->heap);
  16907. return ret;
  16908. #endif /* WOLFSSL_ASN_TEMPLATE */
  16909. }
  16910. #ifdef WOLFSSL_ASN_TEMPLATE
  16911. /* ASN.1 template for the access description.
  16912. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16913. */
  16914. static const ASNItem accessDescASN[] = {
  16915. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  16916. /* accessMethod */
  16917. /* METH */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  16918. /* accessLocation: GeneralName */
  16919. /* LOC */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  16920. };
  16921. enum {
  16922. ACCESSDESCASN_IDX_SEQ = 0,
  16923. ACCESSDESCASN_IDX_METH,
  16924. ACCESSDESCASN_IDX_LOC
  16925. };
  16926. /* Number of items in ASN.1 template for the access description. */
  16927. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  16928. #endif
  16929. /* Decode authority information access extension in a certificate.
  16930. *
  16931. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  16932. *
  16933. * @param [in] input Buffer holding data.
  16934. * @param [in] sz Size of data in buffer.
  16935. * @param [in, out] cert Certificate object.
  16936. * @return 0 on success.
  16937. * @return MEMORY_E on dynamic memory allocation failure.
  16938. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  16939. * is invalid.
  16940. * @return BUFFER_E when data in buffer is too small.
  16941. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  16942. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  16943. */
  16944. static int DecodeAuthInfo(const byte* input, word32 sz, DecodedCert* cert)
  16945. {
  16946. #ifndef WOLFSSL_ASN_TEMPLATE
  16947. word32 idx = 0;
  16948. int length = 0;
  16949. int count = 0;
  16950. byte b = 0;
  16951. word32 oid;
  16952. WOLFSSL_ENTER("DecodeAuthInfo");
  16953. /* Unwrap the list of AIAs */
  16954. if (GetSequence(input, &idx, &length, sz) < 0)
  16955. return ASN_PARSE_E;
  16956. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  16957. /* Unwrap a single AIA */
  16958. if (GetSequence(input, &idx, &length, sz) < 0)
  16959. return ASN_PARSE_E;
  16960. oid = 0;
  16961. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  16962. return ASN_PARSE_E;
  16963. }
  16964. /* Only supporting URIs right now. */
  16965. if (GetASNTag(input, &idx, &b, sz) < 0)
  16966. return ASN_PARSE_E;
  16967. if (GetLength(input, &idx, &length, sz) < 0)
  16968. return ASN_PARSE_E;
  16969. /* Set ocsp entry */
  16970. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  16971. {
  16972. cert->extAuthInfoSz = length;
  16973. cert->extAuthInfo = input + idx;
  16974. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16975. count++;
  16976. #else
  16977. break;
  16978. #endif
  16979. }
  16980. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  16981. /* Set CaIssuers entry */
  16982. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  16983. {
  16984. cert->extAuthInfoCaIssuerSz = length;
  16985. cert->extAuthInfoCaIssuer = input + idx;
  16986. count++;
  16987. }
  16988. #endif
  16989. idx += (word32)length;
  16990. }
  16991. return 0;
  16992. #else
  16993. word32 idx = 0;
  16994. int length = 0;
  16995. int count = 0;
  16996. int ret = 0;
  16997. WOLFSSL_ENTER("DecodeAuthInfo");
  16998. /* Unwrap the list of AIAs */
  16999. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17000. ret = ASN_PARSE_E;
  17001. }
  17002. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  17003. ASNGetData dataASN[accessDescASN_Length];
  17004. /* Clear dynamic data and retrieve OID and name. */
  17005. XMEMSET(dataASN, 0, sizeof(dataASN));
  17006. GetASN_OID(&dataASN[ACCESSDESCASN_IDX_METH], oidCertAuthInfoType);
  17007. GetASN_Choice(&dataASN[ACCESSDESCASN_IDX_LOC], generalNameChoice);
  17008. /* Parse AccessDescription. */
  17009. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  17010. input, &idx, sz);
  17011. if (ret == 0) {
  17012. word32 sz32;
  17013. /* Check we have OCSP and URI. */
  17014. if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum == AIA_OCSP_OID) &&
  17015. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  17016. /* Store URI for OCSP lookup. */
  17017. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17018. &cert->extAuthInfo, &sz32);
  17019. cert->extAuthInfoSz = (int)sz32;
  17020. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17021. count++;
  17022. #else
  17023. break;
  17024. #endif
  17025. }
  17026. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  17027. /* Check we have CA Issuer and URI. */
  17028. else if ((dataASN[ACCESSDESCASN_IDX_METH].data.oid.sum ==
  17029. AIA_CA_ISSUER_OID) &&
  17030. (dataASN[ACCESSDESCASN_IDX_LOC].tag == GENERALNAME_URI)) {
  17031. /* Set CaIssuers entry */
  17032. GetASN_GetConstRef(&dataASN[ACCESSDESCASN_IDX_LOC],
  17033. &cert->extAuthInfoCaIssuer, &sz32);
  17034. cert->extAuthInfoCaIssuerSz = sz32;
  17035. count++;
  17036. }
  17037. #endif
  17038. /* Otherwise skip. */
  17039. }
  17040. }
  17041. return ret;
  17042. #endif
  17043. }
  17044. #ifdef WOLFSSL_ASN_TEMPLATE
  17045. /* ASN.1 template for AuthorityKeyIdentifier.
  17046. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  17047. */
  17048. static const ASNItem authKeyIdASN[] = {
  17049. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17050. /* keyIdentifier */
  17051. /* KEYID */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_KEYID, 0, 0, 1 },
  17052. /* authorityCertIssuer */
  17053. /* ISSUER */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_ISSUER, 1, 0, 1 },
  17054. /* authorityCertSerialNumber */
  17055. /* SERIAL */ { 1, ASN_CONTEXT_SPECIFIC | ASN_AUTHKEYID_SERIAL, 0, 0, 1 },
  17056. };
  17057. enum {
  17058. AUTHKEYIDASN_IDX_SEQ = 0,
  17059. AUTHKEYIDASN_IDX_KEYID,
  17060. AUTHKEYIDASN_IDX_ISSUER,
  17061. AUTHKEYIDASN_IDX_SERIAL
  17062. };
  17063. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  17064. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  17065. #endif
  17066. /* Decode authority information access extension in a certificate.
  17067. *
  17068. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17069. *
  17070. * @param [in] input Buffer holding data.
  17071. * @param [in] sz Size of data in buffer.
  17072. * @param [in, out] cert Certificate object.
  17073. * @return 0 on success.
  17074. * @return MEMORY_E on dynamic memory allocation failure.
  17075. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17076. * is invalid.
  17077. * @return BUFFER_E when data in buffer is too small.
  17078. */
  17079. static int DecodeAuthKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17080. {
  17081. #ifndef WOLFSSL_ASN_TEMPLATE
  17082. word32 idx = 0;
  17083. int length = 0;
  17084. byte tag;
  17085. WOLFSSL_ENTER("DecodeAuthKeyId");
  17086. if (GetSequence(input, &idx, &length, sz) < 0) {
  17087. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17088. return ASN_PARSE_E;
  17089. }
  17090. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  17091. return ASN_PARSE_E;
  17092. }
  17093. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  17094. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  17095. cert->extAuthKeyIdSet = 0;
  17096. return 0;
  17097. }
  17098. if (GetLength(input, &idx, &length, sz) <= 0) {
  17099. WOLFSSL_MSG("\tfail: extension data length");
  17100. return ASN_PARSE_E;
  17101. }
  17102. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17103. #ifdef WOLFSSL_AKID_NAME
  17104. cert->extRawAuthKeyIdSrc = input;
  17105. cert->extRawAuthKeyIdSz = sz;
  17106. #endif
  17107. cert->extAuthKeyIdSrc = &input[idx];
  17108. cert->extAuthKeyIdSz = length;
  17109. #endif /* OPENSSL_EXTRA */
  17110. return GetHashId(input + idx, length, cert->extAuthKeyId,
  17111. HashIdAlg(cert->signatureOID));
  17112. #else
  17113. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  17114. int ret = 0;
  17115. word32 idx = 0;
  17116. WOLFSSL_ENTER("DecodeAuthKeyId");
  17117. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  17118. if (ret == 0) {
  17119. /* Parse an authority key identifier. */
  17120. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  17121. &idx, sz);
  17122. }
  17123. if (ret == 0) {
  17124. /* Key id is optional. */
  17125. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  17126. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  17127. }
  17128. else {
  17129. #ifdef OPENSSL_EXTRA
  17130. /* Store the authority key id. */
  17131. #ifdef WOLFSSL_AKID_NAME
  17132. cert->extRawAuthKeyIdSrc = input;
  17133. cert->extRawAuthKeyIdSz = sz;
  17134. #endif
  17135. GetASN_GetConstRef(&dataASN[AUTHKEYIDASN_IDX_KEYID], &cert->extAuthKeyIdSrc,
  17136. &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(cert->signatureOID));
  17142. }
  17143. }
  17144. FREE_ASNGETDATA(dataASN, cert->heap);
  17145. return ret;
  17146. #endif /* WOLFSSL_ASN_TEMPLATE */
  17147. }
  17148. /* Decode subject key id extension in a certificate.
  17149. *
  17150. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17151. *
  17152. * @param [in] input Buffer holding data.
  17153. * @param [in] sz Size of data in buffer.
  17154. * @param [in, out] cert Certificate object.
  17155. * @return 0 on success.
  17156. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  17157. * invalid.
  17158. * @return MEMORY_E on dynamic memory allocation failure.
  17159. */
  17160. static int DecodeSubjKeyId(const byte* input, word32 sz, DecodedCert* cert)
  17161. {
  17162. word32 idx = 0;
  17163. int length = 0;
  17164. int ret = 0;
  17165. WOLFSSL_ENTER("DecodeSubjKeyId");
  17166. ret = GetOctetString(input, &idx, &length, sz);
  17167. if (ret > 0) {
  17168. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17169. cert->extSubjKeyIdSrc = &input[idx];
  17170. cert->extSubjKeyIdSz = length;
  17171. #endif /* OPENSSL_EXTRA */
  17172. /* Get the hash or hash of the hash if wrong size. */
  17173. ret = GetHashId(input + idx, length, cert->extSubjKeyId,
  17174. HashIdAlg(cert->signatureOID));
  17175. }
  17176. return ret;
  17177. }
  17178. #ifdef WOLFSSL_ASN_TEMPLATE
  17179. /* ASN.1 template for KeyUsage.
  17180. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  17181. */
  17182. static const ASNItem keyUsageASN[] = {
  17183. /* STR */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  17184. };
  17185. enum {
  17186. KEYUSAGEASN_IDX_STR = 0
  17187. };
  17188. /* Number of items in ASN.1 template for KeyUsage. */
  17189. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  17190. #endif
  17191. /* Decode key usage extension in a certificate.
  17192. *
  17193. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  17194. *
  17195. * @param [in] input Buffer holding data.
  17196. * @param [in] sz Size of data in buffer.
  17197. * @param [in, out] cert Certificate object.
  17198. * @return 0 on success.
  17199. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17200. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17201. * is invalid.
  17202. * @return MEMORY_E on dynamic memory allocation failure.
  17203. */
  17204. static int DecodeKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17205. {
  17206. #ifndef WOLFSSL_ASN_TEMPLATE
  17207. word32 idx = 0;
  17208. int length;
  17209. int ret;
  17210. WOLFSSL_ENTER("DecodeKeyUsage");
  17211. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  17212. if (ret != 0)
  17213. return ret;
  17214. if (length == 0 || length > 2)
  17215. return ASN_PARSE_E;
  17216. cert->extKeyUsage = (word16)(input[idx]);
  17217. if (length == 2)
  17218. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  17219. return 0;
  17220. #else
  17221. ASNGetData dataASN[keyUsageASN_Length];
  17222. word32 idx = 0;
  17223. WOLFSSL_ENTER("DecodeKeyUsage");
  17224. /* Clear dynamic data and set where to store extended key usage. */
  17225. XMEMSET(dataASN, 0, sizeof(dataASN));
  17226. GetASN_Int16Bit(&dataASN[KEYUSAGEASN_IDX_STR], &cert->extKeyUsage);
  17227. /* Parse key usage. */
  17228. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  17229. &idx, sz);
  17230. #endif /* WOLFSSL_ASN_TEMPLATE */
  17231. }
  17232. #ifdef WOLFSSL_ASN_TEMPLATE
  17233. /* ASN.1 template for KeyPurposeId.
  17234. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17235. */
  17236. static const ASNItem keyPurposeIdASN[] = {
  17237. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  17238. };
  17239. enum {
  17240. KEYPURPOSEIDASN_IDX_OID = 0
  17241. };
  17242. /* Number of items in ASN.1 template for KeyPurposeId. */
  17243. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  17244. #endif
  17245. /* Decode extended key usage extension in a certificate.
  17246. *
  17247. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  17248. *
  17249. * @param [in] input Buffer holding data.
  17250. * @param [in] sz Size of data in buffer.
  17251. * @param [in, out] cert Certificate object.
  17252. * @return 0 on success.
  17253. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  17254. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17255. * is invalid.
  17256. * @return MEMORY_E on dynamic memory allocation failure.
  17257. */
  17258. static int DecodeExtKeyUsage(const byte* input, word32 sz, DecodedCert* cert)
  17259. {
  17260. #ifndef WOLFSSL_ASN_TEMPLATE
  17261. word32 idx = 0, oid;
  17262. int length, ret;
  17263. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17264. if (GetSequence(input, &idx, &length, sz) < 0) {
  17265. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17266. return ASN_PARSE_E;
  17267. }
  17268. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17269. cert->extExtKeyUsageSrc = input + idx;
  17270. cert->extExtKeyUsageSz = length;
  17271. #endif
  17272. while (idx < (word32)sz) {
  17273. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  17274. if (ret == ASN_UNKNOWN_OID_E)
  17275. continue;
  17276. else if (ret < 0)
  17277. return ret;
  17278. switch (oid) {
  17279. case EKU_ANY_OID:
  17280. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17281. break;
  17282. case EKU_SERVER_AUTH_OID:
  17283. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17284. break;
  17285. case EKU_CLIENT_AUTH_OID:
  17286. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17287. break;
  17288. case EKU_CODESIGNING_OID:
  17289. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17290. break;
  17291. case EKU_EMAILPROTECT_OID:
  17292. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17293. break;
  17294. case EKU_TIMESTAMP_OID:
  17295. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17296. break;
  17297. case EKU_OCSP_SIGN_OID:
  17298. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17299. break;
  17300. #ifdef WOLFSSL_WOLFSSH
  17301. case EKU_SSH_CLIENT_AUTH_OID:
  17302. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_CLIENT_AUTH;
  17303. break;
  17304. case EKU_SSH_MSCL_OID:
  17305. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_MSCL;
  17306. break;
  17307. case EKU_SSH_KP_CLIENT_AUTH_OID:
  17308. cert->extExtKeyUsageSsh |= EXTKEYUSE_SSH_KP_CLIENT_AUTH;
  17309. break;
  17310. #endif /* WOLFSSL_WOLFSSH */
  17311. default:
  17312. break;
  17313. }
  17314. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17315. cert->extExtKeyUsageCount++;
  17316. #endif
  17317. }
  17318. return 0;
  17319. #else
  17320. word32 idx = 0;
  17321. int length;
  17322. int ret = 0;
  17323. WOLFSSL_ENTER("DecodeExtKeyUsage");
  17324. /* Strip SEQUENCE OF and expect to account for all the data. */
  17325. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  17326. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17327. ret = ASN_PARSE_E;
  17328. }
  17329. if (ret == 0) {
  17330. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17331. /* Keep reference for WOLFSSL_X509. */
  17332. cert->extExtKeyUsageSrc = input + idx;
  17333. cert->extExtKeyUsageSz = length;
  17334. #endif
  17335. }
  17336. /* Check all OIDs. */
  17337. while ((ret == 0) && (idx < (word32)sz)) {
  17338. ASNGetData dataASN[keyPurposeIdASN_Length];
  17339. /* Clear dynamic data items and set OID type expected. */
  17340. XMEMSET(dataASN, 0, sizeof(dataASN));
  17341. GetASN_OID(&dataASN[KEYPURPOSEIDASN_IDX_OID], oidIgnoreType);
  17342. /* Decode KeyPurposeId. */
  17343. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  17344. input, &idx, sz);
  17345. /* Skip unknown OIDs. */
  17346. if (ret == ASN_UNKNOWN_OID_E) {
  17347. ret = 0;
  17348. }
  17349. else if (ret == 0) {
  17350. /* Store the bit for the OID. */
  17351. switch (dataASN[KEYPURPOSEIDASN_IDX_OID].data.oid.sum) {
  17352. case EKU_ANY_OID:
  17353. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  17354. break;
  17355. case EKU_SERVER_AUTH_OID:
  17356. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  17357. break;
  17358. case EKU_CLIENT_AUTH_OID:
  17359. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  17360. break;
  17361. case EKU_CODESIGNING_OID:
  17362. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  17363. break;
  17364. case EKU_EMAILPROTECT_OID:
  17365. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  17366. break;
  17367. case EKU_TIMESTAMP_OID:
  17368. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  17369. break;
  17370. case EKU_OCSP_SIGN_OID:
  17371. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  17372. break;
  17373. }
  17374. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17375. /* Keep count for WOLFSSL_X509. */
  17376. cert->extExtKeyUsageCount++;
  17377. #endif
  17378. }
  17379. }
  17380. return ret;
  17381. #endif /* WOLFSSL_ASN_TEMPLATE */
  17382. }
  17383. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  17384. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  17385. {
  17386. word32 idx = 0;
  17387. int len = 0;
  17388. WOLFSSL_ENTER("DecodeNsCertType");
  17389. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0)
  17390. return ASN_PARSE_E;
  17391. /* Don't need to worry about unused bits as CheckBitString makes sure
  17392. * they're zero. */
  17393. if (idx < (word32)sz)
  17394. cert->nsCertType = input[idx];
  17395. else
  17396. return ASN_PARSE_E;
  17397. return 0;
  17398. }
  17399. #endif
  17400. #ifndef IGNORE_NAME_CONSTRAINTS
  17401. #ifdef WOLFSSL_ASN_TEMPLATE
  17402. /* ASN.1 template for GeneralSubtree.
  17403. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17404. */
  17405. static const ASNItem subTreeASN[] = {
  17406. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17407. /* base GeneralName */
  17408. /* BASE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  17409. /* minimum BaseDistance DEFAULT 0*/
  17410. /* MIN */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MIN, 0, 0, 1 },
  17411. /* maximum BaseDistance OPTIONAL */
  17412. /* MAX */ { 1, ASN_CONTEXT_SPECIFIC | ASN_SUBTREE_MAX, 0, 0, 1 },
  17413. };
  17414. enum {
  17415. SUBTREEASN_IDX_SEQ = 0,
  17416. SUBTREEASN_IDX_BASE,
  17417. SUBTREEASN_IDX_MIN,
  17418. SUBTREEASN_IDX_MAX
  17419. };
  17420. /* Number of items in ASN.1 template for GeneralSubtree. */
  17421. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  17422. #endif
  17423. #ifdef WOLFSSL_ASN_TEMPLATE
  17424. /* Decode the Subtree's GeneralName.
  17425. *
  17426. * @param [in] input Buffer holding data.
  17427. * @param [in] sz Size of data in buffer.
  17428. * @param [in] tag BER tag on GeneralName.
  17429. * @param [in, out] head Linked list of subtree names.
  17430. * @param [in] heap Dynamic memory hint.
  17431. * @return 0 on success.
  17432. * @return MEMORY_E when dynamic memory allocation fails.
  17433. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17434. */
  17435. static int DecodeSubtreeGeneralName(const byte* input, word32 sz, byte tag,
  17436. Base_entry** head, void* heap)
  17437. {
  17438. Base_entry* entry;
  17439. word32 nameIdx = 0;
  17440. word32 len = sz;
  17441. int strLen;
  17442. int ret = 0;
  17443. (void)heap;
  17444. /* if constructed has leading sequence */
  17445. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  17446. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  17447. if (ret < 0) {
  17448. ret = ASN_PARSE_E;
  17449. }
  17450. else {
  17451. len = (word32)strLen;
  17452. ret = 0;
  17453. }
  17454. }
  17455. if (ret == 0) {
  17456. /* TODO: consider one malloc. */
  17457. /* Allocate Base Entry object. */
  17458. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17459. DYNAMIC_TYPE_ALTNAME);
  17460. if (entry == NULL) {
  17461. ret = MEMORY_E;
  17462. }
  17463. }
  17464. if (ret == 0) {
  17465. /* Allocate name. */
  17466. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  17467. if (entry->name == NULL) {
  17468. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17469. ret = MEMORY_E;
  17470. }
  17471. }
  17472. if (ret == 0) {
  17473. /* Store name, size and tag in object. */
  17474. XMEMCPY(entry->name, &input[nameIdx], len);
  17475. entry->name[len] = '\0';
  17476. entry->nameSz = (int)len;
  17477. entry->type = tag & ASN_TYPE_MASK;
  17478. /* Put entry at front of linked list. */
  17479. entry->next = *head;
  17480. *head = entry;
  17481. }
  17482. return ret;
  17483. }
  17484. #endif
  17485. /* Decode a subtree of a name constraints in a certificate.
  17486. *
  17487. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  17488. *
  17489. * @param [in] input Buffer holding data.
  17490. * @param [in] sz Size of data in buffer.
  17491. * @param [in, out] head Linked list of subtree names.
  17492. * @param [in] heap Dynamic memory hint.
  17493. * @return 0 on success.
  17494. * @return MEMORY_E when dynamic memory allocation fails.
  17495. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  17496. */
  17497. static int DecodeSubtree(const byte* input, word32 sz, Base_entry** head,
  17498. void* heap)
  17499. {
  17500. #ifndef WOLFSSL_ASN_TEMPLATE
  17501. word32 idx = 0;
  17502. int ret = 0;
  17503. (void)heap;
  17504. while (idx < (word32)sz) {
  17505. int seqLength, strLength;
  17506. word32 nameIdx;
  17507. byte b, bType;
  17508. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  17509. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17510. return ASN_PARSE_E;
  17511. }
  17512. if (idx >= (word32)sz) {
  17513. WOLFSSL_MSG("\tfail: expecting tag");
  17514. return ASN_PARSE_E;
  17515. }
  17516. nameIdx = idx;
  17517. b = input[nameIdx++];
  17518. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  17519. WOLFSSL_MSG("\tinvalid length");
  17520. return ASN_PARSE_E;
  17521. }
  17522. /* Get type, LSB 4-bits */
  17523. bType = (byte)(b & ASN_TYPE_MASK);
  17524. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  17525. bType == ASN_DIR_TYPE) {
  17526. Base_entry* entry;
  17527. /* if constructed has leading sequence */
  17528. if (b & ASN_CONSTRUCTED) {
  17529. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  17530. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  17531. return ASN_PARSE_E;
  17532. }
  17533. }
  17534. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  17535. DYNAMIC_TYPE_ALTNAME);
  17536. if (entry == NULL) {
  17537. WOLFSSL_MSG("allocate error");
  17538. return MEMORY_E;
  17539. }
  17540. entry->name = (char*)XMALLOC((size_t)strLength+1, heap,
  17541. DYNAMIC_TYPE_ALTNAME);
  17542. if (entry->name == NULL) {
  17543. WOLFSSL_MSG("allocate error");
  17544. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  17545. return MEMORY_E;
  17546. }
  17547. XMEMCPY(entry->name, &input[nameIdx], (size_t)strLength);
  17548. entry->name[strLength] = '\0';
  17549. entry->nameSz = strLength;
  17550. entry->type = bType;
  17551. entry->next = *head;
  17552. *head = entry;
  17553. }
  17554. idx += (word32)seqLength;
  17555. }
  17556. return ret;
  17557. #else
  17558. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  17559. word32 idx = 0;
  17560. int ret = 0;
  17561. (void)heap;
  17562. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  17563. /* Process all subtrees. */
  17564. while ((ret == 0) && (idx < (word32)sz)) {
  17565. byte minVal = 0;
  17566. byte maxVal = 0;
  17567. /* Clear dynamic data and set choice for GeneralName and location to
  17568. * store minimum and maximum.
  17569. */
  17570. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  17571. GetASN_Choice(&dataASN[SUBTREEASN_IDX_BASE], generalNameChoice);
  17572. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MIN], &minVal);
  17573. GetASN_Int8Bit(&dataASN[SUBTREEASN_IDX_MAX], &maxVal);
  17574. /* Parse GeneralSubtree. */
  17575. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  17576. &idx, sz);
  17577. if (ret == 0) {
  17578. byte t = dataASN[SUBTREEASN_IDX_BASE].tag;
  17579. /* Check GeneralName tag is one of the types we can handle. */
  17580. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  17581. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  17582. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  17583. /* Parse the general name and store a new entry. */
  17584. ret = DecodeSubtreeGeneralName(input +
  17585. GetASNItem_DataIdx(dataASN[SUBTREEASN_IDX_BASE], input),
  17586. dataASN[SUBTREEASN_IDX_BASE].length, t, head, heap);
  17587. }
  17588. /* Skip entry. */
  17589. }
  17590. }
  17591. FREE_ASNGETDATA(dataASN, heap);
  17592. return ret;
  17593. #endif
  17594. }
  17595. #ifdef WOLFSSL_ASN_TEMPLATE
  17596. /* ASN.1 template for NameConstraints.
  17597. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  17598. */
  17599. static const ASNItem nameConstraintsASN[] = {
  17600. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17601. /* permittedSubtrees */
  17602. /* PERMIT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  17603. /* excludededSubtrees */
  17604. /* EXCLUDE */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  17605. };
  17606. enum {
  17607. NAMECONSTRAINTSASN_IDX_SEQ = 0,
  17608. NAMECONSTRAINTSASN_IDX_PERMIT,
  17609. NAMECONSTRAINTSASN_IDX_EXCLUDE
  17610. };
  17611. /* Number of items in ASN.1 template for NameConstraints. */
  17612. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  17613. #endif
  17614. /* Decode name constraints extension in a certificate.
  17615. *
  17616. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  17617. *
  17618. * @param [in] input Buffer holding data.
  17619. * @param [in] sz Size of data in buffer.
  17620. * @param [in, out] cert Certificate object.
  17621. * @return 0 on success.
  17622. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17623. * is invalid.
  17624. * @return MEMORY_E on dynamic memory allocation failure.
  17625. */
  17626. static int DecodeNameConstraints(const byte* input, word32 sz,
  17627. DecodedCert* cert)
  17628. {
  17629. #ifndef WOLFSSL_ASN_TEMPLATE
  17630. word32 idx = 0;
  17631. int length = 0;
  17632. WOLFSSL_ENTER("DecodeNameConstraints");
  17633. if (GetSequence(input, &idx, &length, sz) < 0) {
  17634. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  17635. return ASN_PARSE_E;
  17636. }
  17637. while (idx < (word32)sz) {
  17638. byte b = input[idx++];
  17639. Base_entry** subtree = NULL;
  17640. if (GetLength(input, &idx, &length, sz) <= 0) {
  17641. WOLFSSL_MSG("\tinvalid length");
  17642. return ASN_PARSE_E;
  17643. }
  17644. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  17645. subtree = &cert->permittedNames;
  17646. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  17647. subtree = &cert->excludedNames;
  17648. else {
  17649. WOLFSSL_MSG("\tinvalid subtree");
  17650. return ASN_PARSE_E;
  17651. }
  17652. if (DecodeSubtree(input + idx, (word32)length, subtree,
  17653. cert->heap) < 0) {
  17654. WOLFSSL_MSG("\terror parsing subtree");
  17655. return ASN_PARSE_E;
  17656. }
  17657. idx += (word32)length;
  17658. }
  17659. return 0;
  17660. #else
  17661. DECL_ASNGETDATA(dataASN, nameConstraintsASN_Length);
  17662. word32 idx = 0;
  17663. int ret = 0;
  17664. CALLOC_ASNGETDATA(dataASN, nameConstraintsASN_Length, ret, cert->heap);
  17665. if (ret == 0) {
  17666. /* Parse NameConstraints. */
  17667. ret = GetASN_Items(nameConstraintsASN, dataASN,
  17668. nameConstraintsASN_Length, 1, input, &idx, sz);
  17669. }
  17670. if (ret == 0) {
  17671. /* If there was a permittedSubtrees then parse it. */
  17672. if (dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data != NULL) {
  17673. ret = DecodeSubtree(
  17674. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.data,
  17675. dataASN[NAMECONSTRAINTSASN_IDX_PERMIT].data.ref.length,
  17676. &cert->permittedNames, cert->heap);
  17677. }
  17678. }
  17679. if (ret == 0) {
  17680. /* If there was a excludedSubtrees then parse it. */
  17681. if (dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data != NULL) {
  17682. ret = DecodeSubtree(
  17683. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.data,
  17684. dataASN[NAMECONSTRAINTSASN_IDX_EXCLUDE].data.ref.length,
  17685. &cert->excludedNames, cert->heap);
  17686. }
  17687. }
  17688. FREE_ASNGETDATA(dataASN, cert->heap);
  17689. return ret;
  17690. #endif /* WOLFSSL_ASN_TEMPLATE */
  17691. }
  17692. #endif /* IGNORE_NAME_CONSTRAINTS */
  17693. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  17694. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  17695. /* Decode ITU-T X.690 OID format to a string representation
  17696. * return string length */
  17697. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  17698. {
  17699. word32 val, inIdx = 0, outIdx = 0;
  17700. int w = 0;
  17701. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  17702. return BAD_FUNC_ARG;
  17703. /* The first byte expands into b/40 dot b%40. */
  17704. val = in[inIdx++];
  17705. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  17706. if (w < 0) {
  17707. w = BUFFER_E;
  17708. goto exit;
  17709. }
  17710. outIdx += w;
  17711. val = 0;
  17712. while (inIdx < inSz && outIdx < outSz) {
  17713. /* extract the next OID digit from in to val */
  17714. /* first bit is used to set if value is coded on 1 or multiple bytes */
  17715. if (in[inIdx] & 0x80) {
  17716. val += in[inIdx] & 0x7F;
  17717. val *= 128;
  17718. }
  17719. else {
  17720. /* write val as text into out */
  17721. val += in[inIdx];
  17722. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  17723. if (w < 0 || (word32)w > outSz - outIdx) {
  17724. w = BUFFER_E;
  17725. goto exit;
  17726. }
  17727. outIdx += w;
  17728. val = 0;
  17729. }
  17730. inIdx++;
  17731. }
  17732. if (outIdx == outSz)
  17733. outIdx--;
  17734. out[outIdx] = 0;
  17735. w = (int)outIdx;
  17736. exit:
  17737. return w;
  17738. }
  17739. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  17740. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  17741. #ifdef WOLFSSL_ASN_TEMPLATE
  17742. /* ASN.1 template for PolicyInformation.
  17743. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  17744. */
  17745. static const ASNItem policyInfoASN[] = {
  17746. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  17747. /* policyIdentifier */
  17748. /* ID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  17749. /* policyQualifiers */
  17750. /* QUALI */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  17751. };
  17752. enum {
  17753. POLICYINFOASN_IDX_SEQ = 0,
  17754. POLICYINFOASN_IDX_ID,
  17755. POLICYINFOASN_IDX_QUALI
  17756. };
  17757. /* Number of items in ASN.1 template for PolicyInformation. */
  17758. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  17759. #endif
  17760. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  17761. static int DecodeCertPolicy(const byte* input, word32 sz, DecodedCert* cert)
  17762. {
  17763. #ifndef WOLFSSL_ASN_TEMPLATE
  17764. word32 idx = 0;
  17765. word32 oldIdx;
  17766. int policy_length = 0;
  17767. int ret;
  17768. int total_length = 0;
  17769. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17770. !defined(WOLFSSL_DUP_CERTPOL)
  17771. int i;
  17772. #endif
  17773. WOLFSSL_ENTER("DecodeCertPolicy");
  17774. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17775. /* Check if cert is null before dereferencing below */
  17776. if (cert == NULL)
  17777. return BAD_FUNC_ARG;
  17778. #else
  17779. (void)cert;
  17780. #endif
  17781. #if defined(WOLFSSL_CERT_EXT)
  17782. cert->extCertPoliciesNb = 0;
  17783. #endif
  17784. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  17785. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  17786. return ASN_PARSE_E;
  17787. }
  17788. /* Validate total length */
  17789. if (total_length > (int)(sz - idx)) {
  17790. WOLFSSL_MSG("\tCertPolicy length mismatch");
  17791. return ASN_PARSE_E;
  17792. }
  17793. /* Unwrap certificatePolicies */
  17794. do {
  17795. int length = 0;
  17796. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  17797. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  17798. return ASN_PARSE_E;
  17799. }
  17800. oldIdx = idx;
  17801. ret = GetASNObjectId(input, &idx, &length, sz);
  17802. if (ret != 0)
  17803. return ret;
  17804. policy_length -= (int)(idx - oldIdx);
  17805. if (length > 0) {
  17806. /* Verify length won't overrun buffer */
  17807. if (length > (int)(sz - idx)) {
  17808. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  17809. return ASN_PARSE_E;
  17810. }
  17811. #if defined(WOLFSSL_SEP)
  17812. cert->deviceType = (byte*)XMALLOC((size_t)length, cert->heap,
  17813. DYNAMIC_TYPE_X509_EXT);
  17814. if (cert->deviceType == NULL) {
  17815. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17816. return MEMORY_E;
  17817. }
  17818. cert->deviceTypeSz = length;
  17819. XMEMCPY(cert->deviceType, input + idx, (size_t)length);
  17820. break;
  17821. #elif defined(WOLFSSL_CERT_EXT)
  17822. /* decode cert policy */
  17823. if (DecodePolicyOID(cert->extCertPolicies[
  17824. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  17825. input + idx, length) <= 0) {
  17826. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17827. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17828. return ASN_PARSE_E;
  17829. }
  17830. #ifndef WOLFSSL_DUP_CERTPOL
  17831. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17832. * NOT appear more than once in a certificate policies
  17833. * extension". This is a sanity check for duplicates.
  17834. * extCertPolicies should only have OID values, additional
  17835. * qualifiers need to be stored in a separate array. */
  17836. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  17837. if (XMEMCMP(cert->extCertPolicies[i],
  17838. cert->extCertPolicies[cert->extCertPoliciesNb],
  17839. MAX_CERTPOL_SZ) == 0) {
  17840. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17841. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17842. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17843. return CERTPOLICIES_E;
  17844. }
  17845. }
  17846. #endif /* !WOLFSSL_DUP_CERTPOL */
  17847. cert->extCertPoliciesNb++;
  17848. #else
  17849. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17850. return 0;
  17851. #endif
  17852. }
  17853. idx += (word32)policy_length;
  17854. } while((int)idx < total_length
  17855. #if defined(WOLFSSL_CERT_EXT)
  17856. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  17857. #endif
  17858. );
  17859. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17860. return 0;
  17861. #else /* WOLFSSL_ASN_TEMPLATE */
  17862. word32 idx = 0;
  17863. int ret = 0;
  17864. int total_length = 0;
  17865. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  17866. !defined(WOLFSSL_DUP_CERTPOL)
  17867. int i;
  17868. #endif
  17869. WOLFSSL_ENTER("DecodeCertPolicy");
  17870. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  17871. /* Check if cert is null before dereferencing below */
  17872. if (cert == NULL)
  17873. ret = BAD_FUNC_ARG;
  17874. #endif
  17875. if (ret == 0) {
  17876. #if defined(WOLFSSL_CERT_EXT)
  17877. cert->extCertPoliciesNb = 0;
  17878. #endif
  17879. /* Strip SEQUENCE OF and check using all data. */
  17880. if (GetASN_Sequence(input, &idx, &total_length, (word32)sz, 1) < 0)
  17881. {
  17882. ret = ASN_PARSE_E;
  17883. }
  17884. }
  17885. /* Unwrap certificatePolicies */
  17886. while ((ret == 0) && ((int)idx < total_length)
  17887. #if defined(WOLFSSL_CERT_EXT)
  17888. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  17889. #endif
  17890. ) {
  17891. ASNGetData dataASN[policyInfoASN_Length];
  17892. byte* data = NULL;
  17893. word32 length = 0;
  17894. /* Clear dynamic data and check OID is a cert policy type. */
  17895. XMEMSET(dataASN, 0, sizeof(dataASN));
  17896. GetASN_OID(&dataASN[POLICYINFOASN_IDX_ID], oidCertPolicyType);
  17897. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  17898. input, &idx, (word32)sz);
  17899. if (ret == 0) {
  17900. /* Get the OID. */
  17901. GetASN_OIDData(&dataASN[POLICYINFOASN_IDX_ID], &data, &length);
  17902. if (length == 0) {
  17903. ret = ASN_PARSE_E;
  17904. }
  17905. }
  17906. #if defined(WOLFSSL_SEP)
  17907. /* Store OID in device type. */
  17908. if (ret == 0) {
  17909. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  17910. DYNAMIC_TYPE_X509_EXT);
  17911. if (cert->deviceType == NULL) {
  17912. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  17913. ret = MEMORY_E;
  17914. }
  17915. }
  17916. if (ret == 0) {
  17917. /* Store device type data and length. */
  17918. cert->deviceTypeSz = (int)length;
  17919. XMEMCPY(cert->deviceType, data, length);
  17920. break;
  17921. }
  17922. #elif defined(WOLFSSL_CERT_EXT)
  17923. if (ret == 0) {
  17924. /* Decode cert policy. */
  17925. if (DecodePolicyOID(
  17926. cert->extCertPolicies[cert->extCertPoliciesNb],
  17927. MAX_CERTPOL_SZ, data, length) <= 0) {
  17928. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  17929. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  17930. ret = ASN_PARSE_E;
  17931. }
  17932. }
  17933. #ifndef WOLFSSL_DUP_CERTPOL
  17934. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  17935. * NOT appear more than once in a certificate policies
  17936. * extension". This is a sanity check for duplicates.
  17937. * extCertPolicies should only have OID values, additional
  17938. * qualifiers need to be stored in a seperate array. */
  17939. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  17940. if (XMEMCMP(cert->extCertPolicies[i],
  17941. cert->extCertPolicies[cert->extCertPoliciesNb],
  17942. MAX_CERTPOL_SZ) == 0) {
  17943. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  17944. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  17945. WOLFSSL_ERROR_VERBOSE(CERTPOLICIES_E);
  17946. ret = CERTPOLICIES_E;
  17947. }
  17948. }
  17949. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  17950. if (ret == 0) {
  17951. /* Keep count of policies seen. */
  17952. cert->extCertPoliciesNb++;
  17953. }
  17954. #else
  17955. (void)data;
  17956. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  17957. break;
  17958. #endif
  17959. }
  17960. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  17961. return ret;
  17962. #endif /* WOLFSSL_ASN_TEMPLATE */
  17963. }
  17964. #endif /* WOLFSSL_SEP */
  17965. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  17966. #ifdef WOLFSSL_ASN_TEMPLATE
  17967. /* ASN.1 template for subject dir attribute.
  17968. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17969. */
  17970. static const ASNItem subjDirAttrASN[] = {
  17971. /* SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  17972. /* OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  17973. /* PLEN */ { 2, ASN_SET, 1, 0, 0 },
  17974. };
  17975. enum {
  17976. SUBJDIRATTRASN_IDX_SEQ = 0,
  17977. SUBJDIRATTRASN_IDX_OID,
  17978. SUBJDIRATTRASN_IDX_SET,
  17979. };
  17980. /* Number of items in ASN.1 template for BasicContraints. */
  17981. #define subjDirAttrASN_Length (sizeof(subjDirAttrASN) / sizeof(ASNItem))
  17982. #endif
  17983. /* Decode subject directory attributes extension in a certificate.
  17984. *
  17985. * X.509: RFC 5280, 4.2.1.8 - Subject Directory Attributes.
  17986. *
  17987. * @param [in] input Buffer holding data.
  17988. * @param [in] sz Size of data in buffer.
  17989. * @param [in, out] cert Certificate object.
  17990. * @return 0 on success.
  17991. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  17992. * is invalid.
  17993. */
  17994. static int DecodeSubjDirAttr(const byte* input, int sz, DecodedCert* cert)
  17995. {
  17996. #ifndef WOLFSSL_ASN_TEMPLATE
  17997. word32 idx = 0;
  17998. int length = 0;
  17999. int ret = 0;
  18000. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18001. #ifdef OPENSSL_ALL
  18002. cert->extSubjDirAttrSrc = input;
  18003. cert->extSubjDirAttrSz = sz;
  18004. #endif /* OPENSSL_ALL */
  18005. /* Unwrap the list of Attributes */
  18006. if (GetSequence(input, &idx, &length, sz) < 0)
  18007. return ASN_PARSE_E;
  18008. if (length == 0) {
  18009. /* RFC 5280 4.2.1.8. Subject Directory Attributes
  18010. If the subjectDirectoryAttributes extension is present, the
  18011. sequence MUST contain at least one entry. */
  18012. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18013. return ASN_PARSE_E;
  18014. }
  18015. /* length is the length of the list contents */
  18016. while (idx < (word32)sz) {
  18017. word32 oid;
  18018. if (GetSequence(input, &idx, &length, sz) < 0)
  18019. return ASN_PARSE_E;
  18020. if (GetObjectId(input, &idx, &oid, oidSubjDirAttrType, sz) < 0)
  18021. return ASN_PARSE_E;
  18022. if (GetSet(input, &idx, &length, sz) < 0)
  18023. return ASN_PARSE_E;
  18024. /* There may be more than one countryOfCitizenship, but save the
  18025. * first one for now. */
  18026. if (oid == SDA_COC_OID) {
  18027. byte tag;
  18028. if (GetHeader(input, &tag, &idx, &length, sz, 1) < 0)
  18029. return ASN_PARSE_E;
  18030. if (length != COUNTRY_CODE_LEN)
  18031. return ASN_PARSE_E;
  18032. if (tag == ASN_PRINTABLE_STRING) {
  18033. XMEMCPY(cert->countryOfCitizenship,
  18034. input + idx, COUNTRY_CODE_LEN);
  18035. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18036. }
  18037. }
  18038. idx += length;
  18039. }
  18040. return ret;
  18041. #else
  18042. DECL_ASNGETDATA(dataASN, subjDirAttrASN_Length);
  18043. int ret = 0;
  18044. word32 idx = 0;
  18045. int length;
  18046. WOLFSSL_ENTER("DecodeSubjDirAttr");
  18047. CALLOC_ASNGETDATA(dataASN, subjDirAttrASN_Length, ret, cert->heap);
  18048. /* Strip outer SEQUENCE. */
  18049. if ((ret == 0) && (GetSequence(input, &idx, &length, sz) < 0)) {
  18050. ret = ASN_PARSE_E;
  18051. }
  18052. /* Handle each inner SEQUENCE. */
  18053. while ((ret == 0) && (idx < (word32)sz)) {
  18054. ret = GetASN_Items(subjDirAttrASN, dataASN, subjDirAttrASN_Length, 1,
  18055. input, &idx, sz);
  18056. /* There may be more than one countryOfCitizenship, but save the
  18057. * first one for now. */
  18058. if ((ret == 0) &&
  18059. (dataASN[SUBJDIRATTRASN_IDX_OID].data.oid.sum == SDA_COC_OID)) {
  18060. int cuLen;
  18061. word32 setIdx = 0;
  18062. byte* setData;
  18063. word32 setLen;
  18064. GetASN_GetRef(&dataASN[SUBJDIRATTRASN_IDX_SET], &setData, &setLen);
  18065. if (GetASNHeader(setData, ASN_PRINTABLE_STRING, &setIdx, &cuLen,
  18066. setLen) < 0) {
  18067. ret = ASN_PARSE_E;
  18068. }
  18069. if ((ret == 0) && (cuLen != COUNTRY_CODE_LEN)) {
  18070. ret = ASN_PARSE_E;
  18071. }
  18072. if (ret == 0) {
  18073. XMEMCPY(cert->countryOfCitizenship, setData + setIdx, cuLen);
  18074. cert->countryOfCitizenship[COUNTRY_CODE_LEN] = 0;
  18075. }
  18076. }
  18077. }
  18078. FREE_ASNGETDATA(dataASN, cert->heap);
  18079. return ret;
  18080. #endif /* WOLFSSL_ASN_TEMPLATE */
  18081. }
  18082. #endif /* WOLFSSL_SUBJ_DIR_ATTR */
  18083. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18084. /* Decode subject infomation access extension in a certificate.
  18085. *
  18086. * X.509: RFC 5280, 4.2.2.2 - Subject Information Access.
  18087. *
  18088. * @param [in] input Buffer holding data.
  18089. * @param [in] sz Size of data in buffer.
  18090. * @param [in, out] cert Certificate object.
  18091. * @return 0 on success.
  18092. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18093. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18094. * is invalid.
  18095. * @return MEMORY_E on dynamic memory allocation failure.
  18096. */
  18097. static int DecodeSubjInfoAcc(const byte* input, int sz, DecodedCert* cert)
  18098. {
  18099. word32 idx = 0;
  18100. int length = 0;
  18101. int ret = 0;
  18102. WOLFSSL_ENTER("DecodeSubjInfoAcc");
  18103. #ifdef OPENSSL_ALL
  18104. cert->extSubjAltNameSrc = input;
  18105. cert->extSubjAltNameSz = sz;
  18106. #endif /* OPENSSL_ALL */
  18107. /* Unwrap SubjectInfoAccessSyntax, the list of AccessDescriptions */
  18108. if (GetSequence(input, &idx, &length, sz) < 0)
  18109. return ASN_PARSE_E;
  18110. if (length == 0) {
  18111. /* RFC 5280 4.2.2.2. Subject Information Access
  18112. If the subjectInformationAccess extension is present, the
  18113. sequence MUST contain at least one entry. */
  18114. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18115. return ASN_PARSE_E;
  18116. }
  18117. /* Per fpkx-x509-cert-profile-common... section 5.3.
  18118. * [The] subjectInfoAccess extension must contain at least one
  18119. * instance of the id-ad-caRepository access method containing a
  18120. * publicly accessible HTTP URI which returns as certs-only
  18121. * CMS.
  18122. */
  18123. while (idx < (word32)sz) {
  18124. word32 oid = 0;
  18125. byte b;
  18126. /* Unwrap an AccessDescription */
  18127. if (GetSequence(input, &idx, &length, sz) < 0)
  18128. return ASN_PARSE_E;
  18129. /* Get the accessMethod */
  18130. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  18131. return ASN_PARSE_E;
  18132. /* Only supporting URIs right now. */
  18133. if (GetASNTag(input, &idx, &b, sz) < 0)
  18134. return ASN_PARSE_E;
  18135. if (GetLength(input, &idx, &length, sz) < 0)
  18136. return ASN_PARSE_E;
  18137. /* Set caRepo entry */
  18138. if (b == GENERALNAME_URI && oid == AIA_CA_REPO_OID) {
  18139. cert->extSubjInfoAccCaRepoSz = length;
  18140. cert->extSubjInfoAccCaRepo = input + idx;
  18141. break;
  18142. }
  18143. idx += length;
  18144. }
  18145. if (cert->extSubjInfoAccCaRepo == NULL ||
  18146. cert->extSubjInfoAccCaRepoSz == 0) {
  18147. WOLFSSL_MSG("SubjectInfoAccess missing an URL.");
  18148. ret = ASN_PARSE_E;
  18149. }
  18150. WOLFSSL_LEAVE("DecodeSubjInfoAcc", ret);
  18151. return ret;
  18152. }
  18153. #endif /* WOLFSSL_SUBJ_INFO_ACC */
  18154. /* Macro to check if bit is set, if not sets and return success.
  18155. Otherwise returns failure */
  18156. /* Macro required here because bit-field operation */
  18157. #ifndef WOLFSSL_NO_ASN_STRICT
  18158. #define VERIFY_AND_SET_OID(bit) \
  18159. if ((bit) == 0) \
  18160. (bit) = 1; \
  18161. else \
  18162. return ASN_OBJECT_ID_E;
  18163. #else
  18164. /* With no strict defined, the verify is skipped */
  18165. #define VERIFY_AND_SET_OID(bit) bit = 1;
  18166. #endif
  18167. /* Parse extension type specific data based on OID sum.
  18168. *
  18169. * Supported extensions:
  18170. * Basic Constraints - BASIC_CA_OID
  18171. * CRL Distribution Points - CRL_DIST_OID
  18172. * Authority Information Access - AUTH_INFO_OID
  18173. * Subject Alternative Name - ALT_NAMES_OID
  18174. * Authority Key Identifier - AUTH_KEY_OID
  18175. * Subject Key Identifier - SUBJ_KEY_OID
  18176. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  18177. * Key Usage - KEY_USAGE_OID
  18178. * Extended Key Usage - EXT_KEY_USAGE_OID
  18179. * Name Constraints - NAME_CONS_OID
  18180. * Inhibit anyPolicy - INHIBIT_ANY_OID
  18181. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  18182. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  18183. * Subject Directory Attributes - SUBJ_DIR_ATTR_OID
  18184. * Subject Information Access - SUBJ_INFO_ACC_OID
  18185. * Unsupported extensions from RFC 5280:
  18186. * 4.2.1.5 - Policy mappings
  18187. * 4.2.1.7 - Issuer Alternative Name
  18188. * 4.2.1.11 - Policy Constraints
  18189. * 4.2.1.15 - Freshest CRL
  18190. *
  18191. * @param [in] input Buffer containing extension type specific data.
  18192. * @param [in] length Length of data.
  18193. * @param [in] oid OID sum for extension.
  18194. * @param [in] critical Whether extension is critical.
  18195. * @param [in, out] cert Certificate object.
  18196. * @return 0 on success.
  18197. * @return ASN_PARSE_E when BER encoding is invalid.
  18198. * @return MEMORY_E on dynamic memory allocation failure.
  18199. * @return Other negative values on error.
  18200. */
  18201. static int DecodeExtensionType(const byte* input, word32 length, word32 oid,
  18202. byte critical, DecodedCert* cert,
  18203. int *isUnknownExt)
  18204. {
  18205. int ret = 0;
  18206. word32 idx = 0;
  18207. if (isUnknownExt != NULL)
  18208. *isUnknownExt = 0;
  18209. switch (oid) {
  18210. /* Basic Constraints. */
  18211. case BASIC_CA_OID:
  18212. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  18213. cert->extBasicConstCrit = critical ? 1 : 0;
  18214. if (DecodeBasicCaConstraint(input, (int)length, cert) < 0) {
  18215. ret = ASN_PARSE_E;
  18216. }
  18217. break;
  18218. /* CRL Distribution point. */
  18219. case CRL_DIST_OID:
  18220. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  18221. cert->extCRLdistCrit = critical ? 1 : 0;
  18222. if (DecodeCrlDist(input, length, cert) < 0) {
  18223. ret = ASN_PARSE_E;
  18224. }
  18225. break;
  18226. /* Authority information access. */
  18227. case AUTH_INFO_OID:
  18228. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  18229. cert->extAuthInfoCrit = critical ? 1 : 0;
  18230. if (DecodeAuthInfo(input, length, cert) < 0) {
  18231. ret = ASN_PARSE_E;
  18232. }
  18233. break;
  18234. /* Subject alternative name. */
  18235. case ALT_NAMES_OID:
  18236. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  18237. cert->extSubjAltNameCrit = critical ? 1 : 0;
  18238. ret = DecodeAltNames(input, length, cert);
  18239. break;
  18240. /* Authority Key Identifier. */
  18241. case AUTH_KEY_OID:
  18242. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  18243. cert->extAuthKeyIdCrit = critical ? 1 : 0;
  18244. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18245. /* This check is added due to RFC 5280 section 4.2.1.1
  18246. * stating that conforming CA's must mark this extension
  18247. * as non-critical. When parsing extensions check that
  18248. * certificate was made in compliance with this. */
  18249. if (critical) {
  18250. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  18251. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18252. ret = ASN_CRIT_EXT_E;
  18253. }
  18254. #endif
  18255. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  18256. ret = ASN_PARSE_E;
  18257. }
  18258. break;
  18259. /* Subject Key Identifier. */
  18260. case SUBJ_KEY_OID:
  18261. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  18262. cert->extSubjKeyIdCrit = critical ? 1 : 0;
  18263. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  18264. /* This check is added due to RFC 5280 section 4.2.1.2
  18265. * stating that conforming CA's must mark this extension
  18266. * as non-critical. When parsing extensions check that
  18267. * certificate was made in compliance with this. */
  18268. if (critical) {
  18269. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  18270. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  18271. ret = ASN_CRIT_EXT_E;
  18272. }
  18273. #endif
  18274. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  18275. ret = ASN_PARSE_E;
  18276. }
  18277. break;
  18278. /* Certificate policies. */
  18279. case CERT_POLICY_OID:
  18280. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  18281. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  18282. #if defined(OPENSSL_EXTRA) || \
  18283. defined(OPENSSL_EXTRA_X509_SMALL)
  18284. cert->extCertPolicyCrit = critical ? 1 : 0;
  18285. #endif
  18286. #endif
  18287. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  18288. defined(WOLFSSL_QT)
  18289. if (DecodeCertPolicy(input, length, cert) < 0) {
  18290. ret = ASN_PARSE_E;
  18291. }
  18292. #else
  18293. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  18294. #endif
  18295. break;
  18296. /* Key usage. */
  18297. case KEY_USAGE_OID:
  18298. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  18299. cert->extKeyUsageCrit = critical ? 1 : 0;
  18300. if (DecodeKeyUsage(input, length, cert) < 0) {
  18301. ret = ASN_PARSE_E;
  18302. }
  18303. break;
  18304. /* Extended key usage. */
  18305. case EXT_KEY_USAGE_OID:
  18306. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  18307. cert->extExtKeyUsageCrit = critical ? 1 : 0;
  18308. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  18309. ret = ASN_PARSE_E;
  18310. }
  18311. break;
  18312. #ifndef IGNORE_NAME_CONSTRAINTS
  18313. /* Name constraints. */
  18314. case NAME_CONS_OID:
  18315. #ifndef WOLFSSL_NO_ASN_STRICT
  18316. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  18317. "The name constraints extension,
  18318. which MUST be used only in a CA certificate" */
  18319. if (!cert->isCA) {
  18320. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  18321. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  18322. ret = ASN_NAME_INVALID_E;
  18323. }
  18324. #endif
  18325. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  18326. cert->extNameConstraintCrit = critical ? 1 : 0;
  18327. if (DecodeNameConstraints(input, length, cert) < 0) {
  18328. ret = ASN_PARSE_E;
  18329. }
  18330. break;
  18331. #endif /* IGNORE_NAME_CONSTRAINTS */
  18332. /* Inhibit anyPolicy. */
  18333. case INHIBIT_ANY_OID:
  18334. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  18335. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  18336. break;
  18337. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18338. /* Netscape's certificate type. */
  18339. case NETSCAPE_CT_OID:
  18340. if (DecodeNsCertType(input, (int)length, cert) < 0)
  18341. ret = ASN_PARSE_E;
  18342. break;
  18343. #endif
  18344. #ifdef HAVE_OCSP
  18345. /* OCSP no check. */
  18346. case OCSP_NOCHECK_OID:
  18347. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  18348. ret = GetASNNull(input, &idx, length);
  18349. if (ret != 0) {
  18350. ret = ASN_PARSE_E;
  18351. }
  18352. break;
  18353. #endif
  18354. case POLICY_CONST_OID:
  18355. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  18356. cert->extPolicyConstCrit = critical ? 1 : 0;
  18357. if (DecodePolicyConstraints(&input[idx], (int)length, cert) < 0)
  18358. return ASN_PARSE_E;
  18359. break;
  18360. #ifdef WOLFSSL_SUBJ_DIR_ATTR
  18361. case SUBJ_DIR_ATTR_OID:
  18362. VERIFY_AND_SET_OID(cert->extSubjDirAttrSet);
  18363. if (DecodeSubjDirAttr(&input[idx], length, cert) < 0)
  18364. return ASN_PARSE_E;
  18365. break;
  18366. #endif
  18367. #ifdef WOLFSSL_SUBJ_INFO_ACC
  18368. case SUBJ_INFO_ACC_OID:
  18369. VERIFY_AND_SET_OID(cert->extSubjInfoAccSet);
  18370. if (DecodeSubjInfoAcc(&input[idx], length, cert) < 0)
  18371. return ASN_PARSE_E;
  18372. break;
  18373. #endif
  18374. default:
  18375. if (isUnknownExt != NULL)
  18376. *isUnknownExt = 1;
  18377. #ifndef WOLFSSL_NO_ASN_STRICT
  18378. /* While it is a failure to not support critical extensions,
  18379. * still parse the certificate ignoring the unsupported
  18380. * extension to allow caller to accept it with the verify
  18381. * callback. */
  18382. if (critical) {
  18383. WOLFSSL_ERROR_VERBOSE(ASN_CRIT_EXT_E);
  18384. ret = ASN_CRIT_EXT_E;
  18385. }
  18386. #endif
  18387. break;
  18388. }
  18389. return ret;
  18390. }
  18391. #ifdef WOLFSSL_ASN_TEMPLATE
  18392. /* ASN.1 template for extensions.
  18393. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18394. */
  18395. static const ASNItem certExtHdrASN[] = {
  18396. /* EXTTAG */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  18397. /* EXTSEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18398. };
  18399. enum {
  18400. CERTEXTHDRASN_IDX_EXTTAG = 0,
  18401. CERTEXTHDRASN_IDX_EXTSEQ
  18402. };
  18403. /* Number of itesm in ASN.1 template for extensions. */
  18404. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  18405. /* ASN.1 template for Extension.
  18406. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18407. */
  18408. static const ASNItem certExtASN[] = {
  18409. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18410. /* Extension object id */
  18411. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  18412. /* critical - when true, must be parseable. */
  18413. /* CRIT */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  18414. /* Data for extension - leave index at start of data. */
  18415. /* VAL */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  18416. };
  18417. enum {
  18418. CERTEXTASN_IDX_SEQ = 0,
  18419. CERTEXTASN_IDX_OID,
  18420. CERTEXTASN_IDX_CRIT,
  18421. CERTEXTASN_IDX_VAL
  18422. };
  18423. /* Number of items in ASN.1 template for Extension. */
  18424. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  18425. #endif
  18426. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_ASN_TEMPLATE) \
  18427. && defined(HAVE_OID_DECODING)
  18428. int wc_SetUnknownExtCallback(DecodedCert* cert,
  18429. wc_UnknownExtCallback cb) {
  18430. if (cert == NULL) {
  18431. return BAD_FUNC_ARG;
  18432. }
  18433. cert->unknownExtCallback = cb;
  18434. return 0;
  18435. }
  18436. #endif
  18437. /*
  18438. * Processing the Certificate Extensions. This does not modify the current
  18439. * index. It is works starting with the recorded extensions pointer.
  18440. */
  18441. static int DecodeCertExtensions(DecodedCert* cert)
  18442. {
  18443. #ifndef WOLFSSL_ASN_TEMPLATE
  18444. int ret = 0;
  18445. word32 idx = 0;
  18446. word32 sz = (word32)cert->extensionsSz;
  18447. const byte* input = cert->extensions;
  18448. int length;
  18449. word32 oid;
  18450. byte critical = 0;
  18451. byte criticalFail = 0;
  18452. byte tag = 0;
  18453. WOLFSSL_ENTER("DecodeCertExtensions");
  18454. if (input == NULL || sz == 0)
  18455. return BAD_FUNC_ARG;
  18456. #ifdef WOLFSSL_CERT_REQ
  18457. if (!cert->isCSR)
  18458. #endif
  18459. { /* Not included in CSR */
  18460. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  18461. return ASN_PARSE_E;
  18462. }
  18463. if (tag != ASN_EXTENSIONS) {
  18464. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  18465. return ASN_PARSE_E;
  18466. }
  18467. if (GetLength(input, &idx, &length, sz) < 0) {
  18468. WOLFSSL_MSG("\tfail: invalid length");
  18469. return ASN_PARSE_E;
  18470. }
  18471. }
  18472. if (GetSequence(input, &idx, &length, sz) < 0) {
  18473. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  18474. return ASN_PARSE_E;
  18475. }
  18476. while (idx < (word32)sz) {
  18477. word32 localIdx;
  18478. if (GetSequence(input, &idx, &length, sz) < 0) {
  18479. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  18480. return ASN_PARSE_E;
  18481. }
  18482. oid = 0;
  18483. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  18484. WOLFSSL_MSG("\tfail: OBJECT ID");
  18485. return ret;
  18486. }
  18487. /* check for critical flag */
  18488. critical = 0;
  18489. if ((idx + 1) > (word32)sz) {
  18490. WOLFSSL_MSG("\tfail: malformed buffer");
  18491. return BUFFER_E;
  18492. }
  18493. localIdx = idx;
  18494. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  18495. if (tag == ASN_BOOLEAN) {
  18496. ret = GetBoolean(input, &idx, sz);
  18497. if (ret < 0) {
  18498. WOLFSSL_MSG("\tfail: critical boolean");
  18499. return ret;
  18500. }
  18501. critical = (byte)ret;
  18502. }
  18503. }
  18504. /* process the extension based on the OID */
  18505. ret = GetOctetString(input, &idx, &length, sz);
  18506. if (ret < 0) {
  18507. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  18508. return ret;
  18509. }
  18510. ret = DecodeExtensionType(input + idx, (word32)length, oid, critical,
  18511. cert, NULL);
  18512. if (ret == ASN_CRIT_EXT_E) {
  18513. ret = 0;
  18514. criticalFail = 1;
  18515. }
  18516. if (ret < 0)
  18517. goto end;
  18518. idx += (word32)length;
  18519. }
  18520. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  18521. end:
  18522. return ret;
  18523. #else
  18524. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  18525. ASNGetData dataExtsASN[certExtHdrASN_Length];
  18526. int ret = 0;
  18527. const byte* input = cert->extensions;
  18528. int sz = cert->extensionsSz;
  18529. word32 idx = 0;
  18530. int criticalRet = 0;
  18531. int offset = 0;
  18532. WOLFSSL_ENTER("DecodeCertExtensions");
  18533. if (input == NULL || sz == 0)
  18534. ret = BAD_FUNC_ARG;
  18535. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  18536. #ifdef WOLFSSL_CERT_REQ
  18537. if (cert->isCSR) {
  18538. offset = CERTEXTHDRASN_IDX_EXTSEQ;
  18539. }
  18540. #endif
  18541. if (ret == 0) {
  18542. /* Clear dynamic data. */
  18543. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  18544. /* Parse extensions header. */
  18545. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  18546. (int)(certExtHdrASN_Length - (size_t)offset), 0,
  18547. input, &idx, (word32)sz);
  18548. }
  18549. /* Parse each extension. */
  18550. while ((ret == 0) && (idx < (word32)sz)) {
  18551. byte critical = 0;
  18552. int isUnknownExt = 0;
  18553. /* Clear dynamic data. */
  18554. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  18555. /* Ensure OID is an extention type. */
  18556. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  18557. /* Set criticality variable. */
  18558. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  18559. /* Parse extension wrapper. */
  18560. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  18561. &idx, (word32)sz);
  18562. if (ret == 0) {
  18563. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  18564. word32 length = dataASN[CERTEXTASN_IDX_VAL].length;
  18565. /* Decode the extension by type. */
  18566. ret = DecodeExtensionType(input + idx, length, oid, critical, cert,
  18567. &isUnknownExt);
  18568. #if defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_DECODING)
  18569. if (isUnknownExt && (cert->unknownExtCallback != NULL)) {
  18570. word16 decOid[MAX_OID_SZ];
  18571. word32 decOidSz = sizeof(decOid);
  18572. ret = DecodeObjectId(
  18573. dataASN[CERTEXTASN_IDX_OID].data.oid.data,
  18574. dataASN[CERTEXTASN_IDX_OID].data.oid.length,
  18575. decOid, &decOidSz);
  18576. if (ret != 0) {
  18577. /* Should never get here as the extension was successfully
  18578. * decoded earlier. Something might be corrupted. */
  18579. WOLFSSL_MSG("DecodeObjectId() failed. Corruption?");
  18580. WOLFSSL_ERROR(ret);
  18581. }
  18582. ret = cert->unknownExtCallback(decOid, decOidSz, critical,
  18583. dataASN[CERTEXTASN_IDX_VAL].data.buffer.data,
  18584. dataASN[CERTEXTASN_IDX_VAL].length);
  18585. }
  18586. #endif
  18587. (void)isUnknownExt;
  18588. /* Move index on to next extension. */
  18589. idx += length;
  18590. }
  18591. /* Don't fail criticality until all other extensions have been checked.
  18592. */
  18593. if (ret == ASN_CRIT_EXT_E) {
  18594. criticalRet = ASN_CRIT_EXT_E;
  18595. ret = 0;
  18596. }
  18597. }
  18598. if (ret == 0) {
  18599. /* Use criticality return. */
  18600. ret = criticalRet;
  18601. }
  18602. FREE_ASNGETDATA(dataASN, cert->heap);
  18603. return ret;
  18604. #endif
  18605. }
  18606. #ifdef WOLFSSL_ASN_TEMPLATE
  18607. /* ASN template for an X509 certificate.
  18608. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  18609. */
  18610. static const ASNItem x509CertASN[] = {
  18611. /* Certificate ::= SEQUENCE */
  18612. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18613. /* tbsCertificate TBSCertificate */
  18614. /* TBSCertificate ::= SEQUENCE */
  18615. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18616. /* version [0] EXPLICT Version DEFAULT v1 */
  18617. /* TBS_VER */ { 2, ASN_CONTEXT_SPECIFIC | ASN_X509_CERT_VERSION, 1, 1, 1 },
  18618. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  18619. /* TBS_VER_INT */ { 3, ASN_INTEGER, 0, 0, 0 },
  18620. /* serialNumber CertificateSerialNumber */
  18621. /* CetificateSerialNumber ::= INTEGER */
  18622. /* TBS_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  18623. /* signature AlgorithmIdentifier */
  18624. /* AlgorithmIdentifier ::= SEQUENCE */
  18625. /* TBS_ALGOID_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18626. /* Algorithm OBJECT IDENTIFIER */
  18627. /* TBS_ALGOID_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  18628. /* parameters ANY defined by algorithm OPTIONAL */
  18629. /* TBS_ALGOID_PARAMS_NULL */ { 3, ASN_TAG_NULL, 0, 0, 2 },
  18630. #ifdef WC_RSA_PSS
  18631. /* TBS_ALGOID_PARAMS */ { 3, ASN_SEQUENCE, 1, 0, 2 },
  18632. #endif
  18633. /* issuer Name */
  18634. /* TBS_ISSUER_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18635. /* validity Validity */
  18636. /* Validity ::= SEQUENCE */
  18637. /* TBS_VALIDITY_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18638. /* notBefore Time */
  18639. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18640. /* TBS_VALIDITY_NOTB_UTC */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  18641. /* TBS_VALIDITY_NOTB_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  18642. /* notAfter Time */
  18643. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  18644. /* TBS_VALIDITY_NOTA_UTC */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  18645. /* TBS_VALIDITY_NOTA_GT */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  18646. /* subject Name */
  18647. /* TBS_SUBJECT_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  18648. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  18649. /* TBS_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  18650. /* algorithm AlgorithmIdentifier */
  18651. /* AlgorithmIdentifier ::= SEQUENCE */
  18652. /* TBS_SPUBKEYINFO_ALGO_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  18653. /* Algorithm OBJECT IDENTIFIER */
  18654. /* TBS_SPUBKEYINFO_ALGO_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  18655. /* parameters ANY defined by algorithm OPTIONAL */
  18656. /* TBS_SPUBKEYINFO_ALGO_NULL */ { 4, ASN_TAG_NULL, 0, 0, 2 },
  18657. /* TBS_SPUBKEYINFO_ALGO_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 2 },
  18658. #ifdef WC_RSA_PSS
  18659. /* TBS_SPUBKEYINFO_ALGO_P_SEQ */ { 4, ASN_SEQUENCE, 1, 0, 2 },
  18660. #endif
  18661. /* subjectPublicKey BIT STRING */
  18662. /* TBS_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  18663. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  18664. /* TBS_ISSUERUID */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  18665. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  18666. /* TBS_SUBJECTUID */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  18667. /* extensions Extensions OPTIONAL */
  18668. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 1 },
  18669. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  18670. /* signatureAlgorithm AlgorithmIdentifier */
  18671. /* AlgorithmIdentifier ::= SEQUENCE */
  18672. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18673. /* Algorithm OBJECT IDENTIFIER */
  18674. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18675. /* parameters ANY defined by algorithm OPTIONAL */
  18676. /* SIGALGO_PARAMS_NULL */ { 2, ASN_TAG_NULL, 0, 0, 2 },
  18677. #ifdef WC_RSA_PSS
  18678. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18679. #endif
  18680. /* signature BIT STRING */
  18681. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18682. };
  18683. enum {
  18684. X509CERTASN_IDX_SEQ = 0,
  18685. X509CERTASN_IDX_TBS_SEQ,
  18686. X509CERTASN_IDX_TBS_VER,
  18687. X509CERTASN_IDX_TBS_VER_INT,
  18688. X509CERTASN_IDX_TBS_SERIAL,
  18689. X509CERTASN_IDX_TBS_ALGOID_SEQ,
  18690. X509CERTASN_IDX_TBS_ALGOID_OID,
  18691. X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL,
  18692. #ifdef WC_RSA_PSS
  18693. X509CERTASN_IDX_TBS_ALGOID_PARAMS,
  18694. #endif
  18695. X509CERTASN_IDX_TBS_ISSUER_SEQ,
  18696. X509CERTASN_IDX_TBS_VALIDITY_SEQ,
  18697. X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC,
  18698. X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT,
  18699. X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC,
  18700. X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT,
  18701. X509CERTASN_IDX_TBS_SUBJECT_SEQ,
  18702. X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ,
  18703. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  18704. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID,
  18705. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_NULL,
  18706. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID,
  18707. #ifdef WC_RSA_PSS
  18708. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_P_SEQ,
  18709. #endif
  18710. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY,
  18711. X509CERTASN_IDX_TBS_ISSUERUID,
  18712. X509CERTASN_IDX_TBS_SUBJECTUID,
  18713. X509CERTASN_IDX_TBS_EXT,
  18714. X509CERTASN_IDX_TBS_EXT_SEQ,
  18715. X509CERTASN_IDX_SIGALGO_SEQ,
  18716. X509CERTASN_IDX_SIGALGO_OID,
  18717. X509CERTASN_IDX_SIGALGO_PARAMS_NULL,
  18718. #ifdef WC_RSA_PSS
  18719. X509CERTASN_IDX_SIGALGO_PARAMS,
  18720. #endif
  18721. X509CERTASN_IDX_SIGNATURE,
  18722. WOLF_ENUM_DUMMY_LAST_ELEMENT(X509CERTASN_IDX)
  18723. };
  18724. /* Number of items in ASN template for an X509 certificate. */
  18725. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  18726. /* Check the data data.
  18727. *
  18728. * @param [in] dataASN ASN template dynamic data item.
  18729. * @param [in] dataType BEFORE or AFTER date.
  18730. * @return 0 on success.
  18731. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  18732. * @return ASN_DATE_SZ_E when time data is not supported.
  18733. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18734. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18735. */
  18736. static int CheckDate(ASNGetData *dataASN, int dateType)
  18737. {
  18738. int ret = 0;
  18739. /* Check BER tag is valid. */
  18740. if ((dataASN->tag != ASN_UTC_TIME) &&
  18741. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  18742. ret = ASN_TIME_E;
  18743. }
  18744. /* Check date length is valid. */
  18745. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  18746. (dataASN->length < MIN_DATE_SIZE))) {
  18747. ret = ASN_DATE_SZ_E;
  18748. }
  18749. #ifndef NO_ASN_TIME_CHECK
  18750. /* Check date is a valid string and BEFORE or AFTER now. */
  18751. if ((ret == 0) &&
  18752. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  18753. if (dateType == BEFORE) {
  18754. ret = ASN_BEFORE_DATE_E;
  18755. }
  18756. else {
  18757. ret = ASN_AFTER_DATE_E;
  18758. }
  18759. }
  18760. #endif
  18761. (void)dateType;
  18762. return ret;
  18763. }
  18764. /* Decode a certificate. Internal/non-public API.
  18765. *
  18766. * @param [in] cert Certificate object.
  18767. * @param [in] verify Whether to verify dates before and after now.
  18768. * @param [out] criticalExt Critical extension return code.
  18769. * @param [out] badDateRet Bad date return code.
  18770. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  18771. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  18772. * @return 0 on success.
  18773. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  18774. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  18775. * @return ASN_DATE_SZ_E when time data is not supported.
  18776. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  18777. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  18778. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  18779. * is invalid.
  18780. * @return BUFFER_E when data in buffer is too small.
  18781. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  18782. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  18783. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  18784. * non-zero length.
  18785. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  18786. */
  18787. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  18788. int* badDateRet, int stopAtPubKey,
  18789. int stopAfterPubKey)
  18790. {
  18791. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  18792. int ret = 0;
  18793. int badDate = 0;
  18794. byte version;
  18795. word32 idx;
  18796. word32 serialSz;
  18797. const unsigned char* issuer = NULL;
  18798. word32 issuerSz = 0;
  18799. const unsigned char* subject = NULL;
  18800. word32 subjectSz = 0;
  18801. word32 pubKeyOffset = 0;
  18802. word32 pubKeyEnd = 0;
  18803. int done = 0;
  18804. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  18805. if (ret == 0) {
  18806. version = 0;
  18807. serialSz = EXTERNAL_SERIAL_SIZE;
  18808. /* Get the version and put the serial number into the buffer. */
  18809. GetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT], &version);
  18810. GetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  18811. &serialSz);
  18812. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  18813. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  18814. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  18815. oidKeyType);
  18816. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  18817. oidCurveType);
  18818. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  18819. /* Parse the X509 certificate. */
  18820. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  18821. cert->source, &cert->srcIdx, cert->maxIdx);
  18822. #ifdef WOLFSSL_CLANG_TIDY
  18823. /* work around clang-tidy false positive re cert->source. */
  18824. if ((ret == 0) && (cert->source == NULL)) {
  18825. ret = ASN_PARSE_E;
  18826. }
  18827. #endif
  18828. }
  18829. /* Check version is valid/supported - can't be negative. */
  18830. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  18831. WOLFSSL_MSG("Unexpected certificate version");
  18832. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18833. ret = ASN_PARSE_E;
  18834. }
  18835. if (ret == 0) {
  18836. int i;
  18837. pubKeyOffset = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset;
  18838. /* Set fields extracted from data. */
  18839. cert->version = version;
  18840. cert->serialSz = (int)serialSz;
  18841. cert->signatureOID = dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum;
  18842. cert->keyOID = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID].data.oid.sum;
  18843. cert->certBegin = dataASN[X509CERTASN_IDX_TBS_SEQ].offset;
  18844. /* No bad date error - don't always care. */
  18845. badDate = 0;
  18846. /* Find the item with the BEFORE date and check it. */
  18847. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].tag != 0)
  18848. ? X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC
  18849. : X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT;
  18850. if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
  18851. badDate = ASN_BEFORE_DATE_E;
  18852. }
  18853. /* Store reference to BEFOREdate. */
  18854. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  18855. cert->beforeDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18856. /* Find the item with the AFTER date and check it. */
  18857. i = (dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].tag != 0)
  18858. ? X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC
  18859. : X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT;
  18860. if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
  18861. badDate = ASN_AFTER_DATE_E;
  18862. }
  18863. /* Store reference to AFTER date. */
  18864. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  18865. cert->afterDateLen = (int)GetASNItem_Length(dataASN[i], cert->source);
  18866. /* Get the issuer name. */
  18867. issuer = cert->source + dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18868. issuerSz = dataASN[X509CERTASN_IDX_TBS_VALIDITY_SEQ].offset -
  18869. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].offset;
  18870. /* Get the subject name. */
  18871. subject = cert->source +
  18872. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18873. subjectSz = dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ].offset -
  18874. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].offset;
  18875. }
  18876. if ((ret == 0) && stopAtPubKey) {
  18877. /* Return any bad date error through badDateRet and return offset of
  18878. * subjectPublicKeyInfo.
  18879. */
  18880. if (badDateRet != NULL) {
  18881. *badDateRet = badDate;
  18882. }
  18883. done = 1;
  18884. }
  18885. if ((ret == 0) && (!done)) {
  18886. /* Store the signature information. */
  18887. cert->sigIndex = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18888. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE],
  18889. &cert->signature, &cert->sigLength);
  18890. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  18891. if (dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum
  18892. != cert->signatureOID) {
  18893. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  18894. ret = ASN_SIG_OID_E;
  18895. }
  18896. /* Parameters not allowed after ECDSA or EdDSA algorithm OID. */
  18897. else if (IsSigAlgoECC(cert->signatureOID)) {
  18898. if ((dataASN[X509CERTASN_IDX_SIGALGO_PARAMS_NULL].tag != 0)
  18899. #ifdef WC_RSA_PSS
  18900. || (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0)
  18901. #endif
  18902. ) {
  18903. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18904. ret = ASN_PARSE_E;
  18905. }
  18906. }
  18907. #ifdef WC_RSA_PSS
  18908. /* Check parameters starting with a SEQUENCE. */
  18909. else if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  18910. word32 oid = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  18911. word32 sigAlgParamsSz = 0;
  18912. /* Parameters only with RSA PSS. */
  18913. if (oid != CTC_RSASSAPSS) {
  18914. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18915. ret = ASN_PARSE_E;
  18916. }
  18917. if (ret == 0) {
  18918. const byte* tbsParams;
  18919. word32 tbsParamsSz;
  18920. const byte* sigAlgParams;
  18921. /* Check RSA PSS parameters are the same. */
  18922. tbsParams =
  18923. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18924. cert->source);
  18925. tbsParamsSz =
  18926. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  18927. cert->source);
  18928. sigAlgParams =
  18929. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18930. cert->source);
  18931. sigAlgParamsSz =
  18932. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  18933. cert->source);
  18934. if ((tbsParamsSz != sigAlgParamsSz) ||
  18935. (XMEMCMP(tbsParams, sigAlgParams, tbsParamsSz) != 0)) {
  18936. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  18937. ret = ASN_PARSE_E;
  18938. }
  18939. }
  18940. if (ret == 0) {
  18941. /* Store parameters for use in signature verification. */
  18942. cert->sigParamsIndex =
  18943. dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].offset;
  18944. cert->sigParamsLength = sigAlgParamsSz;
  18945. }
  18946. }
  18947. #endif
  18948. }
  18949. if ((ret == 0) && (!done)) {
  18950. pubKeyEnd = dataASN[X509CERTASN_IDX_TBS_ISSUERUID].offset;
  18951. if (stopAfterPubKey) {
  18952. /* Return any bad date error through badDateRed and return offset
  18953. * after subjectPublicKeyInfo.
  18954. */
  18955. if (badDateRet != NULL) {
  18956. *badDateRet = badDate;
  18957. }
  18958. done = 1;
  18959. }
  18960. }
  18961. if ((ret == 0) && (!done) &&
  18962. (dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data != NULL)) {
  18963. #ifndef ALLOW_V1_EXTENSIONS
  18964. /* Certificate extensions were only defined in version 2. */
  18965. if (cert->version < 2) {
  18966. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  18967. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  18968. ret = ASN_VERSION_E;
  18969. }
  18970. #endif
  18971. if (ret == 0) {
  18972. /* Save references to extension data. */
  18973. cert->extensions = GetASNItem_Addr(
  18974. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18975. cert->extensionsSz = (int)GetASNItem_Length(
  18976. dataASN[X509CERTASN_IDX_TBS_EXT], cert->source);
  18977. cert->extensionsIdx = dataASN[X509CERTASN_IDX_TBS_EXT].offset;
  18978. /* Advance past extensions. */
  18979. cert->srcIdx = dataASN[X509CERTASN_IDX_SIGALGO_SEQ].offset;
  18980. }
  18981. }
  18982. /* Dispose of memory before allocating for extension decoding. */
  18983. FREE_ASNGETDATA(dataASN, cert->heap);
  18984. if ((ret == 0) && (issuer != NULL)) {
  18985. idx = 0;
  18986. /* Put issuer into cert and calculate hash. */
  18987. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER, issuer,
  18988. &idx, issuerSz);
  18989. }
  18990. if ((ret == 0) && (subject != NULL)) {
  18991. idx = 0;
  18992. /* Put subject into cert and calculate hash. */
  18993. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  18994. subject, &idx, subjectSz);
  18995. }
  18996. if (ret == 0) {
  18997. /* Determine if self signed by comparing issuer and subject hashes. */
  18998. #ifdef WOLFSSL_CERT_REQ
  18999. if (cert->isCSR) {
  19000. cert->selfSigned = 1;
  19001. }
  19002. else
  19003. #endif
  19004. {
  19005. cert->selfSigned = (XMEMCMP(cert->issuerHash, cert->subjectHash,
  19006. KEYID_SIZE) == 0);
  19007. }
  19008. if (stopAtPubKey) {
  19009. ret = (int)pubKeyOffset;
  19010. }
  19011. }
  19012. if ((ret == 0) && (!stopAtPubKey)) {
  19013. /* Parse the public key. */
  19014. idx = pubKeyOffset;
  19015. ret = GetCertKey(cert, cert->source, &idx, pubKeyEnd);
  19016. }
  19017. if ((ret == 0) && (!stopAtPubKey) && (!stopAfterPubKey) &&
  19018. (cert->extensions != NULL)) {
  19019. /* Decode the extension data starting at [3]. */
  19020. ret = DecodeCertExtensions(cert);
  19021. if (criticalExt != NULL) {
  19022. if (ret == ASN_CRIT_EXT_E) {
  19023. /* Return critical extension not recognized. */
  19024. *criticalExt = ret;
  19025. ret = 0;
  19026. }
  19027. else {
  19028. /* No critical extension error. */
  19029. *criticalExt = 0;
  19030. }
  19031. }
  19032. }
  19033. if ((ret == 0) && (!done) && (badDate != 0)) {
  19034. /* Parsed whole certificate fine but return any date errors. */
  19035. ret = badDate;
  19036. }
  19037. return ret;
  19038. }
  19039. /* Decode BER/DER data into certificate object.
  19040. *
  19041. * BER/DER data information held in source, srcIdx and maxIdx fields of
  19042. * certificate object.
  19043. *
  19044. * @param [in] cert Decoded certificate object.
  19045. * @param [in] verify Whether to find CA and verify certificate.
  19046. * @param [in] criticalExt Any error for critical extensions not recognized.
  19047. * @return 0 on success.
  19048. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19049. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  19050. * @return ASN_DATE_SZ_E when time data is not supported.
  19051. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  19052. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  19053. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19054. * is invalid.
  19055. * @return BUFFER_E when data in buffer is too small.
  19056. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19057. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  19058. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19059. * non-zero length.
  19060. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19061. */
  19062. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  19063. {
  19064. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  19065. }
  19066. #ifdef WOLFSSL_CERT_REQ
  19067. /* ASN.1 template for certificate request Attribute.
  19068. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  19069. */
  19070. static const ASNItem reqAttrASN[] = {
  19071. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19072. /* type */
  19073. /* TYPE */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  19074. /* values */
  19075. /* VALS */ { 1, ASN_SET, 1, 0, 0 },
  19076. };
  19077. enum {
  19078. REQATTRASN_IDX_SEQ = 0,
  19079. REQATTRASN_IDX_TYPE,
  19080. REQATTRASN_IDX_VALS
  19081. };
  19082. /* Number of items in ASN.1 template for certificate request Attribute. */
  19083. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  19084. /* ASN.1 template for a string choice. */
  19085. static const ASNItem strAttrASN[] = {
  19086. { 0, 0, 0, 0, 0 },
  19087. };
  19088. enum {
  19089. STRATTRASN_IDX_STR = 0
  19090. };
  19091. /* Number of items in ASN.1 template for a string choice. */
  19092. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  19093. /* ASN.1 choices for types for a string in an attribute. */
  19094. static const byte strAttrChoice[] = {
  19095. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  19096. };
  19097. /* Decode a certificate request attribute's value.
  19098. *
  19099. * @param [in] cert Certificate request object.
  19100. * @param [out] criticalExt Critical extension return code.
  19101. * @param [in] oid OID decribing which attribute was found.
  19102. * @param [in] aIdx Index into certificate source to start parsing.
  19103. * @param [in] input Attribute value data.
  19104. * @param [in] maxIdx Maximum index to parse to.
  19105. * @return 0 on success.
  19106. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19107. * is invalid.
  19108. */
  19109. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  19110. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  19111. {
  19112. int ret = 0;
  19113. word32 idx = 0;
  19114. ASNGetData strDataASN[strAttrASN_Length];
  19115. switch (oid) {
  19116. case PKCS9_CONTENT_TYPE_OID:
  19117. /* Clear dynamic data and specify choices acceptable. */
  19118. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19119. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19120. /* Parse a string. */
  19121. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19122. 1, input, &idx, maxIdx);
  19123. if (ret == 0) {
  19124. /* Store references to password data. */
  19125. cert->contentType =
  19126. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19127. cert->contentTypeLen =
  19128. (int)strDataASN[STRATTRASN_IDX_STR].data.ref.length;
  19129. }
  19130. break;
  19131. /* A password by which the entity may request certificate revocation.
  19132. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  19133. */
  19134. case CHALLENGE_PASSWORD_OID:
  19135. /* Clear dynamic data and specify choices acceptable. */
  19136. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19137. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19138. /* Parse a string. */
  19139. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19140. 1, input, &idx, maxIdx);
  19141. if (ret == 0) {
  19142. /* Store references to password data. */
  19143. cert->cPwd =
  19144. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19145. cert->cPwdLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19146. data.ref.length;
  19147. }
  19148. break;
  19149. /* Requested serial number to issue with.
  19150. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  19151. * (References: ISO/IEC 9594-6:1997)
  19152. */
  19153. case SERIAL_NUMBER_OID:
  19154. /* Clear dynamic data and specify choices acceptable. */
  19155. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  19156. GetASN_Choice(&strDataASN[STRATTRASN_IDX_STR], strAttrChoice);
  19157. /* Parse a string. */
  19158. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  19159. 1, input, &idx, maxIdx);
  19160. if (ret == 0) {
  19161. /* Store references to serial number. */
  19162. cert->sNum =
  19163. (char*)strDataASN[STRATTRASN_IDX_STR].data.ref.data;
  19164. cert->sNumLen = (int)strDataASN[STRATTRASN_IDX_STR].
  19165. data.ref.length;
  19166. /* Store serial number if small enough. */
  19167. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  19168. XMEMCPY(cert->serial, cert->sNum, (size_t)cert->sNumLen);
  19169. cert->serialSz = cert->sNumLen;
  19170. }
  19171. }
  19172. break;
  19173. /* Certificate extensions to be included in generated certificate.
  19174. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  19175. */
  19176. case EXTENSION_REQUEST_OID:
  19177. /* Store references to all extensions. */
  19178. cert->extensions = input;
  19179. cert->extensionsSz = (int)maxIdx;
  19180. cert->extensionsIdx = aIdx;
  19181. /* Decode and validate extensions. */
  19182. ret = DecodeCertExtensions(cert);
  19183. if (ret == ASN_CRIT_EXT_E) {
  19184. /* Return critical extension not recognized. */
  19185. *criticalExt = ret;
  19186. ret = 0;
  19187. }
  19188. else {
  19189. /* No critical extension error. */
  19190. *criticalExt = 0;
  19191. }
  19192. break;
  19193. default:
  19194. ret = ASN_PARSE_E;
  19195. break;
  19196. }
  19197. return ret;
  19198. }
  19199. /* Decode attributes of a BER encoded certificate request.
  19200. *
  19201. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19202. *
  19203. * Outer sequence has been removed.
  19204. *
  19205. * @param [in] cert Certificate request object.
  19206. * @param [out] criticalExt Critical extension return code.
  19207. * @param [in] idx Index into certificate source to start parsing.
  19208. * @param [in] maxIdx Maximum index to parse to.
  19209. * @return 0 on success.
  19210. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19211. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19212. * is invalid.
  19213. * @return BUFFER_E when data in buffer is too small.
  19214. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19215. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19216. * non-zero length.
  19217. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19218. */
  19219. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  19220. word32 idx, word32 maxIdx)
  19221. {
  19222. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  19223. int ret = 0;
  19224. WOLFSSL_ENTER("DecodeCertReqAttributes");
  19225. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  19226. /* Parse each attribute until all data used up. */
  19227. while ((ret == 0) && (idx < maxIdx)) {
  19228. /* Clear dynamic data. */
  19229. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  19230. GetASN_OID(&dataASN[REQATTRASN_IDX_TYPE], oidIgnoreType);
  19231. /* Parse an attribute. */
  19232. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  19233. cert->source, &idx, maxIdx);
  19234. /* idx is now at end of attribute data. */
  19235. if (ret == 0) {
  19236. ret = DecodeCertReqAttrValue(cert, criticalExt,
  19237. dataASN[REQATTRASN_IDX_TYPE].data.oid.sum,
  19238. GetASNItem_DataIdx(dataASN[REQATTRASN_IDX_VALS], cert->source),
  19239. dataASN[REQATTRASN_IDX_VALS].data.ref.data,
  19240. dataASN[REQATTRASN_IDX_VALS].data.ref.length);
  19241. }
  19242. }
  19243. FREE_ASNGETDATA(dataASN, cert->heap);
  19244. return ret;
  19245. }
  19246. /* ASN.1 template for a certificate request.
  19247. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  19248. * PKCS#10: RFC 2986, 4.2 - CertificationRequest
  19249. */
  19250. static const ASNItem certReqASN[] = {
  19251. /* CertificationRequest */
  19252. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19253. /* CertificationRequestInfo */
  19254. /* INFO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19255. /* version INTEGER { v1(0), v2(1), v3(2) */
  19256. /* INFO_VER */ { 2, ASN_INTEGER, 0, 0, 0 },
  19257. /* subject Name */
  19258. /* INFO_SUBJ_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  19259. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  19260. /* INFO_SPUBKEYINFO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  19261. /* algorithm AlgorithmIdentifier */
  19262. /* INFO_SPUBKEYINFO_ALGOID_SEQ */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  19263. /* Algorithm OBJECT IDENTIFIER */
  19264. /* INFO_SPUBKEYINFO_ALGOID_OID */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  19265. /* parameters ANY defined by algorithm OPTIONAL */
  19266. /* INFO_SPUBKEYINFO_ALGOID_NULL */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  19267. /* INFO_SPUBKEYINFO_ALGOID_CURVEID */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  19268. /* INFO_SPUBKEYINFO_ALGOID_PARAMS */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  19269. /* subjectPublicKey BIT STRING */
  19270. /* INFO_SPUBKEYINFO_PUBKEY */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  19271. /* attributes [0] Attributes */
  19272. /* INFO_ATTRS */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  19273. /* signatureAlgorithm AlgorithmIdentifier */
  19274. /* INFO_SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  19275. /* Algorithm OBJECT IDENTIFIER */
  19276. /* INFO_SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  19277. /* parameters ANY defined by algorithm OPTIONAL */
  19278. /* INFO_SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  19279. /* signature BIT STRING */
  19280. /* INFO_SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  19281. };
  19282. enum {
  19283. CERTREQASN_IDX_SEQ = 0,
  19284. CERTREQASN_IDX_INFO_SEQ,
  19285. CERTREQASN_IDX_INFO_VER,
  19286. CERTREQASN_IDX_INFO_SUBJ_SEQ,
  19287. CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ,
  19288. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_SEQ,
  19289. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID,
  19290. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_NULL,
  19291. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID,
  19292. CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_PARAMS,
  19293. CERTREQASN_IDX_INFO_SPUBKEYINFO_PUBKEY,
  19294. CERTREQASN_IDX_INFO_ATTRS,
  19295. CERTREQASN_IDX_INFO_SIGALGO_SEQ,
  19296. CERTREQASN_IDX_INFO_SIGALGO_OID,
  19297. CERTREQASN_IDX_INFO_SIGALGO_NULL,
  19298. CERTREQASN_IDX_INFO_SIGNATURE
  19299. };
  19300. /* Number of items in ASN.1 template for a certificate request. */
  19301. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  19302. /* Parse BER encoded certificate request.
  19303. *
  19304. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  19305. *
  19306. * @param [in] cert Certificate request object.
  19307. * @param [out] criticalExt Critical extension return code.
  19308. * @return 0 on success.
  19309. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  19310. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19311. * is invalid.
  19312. * @return BUFFER_E when data in buffer is too small.
  19313. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  19314. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  19315. * non-zero length.
  19316. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  19317. * @return MEMORY_E on dynamic memory allocation failure.
  19318. */
  19319. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  19320. {
  19321. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  19322. int ret = 0;
  19323. byte version;
  19324. word32 idx;
  19325. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  19326. if (ret == 0) {
  19327. /* Default version is 0. */
  19328. version = 0;
  19329. /* Set version var and OID types to expect. */
  19330. GetASN_Int8Bit(&dataASN[CERTREQASN_IDX_INFO_VER], &version);
  19331. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19332. oidKeyType);
  19333. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19334. oidCurveType);
  19335. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19336. /* Parse a certificate request. */
  19337. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  19338. cert->source, &cert->srcIdx, cert->maxIdx);
  19339. }
  19340. /* Check version is valid/supported - can't be negative. */
  19341. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  19342. WOLFSSL_MSG("Unexpected certificate request version");
  19343. ret = ASN_PARSE_E;
  19344. }
  19345. if (ret == 0) {
  19346. /* Set fields of certificate request. */
  19347. cert->version = version;
  19348. cert->signatureOID =
  19349. dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  19350. cert->keyOID =
  19351. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID].data.oid.sum;
  19352. cert->certBegin = dataASN[CERTREQASN_IDX_INFO_SEQ].offset;
  19353. /* Parse the subject name. */
  19354. idx = dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ].offset;
  19355. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  19356. cert->source, &idx,
  19357. dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset);
  19358. }
  19359. if (ret == 0) {
  19360. /* Parse the certificate request Attributes. */
  19361. ret = DecodeCertReqAttributes(cert, criticalExt,
  19362. GetASNItem_DataIdx(dataASN[CERTREQASN_IDX_INFO_ATTRS],
  19363. cert->source),
  19364. dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset);
  19365. }
  19366. if (ret == 0) {
  19367. /* Parse the certificate request's key. */
  19368. idx = dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_SEQ].offset;
  19369. ret = GetCertKey(cert, cert->source, &idx,
  19370. dataASN[CERTREQASN_IDX_INFO_ATTRS].offset);
  19371. }
  19372. if (ret == 0) {
  19373. /* Store references to signature. */
  19374. cert->sigIndex = dataASN[CERTREQASN_IDX_INFO_SIGALGO_SEQ].offset;
  19375. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE],
  19376. &cert->signature, &cert->sigLength);
  19377. }
  19378. FREE_ASNGETDATA(dataASN, cert->heap);
  19379. return ret;
  19380. }
  19381. #endif /* WOLFSSL_CERT_REQ */
  19382. #endif
  19383. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19384. {
  19385. int ret;
  19386. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19387. defined(WOLFSSL_DYN_CERT)
  19388. char* ptr;
  19389. #endif
  19390. ret = ParseCertRelative(cert, type, verify, cm);
  19391. if (ret < 0)
  19392. return ret;
  19393. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19394. defined(WOLFSSL_DYN_CERT)
  19395. /* cert->subjectCN not stored as copy of WOLFSSL_NO_MALLOC defind */
  19396. if (cert->subjectCNLen > 0) {
  19397. ptr = (char*)XMALLOC((size_t)cert->subjectCNLen + 1, cert->heap,
  19398. DYNAMIC_TYPE_SUBJECT_CN);
  19399. if (ptr == NULL)
  19400. return MEMORY_E;
  19401. XMEMCPY(ptr, cert->subjectCN, (size_t)cert->subjectCNLen);
  19402. ptr[cert->subjectCNLen] = '\0';
  19403. cert->subjectCN = ptr;
  19404. cert->subjectCNStored = 1;
  19405. }
  19406. #endif
  19407. #if (!defined(WOLFSSL_NO_MALLOC) && !defined(NO_WOLFSSL_CM_VERIFY)) || \
  19408. defined(WOLFSSL_DYN_CERT)
  19409. /* cert->publicKey not stored as copy if WOLFSSL_NO_MALLOC defined */
  19410. if ((cert->keyOID == RSAk
  19411. #ifdef WC_RSA_PSS
  19412. || cert->keyOID == RSAPSSk
  19413. #endif
  19414. ) && cert->publicKey != NULL && cert->pubKeySize > 0) {
  19415. ptr = (char*)XMALLOC(cert->pubKeySize, cert->heap,
  19416. DYNAMIC_TYPE_PUBLIC_KEY);
  19417. if (ptr == NULL)
  19418. return MEMORY_E;
  19419. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  19420. cert->publicKey = (byte *)ptr;
  19421. cert->pubKeyStored = 1;
  19422. }
  19423. #endif
  19424. return ret;
  19425. }
  19426. int wc_ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  19427. {
  19428. return ParseCert(cert, type, verify, cm);
  19429. }
  19430. #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
  19431. !defined(GetCA)
  19432. /* from SSL proper, for locking can't do find here anymore.
  19433. * brought in from internal.h if built with compat layer.
  19434. * if defined(GetCA), it's a predefined macro and these prototypes
  19435. * would conflict.
  19436. */
  19437. #ifdef __cplusplus
  19438. extern "C" {
  19439. #endif
  19440. Signer* GetCA(void* signers, byte* hash);
  19441. #ifndef NO_SKID
  19442. Signer* GetCAByName(void* signers, byte* hash);
  19443. #endif
  19444. #ifdef __cplusplus
  19445. }
  19446. #endif
  19447. #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
  19448. #if defined(WOLFCRYPT_ONLY)
  19449. /* dummy functions, not using wolfSSL so don't need actual ones */
  19450. Signer* GetCA(void* signers, byte* hash)
  19451. {
  19452. (void)hash;
  19453. return (Signer*)signers;
  19454. }
  19455. #ifndef NO_SKID
  19456. Signer* GetCAByName(void* signers, byte* hash)
  19457. {
  19458. (void)hash;
  19459. return (Signer*)signers;
  19460. }
  19461. #endif /* NO_SKID */
  19462. #endif /* WOLFCRYPT_ONLY */
  19463. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  19464. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  19465. {
  19466. Signer* ca = NULL;
  19467. if (cert->extSubjKeyIdSet)
  19468. ca = GetCA(cm, cert->extSubjKeyId);
  19469. if (ca == NULL)
  19470. ca = GetCAByName(cm, cert->subjectHash);
  19471. if (ca) {
  19472. if ((ca->pubKeySize == cert->pubKeySize) &&
  19473. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  19474. return ca;
  19475. }
  19476. }
  19477. return NULL;
  19478. }
  19479. #endif
  19480. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  19481. #ifdef WOLFSSL_ASN_TEMPLATE
  19482. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  19483. *
  19484. * @param [in] input Input data.
  19485. * @param [in] maxIdx Maximum index for data.
  19486. * @param [in] sigOID Signature OID for determining hash algorithm.
  19487. * @param [out] hash Hash of AKI.
  19488. * @param [out] set Whether the hash buffer was set.
  19489. * @param [in] heap Dynamic memory allocation hint.
  19490. * @return 0 on success.
  19491. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  19492. * is invalid.
  19493. * @return MEMORY_E on dynamic memory allocation failure.
  19494. */
  19495. static int GetAKIHash(const byte* input, word32 maxIdx, int sigOID,
  19496. byte* hash, int* set, void* heap)
  19497. {
  19498. /* AKI and Certificate Extenion ASN.1 templates are the same length. */
  19499. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  19500. int ret = 0;
  19501. word32 idx = 0;
  19502. word32 extEndIdx;
  19503. byte* extData;
  19504. word32 extDataSz;
  19505. byte critical;
  19506. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  19507. (void)heap;
  19508. extEndIdx = idx + maxIdx;
  19509. /* Step through each extension looking for AKI. */
  19510. while ((ret == 0) && (idx < extEndIdx)) {
  19511. /* Clear dynamic data and check for certificate extension type OIDs. */
  19512. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  19513. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  19514. /* Set criticality variable. */
  19515. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  19516. /* Parse an extension. */
  19517. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  19518. &idx, extEndIdx);
  19519. if (ret == 0) {
  19520. /* Get reference to extension data and move index on past this
  19521. * extension. */
  19522. GetASN_GetRef(&dataASN[CERTEXTASN_IDX_VAL], &extData, &extDataSz);
  19523. idx += extDataSz;
  19524. /* Check whether we have the AKI extension. */
  19525. if (dataASN[CERTEXTASN_IDX_OID].data.oid.sum == AUTH_KEY_OID) {
  19526. /* Clear dynamic data. */
  19527. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  19528. /* Start parsing extension data from the start. */
  19529. idx = 0;
  19530. /* Parse AKI extension data. */
  19531. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  19532. 1, extData, &idx, extDataSz);
  19533. if ((ret == 0) &&
  19534. (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data
  19535. != NULL)) {
  19536. /* We parsed successfully and have data. */
  19537. *set = 1;
  19538. /* Get the hash or hash of the hash if wrong size. */
  19539. ret = GetHashId(
  19540. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  19541. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  19542. hash, sigOID);
  19543. }
  19544. break;
  19545. }
  19546. }
  19547. }
  19548. FREE_ASNGETDATA(dataASN, heap);
  19549. return ret;
  19550. }
  19551. #endif
  19552. /* Only quick step through the certificate to find fields that are then used
  19553. * in certificate signature verification.
  19554. * Must use the signature OID from the signed part of the certificate.
  19555. * Works also on certificate signing requests.
  19556. *
  19557. * This is only for minimizing dynamic memory usage during TLS certificate
  19558. * chain processing.
  19559. * Doesn't support:
  19560. * OCSP Only: alt lookup using subject and pub key w/o sig check
  19561. */
  19562. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  19563. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  19564. {
  19565. #ifndef WOLFSSL_ASN_TEMPLATE
  19566. #ifndef WOLFSSL_SMALL_STACK
  19567. SignatureCtx sigCtx[1];
  19568. #else
  19569. SignatureCtx* sigCtx;
  19570. #endif
  19571. byte hash[KEYID_SIZE];
  19572. Signer* ca = NULL;
  19573. word32 idx = 0;
  19574. int len;
  19575. word32 tbsCertIdx = 0;
  19576. word32 sigIndex = 0;
  19577. word32 signatureOID = 0;
  19578. word32 oid = 0;
  19579. word32 issuerIdx = 0;
  19580. word32 issuerSz = 0;
  19581. #ifndef NO_SKID
  19582. int extLen = 0;
  19583. word32 extIdx = 0;
  19584. word32 extEndIdx = 0;
  19585. int extAuthKeyIdSet = 0;
  19586. #endif
  19587. int ret = 0;
  19588. word32 localIdx;
  19589. byte tag;
  19590. const byte* sigParams = NULL;
  19591. word32 sigParamsSz = 0;
  19592. if (cert == NULL) {
  19593. return BAD_FUNC_ARG;
  19594. }
  19595. #ifdef WOLFSSL_SMALL_STACK
  19596. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  19597. if (sigCtx == NULL)
  19598. return MEMORY_E;
  19599. #endif
  19600. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  19601. /* Certificate SEQUENCE */
  19602. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19603. ret = ASN_PARSE_E;
  19604. if (ret == 0) {
  19605. tbsCertIdx = idx;
  19606. /* TBSCertificate SEQUENCE */
  19607. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19608. ret = ASN_PARSE_E;
  19609. }
  19610. if (ret == 0) {
  19611. sigIndex = len + idx;
  19612. if ((idx + 1) > certSz)
  19613. ret = BUFFER_E;
  19614. }
  19615. if (ret == 0) {
  19616. /* version - optional */
  19617. localIdx = idx;
  19618. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19619. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  19620. idx++;
  19621. if (GetLength(cert, &idx, &len, certSz) < 0)
  19622. ret = ASN_PARSE_E;
  19623. idx += len;
  19624. }
  19625. }
  19626. }
  19627. if (ret == 0) {
  19628. /* serialNumber */
  19629. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  19630. ret = ASN_PARSE_E;
  19631. }
  19632. if (ret == 0) {
  19633. idx += len;
  19634. /* signature */
  19635. if (!req) {
  19636. if (GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  19637. ret = ASN_PARSE_E;
  19638. #ifdef WC_RSA_PSS
  19639. else if (signatureOID == CTC_RSASSAPSS) {
  19640. int start = idx;
  19641. sigParams = cert + idx;
  19642. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19643. ret = ASN_PARSE_E;
  19644. if (ret == 0) {
  19645. idx += len;
  19646. sigParamsSz = idx - start;
  19647. }
  19648. }
  19649. #endif
  19650. }
  19651. }
  19652. if (ret == 0) {
  19653. issuerIdx = idx;
  19654. /* issuer for cert or subject for csr */
  19655. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19656. ret = ASN_PARSE_E;
  19657. }
  19658. if (ret == 0) {
  19659. issuerSz = len + idx - issuerIdx;
  19660. }
  19661. #ifndef NO_SKID
  19662. if (!req && ret == 0) {
  19663. idx += len;
  19664. /* validity */
  19665. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19666. ret = ASN_PARSE_E;
  19667. }
  19668. if (!req && ret == 0) {
  19669. idx += len;
  19670. /* subject */
  19671. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19672. ret = ASN_PARSE_E;
  19673. }
  19674. if (ret == 0) {
  19675. idx += len;
  19676. /* subjectPublicKeyInfo */
  19677. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19678. ret = ASN_PARSE_E;
  19679. }
  19680. if (req && ret == 0) {
  19681. idx += len;
  19682. /* attributes */
  19683. if (GetASNHeader_ex(cert,
  19684. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  19685. &len, certSz, 1) < 0)
  19686. ret = ASN_PARSE_E;
  19687. }
  19688. if (!req) {
  19689. if (ret == 0) {
  19690. idx += len;
  19691. if ((idx + 1) > certSz)
  19692. ret = BUFFER_E;
  19693. }
  19694. if (ret == 0) {
  19695. /* issuerUniqueID - optional */
  19696. localIdx = idx;
  19697. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19698. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  19699. idx++;
  19700. if (GetLength(cert, &idx, &len, certSz) < 0)
  19701. ret = ASN_PARSE_E;
  19702. idx += len;
  19703. }
  19704. }
  19705. }
  19706. if (ret == 0) {
  19707. if ((idx + 1) > certSz)
  19708. ret = BUFFER_E;
  19709. }
  19710. if (ret == 0) {
  19711. /* subjectUniqueID - optional */
  19712. localIdx = idx;
  19713. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  19714. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  19715. idx++;
  19716. if (GetLength(cert, &idx, &len, certSz) < 0)
  19717. ret = ASN_PARSE_E;
  19718. idx += len;
  19719. }
  19720. }
  19721. }
  19722. if (ret == 0) {
  19723. if ((idx + 1) > certSz)
  19724. ret = BUFFER_E;
  19725. }
  19726. /* extensions - optional */
  19727. localIdx = idx;
  19728. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19729. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  19730. idx++;
  19731. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  19732. ret = ASN_PARSE_E;
  19733. if (ret == 0) {
  19734. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  19735. ret = ASN_PARSE_E;
  19736. }
  19737. if (ret == 0) {
  19738. extEndIdx = idx + extLen;
  19739. /* Check each extension for the ones we want. */
  19740. while (ret == 0 && idx < extEndIdx) {
  19741. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19742. ret = ASN_PARSE_E;
  19743. if (ret == 0) {
  19744. extIdx = idx;
  19745. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  19746. certSz) < 0) {
  19747. ret = ASN_PARSE_E;
  19748. }
  19749. if (ret == 0) {
  19750. if ((extIdx + 1) > certSz)
  19751. ret = BUFFER_E;
  19752. }
  19753. }
  19754. if (ret == 0) {
  19755. localIdx = extIdx;
  19756. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  19757. tag == ASN_BOOLEAN) {
  19758. if (GetBoolean(cert, &extIdx, certSz) < 0)
  19759. ret = ASN_PARSE_E;
  19760. }
  19761. }
  19762. if (ret == 0) {
  19763. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  19764. ret = ASN_PARSE_E;
  19765. }
  19766. if (ret == 0) {
  19767. switch (oid) {
  19768. case AUTH_KEY_OID:
  19769. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  19770. ret = ASN_PARSE_E;
  19771. if (ret == 0 && (extIdx + 1) >= certSz)
  19772. ret = BUFFER_E;
  19773. if (ret == 0 &&
  19774. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  19775. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  19776. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  19777. ret = ASN_PARSE_E;
  19778. if (ret == 0) {
  19779. extAuthKeyIdSet = 1;
  19780. /* Get the hash or hash of the hash if wrong
  19781. * size. */
  19782. ret = GetHashId(cert + extIdx, extLen,
  19783. hash, HashIdAlg(signatureOID));
  19784. }
  19785. }
  19786. break;
  19787. default:
  19788. break;
  19789. }
  19790. }
  19791. idx += len;
  19792. }
  19793. }
  19794. }
  19795. }
  19796. else if (ret == 0) {
  19797. idx += len;
  19798. }
  19799. if (ret == 0 && pubKey == NULL) {
  19800. if (extAuthKeyIdSet)
  19801. ca = GetCA(cm, hash);
  19802. if (ca == NULL) {
  19803. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  19804. HashIdAlg(signatureOID));
  19805. if (ret == 0)
  19806. ca = GetCAByName(cm, hash);
  19807. }
  19808. }
  19809. #else
  19810. if (ret == 0 && pubKey == NULL) {
  19811. ret = CalcHashId_ex(cert + issuerIdx, issuerSz, hash,
  19812. HashIdAlg(signatureOID));
  19813. if (ret == 0)
  19814. ca = GetCA(cm, hash);
  19815. }
  19816. #endif /* !NO_SKID */
  19817. if (ca == NULL && pubKey == NULL)
  19818. ret = ASN_NO_SIGNER_E;
  19819. if (ret == 0) {
  19820. idx = sigIndex;
  19821. /* signatureAlgorithm */
  19822. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  19823. ret = ASN_PARSE_E;
  19824. #ifdef WC_RSA_PSS
  19825. else if (signatureOID == CTC_RSASSAPSS) {
  19826. word32 sz = idx;
  19827. const byte* params = cert + idx;
  19828. if (GetSequence(cert, &idx, &len, certSz) < 0)
  19829. ret = ASN_PARSE_E;
  19830. if (ret == 0) {
  19831. idx += len;
  19832. sz = idx - sz;
  19833. if (req) {
  19834. if ((sz != sigParamsSz) ||
  19835. (XMEMCMP(sigParams, params, sz) != 0)) {
  19836. ret = ASN_PARSE_E;
  19837. }
  19838. }
  19839. else {
  19840. sigParams = params;
  19841. sigParamsSz = sz;
  19842. }
  19843. }
  19844. }
  19845. #endif
  19846. /* In CSR signature data is not present in body */
  19847. if (req)
  19848. signatureOID = oid;
  19849. }
  19850. if (ret == 0) {
  19851. if (oid != signatureOID)
  19852. ret = ASN_SIG_OID_E;
  19853. }
  19854. if (ret == 0) {
  19855. /* signatureValue */
  19856. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  19857. ret = ASN_PARSE_E;
  19858. }
  19859. if (ret == 0) {
  19860. if (pubKey != NULL) {
  19861. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19862. sigIndex - tbsCertIdx, pubKey, pubKeySz, pubKeyOID,
  19863. cert + idx, len, signatureOID, sigParams, sigParamsSz, NULL);
  19864. }
  19865. else {
  19866. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  19867. sigIndex - tbsCertIdx, ca->publicKey, ca->pubKeySize,
  19868. ca->keyOID, cert + idx, len, signatureOID, sigParams,
  19869. sigParamsSz, NULL);
  19870. }
  19871. if (ret != 0) {
  19872. WOLFSSL_ERROR_VERBOSE(ret);
  19873. WOLFSSL_MSG("Confirm signature failed");
  19874. }
  19875. }
  19876. FreeSignatureCtx(sigCtx);
  19877. #ifdef WOLFSSL_SMALL_STACK
  19878. if (sigCtx != NULL)
  19879. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  19880. #endif
  19881. return ret;
  19882. #else /* WOLFSSL_ASN_TEMPLATE */
  19883. /* X509 ASN.1 template longer than Certificate Request template. */
  19884. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  19885. #ifndef WOLFSSL_SMALL_STACK
  19886. SignatureCtx sigCtx[1];
  19887. #else
  19888. SignatureCtx* sigCtx = NULL;
  19889. #endif
  19890. byte hash[KEYID_SIZE];
  19891. Signer* ca = NULL;
  19892. int ret = 0;
  19893. word32 idx = 0;
  19894. #ifndef NO_SKID
  19895. int extAuthKeyIdSet = 0;
  19896. #endif
  19897. const byte* tbs = NULL;
  19898. word32 tbsSz = 0;
  19899. #ifdef WC_RSA_PSS
  19900. const byte* tbsParams = NULL;
  19901. word32 tbsParamsSz = 0;
  19902. #endif
  19903. const byte* sig = NULL;
  19904. word32 sigSz = 0;
  19905. word32 sigOID = 0;
  19906. const byte* sigParams = NULL;
  19907. word32 sigParamsSz = 0;
  19908. const byte* caName = NULL;
  19909. word32 caNameLen = 0;
  19910. #ifndef NO_SKID
  19911. const byte* akiData = NULL;
  19912. word32 akiLen = 0;
  19913. #endif
  19914. (void)req;
  19915. (void)heap;
  19916. if (cert == NULL) {
  19917. ret = BAD_FUNC_ARG;
  19918. }
  19919. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  19920. if ((ret == 0) && (!req)) {
  19921. /* Clear dynamic data for certificate items. */
  19922. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  19923. /* Set OID types expected for signature and public key. */
  19924. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID], oidSigType);
  19925. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_OID],
  19926. oidKeyType);
  19927. GetASN_OID(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_CURVEID],
  19928. oidCurveType);
  19929. GetASN_OID(&dataASN[X509CERTASN_IDX_SIGALGO_OID], oidSigType);
  19930. /* Parse certificate. */
  19931. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  19932. &idx, certSz);
  19933. /* Check signature OIDs match. */
  19934. if ((ret == 0) && dataASN[X509CERTASN_IDX_TBS_ALGOID_OID].data.oid.sum
  19935. != dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum) {
  19936. ret = ASN_SIG_OID_E;
  19937. }
  19938. /* Store the data for verification in the certificate. */
  19939. if (ret == 0) {
  19940. tbs = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19941. tbsSz = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_SEQ], cert);
  19942. caName = GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19943. cert);
  19944. caNameLen = GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  19945. cert);
  19946. sigOID = dataASN[X509CERTASN_IDX_SIGALGO_OID].data.oid.sum;
  19947. #ifdef WC_RSA_PSS
  19948. if (dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].tag != 0) {
  19949. tbsParams =
  19950. GetASNItem_Addr(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19951. cert);
  19952. tbsParamsSz =
  19953. GetASNItem_Length(dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS],
  19954. cert);
  19955. }
  19956. if (dataASN[X509CERTASN_IDX_SIGALGO_PARAMS].tag != 0) {
  19957. sigParams =
  19958. GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19959. cert);
  19960. sigParamsSz =
  19961. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  19962. cert);
  19963. }
  19964. #endif
  19965. GetASN_GetConstRef(&dataASN[X509CERTASN_IDX_SIGNATURE], &sig, &sigSz);
  19966. #ifdef WC_RSA_PSS
  19967. if (tbsParamsSz != sigParamsSz) {
  19968. ret = ASN_PARSE_E;
  19969. }
  19970. else if ((tbsParamsSz > 0) && (sigOID != CTC_RSASSAPSS)) {
  19971. ret = ASN_PARSE_E;
  19972. }
  19973. else if ((tbsParamsSz > 0) &&
  19974. (XMEMCMP(tbsParams, sigParams, tbsParamsSz) != 0)) {
  19975. ret = ASN_PARSE_E;
  19976. }
  19977. #endif
  19978. }
  19979. }
  19980. else if (ret == 0) {
  19981. #ifndef WOLFSSL_CERT_REQ
  19982. ret = NOT_COMPILED_IN;
  19983. #else
  19984. /* Clear dynamic data for certificate request items. */
  19985. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  19986. /* Set OID types expected for signature and public key. */
  19987. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_OID],
  19988. oidKeyType);
  19989. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SPUBKEYINFO_ALGOID_CURVEID],
  19990. oidCurveType);
  19991. GetASN_OID(&dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID], oidSigType);
  19992. /* Parse certificate request. */
  19993. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  19994. &idx, certSz);
  19995. if (ret == 0) {
  19996. /* Store the data for verification in the certificate. */
  19997. tbs = GetASNItem_Addr(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19998. tbsSz = GetASNItem_Length(dataASN[CERTREQASN_IDX_INFO_SEQ], cert);
  19999. caName = GetASNItem_Addr(
  20000. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20001. caNameLen = GetASNItem_Length(
  20002. dataASN[CERTREQASN_IDX_INFO_SUBJ_SEQ], cert);
  20003. sigOID = dataASN[CERTREQASN_IDX_INFO_SIGALGO_OID].data.oid.sum;
  20004. #ifdef WC_RSA_PSS
  20005. sigParams = GetASNItem_Addr(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20006. cert);
  20007. sigParamsSz =
  20008. GetASNItem_Length(dataASN[X509CERTASN_IDX_SIGALGO_PARAMS],
  20009. cert);
  20010. #endif
  20011. GetASN_GetConstRef(&dataASN[CERTREQASN_IDX_INFO_SIGNATURE], &sig,
  20012. &sigSz);
  20013. }
  20014. #endif
  20015. }
  20016. #ifndef NO_SKID
  20017. if ((ret == 0) && (pubKey == NULL) && !req) {
  20018. akiData = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.data;
  20019. akiLen = dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.ref.length;
  20020. }
  20021. #endif
  20022. FREE_ASNGETDATA(dataASN, heap);
  20023. /* If no public passed, then find the CA. */
  20024. if ((ret == 0) && (pubKey == NULL)) {
  20025. #ifndef NO_SKID
  20026. /* Find the AKI extension in list of extensions and get hash. */
  20027. if ((!req) && (akiData != NULL)) {
  20028. /* TODO: test case */
  20029. ret = GetAKIHash(akiData, akiLen, sigOID, hash, &extAuthKeyIdSet,
  20030. heap);
  20031. }
  20032. /* Get the CA by hash one was found. */
  20033. if (extAuthKeyIdSet) {
  20034. ca = GetCA(cm, hash);
  20035. }
  20036. if (ca == NULL)
  20037. #endif
  20038. {
  20039. /* Try hash of issuer name. */
  20040. ret = CalcHashId_ex(caName, caNameLen, hash, HashIdAlg(sigOID));
  20041. if (ret == 0) {
  20042. ca = GetCAByName(cm, hash);
  20043. }
  20044. }
  20045. if (ca != NULL) {
  20046. /* Extract public key information. */
  20047. pubKey = ca->publicKey;
  20048. pubKeySz = ca->pubKeySize;
  20049. pubKeyOID = ca->keyOID;
  20050. }
  20051. else {
  20052. /* No public key to verify with. */
  20053. ret = ASN_NO_SIGNER_E;
  20054. }
  20055. }
  20056. if (ret == 0) {
  20057. #ifdef WOLFSSL_SMALL_STACK
  20058. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  20059. DYNAMIC_TYPE_SIGNATURE);
  20060. if (sigCtx == NULL) {
  20061. ret = MEMORY_E;
  20062. }
  20063. if (ret == 0)
  20064. #endif
  20065. {
  20066. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  20067. /* Check signature. */
  20068. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz,
  20069. pubKeyOID, sig, sigSz, sigOID, sigParams, sigParamsSz, NULL);
  20070. if (ret != 0) {
  20071. WOLFSSL_MSG("Confirm signature failed");
  20072. }
  20073. FreeSignatureCtx(sigCtx);
  20074. #ifdef WOLFSSL_SMALL_STACK
  20075. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  20076. #endif
  20077. }
  20078. }
  20079. return ret;
  20080. #endif /* WOLFSSL_ASN_TEMPLATE */
  20081. }
  20082. #ifdef OPENSSL_EXTRA
  20083. /* Call CheckCertSignature_ex using a public key buffer for verification
  20084. */
  20085. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20086. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20087. {
  20088. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20089. pubKey, pubKeySz, pubKeyOID, 0);
  20090. }
  20091. int wc_CheckCertSigPubKey(const byte* cert, word32 certSz, void* heap,
  20092. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20093. {
  20094. return CheckCertSignaturePubKey(cert, certSz, heap, pubKey, pubKeySz,
  20095. pubKeyOID);
  20096. }
  20097. #ifdef WOLFSSL_CERT_REQ
  20098. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  20099. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  20100. {
  20101. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  20102. pubKey, pubKeySz, pubKeyOID, 1);
  20103. }
  20104. #endif /* WOLFSSL_CERT_REQ */
  20105. #endif /* OPENSSL_EXTRA */
  20106. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  20107. /* Call CheckCertSignature_ex using a certificate manager (cm)
  20108. */
  20109. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  20110. {
  20111. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  20112. }
  20113. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  20114. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  20115. #if (defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) || \
  20116. (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)))
  20117. /* ASN.1 DER decode instruction. */
  20118. typedef struct DecodeInstr {
  20119. /* Tag expected. */
  20120. byte tag;
  20121. /* Operation to perform: step in or go over */
  20122. byte op:1;
  20123. /* ASN.1 item is optional. */
  20124. byte optional:1;
  20125. } DecodeInstr;
  20126. /* Step into ASN.1 item. */
  20127. #define DECODE_INSTR_IN 0
  20128. /* Step over ASN.1 item. */
  20129. #define DECODE_INSTR_OVER 1
  20130. /* Get the public key data from the DER encoded X.509 certificate.
  20131. *
  20132. * Assumes data has previously been parsed for complete validity.
  20133. *
  20134. * @param [in] cert DER encoded X.509 certificate data.
  20135. * @param [in] certSz Length of DER encoding.
  20136. * @param [out] pubKey Public key data. (From the BIT_STRING.)
  20137. * @param [out] pubKeySz Length of public key data in bytes.
  20138. * @return 0 on success.
  20139. * @return BAD_FUNC_ARG when cert, pubKey or pubKeySz is NULL.
  20140. * @return ASN_PARSE_E when certificate encoding is invalid.
  20141. */
  20142. int wc_CertGetPubKey(const byte* cert, word32 certSz,
  20143. const unsigned char** pubKey, word32* pubKeySz)
  20144. {
  20145. int ret = 0;
  20146. int l;
  20147. word32 o = 0;
  20148. int i;
  20149. static DecodeInstr ops[] = {
  20150. /* Outer SEQ */
  20151. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20152. /* TBSCertificate: SEQ */
  20153. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20154. /* Version: [0] */
  20155. { ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_X509_CERT_VERSION,
  20156. DECODE_INSTR_OVER, 1 },
  20157. /* CertificateSerialNumber: INT */
  20158. { ASN_INTEGER, DECODE_INSTR_OVER, 0 },
  20159. /* AlgorithmIdentifier: SEQ */
  20160. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20161. /* issuer: SEQ */
  20162. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20163. /* Validity: SEQ */
  20164. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20165. /* subject: SEQ */
  20166. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20167. /* subjectPublicKeyInfo SEQ */
  20168. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_IN , 0 },
  20169. /* AlgorithmIdentifier: SEQ */
  20170. { ASN_SEQUENCE | ASN_CONSTRUCTED, DECODE_INSTR_OVER, 0 },
  20171. /* PublicKey: BIT_STRING */
  20172. { ASN_BIT_STRING, DECODE_INSTR_IN , 0 },
  20173. };
  20174. /* Validate parameters. */
  20175. if ((cert == NULL) || (pubKey == NULL) || (pubKeySz == NULL)) {
  20176. ret = BAD_FUNC_ARG;
  20177. }
  20178. /* Process each instruction to take us to public key data. */
  20179. for (i = 0; (ret == 0) && (i < (int)(sizeof(ops) / sizeof(*ops))); i++) {
  20180. DecodeInstr op = ops[i];
  20181. /* Check the current ASN.1 item has the expected tag. */
  20182. if (cert[o] != op.tag) {
  20183. /* If not optional then error, otherwise skip op. */
  20184. if (!op.optional) {
  20185. ret = ASN_PARSE_E;
  20186. }
  20187. }
  20188. else {
  20189. /* Move past tag. */
  20190. o++;
  20191. /* Get the length of ASN.1 item and move past length encoding. */
  20192. if (GetLength(cert, &o, &l, certSz) < 0) {
  20193. ret = ASN_PARSE_E;
  20194. }
  20195. /* Skip data if required. */
  20196. else if (op.op == DECODE_INSTR_OVER) {
  20197. o += l;
  20198. }
  20199. }
  20200. }
  20201. if (ret == 0) {
  20202. /* Return the public key data and length.
  20203. * Skip first byte of BIT_STRING data: unused bits. */
  20204. *pubKey = cert + o + 1;
  20205. *pubKeySz = l - 1;
  20206. }
  20207. return ret;
  20208. }
  20209. #endif
  20210. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  20211. {
  20212. int ret = 0;
  20213. #ifndef WOLFSSL_ASN_TEMPLATE
  20214. word32 confirmOID = 0;
  20215. #ifdef WOLFSSL_CERT_REQ
  20216. int len = 0;
  20217. #endif
  20218. #endif
  20219. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20220. int idx = 0;
  20221. #endif
  20222. byte* sce_tsip_encRsaKeyIdx;
  20223. if (cert == NULL) {
  20224. return BAD_FUNC_ARG;
  20225. }
  20226. #ifdef WOLFSSL_CERT_REQ
  20227. if (type == CERTREQ_TYPE)
  20228. cert->isCSR = 1;
  20229. #endif
  20230. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  20231. #ifndef WOLFSSL_ASN_TEMPLATE
  20232. cert->badDate = 0;
  20233. cert->criticalExt = 0;
  20234. if ((ret = DecodeToKey(cert, verify)) < 0) {
  20235. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20236. cert->badDate = ret;
  20237. if (verify == VERIFY_SKIP_DATE)
  20238. ret = 0;
  20239. }
  20240. else
  20241. return ret;
  20242. }
  20243. WOLFSSL_MSG("Parsed Past Key");
  20244. #ifdef WOLFSSL_CERT_REQ
  20245. /* Read attributes */
  20246. if (cert->isCSR) {
  20247. if (GetASNHeader_ex(cert->source,
  20248. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  20249. &len, cert->maxIdx, 1) < 0) {
  20250. WOLFSSL_MSG("GetASNHeader_ex error");
  20251. return ASN_PARSE_E;
  20252. }
  20253. if (len) {
  20254. word32 attrMaxIdx = cert->srcIdx + (word32)len;
  20255. word32 oid;
  20256. byte tag;
  20257. if (attrMaxIdx > cert->maxIdx) {
  20258. WOLFSSL_MSG("Attribute length greater than CSR length");
  20259. return ASN_PARSE_E;
  20260. }
  20261. while (cert->srcIdx < attrMaxIdx) {
  20262. /* Attributes have the structure:
  20263. * SEQ -> OID -> SET -> ATTRIBUTE */
  20264. if (GetSequence(cert->source, &cert->srcIdx, &len,
  20265. attrMaxIdx) < 0) {
  20266. WOLFSSL_MSG("attr GetSequence error");
  20267. return ASN_PARSE_E;
  20268. }
  20269. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  20270. oidCsrAttrType, attrMaxIdx) < 0) {
  20271. WOLFSSL_MSG("attr GetObjectId error");
  20272. return ASN_PARSE_E;
  20273. }
  20274. if (GetSet(cert->source, &cert->srcIdx, &len,
  20275. attrMaxIdx) < 0) {
  20276. WOLFSSL_MSG("attr GetSet error");
  20277. return ASN_PARSE_E;
  20278. }
  20279. switch (oid) {
  20280. case PKCS9_CONTENT_TYPE_OID:
  20281. if (GetHeader(cert->source, &tag,
  20282. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20283. WOLFSSL_MSG("attr GetHeader error");
  20284. return ASN_PARSE_E;
  20285. }
  20286. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20287. tag != ASN_IA5_STRING) {
  20288. WOLFSSL_MSG("Unsupported attribute value format");
  20289. return ASN_PARSE_E;
  20290. }
  20291. cert->contentType = (char*)cert->source + cert->srcIdx;
  20292. cert->contentTypeLen = len;
  20293. cert->srcIdx += (word32)len;
  20294. break;
  20295. case CHALLENGE_PASSWORD_OID:
  20296. if (GetHeader(cert->source, &tag,
  20297. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20298. WOLFSSL_MSG("attr GetHeader error");
  20299. return ASN_PARSE_E;
  20300. }
  20301. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20302. tag != ASN_IA5_STRING) {
  20303. WOLFSSL_MSG("Unsupported attribute value format");
  20304. return ASN_PARSE_E;
  20305. }
  20306. cert->cPwd = (char*)cert->source + cert->srcIdx;
  20307. cert->cPwdLen = len;
  20308. cert->srcIdx += (word32)len;
  20309. break;
  20310. case SERIAL_NUMBER_OID:
  20311. if (GetHeader(cert->source, &tag,
  20312. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20313. WOLFSSL_MSG("attr GetHeader error");
  20314. return ASN_PARSE_E;
  20315. }
  20316. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  20317. tag != ASN_IA5_STRING) {
  20318. WOLFSSL_MSG("Unsupported attribute value format");
  20319. return ASN_PARSE_E;
  20320. }
  20321. cert->sNum = (char*)cert->source + cert->srcIdx;
  20322. cert->sNumLen = len;
  20323. cert->srcIdx += (word32)len;
  20324. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  20325. XMEMCPY(cert->serial, cert->sNum,
  20326. (size_t)cert->sNumLen);
  20327. cert->serialSz = cert->sNumLen;
  20328. }
  20329. break;
  20330. case DNQUALIFIER_OID:
  20331. if (GetHeader(cert->source, &tag,
  20332. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20333. WOLFSSL_MSG("attr GetHeader error");
  20334. return ASN_PARSE_E;
  20335. }
  20336. cert->dnQualifier = (char*)cert->source + cert->srcIdx;
  20337. cert->dnQualifierLen = len;
  20338. cert->srcIdx += (word32)len;
  20339. break;
  20340. case INITIALS_OID:
  20341. if (GetHeader(cert->source, &tag,
  20342. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20343. WOLFSSL_MSG("attr GetHeader error");
  20344. return ASN_PARSE_E;
  20345. }
  20346. cert->initials = (char*)cert->source + cert->srcIdx;
  20347. cert->initialsLen = len;
  20348. cert->srcIdx += (word32)len;
  20349. break;
  20350. case SURNAME_OID:
  20351. if (GetHeader(cert->source, &tag,
  20352. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20353. WOLFSSL_MSG("attr GetHeader error");
  20354. return ASN_PARSE_E;
  20355. }
  20356. cert->surname = (char*)cert->source + cert->srcIdx;
  20357. cert->surnameLen = len;
  20358. cert->srcIdx += (word32)len;
  20359. break;
  20360. case GIVEN_NAME_OID:
  20361. if (GetHeader(cert->source, &tag,
  20362. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20363. WOLFSSL_MSG("attr GetHeader error");
  20364. return ASN_PARSE_E;
  20365. }
  20366. cert->givenName = (char*)cert->source + cert->srcIdx;
  20367. cert->givenNameLen = len;
  20368. cert->srcIdx += (word32)len;
  20369. break;
  20370. case UNSTRUCTURED_NAME_OID:
  20371. if (GetHeader(cert->source, &tag,
  20372. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  20373. WOLFSSL_MSG("attr GetHeader error");
  20374. return ASN_PARSE_E;
  20375. }
  20376. cert->unstructuredName =
  20377. (char*)cert->source + cert->srcIdx;
  20378. cert->unstructuredNameLen = len;
  20379. cert->srcIdx += (word32)len;
  20380. break;
  20381. case EXTENSION_REQUEST_OID:
  20382. /* save extensions */
  20383. cert->extensions = &cert->source[cert->srcIdx];
  20384. cert->extensionsSz = len;
  20385. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20386. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20387. if (ret == ASN_CRIT_EXT_E) {
  20388. cert->criticalExt = ret;
  20389. }
  20390. else {
  20391. return ret;
  20392. }
  20393. }
  20394. cert->srcIdx += (word32)len;
  20395. break;
  20396. default:
  20397. WOLFSSL_MSG("Unsupported attribute type");
  20398. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20399. return ASN_PARSE_E;
  20400. }
  20401. }
  20402. }
  20403. }
  20404. #endif
  20405. if (cert->srcIdx < cert->sigIndex) {
  20406. #ifndef ALLOW_V1_EXTENSIONS
  20407. if (cert->version < 2) {
  20408. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  20409. WOLFSSL_ERROR_VERBOSE(ASN_VERSION_E);
  20410. return ASN_VERSION_E;
  20411. }
  20412. #endif
  20413. /* save extensions */
  20414. cert->extensions = &cert->source[cert->srcIdx];
  20415. cert->extensionsSz = (int)(cert->sigIndex - cert->srcIdx);
  20416. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  20417. if ((ret = DecodeCertExtensions(cert)) < 0) {
  20418. if (ret == ASN_CRIT_EXT_E)
  20419. cert->criticalExt = ret;
  20420. else
  20421. return ret;
  20422. }
  20423. #ifdef HAVE_OCSP
  20424. if (verify == VERIFY_OCSP_CERT) {
  20425. /* trust for the lifetime of the responder's cert*/
  20426. if (cert->ocspNoCheckSet)
  20427. verify = VERIFY;
  20428. else
  20429. verify = VERIFY_OCSP;
  20430. }
  20431. #endif
  20432. /* advance past extensions */
  20433. cert->srcIdx = cert->sigIndex;
  20434. }
  20435. if ((ret = GetSigAlg(cert,
  20436. #ifdef WOLFSSL_CERT_REQ
  20437. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  20438. #else
  20439. &confirmOID,
  20440. #endif
  20441. cert->maxIdx)) < 0) {
  20442. return ret;
  20443. }
  20444. if ((ret = GetSignature(cert)) < 0) {
  20445. return ret;
  20446. }
  20447. if (confirmOID != cert->signatureOID
  20448. #ifdef WOLFSSL_CERT_REQ
  20449. && !cert->isCSR
  20450. #endif
  20451. ) {
  20452. WOLFSSL_ERROR_VERBOSE(ASN_SIG_OID_E);
  20453. return ASN_SIG_OID_E;
  20454. }
  20455. #else
  20456. #ifdef WOLFSSL_CERT_REQ
  20457. if (cert->isCSR) {
  20458. ret = DecodeCertReq(cert, &cert->criticalExt);
  20459. if (ret < 0) {
  20460. return ret;
  20461. }
  20462. }
  20463. else
  20464. #endif
  20465. {
  20466. ret = DecodeCert(cert, verify, &cert->criticalExt);
  20467. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E) {
  20468. cert->badDate = ret;
  20469. if (verify == VERIFY_SKIP_DATE)
  20470. ret = 0;
  20471. }
  20472. else if (ret < 0) {
  20473. WOLFSSL_ERROR_VERBOSE(ret);
  20474. return ret;
  20475. }
  20476. }
  20477. #endif
  20478. #ifndef NO_SKID
  20479. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  20480. cert->pubKeySize > 0) {
  20481. if (cert->signatureOID == CTC_SM3wSM2) {
  20482. /* TODO: GmSSL creates IDs this way but whole public key info
  20483. * block should be hashed. */
  20484. ret = CalcHashId_ex(cert->publicKey + cert->pubKeySize - 65, 65,
  20485. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  20486. }
  20487. else {
  20488. ret = CalcHashId_ex(cert->publicKey, cert->pubKeySize,
  20489. cert->extSubjKeyId, HashIdAlg(cert->signatureOID));
  20490. }
  20491. if (ret != 0) {
  20492. WOLFSSL_ERROR_VERBOSE(ret);
  20493. return ret;
  20494. }
  20495. }
  20496. #endif /* !NO_SKID */
  20497. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  20498. type != TRUSTED_PEER_TYPE)) {
  20499. cert->ca = NULL;
  20500. #ifndef NO_SKID
  20501. if (cert->extAuthKeyIdSet) {
  20502. cert->ca = GetCA(cm, cert->extAuthKeyId);
  20503. }
  20504. if (cert->ca == NULL && cert->extSubjKeyIdSet
  20505. && verify != VERIFY_OCSP) {
  20506. cert->ca = GetCA(cm, cert->extSubjKeyId);
  20507. }
  20508. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  20509. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  20510. cert->ca = NULL;
  20511. }
  20512. if (cert->ca == NULL) {
  20513. cert->ca = GetCAByName(cm, cert->issuerHash);
  20514. /* If AKID is available then this CA doesn't have the public
  20515. * key required */
  20516. if (cert->ca && cert->extAuthKeyIdSet) {
  20517. WOLFSSL_MSG("CA SKID doesn't match AKID");
  20518. cert->ca = NULL;
  20519. }
  20520. }
  20521. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  20522. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  20523. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  20524. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  20525. if (cert->ca) {
  20526. ret = 0; /* success */
  20527. goto exit_pcr;
  20528. }
  20529. }
  20530. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  20531. #else
  20532. cert->ca = GetCA(cm, cert->issuerHash);
  20533. #endif /* !NO_SKID */
  20534. if (cert->ca) {
  20535. WOLFSSL_MSG("CA found");
  20536. }
  20537. }
  20538. if (cert->selfSigned) {
  20539. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  20540. } else {
  20541. /* RFC 5280 Section 4.2.1.9:
  20542. *
  20543. * load/receive check
  20544. *
  20545. * 1) Is CA boolean set?
  20546. * No - SKIP CHECK
  20547. * Yes - Check key usage
  20548. * 2) Is Key usage extension present?
  20549. * No - goto 3
  20550. * Yes - check keyCertSign assertion
  20551. * 2.a) Is keyCertSign asserted?
  20552. * No - goto 4
  20553. * Yes - goto 3
  20554. * 3) Is pathLen set?
  20555. * No - goto 4
  20556. * Yes - check pathLen against maxPathLen.
  20557. * 3.a) Is pathLen less than maxPathLen?
  20558. * No - goto 4
  20559. * Yes - set maxPathLen to pathLen and EXIT
  20560. * 4) Is maxPathLen > 0?
  20561. * Yes - Reduce by 1
  20562. * No - ERROR
  20563. */
  20564. if (cert->ca && cert->pathLengthSet) {
  20565. int checkPathLen = 0;
  20566. int decrementMaxPathLen = 0;
  20567. cert->maxPathLen = cert->pathLength;
  20568. if (cert->isCA) {
  20569. WOLFSSL_MSG("\tCA boolean set");
  20570. if (cert->extKeyUsageSet) {
  20571. WOLFSSL_MSG("\tExtension Key Usage Set");
  20572. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  20573. checkPathLen = 1;
  20574. }
  20575. else {
  20576. decrementMaxPathLen = 1;
  20577. }
  20578. }
  20579. else {
  20580. checkPathLen = 1;
  20581. } /* !cert->ca check */
  20582. } /* cert is not a CA (assuming entity cert) */
  20583. if (checkPathLen && cert->pathLengthSet) {
  20584. if (cert->pathLength < cert->ca->maxPathLen) {
  20585. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  20586. cert->maxPathLen = cert->pathLength;
  20587. }
  20588. else {
  20589. decrementMaxPathLen = 1;
  20590. }
  20591. }
  20592. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  20593. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  20594. cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
  20595. if (verify != NO_VERIFY && type != CA_TYPE &&
  20596. type != TRUSTED_PEER_TYPE) {
  20597. WOLFSSL_MSG("\tmaxPathLen status: OK");
  20598. }
  20599. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  20600. cert->maxPathLen = 0;
  20601. if (verify != NO_VERIFY && type != CA_TYPE &&
  20602. type != TRUSTED_PEER_TYPE) {
  20603. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20604. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20605. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20606. return ASN_PATHLEN_INV_E;
  20607. }
  20608. }
  20609. } else if (cert->ca && cert->isCA) {
  20610. /* case where cert->pathLength extension is not set */
  20611. if (cert->ca->maxPathLen > 0) {
  20612. cert->maxPathLen = (byte)(cert->ca->maxPathLen - 1);
  20613. } else {
  20614. cert->maxPathLen = 0;
  20615. if (verify != NO_VERIFY && type != CA_TYPE &&
  20616. type != TRUSTED_PEER_TYPE) {
  20617. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  20618. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  20619. WOLFSSL_ERROR_VERBOSE(ASN_PATHLEN_INV_E);
  20620. return ASN_PATHLEN_INV_E;
  20621. }
  20622. }
  20623. }
  20624. }
  20625. #ifdef HAVE_OCSP
  20626. if (verify != NO_VERIFY && type != CA_TYPE &&
  20627. type != TRUSTED_PEER_TYPE) {
  20628. if (cert->ca) {
  20629. /* Need the CA's public key hash for OCSP */
  20630. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  20631. KEYID_SIZE);
  20632. }
  20633. }
  20634. #endif /* HAVE_OCSP */
  20635. }
  20636. #if defined(WOLFSSL_RENESAS_TSIP_TLS) || defined(WOLFSSL_RENESAS_SCEPROTECT)
  20637. /* prepare for TSIP TLS cert verification API use */
  20638. if (cert->keyOID == RSAk) {
  20639. /* to call TSIP API, it needs keys position info in bytes */
  20640. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  20641. cert->pubKeySize,
  20642. &cert->sigCtx.CertAtt.pubkey_n_start,
  20643. &cert->sigCtx.CertAtt.pubkey_n_len,
  20644. &cert->sigCtx.CertAtt.pubkey_e_start,
  20645. &cert->sigCtx.CertAtt.pubkey_e_len)) != 0) {
  20646. WOLFSSL_MSG("Decoding index from cert failed.");
  20647. return ret;
  20648. }
  20649. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20650. }
  20651. else if (cert->keyOID == ECDSAk) {
  20652. cert->sigCtx.CertAtt.certBegin = cert->certBegin;
  20653. }
  20654. /* check if we can use TSIP for cert verification */
  20655. /* if the ca is verified as tsip root ca. */
  20656. /* TSIP can only handle 2048 bits(256 byte) key. */
  20657. if (cert->ca && Renesas_cmn_checkCA(cert->ca->cm_idx) != 0 &&
  20658. (cert->sigCtx.CertAtt.pubkey_n_len == 256 ||
  20659. cert->sigCtx.CertAtt.curve_id == ECC_SECP256R1)) {
  20660. /* assign memory to encrypted tsip Rsa key index */
  20661. if (!cert->sce_tsip_encRsaKeyIdx)
  20662. cert->sce_tsip_encRsaKeyIdx =
  20663. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  20664. cert->heap, DYNAMIC_TYPE_RSA);
  20665. if (cert->sce_tsip_encRsaKeyIdx == NULL)
  20666. return MEMORY_E;
  20667. }
  20668. else {
  20669. if (cert->ca) {
  20670. /* TSIP isn't usable */
  20671. if (Renesas_cmn_checkCA(cert->ca->cm_idx) == 0)
  20672. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't verified "
  20673. "by TSIP.");
  20674. else if (cert->sigCtx.CertAtt.pubkey_n_len != 256)
  20675. WOLFSSL_MSG("SCE-TSIP isn't usable because the ca isn't signed by "
  20676. "RSA 2048.");
  20677. else
  20678. WOLFSSL_MSG("SCE-TSIP isn't usable");
  20679. }
  20680. cert->sce_tsip_encRsaKeyIdx = NULL;
  20681. }
  20682. sce_tsip_encRsaKeyIdx = cert->sce_tsip_encRsaKeyIdx;
  20683. #else
  20684. sce_tsip_encRsaKeyIdx = NULL;
  20685. #endif
  20686. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  20687. if (cert->ca) {
  20688. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20689. verify == VERIFY_SKIP_DATE) {
  20690. /* try to confirm/verify signature */
  20691. if ((ret = ConfirmSignature(&cert->sigCtx,
  20692. cert->source + cert->certBegin,
  20693. cert->sigIndex - cert->certBegin,
  20694. cert->ca->publicKey, cert->ca->pubKeySize,
  20695. cert->ca->keyOID, cert->signature,
  20696. cert->sigLength, cert->signatureOID,
  20697. #ifdef WC_RSA_PSS
  20698. cert->source + cert->sigParamsIndex,
  20699. cert->sigParamsLength,
  20700. #else
  20701. NULL, 0,
  20702. #endif
  20703. sce_tsip_encRsaKeyIdx)) != 0) {
  20704. if (ret != WC_PENDING_E) {
  20705. WOLFSSL_MSG("Confirm signature failed");
  20706. }
  20707. WOLFSSL_ERROR_VERBOSE(ret);
  20708. return ret;
  20709. }
  20710. }
  20711. #ifndef IGNORE_NAME_CONSTRAINTS
  20712. if (verify == VERIFY || verify == VERIFY_OCSP ||
  20713. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  20714. /* check that this cert's name is permitted by the signer's
  20715. * name constraints */
  20716. if (!ConfirmNameConstraints(cert->ca, cert)) {
  20717. WOLFSSL_MSG("Confirm name constraint failed");
  20718. WOLFSSL_ERROR_VERBOSE(ASN_NAME_INVALID_E);
  20719. return ASN_NAME_INVALID_E;
  20720. }
  20721. }
  20722. #endif /* IGNORE_NAME_CONSTRAINTS */
  20723. }
  20724. #ifdef WOLFSSL_CERT_REQ
  20725. else if (type == CERTREQ_TYPE) {
  20726. if ((ret = ConfirmSignature(&cert->sigCtx,
  20727. cert->source + cert->certBegin,
  20728. cert->sigIndex - cert->certBegin,
  20729. cert->publicKey, cert->pubKeySize,
  20730. cert->keyOID, cert->signature,
  20731. cert->sigLength, cert->signatureOID,
  20732. #ifdef WC_RSA_PSS
  20733. cert->source + cert->sigParamsIndex, cert->sigParamsLength,
  20734. #else
  20735. NULL, 0,
  20736. #endif
  20737. sce_tsip_encRsaKeyIdx)) != 0) {
  20738. if (ret != WC_PENDING_E) {
  20739. WOLFSSL_MSG("Confirm signature failed");
  20740. }
  20741. WOLFSSL_ERROR_VERBOSE(ret);
  20742. return ret;
  20743. }
  20744. }
  20745. #endif
  20746. else {
  20747. /* no signer */
  20748. WOLFSSL_MSG("No CA signer to verify with");
  20749. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  20750. /* ret needs to be self-signer error for Qt compat */
  20751. if (cert->selfSigned) {
  20752. WOLFSSL_ERROR_VERBOSE(ASN_SELF_SIGNED_E);
  20753. return ASN_SELF_SIGNED_E;
  20754. }
  20755. else
  20756. #endif
  20757. {
  20758. WOLFSSL_ERROR_VERBOSE(ASN_NO_SIGNER_E);
  20759. return ASN_NO_SIGNER_E;
  20760. }
  20761. }
  20762. }
  20763. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  20764. exit_pcr:
  20765. #endif
  20766. if (cert->badDate != 0) {
  20767. if (verify != VERIFY_SKIP_DATE) {
  20768. return cert->badDate;
  20769. }
  20770. WOLFSSL_MSG("Date error: Verify option is skipping");
  20771. }
  20772. if (cert->criticalExt != 0)
  20773. return cert->criticalExt;
  20774. return ret;
  20775. }
  20776. /* Create and init an new signer */
  20777. Signer* MakeSigner(void* heap)
  20778. {
  20779. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  20780. DYNAMIC_TYPE_SIGNER);
  20781. if (signer) {
  20782. XMEMSET(signer, 0, sizeof(Signer));
  20783. }
  20784. (void)heap;
  20785. return signer;
  20786. }
  20787. /* Free an individual signer.
  20788. *
  20789. * Used by Certificate Manager.
  20790. *
  20791. * @param [in, out] signer On in, signer object.
  20792. * On out, pointer is no longer valid.
  20793. * @param [in] heap Dynamic memory hint.
  20794. */
  20795. void FreeSigner(Signer* signer, void* heap)
  20796. {
  20797. (void)signer;
  20798. (void)heap;
  20799. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20800. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  20801. #ifndef IGNORE_NAME_CONSTRAINTS
  20802. if (signer->permittedNames)
  20803. FreeNameSubtrees(signer->permittedNames, heap);
  20804. if (signer->excludedNames)
  20805. FreeNameSubtrees(signer->excludedNames, heap);
  20806. #endif
  20807. #ifdef WOLFSSL_SIGNER_DER_CERT
  20808. FreeDer(&signer->derCert);
  20809. #endif
  20810. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  20811. }
  20812. /* Free the whole singer table with number of rows.
  20813. *
  20814. * Each table entry is a linked list of signers.
  20815. * Used by Certificate Manager.
  20816. *
  20817. * @param [in, out] table Array of signer objects.
  20818. * @param [in] rows Number of entries in table.
  20819. * @param [in] heap Dynamic memory hint.
  20820. */
  20821. void FreeSignerTable(Signer** table, int rows, void* heap)
  20822. {
  20823. int i;
  20824. for (i = 0; i < rows; i++) {
  20825. Signer* signer = table[i];
  20826. while (signer) {
  20827. Signer* next = signer->next;
  20828. FreeSigner(signer, heap);
  20829. signer = next;
  20830. }
  20831. table[i] = NULL;
  20832. }
  20833. }
  20834. #ifdef WOLFSSL_TRUST_PEER_CERT
  20835. /* Free an individual trusted peer cert.
  20836. *
  20837. * @param [in, out] tp Trusted peer certificate object.
  20838. * @param [in] heap Dynamic memory hint.
  20839. */
  20840. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  20841. {
  20842. if (tp == NULL) {
  20843. return;
  20844. }
  20845. if (tp->name) {
  20846. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  20847. }
  20848. if (tp->sig) {
  20849. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  20850. }
  20851. #ifndef IGNORE_NAME_CONSTRAINTS
  20852. if (tp->permittedNames)
  20853. FreeNameSubtrees(tp->permittedNames, heap);
  20854. if (tp->excludedNames)
  20855. FreeNameSubtrees(tp->excludedNames, heap);
  20856. #endif
  20857. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  20858. (void)heap;
  20859. }
  20860. /* Free the whole Trusted Peer linked list.
  20861. *
  20862. * Each table entry is a linked list of trusted peer certificates.
  20863. * Used by Certificate Manager.
  20864. *
  20865. * @param [in, out] table Array of trusted peer certificate objects.
  20866. * @param [in] rows Number of entries in table.
  20867. * @param [in] heap Dynamic memory hint.
  20868. */
  20869. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  20870. {
  20871. int i;
  20872. for (i = 0; i < rows; i++) {
  20873. TrustedPeerCert* tp = table[i];
  20874. while (tp) {
  20875. TrustedPeerCert* next = tp->next;
  20876. FreeTrustedPeer(tp, heap);
  20877. tp = next;
  20878. }
  20879. table[i] = NULL;
  20880. }
  20881. }
  20882. #endif /* WOLFSSL_TRUST_PEER_CERT */
  20883. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  20884. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  20885. word32 outputSz, int maxSnSz)
  20886. {
  20887. int i;
  20888. int snSzInt = (int)snSz;
  20889. if (sn == NULL || output == NULL || snSzInt < 0)
  20890. return BAD_FUNC_ARG;
  20891. /* remove leading zeros */
  20892. while (snSzInt > 0 && sn[0] == 0) {
  20893. snSzInt--;
  20894. sn++;
  20895. }
  20896. /* RFC 5280 - 4.1.2.2:
  20897. * Serial numbers must be a positive value (and not zero) */
  20898. if (snSzInt == 0) {
  20899. WOLFSSL_ERROR_VERBOSE(BAD_FUNC_ARG);
  20900. return BAD_FUNC_ARG;
  20901. }
  20902. if (sn[0] & 0x80)
  20903. maxSnSz--;
  20904. /* truncate if input is too long */
  20905. if (snSzInt > maxSnSz)
  20906. snSzInt = maxSnSz;
  20907. i = SetASNInt(snSzInt, sn[0], NULL);
  20908. /* truncate if input is too long */
  20909. if (snSzInt > (int)outputSz - i)
  20910. snSzInt = (int)outputSz - i;
  20911. /* sanity check number of bytes to copy */
  20912. if (snSzInt <= 0) {
  20913. return BUFFER_E;
  20914. }
  20915. /* write out ASN.1 Integer */
  20916. (void)SetASNInt(snSzInt, sn[0], output);
  20917. XMEMCPY(output + i, sn, (size_t)snSzInt);
  20918. /* compute final length */
  20919. i += snSzInt;
  20920. return i;
  20921. }
  20922. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20923. #endif /* !NO_CERTS */
  20924. #if defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12) || \
  20925. (defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT))
  20926. int SetMyVersion(word32 version, byte* output, int header)
  20927. {
  20928. int i = 0;
  20929. if (output == NULL)
  20930. return BAD_FUNC_ARG;
  20931. if (header) {
  20932. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  20933. output[i++] = 3;
  20934. }
  20935. output[i++] = ASN_INTEGER;
  20936. output[i++] = 0x01;
  20937. output[i++] = (byte)version;
  20938. return i;
  20939. }
  20940. #endif
  20941. #ifndef WOLFSSL_ASN_TEMPLATE
  20942. int wc_GetSerialNumber(const byte* input, word32* inOutIdx,
  20943. byte* serial, int* serialSz, word32 maxIdx)
  20944. {
  20945. int result = 0;
  20946. int ret;
  20947. WOLFSSL_ENTER("wc_GetSerialNumber");
  20948. if (serial == NULL || input == NULL || serialSz == NULL) {
  20949. return BAD_FUNC_ARG;
  20950. }
  20951. /* First byte is ASN type */
  20952. if ((*inOutIdx+1) > maxIdx) {
  20953. WOLFSSL_MSG("Bad idx first");
  20954. return BUFFER_E;
  20955. }
  20956. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  20957. if (ret != 0)
  20958. return ret;
  20959. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  20960. WOLFSSL_MSG("Serial size bad");
  20961. WOLFSSL_ERROR_VERBOSE(ASN_PARSE_E);
  20962. return ASN_PARSE_E;
  20963. }
  20964. /* return serial */
  20965. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  20966. *inOutIdx += (word32)*serialSz;
  20967. return result;
  20968. }
  20969. #endif
  20970. #ifndef NO_CERTS
  20971. /* TODO: consider moving PEM code out to a different file. */
  20972. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  20973. {
  20974. int ret = BAD_FUNC_ARG;
  20975. if (pDer) {
  20976. int dynType = 0;
  20977. DerBuffer* der;
  20978. /* Determine dynamic type */
  20979. switch (type) {
  20980. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  20981. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  20982. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  20983. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  20984. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  20985. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  20986. default: dynType = DYNAMIC_TYPE_KEY; break;
  20987. }
  20988. /* Setup new buffer */
  20989. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  20990. if (*pDer == NULL) {
  20991. return MEMORY_E;
  20992. }
  20993. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  20994. der = *pDer;
  20995. der->type = type;
  20996. der->dynType = dynType; /* Cache this for FreeDer */
  20997. der->heap = heap;
  20998. der->buffer = (byte*)der + sizeof(DerBuffer);
  20999. der->length = length;
  21000. ret = 0; /* Success */
  21001. }
  21002. return ret;
  21003. }
  21004. void FreeDer(DerBuffer** pDer)
  21005. {
  21006. if (pDer && *pDer)
  21007. {
  21008. DerBuffer* der = (DerBuffer*)*pDer;
  21009. /* ForceZero private keys */
  21010. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  21011. ForceZero(der->buffer, der->length);
  21012. }
  21013. der->buffer = NULL;
  21014. der->length = 0;
  21015. XFREE(der, der->heap, der->dynType);
  21016. *pDer = NULL;
  21017. }
  21018. }
  21019. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  21020. {
  21021. return AllocDer(pDer, length, type, heap);
  21022. }
  21023. void wc_FreeDer(DerBuffer** pDer)
  21024. {
  21025. FreeDer(pDer);
  21026. }
  21027. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  21028. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  21029. updated to reflect maximum length and pem_struct_min_sz
  21030. to reflect minimum size */
  21031. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  21032. wcchar END_CERT = "-----END CERTIFICATE-----";
  21033. #ifdef WOLFSSL_CERT_REQ
  21034. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  21035. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  21036. #endif
  21037. #ifndef NO_DH
  21038. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  21039. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  21040. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  21041. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  21042. #endif
  21043. #ifndef NO_DSA
  21044. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  21045. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  21046. #endif
  21047. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  21048. wcchar END_X509_CRL = "-----END X509 CRL-----";
  21049. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  21050. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  21051. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  21052. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  21053. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  21054. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  21055. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  21056. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  21057. #ifdef HAVE_ECC
  21058. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  21059. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  21060. #ifdef OPENSSL_EXTRA
  21061. wcchar BEGIN_EC_PARAM = "-----BEGIN EC PARAMETERS-----";
  21062. wcchar END_EC_PARAM = "-----END EC PARAMETERS-----";
  21063. #endif
  21064. #endif
  21065. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  21066. !defined(NO_DSA)
  21067. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  21068. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  21069. #endif
  21070. #ifdef OPENSSL_EXTRA
  21071. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  21072. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  21073. const char END_PRIV_KEY_PREFIX[] = "-----END";
  21074. #endif
  21075. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  21076. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  21077. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21078. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  21079. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  21080. #endif
  21081. #if defined(HAVE_PQC)
  21082. #if defined(HAVE_FALCON)
  21083. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  21084. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  21085. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  21086. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  21087. #endif /* HAVE_FALCON */
  21088. #if defined(HAVE_DILITHIUM)
  21089. wcchar BEGIN_DILITHIUM_LEVEL2_PRIV = "-----BEGIN DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21090. wcchar END_DILITHIUM_LEVEL2_PRIV = "-----END DILITHIUM_LEVEL2 PRIVATE KEY-----";
  21091. wcchar BEGIN_DILITHIUM_LEVEL3_PRIV = "-----BEGIN DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21092. wcchar END_DILITHIUM_LEVEL3_PRIV = "-----END DILITHIUM_LEVEL3 PRIVATE KEY-----";
  21093. wcchar BEGIN_DILITHIUM_LEVEL5_PRIV = "-----BEGIN DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21094. wcchar END_DILITHIUM_LEVEL5_PRIV = "-----END DILITHIUM_LEVEL5 PRIVATE KEY-----";
  21095. #endif /* HAVE_DILITHIUM */
  21096. #if defined(HAVE_SPHINCS)
  21097. wcchar BEGIN_SPHINCS_FAST_LEVEL1_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21098. wcchar END_SPHINCS_FAST_LEVEL1_PRIV = "-----END SPHINCS_FAST_LEVEL1 PRIVATE KEY-----";
  21099. wcchar BEGIN_SPHINCS_FAST_LEVEL3_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21100. wcchar END_SPHINCS_FAST_LEVEL3_PRIV = "-----END SPHINCS_FAST_LEVEL3 PRIVATE KEY-----";
  21101. wcchar BEGIN_SPHINCS_FAST_LEVEL5_PRIV = "-----BEGIN SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21102. wcchar END_SPHINCS_FAST_LEVEL5_PRIV = "-----END SPHINCS_FAST_LEVEL5 PRIVATE KEY-----";
  21103. wcchar BEGIN_SPHINCS_SMALL_LEVEL1_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21104. wcchar END_SPHINCS_SMALL_LEVEL1_PRIV = "-----END SPHINCS_SMALL_LEVEL1 PRIVATE KEY-----";
  21105. wcchar BEGIN_SPHINCS_SMALL_LEVEL3_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21106. wcchar END_SPHINCS_SMALL_LEVEL3_PRIV = "-----END SPHINCS_SMALL_LEVEL3 PRIVATE KEY-----";
  21107. wcchar BEGIN_SPHINCS_SMALL_LEVEL5_PRIV = "-----BEGIN SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21108. wcchar END_SPHINCS_SMALL_LEVEL5_PRIV = "-----END SPHINCS_SMALL_LEVEL5 PRIVATE KEY-----";
  21109. #endif /* HAVE_SPHINCS */
  21110. #endif /* HAVE_PQC */
  21111. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  21112. "-----END X509 CRL-----");
  21113. #ifdef WOLFSSL_PEM_TO_DER
  21114. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  21115. const char* endOfLine)
  21116. {
  21117. /* eat end of line characters */
  21118. while (line < endOfLine &&
  21119. (line[0] == '\r' || line[0] == '\n')) {
  21120. line++;
  21121. }
  21122. return line;
  21123. }
  21124. #endif
  21125. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  21126. {
  21127. int ret = BAD_FUNC_ARG;
  21128. switch (type) {
  21129. case CA_TYPE: /* same as below */
  21130. case TRUSTED_PEER_TYPE:
  21131. case CERT_TYPE:
  21132. if (header) *header = BEGIN_CERT;
  21133. if (footer) *footer = END_CERT;
  21134. ret = 0;
  21135. break;
  21136. case CRL_TYPE:
  21137. if (header) *header = BEGIN_X509_CRL;
  21138. if (footer) *footer = END_X509_CRL;
  21139. ret = 0;
  21140. break;
  21141. #ifndef NO_DH
  21142. case DH_PARAM_TYPE:
  21143. if (header) *header = BEGIN_DH_PARAM;
  21144. if (footer) *footer = END_DH_PARAM;
  21145. ret = 0;
  21146. break;
  21147. case X942_PARAM_TYPE:
  21148. if (header) *header = BEGIN_X942_PARAM;
  21149. if (footer) *footer = END_X942_PARAM;
  21150. ret = 0;
  21151. break;
  21152. #endif
  21153. #ifndef NO_DSA
  21154. case DSA_PARAM_TYPE:
  21155. if (header) *header = BEGIN_DSA_PARAM;
  21156. if (footer) *footer = END_DSA_PARAM;
  21157. ret = 0;
  21158. break;
  21159. #endif
  21160. #ifdef WOLFSSL_CERT_REQ
  21161. case CERTREQ_TYPE:
  21162. if (header) *header = BEGIN_CERT_REQ;
  21163. if (footer) *footer = END_CERT_REQ;
  21164. ret = 0;
  21165. break;
  21166. #endif
  21167. #ifndef NO_DSA
  21168. case DSA_TYPE:
  21169. case DSA_PRIVATEKEY_TYPE:
  21170. if (header) *header = BEGIN_DSA_PRIV;
  21171. if (footer) *footer = END_DSA_PRIV;
  21172. ret = 0;
  21173. break;
  21174. #endif
  21175. #ifdef HAVE_ECC
  21176. case ECC_TYPE:
  21177. case ECC_PRIVATEKEY_TYPE:
  21178. if (header) *header = BEGIN_EC_PRIV;
  21179. if (footer) *footer = END_EC_PRIV;
  21180. ret = 0;
  21181. break;
  21182. #ifdef OPENSSL_EXTRA
  21183. case ECC_PARAM_TYPE:
  21184. if (header) *header = BEGIN_EC_PARAM;
  21185. if (footer) *footer = END_EC_PARAM;
  21186. ret = 0;
  21187. break;
  21188. #endif
  21189. #endif
  21190. case RSA_TYPE:
  21191. case PRIVATEKEY_TYPE:
  21192. if (header) *header = BEGIN_RSA_PRIV;
  21193. if (footer) *footer = END_RSA_PRIV;
  21194. ret = 0;
  21195. break;
  21196. #ifdef HAVE_ED25519
  21197. case ED25519_TYPE:
  21198. #endif
  21199. #ifdef HAVE_ED448
  21200. case ED448_TYPE:
  21201. #endif
  21202. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21203. case EDDSA_PRIVATEKEY_TYPE:
  21204. if (header) *header = BEGIN_EDDSA_PRIV;
  21205. if (footer) *footer = END_EDDSA_PRIV;
  21206. ret = 0;
  21207. break;
  21208. #endif
  21209. #ifdef HAVE_PQC
  21210. #ifdef HAVE_FALCON
  21211. case FALCON_LEVEL1_TYPE:
  21212. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  21213. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  21214. ret = 0;
  21215. break;
  21216. case FALCON_LEVEL5_TYPE:
  21217. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  21218. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  21219. ret = 0;
  21220. break;
  21221. #endif /* HAVE_FALCON */
  21222. #ifdef HAVE_DILITHIUM
  21223. case DILITHIUM_LEVEL2_TYPE:
  21224. if (header) *header = BEGIN_DILITHIUM_LEVEL2_PRIV;
  21225. if (footer) *footer = END_DILITHIUM_LEVEL2_PRIV;
  21226. ret = 0;
  21227. break;
  21228. case DILITHIUM_LEVEL3_TYPE:
  21229. if (header) *header = BEGIN_DILITHIUM_LEVEL3_PRIV;
  21230. if (footer) *footer = END_DILITHIUM_LEVEL3_PRIV;
  21231. ret = 0;
  21232. break;
  21233. case DILITHIUM_LEVEL5_TYPE:
  21234. if (header) *header = BEGIN_DILITHIUM_LEVEL5_PRIV;
  21235. if (footer) *footer = END_DILITHIUM_LEVEL5_PRIV;
  21236. ret = 0;
  21237. break;
  21238. #endif /* HAVE_DILITHIUM */
  21239. #ifdef HAVE_SPHINCS
  21240. case SPHINCS_FAST_LEVEL1_TYPE:
  21241. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL1_PRIV;
  21242. if (footer) *footer = END_SPHINCS_FAST_LEVEL1_PRIV;
  21243. ret = 0;
  21244. break;
  21245. case SPHINCS_FAST_LEVEL3_TYPE:
  21246. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL3_PRIV;
  21247. if (footer) *footer = END_SPHINCS_FAST_LEVEL3_PRIV;
  21248. ret = 0;
  21249. break;
  21250. case SPHINCS_FAST_LEVEL5_TYPE:
  21251. if (header) *header = BEGIN_SPHINCS_FAST_LEVEL5_PRIV;
  21252. if (footer) *footer = END_SPHINCS_FAST_LEVEL5_PRIV;
  21253. ret = 0;
  21254. break;
  21255. case SPHINCS_SMALL_LEVEL1_TYPE:
  21256. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL1_PRIV;
  21257. if (footer) *footer = END_SPHINCS_SMALL_LEVEL1_PRIV;
  21258. ret = 0;
  21259. break;
  21260. case SPHINCS_SMALL_LEVEL3_TYPE:
  21261. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL3_PRIV;
  21262. if (footer) *footer = END_SPHINCS_SMALL_LEVEL3_PRIV;
  21263. ret = 0;
  21264. break;
  21265. case SPHINCS_SMALL_LEVEL5_TYPE:
  21266. if (header) *header = BEGIN_SPHINCS_SMALL_LEVEL5_PRIV;
  21267. if (footer) *footer = END_SPHINCS_SMALL_LEVEL5_PRIV;
  21268. ret = 0;
  21269. break;
  21270. #endif /* HAVE_SPHINCS */
  21271. #endif /* HAVE_PQC */
  21272. case PUBLICKEY_TYPE:
  21273. case ECC_PUBLICKEY_TYPE:
  21274. if (header) *header = BEGIN_PUB_KEY;
  21275. if (footer) *footer = END_PUB_KEY;
  21276. ret = 0;
  21277. break;
  21278. case RSA_PUBLICKEY_TYPE:
  21279. if (header) *header = BEGIN_RSA_PUB;
  21280. if (footer) *footer = END_RSA_PUB;
  21281. ret = 0;
  21282. break;
  21283. #ifndef NO_DH
  21284. case DH_PRIVATEKEY_TYPE:
  21285. #endif
  21286. case PKCS8_PRIVATEKEY_TYPE:
  21287. if (header) *header = BEGIN_PRIV_KEY;
  21288. if (footer) *footer = END_PRIV_KEY;
  21289. ret = 0;
  21290. break;
  21291. case PKCS8_ENC_PRIVATEKEY_TYPE:
  21292. if (header) *header = BEGIN_ENC_PRIV_KEY;
  21293. if (footer) *footer = END_ENC_PRIV_KEY;
  21294. ret = 0;
  21295. break;
  21296. default:
  21297. break;
  21298. }
  21299. return ret;
  21300. }
  21301. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21302. static wcchar kProcTypeHeader = "Proc-Type";
  21303. static wcchar kDecInfoHeader = "DEK-Info";
  21304. #ifdef WOLFSSL_PEM_TO_DER
  21305. #ifndef NO_DES3
  21306. static wcchar kEncTypeDes = "DES-CBC";
  21307. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  21308. #endif
  21309. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21310. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  21311. #endif
  21312. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21313. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  21314. #endif
  21315. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21316. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  21317. #endif
  21318. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  21319. {
  21320. int ret = 0;
  21321. if (info == NULL || cipherInfo == NULL)
  21322. return BAD_FUNC_ARG;
  21323. /* determine cipher information */
  21324. #ifndef NO_DES3
  21325. if (XSTRCMP(cipherInfo, kEncTypeDes) == 0) {
  21326. info->cipherType = WC_CIPHER_DES;
  21327. info->keySz = DES_KEY_SIZE;
  21328. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  21329. * block size. */
  21330. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21331. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21332. #else
  21333. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21334. #endif
  21335. }
  21336. else if (XSTRCMP(cipherInfo, kEncTypeDes3) == 0) {
  21337. info->cipherType = WC_CIPHER_DES3;
  21338. info->keySz = DES3_KEY_SIZE;
  21339. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  21340. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  21341. #else
  21342. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  21343. #endif
  21344. }
  21345. else
  21346. #endif /* !NO_DES3 */
  21347. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  21348. if (XSTRCMP(cipherInfo, kEncTypeAesCbc128) == 0) {
  21349. info->cipherType = WC_CIPHER_AES_CBC;
  21350. info->keySz = AES_128_KEY_SIZE;
  21351. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21352. }
  21353. else
  21354. #endif
  21355. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  21356. if (XSTRCMP(cipherInfo, kEncTypeAesCbc192) == 0) {
  21357. info->cipherType = WC_CIPHER_AES_CBC;
  21358. info->keySz = AES_192_KEY_SIZE;
  21359. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21360. }
  21361. else
  21362. #endif
  21363. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  21364. if (XSTRCMP(cipherInfo, kEncTypeAesCbc256) == 0) {
  21365. info->cipherType = WC_CIPHER_AES_CBC;
  21366. info->keySz = AES_256_KEY_SIZE;
  21367. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  21368. }
  21369. else
  21370. #endif
  21371. {
  21372. ret = NOT_COMPILED_IN;
  21373. }
  21374. return ret;
  21375. }
  21376. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  21377. size_t bufSz)
  21378. {
  21379. int err = 0;
  21380. const char* bufferStart;
  21381. const char* bufferEnd;
  21382. char* line;
  21383. if (info == NULL || pBuffer == NULL || bufSz == 0)
  21384. return BAD_FUNC_ARG;
  21385. bufferStart = *pBuffer;
  21386. bufferEnd = bufferStart + bufSz;
  21387. /* find encrypted info marker */
  21388. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  21389. min((word32)bufSz, PEM_LINE_LEN));
  21390. if (line != NULL) {
  21391. word32 lineSz;
  21392. char* finish;
  21393. char* start;
  21394. word32 startSz;
  21395. const char* newline = NULL;
  21396. if (line >= bufferEnd) {
  21397. return BUFFER_E;
  21398. }
  21399. lineSz = (word32)(bufferEnd - line);
  21400. /* find DEC-Info marker */
  21401. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  21402. if (start == NULL)
  21403. return BUFFER_E;
  21404. /* skip dec-info and ": " */
  21405. start += XSTRLEN(kDecInfoHeader);
  21406. if (start >= bufferEnd)
  21407. return BUFFER_E;
  21408. if (start[0] == ':') {
  21409. start++;
  21410. if (start >= bufferEnd)
  21411. return BUFFER_E;
  21412. }
  21413. if (start[0] == ' ')
  21414. start++;
  21415. startSz = (word32)(bufferEnd - start);
  21416. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  21417. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  21418. word32 finishSz;
  21419. if (finish >= bufferEnd) {
  21420. return BUFFER_E;
  21421. }
  21422. finishSz = (word32)(bufferEnd - finish);
  21423. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  21424. /* get cipher name */
  21425. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  21426. return BUFFER_E;
  21427. if (XMEMCPY(info->name, start, (size_t)(finish - start)) == NULL)
  21428. return BUFFER_E;
  21429. info->name[finish - start] = '\0'; /* null term */
  21430. /* populate info */
  21431. err = wc_EncryptedInfoGet(info, info->name);
  21432. if (err != 0)
  21433. return err;
  21434. /* get IV */
  21435. if (finishSz < info->ivSz + 1)
  21436. return BUFFER_E;
  21437. if (newline == NULL) {
  21438. newline = XSTRNSTR(finish, "\n", min(finishSz,
  21439. PEM_LINE_LEN));
  21440. }
  21441. if ((newline != NULL) && (newline > finish)) {
  21442. finish++;
  21443. info->ivSz = (word32)(newline - finish);
  21444. if (info->ivSz > IV_SZ)
  21445. return BUFFER_E;
  21446. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  21447. return BUFFER_E;
  21448. info->set = 1;
  21449. }
  21450. else
  21451. return BUFFER_E;
  21452. }
  21453. else
  21454. return BUFFER_E;
  21455. /* eat end of line characters */
  21456. newline = SkipEndOfLineChars(newline, bufferEnd);
  21457. /* return new headerEnd */
  21458. *pBuffer = newline;
  21459. }
  21460. return err;
  21461. }
  21462. #endif /* WOLFSSL_PEM_TO_DER */
  21463. #ifdef WOLFSSL_DER_TO_PEM
  21464. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  21465. {
  21466. if (cipherInfo != NULL) {
  21467. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  21468. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  21469. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  21470. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  21471. /* strncat's src length needs to include the NULL */
  21472. XSTRNCAT(dest, kProcTypeHeader, 10);
  21473. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  21474. XSTRNCAT(dest, kDecInfoHeader, 9);
  21475. XSTRNCAT(dest, ": ", 3);
  21476. XSTRNCAT(dest, cipherInfo, (size_t)destSz - XSTRLEN(dest) - 1);
  21477. XSTRNCAT(dest, "\n\n", 4);
  21478. }
  21479. }
  21480. return 0;
  21481. }
  21482. #endif /* WOLFSSL_DER_TO_PEM */
  21483. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21484. #ifdef WOLFSSL_DER_TO_PEM
  21485. /* Used for compatibility API */
  21486. WOLFSSL_ABI
  21487. int wc_DerToPem(const byte* der, word32 derSz,
  21488. byte* output, word32 outSz, int type)
  21489. {
  21490. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  21491. }
  21492. /* convert der buffer to pem into output, can't do inplace, der and output
  21493. need to be different */
  21494. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  21495. byte *cipher_info, int type)
  21496. {
  21497. const char* headerStr = NULL;
  21498. const char* footerStr = NULL;
  21499. #ifdef WOLFSSL_SMALL_STACK
  21500. char* header = NULL;
  21501. char* footer = NULL;
  21502. #else
  21503. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  21504. char footer[MAX_X509_HEADER_SZ];
  21505. #endif
  21506. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  21507. int footerLen = MAX_X509_HEADER_SZ;
  21508. int i;
  21509. int err;
  21510. int outLen; /* return length or error */
  21511. (void)cipher_info;
  21512. if (der == output) /* no in place conversion */
  21513. return BAD_FUNC_ARG;
  21514. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  21515. if (err != 0)
  21516. return err;
  21517. #ifdef WOLFSSL_SMALL_STACK
  21518. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21519. if (header == NULL)
  21520. return MEMORY_E;
  21521. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21522. if (footer == NULL) {
  21523. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21524. return MEMORY_E;
  21525. }
  21526. #endif
  21527. /* build header and footer based on type */
  21528. XSTRNCPY(header, headerStr, (size_t)headerLen - 1);
  21529. header[headerLen - 2] = 0;
  21530. XSTRNCPY(footer, footerStr, (size_t)footerLen - 1);
  21531. footer[footerLen - 2] = 0;
  21532. /* add new line to end */
  21533. XSTRNCAT(header, "\n", 2);
  21534. XSTRNCAT(footer, "\n", 2);
  21535. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21536. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  21537. if (err != 0) {
  21538. #ifdef WOLFSSL_SMALL_STACK
  21539. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21540. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21541. #endif
  21542. return err;
  21543. }
  21544. #endif
  21545. headerLen = (int)XSTRLEN(header);
  21546. footerLen = (int)XSTRLEN(footer);
  21547. /* if null output and 0 size passed in then return size needed */
  21548. if (!output && outSz == 0) {
  21549. #ifdef WOLFSSL_SMALL_STACK
  21550. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21551. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21552. #endif
  21553. outLen = 0;
  21554. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  21555. != LENGTH_ONLY_E) {
  21556. WOLFSSL_ERROR_VERBOSE(err);
  21557. return err;
  21558. }
  21559. return headerLen + footerLen + outLen;
  21560. }
  21561. if (!der || !output) {
  21562. #ifdef WOLFSSL_SMALL_STACK
  21563. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21564. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21565. #endif
  21566. return BAD_FUNC_ARG;
  21567. }
  21568. /* don't even try if outSz too short */
  21569. if (outSz < (word32)headerLen + (word32)footerLen + derSz) {
  21570. #ifdef WOLFSSL_SMALL_STACK
  21571. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21572. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21573. #endif
  21574. return BAD_FUNC_ARG;
  21575. }
  21576. /* header */
  21577. XMEMCPY(output, header, (size_t)headerLen);
  21578. i = headerLen;
  21579. #ifdef WOLFSSL_SMALL_STACK
  21580. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21581. #endif
  21582. /* body */
  21583. outLen = (int)outSz - (headerLen + footerLen); /* input to Base64_Encode */
  21584. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  21585. #ifdef WOLFSSL_SMALL_STACK
  21586. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21587. #endif
  21588. WOLFSSL_ERROR_VERBOSE(err);
  21589. return err;
  21590. }
  21591. i += outLen;
  21592. /* footer */
  21593. if ( (i + footerLen) > (int)outSz) {
  21594. #ifdef WOLFSSL_SMALL_STACK
  21595. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21596. #endif
  21597. return BAD_FUNC_ARG;
  21598. }
  21599. XMEMCPY(output + i, footer, (size_t)footerLen);
  21600. #ifdef WOLFSSL_SMALL_STACK
  21601. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  21602. #endif
  21603. return outLen + headerLen + footerLen;
  21604. }
  21605. #endif /* WOLFSSL_DER_TO_PEM */
  21606. #ifdef WOLFSSL_PEM_TO_DER
  21607. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  21608. info->consumed tracks of PEM bytes consumed in case multiple parts */
  21609. int PemToDer(const unsigned char* buff, long longSz, int type,
  21610. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21611. {
  21612. const char* header = NULL;
  21613. const char* footer = NULL;
  21614. const char* headerEnd;
  21615. const char* footerEnd;
  21616. const char* consumedEnd;
  21617. const char* bufferEnd = (const char*)(buff + longSz);
  21618. long neededSz;
  21619. int ret = 0;
  21620. int sz = (int)longSz;
  21621. int encrypted_key = 0;
  21622. DerBuffer* der;
  21623. word32 algId = 0;
  21624. word32 idx;
  21625. #ifdef OPENSSL_EXTRA
  21626. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21627. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  21628. #endif
  21629. WOLFSSL_ENTER("PemToDer");
  21630. /* get PEM header and footer based on type */
  21631. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  21632. if (ret != 0)
  21633. return ret;
  21634. /* map header if not found for type */
  21635. for (;;) {
  21636. headerEnd = XSTRNSTR((char*)buff, header, (word32)sz);
  21637. if (headerEnd) {
  21638. break;
  21639. }
  21640. if (type == PRIVATEKEY_TYPE) {
  21641. if (header == BEGIN_RSA_PRIV) {
  21642. header = BEGIN_PRIV_KEY;
  21643. footer = END_PRIV_KEY;
  21644. }
  21645. else if (header == BEGIN_PRIV_KEY) {
  21646. header = BEGIN_ENC_PRIV_KEY;
  21647. footer = END_ENC_PRIV_KEY;
  21648. }
  21649. #ifdef HAVE_ECC
  21650. else if (header == BEGIN_ENC_PRIV_KEY) {
  21651. header = BEGIN_EC_PRIV;
  21652. footer = END_EC_PRIV;
  21653. }
  21654. else if (header == BEGIN_EC_PRIV) {
  21655. header = BEGIN_DSA_PRIV;
  21656. footer = END_DSA_PRIV;
  21657. }
  21658. #endif
  21659. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  21660. #ifdef HAVE_ECC
  21661. else if (header == BEGIN_DSA_PRIV) {
  21662. #else
  21663. else if (header == BEGIN_ENC_PRIV_KEY) {
  21664. #endif
  21665. header = BEGIN_EDDSA_PRIV;
  21666. footer = END_EDDSA_PRIV;
  21667. }
  21668. #endif
  21669. else {
  21670. #ifdef WOLF_PRIVATE_KEY_ID
  21671. /* allow loading a public key for use with crypto or PK callbacks */
  21672. type = PUBLICKEY_TYPE;
  21673. header = BEGIN_PUB_KEY;
  21674. footer = END_PUB_KEY;
  21675. #else
  21676. break;
  21677. #endif
  21678. }
  21679. }
  21680. else if (type == PUBLICKEY_TYPE) {
  21681. if (header == BEGIN_PUB_KEY) {
  21682. header = BEGIN_RSA_PUB;
  21683. footer = END_RSA_PUB;
  21684. }
  21685. else {
  21686. break;
  21687. }
  21688. }
  21689. #if defined(HAVE_ECC) && defined(OPENSSL_EXTRA)
  21690. else if (type == ECC_PARAM_TYPE) {
  21691. if (header == BEGIN_EC_PARAM) {
  21692. header = BEGIN_EC_PARAM;
  21693. footer = END_EC_PARAM;
  21694. }
  21695. else {
  21696. break;
  21697. }
  21698. }
  21699. #endif
  21700. #ifdef HAVE_CRL
  21701. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  21702. header = BEGIN_X509_CRL;
  21703. footer = END_X509_CRL;
  21704. }
  21705. #endif
  21706. else {
  21707. break;
  21708. }
  21709. }
  21710. if (!headerEnd) {
  21711. #ifdef OPENSSL_EXTRA
  21712. if (type == PRIVATEKEY_TYPE) {
  21713. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  21714. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  21715. if (headerEnd) {
  21716. const char* beginEnd;
  21717. int endLen;
  21718. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  21719. if (beginEnd >= (char*)buff + sz) {
  21720. return BUFFER_E;
  21721. }
  21722. /* back up to BEGIN_PRIV_KEY_PREFIX */
  21723. while (headerEnd > (char*)buff &&
  21724. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21725. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  21726. *headerEnd != '\n') {
  21727. headerEnd--;
  21728. }
  21729. if (headerEnd <= (char*)buff ||
  21730. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  21731. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  21732. beginEnd - headerEnd > PEM_LINE_LEN) {
  21733. WOLFSSL_MSG("Couldn't find PEM header");
  21734. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21735. return ASN_NO_PEM_HEADER;
  21736. }
  21737. /* headerEnd now points to beginning of header */
  21738. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  21739. beginBuf[beginEnd - headerEnd] = '\0';
  21740. /* look for matching footer */
  21741. footer = XSTRNSTR(beginEnd,
  21742. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  21743. (unsigned int)((char*)buff + sz - beginEnd));
  21744. if (!footer) {
  21745. WOLFSSL_MSG("Couldn't find PEM footer");
  21746. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21747. return ASN_NO_PEM_HEADER;
  21748. }
  21749. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  21750. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  21751. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  21752. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  21753. WOLFSSL_MSG("Unexpected footer for PEM");
  21754. return BUFFER_E;
  21755. }
  21756. endLen = (unsigned int)(beginEnd - headerEnd -
  21757. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  21758. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  21759. XMEMCPY(endBuf, footer, endLen);
  21760. endBuf[endLen] = '\0';
  21761. header = beginBuf;
  21762. footer = endBuf;
  21763. headerEnd = beginEnd;
  21764. }
  21765. }
  21766. if (!headerEnd) {
  21767. WOLFSSL_MSG("Couldn't find PEM header");
  21768. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  21769. return ASN_NO_PEM_HEADER;
  21770. }
  21771. #else
  21772. WOLFSSL_MSG("Couldn't find PEM header");
  21773. return ASN_NO_PEM_HEADER;
  21774. #endif
  21775. } else {
  21776. headerEnd += XSTRLEN(header);
  21777. }
  21778. /* eat end of line characters */
  21779. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  21780. if (keyFormat) {
  21781. /* keyFormat is Key_Sum enum */
  21782. if (type == PRIVATEKEY_TYPE) {
  21783. #ifndef NO_RSA
  21784. if (header == BEGIN_RSA_PRIV)
  21785. *keyFormat = RSAk;
  21786. #endif
  21787. #ifdef HAVE_ECC
  21788. if (header == BEGIN_EC_PRIV)
  21789. *keyFormat = ECDSAk;
  21790. #endif
  21791. #ifndef NO_DSA
  21792. if (header == BEGIN_DSA_PRIV)
  21793. *keyFormat = DSAk;
  21794. #endif
  21795. }
  21796. #ifdef WOLF_PRIVATE_KEY_ID
  21797. else if (type == PUBLICKEY_TYPE) {
  21798. #ifndef NO_RSA
  21799. if (header == BEGIN_RSA_PUB)
  21800. *keyFormat = RSAk;
  21801. #endif
  21802. }
  21803. #endif
  21804. }
  21805. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21806. if (info) {
  21807. ret = wc_EncryptedInfoParse(info, &headerEnd,
  21808. (size_t)(bufferEnd - headerEnd));
  21809. if (ret < 0)
  21810. return ret;
  21811. if (info->set)
  21812. encrypted_key = 1;
  21813. }
  21814. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21815. /* find footer */
  21816. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  21817. sz - headerEnd));
  21818. if (!footerEnd) {
  21819. if (info)
  21820. info->consumed = longSz; /* No more certs if no footer */
  21821. return BUFFER_E;
  21822. }
  21823. consumedEnd = footerEnd + XSTRLEN(footer);
  21824. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  21825. /* eat end of line characters */
  21826. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  21827. /* skip possible null term */
  21828. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  21829. consumedEnd++;
  21830. }
  21831. if (info)
  21832. info->consumed = (long)(consumedEnd - (const char*)buff);
  21833. /* set up der buffer */
  21834. neededSz = (long)(footerEnd - headerEnd);
  21835. if (neededSz > sz || neededSz <= 0)
  21836. return BUFFER_E;
  21837. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  21838. if (ret < 0) {
  21839. return ret;
  21840. }
  21841. der = *pDer;
  21842. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  21843. der->buffer, &der->length) < 0) {
  21844. WOLFSSL_ERROR(BUFFER_E);
  21845. return BUFFER_E;
  21846. }
  21847. if ((header == BEGIN_PRIV_KEY
  21848. #ifdef OPENSSL_EXTRA
  21849. || header == beginBuf
  21850. #endif
  21851. #ifdef HAVE_ECC
  21852. || header == BEGIN_EC_PRIV
  21853. #endif
  21854. ) && !encrypted_key)
  21855. {
  21856. /* detect pkcs8 key and get alg type */
  21857. /* keep PKCS8 header */
  21858. idx = 0;
  21859. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  21860. if (ret > 0) {
  21861. if (keyFormat)
  21862. *keyFormat = (int)algId;
  21863. }
  21864. else {
  21865. /* ignore failure here and assume key is not pkcs8 wrapped */
  21866. }
  21867. return 0;
  21868. }
  21869. #ifdef WOLFSSL_ENCRYPTED_KEYS
  21870. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  21871. int passwordSz = NAME_SZ;
  21872. #ifdef WOLFSSL_SMALL_STACK
  21873. char* password = NULL;
  21874. #else
  21875. char password[NAME_SZ];
  21876. #endif
  21877. if (!info || !info->passwd_cb) {
  21878. WOLFSSL_MSG("No password callback set");
  21879. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21880. return NO_PASSWORD;
  21881. }
  21882. #ifdef WOLFSSL_SMALL_STACK
  21883. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  21884. if (password == NULL) {
  21885. return MEMORY_E;
  21886. }
  21887. #endif
  21888. /* get password */
  21889. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  21890. info->passwd_userdata);
  21891. if (ret >= 0) {
  21892. passwordSz = ret;
  21893. #ifdef WOLFSSL_CHECK_MEM_ZERO
  21894. wc_MemZero_Add("PEM password", password, passwordSz);
  21895. #endif
  21896. /* convert and adjust length */
  21897. if (header == BEGIN_ENC_PRIV_KEY) {
  21898. #ifndef NO_PWDBASED
  21899. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  21900. password, passwordSz);
  21901. if (ret > 0) {
  21902. /* update length by decrypted content */
  21903. der->length = (word32)ret;
  21904. idx = 0;
  21905. /* detect pkcs8 key and get alg type */
  21906. /* keep PKCS8 header */
  21907. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  21908. &algId);
  21909. if (ret >= 0) {
  21910. if (keyFormat)
  21911. *keyFormat = (int)algId;
  21912. ret = 0;
  21913. }
  21914. }
  21915. #else
  21916. WOLFSSL_ERROR_VERBOSE(NOT_COMPILED_IN);
  21917. ret = NOT_COMPILED_IN;
  21918. #endif
  21919. }
  21920. /* decrypt the key */
  21921. else {
  21922. if (passwordSz == 0) {
  21923. /* The key is encrypted but does not have a password */
  21924. WOLFSSL_MSG("No password for encrypted key");
  21925. WOLFSSL_ERROR_VERBOSE(NO_PASSWORD);
  21926. ret = NO_PASSWORD;
  21927. }
  21928. else {
  21929. #if ((defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3)) || \
  21930. (!defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21931. defined(HAVE_AES_DECRYPT))) && \
  21932. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  21933. int padVal = 0;
  21934. #endif
  21935. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  21936. (byte*)password, passwordSz, WC_MD5);
  21937. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  21938. #ifndef NO_DES3
  21939. if (info->cipherType == WC_CIPHER_DES3) {
  21940. /* Assuming there is padding:
  21941. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  21942. * (der->length % DES_BLOCK_SIZE) != 0)
  21943. * and assuming the last value signifies the number of
  21944. * padded bytes IE if last value is 0x08 then there are
  21945. * 8 bytes of padding:
  21946. * padVal = der->buffer[der->length-1];
  21947. * then strip this padding before proceeding:
  21948. * der->length -= padVal;
  21949. */
  21950. if (der->length > DES_BLOCK_SIZE &&
  21951. (der->length % DES_BLOCK_SIZE) != 0) {
  21952. padVal = der->buffer[der->length-1];
  21953. if (padVal < DES_BLOCK_SIZE) {
  21954. der->length -= (word32)padVal;
  21955. }
  21956. }
  21957. }
  21958. #endif /* !NO_DES3 */
  21959. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && \
  21960. defined(HAVE_AES_DECRYPT)
  21961. if (info->cipherType == WC_CIPHER_AES_CBC) {
  21962. if (der->length > AES_BLOCK_SIZE) {
  21963. padVal = der->buffer[der->length-1];
  21964. if (padVal <= AES_BLOCK_SIZE) {
  21965. der->length -= (word32)padVal;
  21966. }
  21967. }
  21968. }
  21969. #endif
  21970. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  21971. }
  21972. }
  21973. #ifdef OPENSSL_EXTRA
  21974. if (ret) {
  21975. PEMerr(0, PEM_R_BAD_DECRYPT);
  21976. }
  21977. #endif
  21978. ForceZero(password, (word32)passwordSz);
  21979. }
  21980. #ifdef OPENSSL_EXTRA
  21981. else {
  21982. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  21983. }
  21984. #endif
  21985. #ifdef WOLFSSL_SMALL_STACK
  21986. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  21987. #elif defined(WOLFSSL_CHECK_MEM_ZERO)
  21988. wc_MemZero_Check(password, NAME_SZ);
  21989. #endif
  21990. }
  21991. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  21992. return ret;
  21993. }
  21994. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  21995. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  21996. {
  21997. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  21998. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  21999. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  22000. DerBuffer* der = *pDer;
  22001. /* if a PKCS8 key header exists remove it */
  22002. ret = ToTraditional(der->buffer, der->length);
  22003. if (ret > 0) {
  22004. der->length = (word32)ret;
  22005. }
  22006. ret = 0; /* ignore error removing PKCS8 header */
  22007. }
  22008. #endif
  22009. return ret;
  22010. }
  22011. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22012. /* our KeyPemToDer password callback, password in userData */
  22013. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  22014. {
  22015. (void)rw;
  22016. if (userdata == NULL)
  22017. return 0;
  22018. XSTRNCPY(passwd, (char*)userdata, (size_t)sz);
  22019. return (int)min((word32)sz, (word32)XSTRLEN((char*)userdata));
  22020. }
  22021. #endif
  22022. /* Return bytes written to buff or < 0 for error */
  22023. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  22024. unsigned char* buff, int buffSz, const char* pass)
  22025. {
  22026. int ret;
  22027. DerBuffer* der = NULL;
  22028. #ifdef WOLFSSL_SMALL_STACK
  22029. EncryptedInfo* info = NULL;
  22030. #else
  22031. EncryptedInfo info[1];
  22032. #endif
  22033. WOLFSSL_ENTER("wc_KeyPemToDer");
  22034. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22035. WOLFSSL_MSG("Bad pem der args");
  22036. return BAD_FUNC_ARG;
  22037. }
  22038. #ifdef WOLFSSL_SMALL_STACK
  22039. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  22040. DYNAMIC_TYPE_ENCRYPTEDINFO);
  22041. if (info == NULL)
  22042. return MEMORY_E;
  22043. #endif
  22044. XMEMSET(info, 0, sizeof(EncryptedInfo));
  22045. #ifdef WOLFSSL_ENCRYPTED_KEYS
  22046. info->passwd_cb = KeyPemToDerPassCb;
  22047. info->passwd_userdata = (void*)pass;
  22048. #else
  22049. (void)pass;
  22050. #endif
  22051. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  22052. #ifdef WOLFSSL_SMALL_STACK
  22053. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  22054. #endif
  22055. if (ret < 0 || der == NULL) {
  22056. WOLFSSL_MSG("Bad Pem To Der");
  22057. }
  22058. else if (buff == NULL) {
  22059. WOLFSSL_MSG("Return needed der buff length");
  22060. ret = (int)der->length;
  22061. }
  22062. else if (der->length <= (word32)buffSz) {
  22063. XMEMCPY(buff, der->buffer, der->length);
  22064. ret = (int)der->length;
  22065. }
  22066. else {
  22067. WOLFSSL_MSG("Bad der length");
  22068. ret = BAD_FUNC_ARG;
  22069. }
  22070. FreeDer(&der);
  22071. return ret;
  22072. }
  22073. /* Return bytes written to buff or < 0 for error */
  22074. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  22075. unsigned char* buff, int buffSz, int type)
  22076. {
  22077. int ret;
  22078. DerBuffer* der = NULL;
  22079. WOLFSSL_ENTER("wc_CertPemToDer");
  22080. if (pem == NULL || buff == NULL || buffSz <= 0) {
  22081. WOLFSSL_MSG("Bad pem der args");
  22082. return BAD_FUNC_ARG;
  22083. }
  22084. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  22085. WOLFSSL_MSG("Bad cert type");
  22086. return BAD_FUNC_ARG;
  22087. }
  22088. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  22089. if (ret < 0 || der == NULL) {
  22090. WOLFSSL_MSG("Bad Pem To Der");
  22091. }
  22092. else {
  22093. if (der->length <= (word32)buffSz) {
  22094. XMEMCPY(buff, der->buffer, der->length);
  22095. ret = (int)der->length;
  22096. }
  22097. else {
  22098. WOLFSSL_MSG("Bad der length");
  22099. ret = BAD_FUNC_ARG;
  22100. }
  22101. }
  22102. FreeDer(&der);
  22103. return ret;
  22104. }
  22105. #endif /* WOLFSSL_PEM_TO_DER */
  22106. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  22107. #ifdef WOLFSSL_PEM_TO_DER
  22108. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22109. /* Return bytes written to buff, needed buff size if buff is NULL, or less than
  22110. zero for error */
  22111. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  22112. unsigned char* buff, int buffSz)
  22113. {
  22114. int ret;
  22115. DerBuffer* der = NULL;
  22116. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  22117. if (pem == NULL || (buff != NULL && buffSz <= 0)) {
  22118. WOLFSSL_MSG("Bad pem der args");
  22119. return BAD_FUNC_ARG;
  22120. }
  22121. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  22122. if (ret < 0 || der == NULL) {
  22123. WOLFSSL_MSG("Bad Pem To Der");
  22124. }
  22125. else if (buff == NULL) {
  22126. WOLFSSL_MSG("Return needed der buff length");
  22127. ret = (int)der->length;
  22128. }
  22129. else if (der->length <= (word32)buffSz) {
  22130. XMEMCPY(buff, der->buffer, der->length);
  22131. ret = (int)der->length;
  22132. }
  22133. else {
  22134. WOLFSSL_MSG("Bad der length");
  22135. ret = BAD_FUNC_ARG;
  22136. }
  22137. FreeDer(&der);
  22138. return ret;
  22139. }
  22140. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22141. #endif /* WOLFSSL_PEM_TO_DER */
  22142. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  22143. #ifdef WOLFSSL_CERT_GEN
  22144. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  22145. {
  22146. #ifndef WOLFSSL_SMALL_STACK
  22147. byte staticBuffer[FILE_BUFFER_SIZE];
  22148. #endif
  22149. byte* fileBuf = NULL;
  22150. int ret = 0;
  22151. XFILE file = XBADFILE;
  22152. int dynamic = 0;
  22153. long sz = 0;
  22154. WOLFSSL_ENTER("wc_PemCertToDer");
  22155. if (fileName == NULL) {
  22156. ret = BAD_FUNC_ARG;
  22157. }
  22158. else {
  22159. file = XFOPEN(fileName, "rb");
  22160. if (file == XBADFILE) {
  22161. ret = IO_FAILED_E;
  22162. }
  22163. }
  22164. if (ret == 0) {
  22165. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22166. ret = IO_FAILED_E;
  22167. }
  22168. }
  22169. if (ret == 0) {
  22170. sz = XFTELL(file);
  22171. if (sz <= 0) {
  22172. ret = IO_FAILED_E;
  22173. }
  22174. }
  22175. if (ret == 0) {
  22176. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22177. ret = IO_FAILED_E;
  22178. }
  22179. }
  22180. if (ret == 0) {
  22181. #ifndef WOLFSSL_SMALL_STACK
  22182. if (sz <= (long)sizeof(staticBuffer))
  22183. fileBuf = staticBuffer;
  22184. else
  22185. #endif
  22186. {
  22187. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22188. if (fileBuf == NULL)
  22189. ret = MEMORY_E;
  22190. else
  22191. dynamic = 1;
  22192. }
  22193. }
  22194. if (ret == 0) {
  22195. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22196. ret = IO_FAILED_E;
  22197. }
  22198. else {
  22199. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  22200. }
  22201. }
  22202. if (file != XBADFILE)
  22203. XFCLOSE(file);
  22204. if (dynamic)
  22205. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22206. return ret;
  22207. }
  22208. /* load pem cert from file into der buffer, return der size or error */
  22209. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  22210. {
  22211. int ret;
  22212. DerBuffer* converted = NULL;
  22213. ret = wc_PemCertToDer_ex(fileName, &converted);
  22214. if (ret == 0) {
  22215. if (converted->length < (word32)derSz) {
  22216. XMEMCPY(derBuf, converted->buffer, converted->length);
  22217. ret = (int)converted->length;
  22218. }
  22219. else
  22220. ret = BUFFER_E;
  22221. FreeDer(&converted);
  22222. }
  22223. return ret;
  22224. }
  22225. #endif /* WOLFSSL_CERT_GEN */
  22226. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  22227. /* load pem public key from file into der buffer, return der size or error */
  22228. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  22229. {
  22230. #ifndef WOLFSSL_SMALL_STACK
  22231. byte staticBuffer[FILE_BUFFER_SIZE];
  22232. #endif
  22233. byte* fileBuf = NULL;
  22234. int dynamic = 0;
  22235. int ret = 0;
  22236. long sz = 0;
  22237. XFILE file = XBADFILE;
  22238. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  22239. if (fileName == NULL) {
  22240. ret = BAD_FUNC_ARG;
  22241. }
  22242. else {
  22243. file = XFOPEN(fileName, "rb");
  22244. if (file == XBADFILE) {
  22245. ret = IO_FAILED_E;
  22246. }
  22247. }
  22248. if (ret == 0) {
  22249. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  22250. ret = IO_FAILED_E;
  22251. }
  22252. }
  22253. if (ret == 0) {
  22254. sz = XFTELL(file);
  22255. if (sz <= 0) {
  22256. ret = IO_FAILED_E;
  22257. }
  22258. }
  22259. if (ret == 0) {
  22260. if (XFSEEK(file, 0, XSEEK_SET) != 0) {
  22261. ret = IO_FAILED_E;
  22262. }
  22263. }
  22264. if (ret == 0) {
  22265. #ifndef WOLFSSL_SMALL_STACK
  22266. if (sz <= (long)sizeof(staticBuffer))
  22267. fileBuf = staticBuffer;
  22268. else
  22269. #endif
  22270. {
  22271. fileBuf = (byte*)XMALLOC((size_t)sz, NULL, DYNAMIC_TYPE_FILE);
  22272. if (fileBuf == NULL)
  22273. ret = MEMORY_E;
  22274. else
  22275. dynamic = 1;
  22276. }
  22277. }
  22278. if (ret == 0) {
  22279. if ((size_t)XFREAD(fileBuf, 1, (size_t)sz, file) != (size_t)sz) {
  22280. ret = BUFFER_E;
  22281. }
  22282. else {
  22283. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  22284. 0, NULL, NULL);
  22285. }
  22286. }
  22287. if (file != XBADFILE)
  22288. XFCLOSE(file);
  22289. if (dynamic)
  22290. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  22291. return ret;
  22292. }
  22293. /* load pem public key from file into der buffer, return der size or error */
  22294. int wc_PemPubKeyToDer(const char* fileName,
  22295. unsigned char* derBuf, int derSz)
  22296. {
  22297. int ret;
  22298. DerBuffer* converted = NULL;
  22299. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  22300. if (ret == 0) {
  22301. if (converted->length < (word32)derSz) {
  22302. XMEMCPY(derBuf, converted->buffer, converted->length);
  22303. ret = (int)converted->length;
  22304. }
  22305. else
  22306. ret = BUFFER_E;
  22307. FreeDer(&converted);
  22308. }
  22309. return ret;
  22310. }
  22311. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  22312. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  22313. /* Get public key in DER format from a populated DecodedCert struct.
  22314. *
  22315. * Users must call wc_InitDecodedCert() and wc_ParseCert() before calling
  22316. * this API. wc_InitDecodedCert() accepts a DER/ASN.1 encoded certificate.
  22317. * To convert a PEM cert to DER first use wc_CertPemToDer() before calling
  22318. * wc_InitDecodedCert().
  22319. *
  22320. * cert - populated DecodedCert struct holding X.509 certificate
  22321. * derKey - output buffer to place DER/ASN.1 encoded public key
  22322. * derKeySz [IN/OUT] - size of derKey buffer on input, size of public key
  22323. * on return. If derKey is passed in as NULL, derKeySz
  22324. * will be set to required buffer size for public key
  22325. * and LENGTH_ONLY_E will be returned from function.
  22326. * Returns 0 on success, or negative error code on failure. LENGTH_ONLY_E
  22327. * if derKey is NULL and returning length only.
  22328. */
  22329. int wc_GetPubKeyDerFromCert(struct DecodedCert* cert,
  22330. byte* derKey, word32* derKeySz)
  22331. {
  22332. int ret = 0;
  22333. /* derKey may be NULL to return length only */
  22334. if (cert == NULL || derKeySz == NULL ||
  22335. (derKey != NULL && *derKeySz == 0)) {
  22336. return BAD_FUNC_ARG;
  22337. }
  22338. if (cert->publicKey == NULL) {
  22339. WOLFSSL_MSG("DecodedCert does not contain public key\n");
  22340. return BAD_FUNC_ARG;
  22341. }
  22342. /* if derKey is NULL, return required output buffer size in derKeySz */
  22343. if (derKey == NULL) {
  22344. *derKeySz = cert->pubKeySize;
  22345. ret = LENGTH_ONLY_E;
  22346. }
  22347. if (ret == 0) {
  22348. if (cert->pubKeySize > *derKeySz) {
  22349. WOLFSSL_MSG("Output buffer not large enough for public key DER");
  22350. ret = BAD_FUNC_ARG;
  22351. }
  22352. else {
  22353. XMEMCPY(derKey, cert->publicKey, cert->pubKeySize);
  22354. *derKeySz = cert->pubKeySize;
  22355. }
  22356. }
  22357. return ret;
  22358. }
  22359. #ifdef WOLFSSL_FPKI
  22360. /* Search through list for first matching alt name of the same type
  22361. * If 'current' is null then the search starts at the head of the list
  22362. * otherwise the search starts from the node after 'current' alt name.
  22363. * Returns 0 on success
  22364. */
  22365. static DNS_entry* FindAltName(struct DecodedCert* cert, int nameType,
  22366. DNS_entry* current)
  22367. {
  22368. DNS_entry* entry;
  22369. if (current == NULL) {
  22370. entry = cert->altNames;
  22371. }
  22372. else {
  22373. entry = current->next;
  22374. }
  22375. /* cycle through alt names to check for needed types */
  22376. while (entry != NULL) {
  22377. if (entry->type == nameType) {
  22378. break;
  22379. }
  22380. entry = entry->next;
  22381. }
  22382. return entry;
  22383. }
  22384. /* returns 0 on success */
  22385. int wc_GetUUIDFromCert(struct DecodedCert* cert, byte* uuid, word32* uuidSz)
  22386. {
  22387. int ret = ALT_NAME_E;
  22388. DNS_entry* id = NULL;
  22389. do {
  22390. id = FindAltName(cert, ASN_URI_TYPE, id);
  22391. if (id != NULL) {
  22392. /* check if URI string matches expected format for UUID */
  22393. if (id->len != DEFAULT_UUID_SZ) {
  22394. continue; /* size not right not a UUID URI */
  22395. }
  22396. if (XMEMCMP(id->name, "urn:uuid:", 9) != 0) {
  22397. continue; /* beginning text not right for a UUID URI */
  22398. }
  22399. if (uuid == NULL) {
  22400. *uuidSz = id->len;
  22401. return LENGTH_ONLY_E;
  22402. }
  22403. if ((int)*uuidSz < id->len) {
  22404. return BUFFER_E;
  22405. }
  22406. XMEMCPY(uuid, id->name, id->len);
  22407. ret = 0; /* success */
  22408. break;
  22409. }
  22410. } while (id != NULL);
  22411. return ret;
  22412. }
  22413. /* reutrns 0 on success */
  22414. int wc_GetFASCNFromCert(struct DecodedCert* cert, byte* fascn, word32* fascnSz)
  22415. {
  22416. int ret = ALT_NAME_E;
  22417. DNS_entry* id = NULL;
  22418. do {
  22419. id = FindAltName(cert, ASN_OTHER_TYPE, id);
  22420. if (id != NULL && id->oidSum == FASCN_OID) {
  22421. if (fascn == NULL) {
  22422. *fascnSz = id->len;
  22423. return LENGTH_ONLY_E;
  22424. }
  22425. if ((int)*fascnSz < id->len) {
  22426. return BUFFER_E;
  22427. }
  22428. XMEMCPY(fascn, id->name, id->len);
  22429. ret = 0; /* success */
  22430. }
  22431. } while (id != NULL);
  22432. return ret;
  22433. }
  22434. #endif /* WOLFSSL_FPKI */
  22435. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  22436. defined(WOLFSSL_KCAPI_RSA) || \
  22437. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  22438. /* USER RSA ifdef portions used instead of refactor in consideration for
  22439. possible fips build */
  22440. /* Encode a public RSA key to output.
  22441. *
  22442. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22443. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22444. *
  22445. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22446. * (RSAPublicKey).
  22447. *
  22448. * @param [out] output Buffer to put encoded data in.
  22449. * @param [in] key RSA key object.
  22450. * @param [in] outLen Size of the output buffer in bytes.
  22451. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22452. * @return Size of encoded data in bytes on success.
  22453. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  22454. * minimum length (5 bytes).
  22455. * @return MEMORY_E when dynamic memory allocation failed.
  22456. */
  22457. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  22458. int with_header)
  22459. {
  22460. #ifndef WOLFSSL_ASN_TEMPLATE
  22461. int nSz, eSz;
  22462. word32 seqSz, algoSz = 0, headSz = 0, bitStringSz = 0, idx;
  22463. byte seq[MAX_SEQ_SZ];
  22464. byte headSeq[MAX_SEQ_SZ];
  22465. byte bitString[1 + MAX_LENGTH_SZ + 1];
  22466. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  22467. if (key == NULL) {
  22468. return BAD_FUNC_ARG;
  22469. }
  22470. #ifdef HAVE_USER_RSA
  22471. nSz = SetASNIntRSA(key->n, NULL);
  22472. #else
  22473. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  22474. #endif
  22475. if (nSz < 0)
  22476. return nSz;
  22477. #ifdef HAVE_USER_RSA
  22478. eSz = SetASNIntRSA(key->e, NULL);
  22479. #else
  22480. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  22481. #endif
  22482. if (eSz < 0)
  22483. return eSz;
  22484. seqSz = SetSequence((word32)(nSz + eSz), seq);
  22485. /* headers */
  22486. if (with_header) {
  22487. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  22488. bitStringSz = SetBitString(seqSz + (word32)(nSz + eSz), 0, bitString);
  22489. headSz = SetSequence((word32)(nSz + eSz) + seqSz + bitStringSz + algoSz,
  22490. headSeq);
  22491. }
  22492. /* if getting length only */
  22493. if (output == NULL) {
  22494. return (int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz;
  22495. }
  22496. /* check output size */
  22497. if (((int)(headSz + algoSz + bitStringSz + seqSz) + nSz + eSz) > outLen) {
  22498. return BUFFER_E;
  22499. }
  22500. /* write output */
  22501. idx = 0;
  22502. if (with_header) {
  22503. /* header size */
  22504. XMEMCPY(output + idx, headSeq, headSz);
  22505. idx += headSz;
  22506. /* algo */
  22507. XMEMCPY(output + idx, algo, algoSz);
  22508. idx += algoSz;
  22509. /* bit string */
  22510. XMEMCPY(output + idx, bitString, bitStringSz);
  22511. idx += bitStringSz;
  22512. }
  22513. /* seq */
  22514. XMEMCPY(output + idx, seq, seqSz);
  22515. idx += seqSz;
  22516. /* n */
  22517. #ifdef HAVE_USER_RSA
  22518. nSz = SetASNIntRSA(key->n, output + idx);
  22519. #else
  22520. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  22521. #endif
  22522. idx += (word32)nSz;
  22523. /* e */
  22524. #ifdef HAVE_USER_RSA
  22525. eSz = SetASNIntRSA(key->e, output + idx);
  22526. #else
  22527. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  22528. #endif
  22529. idx += (word32)eSz;
  22530. return (int)idx;
  22531. #else
  22532. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  22533. int sz = 0;
  22534. int ret = 0;
  22535. int o = 0;
  22536. /* Check parameter validity. */
  22537. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  22538. ret = BAD_FUNC_ARG;
  22539. }
  22540. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  22541. if (ret == 0) {
  22542. if (!with_header) {
  22543. /* Start encoding with items after header. */
  22544. o = RSAPUBLICKEYASN_IDX_PUBKEY_RSA_SEQ;
  22545. }
  22546. /* Set OID for RSA key. */
  22547. SetASN_OID(&dataASN[RSAPUBLICKEYASN_IDX_ALGOID_OID], RSAk, oidKeyType);
  22548. #ifdef WC_RSA_PSS
  22549. dataASN[RSAPUBLICKEYASN_IDX_ALGOID_P_SEQ].noOut = 1;
  22550. #endif
  22551. /* Set public key mp_ints. */
  22552. #ifdef HAVE_USER_RSA
  22553. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], key->n);
  22554. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], key->e);
  22555. #else
  22556. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_N], &key->n);
  22557. SetASN_MP(&dataASN[RSAPUBLICKEYASN_IDX_PUBKEY_RSA_E], &key->e);
  22558. #endif
  22559. /* Calculate size of RSA public key. */
  22560. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22561. (int)rsaPublicKeyASN_Length - o, &sz);
  22562. }
  22563. /* Check output buffer is big enough for encoding. */
  22564. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  22565. ret = BUFFER_E;
  22566. }
  22567. if ((ret == 0) && (output != NULL)) {
  22568. /* Encode RSA public key. */
  22569. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  22570. (int)rsaPublicKeyASN_Length - o, output);
  22571. }
  22572. if (ret == 0) {
  22573. /* Return size of encoding. */
  22574. ret = sz;
  22575. }
  22576. FREE_ASNSETDATA(dataASN, key->heap);
  22577. return ret;
  22578. #endif /* WOLFSSL_ASN_TEMPLATE */
  22579. }
  22580. /* Calculate size of encoded public RSA key in bytes.
  22581. *
  22582. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22583. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22584. *
  22585. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  22586. * (RSAPublicKey).
  22587. *
  22588. * @param [in] key RSA key object.
  22589. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  22590. * @return Size of encoded data in bytes on success.
  22591. * @return BAD_FUNC_ARG when key is NULL.
  22592. * @return MEMORY_E when dynamic memory allocation failed.
  22593. */
  22594. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  22595. {
  22596. return SetRsaPublicKey(NULL, key, 0, with_header);
  22597. }
  22598. /* Encode public RSA key in DER format.
  22599. *
  22600. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  22601. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  22602. *
  22603. * @param [in] key RSA key object.
  22604. * @param [out] output Buffer to put encoded data in.
  22605. * @param [in] inLen Size of buffer in bytes.
  22606. * @return Size of encoded data in bytes on success.
  22607. * @return BAD_FUNC_ARG when key or output is NULL.
  22608. * @return MEMORY_E when dynamic memory allocation failed.
  22609. */
  22610. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  22611. {
  22612. return SetRsaPublicKey(output, key, (int)inLen, 1);
  22613. }
  22614. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  22615. * seq + n + e is returned in ASN.1 DER format */
  22616. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  22617. int with_header)
  22618. {
  22619. return SetRsaPublicKey(output, key, (int)inLen, with_header);
  22620. }
  22621. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || WOLFSSL_KCAPI_RSA ||
  22622. ((OPENSSL_EXTRA || WOLFSSL_KEY_GEN) && !HAVE_USER_RSA))) */
  22623. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || \
  22624. defined(WOLFSSL_KCAPI_RSA) || defined(WOLFSSL_SE050)) && \
  22625. !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  22626. /* Encode private RSA key in DER format.
  22627. *
  22628. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  22629. *
  22630. * @param [in] key RSA key object.
  22631. * @param [out] output Buffer to put encoded data in.
  22632. * @param [in] inLen Size of buffer in bytes.
  22633. * @return Size of encoded data in bytes on success.
  22634. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  22635. * @return MEMORY_E when dynamic memory allocation failed.
  22636. */
  22637. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  22638. {
  22639. #ifndef WOLFSSL_ASN_TEMPLATE
  22640. int ret = 0, i;
  22641. word32 seqSz = 0, verSz = 0, intTotalLen = 0, outLen = 0;
  22642. word32 sizes[RSA_INTS];
  22643. byte seq[MAX_SEQ_SZ];
  22644. byte ver[MAX_VERSION_SZ];
  22645. byte* tmps[RSA_INTS];
  22646. if (key == NULL)
  22647. return BAD_FUNC_ARG;
  22648. if (key->type != RSA_PRIVATE)
  22649. return BAD_FUNC_ARG;
  22650. for (i = 0; i < RSA_INTS; i++)
  22651. tmps[i] = NULL;
  22652. /* write all big ints from key to DER tmps */
  22653. for (i = 0; i < RSA_INTS; i++) {
  22654. mp_int* keyInt = GetRsaInt(key, i);
  22655. int mpSz;
  22656. word32 rawLen;
  22657. ret = mp_unsigned_bin_size(keyInt);
  22658. if (ret < 0)
  22659. return ret;
  22660. rawLen = (word32)ret + 1;
  22661. ret = 0;
  22662. if (output != NULL) {
  22663. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  22664. DYNAMIC_TYPE_RSA);
  22665. if (tmps[i] == NULL) {
  22666. ret = MEMORY_E;
  22667. break;
  22668. }
  22669. }
  22670. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  22671. if (mpSz < 0) {
  22672. ret = mpSz;
  22673. break;
  22674. }
  22675. sizes[i] = (word32)mpSz;
  22676. intTotalLen += (word32)mpSz;
  22677. }
  22678. if (ret == 0) {
  22679. /* make headers */
  22680. ret = SetMyVersion(0, ver, FALSE);
  22681. }
  22682. if (ret >= 0) {
  22683. verSz = (word32)ret;
  22684. ret = 0;
  22685. seqSz = SetSequence(verSz + intTotalLen, seq);
  22686. outLen = seqSz + verSz + intTotalLen;
  22687. if (output != NULL && outLen > inLen)
  22688. ret = BUFFER_E;
  22689. }
  22690. if (ret == 0 && output != NULL) {
  22691. word32 j;
  22692. /* write to output */
  22693. XMEMCPY(output, seq, seqSz);
  22694. j = seqSz;
  22695. XMEMCPY(output + j, ver, verSz);
  22696. j += verSz;
  22697. for (i = 0; i < RSA_INTS; i++) {
  22698. XMEMCPY(output + j, tmps[i], sizes[i]);
  22699. j += sizes[i];
  22700. }
  22701. }
  22702. for (i = 0; i < RSA_INTS; i++) {
  22703. if (tmps[i])
  22704. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  22705. }
  22706. if (ret == 0)
  22707. ret = (int)outLen;
  22708. return ret;
  22709. #else
  22710. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  22711. int i;
  22712. int sz = 0;
  22713. int ret = 0;
  22714. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  22715. ret = BAD_FUNC_ARG;
  22716. }
  22717. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  22718. if (ret == 0) {
  22719. /* Set the version. */
  22720. SetASN_Int8Bit(&dataASN[RSAKEYASN_IDX_VER], 0);
  22721. /* Set all the mp_ints in private key. */
  22722. for (i = 0; i < RSA_INTS; i++) {
  22723. SetASN_MP(&dataASN[(byte)RSAKEYASN_IDX_N + i], GetRsaInt(key, i));
  22724. }
  22725. /* Calculate size of RSA private key encoding. */
  22726. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  22727. }
  22728. /* Check output buffer has enough space for encoding. */
  22729. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  22730. ret = BAD_FUNC_ARG;
  22731. }
  22732. if ((ret == 0) && (output != NULL)) {
  22733. /* Encode RSA private key. */
  22734. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  22735. }
  22736. if (ret == 0) {
  22737. /* Return size of encoding. */
  22738. ret = sz;
  22739. }
  22740. FREE_ASNSETDATA(dataASN, key->heap);
  22741. return ret;
  22742. #endif
  22743. }
  22744. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  22745. #ifdef WOLFSSL_CERT_GEN
  22746. /* Initialize and Set Certificate defaults:
  22747. version = 3 (0x2)
  22748. serial = 0
  22749. sigType = SHA_WITH_RSA
  22750. issuer = blank
  22751. daysValid = 500
  22752. selfSigned = 1 (true) use subject as issuer
  22753. subject = blank
  22754. */
  22755. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  22756. {
  22757. #ifdef WOLFSSL_MULTI_ATTRIB
  22758. int i = 0;
  22759. #endif
  22760. if (cert == NULL) {
  22761. return BAD_FUNC_ARG;
  22762. }
  22763. XMEMSET(cert, 0, sizeof(Cert));
  22764. cert->version = 2; /* version 3 is hex 2 */
  22765. #ifndef NO_SHA
  22766. cert->sigType = CTC_SHAwRSA;
  22767. #elif !defined(NO_SHA256)
  22768. cert->sigType = CTC_SHA256wRSA;
  22769. #else
  22770. cert->sigType = 0;
  22771. #endif
  22772. cert->daysValid = 500;
  22773. cert->selfSigned = 1;
  22774. cert->keyType = RSA_KEY;
  22775. cert->issuer.countryEnc = CTC_PRINTABLE;
  22776. cert->issuer.stateEnc = CTC_UTF8;
  22777. cert->issuer.streetEnc = CTC_UTF8;
  22778. cert->issuer.localityEnc = CTC_UTF8;
  22779. cert->issuer.surEnc = CTC_UTF8;
  22780. #ifdef WOLFSSL_CERT_NAME_ALL
  22781. cert->issuer.givenNameEnc = CTC_UTF8;
  22782. cert->issuer.initialsEnc = CTC_UTF8;
  22783. cert->issuer.dnQualifierEnc = CTC_UTF8;
  22784. cert->issuer.dnNameEnc = CTC_UTF8;
  22785. #endif
  22786. cert->issuer.orgEnc = CTC_UTF8;
  22787. cert->issuer.unitEnc = CTC_UTF8;
  22788. cert->issuer.commonNameEnc = CTC_UTF8;
  22789. cert->issuer.serialDevEnc = CTC_PRINTABLE;
  22790. cert->issuer.userIdEnc = CTC_UTF8;
  22791. cert->issuer.postalCodeEnc = CTC_UTF8;
  22792. #ifdef WOLFSSL_CERT_EXT
  22793. cert->issuer.busCatEnc = CTC_UTF8;
  22794. cert->issuer.joiCEnc = CTC_UTF8;
  22795. cert->issuer.joiStEnc = CTC_UTF8;
  22796. #endif
  22797. cert->subject.countryEnc = CTC_PRINTABLE;
  22798. cert->subject.stateEnc = CTC_UTF8;
  22799. cert->subject.streetEnc = CTC_UTF8;
  22800. cert->subject.localityEnc = CTC_UTF8;
  22801. cert->subject.surEnc = CTC_UTF8;
  22802. #ifdef WOLFSSL_CERT_NAME_ALL
  22803. cert->subject.givenNameEnc = CTC_UTF8;
  22804. cert->subject.initialsEnc = CTC_UTF8;
  22805. cert->subject.dnQualifierEnc = CTC_UTF8;
  22806. cert->subject.dnNameEnc = CTC_UTF8;
  22807. #endif
  22808. cert->subject.orgEnc = CTC_UTF8;
  22809. cert->subject.unitEnc = CTC_UTF8;
  22810. cert->subject.commonNameEnc = CTC_UTF8;
  22811. cert->subject.serialDevEnc = CTC_PRINTABLE;
  22812. cert->subject.userIdEnc = CTC_UTF8;
  22813. cert->subject.postalCodeEnc = CTC_UTF8;
  22814. #ifdef WOLFSSL_CERT_EXT
  22815. cert->subject.busCatEnc = CTC_UTF8;
  22816. cert->subject.joiCEnc = CTC_UTF8;
  22817. cert->subject.joiStEnc = CTC_UTF8;
  22818. #endif
  22819. #ifdef WOLFSSL_MULTI_ATTRIB
  22820. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  22821. cert->issuer.name[i].type = CTC_UTF8;
  22822. cert->subject.name[i].type = CTC_UTF8;
  22823. }
  22824. #endif /* WOLFSSL_MULTI_ATTRIB */
  22825. cert->heap = heap;
  22826. (void)devId; /* future */
  22827. return 0;
  22828. }
  22829. WOLFSSL_ABI
  22830. int wc_InitCert(Cert* cert)
  22831. {
  22832. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  22833. }
  22834. WOLFSSL_ABI
  22835. Cert* wc_CertNew(void* heap)
  22836. {
  22837. Cert* certNew;
  22838. certNew = (Cert*)XMALLOC(sizeof(Cert), heap, DYNAMIC_TYPE_CERT);
  22839. if (certNew) {
  22840. if (wc_InitCert_ex(certNew, heap, INVALID_DEVID) != 0) {
  22841. XFREE(certNew, heap, DYNAMIC_TYPE_CERT);
  22842. certNew = NULL;
  22843. }
  22844. }
  22845. return certNew;
  22846. }
  22847. WOLFSSL_ABI
  22848. void wc_CertFree(Cert* cert)
  22849. {
  22850. if (cert) {
  22851. void* heap = cert->heap;
  22852. ForceZero(cert, sizeof(Cert));
  22853. XFREE(cert, heap, DYNAMIC_TYPE_CERT);
  22854. (void)heap;
  22855. }
  22856. }
  22857. /* DER encoded x509 Certificate */
  22858. typedef struct DerCert {
  22859. byte size[MAX_LENGTH_SZ]; /* length encoded */
  22860. byte version[MAX_VERSION_SZ]; /* version encoded */
  22861. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  22862. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  22863. byte issuer[WC_ASN_NAME_MAX]; /* issuer encoded */
  22864. byte subject[WC_ASN_NAME_MAX]; /* subject encoded */
  22865. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  22866. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  22867. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  22868. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  22869. #ifdef WOLFSSL_CERT_EXT
  22870. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  22871. byte akid[MAX_KID_SZ
  22872. #ifdef WOLFSSL_AKID_NAME
  22873. + sizeof(CertName) + CTC_SERIAL_SIZE
  22874. #endif
  22875. ]; /* Authority Key Identifier extension */
  22876. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  22877. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  22878. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22879. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  22880. #endif
  22881. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  22882. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  22883. #endif
  22884. #ifdef WOLFSSL_CERT_REQ
  22885. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  22886. #ifdef WOLFSSL_CUSTOM_OID
  22887. byte extCustom[MAX_ATTRIB_SZ]; /* Encoded user oid and value */
  22888. #endif
  22889. #endif
  22890. #ifdef WOLFSSL_ALT_NAMES
  22891. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  22892. #endif
  22893. int sizeSz; /* encoded size length */
  22894. int versionSz; /* encoded version length */
  22895. int serialSz; /* encoded serial length */
  22896. int sigAlgoSz; /* encoded sig algo length */
  22897. int issuerSz; /* encoded issuer length */
  22898. int subjectSz; /* encoded subject length */
  22899. int validitySz; /* encoded validity length */
  22900. int publicKeySz; /* encoded public key length */
  22901. int caSz; /* encoded CA extension length */
  22902. #ifdef WOLFSSL_CERT_EXT
  22903. int skidSz; /* encoded SKID extension length */
  22904. int akidSz; /* encoded SKID extension length */
  22905. int keyUsageSz; /* encoded KeyUsage extension length */
  22906. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  22907. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  22908. int nsCertTypeSz; /* encoded Netscape Certifcate Type
  22909. * extension length */
  22910. #endif
  22911. int certPoliciesSz; /* encoded CertPolicies extension length*/
  22912. int crlInfoSz; /* encoded CRL Dist Points length */
  22913. #endif
  22914. #ifdef WOLFSSL_ALT_NAMES
  22915. int altNamesSz; /* encoded AltNames extension length */
  22916. #endif
  22917. int extensionsSz; /* encoded extensions total length */
  22918. int total; /* total encoded lengths */
  22919. #ifdef WOLFSSL_CERT_REQ
  22920. int attribSz;
  22921. #ifdef WOLFSSL_CUSTOM_OID
  22922. int extCustomSz;
  22923. #endif
  22924. #endif
  22925. } DerCert;
  22926. #ifdef WOLFSSL_CERT_REQ
  22927. #ifndef WOLFSSL_ASN_TEMPLATE
  22928. /* Write a set header to output */
  22929. static word32 SetPrintableString(word32 len, byte* output)
  22930. {
  22931. output[0] = ASN_PRINTABLE_STRING;
  22932. return SetLength(len, output + 1) + 1;
  22933. }
  22934. static word32 SetUTF8String(word32 len, byte* output)
  22935. {
  22936. output[0] = ASN_UTF8STRING;
  22937. return SetLength(len, output + 1) + 1;
  22938. }
  22939. #endif
  22940. #endif /* WOLFSSL_CERT_REQ */
  22941. #ifndef WOLFSSL_CERT_GEN_CACHE
  22942. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  22943. static
  22944. #endif
  22945. WOLFSSL_ABI
  22946. void wc_SetCert_Free(Cert* cert)
  22947. {
  22948. if (cert != NULL) {
  22949. cert->der = NULL;
  22950. if (cert->decodedCert) {
  22951. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  22952. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  22953. cert->decodedCert = NULL;
  22954. }
  22955. }
  22956. }
  22957. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz,
  22958. int devId)
  22959. {
  22960. int ret;
  22961. if (cert == NULL) {
  22962. ret = BAD_FUNC_ARG;
  22963. }
  22964. else {
  22965. /* Allocate DecodedCert struct and Zero */
  22966. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22967. DYNAMIC_TYPE_DCERT);
  22968. if (cert->decodedCert == NULL) {
  22969. ret = MEMORY_E;
  22970. }
  22971. else {
  22972. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  22973. InitDecodedCert_ex((DecodedCert*)cert->decodedCert, der, derSz,
  22974. cert->heap, devId);
  22975. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  22976. CERT_TYPE, 0, NULL);
  22977. if (ret >= 0) {
  22978. cert->der = (byte*)der;
  22979. }
  22980. else {
  22981. wc_SetCert_Free(cert);
  22982. }
  22983. }
  22984. }
  22985. return ret;
  22986. }
  22987. #endif /* WOLFSSL_CERT_GEN */
  22988. #ifdef WOLFSSL_CERT_GEN
  22989. #ifndef NO_ASN_TIME
  22990. static WC_INLINE byte itob(int number)
  22991. {
  22992. return (byte)number + 0x30;
  22993. }
  22994. /* write time to output, format */
  22995. static void SetTime(struct tm* date, byte* output)
  22996. {
  22997. int i = 0;
  22998. output[i++] = itob((date->tm_year % 10000) / 1000);
  22999. output[i++] = itob((date->tm_year % 1000) / 100);
  23000. output[i++] = itob((date->tm_year % 100) / 10);
  23001. output[i++] = itob( date->tm_year % 10);
  23002. output[i++] = itob(date->tm_mon / 10);
  23003. output[i++] = itob(date->tm_mon % 10);
  23004. output[i++] = itob(date->tm_mday / 10);
  23005. output[i++] = itob(date->tm_mday % 10);
  23006. output[i++] = itob(date->tm_hour / 10);
  23007. output[i++] = itob(date->tm_hour % 10);
  23008. output[i++] = itob(date->tm_min / 10);
  23009. output[i++] = itob(date->tm_min % 10);
  23010. output[i++] = itob(date->tm_sec / 10);
  23011. output[i++] = itob(date->tm_sec % 10);
  23012. output[i] = 'Z'; /* Zulu profile */
  23013. }
  23014. #endif
  23015. #ifndef WOLFSSL_ASN_TEMPLATE
  23016. /* Copy Dates from cert, return bytes written */
  23017. static int CopyValidity(byte* output, Cert* cert)
  23018. {
  23019. word32 seqSz;
  23020. WOLFSSL_ENTER("CopyValidity");
  23021. /* headers and output */
  23022. seqSz = SetSequence((word32)(cert->beforeDateSz + cert->afterDateSz),
  23023. output);
  23024. if (output) {
  23025. XMEMCPY(output + seqSz, cert->beforeDate, (size_t)cert->beforeDateSz);
  23026. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  23027. (size_t)cert->afterDateSz);
  23028. }
  23029. return (int)seqSz + cert->beforeDateSz + cert->afterDateSz;
  23030. }
  23031. #endif /* !WOLFSSL_ASN_TEMPLATE */
  23032. /* Simple name OID size. */
  23033. #define NAME_OID_SZ 3
  23034. /* Domain name OIDs. */
  23035. static const byte nameOid[][NAME_OID_SZ] = {
  23036. { 0x55, 0x04, ASN_COUNTRY_NAME },
  23037. { 0x55, 0x04, ASN_STATE_NAME },
  23038. { 0x55, 0x04, ASN_STREET_ADDR },
  23039. { 0x55, 0x04, ASN_LOCALITY_NAME },
  23040. #ifdef WOLFSSL_CERT_NAME_ALL
  23041. { 0x55, 0x04, ASN_NAME },
  23042. { 0x55, 0x04, ASN_GIVEN_NAME },
  23043. { 0x55, 0x04, ASN_INITIALS },
  23044. { 0x55, 0x04, ASN_DNQUALIFIER },
  23045. #endif
  23046. { 0x55, 0x04, ASN_SUR_NAME },
  23047. { 0x55, 0x04, ASN_ORG_NAME },
  23048. { 0x00, 0x00, ASN_DOMAIN_COMPONENT}, /* not actual OID - see dcOid */
  23049. /* list all DC values before OUs */
  23050. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  23051. { 0x55, 0x04, ASN_COMMON_NAME },
  23052. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  23053. #ifdef WOLFSSL_CERT_EXT
  23054. { 0x55, 0x04, ASN_BUS_CAT },
  23055. #endif
  23056. { 0x55, 0x04, ASN_POSTAL_CODE },
  23057. { 0x00, 0x00, ASN_EMAIL_NAME}, /* not actual OID - see attrEmailOid */
  23058. { 0x00, 0x00, ASN_USER_ID}, /* not actual OID - see uidOid */
  23059. #ifdef WOLFSSL_CUSTOM_OID
  23060. { 0x00, 0x00, ASN_CUSTOM_NAME} /* OID comes from CertOidField */
  23061. #endif
  23062. };
  23063. #define NAME_ENTRIES (int)(sizeof(nameOid)/NAME_OID_SZ)
  23064. /* Get ASN Name from index */
  23065. byte GetCertNameId(int idx)
  23066. {
  23067. if (idx < NAME_ENTRIES)
  23068. return nameOid[idx][2];
  23069. return 0;
  23070. }
  23071. /* Get Which Name from index */
  23072. const char* GetOneCertName(CertName* name, int idx)
  23073. {
  23074. byte type = GetCertNameId(idx);
  23075. switch (type) {
  23076. case ASN_COUNTRY_NAME:
  23077. return name->country;
  23078. case ASN_STATE_NAME:
  23079. return name->state;
  23080. case ASN_STREET_ADDR:
  23081. return name->street;
  23082. case ASN_LOCALITY_NAME:
  23083. return name->locality;
  23084. #ifdef WOLFSSL_CERT_NAME_ALL
  23085. case ASN_NAME:
  23086. return name->dnName;
  23087. case ASN_GIVEN_NAME:
  23088. return name->givenName;
  23089. case ASN_INITIALS:
  23090. return name->initials;
  23091. case ASN_DNQUALIFIER:
  23092. return name->dnQualifier;
  23093. #endif /* WOLFSSL_CERT_NAME_ALL */
  23094. case ASN_SUR_NAME:
  23095. return name->sur;
  23096. case ASN_ORG_NAME:
  23097. return name->org;
  23098. case ASN_ORGUNIT_NAME:
  23099. return name->unit;
  23100. case ASN_COMMON_NAME:
  23101. return name->commonName;
  23102. case ASN_SERIAL_NUMBER:
  23103. return name->serialDev;
  23104. case ASN_USER_ID:
  23105. return name->userId;
  23106. case ASN_POSTAL_CODE:
  23107. return name->postalCode;
  23108. case ASN_EMAIL_NAME:
  23109. return name->email;
  23110. #ifdef WOLFSSL_CERT_EXT
  23111. case ASN_BUS_CAT:
  23112. return name->busCat;
  23113. #endif
  23114. #ifdef WOLFSSL_CUSTOM_OID
  23115. case ASN_CUSTOM_NAME:
  23116. return (const char*)name->custom.val;
  23117. #endif
  23118. default:
  23119. return NULL;
  23120. }
  23121. }
  23122. /* Get Which Name Encoding from index */
  23123. static char GetNameType(CertName* name, int idx)
  23124. {
  23125. byte type = GetCertNameId(idx);
  23126. switch (type) {
  23127. case ASN_COUNTRY_NAME:
  23128. return name->countryEnc;
  23129. case ASN_STATE_NAME:
  23130. return name->stateEnc;
  23131. case ASN_STREET_ADDR:
  23132. return name->streetEnc;
  23133. case ASN_LOCALITY_NAME:
  23134. return name->localityEnc;
  23135. #ifdef WOLFSSL_CERT_NAME_ALL
  23136. case ASN_NAME:
  23137. return name->dnNameEnc;
  23138. case ASN_GIVEN_NAME:
  23139. return name->givenNameEnc;
  23140. case ASN_INITIALS:
  23141. return name->initialsEnc;
  23142. case ASN_DNQUALIFIER:
  23143. return name->dnQualifierEnc;
  23144. #endif /* WOLFSSL_CERT_NAME_ALL */
  23145. case ASN_SUR_NAME:
  23146. return name->surEnc;
  23147. case ASN_ORG_NAME:
  23148. return name->orgEnc;
  23149. case ASN_ORGUNIT_NAME:
  23150. return name->unitEnc;
  23151. case ASN_COMMON_NAME:
  23152. return name->commonNameEnc;
  23153. case ASN_SERIAL_NUMBER:
  23154. return name->serialDevEnc;
  23155. case ASN_USER_ID:
  23156. return name->userIdEnc;
  23157. case ASN_POSTAL_CODE:
  23158. return name->postalCodeEnc;
  23159. case ASN_EMAIL_NAME:
  23160. return 0; /* special */
  23161. #ifdef WOLFSSL_CERT_EXT
  23162. case ASN_BUS_CAT:
  23163. return name->busCatEnc;
  23164. #endif
  23165. #ifdef WOLFSSL_CUSTOM_OID
  23166. case ASN_CUSTOM_NAME:
  23167. return name->custom.enc;
  23168. #endif
  23169. default:
  23170. return 0;
  23171. }
  23172. }
  23173. #ifndef WOLFSSL_ASN_TEMPLATE
  23174. /*
  23175. Extensions ::= SEQUENCE OF Extension
  23176. Extension ::= SEQUENCE {
  23177. extnId OBJECT IDENTIFIER,
  23178. critical BOOLEAN DEFAULT FALSE,
  23179. extnValue OCTET STRING }
  23180. */
  23181. /* encode all extensions, return total bytes written */
  23182. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  23183. const byte* ext, int extSz)
  23184. {
  23185. if (out == NULL || IdxInOut == NULL || ext == NULL)
  23186. return BAD_FUNC_ARG;
  23187. if (outSz < (word32)(*IdxInOut+extSz))
  23188. return BUFFER_E;
  23189. XMEMCPY(&out[*IdxInOut], ext, (size_t)extSz); /* extensions */
  23190. *IdxInOut += extSz;
  23191. return *IdxInOut;
  23192. }
  23193. /* encode extensions header, return total bytes written */
  23194. static int SetExtensionsHeader(byte* out, word32 outSz, word32 extSz)
  23195. {
  23196. byte sequence[MAX_SEQ_SZ];
  23197. byte len[MAX_LENGTH_SZ];
  23198. word32 seqSz, lenSz, idx = 0;
  23199. if (out == NULL)
  23200. return BAD_FUNC_ARG;
  23201. if (outSz < 3)
  23202. return BUFFER_E;
  23203. seqSz = SetSequence(extSz, sequence);
  23204. /* encode extensions length provided */
  23205. lenSz = SetLength(extSz+seqSz, len);
  23206. if (outSz < (word32)(lenSz+seqSz+1))
  23207. return BUFFER_E;
  23208. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  23209. XMEMCPY(&out[idx], len, lenSz); /* length */
  23210. idx += lenSz;
  23211. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  23212. idx += seqSz;
  23213. return (int)idx;
  23214. }
  23215. /* encode CA basic constraints true with path length
  23216. * return total bytes written */
  23217. static int SetCaWithPathLen(byte* out, word32 outSz, byte pathLen)
  23218. {
  23219. /* ASN1->DER sequence for Basic Constraints True and path length */
  23220. const byte caPathLenBasicConstASN1[] = {
  23221. 0x30, 0x0F, 0x06, 0x03, 0x55, 0x1D, 0x13, 0x04,
  23222. 0x08, 0x30, 0x06, 0x01, 0x01, 0xFF, 0x02, 0x01,
  23223. 0x00
  23224. };
  23225. if (out == NULL)
  23226. return BAD_FUNC_ARG;
  23227. if (outSz < sizeof(caPathLenBasicConstASN1))
  23228. return BUFFER_E;
  23229. XMEMCPY(out, caPathLenBasicConstASN1, sizeof(caPathLenBasicConstASN1));
  23230. out[sizeof(caPathLenBasicConstASN1)-1] = pathLen;
  23231. return (int)sizeof(caPathLenBasicConstASN1);
  23232. }
  23233. /* encode CA basic constraints true
  23234. * return total bytes written */
  23235. static int SetCa(byte* out, word32 outSz)
  23236. {
  23237. /* ASN1->DER sequence for Basic Constraints True */
  23238. const byte caBasicConstASN1[] = {
  23239. 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23240. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff
  23241. };
  23242. if (out == NULL)
  23243. return BAD_FUNC_ARG;
  23244. if (outSz < sizeof(caBasicConstASN1))
  23245. return BUFFER_E;
  23246. XMEMCPY(out, caBasicConstASN1, sizeof(caBasicConstASN1));
  23247. return (int)sizeof(caBasicConstASN1);
  23248. }
  23249. /* encode basic constraints without CA Boolean
  23250. * return total bytes written */
  23251. static int SetBC(byte* out, word32 outSz)
  23252. {
  23253. /* ASN1->DER sequence for Basic Constraint without CA Boolean */
  23254. const byte BasicConstASN1[] = {
  23255. 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  23256. 0x02, 0x30, 0x00
  23257. };
  23258. if (out == NULL)
  23259. return BAD_FUNC_ARG;
  23260. if (outSz < sizeof(BasicConstASN1))
  23261. return BUFFER_E;
  23262. XMEMCPY(out, BasicConstASN1, sizeof(BasicConstASN1));
  23263. return (int)sizeof(BasicConstASN1);
  23264. }
  23265. #endif
  23266. #ifdef WOLFSSL_CERT_EXT
  23267. #ifndef WOLFSSL_ASN_TEMPLATE
  23268. /* encode OID and associated value, return total bytes written */
  23269. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  23270. byte *in, word32 inSz)
  23271. {
  23272. word32 idx = 0;
  23273. if (out == NULL || oid == NULL || in == NULL)
  23274. return BAD_FUNC_ARG;
  23275. if (outSz < 3)
  23276. return BUFFER_E;
  23277. /* sequence, + 1 => byte to put value size */
  23278. idx = SetSequence(inSz + oidSz + 1, out);
  23279. if ((idx + inSz + oidSz + 1) > outSz)
  23280. return BUFFER_E;
  23281. XMEMCPY(out+idx, oid, oidSz);
  23282. idx += oidSz;
  23283. out[idx++] = (byte)inSz;
  23284. XMEMCPY(out+idx, in, inSz);
  23285. return (int)(idx+inSz);
  23286. }
  23287. /* encode Subject Key Identifier, return total bytes written
  23288. * RFC5280 : non-critical */
  23289. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  23290. {
  23291. byte skid_len[1 + MAX_LENGTH_SZ];
  23292. byte skid_enc_len[MAX_LENGTH_SZ];
  23293. word32 idx = 0, skid_lenSz, skid_enc_lenSz;
  23294. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  23295. if (output == NULL || input == NULL)
  23296. return BAD_FUNC_ARG;
  23297. /* Octet String header */
  23298. skid_lenSz = SetOctetString(length, skid_len);
  23299. /* length of encoded value */
  23300. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  23301. if (outSz < 3)
  23302. return BUFFER_E;
  23303. idx = SetSequence(length + (word32)sizeof(skid_oid) + skid_lenSz +
  23304. skid_enc_lenSz, output);
  23305. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  23306. return BUFFER_E;
  23307. /* put oid */
  23308. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  23309. idx += sizeof(skid_oid);
  23310. /* put encoded len */
  23311. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  23312. idx += skid_enc_lenSz;
  23313. /* put octet header */
  23314. XMEMCPY(output+idx, skid_len, skid_lenSz);
  23315. idx += skid_lenSz;
  23316. /* put value */
  23317. XMEMCPY(output+idx, input, length);
  23318. idx += length;
  23319. return (int)idx;
  23320. }
  23321. /* encode Authority Key Identifier, return total bytes written
  23322. * RFC5280 : non-critical */
  23323. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  23324. byte rawAkid)
  23325. {
  23326. int enc_valSz;
  23327. byte enc_val_buf[MAX_KID_SZ];
  23328. byte* enc_val;
  23329. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  23330. const byte akid_cs[] = { 0x80 };
  23331. word32 inSeqSz, idx;
  23332. (void)rawAkid;
  23333. if (output == NULL || input == NULL)
  23334. return BAD_FUNC_ARG;
  23335. #ifdef WOLFSSL_AKID_NAME
  23336. if (rawAkid) {
  23337. enc_val = input;
  23338. enc_valSz = length;
  23339. }
  23340. else
  23341. #endif
  23342. {
  23343. enc_val = enc_val_buf;
  23344. enc_valSz = (int)length + 3 + (int)sizeof(akid_cs);
  23345. if (enc_valSz > (int)sizeof(enc_val_buf))
  23346. return BAD_FUNC_ARG;
  23347. /* sequence for ContentSpec & value */
  23348. enc_valSz = SetOidValue(enc_val, (word32)enc_valSz, akid_cs,
  23349. sizeof(akid_cs), input, length);
  23350. if (enc_valSz <= 0)
  23351. return enc_valSz;
  23352. }
  23353. /* The size of the extension sequence contents */
  23354. inSeqSz = (word32)sizeof(akid_oid) +
  23355. SetOctetString((word32)enc_valSz, NULL) + (word32)enc_valSz;
  23356. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  23357. return BAD_FUNC_ARG;
  23358. /* Write out the sequence header */
  23359. idx = SetSequence(inSeqSz, output);
  23360. /* Write out OID */
  23361. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  23362. idx += sizeof(akid_oid);
  23363. /* Write out AKID */
  23364. idx += SetOctetString((word32)enc_valSz, output + idx);
  23365. XMEMCPY(output + idx, enc_val, (size_t)enc_valSz);
  23366. return (int)idx + enc_valSz;
  23367. }
  23368. /* encode Key Usage, return total bytes written
  23369. * RFC5280 : critical */
  23370. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  23371. {
  23372. byte ku[5];
  23373. word32 idx;
  23374. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  23375. 0x01, 0x01, 0xff, 0x04};
  23376. if (output == NULL)
  23377. return BAD_FUNC_ARG;
  23378. idx = SetBitString16Bit(input, ku);
  23379. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  23380. ku, idx);
  23381. }
  23382. static int SetOjectIdValue(byte* output, word32 outSz, word32* idx,
  23383. const byte* oid, word32 oidSz)
  23384. {
  23385. /* verify room */
  23386. if (*idx + 2 + oidSz >= outSz)
  23387. return ASN_PARSE_E;
  23388. *idx += (word32)SetObjectId((int)oidSz, &output[*idx]);
  23389. XMEMCPY(&output[*idx], oid, oidSz);
  23390. *idx += oidSz;
  23391. return 0;
  23392. }
  23393. #endif
  23394. #ifdef WOLFSSL_ASN_TEMPLATE
  23395. /* ASN.1 template for extended key usage.
  23396. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  23397. * Dynamic creation of template for encoding.
  23398. */
  23399. static const ASNItem ekuASN[] = {
  23400. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23401. /* OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23402. };
  23403. enum {
  23404. EKUASN_IDX_SEQ = 0,
  23405. EKUASN_IDX_OID
  23406. };
  23407. /* OIDs corresponding to extended key usage. */
  23408. struct {
  23409. const byte* oid;
  23410. word32 oidSz;
  23411. } ekuOid[] = {
  23412. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  23413. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  23414. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  23415. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  23416. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  23417. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  23418. };
  23419. #define EKU_OID_LO 1
  23420. #define EKU_OID_HI 6
  23421. #endif /* WOLFSSL_ASN_TEMPLATE */
  23422. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  23423. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  23424. {
  23425. #ifndef WOLFSSL_ASN_TEMPLATE
  23426. word32 idx = 0, oidListSz = 0, totalSz;
  23427. int ret = 0;
  23428. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  23429. if (output == NULL)
  23430. return BAD_FUNC_ARG;
  23431. /* Skip to OID List */
  23432. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  23433. idx = totalSz;
  23434. /* Build OID List */
  23435. /* If any set, then just use it */
  23436. if (input & EXTKEYUSE_ANY) {
  23437. ret |= SetOjectIdValue(output, outSz, &idx,
  23438. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  23439. }
  23440. else {
  23441. if (input & EXTKEYUSE_SERVER_AUTH)
  23442. ret |= SetOjectIdValue(output, outSz, &idx,
  23443. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  23444. if (input & EXTKEYUSE_CLIENT_AUTH)
  23445. ret |= SetOjectIdValue(output, outSz, &idx,
  23446. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  23447. if (input & EXTKEYUSE_CODESIGN)
  23448. ret |= SetOjectIdValue(output, outSz, &idx,
  23449. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  23450. if (input & EXTKEYUSE_EMAILPROT)
  23451. ret |= SetOjectIdValue(output, outSz, &idx,
  23452. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  23453. if (input & EXTKEYUSE_TIMESTAMP)
  23454. ret |= SetOjectIdValue(output, outSz, &idx,
  23455. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  23456. if (input & EXTKEYUSE_OCSP_SIGN)
  23457. ret |= SetOjectIdValue(output, outSz, &idx,
  23458. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  23459. #ifdef WOLFSSL_EKU_OID
  23460. /* iterate through OID values */
  23461. if (input & EXTKEYUSE_USER) {
  23462. int i, sz;
  23463. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23464. sz = cert->extKeyUsageOIDSz[i];
  23465. if (sz > 0) {
  23466. ret |= SetOjectIdValue(output, outSz, &idx,
  23467. cert->extKeyUsageOID[i], sz);
  23468. }
  23469. }
  23470. }
  23471. #endif /* WOLFSSL_EKU_OID */
  23472. }
  23473. if (ret != 0)
  23474. return ASN_PARSE_E;
  23475. /* Calculate Sizes */
  23476. oidListSz = idx - totalSz;
  23477. totalSz = idx - 2; /* exclude first seq/len (2) */
  23478. /* 1. Seq + Total Len (2) */
  23479. idx = SetSequence(totalSz, output);
  23480. /* 2. Object ID (2) */
  23481. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  23482. idx += sizeof(extkeyusage_oid);
  23483. /* 3. Octet String (2) */
  23484. idx += SetOctetString(totalSz - idx, &output[idx]);
  23485. /* 4. Seq + OidListLen (2) */
  23486. idx += SetSequence(oidListSz, &output[idx]);
  23487. /* 5. Oid List (already set in-place above) */
  23488. idx += oidListSz;
  23489. (void)cert;
  23490. return (int)idx;
  23491. #else
  23492. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  23493. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  23494. ASNSetData* dataASN;
  23495. ASNItem* extKuASN = NULL;
  23496. int asnIdx = 1;
  23497. size_t cnt = 1 + EKU_OID_HI;
  23498. int i;
  23499. int ret = 0;
  23500. int sz = 0;
  23501. #ifdef WOLFSSL_EKU_OID
  23502. cnt += CTC_MAX_EKU_NB;
  23503. #endif
  23504. /* Allocate memory for dynamic data items. */
  23505. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  23506. DYNAMIC_TYPE_TMP_BUFFER);
  23507. if (dataASN == NULL) {
  23508. ret = MEMORY_E;
  23509. }
  23510. if (ret == 0) {
  23511. /* Allocate memory for dynamic ASN.1 template. */
  23512. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  23513. DYNAMIC_TYPE_TMP_BUFFER);
  23514. if (extKuASN == NULL) {
  23515. ret = MEMORY_E;
  23516. }
  23517. }
  23518. if (ret == 0) {
  23519. /* Copy Sequence into dynamic ASN.1 template. */
  23520. XMEMCPY(&extKuASN[EKUASN_IDX_SEQ], ekuASN, sizeof(ASNItem));
  23521. /* Clear dynamic data. */
  23522. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  23523. /* Build up the template and data. */
  23524. /* If 'any' set, then just use it. */
  23525. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  23526. /* Set template item. */
  23527. XMEMCPY(&extKuASN[EKUASN_IDX_OID], &ekuASN[EKUASN_IDX_OID],
  23528. sizeof(ASNItem));
  23529. /* Set data item. */
  23530. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  23531. sizeof(extExtKeyUsageAnyOid));
  23532. asnIdx++;
  23533. }
  23534. else {
  23535. /* Step through the flagged purposes. */
  23536. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  23537. if ((input & (1 << i)) != 0) {
  23538. /* Set template item. */
  23539. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23540. sizeof(ASNItem));
  23541. /* Set data item. */
  23542. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  23543. ekuOid[i - 1].oidSz);
  23544. asnIdx++;
  23545. }
  23546. }
  23547. #ifdef WOLFSSL_EKU_OID
  23548. if (input & EXTKEYUSE_USER) {
  23549. /* Iterate through OID values */
  23550. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  23551. sz = cert->extKeyUsageOIDSz[i];
  23552. if (sz > 0) {
  23553. /* Set template item. */
  23554. XMEMCPY(&extKuASN[asnIdx], &ekuASN[EKUASN_IDX_OID],
  23555. sizeof(ASNItem));
  23556. /* Set data item. */
  23557. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  23558. sz);
  23559. asnIdx++;
  23560. }
  23561. }
  23562. }
  23563. #endif /* WOLFSSL_EKU_OID */
  23564. (void)cert;
  23565. }
  23566. /* Calculate size of encoding. */
  23567. sz = 0;
  23568. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  23569. }
  23570. /* When buffer to write to, ensure it's big enough. */
  23571. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  23572. ret = BUFFER_E;
  23573. }
  23574. if ((ret == 0) && (output != NULL)) {
  23575. /* Encode extended key usage. */
  23576. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  23577. }
  23578. if (ret == 0) {
  23579. /* Return the encoding size. */
  23580. ret = sz;
  23581. }
  23582. /* Dispose of allocated data. */
  23583. if (extKuASN != NULL) {
  23584. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23585. }
  23586. if (dataASN != NULL) {
  23587. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23588. }
  23589. return ret;
  23590. #endif
  23591. }
  23592. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  23593. #ifndef WOLFSSL_ASN_TEMPLATE
  23594. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  23595. {
  23596. word32 idx;
  23597. byte unusedBits = 0;
  23598. byte nsCertType = input;
  23599. word32 totalSz;
  23600. word32 bitStrSz;
  23601. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  23602. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  23603. if (cert == NULL || output == NULL ||
  23604. input == 0)
  23605. return BAD_FUNC_ARG;
  23606. totalSz = sizeof(nscerttype_oid);
  23607. /* Get amount of lsb zero's */
  23608. for (;(input & 1) == 0; input >>= 1)
  23609. unusedBits++;
  23610. /* 1 byte of NS Cert Type extension */
  23611. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  23612. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  23613. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23614. return BAD_FUNC_ARG;
  23615. /* 1. Seq + Total Len */
  23616. idx = SetSequence(totalSz, output);
  23617. /* 2. Object ID */
  23618. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  23619. idx += sizeof(nscerttype_oid);
  23620. /* 3. Octet String */
  23621. idx += SetOctetString(bitStrSz, &output[idx]);
  23622. /* 4. Bit String */
  23623. idx += SetBitString(1, unusedBits, &output[idx]);
  23624. output[idx++] = nsCertType;
  23625. return (int)idx;
  23626. }
  23627. #endif
  23628. #endif
  23629. #ifndef WOLFSSL_ASN_TEMPLATE
  23630. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  23631. int inSz)
  23632. {
  23633. word32 idx;
  23634. word32 totalSz;
  23635. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  23636. if (cert == NULL || output == NULL ||
  23637. input == 0 || inSz <= 0)
  23638. return BAD_FUNC_ARG;
  23639. totalSz = (word32)sizeof(crlinfo_oid) + SetOctetString((word32)inSz, NULL) +
  23640. (word32)inSz;
  23641. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  23642. return BAD_FUNC_ARG;
  23643. /* 1. Seq + Total Len */
  23644. idx = SetSequence(totalSz, output);
  23645. /* 2. Object ID */
  23646. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  23647. idx += sizeof(crlinfo_oid);
  23648. /* 3. Octet String */
  23649. idx += SetOctetString((word32)inSz, &output[idx]);
  23650. /* 4. CRL Info */
  23651. XMEMCPY(&output[idx], input, (size_t)inSz);
  23652. idx += (word32)inSz;
  23653. return (int)idx;
  23654. }
  23655. #endif
  23656. /* encode Certificate Policies, return total bytes written
  23657. * each input value must be ITU-T X.690 formatted : a.b.c...
  23658. * input must be an array of values with a NULL terminated for the latest
  23659. * RFC5280 : non-critical */
  23660. static int SetCertificatePolicies(byte *output,
  23661. word32 outputSz,
  23662. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  23663. word16 nb_certpol,
  23664. void* heap)
  23665. {
  23666. #ifndef WOLFSSL_ASN_TEMPLATE
  23667. byte oid[MAX_OID_SZ];
  23668. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  23669. byte out[MAX_CERTPOL_SZ];
  23670. word32 oidSz;
  23671. word32 outSz;
  23672. word32 i = 0;
  23673. word32 der_oidSz[MAX_CERTPOL_NB];
  23674. int ret;
  23675. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  23676. const byte oid_oid[] = { 0x06 };
  23677. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  23678. return BAD_FUNC_ARG;
  23679. for (i = 0; i < nb_certpol; i++) {
  23680. oidSz = sizeof(oid);
  23681. XMEMSET(oid, 0, oidSz);
  23682. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23683. if (ret != 0)
  23684. return ret;
  23685. /* compute sequence value for the oid */
  23686. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  23687. sizeof(oid_oid), oid, oidSz);
  23688. if (ret <= 0)
  23689. return ret;
  23690. else
  23691. der_oidSz[i] = (word32)ret;
  23692. }
  23693. /* concatenate oid, keep two byte for sequence/size of the created value */
  23694. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  23695. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  23696. outSz += der_oidSz[i];
  23697. }
  23698. /* add sequence */
  23699. ret = (int)SetSequence(outSz-2, out);
  23700. if (ret <= 0)
  23701. return ret;
  23702. /* add Policy OID to compute final value */
  23703. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  23704. out, outSz);
  23705. #else
  23706. int i;
  23707. int ret = 0;
  23708. byte oid[MAX_OID_SZ];
  23709. word32 oidSz;
  23710. word32 sz = 0;
  23711. int piSz;
  23712. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  23713. ret = BAD_FUNC_ARG;
  23714. }
  23715. /* Put in policyIdentifier but not policyQualifiers. */
  23716. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  23717. ASNSetData dataASN[policyInfoASN_Length];
  23718. oidSz = sizeof(oid);
  23719. XMEMSET(oid, 0, oidSz);
  23720. dataASN[POLICYINFOASN_IDX_QUALI].noOut = 1;
  23721. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  23722. if (ret == 0) {
  23723. XMEMSET(dataASN, 0, sizeof(dataASN));
  23724. SetASN_Buffer(&dataASN[POLICYINFOASN_IDX_ID], oid, oidSz);
  23725. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23726. &piSz);
  23727. }
  23728. if ((ret == 0) && (output != NULL) && (sz + (word32)piSz > outputSz)) {
  23729. ret = BUFFER_E;
  23730. }
  23731. if (ret == 0) {
  23732. if (output != NULL) {
  23733. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  23734. output);
  23735. output += piSz;
  23736. }
  23737. sz += (word32)piSz;
  23738. }
  23739. }
  23740. if (ret == 0) {
  23741. ret = (int)sz;
  23742. }
  23743. return ret;
  23744. #endif
  23745. }
  23746. #endif /* WOLFSSL_CERT_EXT */
  23747. #ifdef WOLFSSL_ALT_NAMES
  23748. #ifndef WOLFSSL_ASN_TEMPLATE
  23749. /* encode Alternative Names, return total bytes written */
  23750. static int SetAltNames(byte *output, word32 outSz,
  23751. const byte *input, word32 length, int critical)
  23752. {
  23753. byte san_len[1 + MAX_LENGTH_SZ];
  23754. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  23755. const byte san_crit[] = { 0x01, 0x01, 0xff };
  23756. word32 seqSz, san_lenSz, idx = 0;
  23757. if (output == NULL || input == NULL)
  23758. return BAD_FUNC_ARG;
  23759. if (outSz < length)
  23760. return BUFFER_E;
  23761. /* Octet String header */
  23762. san_lenSz = SetOctetString(length, san_len);
  23763. if (outSz < MAX_SEQ_SZ)
  23764. return BUFFER_E;
  23765. seqSz = length + (word32)sizeof(san_oid) + san_lenSz;
  23766. if (critical)
  23767. seqSz += sizeof(san_crit);
  23768. idx = SetSequence(seqSz, output);
  23769. if (seqSz > outSz)
  23770. return BUFFER_E;
  23771. /* put oid */
  23772. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  23773. idx += sizeof(san_oid);
  23774. if (critical) {
  23775. XMEMCPY(output+idx, san_crit, sizeof(san_crit));
  23776. idx += sizeof(san_crit);
  23777. }
  23778. /* put octet header */
  23779. XMEMCPY(output+idx, san_len, san_lenSz);
  23780. idx += san_lenSz;
  23781. /* put value */
  23782. XMEMCPY(output+idx, input, length);
  23783. idx += length;
  23784. return (int)idx;
  23785. }
  23786. #endif /* WOLFSSL_ASN_TEMPLATE */
  23787. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  23788. {
  23789. word32 idx;
  23790. const DNS_entry* curName;
  23791. word32 namesSz = 0;
  23792. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23793. word32 i;
  23794. #endif
  23795. if (output == NULL)
  23796. return BAD_FUNC_ARG;
  23797. if (names == NULL)
  23798. return 0;
  23799. curName = names;
  23800. do {
  23801. namesSz += (word32)curName->len + 2 +
  23802. ((curName->len < ASN_LONG_LENGTH) ? 0
  23803. : BytePrecision((word32)curName->len));
  23804. curName = curName->next;
  23805. } while (curName != NULL);
  23806. if (outputSz < MAX_SEQ_SZ + namesSz)
  23807. return BUFFER_E;
  23808. idx = SetSequence(namesSz, output);
  23809. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23810. namesSz += idx;
  23811. i = namesSz;
  23812. #endif
  23813. curName = names;
  23814. do {
  23815. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23816. word32 len = SetLength(curName->len, NULL);
  23817. idx = i - curName->len - len - 1;
  23818. i = idx;
  23819. #endif
  23820. output[idx] = (byte) (ASN_CONTEXT_SPECIFIC | curName->type);
  23821. if (curName->type == ASN_DIR_TYPE || curName->type == ASN_OTHER_TYPE) {
  23822. output[idx] |= ASN_CONSTRUCTED;
  23823. }
  23824. idx++;
  23825. idx += SetLength((word32)curName->len, output + idx);
  23826. XMEMCPY(output + idx, curName->name, (size_t)curName->len);
  23827. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  23828. idx += (word32)curName->len;
  23829. #endif
  23830. curName = curName->next;
  23831. } while (curName != NULL);
  23832. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  23833. idx = namesSz;
  23834. #endif
  23835. return (int)idx;
  23836. }
  23837. #endif /* WOLFSSL_ALT_NAMES */
  23838. #endif /* WOLFSSL_CERT_GEN */
  23839. #if defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  23840. /* Simple domain name OID size. */
  23841. #define DN_OID_SZ 3
  23842. /* Encodes one attribute of the name (issuer/subject)
  23843. *
  23844. * name structure to hold result of encoding
  23845. * nameStr value to be encoded
  23846. * nameTag tag of encoding i.e CTC_UTF8
  23847. * type id of attribute i.e ASN_COMMON_NAME
  23848. * emailTag tag of email i.e CTC_UTF8
  23849. * returns length on success
  23850. */
  23851. static int EncodeName(EncodedName* name, const char* nameStr,
  23852. byte nameTag, byte type, byte emailTag, CertName* cname)
  23853. {
  23854. #if !defined(WOLFSSL_ASN_TEMPLATE)
  23855. word32 idx = 0;
  23856. /* bottom up */
  23857. byte firstLen[1 + MAX_LENGTH_SZ];
  23858. byte secondLen[MAX_LENGTH_SZ];
  23859. byte sequence[MAX_SEQ_SZ];
  23860. byte set[MAX_SET_SZ];
  23861. word32 strLen;
  23862. word32 thisLen;
  23863. word32 firstSz, secondSz, seqSz, setSz;
  23864. if (nameStr == NULL) {
  23865. name->used = 0;
  23866. return 0;
  23867. }
  23868. thisLen = strLen = (word32)XSTRLEN(nameStr);
  23869. #ifdef WOLFSSL_CUSTOM_OID
  23870. if (type == ASN_CUSTOM_NAME) {
  23871. if (cname == NULL || cname->custom.oidSz == 0) {
  23872. name->used = 0;
  23873. return 0;
  23874. }
  23875. thisLen = strLen = (word32)cname->custom.valSz;
  23876. }
  23877. #else
  23878. (void)cname;
  23879. #endif
  23880. if (strLen == 0) { /* no user data for this item */
  23881. name->used = 0;
  23882. return 0;
  23883. }
  23884. /* Restrict country code size */
  23885. if (type == ASN_COUNTRY_NAME && strLen != CTC_COUNTRY_SIZE) {
  23886. WOLFSSL_MSG("Country code size error");
  23887. WOLFSSL_ERROR_VERBOSE(ASN_COUNTRY_SIZE_E);
  23888. return ASN_COUNTRY_SIZE_E;
  23889. }
  23890. secondSz = SetLength(strLen, secondLen);
  23891. thisLen += secondSz;
  23892. switch (type) {
  23893. case ASN_EMAIL_NAME: /* email */
  23894. thisLen += (int)sizeof(attrEmailOid);
  23895. firstSz = (int)sizeof(attrEmailOid);
  23896. break;
  23897. case ASN_DOMAIN_COMPONENT:
  23898. thisLen += (int)sizeof(dcOid);
  23899. firstSz = (int)sizeof(dcOid);
  23900. break;
  23901. case ASN_USER_ID:
  23902. thisLen += (int)sizeof(uidOid);
  23903. firstSz = (int)sizeof(uidOid);
  23904. break;
  23905. case ASN_FAVOURITE_DRINK:
  23906. thisLen += (int)sizeof(fvrtDrk);
  23907. firstSz = (int)sizeof(fvrtDrk);
  23908. break;
  23909. #ifdef WOLFSSL_CUSTOM_OID
  23910. case ASN_CUSTOM_NAME:
  23911. thisLen += cname->custom.oidSz;
  23912. firstSz = cname->custom.oidSz;
  23913. break;
  23914. #endif
  23915. default:
  23916. thisLen += DN_OID_SZ;
  23917. firstSz = DN_OID_SZ;
  23918. }
  23919. thisLen++; /* id type */
  23920. firstSz = (word32)SetObjectId((int)firstSz, firstLen);
  23921. thisLen += firstSz;
  23922. seqSz = SetSequence(thisLen, sequence);
  23923. thisLen += seqSz;
  23924. setSz = SetSet(thisLen, set);
  23925. thisLen += setSz;
  23926. if (thisLen > (int)sizeof(name->encoded)) {
  23927. return BUFFER_E;
  23928. }
  23929. /* store it */
  23930. idx = 0;
  23931. /* set */
  23932. XMEMCPY(name->encoded, set, setSz);
  23933. idx += setSz;
  23934. /* seq */
  23935. XMEMCPY(name->encoded + idx, sequence, seqSz);
  23936. idx += seqSz;
  23937. /* asn object id */
  23938. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  23939. idx += firstSz;
  23940. switch (type) {
  23941. case ASN_EMAIL_NAME:
  23942. /* email joint id */
  23943. XMEMCPY(name->encoded + idx, attrEmailOid, sizeof(attrEmailOid));
  23944. idx += (int)sizeof(attrEmailOid);
  23945. name->encoded[idx++] = emailTag;
  23946. break;
  23947. case ASN_DOMAIN_COMPONENT:
  23948. XMEMCPY(name->encoded + idx, dcOid, sizeof(dcOid)-1);
  23949. idx += (int)sizeof(dcOid)-1;
  23950. /* id type */
  23951. name->encoded[idx++] = type;
  23952. /* str type */
  23953. name->encoded[idx++] = nameTag;
  23954. break;
  23955. case ASN_USER_ID:
  23956. XMEMCPY(name->encoded + idx, uidOid, sizeof(uidOid));
  23957. idx += (int)sizeof(uidOid);
  23958. /* str type */
  23959. name->encoded[idx++] = nameTag;
  23960. break;
  23961. case ASN_FAVOURITE_DRINK:
  23962. XMEMCPY(name->encoded + idx, fvrtDrk, sizeof(fvrtDrk));
  23963. idx += (int)sizeof(fvrtDrk);
  23964. /* str type */
  23965. name->encoded[idx++] = nameTag;
  23966. break;
  23967. #ifdef WOLFSSL_CUSTOM_OID
  23968. case ASN_CUSTOM_NAME:
  23969. XMEMCPY(name->encoded + idx, cname->custom.oid,
  23970. cname->custom.oidSz);
  23971. idx += cname->custom.oidSz;
  23972. /* str type */
  23973. name->encoded[idx++] = nameTag;
  23974. break;
  23975. #endif
  23976. default:
  23977. name->encoded[idx++] = 0x55;
  23978. name->encoded[idx++] = 0x04;
  23979. /* id type */
  23980. name->encoded[idx++] = type;
  23981. /* str type */
  23982. name->encoded[idx++] = nameTag;
  23983. }
  23984. /* second length */
  23985. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  23986. idx += secondSz;
  23987. /* str value */
  23988. XMEMCPY(name->encoded + idx, nameStr, strLen);
  23989. idx += strLen;
  23990. name->type = type;
  23991. name->totalLen = (int)idx;
  23992. name->used = 1;
  23993. return (int)idx;
  23994. #else
  23995. DECL_ASNSETDATA(dataASN, rdnASN_Length);
  23996. ASNItem namesASN[rdnASN_Length];
  23997. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  23998. int ret = 0;
  23999. int sz = 0;
  24000. const byte* oid;
  24001. word32 oidSz;
  24002. word32 nameSz;
  24003. /* Validate input parameters. */
  24004. if ((name == NULL) || (nameStr == NULL)) {
  24005. ret = BAD_FUNC_ARG;
  24006. }
  24007. CALLOC_ASNSETDATA(dataASN, rdnASN_Length, ret, NULL);
  24008. if (ret == 0) {
  24009. nameSz = (word32)XSTRLEN(nameStr);
  24010. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  24011. * based on type. */
  24012. XMEMCPY(namesASN, rdnASN, sizeof(namesASN));
  24013. /* Set OID and ASN.1 tag for name depending on type. */
  24014. switch (type) {
  24015. case ASN_EMAIL_NAME:
  24016. /* email OID different to standard types. */
  24017. oid = attrEmailOid;
  24018. oidSz = sizeof(attrEmailOid);
  24019. /* Use email specific type/tag. */
  24020. nameTag = emailTag;
  24021. break;
  24022. case ASN_DOMAIN_COMPONENT:
  24023. /* Domain component OID different to standard types. */
  24024. oid = dcOid;
  24025. oidSz = sizeof(dcOid);
  24026. break;
  24027. case ASN_USER_ID:
  24028. /* Domain component OID different to standard types. */
  24029. oid = uidOid;
  24030. oidSz = sizeof(uidOid);
  24031. break;
  24032. case ASN_FAVOURITE_DRINK:
  24033. oid = fvrtDrk;
  24034. oidSz = sizeof(fvrtDrk);
  24035. break;
  24036. #ifdef WOLFSSL_CUSTOM_OID
  24037. case ASN_CUSTOM_NAME:
  24038. nameSz = cname->custom.valSz;
  24039. oid = cname->custom.oid;
  24040. oidSz = cname->custom.oidSz;
  24041. break;
  24042. #endif
  24043. default:
  24044. /* Construct OID using type. */
  24045. dnOid[2] = type;
  24046. oid = dnOid;
  24047. oidSz = DN_OID_SZ;
  24048. break;
  24049. }
  24050. /* Set OID corresponding to the name type. */
  24051. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24052. /* Set name string. */
  24053. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], (const byte *)nameStr, nameSz);
  24054. /* Set the ASN.1 tag for the name string. */
  24055. namesASN[RDNASN_IDX_ATTR_VAL].tag = nameTag;
  24056. /* Calculate size of encoded name and indexes of components. */
  24057. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  24058. }
  24059. /* Check if name's buffer is big enough. */
  24060. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  24061. ret = BUFFER_E;
  24062. }
  24063. if (ret == 0) {
  24064. /* Encode name into the buffer. */
  24065. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  24066. /* Cache the type and size, and set that it is used. */
  24067. name->type = type;
  24068. name->totalLen = sz;
  24069. name->used = 1;
  24070. /* Return size of encoding. */
  24071. ret = sz;
  24072. }
  24073. (void)cname;
  24074. FREE_ASNSETDATA(dataASN, NULL);
  24075. return ret;
  24076. #endif /* WOLFSSL_ASN_TEMPLATE */
  24077. }
  24078. /* canonical encoding one attribute of the name (issuer/subject)
  24079. * call EncodeName with CTC_UTF8 for email type
  24080. *
  24081. * name structure to hold result of encoding
  24082. * nameStr value to be encoded
  24083. * nameType type of encoding i.e CTC_UTF8
  24084. * type id of attribute i.e ASN_COMMON_NAME
  24085. *
  24086. * returns length on success
  24087. */
  24088. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  24089. char nameType, byte type)
  24090. {
  24091. return EncodeName(name, nameStr, (byte)nameType, type,
  24092. ASN_UTF8STRING, NULL);
  24093. }
  24094. #endif /* WOLFSSL_CERT_GEN || OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  24095. #ifdef WOLFSSL_CERT_GEN
  24096. /* Encodes one attribute of the name (issuer/subject)
  24097. * call we_EncodeName_ex with 0x16, IA5String for email type
  24098. * name structure to hold result of encoding
  24099. * nameStr value to be encoded
  24100. * nameType type of encoding i.e CTC_UTF8
  24101. * type id of attribute i.e ASN_COMMON_NAME
  24102. *
  24103. * returns length on success
  24104. */
  24105. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  24106. byte type)
  24107. {
  24108. return EncodeName(name, nameStr, (byte)nameType, type,
  24109. ASN_IA5_STRING, NULL);
  24110. }
  24111. #ifdef WOLFSSL_ASN_TEMPLATE
  24112. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  24113. word32 oidSz, byte tag, const byte* data, word32 sz)
  24114. {
  24115. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  24116. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_TYPE], oid, oidSz);
  24117. namesASN[RDNASN_IDX_ATTR_VAL].tag = tag;
  24118. SetASN_Buffer(&dataASN[RDNASN_IDX_ATTR_VAL], data, sz);
  24119. }
  24120. #ifdef WOLFSSL_MULTI_ATTRIB
  24121. static int FindMultiAttrib(CertName* name, int id, int* idx)
  24122. {
  24123. int i;
  24124. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  24125. if (name->name[i].sz > 0 && name->name[i].id == id) {
  24126. break;
  24127. }
  24128. }
  24129. if (i == CTC_MAX_ATTRIB) {
  24130. i = -1;
  24131. }
  24132. *idx = i;
  24133. return i >= 0;
  24134. }
  24135. #endif
  24136. /* ASN.1 template for the SEQUENCE around the RDNs.
  24137. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  24138. */
  24139. static const ASNItem nameASN[] = {
  24140. { 0, ASN_SEQUENCE, 1, 1, 0 },
  24141. };
  24142. enum {
  24143. NAMEASN_IDX_SEQ = 0
  24144. };
  24145. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  24146. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  24147. static int SetNameRdnItems(ASNSetData* dataASN, ASNItem* namesASN,
  24148. int maxIdx, CertName* name)
  24149. {
  24150. int i;
  24151. int idx;
  24152. int ret = 0;
  24153. word32 nameLen[NAME_ENTRIES];
  24154. #ifdef WOLFSSL_MULTI_ATTRIB
  24155. int j;
  24156. #endif
  24157. for (i = 0; i < NAME_ENTRIES; i++) {
  24158. /* Keep name length to identify component is to be encoded. */
  24159. const char* nameStr = GetOneCertName(name, i);
  24160. nameLen[i] = nameStr ? (word32)XSTRLEN(nameStr) : 0;
  24161. }
  24162. idx = nameASN_Length;
  24163. for (i = 0; i < NAME_ENTRIES; i++) {
  24164. int type = GetCertNameId(i);
  24165. #ifdef WOLFSSL_MULTI_ATTRIB
  24166. j = -1;
  24167. /* Put DomainComponents before OrgUnitName. */
  24168. while (FindMultiAttrib(name, type, &j)) {
  24169. if (GetCertNameId(i) != ASN_DOMAIN_COMPONENT) {
  24170. continue;
  24171. }
  24172. if (dataASN != NULL && namesASN != NULL) {
  24173. if (idx > maxIdx - (int)rdnASN_Length) {
  24174. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24175. ret = BUFFER_E;
  24176. break;
  24177. }
  24178. /* Copy data into dynamic vars. */
  24179. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  24180. sizeof(dcOid), (byte)name->name[j].type,
  24181. (byte*)name->name[j].value,
  24182. (word32)name->name[j].sz);
  24183. }
  24184. idx += (int)rdnASN_Length;
  24185. }
  24186. if (ret != 0)
  24187. break;
  24188. #endif
  24189. if (nameLen[i] > 0) {
  24190. if (dataASN != NULL) {
  24191. if (idx > maxIdx - (int)rdnASN_Length) {
  24192. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24193. ret = BUFFER_E;
  24194. break;
  24195. }
  24196. /* Write out first instance of attribute type. */
  24197. if (type == ASN_EMAIL_NAME) {
  24198. /* Copy email data into dynamic vars. */
  24199. SetRdnItems(namesASN + idx, dataASN + idx, attrEmailOid,
  24200. sizeof(attrEmailOid), ASN_IA5_STRING,
  24201. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24202. }
  24203. else if (type == ASN_USER_ID) {
  24204. /* Copy userID data into dynamic vars. */
  24205. SetRdnItems(namesASN + idx, dataASN + idx, uidOid,
  24206. sizeof(uidOid), (byte)GetNameType(name, i),
  24207. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24208. }
  24209. else if (type == ASN_FAVOURITE_DRINK) {
  24210. /* Copy favourite drink data into dynamic vars. */
  24211. SetRdnItems(namesASN + idx, dataASN + idx, fvrtDrk,
  24212. sizeof(fvrtDrk), (byte)GetNameType(name, i),
  24213. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24214. }
  24215. else if (type == ASN_CUSTOM_NAME) {
  24216. #ifdef WOLFSSL_CUSTOM_OID
  24217. SetRdnItems(namesASN + idx, dataASN + idx, name->custom.oid,
  24218. name->custom.oidSz, name->custom.enc,
  24219. name->custom.val, name->custom.valSz);
  24220. #endif
  24221. }
  24222. else {
  24223. /* Copy name data into dynamic vars. */
  24224. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24225. NAME_OID_SZ, (byte)GetNameType(name, i),
  24226. (const byte*)GetOneCertName(name, i), nameLen[i]);
  24227. }
  24228. }
  24229. idx += (int)rdnASN_Length;
  24230. }
  24231. #ifdef WOLFSSL_MULTI_ATTRIB
  24232. j = -1;
  24233. /* Write all other attributes of this type. */
  24234. while (FindMultiAttrib(name, type, &j)) {
  24235. if (GetCertNameId(i) == ASN_DOMAIN_COMPONENT) {
  24236. continue;
  24237. }
  24238. if (dataASN != NULL && namesASN != NULL) {
  24239. if (idx > maxIdx - (int)rdnASN_Length) {
  24240. WOLFSSL_MSG("Wanted to write more ASN than allocated");
  24241. ret = BUFFER_E;
  24242. break;
  24243. }
  24244. /* Copy data into dynamic vars. */
  24245. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  24246. NAME_OID_SZ, (byte)name->name[j].type,
  24247. (byte*)name->name[j].value, (word32)name->name[j].sz);
  24248. }
  24249. idx += (int)rdnASN_Length;
  24250. }
  24251. if (ret != 0)
  24252. break;
  24253. #endif
  24254. }
  24255. if (ret == 0)
  24256. ret = idx;
  24257. return ret;
  24258. }
  24259. #endif
  24260. /* encode CertName into output, return total bytes written */
  24261. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  24262. {
  24263. #ifndef WOLFSSL_ASN_TEMPLATE
  24264. int ret;
  24265. int i;
  24266. word32 idx, totalBytes = 0;
  24267. #ifdef WOLFSSL_SMALL_STACK
  24268. EncodedName* names = NULL;
  24269. #else
  24270. EncodedName names[NAME_ENTRIES];
  24271. #endif
  24272. #ifdef WOLFSSL_MULTI_ATTRIB
  24273. EncodedName addNames[CTC_MAX_ATTRIB];
  24274. int j, type;
  24275. #endif
  24276. if (output == NULL || name == NULL)
  24277. return BAD_FUNC_ARG;
  24278. if (outputSz < 3)
  24279. return BUFFER_E;
  24280. #ifdef WOLFSSL_SMALL_STACK
  24281. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  24282. DYNAMIC_TYPE_TMP_BUFFER);
  24283. if (names == NULL)
  24284. return MEMORY_E;
  24285. #endif
  24286. for (i = 0; i < NAME_ENTRIES; i++) {
  24287. const char* nameStr = GetOneCertName(name, i);
  24288. ret = EncodeName(&names[i], nameStr, (byte)GetNameType(name, i),
  24289. GetCertNameId(i), ASN_IA5_STRING, name);
  24290. if (ret < 0) {
  24291. #ifdef WOLFSSL_SMALL_STACK
  24292. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24293. #endif
  24294. WOLFSSL_MSG("EncodeName failed");
  24295. return BUFFER_E;
  24296. }
  24297. totalBytes += (word32)ret;
  24298. }
  24299. #ifdef WOLFSSL_MULTI_ATTRIB
  24300. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  24301. if (name->name[i].sz > 0) {
  24302. ret = EncodeName(&addNames[i], name->name[i].value,
  24303. (byte)name->name[i].type, (byte)name->name[i].id,
  24304. ASN_IA5_STRING, NULL);
  24305. if (ret < 0) {
  24306. #ifdef WOLFSSL_SMALL_STACK
  24307. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24308. #endif
  24309. WOLFSSL_MSG("EncodeName on multiple attributes failed");
  24310. return BUFFER_E;
  24311. }
  24312. totalBytes += (word32)ret;
  24313. }
  24314. else {
  24315. addNames[i].used = 0;
  24316. }
  24317. }
  24318. #endif /* WOLFSSL_MULTI_ATTRIB */
  24319. /* header */
  24320. idx = SetSequence(totalBytes, output);
  24321. totalBytes += idx;
  24322. if (totalBytes > WC_ASN_NAME_MAX) {
  24323. #ifdef WOLFSSL_SMALL_STACK
  24324. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24325. #endif
  24326. WOLFSSL_MSG("Total Bytes is greater than WC_ASN_NAME_MAX");
  24327. return BUFFER_E;
  24328. }
  24329. for (i = 0; i < NAME_ENTRIES; i++) {
  24330. #ifdef WOLFSSL_MULTI_ATTRIB
  24331. type = GetCertNameId(i);
  24332. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  24333. if (name->name[j].sz > 0 && type == name->name[j].id) {
  24334. if (outputSz < idx + (word32)addNames[j].totalLen) {
  24335. #ifdef WOLFSSL_SMALL_STACK
  24336. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24337. #endif
  24338. WOLFSSL_MSG("Not enough space left for DC value");
  24339. return BUFFER_E;
  24340. }
  24341. XMEMCPY(output + idx, addNames[j].encoded,
  24342. (size_t)addNames[j].totalLen);
  24343. idx += (word32)addNames[j].totalLen;
  24344. }
  24345. }
  24346. #endif /* WOLFSSL_MULTI_ATTRIB */
  24347. if (names[i].used) {
  24348. if (outputSz < idx + (word32)names[i].totalLen) {
  24349. #ifdef WOLFSSL_SMALL_STACK
  24350. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24351. #endif
  24352. return BUFFER_E;
  24353. }
  24354. XMEMCPY(output + idx, names[i].encoded, (size_t)names[i].totalLen);
  24355. idx += (word32)names[i].totalLen;
  24356. }
  24357. }
  24358. #ifdef WOLFSSL_SMALL_STACK
  24359. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  24360. #endif
  24361. (void)heap;
  24362. return (int)totalBytes;
  24363. #else
  24364. /* TODO: consider calculating size of entries, putting length into
  24365. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  24366. ASNSetData* dataASN = NULL; /* Can't use DECL_ASNSETDATA. Always dynamic. */
  24367. ASNItem* namesASN = NULL;
  24368. word32 items = 0;
  24369. int ret = 0;
  24370. int sz = 0;
  24371. /* Calculate length of name entries and size for allocating. */
  24372. ret = SetNameRdnItems(NULL, NULL, 0, name);
  24373. if (ret > 0) {
  24374. items = (word32)ret;
  24375. ret = 0;
  24376. }
  24377. /* Allocate dynamic data items. */
  24378. dataASN = (ASNSetData*)XMALLOC(items * sizeof(ASNSetData), heap,
  24379. DYNAMIC_TYPE_TMP_BUFFER);
  24380. if (dataASN == NULL) {
  24381. ret = MEMORY_E;
  24382. }
  24383. else {
  24384. /* Allocate dynamic ASN.1 template items. */
  24385. namesASN = (ASNItem*)XMALLOC(items * sizeof(ASNItem), heap,
  24386. DYNAMIC_TYPE_TMP_BUFFER);
  24387. if (namesASN == NULL) {
  24388. ret = MEMORY_E;
  24389. }
  24390. }
  24391. if (ret == 0) {
  24392. /* Clear the dynamic data. */
  24393. XMEMSET(dataASN, 0, items * sizeof(ASNSetData));
  24394. /* Copy in the outer sequence. */
  24395. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  24396. ret = SetNameRdnItems(dataASN, namesASN, (int)items, name);
  24397. if (ret == (int)items)
  24398. ret = 0;
  24399. else if (ret > 0) {
  24400. WOLFSSL_MSG("SetNameRdnItems returned different length");
  24401. ret = BUFFER_E;
  24402. }
  24403. }
  24404. if (ret == 0) {
  24405. /* Calculate size of encoding. */
  24406. ret = SizeASN_Items(namesASN, dataASN, (int)items, &sz);
  24407. }
  24408. /* Check buffer size if passed in. */
  24409. if (ret == 0 && output != NULL && sz > (int)outputSz) {
  24410. ret = BUFFER_E;
  24411. }
  24412. if (ret == 0) {
  24413. if (output != NULL) {
  24414. /* Encode Name. */
  24415. ret = SetASN_Items(namesASN, dataASN, (int)items, output);
  24416. }
  24417. else {
  24418. /* Return the encoding size. */
  24419. ret = sz;
  24420. }
  24421. }
  24422. if (namesASN != NULL)
  24423. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24424. if (dataASN != NULL)
  24425. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  24426. (void)heap;
  24427. return ret;
  24428. #endif
  24429. }
  24430. int SetName(byte* output, word32 outputSz, CertName* name)
  24431. {
  24432. return SetNameEx(output, outputSz, name, NULL);
  24433. }
  24434. #ifdef WOLFSSL_ASN_TEMPLATE
  24435. static int EncodePublicKey(int keyType, byte* output, int outLen,
  24436. RsaKey* rsaKey, ecc_key* eccKey,
  24437. ed25519_key* ed25519Key, ed448_key* ed448Key,
  24438. DsaKey* dsaKey)
  24439. {
  24440. int ret = 0;
  24441. (void)outLen;
  24442. (void)rsaKey;
  24443. (void)eccKey;
  24444. (void)ed25519Key;
  24445. (void)ed448Key;
  24446. (void)dsaKey;
  24447. switch (keyType) {
  24448. #ifndef NO_RSA
  24449. case RSA_KEY:
  24450. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  24451. if (ret <= 0) {
  24452. ret = PUBLIC_KEY_E;
  24453. }
  24454. break;
  24455. #endif
  24456. #ifdef HAVE_ECC
  24457. case ECC_KEY:
  24458. ret = SetEccPublicKey(output, eccKey, outLen, 1, 0);
  24459. if (ret <= 0) {
  24460. ret = PUBLIC_KEY_E;
  24461. }
  24462. break;
  24463. #endif /* HAVE_ECC */
  24464. #ifdef HAVE_ED25519
  24465. case ED25519_KEY:
  24466. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output,
  24467. (word32)outLen, 1);
  24468. if (ret <= 0) {
  24469. ret = PUBLIC_KEY_E;
  24470. }
  24471. break;
  24472. #endif
  24473. #ifdef HAVE_ED448
  24474. case ED448_KEY:
  24475. ret = wc_Ed448PublicKeyToDer(ed448Key, output, (word32)outLen, 1);
  24476. if (ret <= 0) {
  24477. ret = PUBLIC_KEY_E;
  24478. }
  24479. break;
  24480. #endif
  24481. default:
  24482. ret = PUBLIC_KEY_E;
  24483. break;
  24484. }
  24485. return ret;
  24486. }
  24487. /* ASN.1 template for certificate extensions.
  24488. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  24489. * All extensions supported for encoding are described.
  24490. */
  24491. static const ASNItem static_certExtsASN[] = {
  24492. /* Basic Constraints Extension - 4.2.1.9 */
  24493. /* BC_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24494. /* BC_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24495. /* BC_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24496. /* BC_STR_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24497. /* cA */
  24498. /* BC_CA */ { 3, ASN_BOOLEAN, 0, 0, 0 },
  24499. /* pathLenConstraint */
  24500. /* BC_PATHLEN */ { 3, ASN_INTEGER, 0, 0, 1 },
  24501. /* Subject Alternative Name - 4.2.1.6 */
  24502. /* SAN_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24503. /* SAN_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24504. /* SAN_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24505. /* SAN_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24506. /* Subject Key Identifier - 4.2.1.2 */
  24507. /* SKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24508. /* SKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24509. /* SKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24510. /* SKID_KEYID */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24511. /* Authority Key Identifier - 4.2.1.1 */
  24512. /* AKID_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24513. /* AKID_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24514. /* AKID_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24515. /* AKID_STR_SEQ, */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  24516. /* AKID_KEYID */ { 3, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  24517. /* Key Usage - 4.2.1.3 */
  24518. /* KU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24519. /* KU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24520. /* KU_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24521. /* KU_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24522. /* KU_USAGE */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24523. /* Extended Key Usage - 4,2,1,12 */
  24524. /* EKU_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24525. /* EKU_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24526. /* EKU_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24527. /* Certificate Policies - 4.2.1.4 */
  24528. /* POLICIES_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24529. /* POLICIES_OID, */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24530. /* POLICIES_STR, */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24531. /* POLICIES_INFO */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  24532. /* Netscape Certificate Type */
  24533. /* NSTYPE_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24534. /* NSTYPE_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24535. /* NSTYPE_STR */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24536. /* NSTYPE_USAGE, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  24537. /* CRLINFO_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24538. /* CRLINFO_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24539. /* CRLINFO_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24540. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24541. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24542. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24543. };
  24544. enum {
  24545. CERTEXTSASN_IDX_BC_SEQ = 0,
  24546. CERTEXTSASN_IDX_BC_OID,
  24547. CERTEXTSASN_IDX_BC_STR,
  24548. CERTEXTSASN_IDX_BC_STR_SEQ,
  24549. CERTEXTSASN_IDX_BC_CA,
  24550. CERTEXTSASN_IDX_BC_PATHLEN,
  24551. CERTEXTSASN_IDX_SAN_SEQ,
  24552. CERTEXTSASN_IDX_SAN_OID,
  24553. CERTEXTSASN_IDX_SAN_CRIT,
  24554. CERTEXTSASN_IDX_SAN_STR,
  24555. CERTEXTSASN_IDX_SKID_SEQ,
  24556. CERTEXTSASN_IDX_SKID_OID,
  24557. CERTEXTSASN_IDX_SKID_STR,
  24558. CERTEXTSASN_IDX_SKID_KEYID,
  24559. CERTEXTSASN_IDX_AKID_SEQ,
  24560. CERTEXTSASN_IDX_AKID_OID,
  24561. CERTEXTSASN_IDX_AKID_STR,
  24562. CERTEXTSASN_IDX_AKID_STR_SEQ,
  24563. CERTEXTSASN_IDX_AKID_KEYID,
  24564. CERTEXTSASN_IDX_KU_SEQ,
  24565. CERTEXTSASN_IDX_KU_OID,
  24566. CERTEXTSASN_IDX_KU_CRIT,
  24567. CERTEXTSASN_IDX_KU_STR,
  24568. CERTEXTSASN_IDX_KU_USAGE,
  24569. CERTEXTSASN_IDX_EKU_SEQ,
  24570. CERTEXTSASN_IDX_EKU_OID,
  24571. CERTEXTSASN_IDX_EKU_STR,
  24572. CERTEXTSASN_IDX_POLICIES_SEQ,
  24573. CERTEXTSASN_IDX_POLICIES_OID,
  24574. CERTEXTSASN_IDX_POLICIES_STR,
  24575. CERTEXTSASN_IDX_POLICIES_INFO,
  24576. CERTEXTSASN_IDX_NSTYPE_SEQ,
  24577. CERTEXTSASN_IDX_NSTYPE_OID,
  24578. CERTEXTSASN_IDX_NSTYPE_STR,
  24579. CERTEXTSASN_IDX_NSTYPE_USAGE,
  24580. CERTEXTSASN_IDX_CRLINFO_SEQ,
  24581. CERTEXTSASN_IDX_CRLINFO_OID,
  24582. CERTEXTSASN_IDX_CRLINFO_STR,
  24583. CERTEXTSASN_IDX_CUSTOM_SEQ,
  24584. CERTEXTSASN_IDX_CUSTOM_OID,
  24585. CERTEXTSASN_IDX_CUSTOM_STR,
  24586. CERTEXTSASN_IDX_START_CUSTOM
  24587. };
  24588. /* Number of items in ASN.1 template for certificate extensions. We multiply
  24589. * by 4 because there are 4 things (seq, OID, crit flag, octet string). */
  24590. #define certExtsASN_Length ((sizeof(static_certExtsASN) / sizeof(ASNItem)) \
  24591. + (NUM_CUSTOM_EXT * 4))
  24592. static const ASNItem customExtASN[] = {
  24593. /* CUSTOM_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24594. /* CUSTOM_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  24595. /* CUSTOM_CRIT */ { 1, ASN_BOOLEAN, 0, 0, 0 },
  24596. /* CUSTOM_STR */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  24597. };
  24598. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  24599. int forRequest)
  24600. {
  24601. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  24602. int sz;
  24603. int ret = 0;
  24604. int i = 0;
  24605. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  24606. #ifdef WOLFSSL_ALT_NAMES
  24607. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  24608. #endif
  24609. #ifdef WOLFSSL_CERT_EXT
  24610. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  24611. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  24612. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  24613. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  24614. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  24615. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  24616. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  24617. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  24618. #endif
  24619. #ifdef WOLFSSL_SMALL_STACK
  24620. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24621. byte *encodedOids;
  24622. #endif
  24623. ASNItem *certExtsASN = (ASNItem *)XMALLOC(certExtsASN_Length *
  24624. sizeof(ASNItem), cert->heap,
  24625. DYNAMIC_TYPE_TMP_BUFFER);
  24626. if (certExtsASN == NULL) {
  24627. return MEMORY_E;
  24628. }
  24629. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24630. encodedOids = (byte *)XMALLOC(NUM_CUSTOM_EXT * MAX_OID_SZ, cert->heap,
  24631. DYNAMIC_TYPE_TMP_BUFFER);
  24632. if (encodedOids == NULL) {
  24633. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24634. return MEMORY_E;
  24635. }
  24636. #endif
  24637. #else
  24638. ASNItem certExtsASN[certExtsASN_Length];
  24639. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24640. byte encodedOids[NUM_CUSTOM_EXT * MAX_OID_SZ];
  24641. #endif
  24642. #endif
  24643. /* Clone static_certExtsASN into a certExtsASN and then fill the rest of it
  24644. * with (NUM_CUSTOM_EXT*4) more ASNItems specifying extensions. See comment
  24645. * above definition of certExtsASN_Length. */
  24646. XMEMCPY(certExtsASN, static_certExtsASN, sizeof(static_certExtsASN));
  24647. for (i = sizeof(static_certExtsASN) / sizeof(ASNItem);
  24648. i < (int)certExtsASN_Length; i += 4) {
  24649. XMEMCPY(&certExtsASN[i], customExtASN, sizeof(customExtASN));
  24650. }
  24651. (void)forRequest;
  24652. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  24653. if (ret == 0) {
  24654. if (cert->isCA) {
  24655. /* Set Basic Constraints to be a Certificate Authority. */
  24656. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_BC_CA], 1);
  24657. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24658. if (cert->pathLenSet
  24659. #ifdef WOLFSSL_CERT_EXT
  24660. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  24661. #endif
  24662. ) {
  24663. SetASN_Int8Bit(&dataASN[CERTEXTSASN_IDX_BC_PATHLEN],
  24664. cert->pathLen);
  24665. }
  24666. else {
  24667. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24668. }
  24669. }
  24670. else if (cert->basicConstSet) {
  24671. /* Set Basic Constraints to be a non Certificate Authority. */
  24672. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_BC_OID], bcOID, sizeof(bcOID));
  24673. dataASN[CERTEXTSASN_IDX_BC_CA].noOut = 1;
  24674. dataASN[CERTEXTSASN_IDX_BC_PATHLEN].noOut = 1;
  24675. }
  24676. else {
  24677. /* Don't write out Basic Constraints extension items. */
  24678. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_BC_SEQ,
  24679. CERTEXTSASN_IDX_BC_PATHLEN);
  24680. }
  24681. #ifdef WOLFSSL_ALT_NAMES
  24682. if (cert->altNamesSz > 0) {
  24683. /* Set Subject Alternative Name OID and data. */
  24684. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_OID],
  24685. sanOID, sizeof(sanOID));
  24686. if (cert->altNamesCrit) {
  24687. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_SAN_CRIT], 1);
  24688. }
  24689. else {
  24690. dataASN[CERTEXTSASN_IDX_SAN_CRIT].noOut = 1;
  24691. }
  24692. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SAN_STR],
  24693. cert->altNames, (word32)cert->altNamesSz);
  24694. }
  24695. else
  24696. #endif
  24697. {
  24698. /* Don't write out Subject Alternative Name extension items. */
  24699. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SAN_SEQ,
  24700. CERTEXTSASN_IDX_SAN_STR);
  24701. }
  24702. #ifdef WOLFSSL_CERT_EXT
  24703. if (cert->skidSz > 0) {
  24704. /* Set Subject Key Identifier OID and data. */
  24705. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_OID],
  24706. skidOID, sizeof(skidOID));
  24707. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_SKID_KEYID],
  24708. cert->skid, (word32)cert->skidSz);
  24709. }
  24710. else
  24711. #endif
  24712. {
  24713. /* Don't write out Subject Key Identifier extension items. */
  24714. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_SKID_SEQ,
  24715. CERTEXTSASN_IDX_SKID_KEYID);
  24716. }
  24717. #ifdef WOLFSSL_CERT_EXT
  24718. if (cert->akidSz > 0) {
  24719. /* Set Authority Key Identifier OID and data. */
  24720. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_OID],
  24721. akidOID, sizeof(akidOID));
  24722. #ifdef WOLFSSL_AKID_NAME
  24723. if (cert->rawAkid) {
  24724. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_STR],
  24725. cert->akid, cert->akidSz);
  24726. /* cert->akid contains the internal ext structure */
  24727. SetASNItem_NoOutBelow(dataASN, certExtsASN,
  24728. CERTEXTSASN_IDX_AKID_STR, certExtsASN_Length);
  24729. }
  24730. else
  24731. #endif
  24732. {
  24733. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_AKID_KEYID],
  24734. cert->akid, (word32)cert->akidSz);
  24735. }
  24736. }
  24737. else
  24738. #endif
  24739. {
  24740. /* Don't write out Authority Key Identifier extension items. */
  24741. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_AKID_SEQ,
  24742. CERTEXTSASN_IDX_AKID_KEYID);
  24743. }
  24744. #ifdef WOLFSSL_CERT_EXT
  24745. if (cert->keyUsage != 0) {
  24746. /* Set Key Usage OID, critical and value. */
  24747. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_KU_OID],
  24748. kuOID, sizeof(kuOID));
  24749. SetASN_Boolean(&dataASN[CERTEXTSASN_IDX_KU_CRIT], 1);
  24750. SetASN_Int16Bit(&dataASN[CERTEXTSASN_IDX_KU_USAGE],
  24751. cert->keyUsage);
  24752. }
  24753. else
  24754. #endif
  24755. {
  24756. /* Don't write out Key Usage extension items. */
  24757. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_KU_SEQ,
  24758. CERTEXTSASN_IDX_KU_USAGE);
  24759. }
  24760. #ifdef WOLFSSL_CERT_EXT
  24761. if (cert->extKeyUsage != 0) {
  24762. /* Calculate size of Extended Key Usage data. */
  24763. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  24764. if (sz <= 0) {
  24765. ret = KEYUSAGE_E;
  24766. }
  24767. /* Set Extended Key Usage OID and data. */
  24768. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_OID],
  24769. ekuOID, sizeof(ekuOID));
  24770. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_EKU_STR],
  24771. NULL, (word32)sz);
  24772. }
  24773. else
  24774. #endif
  24775. {
  24776. /* Don't write out Extended Key Usage extension items. */
  24777. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_EKU_SEQ,
  24778. CERTEXTSASN_IDX_EKU_STR);
  24779. }
  24780. #ifdef WOLFSSL_CERT_EXT
  24781. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24782. /* Calculate size of certificate policies. */
  24783. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  24784. cert->certPoliciesNb, cert->heap);
  24785. if (sz > 0) {
  24786. /* Set Certificate Policies OID. */
  24787. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_OID],
  24788. cpOID, sizeof(cpOID));
  24789. /* Make space for data. */
  24790. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_POLICIES_INFO],
  24791. NULL, (word32)sz);
  24792. }
  24793. else {
  24794. ret = CERTPOLICIES_E;
  24795. }
  24796. }
  24797. else
  24798. #endif
  24799. {
  24800. /* Don't write out Certificate Policies extension items. */
  24801. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_POLICIES_SEQ,
  24802. CERTEXTSASN_IDX_POLICIES_INFO);
  24803. }
  24804. #if defined(WOLFSSL_CERT_EXT) && !defined(IGNORE_NETSCAPE_CERT_TYPE)
  24805. /* Netscape Certificate Type */
  24806. if (cert->nsCertType != 0) {
  24807. /* Set Netscape Certificate Type OID and data. */
  24808. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_OID],
  24809. nsCertOID, sizeof(nsCertOID));
  24810. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_NSTYPE_USAGE],
  24811. &cert->nsCertType, 1);
  24812. }
  24813. else
  24814. #endif
  24815. {
  24816. /* Don't write out Netscape Certificate Type. */
  24817. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_NSTYPE_SEQ,
  24818. CERTEXTSASN_IDX_NSTYPE_USAGE);
  24819. }
  24820. #ifdef WOLFSSL_CERT_EXT
  24821. if (cert->crlInfoSz > 0) {
  24822. /* Set CRL Distribution Points OID and data. */
  24823. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_OID],
  24824. crlInfoOID, sizeof(crlInfoOID));
  24825. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CRLINFO_STR],
  24826. cert->crlInfo, (word32)cert->crlInfoSz);
  24827. }
  24828. else
  24829. #endif
  24830. {
  24831. /* Don't write out CRL Distribution Points. */
  24832. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CRLINFO_SEQ,
  24833. CERTEXTSASN_IDX_CRLINFO_STR);
  24834. }
  24835. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24836. /* encode a custom oid and value */
  24837. if (cert->extCustom.oidSz > 0) {
  24838. /* Set CRL Distribution Points OID and data. */
  24839. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_OID],
  24840. cert->extCustom.oid, cert->extCustom.oidSz);
  24841. SetASN_Buffer(&dataASN[CERTEXTSASN_IDX_CUSTOM_STR],
  24842. cert->extCustom.val, cert->extCustom.valSz);
  24843. }
  24844. else
  24845. #endif
  24846. {
  24847. /* Don't write out custom OID. */
  24848. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_CUSTOM_SEQ,
  24849. CERTEXTSASN_IDX_CUSTOM_STR);
  24850. }
  24851. i = 0;
  24852. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CUSTOM_OID)
  24853. for (; i < cert->customCertExtCount; i++) {
  24854. int idx = CERTEXTSASN_IDX_START_CUSTOM + (i * 4);
  24855. word32 encodedOidSz = MAX_OID_SZ;
  24856. idx++; /* Skip one for for SEQ. */
  24857. /* EncodePolicyOID() will never return error since we parsed this
  24858. * OID when it was set. */
  24859. EncodePolicyOID(&encodedOids[i * MAX_OID_SZ], &encodedOidSz,
  24860. cert->customCertExt[i].oid, NULL);
  24861. SetASN_Buffer(&dataASN[idx], &encodedOids[i * MAX_OID_SZ],
  24862. encodedOidSz);
  24863. idx++;
  24864. if (cert->customCertExt[i].crit) {
  24865. SetASN_Boolean(&dataASN[idx], 1);
  24866. } else {
  24867. dataASN[idx].noOut = 1;
  24868. }
  24869. idx++;
  24870. SetASN_Buffer(&dataASN[idx], cert->customCertExt[i].val,
  24871. cert->customCertExt[i].valSz);
  24872. }
  24873. #endif
  24874. while (i < NUM_CUSTOM_EXT) {
  24875. SetASNItem_NoOut(dataASN, CERTEXTSASN_IDX_START_CUSTOM + (i * 4),
  24876. CERTEXTSASN_IDX_START_CUSTOM + (i * 4) + 3);
  24877. i++;
  24878. }
  24879. }
  24880. if (ret == 0) {
  24881. /* Calculate size of encoded extensions. */
  24882. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  24883. }
  24884. if (ret == 0) {
  24885. /* Only SEQUENCE - don't encode extensions. */
  24886. if (sz == 2) {
  24887. sz = 0;
  24888. }
  24889. /* Check buffer is big enough. */
  24890. else if ((output != NULL) && (sz > (int)maxSz)) {
  24891. ret = BUFFER_E;
  24892. }
  24893. }
  24894. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  24895. /* Encode certificate extensions into buffer. */
  24896. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  24897. #ifdef WOLFSSL_CERT_EXT
  24898. if (cert->extKeyUsage != 0){
  24899. /* Encode Extended Key Usage into space provided. */
  24900. if (SetExtKeyUsage(cert,
  24901. (byte*)dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.data,
  24902. dataASN[CERTEXTSASN_IDX_EKU_STR].data.buffer.length,
  24903. cert->extKeyUsage) <= 0) {
  24904. ret = KEYUSAGE_E;
  24905. }
  24906. }
  24907. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  24908. /* Encode Certificate Policies into space provided. */
  24909. if (SetCertificatePolicies(
  24910. (byte*)dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.data,
  24911. dataASN[CERTEXTSASN_IDX_POLICIES_INFO].data.buffer.length,
  24912. cert->certPolicies, cert->certPoliciesNb, cert->heap) <= 0) {
  24913. ret = CERTPOLICIES_E;
  24914. }
  24915. }
  24916. #endif
  24917. }
  24918. if (ret == 0) {
  24919. /* Return the encoding size. */
  24920. ret = sz;
  24921. }
  24922. FREE_ASNSETDATA(dataASN, cert->heap);
  24923. #ifdef WOLFSSL_SMALL_STACK
  24924. #if defined(WOLFSSL_CUSTOM_OID) && defined(WOLFSSL_CERT_EXT)
  24925. XFREE(encodedOids, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24926. #endif
  24927. XFREE(certExtsASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24928. #endif
  24929. return ret;
  24930. }
  24931. #endif /* WOLFSSL_ASN_TEMPLATE */
  24932. #ifndef WOLFSSL_ASN_TEMPLATE
  24933. /* Set Date validity from now until now + daysValid
  24934. * return size in bytes written to output, 0 on error */
  24935. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  24936. * "MUST always encode certificate validity dates through the year 2049 as
  24937. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  24938. * GeneralizedTime." */
  24939. static int SetValidity(byte* output, int daysValid)
  24940. {
  24941. #ifndef NO_ASN_TIME
  24942. byte before[MAX_DATE_SIZE];
  24943. byte after[MAX_DATE_SIZE];
  24944. word32 beforeSz, afterSz, seqSz;
  24945. time_t now;
  24946. time_t then;
  24947. struct tm* tmpTime;
  24948. struct tm* expandedTime;
  24949. struct tm localTime;
  24950. #if defined(NEED_TMP_TIME)
  24951. /* for use with gmtime_r */
  24952. struct tm tmpTimeStorage;
  24953. tmpTime = &tmpTimeStorage;
  24954. #else
  24955. tmpTime = NULL;
  24956. #endif
  24957. (void)tmpTime;
  24958. now = wc_Time(0);
  24959. /* before now */
  24960. before[0] = ASN_GENERALIZED_TIME;
  24961. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  24962. /* subtract 1 day of seconds for more compliance */
  24963. then = now - 86400;
  24964. expandedTime = XGMTIME(&then, tmpTime);
  24965. if (expandedTime == NULL) {
  24966. WOLFSSL_MSG("XGMTIME failed");
  24967. return 0; /* error */
  24968. }
  24969. localTime = *expandedTime;
  24970. /* adjust */
  24971. localTime.tm_year += 1900;
  24972. localTime.tm_mon += 1;
  24973. SetTime(&localTime, before + beforeSz);
  24974. beforeSz += ASN_GEN_TIME_SZ;
  24975. after[0] = ASN_GENERALIZED_TIME;
  24976. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  24977. /* add daysValid of seconds */
  24978. then = now + (daysValid * (time_t)86400);
  24979. expandedTime = XGMTIME(&then, tmpTime);
  24980. if (expandedTime == NULL) {
  24981. WOLFSSL_MSG("XGMTIME failed");
  24982. return 0; /* error */
  24983. }
  24984. localTime = *expandedTime;
  24985. /* adjust */
  24986. localTime.tm_year += 1900;
  24987. localTime.tm_mon += 1;
  24988. SetTime(&localTime, after + afterSz);
  24989. afterSz += ASN_GEN_TIME_SZ;
  24990. /* headers and output */
  24991. seqSz = SetSequence(beforeSz + afterSz, output);
  24992. XMEMCPY(output + seqSz, before, beforeSz);
  24993. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  24994. return (int)(seqSz + beforeSz + afterSz);
  24995. #else
  24996. (void)output;
  24997. (void)daysValid;
  24998. return NOT_COMPILED_IN;
  24999. #endif
  25000. }
  25001. #else
  25002. static int SetValidity(byte* before, byte* after, int daysValid)
  25003. {
  25004. #ifndef NO_ASN_TIME
  25005. int ret = 0;
  25006. time_t now;
  25007. time_t then;
  25008. struct tm* tmpTime;
  25009. struct tm* expandedTime;
  25010. struct tm localTime;
  25011. #if defined(NEED_TMP_TIME)
  25012. /* for use with gmtime_r */
  25013. struct tm tmpTimeStorage;
  25014. tmpTime = &tmpTimeStorage;
  25015. #else
  25016. tmpTime = NULL;
  25017. #endif
  25018. (void)tmpTime;
  25019. now = wc_Time(0);
  25020. /* subtract 1 day of seconds for more compliance */
  25021. then = now - 86400;
  25022. expandedTime = XGMTIME(&then, tmpTime);
  25023. if (expandedTime == NULL) {
  25024. WOLFSSL_MSG("XGMTIME failed");
  25025. ret = DATE_E;
  25026. }
  25027. if (ret == 0) {
  25028. localTime = *expandedTime;
  25029. /* adjust */
  25030. localTime.tm_year += 1900;
  25031. localTime.tm_mon += 1;
  25032. SetTime(&localTime, before);
  25033. /* add daysValid of seconds */
  25034. then = now + (daysValid * (time_t)86400);
  25035. expandedTime = XGMTIME(&then, tmpTime);
  25036. if (expandedTime == NULL) {
  25037. WOLFSSL_MSG("XGMTIME failed");
  25038. ret = DATE_E;
  25039. }
  25040. }
  25041. if (ret == 0) {
  25042. localTime = *expandedTime;
  25043. /* adjust */
  25044. localTime.tm_year += 1900;
  25045. localTime.tm_mon += 1;
  25046. SetTime(&localTime, after);
  25047. }
  25048. return ret;
  25049. #else
  25050. (void)before;
  25051. (void)after;
  25052. (void)daysValid;
  25053. return NOT_COMPILED_IN;
  25054. #endif
  25055. }
  25056. #endif /* WOLFSSL_ASN_TEMPLATE */
  25057. #ifndef WOLFSSL_ASN_TEMPLATE
  25058. /* encode info from cert into DER encoded format */
  25059. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  25060. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  25061. ed448_key* ed448Key, falcon_key* falconKey,
  25062. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25063. {
  25064. int ret;
  25065. if (cert == NULL || der == NULL || rng == NULL)
  25066. return BAD_FUNC_ARG;
  25067. /* make sure at least one key type is provided */
  25068. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  25069. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  25070. dilithiumKey == NULL && sphincsKey == NULL) {
  25071. return PUBLIC_KEY_E;
  25072. }
  25073. /* init */
  25074. XMEMSET(der, 0, sizeof(DerCert));
  25075. /* version */
  25076. der->versionSz = SetMyVersion((word32)cert->version, der->version, TRUE);
  25077. /* serial number (must be positive) */
  25078. if (cert->serialSz == 0) {
  25079. /* generate random serial */
  25080. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25081. ret = wc_RNG_GenerateBlock(rng, cert->serial, (word32)cert->serialSz);
  25082. if (ret != 0)
  25083. return ret;
  25084. /* Clear the top bit to avoid a negative value */
  25085. cert->serial[0] &= 0x7f;
  25086. }
  25087. der->serialSz = SetSerialNumber(cert->serial, (word32)cert->serialSz,
  25088. der->serial, sizeof(der->serial),
  25089. CTC_SERIAL_SIZE);
  25090. if (der->serialSz < 0)
  25091. return der->serialSz;
  25092. /* signature algo */
  25093. der->sigAlgoSz = (int)SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  25094. if (der->sigAlgoSz <= 0)
  25095. return ALGO_ID_E;
  25096. /* public key */
  25097. #ifndef NO_RSA
  25098. if (cert->keyType == RSA_KEY) {
  25099. if (rsaKey == NULL)
  25100. return PUBLIC_KEY_E;
  25101. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  25102. sizeof(der->publicKey), 1);
  25103. }
  25104. #endif
  25105. #ifdef HAVE_ECC
  25106. if (cert->keyType == ECC_KEY) {
  25107. if (eccKey == NULL)
  25108. return PUBLIC_KEY_E;
  25109. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  25110. sizeof(der->publicKey), 1, 0);
  25111. }
  25112. #endif
  25113. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  25114. if (cert->keyType == DSA_KEY) {
  25115. if (dsaKey == NULL)
  25116. return PUBLIC_KEY_E;
  25117. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  25118. sizeof(der->publicKey), 1);
  25119. }
  25120. #endif
  25121. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  25122. if (cert->keyType == ED25519_KEY) {
  25123. if (ed25519Key == NULL)
  25124. return PUBLIC_KEY_E;
  25125. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  25126. (word32)sizeof(der->publicKey), 1);
  25127. }
  25128. #endif
  25129. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  25130. if (cert->keyType == ED448_KEY) {
  25131. if (ed448Key == NULL)
  25132. return PUBLIC_KEY_E;
  25133. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  25134. (word32)sizeof(der->publicKey), 1);
  25135. }
  25136. #endif
  25137. #if defined(HAVE_PQC)
  25138. #if defined(HAVE_FALCON)
  25139. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  25140. (cert->keyType == FALCON_LEVEL5_KEY)) {
  25141. if (falconKey == NULL)
  25142. return PUBLIC_KEY_E;
  25143. der->publicKeySz =
  25144. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  25145. (word32)sizeof(der->publicKey), 1);
  25146. }
  25147. #endif /* HAVE_FALCON */
  25148. #if defined(HAVE_DILITHIUM)
  25149. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  25150. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  25151. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  25152. if (dilithiumKey == NULL)
  25153. return PUBLIC_KEY_E;
  25154. der->publicKeySz =
  25155. wc_Dilithium_PublicKeyToDer(dilithiumKey, der->publicKey,
  25156. (word32)sizeof(der->publicKey), 1);
  25157. }
  25158. #endif /* HAVE_DILITHIUM */
  25159. #if defined(HAVE_SPHINCS)
  25160. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  25161. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  25162. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  25163. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  25164. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  25165. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  25166. if (sphincsKey == NULL)
  25167. return PUBLIC_KEY_E;
  25168. der->publicKeySz =
  25169. wc_Sphincs_PublicKeyToDer(sphincsKey, der->publicKey,
  25170. (word32)sizeof(der->publicKey), 1);
  25171. }
  25172. #endif /* HAVE_SPHINCS */
  25173. #endif /* HAVE_PQC */
  25174. if (der->publicKeySz <= 0)
  25175. return PUBLIC_KEY_E;
  25176. der->validitySz = 0;
  25177. /* copy date validity if already set in cert struct */
  25178. if (cert->beforeDateSz && cert->afterDateSz) {
  25179. der->validitySz = CopyValidity(der->validity, cert);
  25180. if (der->validitySz <= 0)
  25181. return DATE_E;
  25182. }
  25183. /* set date validity using daysValid if not set already */
  25184. if (der->validitySz == 0) {
  25185. der->validitySz = SetValidity(der->validity, cert->daysValid);
  25186. if (der->validitySz <= 0)
  25187. return DATE_E;
  25188. }
  25189. /* subject name */
  25190. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25191. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  25192. /* Use the raw subject */
  25193. word32 idx;
  25194. der->subjectSz = (int)min((word32)sizeof(der->subject),
  25195. (word32)XSTRLEN((const char*)cert->sbjRaw));
  25196. /* header */
  25197. idx = SetSequence((word32)der->subjectSz, der->subject);
  25198. if ((word32)der->subjectSz + idx > (word32)sizeof(der->subject)) {
  25199. return SUBJECT_E;
  25200. }
  25201. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  25202. (size_t)der->subjectSz);
  25203. der->subjectSz += (int)idx;
  25204. }
  25205. else
  25206. #endif
  25207. {
  25208. /* Use the name structure */
  25209. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  25210. &cert->subject, cert->heap);
  25211. }
  25212. if (der->subjectSz <= 0)
  25213. return SUBJECT_E;
  25214. /* issuer name */
  25215. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  25216. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  25217. /* Use the raw issuer */
  25218. word32 idx;
  25219. der->issuerSz = (int)min((word32)sizeof(der->issuer),
  25220. (word32)XSTRLEN((const char*)cert->issRaw));
  25221. /* header */
  25222. idx = SetSequence((word32)der->issuerSz, der->issuer);
  25223. if ((word32)der->issuerSz + idx > (word32)sizeof(der->issuer)) {
  25224. return ISSUER_E;
  25225. }
  25226. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  25227. (size_t)der->issuerSz);
  25228. der->issuerSz += (int)idx;
  25229. }
  25230. else
  25231. #endif
  25232. {
  25233. /* Use the name structure */
  25234. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  25235. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  25236. }
  25237. if (der->issuerSz <= 0)
  25238. return ISSUER_E;
  25239. /* set the extensions */
  25240. der->extensionsSz = 0;
  25241. /* RFC 5280 : 4.2.1.9. Basic Constraints
  25242. * The pathLenConstraint field is meaningful only if the CA boolean is
  25243. * asserted and the key usage extension, if present, asserts the
  25244. * keyCertSign bit */
  25245. /* Set CA and path length */
  25246. if ((cert->isCA) && (cert->pathLenSet)
  25247. #ifdef WOLFSSL_CERT_EXT
  25248. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  25249. #endif
  25250. ) {
  25251. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  25252. if (der->caSz <= 0)
  25253. return CA_TRUE_E;
  25254. der->extensionsSz += der->caSz;
  25255. }
  25256. /* Set CA */
  25257. else if (cert->isCA) {
  25258. der->caSz = SetCa(der->ca, sizeof(der->ca));
  25259. if (der->caSz <= 0)
  25260. return CA_TRUE_E;
  25261. der->extensionsSz += der->caSz;
  25262. }
  25263. /* Set Basic Constraint */
  25264. else if (cert->basicConstSet) {
  25265. der->caSz = SetBC(der->ca, sizeof(der->ca));
  25266. if (der->caSz <= 0)
  25267. return EXTENSIONS_E;
  25268. der->extensionsSz += der->caSz;
  25269. }
  25270. else
  25271. der->caSz = 0;
  25272. #ifdef WOLFSSL_ALT_NAMES
  25273. /* Alternative Name */
  25274. if (cert->altNamesSz) {
  25275. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  25276. cert->altNames, (word32)cert->altNamesSz,
  25277. cert->altNamesCrit);
  25278. if (der->altNamesSz <= 0)
  25279. return ALT_NAME_E;
  25280. der->extensionsSz += der->altNamesSz;
  25281. }
  25282. else
  25283. der->altNamesSz = 0;
  25284. #endif
  25285. #ifdef WOLFSSL_CERT_EXT
  25286. /* SKID */
  25287. if (cert->skidSz) {
  25288. /* check the provided SKID size */
  25289. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  25290. return SKID_E;
  25291. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  25292. cert (CTC_MAX_SKID_SIZE). */
  25293. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  25294. cert->skid, (word32)cert->skidSz);
  25295. if (der->skidSz <= 0)
  25296. return SKID_E;
  25297. der->extensionsSz += der->skidSz;
  25298. }
  25299. else
  25300. der->skidSz = 0;
  25301. /* AKID */
  25302. if (cert->akidSz) {
  25303. /* check the provided AKID size */
  25304. if ((
  25305. #ifdef WOLFSSL_AKID_NAME
  25306. !cert->rawAkid &&
  25307. #endif
  25308. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  25309. #ifdef WOLFSSL_AKID_NAME
  25310. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  25311. #endif
  25312. )
  25313. return AKID_E;
  25314. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  25315. (word32)cert->akidSz,
  25316. #ifdef WOLFSSL_AKID_NAME
  25317. cert->rawAkid
  25318. #else
  25319. 0
  25320. #endif
  25321. );
  25322. if (der->akidSz <= 0)
  25323. return AKID_E;
  25324. der->extensionsSz += der->akidSz;
  25325. }
  25326. else
  25327. der->akidSz = 0;
  25328. /* Key Usage */
  25329. if (cert->keyUsage != 0){
  25330. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  25331. cert->keyUsage);
  25332. if (der->keyUsageSz <= 0)
  25333. return KEYUSAGE_E;
  25334. der->extensionsSz += der->keyUsageSz;
  25335. }
  25336. else
  25337. der->keyUsageSz = 0;
  25338. /* Extended Key Usage */
  25339. if (cert->extKeyUsage != 0){
  25340. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  25341. sizeof(der->extKeyUsage), cert->extKeyUsage);
  25342. if (der->extKeyUsageSz <= 0)
  25343. return EXTKEYUSAGE_E;
  25344. der->extensionsSz += der->extKeyUsageSz;
  25345. }
  25346. else
  25347. der->extKeyUsageSz = 0;
  25348. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25349. /* Netscape Certificate Type */
  25350. if (cert->nsCertType != 0) {
  25351. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  25352. sizeof(der->nsCertType), cert->nsCertType);
  25353. if (der->nsCertTypeSz <= 0)
  25354. return EXTENSIONS_E;
  25355. der->extensionsSz += der->nsCertTypeSz;
  25356. }
  25357. else
  25358. der->nsCertTypeSz = 0;
  25359. #endif
  25360. if (cert->crlInfoSz > 0) {
  25361. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  25362. cert->crlInfo, cert->crlInfoSz);
  25363. if (der->crlInfoSz <= 0)
  25364. return EXTENSIONS_E;
  25365. der->extensionsSz += der->crlInfoSz;
  25366. }
  25367. else
  25368. der->crlInfoSz = 0;
  25369. /* Certificate Policies */
  25370. if (cert->certPoliciesNb != 0) {
  25371. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  25372. sizeof(der->certPolicies),
  25373. cert->certPolicies,
  25374. cert->certPoliciesNb,
  25375. cert->heap);
  25376. if (der->certPoliciesSz <= 0)
  25377. return CERTPOLICIES_E;
  25378. der->extensionsSz += der->certPoliciesSz;
  25379. }
  25380. else
  25381. der->certPoliciesSz = 0;
  25382. #endif /* WOLFSSL_CERT_EXT */
  25383. /* put extensions */
  25384. if (der->extensionsSz > 0) {
  25385. /* put the start of extensions sequence (ID, Size) */
  25386. der->extensionsSz = SetExtensionsHeader(der->extensions,
  25387. sizeof(der->extensions),
  25388. (word32)der->extensionsSz);
  25389. if (der->extensionsSz <= 0)
  25390. return EXTENSIONS_E;
  25391. /* put CA */
  25392. if (der->caSz) {
  25393. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25394. &der->extensionsSz,
  25395. der->ca, der->caSz);
  25396. if (ret == 0)
  25397. return EXTENSIONS_E;
  25398. }
  25399. #ifdef WOLFSSL_ALT_NAMES
  25400. /* put Alternative Names */
  25401. if (der->altNamesSz) {
  25402. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25403. &der->extensionsSz,
  25404. der->altNames, der->altNamesSz);
  25405. if (ret <= 0)
  25406. return EXTENSIONS_E;
  25407. }
  25408. #endif
  25409. #ifdef WOLFSSL_CERT_EXT
  25410. /* put SKID */
  25411. if (der->skidSz) {
  25412. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25413. &der->extensionsSz,
  25414. der->skid, der->skidSz);
  25415. if (ret <= 0)
  25416. return EXTENSIONS_E;
  25417. }
  25418. /* put AKID */
  25419. if (der->akidSz) {
  25420. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25421. &der->extensionsSz,
  25422. der->akid, der->akidSz);
  25423. if (ret <= 0)
  25424. return EXTENSIONS_E;
  25425. }
  25426. /* put CRL Distribution Points */
  25427. if (der->crlInfoSz) {
  25428. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25429. &der->extensionsSz,
  25430. der->crlInfo, der->crlInfoSz);
  25431. if (ret <= 0)
  25432. return EXTENSIONS_E;
  25433. }
  25434. /* put KeyUsage */
  25435. if (der->keyUsageSz) {
  25436. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25437. &der->extensionsSz,
  25438. der->keyUsage, der->keyUsageSz);
  25439. if (ret <= 0)
  25440. return EXTENSIONS_E;
  25441. }
  25442. /* put ExtendedKeyUsage */
  25443. if (der->extKeyUsageSz) {
  25444. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25445. &der->extensionsSz,
  25446. der->extKeyUsage, der->extKeyUsageSz);
  25447. if (ret <= 0)
  25448. return EXTENSIONS_E;
  25449. }
  25450. /* put Netscape Cert Type */
  25451. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  25452. if (der->nsCertTypeSz) {
  25453. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25454. &der->extensionsSz,
  25455. der->nsCertType, der->nsCertTypeSz);
  25456. if (ret <= 0)
  25457. return EXTENSIONS_E;
  25458. }
  25459. #endif
  25460. /* put Certificate Policies */
  25461. if (der->certPoliciesSz) {
  25462. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  25463. &der->extensionsSz,
  25464. der->certPolicies, der->certPoliciesSz);
  25465. if (ret <= 0)
  25466. return EXTENSIONS_E;
  25467. }
  25468. #endif /* WOLFSSL_CERT_EXT */
  25469. }
  25470. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  25471. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  25472. der->extensionsSz;
  25473. return 0;
  25474. }
  25475. /* write DER encoded cert to buffer, size already checked */
  25476. static int WriteCertBody(DerCert* der, byte* buf)
  25477. {
  25478. word32 idx;
  25479. /* signed part header */
  25480. idx = SetSequence((word32)der->total, buf);
  25481. /* version */
  25482. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  25483. idx += (word32)der->versionSz;
  25484. /* serial */
  25485. XMEMCPY(buf + idx, der->serial, (size_t)der->serialSz);
  25486. idx += (word32)der->serialSz;
  25487. /* sig algo */
  25488. XMEMCPY(buf + idx, der->sigAlgo, (size_t)der->sigAlgoSz);
  25489. idx += (word32)der->sigAlgoSz;
  25490. /* issuer */
  25491. XMEMCPY(buf + idx, der->issuer, (size_t)der->issuerSz);
  25492. idx += (word32)der->issuerSz;
  25493. /* validity */
  25494. XMEMCPY(buf + idx, der->validity, (size_t)der->validitySz);
  25495. idx += (word32)der->validitySz;
  25496. /* subject */
  25497. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  25498. idx += (word32)der->subjectSz;
  25499. /* public key */
  25500. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  25501. idx += (word32)der->publicKeySz;
  25502. if (der->extensionsSz) {
  25503. /* extensions */
  25504. XMEMCPY(buf + idx, der->extensions,
  25505. min((word32)der->extensionsSz,
  25506. (word32)sizeof(der->extensions)));
  25507. idx += (word32)der->extensionsSz;
  25508. }
  25509. return (int)idx;
  25510. }
  25511. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25512. /* Make signature from buffer (sz), write to sig (sigSz) */
  25513. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, word32 sz,
  25514. byte* sig, word32 sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  25515. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  25516. dilithium_key* dilithiumKey, sphincs_key* sphincsKey, WC_RNG* rng,
  25517. word32 sigAlgoType, void* heap)
  25518. {
  25519. int digestSz = 0, typeH = 0, ret = 0;
  25520. (void)digestSz;
  25521. (void)typeH;
  25522. (void)buf;
  25523. (void)sz;
  25524. (void)sig;
  25525. (void)sigSz;
  25526. (void)rsaKey;
  25527. (void)eccKey;
  25528. (void)ed25519Key;
  25529. (void)ed448Key;
  25530. (void)falconKey;
  25531. (void)dilithiumKey;
  25532. (void)sphincsKey;
  25533. (void)rng;
  25534. (void)heap;
  25535. switch (certSignCtx->state) {
  25536. case CERTSIGN_STATE_BEGIN:
  25537. case CERTSIGN_STATE_DIGEST:
  25538. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  25539. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  25540. DYNAMIC_TYPE_TMP_BUFFER);
  25541. if (certSignCtx->digest == NULL) {
  25542. ret = MEMORY_E; goto exit_ms;
  25543. }
  25544. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  25545. &typeH, &digestSz, 0);
  25546. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  25547. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  25548. if (ret != 0) {
  25549. goto exit_ms;
  25550. }
  25551. FALL_THROUGH;
  25552. case CERTSIGN_STATE_ENCODE:
  25553. #ifndef NO_RSA
  25554. if (rsaKey) {
  25555. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  25556. DYNAMIC_TYPE_TMP_BUFFER);
  25557. if (certSignCtx->encSig == NULL) {
  25558. ret = MEMORY_E; goto exit_ms;
  25559. }
  25560. /* signature */
  25561. certSignCtx->encSigSz = (int)wc_EncodeSignature(certSignCtx->encSig,
  25562. certSignCtx->digest, (word32)digestSz, typeH);
  25563. }
  25564. #endif /* !NO_RSA */
  25565. FALL_THROUGH;
  25566. case CERTSIGN_STATE_DO:
  25567. certSignCtx->state = CERTSIGN_STATE_DO;
  25568. ret = ALGO_ID_E; /* default to error */
  25569. #ifndef NO_RSA
  25570. if (rsaKey) {
  25571. /* signature */
  25572. ret = wc_RsaSSL_Sign(certSignCtx->encSig,
  25573. (word32)certSignCtx->encSigSz,
  25574. sig, sigSz, rsaKey, rng);
  25575. }
  25576. #endif /* !NO_RSA */
  25577. #if defined(HAVE_ECC) && defined(HAVE_ECC_SIGN)
  25578. if (!rsaKey && eccKey) {
  25579. word32 outSz = sigSz;
  25580. ret = wc_ecc_sign_hash(certSignCtx->digest, (word32)digestSz,
  25581. sig, &outSz, rng, eccKey);
  25582. if (ret == 0)
  25583. ret = (int)outSz;
  25584. }
  25585. #endif /* HAVE_ECC && HAVE_ECC_SIGN */
  25586. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  25587. if (!rsaKey && !eccKey && ed25519Key) {
  25588. word32 outSz = sigSz;
  25589. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  25590. if (ret == 0)
  25591. ret = (int)outSz;
  25592. }
  25593. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  25594. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  25595. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  25596. word32 outSz = sigSz;
  25597. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  25598. if (ret == 0)
  25599. ret = (int)outSz;
  25600. }
  25601. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  25602. #if defined(HAVE_PQC)
  25603. #if defined(HAVE_FALCON)
  25604. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  25605. word32 outSz = sigSz;
  25606. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  25607. if (ret == 0)
  25608. ret = outSz;
  25609. }
  25610. #endif /* HAVE_FALCON */
  25611. #if defined(HAVE_DILITHIUM)
  25612. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25613. dilithiumKey) {
  25614. word32 outSz = sigSz;
  25615. ret = wc_dilithium_sign_msg(buf, sz, sig, &outSz, dilithiumKey);
  25616. if (ret == 0)
  25617. ret = outSz;
  25618. }
  25619. #endif /* HAVE_DILITHIUM */
  25620. #if defined(HAVE_SPHINCS)
  25621. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && !falconKey &&
  25622. !dilithiumKey && sphincsKey) {
  25623. word32 outSz = sigSz;
  25624. ret = wc_sphincs_sign_msg(buf, sz, sig, &outSz, sphincsKey);
  25625. if (ret == 0)
  25626. ret = outSz;
  25627. }
  25628. #endif /* HAVE_SPHINCS */
  25629. #endif /* HAVE_PQC */
  25630. break;
  25631. }
  25632. exit_ms:
  25633. #ifdef WOLFSSL_ASYNC_CRYPT
  25634. if (ret == WC_PENDING_E) {
  25635. return ret;
  25636. }
  25637. #endif
  25638. #ifndef NO_RSA
  25639. if (rsaKey) {
  25640. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25641. }
  25642. #endif /* !NO_RSA */
  25643. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  25644. certSignCtx->digest = NULL;
  25645. /* reset state */
  25646. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  25647. if (ret < 0) {
  25648. WOLFSSL_ERROR_VERBOSE(ret);
  25649. }
  25650. return ret;
  25651. }
  25652. #ifdef WOLFSSL_ASN_TEMPLATE
  25653. /* Generate a random integer value of at most len bytes.
  25654. *
  25655. * Most-significant bit will not be set when maximum size.
  25656. * Random value may be smaller than maximum size in bytes.
  25657. *
  25658. * @param [in] rng Random number generator.
  25659. * @param [out] out Buffer to hold integer value.
  25660. * @param [in] len Maximum number of bytes of integer.
  25661. * @return 0 on success.
  25662. * @return -ve when random number generation failed.
  25663. */
  25664. static int GenerateInteger(WC_RNG* rng, byte* out, word32 len)
  25665. {
  25666. int ret;
  25667. /* Generate random number. */
  25668. ret = wc_RNG_GenerateBlock(rng, out, len);
  25669. if (ret == 0) {
  25670. int i;
  25671. /* Clear the top bit to make positive. */
  25672. out[0] &= 0x7f;
  25673. /* Find first non-zero byte. One zero byte is valid though. */
  25674. for (i = 0; i < (int)len - 1; i++) {
  25675. if (out[i] != 0) {
  25676. break;
  25677. }
  25678. }
  25679. if (i != 0) {
  25680. /* Remove leading zeros. */
  25681. XMEMMOVE(out, out + i, (size_t)len - (size_t)i);
  25682. }
  25683. }
  25684. return ret;
  25685. }
  25686. /* ASN.1 template for a Certificate.
  25687. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  25688. */
  25689. static const ASNItem sigASN[] = {
  25690. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25691. /* tbsCertificate */
  25692. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25693. /* signatureAlgorithm */
  25694. /* SIGALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25695. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25696. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  25697. /* signatureValue */
  25698. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25699. };
  25700. enum {
  25701. SIGASN_IDX_SEQ = 0,
  25702. SIGASN_IDX_TBS_SEQ,
  25703. SIGASN_IDX_SIGALGO_SEQ,
  25704. SIGASN_IDX_SIGALGO_OID,
  25705. SIGASN_IDX_SIGALGO_NULL,
  25706. SIGASN_IDX_SIGNATURE
  25707. };
  25708. /* Number of items in ASN.1 template for a Certificate. */
  25709. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  25710. #endif
  25711. /* add signature to end of buffer, size of buffer assumed checked, return
  25712. new length */
  25713. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  25714. int sigAlgoType)
  25715. {
  25716. #ifndef WOLFSSL_ASN_TEMPLATE
  25717. byte seq[MAX_SEQ_SZ];
  25718. word32 idx, seqSz;
  25719. if ((bodySz < 0) || (sigSz < 0))
  25720. return BUFFER_E;
  25721. idx = (word32)bodySz;
  25722. /* algo */
  25723. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  25724. /* bit string */
  25725. idx += SetBitString((word32)sigSz, 0, buf ? buf + idx : NULL);
  25726. /* signature */
  25727. if (buf)
  25728. XMEMCPY(buf + idx, sig, (size_t)sigSz);
  25729. idx += (word32)sigSz;
  25730. /* make room for overall header */
  25731. seqSz = SetSequence(idx, seq);
  25732. if (buf) {
  25733. XMEMMOVE(buf + seqSz, buf, idx);
  25734. XMEMCPY(buf, seq, seqSz);
  25735. }
  25736. return (int)(idx + seqSz);
  25737. #else
  25738. DECL_ASNSETDATA(dataASN, sigASN_Length);
  25739. word32 seqSz;
  25740. int sz;
  25741. int ret = 0;
  25742. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  25743. /* In place, put body between SEQUENCE and signature. */
  25744. if (ret == 0) {
  25745. /* Set sigature OID and signature data. */
  25746. SetASN_OID(&dataASN[SIGASN_IDX_SIGALGO_OID], (word32)sigAlgoType,
  25747. oidSigType);
  25748. if (IsSigAlgoECC((word32)sigAlgoType)) {
  25749. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  25750. dataASN[SIGASN_IDX_SIGALGO_NULL].noOut = 1;
  25751. }
  25752. SetASN_Buffer(&dataASN[SIGASN_IDX_SIGNATURE], sig, (word32)sigSz);
  25753. /* Calculate size of signature data. */
  25754. ret = SizeASN_Items(&sigASN[SIGASN_IDX_SIGALGO_SEQ],
  25755. &dataASN[SIGASN_IDX_SIGALGO_SEQ], sigASN_Length - 2, &sz);
  25756. }
  25757. if (ret == 0) {
  25758. /* Calculate size of outer sequence by calculating size of the encoded
  25759. * length and adding 1 for tag. */
  25760. seqSz = SizeASNHeader((word32)bodySz + (word32)sz);
  25761. if (buf != NULL) {
  25762. /* Move body to after sequence. */
  25763. XMEMMOVE(buf + seqSz, buf, (size_t)bodySz);
  25764. }
  25765. /* Leave space for body in encoding. */
  25766. SetASN_ReplaceBuffer(&dataASN[SIGASN_IDX_TBS_SEQ], NULL,
  25767. (word32)bodySz);
  25768. /* Calculate overall size and put in offsets and lengths. */
  25769. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  25770. }
  25771. if ((ret == 0) && (buf != NULL)) {
  25772. /* Write SEQUENCE and signature around body. */
  25773. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  25774. }
  25775. if (ret == 0) {
  25776. /* Return the encoding size. */
  25777. ret = sz;
  25778. }
  25779. FREE_ASNSETDATA(dataASN, NULL);
  25780. return ret;
  25781. #endif /* WOLFSSL_ASN_TEMPLATE */
  25782. }
  25783. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  25784. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  25785. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  25786. DsaKey* dsaKey, ed25519_key* ed25519Key,
  25787. ed448_key* ed448Key, falcon_key* falconKey,
  25788. dilithium_key* dilithiumKey, sphincs_key* sphincsKey)
  25789. {
  25790. #ifndef WOLFSSL_ASN_TEMPLATE
  25791. int ret;
  25792. #ifdef WOLFSSL_SMALL_STACK
  25793. DerCert* der;
  25794. #else
  25795. DerCert der[1];
  25796. #endif
  25797. if (derBuffer == NULL)
  25798. return BAD_FUNC_ARG;
  25799. if (eccKey)
  25800. cert->keyType = ECC_KEY;
  25801. else if (rsaKey)
  25802. cert->keyType = RSA_KEY;
  25803. else if (dsaKey)
  25804. cert->keyType = DSA_KEY;
  25805. else if (ed25519Key)
  25806. cert->keyType = ED25519_KEY;
  25807. else if (ed448Key)
  25808. cert->keyType = ED448_KEY;
  25809. #ifdef HAVE_PQC
  25810. #ifdef HAVE_FALCON
  25811. else if ((falconKey != NULL) && (falconKey->level == 1))
  25812. cert->keyType = FALCON_LEVEL1_KEY;
  25813. else if ((falconKey != NULL) && (falconKey->level == 5))
  25814. cert->keyType = FALCON_LEVEL5_KEY;
  25815. #endif /* HAVE_FALCON */
  25816. #ifdef HAVE_DILITHIUM
  25817. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  25818. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25819. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  25820. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25821. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  25822. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25823. #endif /* HAVE_DILITHIUM */
  25824. #ifdef HAVE_SPHINCS
  25825. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25826. && (sphincsKey->optim == FAST_VARIANT))
  25827. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25828. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25829. && (sphincsKey->optim == FAST_VARIANT))
  25830. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25831. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25832. && (sphincsKey->optim == FAST_VARIANT))
  25833. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25834. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25835. && (sphincsKey->optim == SMALL_VARIANT))
  25836. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25837. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25838. && (sphincsKey->optim == SMALL_VARIANT))
  25839. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25840. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25841. && (sphincsKey->optim == SMALL_VARIANT))
  25842. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25843. #endif /* HAVE_SPHINCS */
  25844. #endif /* HAVE_PQC */
  25845. else
  25846. return BAD_FUNC_ARG;
  25847. #ifdef WOLFSSL_SMALL_STACK
  25848. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25849. if (der == NULL)
  25850. return MEMORY_E;
  25851. #endif
  25852. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  25853. ed448Key, falconKey, dilithiumKey, sphincsKey);
  25854. if (ret == 0) {
  25855. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  25856. ret = BUFFER_E;
  25857. else
  25858. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  25859. }
  25860. #ifdef WOLFSSL_SMALL_STACK
  25861. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  25862. #endif
  25863. return ret;
  25864. #else
  25865. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  25866. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  25867. word32 publicKeySz = 0;
  25868. word32 issuerSz = 0;
  25869. word32 subjectSz = 0;
  25870. word32 extSz = 0;
  25871. int sz = 0;
  25872. int ret = 0;
  25873. word32 issRawLen = 0;
  25874. word32 sbjRawLen = 0;
  25875. /* Unused without OQS */
  25876. (void)falconKey;
  25877. (void)dilithiumKey;
  25878. (void)sphincsKey;
  25879. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  25880. if (ret == 0) {
  25881. /* Set key type into certificate object based on key passed in. */
  25882. if (rsaKey) {
  25883. cert->keyType = RSA_KEY;
  25884. }
  25885. else if (eccKey) {
  25886. cert->keyType = ECC_KEY;
  25887. }
  25888. else if (dsaKey) {
  25889. cert->keyType = DSA_KEY;
  25890. }
  25891. else if (ed25519Key) {
  25892. cert->keyType = ED25519_KEY;
  25893. }
  25894. else if (ed448Key) {
  25895. cert->keyType = ED448_KEY;
  25896. }
  25897. #ifdef HAVE_PQC
  25898. #ifdef HAVE_FALCON
  25899. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  25900. cert->keyType = FALCON_LEVEL1_KEY;
  25901. }
  25902. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  25903. cert->keyType = FALCON_LEVEL5_KEY;
  25904. }
  25905. #endif /* HAVE_FALCON */
  25906. #ifdef HAVE_DILITHIUM
  25907. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  25908. cert->keyType = DILITHIUM_LEVEL2_KEY;
  25909. }
  25910. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  25911. cert->keyType = DILITHIUM_LEVEL3_KEY;
  25912. }
  25913. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  25914. cert->keyType = DILITHIUM_LEVEL5_KEY;
  25915. }
  25916. #endif /* HAVE_DILITHIUM */
  25917. #ifdef HAVE_SPHINCS
  25918. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25919. && (sphincsKey->optim == FAST_VARIANT)) {
  25920. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  25921. }
  25922. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25923. && (sphincsKey->optim == FAST_VARIANT)) {
  25924. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  25925. }
  25926. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25927. && (sphincsKey->optim == FAST_VARIANT)) {
  25928. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  25929. }
  25930. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  25931. && (sphincsKey->optim == SMALL_VARIANT)) {
  25932. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  25933. }
  25934. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  25935. && (sphincsKey->optim == SMALL_VARIANT)) {
  25936. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  25937. }
  25938. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  25939. && (sphincsKey->optim == SMALL_VARIANT)) {
  25940. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  25941. }
  25942. #endif /* HAVE_SPHINCS */
  25943. #endif /* HAVE_PQC */
  25944. else {
  25945. ret = BAD_FUNC_ARG;
  25946. }
  25947. }
  25948. if ((ret == 0) && (cert->serialSz == 0)) {
  25949. /* Generate random serial number. */
  25950. cert->serialSz = CTC_GEN_SERIAL_SZ;
  25951. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  25952. }
  25953. if (ret == 0) {
  25954. /* Determine issuer name size. */
  25955. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25956. defined(WOLFSSL_CERT_REQ)
  25957. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  25958. if (issRawLen > 0) {
  25959. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  25960. }
  25961. else
  25962. #endif
  25963. {
  25964. /* Calculate issuer name encoding size. If the cert is self-signed
  25965. * use the subject instead of the issuer. */
  25966. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, cert->selfSigned ?
  25967. &cert->subject : &cert->issuer, cert->heap);
  25968. issuerSz = (word32)ret;
  25969. }
  25970. }
  25971. if (ret >= 0) {
  25972. /* Determine subject name size. */
  25973. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  25974. defined(WOLFSSL_CERT_REQ)
  25975. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  25976. if (sbjRawLen > 0) {
  25977. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  25978. }
  25979. else
  25980. #endif
  25981. {
  25982. /* Calculate subject name encoding size. */
  25983. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject,
  25984. cert->heap);
  25985. subjectSz = (word32)ret;
  25986. }
  25987. }
  25988. if (ret >= 0) {
  25989. /* Calculate public key encoding size. */
  25990. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  25991. eccKey, ed25519Key, ed448Key, dsaKey);
  25992. publicKeySz = (word32)ret;
  25993. }
  25994. if (ret >= 0) {
  25995. /* Calculate extensions encoding size - may be 0. */
  25996. ret = EncodeExtensions(cert, NULL, 0, 0);
  25997. extSz = (word32)ret;
  25998. }
  25999. if (ret >= 0) {
  26000. /* Don't write out outer sequence - only doing body. */
  26001. dataASN[X509CERTASN_IDX_SEQ].noOut = 1;
  26002. /* Set version, serial number and signature OID */
  26003. SetASN_Int8Bit(&dataASN[X509CERTASN_IDX_TBS_VER_INT],
  26004. (byte)cert->version);
  26005. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SERIAL], cert->serial,
  26006. (word32)cert->serialSz);
  26007. SetASN_OID(&dataASN[X509CERTASN_IDX_TBS_ALGOID_OID],
  26008. (word32)cert->sigType, oidSigType);
  26009. if (IsSigAlgoECC((word32)cert->sigType)) {
  26010. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  26011. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS_NULL].noOut = 1;
  26012. }
  26013. #ifdef WC_RSA_PSS
  26014. /* TODO: Encode RSA PSS parameters. */
  26015. dataASN[X509CERTASN_IDX_TBS_ALGOID_PARAMS].noOut = 1;
  26016. #endif
  26017. if (issRawLen > 0) {
  26018. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26019. defined(WOLFSSL_CERT_REQ)
  26020. /* Put in encoded issuer name. */
  26021. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  26022. cert->issRaw, issuerSz);
  26023. #endif
  26024. }
  26025. else {
  26026. /* Leave space for issuer name. */
  26027. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ],
  26028. NULL, issuerSz);
  26029. }
  26030. if (cert->beforeDateSz && cert->afterDateSz) {
  26031. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  26032. /* Make space for before date data. */
  26033. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC],
  26034. cert->beforeDate + 2, ASN_UTC_TIME_SIZE - 1);
  26035. /* Don't put out Generalized Time before data. */
  26036. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT].noOut = 1;
  26037. }
  26038. else {
  26039. /* Don't put out UTC before data. */
  26040. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  26041. /* Make space for before date data. */
  26042. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  26043. cert->beforeDate + 2, ASN_GEN_TIME_SZ);
  26044. }
  26045. if (cert->afterDate[0] == ASN_UTC_TIME) {
  26046. /* Make space for after date data. */
  26047. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC],
  26048. cert->afterDate + 2, ASN_UTC_TIME_SIZE - 1);
  26049. /* Don't put out UTC Generalized Time after data. */
  26050. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT].noOut = 1;
  26051. }
  26052. else {
  26053. /* Don't put out UTC after data. */
  26054. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  26055. /* Make space for after date data. */
  26056. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  26057. cert->afterDate + 2, ASN_GEN_TIME_SZ);
  26058. }
  26059. }
  26060. else
  26061. {
  26062. /* Don't put out UTC before data. */
  26063. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_UTC].noOut = 1;
  26064. /* Make space for before date data. */
  26065. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT],
  26066. NULL, ASN_GEN_TIME_SZ);
  26067. /* Don't put out UTC after data. */
  26068. dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_UTC].noOut = 1;
  26069. /* Make space for after date data. */
  26070. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT],
  26071. NULL, ASN_GEN_TIME_SZ);
  26072. }
  26073. if (sbjRawLen > 0) {
  26074. /* Put in encoded subject name. */
  26075. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  26076. defined(WOLFSSL_CERT_REQ)
  26077. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  26078. cert->sbjRaw, subjectSz);
  26079. #endif
  26080. }
  26081. else {
  26082. /* Leave space for subject name. */
  26083. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ],
  26084. NULL, subjectSz);
  26085. }
  26086. /* Leave space for public key. */
  26087. SetASN_ReplaceBuffer(&dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ],
  26088. NULL, publicKeySz);
  26089. /* Replacement buffer instead of algorithm identifier items. */
  26090. SetASNItem_NoOut(dataASN,
  26091. X509CERTASN_IDX_TBS_SPUBKEYINFO_ALGO_SEQ,
  26092. X509CERTASN_IDX_TBS_SPUBKEYINFO_PUBKEY);
  26093. /* issuerUniqueID and subjectUniqueID not supported. */
  26094. dataASN[X509CERTASN_IDX_TBS_ISSUERUID].noOut = 1;
  26095. dataASN[X509CERTASN_IDX_TBS_SUBJECTUID].noOut = 1;
  26096. /* Leave space for extensions if any set into certificate object. */
  26097. if (extSz > 0) {
  26098. SetASN_Buffer(&dataASN[X509CERTASN_IDX_TBS_EXT_SEQ], NULL, extSz);
  26099. }
  26100. else {
  26101. SetASNItem_NoOutNode(dataASN, x509CertASN,
  26102. X509CERTASN_IDX_TBS_EXT, x509CertASN_Length);
  26103. }
  26104. /* No signature - added later. */
  26105. SetASNItem_NoOut(dataASN, X509CERTASN_IDX_SIGALGO_SEQ,
  26106. X509CERTASN_IDX_SIGNATURE);
  26107. /* Calculate encoded certificate body size. */
  26108. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  26109. }
  26110. /* Check buffer is big enough for encoded data. */
  26111. if ((ret == 0) && (sz > (int)derSz)) {
  26112. ret = BUFFER_E;
  26113. }
  26114. if (ret == 0) {
  26115. /* Encode certificate body into buffer. */
  26116. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  26117. if (issRawLen == 0) {
  26118. /* Encode issuer name into buffer. Use the subject as the issuer
  26119. * if it is self-signed. Size will be correct because we did the
  26120. * same for size. */
  26121. ret = SetNameEx(
  26122. (byte*)dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.data,
  26123. dataASN[X509CERTASN_IDX_TBS_ISSUER_SEQ].data.buffer.length,
  26124. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  26125. }
  26126. }
  26127. if ((ret >= 0) && (sbjRawLen == 0)) {
  26128. /* Encode subject name into buffer. */
  26129. ret = SetNameEx(
  26130. (byte*)dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.data,
  26131. dataASN[X509CERTASN_IDX_TBS_SUBJECT_SEQ].data.buffer.length,
  26132. &cert->subject, cert->heap);
  26133. }
  26134. if (ret >= 0) {
  26135. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  26136. {
  26137. /* Encode validity into buffer. */
  26138. ret = SetValidity(
  26139. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTB_GT]
  26140. .data.buffer.data,
  26141. (byte*)dataASN[X509CERTASN_IDX_TBS_VALIDITY_NOTA_GT]
  26142. .data.buffer.data, cert->daysValid);
  26143. }
  26144. }
  26145. if (ret >= 0) {
  26146. /* Encode public key into buffer. */
  26147. ret = EncodePublicKey(cert->keyType,
  26148. (byte*)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  26149. .data.buffer.data,
  26150. (int)dataASN[X509CERTASN_IDX_TBS_SPUBKEYINFO_SEQ]
  26151. .data.buffer.length,
  26152. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  26153. }
  26154. if ((ret >= 0) && (!dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].noOut)) {
  26155. /* Encode extensions into buffer. */
  26156. ret = EncodeExtensions(cert,
  26157. (byte*)dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.data,
  26158. dataASN[X509CERTASN_IDX_TBS_EXT_SEQ].data.buffer.length, 0);
  26159. }
  26160. if (ret >= 0) {
  26161. /* Store encoded certifcate body size. */
  26162. cert->bodySz = sz;
  26163. /* Return the encoding size. */
  26164. ret = sz;
  26165. }
  26166. FREE_ASNSETDATA(dataASN, cert->heap);
  26167. return ret;
  26168. #endif
  26169. }
  26170. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26171. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  26172. void* key, WC_RNG* rng)
  26173. {
  26174. RsaKey* rsaKey = NULL;
  26175. DsaKey* dsaKey = NULL;
  26176. ecc_key* eccKey = NULL;
  26177. ed25519_key* ed25519Key = NULL;
  26178. ed448_key* ed448Key = NULL;
  26179. falcon_key* falconKey = NULL;
  26180. dilithium_key* dilithiumKey = NULL;
  26181. sphincs_key* sphincsKey = NULL;
  26182. if (keyType == RSA_TYPE)
  26183. rsaKey = (RsaKey*)key;
  26184. else if (keyType == DSA_TYPE)
  26185. dsaKey = (DsaKey*)key;
  26186. else if (keyType == ECC_TYPE)
  26187. eccKey = (ecc_key*)key;
  26188. else if (keyType == ED25519_TYPE)
  26189. ed25519Key = (ed25519_key*)key;
  26190. else if (keyType == ED448_TYPE)
  26191. ed448Key = (ed448_key*)key;
  26192. else if (keyType == FALCON_LEVEL1_TYPE)
  26193. falconKey = (falcon_key*)key;
  26194. else if (keyType == FALCON_LEVEL5_TYPE)
  26195. falconKey = (falcon_key*)key;
  26196. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  26197. dilithiumKey = (dilithium_key*)key;
  26198. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  26199. dilithiumKey = (dilithium_key*)key;
  26200. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  26201. dilithiumKey = (dilithium_key*)key;
  26202. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  26203. sphincsKey = (sphincs_key*)key;
  26204. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  26205. sphincsKey = (sphincs_key*)key;
  26206. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  26207. sphincsKey = (sphincs_key*)key;
  26208. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  26209. sphincsKey = (sphincs_key*)key;
  26210. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  26211. sphincsKey = (sphincs_key*)key;
  26212. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  26213. sphincsKey = (sphincs_key*)key;
  26214. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  26215. ed25519Key, ed448Key, falconKey, dilithiumKey,
  26216. sphincsKey);
  26217. }
  26218. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  26219. WOLFSSL_ABI
  26220. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  26221. ecc_key* eccKey, WC_RNG* rng)
  26222. {
  26223. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  26224. NULL, NULL, NULL, NULL);
  26225. }
  26226. #ifdef WOLFSSL_CERT_REQ
  26227. #ifndef WOLFSSL_ASN_TEMPLATE
  26228. /* return size of data set on success
  26229. * if getting size only then attr and oid should be NULL
  26230. */
  26231. static word32 SetReqAttribSingle(byte* output, word32* idx, char* attr,
  26232. word32 attrSz, const byte* oid, word32 oidSz, byte printable,
  26233. word32 extSz)
  26234. {
  26235. word32 totalSz = 0;
  26236. word32 seqSz = 0;
  26237. word32 setSz = 0;
  26238. word32 strSz = 0;
  26239. byte seq[MAX_SEQ_SZ];
  26240. byte set[MAX_SET_SZ];
  26241. byte str[MAX_PRSTR_SZ];
  26242. totalSz = (word32)SetObjectId((int)oidSz, NULL);
  26243. totalSz += oidSz;
  26244. if (extSz > 0) {
  26245. totalSz += setSz = SetSet(extSz, set);
  26246. totalSz += seqSz = SetSequence(totalSz + extSz, seq);
  26247. totalSz += extSz;
  26248. }
  26249. else {
  26250. if (printable) {
  26251. strSz = SetPrintableString(attrSz, str);
  26252. totalSz += strSz;
  26253. }
  26254. else {
  26255. totalSz += strSz = SetUTF8String(attrSz, str);
  26256. }
  26257. totalSz += setSz = SetSet(strSz + attrSz, set);
  26258. totalSz += seqSz = SetSequence(totalSz + attrSz, seq);
  26259. totalSz += attrSz;
  26260. }
  26261. if (oid) {
  26262. XMEMCPY(&output[*idx], seq, seqSz);
  26263. *idx += seqSz;
  26264. *idx += (word32)SetObjectId((int)oidSz, output + *idx);
  26265. XMEMCPY(&output[*idx], oid, oidSz);
  26266. *idx += oidSz;
  26267. XMEMCPY(&output[*idx], set, setSz);
  26268. *idx += setSz;
  26269. if (strSz > 0) {
  26270. XMEMCPY(&output[*idx], str, strSz);
  26271. *idx += strSz;
  26272. if (attrSz > 0) {
  26273. XMEMCPY(&output[*idx], attr, attrSz);
  26274. *idx += attrSz;
  26275. }
  26276. }
  26277. }
  26278. return totalSz;
  26279. }
  26280. static int SetReqAttrib(byte* output, Cert* cert, word32 extSz)
  26281. {
  26282. word32 sz = 0; /* overall size */
  26283. word32 setSz = 0;
  26284. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  26285. sz++;
  26286. if (cert->challengePw[0]) {
  26287. setSz += SetReqAttribSingle(output, &sz, NULL,
  26288. (word32)XSTRLEN(cert->challengePw), NULL,
  26289. sizeof(attrChallengePasswordOid),
  26290. (byte)cert->challengePwPrintableString, 0);
  26291. }
  26292. if (cert->unstructuredName[0]) {
  26293. setSz += SetReqAttribSingle(output, &sz, NULL,
  26294. (word32)XSTRLEN(cert->unstructuredName), NULL,
  26295. sizeof(attrUnstructuredNameOid), 1, 0);
  26296. }
  26297. if (extSz) {
  26298. setSz += SetReqAttribSingle(output, &sz, NULL, 0, NULL,
  26299. sizeof(attrExtensionRequestOid), 1, extSz);
  26300. }
  26301. /* Put the pieces together. */
  26302. sz += SetLength(setSz, &output[sz]);
  26303. if (sz + setSz - extSz > MAX_ATTRIB_SZ) {
  26304. WOLFSSL_MSG("Attribute Buffer is not big enough!");
  26305. return REQ_ATTRIBUTE_E;
  26306. }
  26307. if (cert->challengePw[0]) {
  26308. SetReqAttribSingle(output, &sz, cert->challengePw,
  26309. (word32)XSTRLEN(cert->challengePw),
  26310. &attrChallengePasswordOid[0],
  26311. sizeof(attrChallengePasswordOid),
  26312. (byte)cert->challengePwPrintableString, 0);
  26313. }
  26314. if (cert->unstructuredName[0]) {
  26315. SetReqAttribSingle(output, &sz, cert->unstructuredName,
  26316. (word32)XSTRLEN(cert->unstructuredName),
  26317. &attrUnstructuredNameOid[0],
  26318. sizeof(attrUnstructuredNameOid), 1, 0);
  26319. }
  26320. if (extSz) {
  26321. SetReqAttribSingle(output, &sz, NULL, 0, &attrExtensionRequestOid[0],
  26322. sizeof(attrExtensionRequestOid), 1, extSz);
  26323. /* The actual extension data will be tacked onto the output later. */
  26324. }
  26325. return (int)sz;
  26326. }
  26327. #ifdef WOLFSSL_CUSTOM_OID
  26328. /* encode a custom oid and value */
  26329. static int SetCustomObjectId(Cert* cert, byte* output, word32 outSz,
  26330. CertOidField* custom)
  26331. {
  26332. int idx = 0, cust_lenSz, cust_oidSz;
  26333. if (cert == NULL || output == NULL || custom == NULL) {
  26334. return BAD_FUNC_ARG;
  26335. }
  26336. if (custom->oid == NULL || custom->oidSz <= 0) {
  26337. return 0; /* none set */
  26338. }
  26339. /* Octet String header */
  26340. cust_lenSz = SetOctetString(custom->valSz, NULL);
  26341. cust_oidSz = SetObjectId(custom->oidSz, NULL);
  26342. /* check for output buffer room */
  26343. if ((word32)(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz) >
  26344. outSz) {
  26345. return BUFFER_E;
  26346. }
  26347. /* put sequence with total */
  26348. idx = SetSequence(custom->valSz + custom->oidSz + cust_lenSz + cust_oidSz,
  26349. output);
  26350. /* put oid header */
  26351. idx += SetObjectId(custom->oidSz, output+idx);
  26352. XMEMCPY(output+idx, custom->oid, custom->oidSz);
  26353. idx += custom->oidSz;
  26354. /* put value */
  26355. idx += SetOctetString(custom->valSz, output+idx);
  26356. XMEMCPY(output+idx, custom->val, custom->valSz);
  26357. idx += custom->valSz;
  26358. return idx;
  26359. }
  26360. #endif /* WOLFSSL_CUSTOM_OID */
  26361. /* encode info from cert into DER encoded format */
  26362. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  26363. DsaKey* dsaKey, ecc_key* eccKey,
  26364. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26365. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26366. sphincs_key* sphincsKey)
  26367. {
  26368. int ret;
  26369. (void)eccKey;
  26370. (void)ed25519Key;
  26371. (void)ed448Key;
  26372. (void)falconKey;
  26373. (void)dilithiumKey;
  26374. (void)sphincsKey;
  26375. if (cert == NULL || der == NULL)
  26376. return BAD_FUNC_ARG;
  26377. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  26378. dsaKey == NULL && ed448Key == NULL && falconKey == NULL &&
  26379. falconKey == NULL) {
  26380. return PUBLIC_KEY_E;
  26381. }
  26382. /* init */
  26383. XMEMSET(der, 0, sizeof(DerCert));
  26384. /* version */
  26385. der->versionSz = SetMyVersion((word32)cert->version, der->version, FALSE);
  26386. /* subject name */
  26387. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26388. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  26389. /* Use the raw subject */
  26390. int idx;
  26391. der->subjectSz = (int)min(sizeof(der->subject),
  26392. (word32)XSTRLEN((const char*)cert->sbjRaw));
  26393. /* header */
  26394. idx = (int)SetSequence((word32)der->subjectSz, der->subject);
  26395. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  26396. return SUBJECT_E;
  26397. }
  26398. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  26399. (size_t)der->subjectSz);
  26400. der->subjectSz += idx;
  26401. }
  26402. else
  26403. #endif
  26404. {
  26405. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  26406. &cert->subject, cert->heap);
  26407. }
  26408. if (der->subjectSz <= 0)
  26409. return SUBJECT_E;
  26410. /* public key */
  26411. #ifndef NO_RSA
  26412. if (cert->keyType == RSA_KEY) {
  26413. if (rsaKey == NULL)
  26414. return PUBLIC_KEY_E;
  26415. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  26416. sizeof(der->publicKey), 1);
  26417. }
  26418. #endif
  26419. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  26420. if (cert->keyType == DSA_KEY) {
  26421. if (dsaKey == NULL)
  26422. return PUBLIC_KEY_E;
  26423. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  26424. sizeof(der->publicKey), 1);
  26425. }
  26426. #endif
  26427. #ifdef HAVE_ECC
  26428. if (cert->keyType == ECC_KEY) {
  26429. if (eccKey == NULL)
  26430. return PUBLIC_KEY_E;
  26431. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  26432. sizeof(der->publicKey), 1, 0);
  26433. }
  26434. #endif
  26435. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  26436. if (cert->keyType == ED25519_KEY) {
  26437. if (ed25519Key == NULL)
  26438. return PUBLIC_KEY_E;
  26439. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  26440. (word32)sizeof(der->publicKey), 1);
  26441. }
  26442. #endif
  26443. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  26444. if (cert->keyType == ED448_KEY) {
  26445. if (ed448Key == NULL)
  26446. return PUBLIC_KEY_E;
  26447. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  26448. (word32)sizeof(der->publicKey), 1);
  26449. }
  26450. #endif
  26451. #if defined(HAVE_PQC)
  26452. #if defined(HAVE_FALCON)
  26453. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  26454. (cert->keyType == FALCON_LEVEL5_KEY)) {
  26455. if (falconKey == NULL)
  26456. return PUBLIC_KEY_E;
  26457. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  26458. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26459. }
  26460. #endif
  26461. #if defined(HAVE_DILITHIUM)
  26462. if ((cert->keyType == DILITHIUM_LEVEL2_KEY) ||
  26463. (cert->keyType == DILITHIUM_LEVEL3_KEY) ||
  26464. (cert->keyType == DILITHIUM_LEVEL5_KEY)) {
  26465. if (dilithiumKey == NULL)
  26466. return PUBLIC_KEY_E;
  26467. der->publicKeySz = wc_Dilithium_PublicKeyToDer(dilithiumKey,
  26468. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26469. }
  26470. #endif
  26471. #if defined(HAVE_SPHINCS)
  26472. if ((cert->keyType == SPHINCS_FAST_LEVEL1_KEY) ||
  26473. (cert->keyType == SPHINCS_FAST_LEVEL3_KEY) ||
  26474. (cert->keyType == SPHINCS_FAST_LEVEL5_KEY) ||
  26475. (cert->keyType == SPHINCS_SMALL_LEVEL1_KEY) ||
  26476. (cert->keyType == SPHINCS_SMALL_LEVEL3_KEY) ||
  26477. (cert->keyType == SPHINCS_SMALL_LEVEL5_KEY)) {
  26478. if (sphincsKey == NULL)
  26479. return PUBLIC_KEY_E;
  26480. der->publicKeySz = wc_Sphincs_PublicKeyToDer(sphincsKey,
  26481. der->publicKey, (word32)sizeof(der->publicKey), 1);
  26482. }
  26483. #endif
  26484. #endif /* HAVE_PQC */
  26485. if (der->publicKeySz <= 0)
  26486. return PUBLIC_KEY_E;
  26487. /* set the extensions */
  26488. der->extensionsSz = 0;
  26489. /* RFC 5280 : 4.2.1.9. Basic Constraints
  26490. * The pathLenConstraint field is meaningful only if the CA boolean is
  26491. * asserted and the key usage extension, if present, asserts the
  26492. * keyCertSign bit */
  26493. /* Set CA and path length */
  26494. if ((cert->isCA) && (cert->pathLenSet)
  26495. #ifdef WOLFSSL_CERT_EXT
  26496. && ((cert->keyUsage & KEYUSE_KEY_CERT_SIGN) || (!cert->keyUsage))
  26497. #endif
  26498. ) {
  26499. der->caSz = SetCaWithPathLen(der->ca, sizeof(der->ca), cert->pathLen);
  26500. if (der->caSz <= 0)
  26501. return CA_TRUE_E;
  26502. der->extensionsSz += der->caSz;
  26503. }
  26504. /* Set CA */
  26505. else if (cert->isCA) {
  26506. der->caSz = SetCa(der->ca, sizeof(der->ca));
  26507. if (der->caSz <= 0)
  26508. return CA_TRUE_E;
  26509. der->extensionsSz += der->caSz;
  26510. }
  26511. /* Set Basic Constraint */
  26512. else if (cert->basicConstSet) {
  26513. der->caSz = SetBC(der->ca, sizeof(der->ca));
  26514. if (der->caSz <= 0)
  26515. return EXTENSIONS_E;
  26516. der->extensionsSz += der->caSz;
  26517. }
  26518. else
  26519. der->caSz = 0;
  26520. #ifdef WOLFSSL_ALT_NAMES
  26521. /* Alternative Name */
  26522. if (cert->altNamesSz) {
  26523. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  26524. cert->altNames, (word32)cert->altNamesSz,
  26525. cert->altNamesCrit);
  26526. if (der->altNamesSz <= 0)
  26527. return ALT_NAME_E;
  26528. der->extensionsSz += der->altNamesSz;
  26529. }
  26530. else
  26531. der->altNamesSz = 0;
  26532. #endif
  26533. #ifdef WOLFSSL_CERT_EXT
  26534. /* SKID */
  26535. if (cert->skidSz) {
  26536. /* check the provided SKID size */
  26537. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  26538. return SKID_E;
  26539. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  26540. cert->skid, (word32)cert->skidSz);
  26541. if (der->skidSz <= 0)
  26542. return SKID_E;
  26543. der->extensionsSz += der->skidSz;
  26544. }
  26545. else
  26546. der->skidSz = 0;
  26547. /* Key Usage */
  26548. if (cert->keyUsage != 0) {
  26549. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  26550. cert->keyUsage);
  26551. if (der->keyUsageSz <= 0)
  26552. return KEYUSAGE_E;
  26553. der->extensionsSz += der->keyUsageSz;
  26554. }
  26555. else
  26556. der->keyUsageSz = 0;
  26557. /* Extended Key Usage */
  26558. if (cert->extKeyUsage != 0) {
  26559. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  26560. sizeof(der->extKeyUsage), cert->extKeyUsage);
  26561. if (der->extKeyUsageSz <= 0)
  26562. return EXTKEYUSAGE_E;
  26563. der->extensionsSz += der->extKeyUsageSz;
  26564. }
  26565. else
  26566. der->extKeyUsageSz = 0;
  26567. #endif /* WOLFSSL_CERT_EXT */
  26568. #ifdef WOLFSSL_CUSTOM_OID
  26569. /* encode a custom oid and value */
  26570. /* zero returns, means none set */
  26571. ret = SetCustomObjectId(cert, der->extCustom,
  26572. sizeof(der->extCustom), &cert->extCustom);
  26573. if (ret < 0)
  26574. return ret;
  26575. der->extCustomSz = ret;
  26576. der->extensionsSz += der->extCustomSz;
  26577. #endif
  26578. /* put extensions */
  26579. if (der->extensionsSz > 0) {
  26580. /* put the start of sequence (ID, Size) */
  26581. der->extensionsSz = (int)SetSequence((word32)der->extensionsSz,
  26582. der->extensions);
  26583. if (der->extensionsSz <= 0)
  26584. return EXTENSIONS_E;
  26585. /* put CA */
  26586. if (der->caSz) {
  26587. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26588. &der->extensionsSz,
  26589. der->ca, der->caSz);
  26590. if (ret <= 0)
  26591. return EXTENSIONS_E;
  26592. }
  26593. #ifdef WOLFSSL_ALT_NAMES
  26594. /* put Alternative Names */
  26595. if (der->altNamesSz) {
  26596. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26597. &der->extensionsSz,
  26598. der->altNames, der->altNamesSz);
  26599. if (ret <= 0)
  26600. return EXTENSIONS_E;
  26601. }
  26602. #endif
  26603. #ifdef WOLFSSL_CERT_EXT
  26604. /* put SKID */
  26605. if (der->skidSz) {
  26606. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26607. &der->extensionsSz,
  26608. der->skid, der->skidSz);
  26609. if (ret <= 0)
  26610. return EXTENSIONS_E;
  26611. }
  26612. /* put AKID */
  26613. if (der->akidSz) {
  26614. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26615. &der->extensionsSz,
  26616. der->akid, der->akidSz);
  26617. if (ret <= 0)
  26618. return EXTENSIONS_E;
  26619. }
  26620. /* put KeyUsage */
  26621. if (der->keyUsageSz) {
  26622. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26623. &der->extensionsSz,
  26624. der->keyUsage, der->keyUsageSz);
  26625. if (ret <= 0)
  26626. return EXTENSIONS_E;
  26627. }
  26628. /* put ExtendedKeyUsage */
  26629. if (der->extKeyUsageSz) {
  26630. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26631. &der->extensionsSz,
  26632. der->extKeyUsage, der->extKeyUsageSz);
  26633. if (ret <= 0)
  26634. return EXTENSIONS_E;
  26635. }
  26636. #ifdef WOLFSSL_CUSTOM_OID
  26637. if (der->extCustomSz) {
  26638. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  26639. &der->extensionsSz,
  26640. der->extCustom, der->extCustomSz);
  26641. if (ret <= 0)
  26642. return EXTENSIONS_E;
  26643. }
  26644. #endif
  26645. #endif /* WOLFSSL_CERT_EXT */
  26646. }
  26647. der->attribSz = SetReqAttrib(der->attrib, cert, (word32)der->extensionsSz);
  26648. if (der->attribSz <= 0)
  26649. return REQ_ATTRIBUTE_E;
  26650. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  26651. der->extensionsSz + der->attribSz;
  26652. return 0;
  26653. }
  26654. /* write DER encoded cert req to buffer, size already checked */
  26655. static int WriteCertReqBody(DerCert* der, byte* buf)
  26656. {
  26657. int idx;
  26658. /* signed part header */
  26659. idx = (int)SetSequence((word32)der->total, buf);
  26660. /* version */
  26661. if (buf)
  26662. XMEMCPY(buf + idx, der->version, (size_t)der->versionSz);
  26663. idx += der->versionSz;
  26664. /* subject */
  26665. if (buf)
  26666. XMEMCPY(buf + idx, der->subject, (size_t)der->subjectSz);
  26667. idx += der->subjectSz;
  26668. /* public key */
  26669. if (buf)
  26670. XMEMCPY(buf + idx, der->publicKey, (size_t)der->publicKeySz);
  26671. idx += der->publicKeySz;
  26672. /* attributes */
  26673. if (buf)
  26674. XMEMCPY(buf + idx, der->attrib, (size_t)der->attribSz);
  26675. idx += der->attribSz;
  26676. /* extensions */
  26677. if (der->extensionsSz) {
  26678. if (buf)
  26679. XMEMCPY(buf + idx, der->extensions, min((word32)der->extensionsSz,
  26680. sizeof(der->extensions)));
  26681. idx += der->extensionsSz;
  26682. }
  26683. return idx;
  26684. }
  26685. #endif
  26686. #ifdef WOLFSSL_ASN_TEMPLATE
  26687. /* ASN.1 template for Certificate Request body.
  26688. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  26689. */
  26690. static const ASNItem certReqBodyASN[] = {
  26691. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26692. /* version */
  26693. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  26694. /* subject */
  26695. /* SUBJ_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26696. /* subjectPKInfo */
  26697. /* SPUBKEYINFO_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  26698. /* attributes*/
  26699. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26700. /* Challenge Password Attribute */
  26701. /* ATTRS_CPW_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26702. /* ATTRS_CPW_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26703. /* ATTRS_CPW_SET */ { 3, ASN_SET, 1, 1, 0 },
  26704. /* ATTRS_CPW_PS */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  26705. /* ATTRS_CPW_UTF */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  26706. /* Extensions Attribute */
  26707. /* EXT_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  26708. /* EXT_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26709. /* EXT_SET */ { 3, ASN_SET, 1, 1, 0 },
  26710. /* EXT_BODY */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  26711. };
  26712. enum {
  26713. CERTREQBODYASN_IDX_SEQ = 0,
  26714. CERTREQBODYASN_IDX_VER,
  26715. CERTREQBODYASN_IDX_SUBJ_SEQ,
  26716. CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ,
  26717. CERTREQBODYASN_IDX_ATTRS,
  26718. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ,
  26719. CERTREQBODYASN_IDX_ATTRS_CPW_OID,
  26720. CERTREQBODYASN_IDX_ATTRS_CPW_SET,
  26721. CERTREQBODYASN_IDX_ATTRS_CPW_PS,
  26722. CERTREQBODYASN_IDX_ATTRS_CPW_UTF,
  26723. CERTREQBODYASN_IDX_EXT_SEQ,
  26724. CERTREQBODYASN_IDX_EXT_OID,
  26725. CERTREQBODYASN_IDX_EXT_SET,
  26726. CERTREQBODYASN_IDX_EXT_BODY
  26727. };
  26728. /* Number of items in ASN.1 template for Certificate Request body. */
  26729. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  26730. #endif
  26731. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  26732. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  26733. ed25519_key* ed25519Key, ed448_key* ed448Key,
  26734. falcon_key* falconKey, dilithium_key* dilithiumKey,
  26735. sphincs_key* sphincsKey)
  26736. {
  26737. #ifndef WOLFSSL_ASN_TEMPLATE
  26738. int ret;
  26739. #ifdef WOLFSSL_SMALL_STACK
  26740. DerCert* der;
  26741. #else
  26742. DerCert der[1];
  26743. #endif
  26744. if (eccKey)
  26745. cert->keyType = ECC_KEY;
  26746. else if (rsaKey)
  26747. cert->keyType = RSA_KEY;
  26748. else if (dsaKey)
  26749. cert->keyType = DSA_KEY;
  26750. else if (ed25519Key)
  26751. cert->keyType = ED25519_KEY;
  26752. else if (ed448Key)
  26753. cert->keyType = ED448_KEY;
  26754. #ifdef HAVE_PQC
  26755. #ifdef HAVE_FALCON
  26756. else if ((falconKey != NULL) && (falconKey->level == 1))
  26757. cert->keyType = FALCON_LEVEL1_KEY;
  26758. else if ((falconKey != NULL) && (falconKey->level == 5))
  26759. cert->keyType = FALCON_LEVEL5_KEY;
  26760. #endif /* HAVE_FALCON */
  26761. #ifdef HAVE_DILITHIUM
  26762. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2))
  26763. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26764. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3))
  26765. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26766. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5))
  26767. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26768. #endif /* HAVE_DILITHIUM */
  26769. #ifdef HAVE_SPHINCS
  26770. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26771. && (sphincsKey->optim == FAST_VARIANT))
  26772. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26773. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26774. && (sphincsKey->optim == FAST_VARIANT))
  26775. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26776. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26777. && (sphincsKey->optim == FAST_VARIANT))
  26778. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26779. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26780. && (sphincsKey->optim == SMALL_VARIANT))
  26781. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26782. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26783. && (sphincsKey->optim == SMALL_VARIANT))
  26784. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26785. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26786. && (sphincsKey->optim == SMALL_VARIANT))
  26787. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26788. #endif /* HAVE_SPHINCS */
  26789. #endif /* HAVE_PQC */
  26790. else
  26791. return BAD_FUNC_ARG;
  26792. #ifdef WOLFSSL_SMALL_STACK
  26793. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  26794. DYNAMIC_TYPE_TMP_BUFFER);
  26795. if (der == NULL)
  26796. return MEMORY_E;
  26797. #endif
  26798. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  26799. falconKey, dilithiumKey, sphincsKey);
  26800. if (ret == 0) {
  26801. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  26802. ret = BUFFER_E;
  26803. else
  26804. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  26805. }
  26806. #ifdef WOLFSSL_SMALL_STACK
  26807. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  26808. #endif
  26809. return ret;
  26810. #else
  26811. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  26812. word32 publicKeySz = 0;
  26813. word32 subjectSz = 0;
  26814. word32 extSz = 0;
  26815. int sz = 0;
  26816. int ret = 0;
  26817. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26818. word32 sbjRawSz = 0;
  26819. #endif
  26820. /* Unused without OQS */
  26821. (void)falconKey;
  26822. (void)dilithiumKey;
  26823. (void)sphincsKey;
  26824. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  26825. if (ret == 0) {
  26826. /* Set key type into certificate object based on key passed in. */
  26827. if (rsaKey != NULL) {
  26828. cert->keyType = RSA_KEY;
  26829. }
  26830. else if (eccKey != NULL) {
  26831. cert->keyType = ECC_KEY;
  26832. }
  26833. else if (dsaKey != NULL) {
  26834. cert->keyType = DSA_KEY;
  26835. }
  26836. else if (ed25519Key != NULL) {
  26837. cert->keyType = ED25519_KEY;
  26838. }
  26839. else if (ed448Key != NULL) {
  26840. cert->keyType = ED448_KEY;
  26841. }
  26842. #ifdef HAVE_PQC
  26843. #ifdef HAVE_FALCON
  26844. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  26845. cert->keyType = FALCON_LEVEL1_KEY;
  26846. }
  26847. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  26848. cert->keyType = FALCON_LEVEL5_KEY;
  26849. }
  26850. #endif /* HAVE_FALCON */
  26851. #ifdef HAVE_DILITHIUM
  26852. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 2)) {
  26853. cert->keyType = DILITHIUM_LEVEL2_KEY;
  26854. }
  26855. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 3)) {
  26856. cert->keyType = DILITHIUM_LEVEL3_KEY;
  26857. }
  26858. else if ((dilithiumKey != NULL) && (dilithiumKey->level == 5)) {
  26859. cert->keyType = DILITHIUM_LEVEL5_KEY;
  26860. }
  26861. #endif /* HAVE_DILITHIUM */
  26862. #ifdef HAVE_SPHINCS
  26863. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26864. && (sphincsKey->optim == FAST_VARIANT)) {
  26865. cert->keyType = SPHINCS_FAST_LEVEL1_KEY;
  26866. }
  26867. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26868. && (sphincsKey->optim == FAST_VARIANT)) {
  26869. cert->keyType = SPHINCS_FAST_LEVEL3_KEY;
  26870. }
  26871. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26872. && (sphincsKey->optim == FAST_VARIANT)) {
  26873. cert->keyType = SPHINCS_FAST_LEVEL5_KEY;
  26874. }
  26875. else if ((sphincsKey != NULL) && (sphincsKey->level == 1)
  26876. && (sphincsKey->optim == SMALL_VARIANT)) {
  26877. cert->keyType = SPHINCS_SMALL_LEVEL1_KEY;
  26878. }
  26879. else if ((sphincsKey != NULL) && (sphincsKey->level == 3)
  26880. && (sphincsKey->optim == SMALL_VARIANT)) {
  26881. cert->keyType = SPHINCS_SMALL_LEVEL3_KEY;
  26882. }
  26883. else if ((sphincsKey != NULL) && (sphincsKey->level == 5)
  26884. && (sphincsKey->optim == SMALL_VARIANT)) {
  26885. cert->keyType = SPHINCS_SMALL_LEVEL5_KEY;
  26886. }
  26887. #endif /* HAVE_SPHINCS */
  26888. #endif /* HAVE_PQC */
  26889. else {
  26890. ret = BAD_FUNC_ARG;
  26891. }
  26892. }
  26893. if (ret == 0) {
  26894. /* Determine subject name size. */
  26895. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26896. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  26897. if (sbjRawSz > 0) {
  26898. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  26899. }
  26900. else
  26901. #endif
  26902. {
  26903. ret = SetNameEx(NULL, WC_ASN_NAME_MAX, &cert->subject, cert->heap);
  26904. subjectSz = (word32)ret;
  26905. }
  26906. }
  26907. if (ret >= 0) {
  26908. /* Determine encode public key size. */
  26909. ret = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  26910. eccKey, ed25519Key, ed448Key, dsaKey);
  26911. publicKeySz = (word32)ret;
  26912. }
  26913. if (ret >= 0) {
  26914. /* Determine encode extensions size. */
  26915. ret = EncodeExtensions(cert, NULL, 0, 1);
  26916. extSz = (word32)ret;
  26917. }
  26918. if (ret >= 0) {
  26919. /* Set version. */
  26920. SetASN_Int8Bit(&dataASN[CERTREQBODYASN_IDX_VER], (byte)cert->version);
  26921. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26922. if (sbjRawSz > 0) {
  26923. /* Put in encoded subject name. */
  26924. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], cert->sbjRaw,
  26925. subjectSz);
  26926. }
  26927. else
  26928. #endif
  26929. {
  26930. /* Leave space for subject name. */
  26931. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ], NULL,
  26932. subjectSz);
  26933. }
  26934. /* Leave space for public key. */
  26935. SetASN_ReplaceBuffer(&dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ],
  26936. NULL, publicKeySz);
  26937. if (cert->challengePw[0] != '\0') {
  26938. /* Add challenge password attribute. */
  26939. /* Set challenge password OID. */
  26940. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_OID],
  26941. attrChallengePasswordOid, sizeof(attrChallengePasswordOid));
  26942. /* Enable the ASN template item with the appropriate tag. */
  26943. if (cert->challengePwPrintableString) {
  26944. /* PRINTABLE_STRING - set buffer */
  26945. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS],
  26946. (byte*)cert->challengePw,
  26947. (word32)XSTRLEN(cert->challengePw));
  26948. /* UTF8STRING - don't encode */
  26949. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF].noOut = 1;
  26950. }
  26951. else {
  26952. /* PRINTABLE_STRING - don't encode */
  26953. dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_PS].noOut = 1;
  26954. /* UTF8STRING - set buffer */
  26955. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_ATTRS_CPW_UTF],
  26956. (byte*)cert->challengePw,
  26957. (word32)XSTRLEN(cert->challengePw));
  26958. }
  26959. }
  26960. else {
  26961. /* Leave out challenge password attribute items. */
  26962. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26963. CERTREQBODYASN_IDX_ATTRS_CPW_SEQ, certReqBodyASN_Length);
  26964. }
  26965. if (extSz > 0) {
  26966. /* Set extension attribute OID. */
  26967. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_OID], attrExtensionRequestOid,
  26968. sizeof(attrExtensionRequestOid));
  26969. /* Leave space for data. */
  26970. SetASN_Buffer(&dataASN[CERTREQBODYASN_IDX_EXT_BODY], NULL, extSz);
  26971. }
  26972. else {
  26973. /* Leave out extension attribute items. */
  26974. SetASNItem_NoOutNode(dataASN, certReqBodyASN,
  26975. CERTREQBODYASN_IDX_EXT_SEQ, certReqBodyASN_Length);
  26976. }
  26977. /* Calculate size of encoded certificate request body. */
  26978. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  26979. &sz);
  26980. }
  26981. /* Check buffer is big enough for encoded data. */
  26982. if ((ret == 0) && (sz > (int)derSz)) {
  26983. ret = BUFFER_E;
  26984. }
  26985. if (ret == 0 && derBuffer != NULL) {
  26986. /* Encode certificate request body into buffer. */
  26987. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  26988. /* Put in generated data */
  26989. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  26990. if (sbjRawSz == 0)
  26991. #endif
  26992. {
  26993. /* Encode subject name into space in buffer. */
  26994. ret = SetNameEx(
  26995. (byte*)dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.data,
  26996. dataASN[CERTREQBODYASN_IDX_SUBJ_SEQ].data.buffer.length,
  26997. &cert->subject, cert->heap);
  26998. }
  26999. }
  27000. if (ret >= 0 && derBuffer != NULL) {
  27001. /* Encode public key into space in buffer. */
  27002. ret = EncodePublicKey(cert->keyType,
  27003. (byte*)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.data,
  27004. (int)dataASN[CERTREQBODYASN_IDX_SPUBKEYINFO_SEQ].data.buffer.length,
  27005. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  27006. }
  27007. if ((ret >= 0 && derBuffer != NULL) &&
  27008. (!dataASN[CERTREQBODYASN_IDX_EXT_BODY].noOut)) {
  27009. /* Encode extensions into space in buffer. */
  27010. ret = EncodeExtensions(cert,
  27011. (byte*)dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.data,
  27012. dataASN[CERTREQBODYASN_IDX_EXT_BODY].data.buffer.length, 1);
  27013. }
  27014. if (ret >= 0) {
  27015. /* Store encoded certifcate request body size. */
  27016. cert->bodySz = sz;
  27017. /* Return the encoding size. */
  27018. ret = sz;
  27019. }
  27020. FREE_ASNSETDATA(dataASN, cert->heap);
  27021. return ret;
  27022. #endif /* WOLFSSL_ASN_TEMPLATE */
  27023. }
  27024. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  27025. void* key)
  27026. {
  27027. RsaKey* rsaKey = NULL;
  27028. DsaKey* dsaKey = NULL;
  27029. ecc_key* eccKey = NULL;
  27030. ed25519_key* ed25519Key = NULL;
  27031. ed448_key* ed448Key = NULL;
  27032. falcon_key* falconKey = NULL;
  27033. dilithium_key* dilithiumKey = NULL;
  27034. sphincs_key* sphincsKey = NULL;
  27035. if (keyType == RSA_TYPE)
  27036. rsaKey = (RsaKey*)key;
  27037. else if (keyType == DSA_TYPE)
  27038. dsaKey = (DsaKey*)key;
  27039. else if (keyType == ECC_TYPE)
  27040. eccKey = (ecc_key*)key;
  27041. else if (keyType == ED25519_TYPE)
  27042. ed25519Key = (ed25519_key*)key;
  27043. else if (keyType == ED448_TYPE)
  27044. ed448Key = (ed448_key*)key;
  27045. else if (keyType == FALCON_LEVEL1_TYPE)
  27046. falconKey = (falcon_key*)key;
  27047. else if (keyType == FALCON_LEVEL5_TYPE)
  27048. falconKey = (falcon_key*)key;
  27049. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27050. dilithiumKey = (dilithium_key*)key;
  27051. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27052. dilithiumKey = (dilithium_key*)key;
  27053. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27054. dilithiumKey = (dilithium_key*)key;
  27055. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27056. sphincsKey = (sphincs_key*)key;
  27057. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27058. sphincsKey = (sphincs_key*)key;
  27059. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27060. sphincsKey = (sphincs_key*)key;
  27061. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27062. sphincsKey = (sphincs_key*)key;
  27063. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27064. sphincsKey = (sphincs_key*)key;
  27065. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27066. sphincsKey = (sphincs_key*)key;
  27067. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  27068. ed25519Key, ed448Key, falconKey, dilithiumKey,
  27069. sphincsKey);
  27070. }
  27071. WOLFSSL_ABI
  27072. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  27073. RsaKey* rsaKey, ecc_key* eccKey)
  27074. {
  27075. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  27076. NULL, NULL, NULL, NULL);
  27077. }
  27078. #endif /* WOLFSSL_CERT_REQ */
  27079. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27080. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  27081. ed448_key* ed448Key, falcon_key* falconKey,
  27082. dilithium_key* dilithiumKey, sphincs_key* sphincsKey,
  27083. WC_RNG* rng)
  27084. {
  27085. int sigSz = 0;
  27086. void* heap = NULL;
  27087. CertSignCtx certSignCtx_lcl;
  27088. CertSignCtx* certSignCtx = &certSignCtx_lcl;
  27089. XMEMSET(certSignCtx, 0, sizeof(*certSignCtx));
  27090. if (requestSz < 0)
  27091. return requestSz;
  27092. /* locate ctx */
  27093. if (rsaKey) {
  27094. #ifndef NO_RSA
  27095. #ifdef WOLFSSL_ASYNC_CRYPT
  27096. certSignCtx = &rsaKey->certSignCtx;
  27097. #endif
  27098. heap = rsaKey->heap;
  27099. #else
  27100. return NOT_COMPILED_IN;
  27101. #endif /* NO_RSA */
  27102. }
  27103. else if (eccKey) {
  27104. #ifdef HAVE_ECC
  27105. #ifdef WOLFSSL_ASYNC_CRYPT
  27106. certSignCtx = &eccKey->certSignCtx;
  27107. #endif
  27108. heap = eccKey->heap;
  27109. #else
  27110. return NOT_COMPILED_IN;
  27111. #endif /* HAVE_ECC */
  27112. }
  27113. if (certSignCtx->sig == NULL) {
  27114. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  27115. DYNAMIC_TYPE_TMP_BUFFER);
  27116. if (certSignCtx->sig == NULL)
  27117. return MEMORY_E;
  27118. }
  27119. sigSz = MakeSignature(certSignCtx, buf, (word32)requestSz, certSignCtx->sig,
  27120. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  27121. falconKey, dilithiumKey, sphincsKey, rng, (word32)sType, heap);
  27122. #ifdef WOLFSSL_ASYNC_CRYPT
  27123. if (sigSz == WC_PENDING_E) {
  27124. /* Not free'ing certSignCtx->sig here because it could still be in use
  27125. * with async operations. */
  27126. return sigSz;
  27127. }
  27128. #endif
  27129. if (sigSz >= 0) {
  27130. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  27131. sigSz = BUFFER_E;
  27132. else
  27133. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  27134. sType);
  27135. }
  27136. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  27137. certSignCtx->sig = NULL;
  27138. return sigSz;
  27139. }
  27140. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  27141. int keyType, void* key, WC_RNG* rng)
  27142. {
  27143. RsaKey* rsaKey = NULL;
  27144. ecc_key* eccKey = NULL;
  27145. ed25519_key* ed25519Key = NULL;
  27146. ed448_key* ed448Key = NULL;
  27147. falcon_key* falconKey = NULL;
  27148. dilithium_key* dilithiumKey = NULL;
  27149. sphincs_key* sphincsKey = NULL;
  27150. if (keyType == RSA_TYPE)
  27151. rsaKey = (RsaKey*)key;
  27152. else if (keyType == ECC_TYPE)
  27153. eccKey = (ecc_key*)key;
  27154. else if (keyType == ED25519_TYPE)
  27155. ed25519Key = (ed25519_key*)key;
  27156. else if (keyType == ED448_TYPE)
  27157. ed448Key = (ed448_key*)key;
  27158. else if (keyType == FALCON_LEVEL1_TYPE)
  27159. falconKey = (falcon_key*)key;
  27160. else if (keyType == FALCON_LEVEL5_TYPE)
  27161. falconKey = (falcon_key*)key;
  27162. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27163. dilithiumKey = (dilithium_key*)key;
  27164. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27165. dilithiumKey = (dilithium_key*)key;
  27166. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27167. dilithiumKey = (dilithium_key*)key;
  27168. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27169. sphincsKey = (sphincs_key*)key;
  27170. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27171. sphincsKey = (sphincs_key*)key;
  27172. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27173. sphincsKey = (sphincs_key*)key;
  27174. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27175. sphincsKey = (sphincs_key*)key;
  27176. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27177. sphincsKey = (sphincs_key*)key;
  27178. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27179. sphincsKey = (sphincs_key*)key;
  27180. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  27181. ed448Key, falconKey, dilithiumKey, sphincsKey, rng);
  27182. }
  27183. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  27184. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  27185. {
  27186. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  27187. NULL, NULL, NULL, rng);
  27188. }
  27189. WOLFSSL_ABI
  27190. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  27191. RsaKey* key, WC_RNG* rng)
  27192. {
  27193. int ret;
  27194. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  27195. if (ret < 0)
  27196. return ret;
  27197. return wc_SignCert(cert->bodySz, cert->sigType,
  27198. buf, buffSz, key, NULL, rng);
  27199. }
  27200. #ifdef WOLFSSL_CERT_EXT
  27201. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  27202. The raw subject pointer will only be valid while "cert" is valid. */
  27203. WOLFSSL_ABI
  27204. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  27205. {
  27206. int rc = BAD_FUNC_ARG;
  27207. if ((subjectRaw != NULL) && (cert != NULL)) {
  27208. *subjectRaw = cert->sbjRaw;
  27209. rc = 0;
  27210. }
  27211. return rc;
  27212. }
  27213. /* Set KID from public key */
  27214. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  27215. ed25519_key* ed25519Key, ed448_key* ed448Key,
  27216. falcon_key* falconKey,
  27217. dilithium_key* dilithiumKey,
  27218. sphincs_key *sphincsKey, int kid_type)
  27219. {
  27220. byte *buf;
  27221. int bufferSz, ret;
  27222. if (cert == NULL ||
  27223. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  27224. ed448Key == NULL && falconKey == NULL && dilithiumKey == NULL &&
  27225. sphincsKey == NULL) ||
  27226. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  27227. return BAD_FUNC_ARG;
  27228. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  27229. DYNAMIC_TYPE_TMP_BUFFER);
  27230. if (buf == NULL)
  27231. return MEMORY_E;
  27232. /* Public Key */
  27233. bufferSz = -1;
  27234. #ifndef NO_RSA
  27235. /* RSA public key */
  27236. if (rsakey != NULL)
  27237. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  27238. #endif
  27239. #ifdef HAVE_ECC
  27240. /* ECC public key */
  27241. if (eckey != NULL)
  27242. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0, 0);
  27243. #endif
  27244. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  27245. /* ED25519 public key */
  27246. if (ed25519Key != NULL) {
  27247. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27248. }
  27249. #endif
  27250. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  27251. /* ED448 public key */
  27252. if (ed448Key != NULL) {
  27253. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  27254. }
  27255. #endif
  27256. #if defined(HAVE_PQC)
  27257. #if defined(HAVE_FALCON)
  27258. if (falconKey != NULL) {
  27259. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  27260. 0);
  27261. }
  27262. #endif
  27263. #if defined(HAVE_DILITHIUM)
  27264. if (dilithiumKey != NULL) {
  27265. bufferSz = wc_Dilithium_PublicKeyToDer(dilithiumKey, buf,
  27266. MAX_PUBLIC_KEY_SZ, 0);
  27267. }
  27268. #endif
  27269. #if defined(HAVE_SPHINCS)
  27270. if (sphincsKey != NULL) {
  27271. bufferSz = wc_Sphincs_PublicKeyToDer(sphincsKey, buf,
  27272. MAX_PUBLIC_KEY_SZ, 0);
  27273. }
  27274. #endif
  27275. #endif /* HAVE_PQC */
  27276. if (bufferSz <= 0) {
  27277. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27278. return PUBLIC_KEY_E;
  27279. }
  27280. /* Compute SKID by hashing public key */
  27281. if (kid_type == SKID_TYPE) {
  27282. int hashId = HashIdAlg(cert->sigType);
  27283. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->skid, hashId);
  27284. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27285. cert->skidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  27286. #else
  27287. cert->skidSz = KEYID_SIZE;
  27288. #endif
  27289. }
  27290. else if (kid_type == AKID_TYPE) {
  27291. int hashId = HashIdAlg(cert->sigType);
  27292. ret = CalcHashId_ex(buf, (word32)bufferSz, cert->akid, hashId);
  27293. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27294. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(hashId));
  27295. #else
  27296. cert->akidSz = KEYID_SIZE;
  27297. #endif
  27298. }
  27299. else
  27300. ret = BAD_FUNC_ARG;
  27301. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27302. return ret;
  27303. }
  27304. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27305. {
  27306. RsaKey* rsaKey = NULL;
  27307. ecc_key* eccKey = NULL;
  27308. ed25519_key* ed25519Key = NULL;
  27309. ed448_key* ed448Key = NULL;
  27310. falcon_key* falconKey = NULL;
  27311. dilithium_key* dilithiumKey = NULL;
  27312. sphincs_key* sphincsKey = NULL;
  27313. if (keyType == RSA_TYPE)
  27314. rsaKey = (RsaKey*)key;
  27315. else if (keyType == ECC_TYPE)
  27316. eccKey = (ecc_key*)key;
  27317. else if (keyType == ED25519_TYPE)
  27318. ed25519Key = (ed25519_key*)key;
  27319. else if (keyType == ED448_TYPE)
  27320. ed448Key = (ed448_key*)key;
  27321. else if (keyType == FALCON_LEVEL1_TYPE)
  27322. falconKey = (falcon_key*)key;
  27323. else if (keyType == FALCON_LEVEL5_TYPE)
  27324. falconKey = (falcon_key*)key;
  27325. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27326. dilithiumKey = (dilithium_key*)key;
  27327. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27328. dilithiumKey = (dilithium_key*)key;
  27329. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27330. dilithiumKey = (dilithium_key*)key;
  27331. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27332. sphincsKey = (sphincs_key*)key;
  27333. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27334. sphincsKey = (sphincs_key*)key;
  27335. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27336. sphincsKey = (sphincs_key*)key;
  27337. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27338. sphincsKey = (sphincs_key*)key;
  27339. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27340. sphincsKey = (sphincs_key*)key;
  27341. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27342. sphincsKey = (sphincs_key*)key;
  27343. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27344. falconKey, dilithiumKey, sphincsKey,
  27345. SKID_TYPE);
  27346. }
  27347. /* Set SKID from RSA or ECC public key */
  27348. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27349. {
  27350. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27351. NULL, SKID_TYPE);
  27352. }
  27353. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  27354. {
  27355. RsaKey* rsaKey = NULL;
  27356. ecc_key* eccKey = NULL;
  27357. ed25519_key* ed25519Key = NULL;
  27358. ed448_key* ed448Key = NULL;
  27359. falcon_key* falconKey = NULL;
  27360. dilithium_key* dilithiumKey = NULL;
  27361. sphincs_key* sphincsKey = NULL;
  27362. if (keyType == RSA_TYPE)
  27363. rsaKey = (RsaKey*)key;
  27364. else if (keyType == ECC_TYPE)
  27365. eccKey = (ecc_key*)key;
  27366. else if (keyType == ED25519_TYPE)
  27367. ed25519Key = (ed25519_key*)key;
  27368. else if (keyType == ED448_TYPE)
  27369. ed448Key = (ed448_key*)key;
  27370. else if (keyType == FALCON_LEVEL1_TYPE)
  27371. falconKey = (falcon_key*)key;
  27372. else if (keyType == FALCON_LEVEL5_TYPE)
  27373. falconKey = (falcon_key*)key;
  27374. else if (keyType == DILITHIUM_LEVEL2_TYPE)
  27375. dilithiumKey = (dilithium_key*)key;
  27376. else if (keyType == DILITHIUM_LEVEL3_TYPE)
  27377. dilithiumKey = (dilithium_key*)key;
  27378. else if (keyType == DILITHIUM_LEVEL5_TYPE)
  27379. dilithiumKey = (dilithium_key*)key;
  27380. else if (keyType == SPHINCS_FAST_LEVEL1_TYPE)
  27381. sphincsKey = (sphincs_key*)key;
  27382. else if (keyType == SPHINCS_FAST_LEVEL3_TYPE)
  27383. sphincsKey = (sphincs_key*)key;
  27384. else if (keyType == SPHINCS_FAST_LEVEL5_TYPE)
  27385. sphincsKey = (sphincs_key*)key;
  27386. else if (keyType == SPHINCS_SMALL_LEVEL1_TYPE)
  27387. sphincsKey = (sphincs_key*)key;
  27388. else if (keyType == SPHINCS_SMALL_LEVEL3_TYPE)
  27389. sphincsKey = (sphincs_key*)key;
  27390. else if (keyType == SPHINCS_SMALL_LEVEL5_TYPE)
  27391. sphincsKey = (sphincs_key*)key;
  27392. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  27393. falconKey, dilithiumKey, sphincsKey,
  27394. AKID_TYPE);
  27395. }
  27396. /* Set SKID from RSA or ECC public key */
  27397. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  27398. {
  27399. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL, NULL,
  27400. NULL, AKID_TYPE);
  27401. }
  27402. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  27403. /* Set SKID from public key file in PEM */
  27404. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  27405. {
  27406. int ret, derSz;
  27407. byte* der;
  27408. word32 idx;
  27409. RsaKey *rsakey = NULL;
  27410. ecc_key *eckey = NULL;
  27411. if (cert == NULL || file == NULL)
  27412. return BAD_FUNC_ARG;
  27413. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  27414. if (der == NULL) {
  27415. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  27416. return MEMORY_E;
  27417. }
  27418. derSz = MAX_PUBLIC_KEY_SZ;
  27419. XMEMSET(der, 0, (size_t)derSz);
  27420. derSz = wc_PemPubKeyToDer(file, der, derSz);
  27421. if (derSz <= 0) {
  27422. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27423. return derSz;
  27424. }
  27425. /* Load PubKey in internal structure */
  27426. #ifndef NO_RSA
  27427. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  27428. if (rsakey == NULL) {
  27429. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27430. return MEMORY_E;
  27431. }
  27432. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  27433. WOLFSSL_MSG("wc_InitRsaKey failure");
  27434. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27435. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27436. return MEMORY_E;
  27437. }
  27438. idx = 0;
  27439. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, (word32)derSz);
  27440. if (ret != 0)
  27441. #endif
  27442. {
  27443. #ifndef NO_RSA
  27444. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  27445. wc_FreeRsaKey(rsakey);
  27446. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27447. rsakey = NULL;
  27448. #endif
  27449. #ifdef HAVE_ECC
  27450. /* Check to load ecc public key */
  27451. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  27452. DYNAMIC_TYPE_ECC);
  27453. if (eckey == NULL) {
  27454. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27455. return MEMORY_E;
  27456. }
  27457. if (wc_ecc_init(eckey) != 0) {
  27458. WOLFSSL_MSG("wc_ecc_init failure");
  27459. wc_ecc_free(eckey);
  27460. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27461. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27462. return MEMORY_E;
  27463. }
  27464. idx = 0;
  27465. ret = wc_EccPublicKeyDecode(der, &idx, eckey, (word32)derSz);
  27466. if (ret != 0) {
  27467. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  27468. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27469. wc_ecc_free(eckey);
  27470. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27471. return PUBLIC_KEY_E;
  27472. }
  27473. #else
  27474. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27475. return PUBLIC_KEY_E;
  27476. #endif /* HAVE_ECC */
  27477. }
  27478. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  27479. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  27480. #ifndef NO_RSA
  27481. wc_FreeRsaKey(rsakey);
  27482. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  27483. #endif
  27484. #ifdef HAVE_ECC
  27485. wc_ecc_free(eckey);
  27486. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  27487. #endif
  27488. return ret;
  27489. }
  27490. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  27491. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  27492. {
  27493. int ret = 0;
  27494. /* Subject Key Id not found !! */
  27495. if (decoded->extSubjKeyIdSet == 0) {
  27496. ret = ASN_NO_SKID;
  27497. }
  27498. /* SKID invalid size */
  27499. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  27500. ret = MEMORY_E;
  27501. }
  27502. else {
  27503. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  27504. cert->akidSz = wc_HashGetDigestSize(wc_HashTypeConvert(HashIdAlg(
  27505. cert->sigType)));
  27506. #else
  27507. cert->akidSz = KEYID_SIZE;
  27508. #endif
  27509. /* Put the SKID of CA to AKID of certificate */
  27510. XMEMCPY(cert->akid, decoded->extSubjKeyId, cert->akidSz);
  27511. }
  27512. return ret;
  27513. }
  27514. /* Set AKID from certificate contains in buffer (DER encoded) */
  27515. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  27516. {
  27517. int ret = 0;
  27518. if (cert == NULL) {
  27519. ret = BAD_FUNC_ARG;
  27520. }
  27521. else {
  27522. /* Check if decodedCert is cached */
  27523. if (cert->der != der) {
  27524. /* Allocate cache for the decoded cert */
  27525. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  27526. }
  27527. if (ret >= 0) {
  27528. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  27529. #ifndef WOLFSSL_CERT_GEN_CACHE
  27530. wc_SetCert_Free(cert);
  27531. #endif
  27532. }
  27533. }
  27534. return ret;
  27535. }
  27536. #ifndef NO_FILESYSTEM
  27537. /* Set AKID from certificate file in PEM */
  27538. int wc_SetAuthKeyId(Cert *cert, const char* file)
  27539. {
  27540. int ret;
  27541. DerBuffer* der = NULL;
  27542. if (cert == NULL || file == NULL)
  27543. return BAD_FUNC_ARG;
  27544. ret = wc_PemCertToDer_ex(file, &der);
  27545. if (ret == 0)
  27546. {
  27547. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, (int)der->length);
  27548. FreeDer(&der);
  27549. }
  27550. return ret;
  27551. }
  27552. #endif /* !NO_FILESYSTEM */
  27553. /* Set KeyUsage from human readable string */
  27554. int wc_SetKeyUsage(Cert *cert, const char *value)
  27555. {
  27556. int ret = 0;
  27557. char *token, *str, *ptr;
  27558. word32 len;
  27559. if (cert == NULL || value == NULL)
  27560. return BAD_FUNC_ARG;
  27561. cert->keyUsage = 0;
  27562. /* duplicate string (including terminator) */
  27563. len = (word32)XSTRLEN(value);
  27564. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27565. if (str == NULL)
  27566. return MEMORY_E;
  27567. XMEMCPY(str, value, len+1);
  27568. /* parse value, and set corresponding Key Usage value */
  27569. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27570. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27571. return KEYUSAGE_E;
  27572. }
  27573. while (token != NULL)
  27574. {
  27575. if (!XSTRCASECMP(token, "digitalSignature"))
  27576. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  27577. else if (!XSTRCASECMP(token, "nonRepudiation") ||
  27578. !XSTRCASECMP(token, "contentCommitment"))
  27579. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  27580. else if (!XSTRCASECMP(token, "keyEncipherment"))
  27581. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  27582. else if (!XSTRCASECMP(token, "dataEncipherment"))
  27583. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  27584. else if (!XSTRCASECMP(token, "keyAgreement"))
  27585. cert->keyUsage |= KEYUSE_KEY_AGREE;
  27586. else if (!XSTRCASECMP(token, "keyCertSign"))
  27587. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  27588. else if (!XSTRCASECMP(token, "cRLSign"))
  27589. cert->keyUsage |= KEYUSE_CRL_SIGN;
  27590. else if (!XSTRCASECMP(token, "encipherOnly"))
  27591. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  27592. else if (!XSTRCASECMP(token, "decipherOnly"))
  27593. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  27594. else {
  27595. ret = KEYUSAGE_E;
  27596. break;
  27597. }
  27598. token = XSTRTOK(NULL, ",", &ptr);
  27599. }
  27600. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27601. return ret;
  27602. }
  27603. /* Set ExtendedKeyUsage from human readable string */
  27604. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  27605. {
  27606. int ret = 0;
  27607. char *token, *str, *ptr;
  27608. word32 len;
  27609. if (cert == NULL || value == NULL)
  27610. return BAD_FUNC_ARG;
  27611. cert->extKeyUsage = 0;
  27612. /* duplicate string (including terminator) */
  27613. len = (word32)XSTRLEN(value);
  27614. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27615. if (str == NULL)
  27616. return MEMORY_E;
  27617. XMEMCPY(str, value, len+1);
  27618. /* parse value, and set corresponding Key Usage value */
  27619. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  27620. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27621. return EXTKEYUSAGE_E;
  27622. }
  27623. while (token != NULL)
  27624. {
  27625. if (!XSTRCASECMP(token, "any"))
  27626. cert->extKeyUsage |= EXTKEYUSE_ANY;
  27627. else if (!XSTRCASECMP(token, "serverAuth"))
  27628. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  27629. else if (!XSTRCASECMP(token, "clientAuth"))
  27630. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  27631. else if (!XSTRCASECMP(token, "codeSigning"))
  27632. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  27633. else if (!XSTRCASECMP(token, "emailProtection"))
  27634. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  27635. else if (!XSTRCASECMP(token, "timeStamping"))
  27636. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  27637. else if (!XSTRCASECMP(token, "OCSPSigning"))
  27638. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  27639. else {
  27640. ret = EXTKEYUSAGE_E;
  27641. break;
  27642. }
  27643. token = XSTRTOK(NULL, ",", &ptr);
  27644. }
  27645. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27646. return ret;
  27647. }
  27648. #ifdef WOLFSSL_EKU_OID
  27649. /*
  27650. * cert structure to set EKU oid in
  27651. * oid the oid in byte representation
  27652. * sz size of oid buffer
  27653. * idx index of array to place oid
  27654. *
  27655. * returns 0 on success
  27656. */
  27657. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  27658. void* heap)
  27659. {
  27660. byte oid[MAX_OID_SZ];
  27661. word32 oidSz = MAX_OID_SZ;
  27662. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  27663. WOLFSSL_MSG("Either idx or sz was too large");
  27664. return BAD_FUNC_ARG;
  27665. }
  27666. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  27667. return BUFFER_E;
  27668. }
  27669. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  27670. cert->extKeyUsageOIDSz[idx] = oidSz;
  27671. cert->extKeyUsage |= EXTKEYUSE_USER;
  27672. return 0;
  27673. }
  27674. #endif /* WOLFSSL_EKU_OID */
  27675. #if defined(WOLFSSL_ASN_TEMPLATE) && defined(WOLFSSL_CERT_GEN) && \
  27676. defined(WOLFSSL_CUSTOM_OID) && defined(HAVE_OID_ENCODING) && \
  27677. defined(WOLFSSL_CERT_EXT)
  27678. int wc_SetCustomExtension(Cert *cert, int critical, const char *oid,
  27679. const byte *der, word32 derSz) {
  27680. CertExtension *ext;
  27681. byte encodedOid[MAX_OID_SZ];
  27682. word32 encodedOidSz = MAX_OID_SZ;
  27683. int ret;
  27684. if (cert == NULL || oid == NULL || der == NULL || derSz == 0) {
  27685. return BAD_FUNC_ARG;
  27686. }
  27687. if (cert->customCertExtCount >= NUM_CUSTOM_EXT) {
  27688. return MEMORY_E;
  27689. }
  27690. /* Make sure we can properly parse the OID. */
  27691. ret = EncodePolicyOID(encodedOid, &encodedOidSz, oid, NULL);
  27692. if (ret != 0) {
  27693. return ret;
  27694. }
  27695. ext = &cert->customCertExt[cert->customCertExtCount];
  27696. ext->oid = oid;
  27697. ext->crit = (critical == 0) ? 0 : 1;
  27698. ext->val = der;
  27699. ext->valSz = derSz;
  27700. cert->customCertExtCount++;
  27701. return 0;
  27702. }
  27703. #endif
  27704. #endif /* WOLFSSL_CERT_EXT */
  27705. #ifdef WOLFSSL_ALT_NAMES
  27706. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  27707. {
  27708. int ret = 0;
  27709. cert->altNamesSz = 0;
  27710. if (decoded->altNames) {
  27711. ret = FlattenAltNames(cert->altNames,
  27712. sizeof(cert->altNames), decoded->altNames);
  27713. if (ret >= 0) {
  27714. cert->altNamesSz = ret;
  27715. ret = 0;
  27716. }
  27717. }
  27718. return ret;
  27719. }
  27720. #ifndef NO_FILESYSTEM
  27721. /* Set Alt Names from der cert, return 0 on success */
  27722. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz,
  27723. int devId)
  27724. {
  27725. int ret;
  27726. #ifdef WOLFSSL_SMALL_STACK
  27727. DecodedCert* decoded;
  27728. #else
  27729. DecodedCert decoded[1];
  27730. #endif
  27731. if (derSz < 0)
  27732. return derSz;
  27733. #ifdef WOLFSSL_SMALL_STACK
  27734. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  27735. DYNAMIC_TYPE_TMP_BUFFER);
  27736. if (decoded == NULL)
  27737. return MEMORY_E;
  27738. #endif
  27739. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27740. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27741. if (ret < 0) {
  27742. WOLFSSL_MSG("ParseCertRelative error");
  27743. }
  27744. else {
  27745. ret = SetAltNamesFromDcert(cert, decoded);
  27746. }
  27747. FreeDecodedCert(decoded);
  27748. #ifdef WOLFSSL_SMALL_STACK
  27749. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  27750. #endif
  27751. return ret < 0 ? ret : 0;
  27752. }
  27753. #endif
  27754. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  27755. {
  27756. int ret = 0;
  27757. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  27758. WOLFSSL_MSG("Couldn't extract dates");
  27759. ret = -1;
  27760. }
  27761. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  27762. decoded->afterDateLen > MAX_DATE_SIZE) {
  27763. WOLFSSL_MSG("Bad date size");
  27764. ret = -1;
  27765. }
  27766. else {
  27767. XMEMCPY(cert->beforeDate, decoded->beforeDate,
  27768. (size_t)decoded->beforeDateLen);
  27769. XMEMCPY(cert->afterDate, decoded->afterDate,
  27770. (size_t)decoded->afterDateLen);
  27771. cert->beforeDateSz = decoded->beforeDateLen;
  27772. cert->afterDateSz = decoded->afterDateLen;
  27773. }
  27774. return ret;
  27775. }
  27776. #endif /* WOLFSSL_ALT_NAMES */
  27777. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  27778. {
  27779. int sz;
  27780. if (decoded->subjectCN) {
  27781. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  27782. : CTC_NAME_SIZE - 1;
  27783. XSTRNCPY(cn->commonName, decoded->subjectCN, (size_t)sz);
  27784. cn->commonName[sz] = '\0';
  27785. cn->commonNameEnc = decoded->subjectCNEnc;
  27786. }
  27787. if (decoded->subjectC) {
  27788. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  27789. : CTC_NAME_SIZE - 1;
  27790. XSTRNCPY(cn->country, decoded->subjectC, (size_t)sz);
  27791. cn->country[sz] = '\0';
  27792. cn->countryEnc = decoded->subjectCEnc;
  27793. }
  27794. if (decoded->subjectST) {
  27795. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  27796. : CTC_NAME_SIZE - 1;
  27797. XSTRNCPY(cn->state, decoded->subjectST, (size_t)sz);
  27798. cn->state[sz] = '\0';
  27799. cn->stateEnc = decoded->subjectSTEnc;
  27800. }
  27801. if (decoded->subjectL) {
  27802. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  27803. : CTC_NAME_SIZE - 1;
  27804. XSTRNCPY(cn->locality, decoded->subjectL, (size_t)sz);
  27805. cn->locality[sz] = '\0';
  27806. cn->localityEnc = decoded->subjectLEnc;
  27807. }
  27808. if (decoded->subjectO) {
  27809. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  27810. : CTC_NAME_SIZE - 1;
  27811. XSTRNCPY(cn->org, decoded->subjectO, (size_t)sz);
  27812. cn->org[sz] = '\0';
  27813. cn->orgEnc = decoded->subjectOEnc;
  27814. }
  27815. if (decoded->subjectOU) {
  27816. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  27817. : CTC_NAME_SIZE - 1;
  27818. XSTRNCPY(cn->unit, decoded->subjectOU, (size_t)sz);
  27819. cn->unit[sz] = '\0';
  27820. cn->unitEnc = decoded->subjectOUEnc;
  27821. }
  27822. if (decoded->subjectSN) {
  27823. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  27824. : CTC_NAME_SIZE - 1;
  27825. XSTRNCPY(cn->sur, decoded->subjectSN, (size_t)sz);
  27826. cn->sur[sz] = '\0';
  27827. cn->surEnc = decoded->subjectSNEnc;
  27828. }
  27829. if (decoded->subjectSND) {
  27830. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  27831. : CTC_NAME_SIZE - 1;
  27832. XSTRNCPY(cn->serialDev, decoded->subjectSND, (size_t)sz);
  27833. cn->serialDev[sz] = '\0';
  27834. cn->serialDevEnc = decoded->subjectSNDEnc;
  27835. }
  27836. if (decoded->subjectUID) {
  27837. sz = (decoded->subjectUIDLen < CTC_NAME_SIZE) ? decoded->subjectUIDLen
  27838. : CTC_NAME_SIZE - 1;
  27839. XSTRNCPY(cn->userId, decoded->subjectUID, (size_t)sz);
  27840. cn->userId[sz] = '\0';
  27841. cn->userIdEnc = decoded->subjectUIDEnc;
  27842. }
  27843. #ifdef WOLFSSL_CERT_EXT
  27844. if (decoded->subjectBC) {
  27845. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  27846. : CTC_NAME_SIZE - 1;
  27847. XSTRNCPY(cn->busCat, decoded->subjectBC, (size_t)sz);
  27848. cn->busCat[sz] = '\0';
  27849. cn->busCatEnc = decoded->subjectBCEnc;
  27850. }
  27851. if (decoded->subjectJC) {
  27852. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  27853. : CTC_NAME_SIZE - 1;
  27854. XSTRNCPY(cn->joiC, decoded->subjectJC, (size_t)sz);
  27855. cn->joiC[sz] = '\0';
  27856. cn->joiCEnc = decoded->subjectJCEnc;
  27857. }
  27858. if (decoded->subjectJS) {
  27859. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  27860. : CTC_NAME_SIZE - 1;
  27861. XSTRNCPY(cn->joiSt, decoded->subjectJS, (size_t)sz);
  27862. cn->joiSt[sz] = '\0';
  27863. cn->joiStEnc = decoded->subjectJSEnc;
  27864. }
  27865. #endif
  27866. if (decoded->subjectEmail) {
  27867. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  27868. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  27869. XSTRNCPY(cn->email, decoded->subjectEmail, (size_t)sz);
  27870. cn->email[sz] = '\0';
  27871. }
  27872. #if defined(WOLFSSL_CERT_NAME_ALL) && \
  27873. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT))
  27874. if (decoded->subjectN) {
  27875. sz = (decoded->subjectNLen < CTC_NAME_SIZE) ? decoded->subjectNLen
  27876. : CTC_NAME_SIZE - 1;
  27877. XSTRNCPY(cn->dnName, decoded->subjectN, (size_t)sz);
  27878. cn->dnName[sz] = '\0';
  27879. cn->dnNameEnc = decoded->subjectNEnc;
  27880. }
  27881. if (decoded->subjectI) {
  27882. sz = (decoded->subjectILen < CTC_NAME_SIZE) ? decoded->subjectILen
  27883. : CTC_NAME_SIZE - 1;
  27884. XSTRNCPY(cn->initials, decoded->subjectI, (size_t)sz);
  27885. cn->initials[sz] = '\0';
  27886. cn->initialsEnc = decoded->subjectIEnc;
  27887. }
  27888. if (decoded->subjectGN) {
  27889. sz = (decoded->subjectGNLen < CTC_NAME_SIZE) ? decoded->subjectGNLen
  27890. : CTC_NAME_SIZE - 1;
  27891. XSTRNCPY(cn->givenName, decoded->subjectGN, (size_t)sz);
  27892. cn->givenName[sz] = '\0';
  27893. cn->givenNameEnc = decoded->subjectGNEnc;
  27894. }
  27895. if (decoded->subjectDNQ) {
  27896. sz = (decoded->subjectDNQLen < CTC_NAME_SIZE) ? decoded->subjectDNQLen
  27897. : CTC_NAME_SIZE - 1;
  27898. XSTRNCPY(cn->dnQualifier, decoded->subjectDNQ, (size_t)sz);
  27899. cn->dnQualifier[sz] = '\0';
  27900. cn->dnQualifierEnc = decoded->subjectDNQEnc;
  27901. }
  27902. #endif /* WOLFSSL_CERT_NAME_ALL */
  27903. }
  27904. #ifndef NO_FILESYSTEM
  27905. /* Set cn name from der buffer, return 0 on success */
  27906. static int SetNameFromCert(CertName* cn, const byte* der, int derSz, int devId)
  27907. {
  27908. int ret;
  27909. #ifdef WOLFSSL_SMALL_STACK
  27910. DecodedCert* decoded;
  27911. #else
  27912. DecodedCert decoded[1];
  27913. #endif
  27914. if (derSz < 0)
  27915. return derSz;
  27916. #ifdef WOLFSSL_SMALL_STACK
  27917. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  27918. DYNAMIC_TYPE_TMP_BUFFER);
  27919. if (decoded == NULL)
  27920. return MEMORY_E;
  27921. #endif
  27922. InitDecodedCert_ex(decoded, der, (word32)derSz, NULL, devId);
  27923. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  27924. if (ret < 0) {
  27925. WOLFSSL_MSG("ParseCertRelative error");
  27926. }
  27927. else {
  27928. SetNameFromDcert(cn, decoded);
  27929. }
  27930. FreeDecodedCert(decoded);
  27931. #ifdef WOLFSSL_SMALL_STACK
  27932. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  27933. #endif
  27934. return ret < 0 ? ret : 0;
  27935. }
  27936. /* Set cert issuer from issuerFile in PEM */
  27937. WOLFSSL_ABI
  27938. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  27939. {
  27940. int ret;
  27941. DerBuffer* der = NULL;
  27942. if (cert == NULL || issuerFile == NULL)
  27943. return BAD_FUNC_ARG;
  27944. ret = wc_PemCertToDer_ex(issuerFile, &der);
  27945. if (ret == 0) {
  27946. cert->selfSigned = 0;
  27947. ret = SetNameFromCert(&cert->issuer, der->buffer, (int)der->length,
  27948. INVALID_DEVID);
  27949. FreeDer(&der);
  27950. }
  27951. return ret;
  27952. }
  27953. /* Set cert subject from subjectFile in PEM */
  27954. WOLFSSL_ABI
  27955. int wc_SetSubject(Cert* cert, const char* subjectFile)
  27956. {
  27957. int ret;
  27958. DerBuffer* der = NULL;
  27959. if (cert == NULL || subjectFile == NULL)
  27960. return BAD_FUNC_ARG;
  27961. ret = wc_PemCertToDer_ex(subjectFile, &der);
  27962. if (ret == 0) {
  27963. ret = SetNameFromCert(&cert->subject, der->buffer, (int)der->length,
  27964. INVALID_DEVID);
  27965. FreeDer(&der);
  27966. }
  27967. return ret;
  27968. }
  27969. #ifdef WOLFSSL_ALT_NAMES
  27970. /* Set alt names from file in PEM */
  27971. WOLFSSL_ABI
  27972. int wc_SetAltNames(Cert* cert, const char* file)
  27973. {
  27974. int ret;
  27975. DerBuffer* der = NULL;
  27976. if (cert == NULL) {
  27977. return BAD_FUNC_ARG;
  27978. }
  27979. ret = wc_PemCertToDer_ex(file, &der);
  27980. if (ret == 0) {
  27981. ret = SetAltNamesFromCert(cert, der->buffer, (int)der->length,
  27982. INVALID_DEVID);
  27983. FreeDer(&der);
  27984. }
  27985. return ret;
  27986. }
  27987. #endif /* WOLFSSL_ALT_NAMES */
  27988. #endif /* !NO_FILESYSTEM */
  27989. /* Set cert issuer from DER buffer */
  27990. WOLFSSL_ABI
  27991. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  27992. {
  27993. int ret = 0;
  27994. if (cert == NULL) {
  27995. ret = BAD_FUNC_ARG;
  27996. }
  27997. else {
  27998. cert->selfSigned = 0;
  27999. /* Check if decodedCert is cached */
  28000. if (cert->der != der) {
  28001. /* Allocate cache for the decoded cert */
  28002. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28003. }
  28004. if (ret >= 0) {
  28005. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  28006. #ifndef WOLFSSL_CERT_GEN_CACHE
  28007. wc_SetCert_Free(cert);
  28008. #endif
  28009. }
  28010. }
  28011. return ret;
  28012. }
  28013. /* Set cert subject from DER buffer */
  28014. WOLFSSL_ABI
  28015. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  28016. {
  28017. int ret = 0;
  28018. if (cert == NULL) {
  28019. ret = BAD_FUNC_ARG;
  28020. }
  28021. else {
  28022. /* Check if decodedCert is cached */
  28023. if (cert->der != der) {
  28024. /* Allocate cache for the decoded cert */
  28025. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28026. }
  28027. if (ret >= 0) {
  28028. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  28029. #ifndef WOLFSSL_CERT_GEN_CACHE
  28030. wc_SetCert_Free(cert);
  28031. #endif
  28032. }
  28033. }
  28034. return ret;
  28035. }
  28036. #ifdef WOLFSSL_CERT_EXT
  28037. /* Set cert raw subject from DER buffer */
  28038. WOLFSSL_ABI
  28039. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  28040. {
  28041. int ret = 0;
  28042. if (cert == NULL) {
  28043. ret = BAD_FUNC_ARG;
  28044. }
  28045. else {
  28046. /* Check if decodedCert is cached */
  28047. if (cert->der != der) {
  28048. /* Allocate cache for the decoded cert */
  28049. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28050. }
  28051. if (ret >= 0) {
  28052. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  28053. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  28054. (int)sizeof(CertName))) {
  28055. XMEMCPY(cert->sbjRaw,
  28056. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  28057. (size_t)((DecodedCert*)cert->decodedCert)->
  28058. subjectRawLen);
  28059. }
  28060. #ifndef WOLFSSL_CERT_GEN_CACHE
  28061. wc_SetCert_Free(cert);
  28062. #endif
  28063. }
  28064. }
  28065. return ret;
  28066. }
  28067. /* Set cert raw issuer from DER buffer */
  28068. WOLFSSL_ABI
  28069. int wc_SetIssuerRaw(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. /* Copy the subject to the issuer field */
  28086. XMEMCPY(cert->issRaw,
  28087. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  28088. (size_t)((DecodedCert*)cert->decodedCert)->
  28089. subjectRawLen);
  28090. }
  28091. #ifndef WOLFSSL_CERT_GEN_CACHE
  28092. wc_SetCert_Free(cert);
  28093. #endif
  28094. }
  28095. }
  28096. return ret;
  28097. }
  28098. #endif
  28099. #ifdef WOLFSSL_ALT_NAMES
  28100. /* Set cert alt names from DER buffer */
  28101. WOLFSSL_ABI
  28102. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  28103. {
  28104. int ret = 0;
  28105. if (cert == NULL) {
  28106. ret = BAD_FUNC_ARG;
  28107. }
  28108. else {
  28109. /* Check if decodedCert is cached */
  28110. if (cert->der != der) {
  28111. /* Allocate cache for the decoded cert */
  28112. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28113. }
  28114. if (ret >= 0) {
  28115. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28116. #ifndef WOLFSSL_CERT_GEN_CACHE
  28117. wc_SetCert_Free(cert);
  28118. #endif
  28119. }
  28120. }
  28121. return(ret);
  28122. }
  28123. /* Set cert dates from DER buffer */
  28124. WOLFSSL_ABI
  28125. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  28126. {
  28127. int ret = 0;
  28128. if (cert == NULL) {
  28129. ret = BAD_FUNC_ARG;
  28130. }
  28131. else {
  28132. /* Check if decodedCert is cached */
  28133. if (cert->der != der) {
  28134. /* Allocate cache for the decoded cert */
  28135. ret = wc_SetCert_LoadDer(cert, der, (word32)derSz, INVALID_DEVID);
  28136. }
  28137. if (ret >= 0) {
  28138. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  28139. #ifndef WOLFSSL_CERT_GEN_CACHE
  28140. wc_SetCert_Free(cert);
  28141. #endif
  28142. }
  28143. }
  28144. return(ret);
  28145. }
  28146. #endif /* WOLFSSL_ALT_NAMES */
  28147. #endif /* WOLFSSL_CERT_GEN */
  28148. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  28149. || defined(OPENSSL_EXTRA)
  28150. /* Encode OID string representation to ITU-T X.690 format */
  28151. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  28152. {
  28153. word32 idx = 0, nb_val;
  28154. char *token, *str, *ptr;
  28155. word32 len;
  28156. (void)heap;
  28157. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  28158. return BAD_FUNC_ARG;
  28159. /* duplicate string (including terminator) */
  28160. len = (word32)XSTRLEN(in);
  28161. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28162. if (str == NULL)
  28163. return MEMORY_E;
  28164. XMEMCPY(str, in, len+1);
  28165. nb_val = 0;
  28166. /* parse value, and set corresponding Policy OID value */
  28167. token = XSTRTOK(str, ".", &ptr);
  28168. while (token != NULL)
  28169. {
  28170. word32 val = (word32)XATOI(token);
  28171. if (nb_val == 0) {
  28172. if (val > 2) {
  28173. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28174. return ASN_OBJECT_ID_E;
  28175. }
  28176. out[idx] = (byte)(40 * val);
  28177. }
  28178. else if (nb_val == 1) {
  28179. if (val > 127) {
  28180. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28181. return ASN_OBJECT_ID_E;
  28182. }
  28183. if (idx > *outSz) {
  28184. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28185. return BUFFER_E;
  28186. }
  28187. out[idx++] += (byte)val;
  28188. }
  28189. else {
  28190. word32 tb = 0;
  28191. int i = 0;
  28192. byte oid[MAX_OID_SZ];
  28193. while (val >= 128) {
  28194. word32 x = val % 128;
  28195. val /= 128;
  28196. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  28197. }
  28198. if ((idx+(word32)i) >= *outSz) {
  28199. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28200. return BUFFER_E;
  28201. }
  28202. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  28203. /* push value in the right order */
  28204. while (i >= 0)
  28205. out[idx++] = oid[i--];
  28206. }
  28207. token = XSTRTOK(NULL, ".", &ptr);
  28208. nb_val++;
  28209. }
  28210. *outSz = idx;
  28211. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  28212. return 0;
  28213. }
  28214. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  28215. #endif /* !NO_CERTS */
  28216. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  28217. /* Helper function for wolfSSL_i2d_DHparams */
  28218. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  28219. {
  28220. #ifndef WOLFSSL_ASN_TEMPLATE
  28221. word32 idx = 0;
  28222. word32 total;
  28223. WOLFSSL_ENTER("StoreDHparams");
  28224. if (out == NULL) {
  28225. WOLFSSL_MSG("Null buffer error");
  28226. return BUFFER_E;
  28227. }
  28228. /* determine size */
  28229. /* integer - g */
  28230. idx = SetASNIntMP(g, -1, NULL);
  28231. /* integer - p */
  28232. idx += SetASNIntMP(p, -1, NULL);
  28233. total = idx;
  28234. /* sequence */
  28235. idx += SetSequence(idx, NULL);
  28236. /* make sure output fits in buffer */
  28237. if (idx > *outLen) {
  28238. return BUFFER_E;
  28239. }
  28240. /* write DH parameters */
  28241. /* sequence - for P and G only */
  28242. idx = SetSequence(total, out);
  28243. /* integer - p */
  28244. idx += SetASNIntMP(p, -1, out + idx);
  28245. /* integer - g */
  28246. idx += SetASNIntMP(g, -1, out + idx);
  28247. *outLen = idx;
  28248. return 0;
  28249. #else
  28250. ASNSetData dataASN[dhParamASN_Length];
  28251. int ret = 0;
  28252. int sz = 0;
  28253. WOLFSSL_ENTER("StoreDHparams");
  28254. if (out == NULL) {
  28255. ret = BUFFER_E;
  28256. }
  28257. if (ret == 0) {
  28258. XMEMSET(dataASN, 0, sizeof(dataASN));
  28259. /* Set mp_int containing p and g. */
  28260. SetASN_MP(&dataASN[DHPARAMASN_IDX_PRIME], p);
  28261. SetASN_MP(&dataASN[DHPARAMASN_IDX_BASE], g);
  28262. /* privateValueLength not encoded. */
  28263. dataASN[DHPARAMASN_IDX_PRIVLEN].noOut = 1;
  28264. /* Calculate the size of the DH parameters. */
  28265. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  28266. }
  28267. /* Check buffer is big enough for encoding. */
  28268. if ((ret == 0) && ((int)*outLen < sz)) {
  28269. ret = BUFFER_E;
  28270. }
  28271. if (ret == 0) {
  28272. /* Encode the DH parameters into buffer. */
  28273. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  28274. /* Set the actual encoding size. */
  28275. *outLen = sz;
  28276. }
  28277. return ret;
  28278. #endif /* WOLFSSL_ASN_TEMPLATE */
  28279. }
  28280. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  28281. #if defined(HAVE_ECC) || !defined(NO_DSA)
  28282. #ifdef WOLFSSL_ASN_TEMPLATE
  28283. /* ASN.1 template for DSA signature.
  28284. * RFC 5912, 6 - DSA-Sig-Value
  28285. */
  28286. static const ASNItem dsaSigASN[] = {
  28287. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28288. /* r */
  28289. /* R */ { 1, ASN_INTEGER, 0, 0, 0 },
  28290. /* s */
  28291. /* S */ { 1, ASN_INTEGER, 0, 0, 0 },
  28292. };
  28293. enum {
  28294. DSASIGASN_IDX_SEQ = 0,
  28295. DSASIGASN_IDX_R,
  28296. DSASIGASN_IDX_S
  28297. };
  28298. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  28299. #endif
  28300. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28301. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  28302. {
  28303. #ifndef WOLFSSL_ASN_TEMPLATE
  28304. word32 idx = 0;
  28305. int rSz; /* encoding size */
  28306. int sSz;
  28307. int headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28308. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28309. int rLeadingZero = mp_leading_bit(r);
  28310. int sLeadingZero = mp_leading_bit(s);
  28311. int rLen = mp_unsigned_bin_size(r); /* big int size */
  28312. int sLen = mp_unsigned_bin_size(s);
  28313. if (*outLen < (word32)((rLen + rLeadingZero + sLen + sLeadingZero +
  28314. headerSz + 2))) /* SEQ_TAG + LEN(ENUM) */
  28315. return BUFFER_E;
  28316. idx = SetSequence((word32)(rLen + rLeadingZero + sLen + sLeadingZero +
  28317. headerSz), out);
  28318. /* store r */
  28319. rSz = SetASNIntMP(r, (int)(*outLen - idx), &out[idx]);
  28320. if (rSz < 0)
  28321. return rSz;
  28322. idx += (word32)rSz;
  28323. /* store s */
  28324. sSz = SetASNIntMP(s, (int)(*outLen - idx), &out[idx]);
  28325. if (sSz < 0)
  28326. return sSz;
  28327. idx += (word32)sSz;
  28328. *outLen = idx;
  28329. return 0;
  28330. #else
  28331. ASNSetData dataASN[dsaSigASN_Length];
  28332. int ret;
  28333. int sz;
  28334. /* Clear dynamic data and set mp_ints r and s */
  28335. XMEMSET(dataASN, 0, sizeof(dataASN));
  28336. SetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28337. SetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28338. /* Calculate size of encoding. */
  28339. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28340. /* Check buffer is big enough for encoding. */
  28341. if ((ret == 0) && ((int)*outLen < sz)) {
  28342. ret = BUFFER_E;
  28343. }
  28344. if (ret == 0) {
  28345. /* Encode DSA signature into buffer. */
  28346. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28347. /* Set the actual encoding size. */
  28348. *outLen = (word32)sz;
  28349. }
  28350. return ret;
  28351. #endif /* WOLFSSL_ASN_TEMPLATE */
  28352. }
  28353. #ifndef WOLFSSL_ASN_TEMPLATE
  28354. /* determine if leading bit is set */
  28355. static word32 is_leading_bit_set(const byte* input, word32 sz)
  28356. {
  28357. byte c = 0;
  28358. if (sz > 0)
  28359. c = input[0];
  28360. return (c & 0x80) != 0;
  28361. }
  28362. static word32 trim_leading_zeros(const byte** input, word32 sz)
  28363. {
  28364. int i;
  28365. word32 leadingZeroCount = 0;
  28366. const byte* tmp = *input;
  28367. for (i=0; i<(int)sz; i++) {
  28368. if (tmp[i] != 0)
  28369. break;
  28370. leadingZeroCount++;
  28371. }
  28372. /* catch all zero case */
  28373. if (sz > 0 && leadingZeroCount == sz) {
  28374. leadingZeroCount--;
  28375. }
  28376. *input += leadingZeroCount;
  28377. sz -= leadingZeroCount;
  28378. return sz;
  28379. }
  28380. #endif
  28381. /* Der Encode r & s ints into out, outLen is (in/out) size */
  28382. /* All input/outputs are assumed to be big-endian */
  28383. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  28384. const byte* s, word32 sLen)
  28385. {
  28386. #ifndef WOLFSSL_ASN_TEMPLATE
  28387. int ret;
  28388. word32 idx;
  28389. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  28390. word32 rAddLeadZero, sAddLeadZero;
  28391. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  28392. return BAD_FUNC_ARG;
  28393. /* Trim leading zeros */
  28394. rLen = trim_leading_zeros(&r, rLen);
  28395. sLen = trim_leading_zeros(&s, sLen);
  28396. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  28397. /* Add leading zero if MSB is set */
  28398. rAddLeadZero = is_leading_bit_set(r, rLen);
  28399. sAddLeadZero = is_leading_bit_set(s, sLen);
  28400. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  28401. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  28402. return BUFFER_E;
  28403. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  28404. /* store r */
  28405. ret = SetASNInt((int)rLen, (byte)(rAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28406. if (ret < 0)
  28407. return ret;
  28408. idx += (word32)ret;
  28409. XMEMCPY(&out[idx], r, rLen);
  28410. idx += rLen;
  28411. /* store s */
  28412. ret = SetASNInt((int)sLen, (byte)(sAddLeadZero ? 0x80U : 0x00U), &out[idx]);
  28413. if (ret < 0)
  28414. return ret;
  28415. idx += (word32)ret;
  28416. XMEMCPY(&out[idx], s, sLen);
  28417. idx += sLen;
  28418. *outLen = idx;
  28419. return 0;
  28420. #else
  28421. ASNSetData dataASN[dsaSigASN_Length];
  28422. int ret;
  28423. int sz;
  28424. /* Clear dynamic data and set buffers for r and s */
  28425. XMEMSET(dataASN, 0, sizeof(dataASN));
  28426. SetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28427. SetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28428. /* Calculate size of encoding. */
  28429. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  28430. /* Check buffer is big enough for encoding. */
  28431. if ((ret == 0) && ((int)*outLen < sz)) {
  28432. ret = BUFFER_E;
  28433. }
  28434. if (ret == 0) {
  28435. /* Encode DSA signature into buffer. */
  28436. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  28437. /* Set the actual encoding size. */
  28438. *outLen = (word32)sz;
  28439. }
  28440. return ret;
  28441. #endif /* WOLFSSL_ASN_TEMPLATE */
  28442. }
  28443. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  28444. /* All input/outputs are assumed to be big-endian */
  28445. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  28446. byte* s, word32* sLen)
  28447. {
  28448. #ifndef WOLFSSL_ASN_TEMPLATE
  28449. int ret;
  28450. word32 idx = 0;
  28451. int len = 0;
  28452. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28453. return ASN_ECC_KEY_E;
  28454. }
  28455. #ifndef NO_STRICT_ECDSA_LEN
  28456. /* enable strict length checking for signature */
  28457. if (sigLen != idx + (word32)len) {
  28458. return ASN_ECC_KEY_E;
  28459. }
  28460. #else
  28461. /* allow extra signature bytes at end */
  28462. if ((word32)len > (sigLen - idx)) {
  28463. return ASN_ECC_KEY_E;
  28464. }
  28465. #endif
  28466. ret = GetASNInt(sig, &idx, &len, sigLen);
  28467. if (ret != 0)
  28468. return ret;
  28469. if (rLen)
  28470. *rLen = (word32)len;
  28471. if (r)
  28472. XMEMCPY(r, (byte*)sig + idx, (size_t)len);
  28473. idx += (word32)len;
  28474. ret = GetASNInt(sig, &idx, &len, sigLen);
  28475. if (ret != 0)
  28476. return ret;
  28477. if (sLen)
  28478. *sLen = (word32)len;
  28479. if (s)
  28480. XMEMCPY(s, (byte*)sig + idx, (size_t)len);
  28481. #ifndef NO_STRICT_ECDSA_LEN
  28482. /* sanity check that the index has been advanced all the way to the end of
  28483. * the buffer */
  28484. if (idx + (word32)len != sigLen) {
  28485. ret = ASN_ECC_KEY_E;
  28486. }
  28487. #endif
  28488. return ret;
  28489. #else
  28490. ASNGetData dataASN[dsaSigASN_Length];
  28491. word32 idx = 0;
  28492. /* Clear dynamic data and set buffers to put r and s into. */
  28493. XMEMSET(dataASN, 0, sizeof(dataASN));
  28494. GetASN_Buffer(&dataASN[DSASIGASN_IDX_R], r, rLen);
  28495. GetASN_Buffer(&dataASN[DSASIGASN_IDX_S], s, sLen);
  28496. /* Decode the DSA signature. */
  28497. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  28498. sigLen);
  28499. #endif /* WOLFSSL_ASN_TEMPLATE */
  28500. }
  28501. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  28502. {
  28503. return DecodeECC_DSA_Sig_Ex(sig, sigLen, r, s, 1);
  28504. }
  28505. int DecodeECC_DSA_Sig_Ex(const byte* sig, word32 sigLen, mp_int* r, mp_int* s,
  28506. int init)
  28507. {
  28508. #ifndef WOLFSSL_ASN_TEMPLATE
  28509. word32 idx = 0;
  28510. int len = 0;
  28511. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  28512. return ASN_ECC_KEY_E;
  28513. }
  28514. #ifndef NO_STRICT_ECDSA_LEN
  28515. /* enable strict length checking for signature */
  28516. if (sigLen != idx + (word32)len) {
  28517. return ASN_ECC_KEY_E;
  28518. }
  28519. #else
  28520. /* allow extra signature bytes at end */
  28521. if ((word32)len > (sigLen - idx)) {
  28522. return ASN_ECC_KEY_E;
  28523. }
  28524. #endif
  28525. if (GetIntPositive(r, sig, &idx, sigLen, init) < 0) {
  28526. return ASN_ECC_KEY_E;
  28527. }
  28528. if (GetIntPositive(s, sig, &idx, sigLen, init) < 0) {
  28529. mp_clear(r);
  28530. return ASN_ECC_KEY_E;
  28531. }
  28532. #ifndef NO_STRICT_ECDSA_LEN
  28533. /* sanity check that the index has been advanced all the way to the end of
  28534. * the buffer */
  28535. if (idx != sigLen) {
  28536. mp_clear(r);
  28537. mp_clear(s);
  28538. return ASN_ECC_KEY_E;
  28539. }
  28540. #endif
  28541. return 0;
  28542. #else
  28543. ASNGetData dataASN[dsaSigASN_Length];
  28544. word32 idx = 0;
  28545. int ret;
  28546. /* Clear dynamic data and set mp_ints to put r and s into. */
  28547. XMEMSET(dataASN, 0, sizeof(dataASN));
  28548. if (init) {
  28549. GetASN_MP(&dataASN[DSASIGASN_IDX_R], r);
  28550. GetASN_MP(&dataASN[DSASIGASN_IDX_S], s);
  28551. }
  28552. else {
  28553. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_R], r);
  28554. GetASN_MP_Inited(&dataASN[DSASIGASN_IDX_S], s);
  28555. }
  28556. /* Decode the DSA signature. */
  28557. ret = GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 0, sig, &idx,
  28558. sigLen);
  28559. #ifndef NO_STRICT_ECDSA_LEN
  28560. /* sanity check that the index has been advanced all the way to the end of
  28561. * the buffer */
  28562. if ((ret == 0) && (idx != sigLen)) {
  28563. ret = ASN_ECC_KEY_E;
  28564. }
  28565. #endif
  28566. if (ret != 0) {
  28567. mp_clear(r);
  28568. mp_clear(s);
  28569. }
  28570. return ret;
  28571. #endif /* WOLFSSL_ASN_TEMPLATE */
  28572. }
  28573. #endif
  28574. #ifdef WOLFSSL_ASN_TEMPLATE
  28575. #ifdef WOLFSSL_CUSTOM_CURVES
  28576. /* Convert data to hex string.
  28577. *
  28578. * Big-endian byte array is converted to big-endian hexadecimal string.
  28579. *
  28580. * @param [in] input Buffer containing data.
  28581. * @param [in] inSz Size of data in buffer.
  28582. * @param [out] out Buffer to hold hex string.
  28583. */
  28584. static void DataToHexString(const byte* input, word32 inSz, char* out)
  28585. {
  28586. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  28587. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  28588. word32 i;
  28589. /* Converting a byte of data at a time to two hex characters. */
  28590. for (i = 0; i < inSz; i++) {
  28591. out[i*2 + 0] = hexChar[input[i] >> 4];
  28592. out[i*2 + 1] = hexChar[input[i] & 0xf];
  28593. }
  28594. /* NUL terminate string. */
  28595. out[i * 2] = '\0';
  28596. }
  28597. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28598. /* Convert data to hex string and place in allocated buffer.
  28599. *
  28600. * Big-endian byte array is converted to big-endian hexadecimal string.
  28601. *
  28602. * @param [in] input Buffer containing data.
  28603. * @param [in] inSz Size of data in buffer.
  28604. * @param [out] out Allocated buffer holding hex string.
  28605. * @param [in] heap Dynamic memory allocation hint.
  28606. * @param [in] heapType Type of heap to use.
  28607. * @return 0 on succcess.
  28608. * @return MEMORY_E when dynamic memory allocation fails.
  28609. */
  28610. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  28611. void* heap, int heapType)
  28612. {
  28613. int ret = 0;
  28614. char* str;
  28615. /* Allocate for 2 string characters ber byte plus NUL. */
  28616. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  28617. if (str == NULL) {
  28618. ret = MEMORY_E;
  28619. }
  28620. else {
  28621. /* Convert to hex string. */
  28622. DataToHexString(input, inSz, str);
  28623. *out = str;
  28624. }
  28625. (void)heap;
  28626. (void)heapType;
  28627. return ret;
  28628. }
  28629. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28630. /* ASN.1 template for SpecifiedECDomain.
  28631. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  28632. * NOTE: characteristic-two-field not supported. */
  28633. static const ASNItem eccSpecifiedASN[] = {
  28634. /* version */
  28635. /* VER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28636. /* fieldID */
  28637. /* PRIME_SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28638. /* prime-field or characteristic-two-field */
  28639. /* PRIME_OID */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  28640. /* Prime-p */
  28641. /* PRIME_P */ { 1, ASN_INTEGER, 0, 0, 0 },
  28642. /* fieldID */
  28643. /* PARAM_SEQ, */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28644. /* a */
  28645. /* PARAM_A */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28646. /* b */
  28647. /* PARAM_B */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28648. /* seed */
  28649. /* PARAM_SEED */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  28650. /* base */
  28651. /* BASE */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  28652. /* order */
  28653. /* ORDER */ { 0, ASN_INTEGER, 0, 0, 0 },
  28654. /* cofactor */
  28655. /* COFACTOR */ { 0, ASN_INTEGER, 0, 0, 1 },
  28656. /* hash */
  28657. /* HASH_SEQ */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  28658. };
  28659. enum {
  28660. ECCSPECIFIEDASN_IDX_VER = 0,
  28661. ECCSPECIFIEDASN_IDX_PRIME_SEQ,
  28662. ECCSPECIFIEDASN_IDX_PRIME_OID,
  28663. ECCSPECIFIEDASN_IDX_PRIME_P,
  28664. ECCSPECIFIEDASN_IDX_PARAM_SEQ,
  28665. ECCSPECIFIEDASN_IDX_PARAM_A,
  28666. ECCSPECIFIEDASN_IDX_PARAM_B,
  28667. ECCSPECIFIEDASN_IDX_PARAM_SEED,
  28668. ECCSPECIFIEDASN_IDX_BASE,
  28669. ECCSPECIFIEDASN_IDX_ORDER,
  28670. ECCSPECIFIEDASN_IDX_COFACTOR,
  28671. ECCSPECIFIEDASN_IDX_HASH_SEQ
  28672. };
  28673. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  28674. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  28675. /* OID indicating the prime field is explicity defined. */
  28676. static const byte primeFieldOID[] = {
  28677. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  28678. };
  28679. static const char ecSetCustomName[] = "Custom";
  28680. /* Explicit EC parameter values. */
  28681. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  28682. ecc_key* key)
  28683. {
  28684. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  28685. int ret = 0;
  28686. ecc_set_type* curve;
  28687. word32 idx = 0;
  28688. byte version;
  28689. byte cofactor;
  28690. const byte *base;
  28691. word32 baseLen;
  28692. /* Allocate a new parameter set. */
  28693. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  28694. DYNAMIC_TYPE_ECC_BUFFER);
  28695. if (curve == NULL) {
  28696. ret = MEMORY_E;
  28697. }
  28698. else {
  28699. /* Clear out parameters and set fields to indicate it is custom. */
  28700. XMEMSET(curve, 0, sizeof(*curve));
  28701. }
  28702. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  28703. if (ret == 0) {
  28704. /* Set name to be: "Custom" */
  28705. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28706. curve->name = ecSetCustomName;
  28707. #else
  28708. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  28709. #endif
  28710. curve->id = ECC_CURVE_CUSTOM;
  28711. /* Get version, must have prime field OID and get co-factor. */
  28712. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_VER], &version);
  28713. GetASN_ExpBuffer(&dataASN[ECCSPECIFIEDASN_IDX_PRIME_OID],
  28714. primeFieldOID, sizeof(primeFieldOID));
  28715. GetASN_Int8Bit(&dataASN[ECCSPECIFIEDASN_IDX_COFACTOR], &cofactor);
  28716. /* Decode the explicit parameters. */
  28717. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  28718. input, &idx, inSz);
  28719. }
  28720. /* Version must be 1 or 2 for supporting explicit parameters. */
  28721. if ((ret == 0) && (version < 1 || version > 3)) {
  28722. ret = ASN_PARSE_E;
  28723. }
  28724. #ifndef WOLFSSL_NO_ASN_STRICT
  28725. /* Only version 2 and above can have a seed. */
  28726. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_PARAM_SEED].tag != 0) &&
  28727. (version < 2)) {
  28728. ret = ASN_PARSE_E;
  28729. }
  28730. #endif
  28731. /* Only version 2 and above can have a hash algorithm. */
  28732. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_HASH_SEQ].tag != 0) &&
  28733. (version < 2)) {
  28734. ret = ASN_PARSE_E;
  28735. }
  28736. if ((ret == 0) && (dataASN[ECCSPECIFIEDASN_IDX_COFACTOR].tag != 0)) {
  28737. /* Store optional co-factor. */
  28738. curve->cofactor = cofactor;
  28739. }
  28740. if (ret == 0) {
  28741. /* Length of the prime in bytes is the curve size. */
  28742. curve->size =
  28743. (int)dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length;
  28744. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  28745. GetASN_GetConstRef(&dataASN[ECCSPECIFIEDASN_IDX_BASE], &base,
  28746. &baseLen);
  28747. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  28748. ret = ASN_PARSE_E;
  28749. }
  28750. }
  28751. /* Put the curve parameters into the set.
  28752. * Convert the big-endian number byte array to a big-endian string.
  28753. */
  28754. #ifndef WOLFSSL_ECC_CURVE_STATIC
  28755. /* Allocate buffer to put hex strings into. */
  28756. if (ret == 0) {
  28757. /* Base X-ordinate */
  28758. ret = DataToHexStringAlloc(base + 1, (word32)curve->size,
  28759. (char**)&curve->Gx, key->heap,
  28760. DYNAMIC_TYPE_ECC_BUFFER);
  28761. }
  28762. if (ret == 0) {
  28763. /* Base Y-ordinate */
  28764. ret = DataToHexStringAlloc(base + 1 + curve->size, (word32)curve->size,
  28765. (char**)&curve->Gy, key->heap,
  28766. DYNAMIC_TYPE_ECC_BUFFER);
  28767. }
  28768. if (ret == 0) {
  28769. /* Prime */
  28770. ret = DataToHexStringAlloc(
  28771. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28772. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28773. (char**)&curve->prime, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28774. }
  28775. if (ret == 0) {
  28776. /* Parameter A */
  28777. ret = DataToHexStringAlloc(
  28778. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28779. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28780. (char**)&curve->Af, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28781. }
  28782. if (ret == 0) {
  28783. /* Parameter B */
  28784. ret = DataToHexStringAlloc(
  28785. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28786. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28787. (char**)&curve->Bf, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28788. }
  28789. if (ret == 0) {
  28790. /* Order of curve */
  28791. ret = DataToHexStringAlloc(
  28792. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28793. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28794. (char**)&curve->order, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  28795. }
  28796. #else
  28797. if (ret == 0) {
  28798. /* Base X-ordinate */
  28799. DataToHexString(base + 1, curve->size, curve->Gx);
  28800. /* Base Y-ordinate */
  28801. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  28802. /* Prime */
  28803. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.data,
  28804. dataASN[ECCSPECIFIEDASN_IDX_PRIME_P].data.ref.length,
  28805. curve->prime);
  28806. /* Parameter A */
  28807. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.data,
  28808. dataASN[ECCSPECIFIEDASN_IDX_PARAM_A].data.ref.length,
  28809. curve->Af);
  28810. /* Parameter B */
  28811. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.data,
  28812. dataASN[ECCSPECIFIEDASN_IDX_PARAM_B].data.ref.length,
  28813. curve->Bf);
  28814. /* Order of curve */
  28815. DataToHexString(dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.data,
  28816. dataASN[ECCSPECIFIEDASN_IDX_ORDER].data.ref.length,
  28817. curve->order);
  28818. }
  28819. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  28820. /* Store parameter set in key. */
  28821. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  28822. ret = ASN_PARSE_E;
  28823. }
  28824. if (ret == 0) {
  28825. /* The parameter set was allocated.. */
  28826. key->deallocSet = 1;
  28827. }
  28828. if ((ret != 0) && (curve != NULL)) {
  28829. /* Failed to set parameters so free paramter set. */
  28830. wc_ecc_free_curve(curve, key->heap);
  28831. }
  28832. FREE_ASNGETDATA(dataASN, key->heap);
  28833. return ret;
  28834. }
  28835. #endif /* WOLFSSL_CUSTOM_CURVES */
  28836. #endif /* WOLFSSL_ASN_TEMPLATE */
  28837. #ifdef HAVE_ECC
  28838. #ifdef WOLFSSL_ASN_TEMPLATE
  28839. /* ASN.1 template for ECC private key.
  28840. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  28841. */
  28842. static const ASNItem eccKeyASN[] = {
  28843. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  28844. /* version */
  28845. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  28846. /* privateKey */
  28847. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  28848. /* parameters */
  28849. /* PARAMS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PARAMS, 1, 1, 1 },
  28850. /* named */
  28851. /* CURVEID */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  28852. /* specified */
  28853. /* CURVEPARAMS */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  28854. /* publicKey */
  28855. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ECC_PUBKEY, 1, 1, 1 },
  28856. /* Uncompressed point - X9.62. */
  28857. /* PUBKEY_VAL, */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  28858. };
  28859. enum {
  28860. ECCKEYASN_IDX_SEQ = 0,
  28861. ECCKEYASN_IDX_VER,
  28862. ECCKEYASN_IDX_PKEY,
  28863. ECCKEYASN_IDX_PARAMS,
  28864. ECCKEYASN_IDX_CURVEID,
  28865. ECCKEYASN_IDX_CURVEPARAMS,
  28866. ECCKEYASN_IDX_PUBKEY,
  28867. ECCKEYASN_IDX_PUBKEY_VAL
  28868. };
  28869. /* Number of items in ASN.1 template for ECC private key. */
  28870. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  28871. #endif
  28872. WOLFSSL_ABI
  28873. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  28874. word32 inSz)
  28875. {
  28876. #ifndef WOLFSSL_ASN_TEMPLATE
  28877. word32 oidSum;
  28878. int version, length;
  28879. int privSz, pubSz = 0;
  28880. byte b;
  28881. int ret = 0;
  28882. int curve_id = ECC_CURVE_DEF;
  28883. #ifdef WOLFSSL_SMALL_STACK
  28884. byte* priv;
  28885. byte* pub = NULL;
  28886. #else
  28887. byte priv[ECC_MAXSIZE+1];
  28888. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  28889. #endif
  28890. word32 algId = 0;
  28891. byte* pubData = NULL;
  28892. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  28893. return BAD_FUNC_ARG;
  28894. /* if has pkcs8 header skip it */
  28895. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  28896. /* ignore error, did not have pkcs8 header */
  28897. }
  28898. else {
  28899. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  28900. }
  28901. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  28902. return ASN_PARSE_E;
  28903. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  28904. return ASN_PARSE_E;
  28905. if (*inOutIdx >= inSz)
  28906. return ASN_PARSE_E;
  28907. b = input[*inOutIdx];
  28908. *inOutIdx += 1;
  28909. /* priv type */
  28910. if (b != 4 && b != 6 && b != 7)
  28911. return ASN_PARSE_E;
  28912. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  28913. return ASN_PARSE_E;
  28914. privSz = length;
  28915. if (privSz > ECC_MAXSIZE)
  28916. return BUFFER_E;
  28917. #ifdef WOLFSSL_SMALL_STACK
  28918. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28919. if (priv == NULL)
  28920. return MEMORY_E;
  28921. #endif
  28922. /* priv key */
  28923. XMEMCPY(priv, &input[*inOutIdx], (size_t)privSz);
  28924. *inOutIdx += (word32)length;
  28925. if ((*inOutIdx + 1) < inSz) {
  28926. /* prefix 0, may have */
  28927. b = input[*inOutIdx];
  28928. if (b == ECC_PREFIX_0) {
  28929. *inOutIdx += 1;
  28930. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  28931. ret = ASN_PARSE_E;
  28932. else {
  28933. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  28934. inSz);
  28935. if (ret == 0) {
  28936. if ((ret = CheckCurve(oidSum)) < 0)
  28937. ret = ECC_CURVE_OID_E;
  28938. else {
  28939. curve_id = ret;
  28940. ret = 0;
  28941. }
  28942. }
  28943. }
  28944. }
  28945. }
  28946. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  28947. /* prefix 1 */
  28948. b = input[*inOutIdx];
  28949. *inOutIdx += 1;
  28950. if (b != ECC_PREFIX_1) {
  28951. ret = ASN_ECC_KEY_E;
  28952. }
  28953. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  28954. ret = ASN_PARSE_E;
  28955. }
  28956. else {
  28957. /* key header */
  28958. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  28959. if (ret == 0) {
  28960. /* pub key */
  28961. pubSz = length;
  28962. if (pubSz > 2*(ECC_MAXSIZE+1))
  28963. ret = BUFFER_E;
  28964. else {
  28965. #ifdef WOLFSSL_SMALL_STACK
  28966. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28967. if (pub == NULL)
  28968. ret = MEMORY_E;
  28969. else
  28970. #endif
  28971. {
  28972. XMEMCPY(pub, &input[*inOutIdx], (size_t)pubSz);
  28973. *inOutIdx += (word32)length;
  28974. pubData = pub;
  28975. }
  28976. }
  28977. }
  28978. }
  28979. }
  28980. if (ret == 0) {
  28981. ret = wc_ecc_import_private_key_ex(priv, (word32)privSz, pubData,
  28982. (word32)pubSz, key, curve_id);
  28983. }
  28984. #ifdef WOLFSSL_SMALL_STACK
  28985. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28986. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  28987. #endif
  28988. return ret;
  28989. #else
  28990. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  28991. byte version;
  28992. int ret = 0;
  28993. int curve_id = ECC_CURVE_DEF;
  28994. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  28995. word32 algId = 0;
  28996. #endif
  28997. /* Validate parameters. */
  28998. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  28999. ret = BAD_FUNC_ARG;
  29000. }
  29001. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12) || defined(SM2)
  29002. /* if has pkcs8 header skip it */
  29003. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  29004. /* ignore error, did not have pkcs8 header */
  29005. }
  29006. else {
  29007. curve_id = wc_ecc_get_oid(algId, NULL, NULL);
  29008. }
  29009. #endif
  29010. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29011. if (ret == 0) {
  29012. /* Get the version and set the expected OID type. */
  29013. GetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], &version);
  29014. GetASN_OID(&dataASN[ECCKEYASN_IDX_CURVEID], oidCurveType);
  29015. /* Decode the private ECC key. */
  29016. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29017. inOutIdx, inSz);
  29018. }
  29019. /* Only version 1 supported. */
  29020. if ((ret == 0) && (version != 1)) {
  29021. ret = ASN_PARSE_E;
  29022. }
  29023. /* Curve Parameters are optional. */
  29024. if ((ret == 0) && (dataASN[ECCKEYASN_IDX_PARAMS].tag != 0)) {
  29025. if (dataASN[ECCKEYASN_IDX_CURVEID].tag != 0) {
  29026. /* Named curve - check and get id. */
  29027. curve_id = CheckCurve(dataASN[ECCKEYASN_IDX_CURVEID].data.oid.sum);
  29028. if (curve_id < 0) {
  29029. ret = ECC_CURVE_OID_E;
  29030. }
  29031. }
  29032. else {
  29033. #ifdef WOLFSSL_CUSTOM_CURVES
  29034. /* Parse explicit parameters. */
  29035. ret = EccSpecifiedECDomainDecode(
  29036. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.data,
  29037. dataASN[ECCKEYASN_IDX_CURVEPARAMS].data.ref.length, key);
  29038. #else
  29039. /* Explicit parameters not supported in build configuration. */
  29040. ret = ASN_PARSE_E;
  29041. #endif
  29042. }
  29043. }
  29044. if (ret == 0) {
  29045. /* Import private key value and public point (may be NULL). */
  29046. ret = wc_ecc_import_private_key_ex(
  29047. dataASN[ECCKEYASN_IDX_PKEY].data.ref.data,
  29048. dataASN[ECCKEYASN_IDX_PKEY].data.ref.length,
  29049. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.data,
  29050. dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.ref.length,
  29051. key, curve_id);
  29052. }
  29053. FREE_ASNGETDATA(dataASN, key->heap);
  29054. return ret;
  29055. #endif
  29056. }
  29057. #ifdef WOLFSSL_CUSTOM_CURVES
  29058. #ifndef WOLFSSL_ASN_TEMPLATE
  29059. /* returns 0 on success */
  29060. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  29061. word32 inSz, void* heap, int heapType)
  29062. {
  29063. int len;
  29064. int i;
  29065. char* str;
  29066. word32 localIdx;
  29067. byte tag;
  29068. if (*inOutIdx >= inSz) {
  29069. return BUFFER_E;
  29070. }
  29071. localIdx = *inOutIdx;
  29072. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  29073. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  29074. return ASN_PARSE_E;
  29075. }
  29076. else {
  29077. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  29078. return ASN_PARSE_E;
  29079. }
  29080. str = (char*)XMALLOC((size_t)len * 2 + 1, heap, heapType);
  29081. if (str == NULL) {
  29082. return MEMORY_E;
  29083. }
  29084. for (i=0; i<len; i++)
  29085. ByteToHexStr(input[*inOutIdx + (word32)i], str + i*2);
  29086. str[len*2] = '\0';
  29087. *inOutIdx += (word32)len;
  29088. *out = str;
  29089. (void)heap;
  29090. (void)heapType;
  29091. return 0;
  29092. }
  29093. static int EccKeyParamCopy(char** dst, char* src)
  29094. {
  29095. int ret = 0;
  29096. #ifdef WOLFSSL_ECC_CURVE_STATIC
  29097. word32 length;
  29098. #endif
  29099. if (dst == NULL || src == NULL)
  29100. return BAD_FUNC_ARG;
  29101. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29102. *dst = src;
  29103. #else
  29104. length = (int)XSTRLEN(src) + 1;
  29105. if (length > MAX_ECC_STRING) {
  29106. WOLFSSL_MSG("ECC Param too large for buffer");
  29107. ret = BUFFER_E;
  29108. }
  29109. else {
  29110. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  29111. }
  29112. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29113. #endif
  29114. return ret;
  29115. }
  29116. #endif /* !WOLFSSL_ASN_TEMPLATE */
  29117. #endif /* WOLFSSL_CUSTOM_CURVES */
  29118. WOLFSSL_ABI
  29119. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  29120. ecc_key* key, word32 inSz)
  29121. {
  29122. #ifndef WOLFSSL_ASN_TEMPLATE
  29123. int ret;
  29124. int version, length;
  29125. int curve_id = ECC_CURVE_DEF;
  29126. word32 oidSum, localIdx;
  29127. byte tag, isPrivFormat = 0;
  29128. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  29129. return BAD_FUNC_ARG;
  29130. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29131. return ASN_PARSE_E;
  29132. /* Check if ECC private key is being used and skip private portion */
  29133. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  29134. isPrivFormat = 1;
  29135. /* Type private key */
  29136. if (*inOutIdx >= inSz)
  29137. return ASN_PARSE_E;
  29138. tag = input[*inOutIdx];
  29139. *inOutIdx += 1;
  29140. if (tag != 4 && tag != 6 && tag != 7)
  29141. return ASN_PARSE_E;
  29142. /* Skip Private Key */
  29143. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  29144. return ASN_PARSE_E;
  29145. if (length > ECC_MAXSIZE)
  29146. return BUFFER_E;
  29147. *inOutIdx += (word32)length;
  29148. /* Private Curve Header */
  29149. if (*inOutIdx >= inSz)
  29150. return ASN_PARSE_E;
  29151. tag = input[*inOutIdx];
  29152. *inOutIdx += 1;
  29153. if (tag != ECC_PREFIX_0)
  29154. return ASN_ECC_KEY_E;
  29155. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29156. return ASN_PARSE_E;
  29157. }
  29158. /* Standard ECC public key */
  29159. else {
  29160. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29161. return ASN_PARSE_E;
  29162. ret = SkipObjectId(input, inOutIdx, inSz);
  29163. if (ret != 0)
  29164. return ret;
  29165. }
  29166. if (*inOutIdx >= inSz) {
  29167. return BUFFER_E;
  29168. }
  29169. localIdx = *inOutIdx;
  29170. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  29171. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  29172. #ifdef WOLFSSL_CUSTOM_CURVES
  29173. ecc_set_type* curve;
  29174. int len;
  29175. char* point = NULL;
  29176. ret = 0;
  29177. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  29178. DYNAMIC_TYPE_ECC_BUFFER);
  29179. if (curve == NULL)
  29180. ret = MEMORY_E;
  29181. if (ret == 0) {
  29182. static const char customName[] = "Custom";
  29183. XMEMSET(curve, 0, sizeof(*curve));
  29184. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29185. curve->name = customName;
  29186. #else
  29187. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  29188. #endif
  29189. curve->id = ECC_CURVE_CUSTOM;
  29190. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29191. ret = ASN_PARSE_E;
  29192. }
  29193. if (ret == 0) {
  29194. GetInteger7Bit(input, inOutIdx, inSz);
  29195. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29196. ret = ASN_PARSE_E;
  29197. }
  29198. if (ret == 0) {
  29199. char* p = NULL;
  29200. SkipObjectId(input, inOutIdx, inSz);
  29201. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  29202. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29203. if (ret == 0) {
  29204. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29205. ret = EccKeyParamCopy((char**)&curve->prime, p);
  29206. #else
  29207. const char *_tmp_ptr = &curve->prime[0];
  29208. ret = EccKeyParamCopy((char**)&_tmp_ptr, p);
  29209. #endif
  29210. }
  29211. }
  29212. if (ret == 0) {
  29213. curve->size = (int)XSTRLEN(curve->prime) / 2;
  29214. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  29215. ret = ASN_PARSE_E;
  29216. }
  29217. if (ret == 0) {
  29218. char* af = NULL;
  29219. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  29220. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29221. if (ret == 0) {
  29222. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29223. ret = EccKeyParamCopy((char**)&curve->Af, af);
  29224. #else
  29225. const char *_tmp_ptr = &curve->Af[0];
  29226. ret = EccKeyParamCopy((char**)&_tmp_ptr, af);
  29227. #endif
  29228. }
  29229. }
  29230. if (ret == 0) {
  29231. char* bf = NULL;
  29232. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  29233. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29234. if (ret == 0) {
  29235. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29236. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  29237. #else
  29238. const char *_tmp_ptr = &curve->Bf[0];
  29239. ret = EccKeyParamCopy((char**)&_tmp_ptr, bf);
  29240. #endif
  29241. }
  29242. }
  29243. if (ret == 0) {
  29244. localIdx = *inOutIdx;
  29245. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  29246. == 0 && tag == ASN_BIT_STRING) {
  29247. len = 0;
  29248. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  29249. if (ret > 0)
  29250. ret = 0; /* reset on success */
  29251. *inOutIdx += (word32)len;
  29252. }
  29253. }
  29254. if (ret == 0) {
  29255. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  29256. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29257. /* sanity check that point buffer is not smaller than the expected
  29258. * size to hold ( 0 4 || Gx || Gy )
  29259. * where Gx and Gy are each the size of curve->size * 2 */
  29260. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  29261. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29262. ret = BUFFER_E;
  29263. }
  29264. }
  29265. if (ret == 0) {
  29266. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29267. curve->Gx = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29268. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29269. curve->Gy = (const char*)XMALLOC((size_t)curve->size * 2 + 2,
  29270. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29271. if (curve->Gx == NULL || curve->Gy == NULL) {
  29272. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29273. ret = MEMORY_E;
  29274. }
  29275. #else
  29276. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  29277. WOLFSSL_MSG("curve size is too large to fit in buffer");
  29278. ret = BUFFER_E;
  29279. }
  29280. #endif
  29281. }
  29282. if (ret == 0) {
  29283. char* o = NULL;
  29284. XMEMCPY((char*)curve->Gx, point + 2, (size_t)curve->size * 2);
  29285. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  29286. (size_t)curve->size * 2);
  29287. ((char*)curve->Gx)[curve->size * 2] = '\0';
  29288. ((char*)curve->Gy)[curve->size * 2] = '\0';
  29289. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29290. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  29291. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  29292. if (ret == 0) {
  29293. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29294. ret = EccKeyParamCopy((char**)&curve->order, o);
  29295. #else
  29296. const char *_tmp_ptr = &curve->order[0];
  29297. ret = EccKeyParamCopy((char**)&_tmp_ptr, o);
  29298. #endif
  29299. }
  29300. }
  29301. if (ret == 0) {
  29302. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  29303. #ifndef WOLFSSL_ECC_CURVE_STATIC
  29304. curve->oid = NULL;
  29305. #else
  29306. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  29307. #endif
  29308. curve->oidSz = 0;
  29309. curve->oidSum = 0;
  29310. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  29311. ret = ASN_PARSE_E;
  29312. }
  29313. key->deallocSet = 1;
  29314. curve = NULL;
  29315. }
  29316. if (curve != NULL)
  29317. wc_ecc_free_curve(curve, key->heap);
  29318. if (ret < 0)
  29319. return ret;
  29320. #else
  29321. return ASN_PARSE_E;
  29322. #endif /* WOLFSSL_CUSTOM_CURVES */
  29323. }
  29324. else {
  29325. /* ecc params information */
  29326. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  29327. if (ret != 0)
  29328. return ret;
  29329. /* get curve id */
  29330. if ((ret = CheckCurve(oidSum)) < 0)
  29331. return ECC_CURVE_OID_E;
  29332. else {
  29333. curve_id = ret;
  29334. }
  29335. }
  29336. if (isPrivFormat) {
  29337. /* Public Curve Header - skip */
  29338. if (*inOutIdx >= inSz)
  29339. return ASN_PARSE_E;
  29340. tag = input[*inOutIdx];
  29341. *inOutIdx += 1;
  29342. if (tag != ECC_PREFIX_1)
  29343. return ASN_ECC_KEY_E;
  29344. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  29345. return ASN_PARSE_E;
  29346. }
  29347. /* key header */
  29348. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  29349. if (ret != 0)
  29350. return ret;
  29351. /* This is the raw point data compressed or uncompressed. */
  29352. if (wc_ecc_import_x963_ex(input + *inOutIdx, (word32)length, key,
  29353. curve_id) != 0) {
  29354. return ASN_ECC_KEY_E;
  29355. }
  29356. *inOutIdx += (word32)length;
  29357. return 0;
  29358. #else
  29359. /* eccKeyASN is longer than eccPublicKeyASN. */
  29360. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  29361. int ret = 0;
  29362. int curve_id = ECC_CURVE_DEF;
  29363. int oidIdx = ECCPUBLICKEYASN_IDX_ALGOID_CURVEID;
  29364. #ifdef WOLFSSL_CUSTOM_CURVES
  29365. int specIdx = ECCPUBLICKEYASN_IDX_ALGOID_PARAMS;
  29366. #endif
  29367. int pubIdx = ECCPUBLICKEYASN_IDX_PUBKEY;
  29368. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  29369. ret = BAD_FUNC_ARG;
  29370. }
  29371. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29372. if (ret == 0) {
  29373. /* Clear dynamic data for ECC public key. */
  29374. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  29375. #if !defined(WOLFSSL_SM2) || !defined(WOLFSSL_SM3)
  29376. /* Set required ECDSA OID and ignore the curve OID type. */
  29377. GetASN_ExpBuffer(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], keyEcdsaOid,
  29378. sizeof(keyEcdsaOid));
  29379. #else
  29380. GetASN_OID(&dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID], oidKeyType);
  29381. #endif
  29382. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  29383. /* Decode the public ECC key. */
  29384. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  29385. input, inOutIdx, inSz);
  29386. if (ret != 0) {
  29387. oidIdx = ECCKEYASN_IDX_CURVEID;
  29388. #ifdef WOLFSSL_CUSTOM_CURVES
  29389. specIdx = ECCKEYASN_IDX_CURVEPARAMS;
  29390. #endif
  29391. pubIdx = ECCKEYASN_IDX_PUBKEY_VAL;
  29392. /* Clear dynamic data for ECC private key. */
  29393. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  29394. /* Check named curve OID type. */
  29395. GetASN_OID(&dataASN[oidIdx], oidCurveType);
  29396. /* Try private key format .*/
  29397. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  29398. inOutIdx, inSz);
  29399. if (ret != 0) {
  29400. ret = ASN_PARSE_E;
  29401. }
  29402. }
  29403. }
  29404. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  29405. if ((ret == 0) && (oidIdx == ECCPUBLICKEYASN_IDX_ALGOID_CURVEID)) {
  29406. int oidSum = dataASN[ECCPUBLICKEYASN_IDX_ALGOID_OID].data.oid.sum;
  29407. if ((oidSum != ECDSAk) && (oidSum != SM2k)) {
  29408. ret = ASN_PARSE_E;
  29409. }
  29410. }
  29411. #endif
  29412. if (ret == 0) {
  29413. if (dataASN[oidIdx].tag != 0) {
  29414. /* Named curve - check and get id. */
  29415. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  29416. if (curve_id < 0) {
  29417. ret = ASN_OBJECT_ID_E;
  29418. }
  29419. }
  29420. else {
  29421. #ifdef WOLFSSL_CUSTOM_CURVES
  29422. /* Parse explicit parameters. */
  29423. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  29424. dataASN[specIdx].data.ref.length, key);
  29425. #else
  29426. /* Explicit parameters not supported in build configuration. */
  29427. ret = ASN_PARSE_E;
  29428. #endif
  29429. }
  29430. }
  29431. if (ret == 0) {
  29432. /* Import public point. */
  29433. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  29434. dataASN[pubIdx].data.ref.length, key, curve_id);
  29435. if (ret != 0) {
  29436. ret = ASN_ECC_KEY_E;
  29437. }
  29438. }
  29439. FREE_ASNGETDATA(dataASN, key->heap);
  29440. return ret;
  29441. #endif /* WOLFSSL_ASN_TEMPLATE */
  29442. }
  29443. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  29444. /* build DER formatted ECC key, include optional public key if requested,
  29445. * return length on success, negative on error */
  29446. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  29447. int pubIn, int curveIn)
  29448. {
  29449. #ifndef WOLFSSL_ASN_TEMPLATE
  29450. byte curve[MAX_ALGO_SZ+2];
  29451. byte ver[MAX_VERSION_SZ];
  29452. byte seq[MAX_SEQ_SZ];
  29453. int ret, curveSz, verSz;
  29454. word32 totalSz;
  29455. int privHdrSz = ASN_ECC_HEADER_SZ;
  29456. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  29457. #ifdef WOLFSSL_NO_MALLOC
  29458. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29459. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  29460. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  29461. #else
  29462. byte *prv = NULL, *pub = NULL;
  29463. #endif
  29464. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  29465. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  29466. if (key == NULL || (output == NULL && inLen == NULL))
  29467. return BAD_FUNC_ARG;
  29468. if (curveIn) {
  29469. /* curve */
  29470. curve[curveidx++] = ECC_PREFIX_0;
  29471. curveidx++ /* to put the size after computation */;
  29472. curveSz = SetCurve(key, curve+curveidx, MAX_ALGO_SZ);
  29473. if (curveSz < 0)
  29474. return curveSz;
  29475. /* set computed size */
  29476. curve[1] = (byte)curveSz;
  29477. curveidx += (word32)curveSz;
  29478. }
  29479. /* private */
  29480. privSz = (word32)key->dp->size;
  29481. #ifdef WOLFSSL_QNX_CAAM
  29482. /* check if is a black key, and add MAC size if needed */
  29483. if (key->blackKey > 0 && key->blackKey != CAAM_BLACK_KEY_ECB) {
  29484. privSz = privSz + WC_CAAM_MAC_SZ;
  29485. }
  29486. #endif
  29487. #ifndef WOLFSSL_NO_MALLOC
  29488. prv = (byte*)XMALLOC(privSz + (word32)privHdrSz + MAX_SEQ_SZ,
  29489. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29490. if (prv == NULL) {
  29491. return MEMORY_E;
  29492. }
  29493. #else
  29494. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  29495. return BUFFER_E;
  29496. }
  29497. #endif
  29498. if (privSz < ASN_LONG_LENGTH) {
  29499. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  29500. }
  29501. else {
  29502. prvidx += SetOctetString(privSz, &prv[prvidx]);
  29503. }
  29504. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  29505. if (ret < 0) {
  29506. #ifndef WOLFSSL_NO_MALLOC
  29507. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29508. #endif
  29509. return ret;
  29510. }
  29511. prvidx += privSz;
  29512. /* pubIn */
  29513. if (pubIn) {
  29514. PRIVATE_KEY_UNLOCK();
  29515. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29516. PRIVATE_KEY_LOCK();
  29517. if (ret != LENGTH_ONLY_E) {
  29518. #ifndef WOLFSSL_NO_MALLOC
  29519. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29520. #endif
  29521. return ret;
  29522. }
  29523. #ifndef WOLFSSL_NO_MALLOC
  29524. pub = (byte*)XMALLOC(pubSz + (word32)pubHdrSz + MAX_SEQ_SZ,
  29525. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29526. if (pub == NULL) {
  29527. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29528. return MEMORY_E;
  29529. }
  29530. #else
  29531. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  29532. return BUFFER_E;
  29533. }
  29534. #endif
  29535. pub[pubidx++] = ECC_PREFIX_1;
  29536. if (pubSz > 128) /* leading zero + extra size byte */
  29537. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  29538. else /* leading zero */
  29539. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  29540. /* SetBitString adds leading zero */
  29541. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  29542. PRIVATE_KEY_UNLOCK();
  29543. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  29544. PRIVATE_KEY_LOCK();
  29545. if (ret != 0) {
  29546. #ifndef WOLFSSL_NO_MALLOC
  29547. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29548. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29549. #endif
  29550. return ret;
  29551. }
  29552. pubidx += pubSz;
  29553. }
  29554. /* make headers */
  29555. verSz = SetMyVersion(1, ver, FALSE);
  29556. seqSz = SetSequence((word32)verSz + prvidx + pubidx + curveidx, seq);
  29557. totalSz = prvidx + pubidx + curveidx + (word32)verSz + seqSz;
  29558. if (output == NULL) {
  29559. *inLen = totalSz;
  29560. #ifndef WOLFSSL_NO_MALLOC
  29561. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29562. if (pubIn) {
  29563. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29564. }
  29565. #endif
  29566. return LENGTH_ONLY_E;
  29567. }
  29568. if (inLen != NULL && totalSz > *inLen) {
  29569. #ifndef WOLFSSL_NO_MALLOC
  29570. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29571. if (pubIn) {
  29572. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29573. }
  29574. #endif
  29575. return BAD_FUNC_ARG;
  29576. }
  29577. /* write out */
  29578. /* seq */
  29579. XMEMCPY(output + idx, seq, seqSz);
  29580. idx = seqSz;
  29581. /* ver */
  29582. XMEMCPY(output + idx, ver, (size_t)verSz);
  29583. idx += (word32)verSz;
  29584. /* private */
  29585. XMEMCPY(output + idx, prv, prvidx);
  29586. idx += prvidx;
  29587. #ifndef WOLFSSL_NO_MALLOC
  29588. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29589. #endif
  29590. /* curve */
  29591. XMEMCPY(output + idx, curve, curveidx);
  29592. idx += curveidx;
  29593. /* pubIn */
  29594. if (pubIn) {
  29595. XMEMCPY(output + idx, pub, pubidx);
  29596. /* idx += pubidx; not used after write, if more data remove comment */
  29597. #ifndef WOLFSSL_NO_MALLOC
  29598. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29599. #endif
  29600. }
  29601. return (int)totalSz;
  29602. #else
  29603. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  29604. word32 privSz, pubSz;
  29605. int sz = 0;
  29606. int ret = 0;
  29607. int curveIdSz = 0;
  29608. /* Check validity of parameters. */
  29609. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  29610. ret = BAD_FUNC_ARG;
  29611. }
  29612. /* Check key has parameters when encoding curve. */
  29613. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  29614. ret = BAD_FUNC_ARG;
  29615. }
  29616. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  29617. if (ret == 0) {
  29618. /* Private key size is the curve size. */
  29619. privSz = (word32)key->dp->size;
  29620. if (pubIn) {
  29621. /* Get the length of the public key. */
  29622. PRIVATE_KEY_UNLOCK();
  29623. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  29624. PRIVATE_KEY_LOCK();
  29625. if (ret == LENGTH_ONLY_E)
  29626. ret = 0;
  29627. }
  29628. }
  29629. if (ret == 0) {
  29630. /* Version: 1 */
  29631. SetASN_Int8Bit(&dataASN[ECCKEYASN_IDX_VER], 1);
  29632. /* Leave space for private key. */
  29633. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PKEY], NULL, privSz);
  29634. if (curveIn) {
  29635. /* Get length of the named curve OID to put into the encoding. */
  29636. curveIdSz = SetCurve(key, NULL, 0);
  29637. if (curveIdSz < 0) {
  29638. ret = curveIdSz;
  29639. }
  29640. /* Curve OID */
  29641. SetASN_ReplaceBuffer(&dataASN[ECCKEYASN_IDX_CURVEID], NULL,
  29642. (word32)curveIdSz);
  29643. /* TODO: add support for SpecifiedECDomain curve. */
  29644. dataASN[ECCKEYASN_IDX_CURVEPARAMS].noOut = 1;
  29645. }
  29646. else {
  29647. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PARAMS,
  29648. eccKeyASN_Length);
  29649. }
  29650. if (ret == 0) {
  29651. if (pubIn) {
  29652. /* Leave space for public key. */
  29653. SetASN_Buffer(&dataASN[ECCKEYASN_IDX_PUBKEY_VAL], NULL, pubSz);
  29654. }
  29655. else {
  29656. /* Don't write out public key. */
  29657. SetASNItem_NoOutNode(dataASN, eccKeyASN, ECCKEYASN_IDX_PUBKEY,
  29658. eccKeyASN_Length);
  29659. }
  29660. /* Calculate size of the private key encoding. */
  29661. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  29662. }
  29663. }
  29664. /* Return the size if no buffer. */
  29665. if ((ret == 0) && (output == NULL)) {
  29666. *inLen = (word32)sz;
  29667. ret = LENGTH_ONLY_E;
  29668. }
  29669. /* Check the buffer is big enough. */
  29670. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  29671. ret = BAD_FUNC_ARG;
  29672. }
  29673. if ((ret == 0) && (output != NULL)) {
  29674. /* Encode the private key. */
  29675. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  29676. if (curveIn) {
  29677. /* Put named curve OID data into encoding. */
  29678. curveIdSz = SetCurve(key,
  29679. (byte*)dataASN[ECCKEYASN_IDX_CURVEID].data.buffer.data,
  29680. (size_t)curveIdSz);
  29681. if (curveIdSz < 0) {
  29682. ret = curveIdSz;
  29683. }
  29684. }
  29685. if (ret == 0) {
  29686. /* Export the private value into the buffer. */
  29687. ret = wc_ecc_export_private_only(key,
  29688. (byte*)dataASN[ECCKEYASN_IDX_PKEY].data.buffer.data, &privSz);
  29689. }
  29690. if ((ret == 0) && pubIn) {
  29691. /* Export the public point into the buffer. */
  29692. PRIVATE_KEY_UNLOCK();
  29693. ret = wc_ecc_export_x963(key,
  29694. (byte*)dataASN[ECCKEYASN_IDX_PUBKEY_VAL].data.buffer.data,
  29695. &pubSz);
  29696. PRIVATE_KEY_LOCK();
  29697. }
  29698. }
  29699. if (ret == 0) {
  29700. /* Return the encoding size. */
  29701. ret = sz;
  29702. }
  29703. FREE_ASNSETDATA(dataASN, key->heap);
  29704. return ret;
  29705. #endif
  29706. }
  29707. /* Write a Private ecc key, including public to DER format,
  29708. * length on success else < 0 */
  29709. WOLFSSL_ABI
  29710. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29711. {
  29712. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  29713. }
  29714. /* Write only private ecc key to DER format,
  29715. * length on success else < 0 */
  29716. int wc_EccKeyDerSize(ecc_key* key, int pub)
  29717. {
  29718. word32 sz = 0;
  29719. int ret;
  29720. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  29721. if (ret != LENGTH_ONLY_E) {
  29722. return ret;
  29723. }
  29724. return (int)sz;
  29725. }
  29726. /* Write only private ecc key to DER format,
  29727. * length on success else < 0 */
  29728. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  29729. {
  29730. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  29731. }
  29732. #ifdef HAVE_PKCS8
  29733. /* Write only private ecc key or both private and public parts to unencrypted
  29734. * PKCS#8 format.
  29735. *
  29736. * If output is NULL, places required PKCS#8 buffer size in outLen and
  29737. * returns LENGTH_ONLY_E.
  29738. *
  29739. * return length on success else < 0 */
  29740. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  29741. int includePublic)
  29742. {
  29743. int ret;
  29744. word32 tmpDerSz;
  29745. int algoID = 0;
  29746. word32 oidSz = 0;
  29747. word32 pkcs8Sz = 0;
  29748. const byte* curveOID = NULL;
  29749. #ifdef WOLFSSL_NO_MALLOC
  29750. byte tmpDer[ECC_BUFSIZE];
  29751. #else
  29752. byte* tmpDer = NULL;
  29753. #endif
  29754. word32 sz = ECC_BUFSIZE;
  29755. if (key == NULL || key->dp == NULL || outLen == NULL)
  29756. return BAD_FUNC_ARG;
  29757. /* set algoID, get curve OID */
  29758. algoID = ECDSAk;
  29759. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  29760. if (ret < 0)
  29761. return ret;
  29762. #ifndef WOLFSSL_NO_MALLOC
  29763. /* temp buffer for plain DER key */
  29764. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29765. if (tmpDer == NULL)
  29766. return MEMORY_E;
  29767. #endif
  29768. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  29769. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  29770. if (ret < 0) {
  29771. #ifndef WOLFSSL_NO_MALLOC
  29772. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29773. #endif
  29774. return ret;
  29775. }
  29776. tmpDerSz = (word32)ret;
  29777. /* get pkcs8 expected output size */
  29778. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  29779. curveOID, oidSz);
  29780. if (ret != LENGTH_ONLY_E) {
  29781. #ifndef WOLFSSL_NO_MALLOC
  29782. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29783. #endif
  29784. return ret;
  29785. }
  29786. if (output == NULL) {
  29787. #ifndef WOLFSSL_NO_MALLOC
  29788. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29789. #endif
  29790. *outLen = pkcs8Sz;
  29791. return LENGTH_ONLY_E;
  29792. }
  29793. else if (*outLen < pkcs8Sz) {
  29794. #ifndef WOLFSSL_NO_MALLOC
  29795. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29796. #endif
  29797. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  29798. return BUFFER_E;
  29799. }
  29800. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  29801. algoID, curveOID, oidSz);
  29802. if (ret < 0) {
  29803. #ifndef WOLFSSL_NO_MALLOC
  29804. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29805. #endif
  29806. return ret;
  29807. }
  29808. #ifndef WOLFSSL_NO_MALLOC
  29809. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  29810. #endif
  29811. *outLen = (word32)ret;
  29812. return ret;
  29813. }
  29814. /* Write only private ecc key to unencrypted PKCS#8 format.
  29815. *
  29816. * return length on success else < 0 */
  29817. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  29818. {
  29819. return eccToPKCS8(key, output, outLen, 0);
  29820. }
  29821. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  29822. *
  29823. * return length on success else < 0 */
  29824. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  29825. word32* outLen)
  29826. {
  29827. return eccToPKCS8(key, output, outLen, 1);
  29828. }
  29829. #endif /* HAVE_PKCS8 */
  29830. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  29831. #endif /* HAVE_ECC */
  29832. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  29833. #ifdef WOLFSSL_ASN_TEMPLATE
  29834. /* ASN.1 template for Ed25519 and Ed448 private key.
  29835. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  29836. */
  29837. static const ASNItem edKeyASN[] = {
  29838. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  29839. /* Version */
  29840. /* VER */ { 1, ASN_INTEGER, 0, 0, 0 },
  29841. /* privateKeyAlgorithm */
  29842. /* PKEYALGO_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  29843. /* PKEYALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  29844. /* privateKey */
  29845. /* PKEY */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  29846. /* CurvePrivateKey */
  29847. /* PKEY_CURVEPKEY */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  29848. /* attributes */
  29849. /* ATTRS */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_ATTRS, 1, 1, 1 },
  29850. /* publicKey */
  29851. /* PUBKEY */ { 1, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY, 0, 0, 1 },
  29852. };
  29853. enum {
  29854. EDKEYASN_IDX_SEQ = 0,
  29855. EDKEYASN_IDX_VER,
  29856. EDKEYASN_IDX_PKEYALGO_SEQ,
  29857. EDKEYASN_IDX_PKEYALGO_OID,
  29858. EDKEYASN_IDX_PKEY,
  29859. EDKEYASN_IDX_PKEY_CURVEPKEY,
  29860. EDKEYASN_IDX_ATTRS,
  29861. EDKEYASN_IDX_PUBKEY
  29862. };
  29863. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  29864. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  29865. #endif
  29866. #if ((defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)) \
  29867. || (defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)) \
  29868. || (defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)) \
  29869. || (defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)) \
  29870. || (defined(HAVE_PQC) && defined(HAVE_FALCON)) \
  29871. || (defined(HAVE_PQC) && defined(HAVE_DILITHIUM)) \
  29872. || (defined(HAVE_PQC) && defined(HAVE_SPHINCS)))
  29873. int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  29874. byte* privKey, word32* privKeyLen,
  29875. byte* pubKey, word32* pubKeyLen, int keyType)
  29876. {
  29877. #ifndef WOLFSSL_ASN_TEMPLATE
  29878. word32 oid;
  29879. int version, length, endKeyIdx, privSz, pubSz;
  29880. const byte* priv;
  29881. const byte* pub;
  29882. #else
  29883. int ret = 0;
  29884. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  29885. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  29886. #endif
  29887. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  29888. privKey == NULL || privKeyLen == NULL) {
  29889. return BAD_FUNC_ARG;
  29890. }
  29891. #ifndef WOLFSSL_ASN_TEMPLATE
  29892. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  29893. endKeyIdx = (int)*inOutIdx + length;
  29894. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  29895. return ASN_PARSE_E;
  29896. if (version != 0) {
  29897. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  29898. return ASN_PARSE_E;
  29899. }
  29900. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  29901. return ASN_PARSE_E;
  29902. if (oid != (word32)keyType)
  29903. return ASN_PARSE_E;
  29904. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  29905. return ASN_PARSE_E;
  29906. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29907. return ASN_PARSE_E;
  29908. priv = input + *inOutIdx;
  29909. *inOutIdx += (word32)privSz;
  29910. }
  29911. else {
  29912. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  29913. return ASN_PARSE_E;
  29914. priv = input + *inOutIdx;
  29915. *inOutIdx += (word32)privSz;
  29916. endKeyIdx = (int)*inOutIdx;
  29917. }
  29918. if ((word32)privSz > *privKeyLen)
  29919. return BUFFER_E;
  29920. if (endKeyIdx == (int)*inOutIdx) {
  29921. *privKeyLen = (word32)privSz;
  29922. XMEMCPY(privKey, priv, *privKeyLen);
  29923. if (pubKeyLen != NULL)
  29924. *pubKeyLen = 0;
  29925. }
  29926. else {
  29927. if (pubKeyLen == NULL) {
  29928. return BAD_FUNC_ARG;
  29929. }
  29930. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY | 1,
  29931. inOutIdx, &pubSz, inSz) < 0) {
  29932. return ASN_PARSE_E;
  29933. }
  29934. if ((word32)pubSz > *pubKeyLen)
  29935. return BUFFER_E;
  29936. pub = input + *inOutIdx;
  29937. *inOutIdx += (word32)pubSz;
  29938. *privKeyLen = (word32)privSz;
  29939. XMEMCPY(privKey, priv, *privKeyLen);
  29940. *pubKeyLen = (word32)pubSz;
  29941. if (pubKey != NULL)
  29942. XMEMCPY(pubKey, pub, *pubKeyLen);
  29943. }
  29944. if (endKeyIdx != (int)*inOutIdx)
  29945. return ASN_PARSE_E;
  29946. return 0;
  29947. #else
  29948. if (ret == 0) {
  29949. /* Require OID. */
  29950. word32 oidSz;
  29951. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  29952. GetASN_ExpBuffer(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], oid, oidSz);
  29953. /* Parse full private key. */
  29954. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  29955. inOutIdx, inSz);
  29956. if (ret != 0) {
  29957. /* Parse just the OCTET_STRING. */
  29958. ret = GetASN_Items(&edKeyASN[EDKEYASN_IDX_PKEY_CURVEPKEY],
  29959. &dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], 1, 0, input,
  29960. inOutIdx, inSz);
  29961. if (ret != 0) {
  29962. ret = ASN_PARSE_E;
  29963. }
  29964. }
  29965. }
  29966. /* Check the private value length is correct. */
  29967. if ((ret == 0) && dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length
  29968. > *privKeyLen) {
  29969. ret = ASN_PARSE_E;
  29970. }
  29971. if ((ret == 0) && dataASN[EDKEYASN_IDX_PUBKEY].tag == 0) {
  29972. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29973. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29974. *privKeyLen);
  29975. if (pubKeyLen != NULL)
  29976. *pubKeyLen = 0;
  29977. }
  29978. else if ((ret == 0) &&
  29979. (pubKeyLen != NULL) &&
  29980. (dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  29981. ret = ASN_PARSE_E;
  29982. }
  29983. else if (ret == 0) {
  29984. /* Import private and public value. */
  29985. *privKeyLen = dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.length;
  29986. XMEMCPY(privKey, dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.ref.data,
  29987. *privKeyLen);
  29988. if (pubKeyLen != NULL)
  29989. *pubKeyLen = dataASN[EDKEYASN_IDX_PUBKEY].data.ref.length;
  29990. if (pubKey != NULL && pubKeyLen != NULL)
  29991. XMEMCPY(pubKey, dataASN[EDKEYASN_IDX_PUBKEY].data.ref.data,
  29992. *pubKeyLen);
  29993. }
  29994. FREE_ASNGETDATA(dataASN, NULL);
  29995. return ret;
  29996. #endif /* WOLFSSL_ASN_TEMPLATE */
  29997. }
  29998. int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  29999. byte* pubKey, word32* pubKeyLen, int keyType)
  30000. {
  30001. int ret = 0;
  30002. #ifndef WOLFSSL_ASN_TEMPLATE
  30003. int length;
  30004. word32 oid;
  30005. #else
  30006. word32 len;
  30007. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  30008. #endif
  30009. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  30010. pubKey == NULL || pubKeyLen == NULL) {
  30011. return BAD_FUNC_ARG;
  30012. }
  30013. #ifndef WOLFSSL_ASN_TEMPLATE
  30014. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30015. return ASN_PARSE_E;
  30016. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  30017. return ASN_PARSE_E;
  30018. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  30019. return ASN_PARSE_E;
  30020. if (oid != (word32)keyType)
  30021. return ASN_PARSE_E;
  30022. /* key header */
  30023. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  30024. if (ret != 0)
  30025. return ret;
  30026. /* check that the value found is not too large for pubKey buffer */
  30027. if ((word32)length > *pubKeyLen)
  30028. return ASN_PARSE_E;
  30029. /* check that input buffer is exhausted */
  30030. if (*inOutIdx + (word32)length != inSz)
  30031. return ASN_PARSE_E;
  30032. /* This is the raw point data compressed or uncompressed. */
  30033. *pubKeyLen = (word32)length;
  30034. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  30035. #else
  30036. len = inSz - *inOutIdx;
  30037. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  30038. if (ret == 0) {
  30039. /* Require OID. */
  30040. word32 oidSz;
  30041. const byte* oid = OidFromId((word32)keyType, oidKeyType, &oidSz);
  30042. GetASN_ExpBuffer(&dataASN[EDPUBKEYASN_IDX_ALGOID_OID], oid, oidSz);
  30043. /* Decode Ed25519 private key. */
  30044. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  30045. inOutIdx, inSz);
  30046. if (ret != 0)
  30047. ret = ASN_PARSE_E;
  30048. /* check that input buffer is exhausted */
  30049. if (*inOutIdx != inSz)
  30050. ret = ASN_PARSE_E;
  30051. }
  30052. /* Check the public value length is correct. */
  30053. if ((ret == 0) &&
  30054. (dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length > *pubKeyLen)) {
  30055. ret = ASN_PARSE_E;
  30056. }
  30057. /* Check that the all the buffer was used. */
  30058. if ((ret == 0) &&
  30059. (GetASNItem_Length(dataASN[EDPUBKEYASN_IDX_SEQ], input) != len)) {
  30060. ret = ASN_PARSE_E;
  30061. }
  30062. if (ret == 0) {
  30063. *pubKeyLen = dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.length;
  30064. XMEMCPY(pubKey, dataASN[EDPUBKEYASN_IDX_PUBKEY].data.ref.data,
  30065. *pubKeyLen);
  30066. }
  30067. FREE_ASNGETDATA(dataASN, NULL);
  30068. #endif /* WOLFSSL_ASN_TEMPLATE */
  30069. return ret;
  30070. }
  30071. #endif
  30072. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  30073. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  30074. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30075. ed25519_key* key, word32 inSz)
  30076. {
  30077. int ret;
  30078. byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
  30079. word32 privKeyLen = (word32)sizeof(privKey);
  30080. word32 pubKeyLen = (word32)sizeof(pubKey);
  30081. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30082. return BAD_FUNC_ARG;
  30083. }
  30084. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30085. pubKey, &pubKeyLen, ED25519k);
  30086. if (ret == 0) {
  30087. if (pubKeyLen == 0) {
  30088. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  30089. }
  30090. else {
  30091. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  30092. pubKey, pubKeyLen, key);
  30093. }
  30094. }
  30095. return ret;
  30096. }
  30097. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  30098. ed25519_key* key, word32 inSz)
  30099. {
  30100. int ret;
  30101. byte pubKey[ED25519_PUB_KEY_SIZE];
  30102. word32 pubKeyLen = (word32)sizeof(pubKey);
  30103. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30104. return BAD_FUNC_ARG;
  30105. }
  30106. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30107. pubKey, &pubKeyLen, ED25519k);
  30108. if (ret == 0) {
  30109. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  30110. }
  30111. return ret;
  30112. }
  30113. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  30114. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  30115. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30116. curve25519_key* key, word32 inSz)
  30117. {
  30118. int ret;
  30119. byte privKey[CURVE25519_KEYSIZE];
  30120. word32 privKeyLen = CURVE25519_KEYSIZE;
  30121. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30122. return BAD_FUNC_ARG;
  30123. }
  30124. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30125. NULL, NULL, X25519k);
  30126. if (ret == 0) {
  30127. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  30128. }
  30129. return ret;
  30130. }
  30131. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  30132. curve25519_key* key, word32 inSz)
  30133. {
  30134. int ret;
  30135. byte pubKey[CURVE25519_KEYSIZE];
  30136. word32 pubKeyLen = (word32)sizeof(pubKey);
  30137. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30138. return BAD_FUNC_ARG;
  30139. }
  30140. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30141. pubKey, &pubKeyLen, X25519k);
  30142. if (ret == 0) {
  30143. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  30144. }
  30145. return ret;
  30146. }
  30147. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  30148. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  30149. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  30150. *
  30151. * Pass NULL for output to get the size of the encoding.
  30152. *
  30153. * @param [in] privKey private key buffer
  30154. * @param [in] privKeyLen private ket buffer length
  30155. * @param [in] pubKey public key buffer (optional)
  30156. * @param [in] pubKeyLen public ket buffer length
  30157. * @param [out] output Buffer to put encoded data in (optional)
  30158. * @param [in] outLen Size of buffer in bytes
  30159. * @param [in] keyType is "enum Key_Sum" like ED25519k
  30160. * @return Size of encoded data in bytes on success
  30161. * @return BAD_FUNC_ARG when key is NULL.
  30162. * @return MEMORY_E when dynamic memory allocation failed.
  30163. */
  30164. int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  30165. const byte* pubKey, word32 pubKeyLen,
  30166. byte* output, word32 outLen, int keyType)
  30167. {
  30168. int ret = 0;
  30169. #ifndef WOLFSSL_ASN_TEMPLATE
  30170. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  30171. #else
  30172. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  30173. int sz;
  30174. #endif
  30175. /* Validate parameters. */
  30176. if (privKey == NULL || outLen == 0) {
  30177. return BAD_FUNC_ARG;
  30178. }
  30179. #ifndef WOLFSSL_ASN_TEMPLATE
  30180. /* calculate size */
  30181. if (pubKey) {
  30182. pubSz = 2 + pubKeyLen;
  30183. }
  30184. privSz = 2 + 2 + privKeyLen;
  30185. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  30186. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  30187. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  30188. sz = seqSz + verSz + algoSz + privSz + pubSz;
  30189. /* checkout output size */
  30190. if (output != NULL && sz > outLen) {
  30191. ret = BAD_FUNC_ARG;
  30192. }
  30193. if (ret == 0 && output != NULL) {
  30194. /* write out */
  30195. /* seq */
  30196. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  30197. idx = seqSz;
  30198. /* ver */
  30199. SetMyVersion(0, output + idx, FALSE);
  30200. idx += verSz;
  30201. /* algo */
  30202. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  30203. idx += algoSz;
  30204. /* privKey */
  30205. idx += SetOctetString(2 + privKeyLen, output + idx);
  30206. idx += SetOctetString(privKeyLen, output + idx);
  30207. XMEMCPY(output + idx, privKey, privKeyLen);
  30208. idx += privKeyLen;
  30209. /* pubKey */
  30210. if (pubKey) {
  30211. idx += SetHeader(ASN_CONTEXT_SPECIFIC | ASN_ASYMKEY_PUBKEY |
  30212. 1, pubKeyLen, output + idx);
  30213. XMEMCPY(output + idx, pubKey, pubKeyLen);
  30214. idx += pubKeyLen;
  30215. }
  30216. sz = idx;
  30217. }
  30218. if (ret == 0) {
  30219. /* Return size of encoding. */
  30220. ret = (int)sz;
  30221. }
  30222. #else
  30223. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  30224. if (ret == 0) {
  30225. /* Set version = 0 */
  30226. SetASN_Int8Bit(&dataASN[EDKEYASN_IDX_VER], 0);
  30227. /* Set OID. */
  30228. SetASN_OID(&dataASN[EDKEYASN_IDX_PKEYALGO_OID], (word32)keyType,
  30229. oidKeyType);
  30230. /* Leave space for private key. */
  30231. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY], NULL, privKeyLen);
  30232. /* Don't write out attributes. */
  30233. dataASN[EDKEYASN_IDX_ATTRS].noOut = 1;
  30234. if (pubKey) {
  30235. /* Leave space for public key. */
  30236. SetASN_Buffer(&dataASN[EDKEYASN_IDX_PUBKEY], NULL, pubKeyLen);
  30237. }
  30238. else {
  30239. /* Don't put out public part. */
  30240. SetASNItem_NoOutNode(dataASN, edKeyASN, EDKEYASN_IDX_PUBKEY,
  30241. edKeyASN_Length);
  30242. }
  30243. /* Calculate the size of encoding. */
  30244. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  30245. }
  30246. /* Check buffer is big enough. */
  30247. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  30248. ret = BAD_FUNC_ARG;
  30249. }
  30250. if ((ret == 0) && (output != NULL)) {
  30251. /* Encode private key. */
  30252. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  30253. /* Put private value into space provided. */
  30254. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PKEY_CURVEPKEY].data.buffer.data,
  30255. privKey, privKeyLen);
  30256. if (pubKey != NULL) {
  30257. /* Put public value into space provided. */
  30258. XMEMCPY((byte*)dataASN[EDKEYASN_IDX_PUBKEY].data.buffer.data,
  30259. pubKey, pubKeyLen);
  30260. }
  30261. }
  30262. if (ret == 0) {
  30263. /* Return size of encoding. */
  30264. ret = sz;
  30265. }
  30266. FREE_ASNSETDATA(dataASN, NULL);
  30267. #endif
  30268. return ret;
  30269. }
  30270. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  30271. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  30272. /* Write a Private ED25519 key, including public to DER format,
  30273. * length on success else < 0 */
  30274. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30275. {
  30276. if (key == NULL) {
  30277. return BAD_FUNC_ARG;
  30278. }
  30279. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30280. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  30281. }
  30282. /* Write only private ED25519 key to DER format,
  30283. * length on success else < 0 */
  30284. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  30285. {
  30286. if (key == NULL) {
  30287. return BAD_FUNC_ARG;
  30288. }
  30289. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  30290. NULL, 0, output, inLen, ED25519k);
  30291. }
  30292. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  30293. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  30294. /* Write only private Curve25519 key to DER format,
  30295. * length on success else < 0 */
  30296. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  30297. {
  30298. int ret;
  30299. byte privKey[CURVE25519_KEYSIZE];
  30300. word32 privKeyLen = CURVE25519_KEYSIZE;
  30301. if (key == NULL) {
  30302. return BAD_FUNC_ARG;
  30303. }
  30304. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  30305. if (ret == 0) {
  30306. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30307. X25519k);
  30308. }
  30309. return ret;
  30310. }
  30311. /* Write a public Curve25519 key to DER format,
  30312. * length on success else < 0 */
  30313. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  30314. int withAlg)
  30315. {
  30316. int ret;
  30317. byte pubKey[CURVE25519_PUB_KEY_SIZE];
  30318. word32 pubKeyLen = (word32)sizeof(pubKey);
  30319. if (key == NULL || output == NULL) {
  30320. return BAD_FUNC_ARG;
  30321. }
  30322. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  30323. if (ret == 0) {
  30324. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30325. X25519k, withAlg);
  30326. }
  30327. return ret;
  30328. }
  30329. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  30330. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  30331. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30332. ed448_key* key, word32 inSz)
  30333. {
  30334. int ret;
  30335. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  30336. word32 privKeyLen = (word32)sizeof(privKey);
  30337. word32 pubKeyLen = (word32)sizeof(pubKey);
  30338. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30339. return BAD_FUNC_ARG;
  30340. }
  30341. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30342. pubKey, &pubKeyLen, ED448k);
  30343. if (ret == 0) {
  30344. if (pubKeyLen == 0) {
  30345. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  30346. }
  30347. else {
  30348. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  30349. pubKey, pubKeyLen, key);
  30350. }
  30351. }
  30352. return ret;
  30353. }
  30354. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30355. ed448_key* key, word32 inSz)
  30356. {
  30357. int ret;
  30358. byte pubKey[ED448_PUB_KEY_SIZE];
  30359. word32 pubKeyLen = (word32)sizeof(pubKey);
  30360. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30361. return BAD_FUNC_ARG;
  30362. }
  30363. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30364. pubKey, &pubKeyLen, ED448k);
  30365. if (ret == 0) {
  30366. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  30367. }
  30368. return ret;
  30369. }
  30370. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  30371. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  30372. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  30373. curve448_key* key, word32 inSz)
  30374. {
  30375. int ret;
  30376. byte privKey[CURVE448_KEY_SIZE];
  30377. word32 privKeyLen = CURVE448_KEY_SIZE;
  30378. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30379. return BAD_FUNC_ARG;
  30380. }
  30381. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  30382. NULL, NULL, X448k);
  30383. if (ret == 0) {
  30384. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  30385. }
  30386. return ret;
  30387. }
  30388. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  30389. curve448_key* key, word32 inSz)
  30390. {
  30391. int ret;
  30392. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30393. word32 pubKeyLen = (word32)sizeof(pubKey);
  30394. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  30395. return BAD_FUNC_ARG;
  30396. }
  30397. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  30398. pubKey, &pubKeyLen, X448k);
  30399. if (ret == 0) {
  30400. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  30401. }
  30402. return ret;
  30403. }
  30404. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  30405. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  30406. /* Write a Private ecc key, including public to DER format,
  30407. * length on success else < 0 */
  30408. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  30409. {
  30410. if (key == NULL) {
  30411. return BAD_FUNC_ARG;
  30412. }
  30413. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30414. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  30415. }
  30416. /* Write only private ecc key to DER format,
  30417. * length on success else < 0 */
  30418. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  30419. {
  30420. if (key == NULL) {
  30421. return BAD_FUNC_ARG;
  30422. }
  30423. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  30424. NULL, 0, output, inLen, ED448k);
  30425. }
  30426. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  30427. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  30428. /* Write private Curve448 key to DER format,
  30429. * length on success else < 0 */
  30430. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  30431. {
  30432. int ret;
  30433. byte privKey[CURVE448_KEY_SIZE];
  30434. word32 privKeyLen = CURVE448_KEY_SIZE;
  30435. if (key == NULL) {
  30436. return BAD_FUNC_ARG;
  30437. }
  30438. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  30439. if (ret == 0) {
  30440. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  30441. X448k);
  30442. }
  30443. return ret;
  30444. }
  30445. /* Write a public Curve448 key to DER format,
  30446. * length on success else < 0 */
  30447. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  30448. int withAlg)
  30449. {
  30450. int ret;
  30451. byte pubKey[CURVE448_PUB_KEY_SIZE];
  30452. word32 pubKeyLen = (word32)sizeof(pubKey);
  30453. if (key == NULL || output == NULL) {
  30454. return BAD_FUNC_ARG;
  30455. }
  30456. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  30457. if (ret == 0) {
  30458. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  30459. X448k, withAlg);
  30460. }
  30461. return ret;
  30462. }
  30463. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  30464. #ifndef WOLFSSL_ASN_TEMPLATE
  30465. #if (defined(HAVE_OCSP) || defined(HAVE_CRL)) && !defined(WOLFCRYPT_ONLY)
  30466. /* Get raw Date only, no processing, 0 on success */
  30467. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  30468. byte* format, int maxIdx)
  30469. {
  30470. int ret, length;
  30471. const byte *datePtr = NULL;
  30472. WOLFSSL_ENTER("GetBasicDate");
  30473. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  30474. if (ret < 0)
  30475. return ret;
  30476. XMEMCPY(date, datePtr, length);
  30477. return 0;
  30478. }
  30479. #endif /* HAVE_OCSP || HAVE_CRL */
  30480. #endif /* WOLFSSL_ASN_TEMPLATE */
  30481. #if defined(HAVE_OCSP) && !defined(WOLFCRYPT_ONLY)
  30482. #ifndef WOLFSSL_ASN_TEMPLATE
  30483. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  30484. int sz)
  30485. {
  30486. word32 idx = *inOutIdx;
  30487. word32 len;
  30488. byte tag;
  30489. WOLFSSL_ENTER("GetEnumerated");
  30490. *value = 0;
  30491. if (GetASNTag(input, &idx, &tag, sz) < 0)
  30492. return ASN_PARSE_E;
  30493. if (tag != ASN_ENUMERATED)
  30494. return ASN_PARSE_E;
  30495. if ((int)idx >= sz)
  30496. return BUFFER_E;
  30497. len = input[idx++];
  30498. if (len > 4 || (int)(len + idx) > sz)
  30499. return ASN_PARSE_E;
  30500. while (len--) {
  30501. *value = *value << 8 | input[idx++];
  30502. }
  30503. *inOutIdx = idx;
  30504. return *value;
  30505. }
  30506. #endif /* !WOLFSSL_ASN_TEMPLATE */
  30507. #ifdef WOLFSSL_ASN_TEMPLATE
  30508. /* ASN.1 template for OCSP single response.
  30509. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30510. */
  30511. static const ASNItem singleResponseASN[] = {
  30512. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30513. /* certId */
  30514. /* CID_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30515. /* hashAlgorithm */
  30516. /* CID_HASHALGO_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  30517. /* CID_HASHALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  30518. /* CID_HASHALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  30519. /* issuerNameHash */
  30520. /* CID_ISSUERHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30521. /* issuerKeyHash */
  30522. /* CID_ISSUERKEYHASH */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  30523. /* serialNumber */
  30524. /* CID_SERIAL */ { 2, ASN_INTEGER, 0, 0, 0 },
  30525. /* certStatus - CHOICE */
  30526. /* good [0] IMPLICIT NULL */
  30527. /* CS_GOOD */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  30528. /* revoked [1] IMPLICIT RevokedInfo */
  30529. /* CS_REVOKED */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  30530. /* revocationTime */
  30531. /* CS_REVOKED_TIME */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30532. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  30533. /* CS_REVOKED_REASON */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  30534. /* crlReason */
  30535. /* CS_REVOKED_REASON_VAL */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  30536. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  30537. /* UNKNOWN */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  30538. /* thisUpdate */
  30539. /* THISUPDATE_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30540. /* nextUpdate */
  30541. /* NEXTUPDATE */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30542. /* NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  30543. /* singleExtensions */
  30544. /* EXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  30545. };
  30546. enum {
  30547. SINGLERESPONSEASN_IDX_SEQ = 0,
  30548. SINGLERESPONSEASN_IDX_CID_SEQ,
  30549. SINGLERESPONSEASN_IDX_CID_HASHALGO_SEQ,
  30550. SINGLERESPONSEASN_IDX_CID_HASHALGO_OID,
  30551. SINGLERESPONSEASN_IDX_CID_HASHALGO_NULL,
  30552. SINGLERESPONSEASN_IDX_CID_ISSUERHASH,
  30553. SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH,
  30554. SINGLERESPONSEASN_IDX_CID_SERIAL,
  30555. SINGLERESPONSEASN_IDX_CS_GOOD,
  30556. SINGLERESPONSEASN_IDX_CS_REVOKED,
  30557. SINGLERESPONSEASN_IDX_CS_REVOKED_TIME,
  30558. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON,
  30559. SINGLERESPONSEASN_IDX_CS_REVOKED_REASON_VAL,
  30560. SINGLERESPONSEASN_IDX_UNKNOWN,
  30561. SINGLERESPONSEASN_IDX_THISUPDATE_GT,
  30562. SINGLERESPONSEASN_IDX_NEXTUPDATE,
  30563. SINGLERESPONSEASN_IDX_NEXTUPDATE_GT,
  30564. SINGLERESPONSEASN_IDX_EXT,
  30565. };
  30566. /* Number of items in ASN.1 template for OCSP single response. */
  30567. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  30568. #endif
  30569. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  30570. int wrapperSz, OcspEntry* single)
  30571. {
  30572. #ifndef WOLFSSL_ASN_TEMPLATE
  30573. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  30574. int length;
  30575. int ret;
  30576. byte tag;
  30577. WOLFSSL_ENTER("DecodeSingleResponse");
  30578. prevIndex = idx;
  30579. /* Wrapper around the Single Response */
  30580. if (GetSequence(source, &idx, &length, size) < 0)
  30581. return ASN_PARSE_E;
  30582. /* Wrapper around the CertID */
  30583. certIdIdx = idx;
  30584. if (GetSequence(source, &idx, &length, size) < 0)
  30585. return ASN_PARSE_E;
  30586. single->rawCertId = source + certIdIdx;
  30587. /* Hash algorithm */
  30588. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  30589. if (ret < 0)
  30590. return ret;
  30591. single->hashAlgoOID = oid;
  30592. /* Save reference to the hash of CN */
  30593. ret = GetOctetString(source, &idx, &length, size);
  30594. if (ret < 0)
  30595. return ret;
  30596. if (length > (int)sizeof(single->issuerHash))
  30597. return BUFFER_E;
  30598. XMEMCPY(single->issuerHash, source + idx, length);
  30599. idx += length;
  30600. /* Save reference to the hash of the issuer public key */
  30601. ret = GetOctetString(source, &idx, &length, size);
  30602. if (ret < 0)
  30603. return ret;
  30604. if (length > (int)sizeof(single->issuerKeyHash))
  30605. return BUFFER_E;
  30606. XMEMCPY(single->issuerKeyHash, source + idx, length);
  30607. idx += length;
  30608. /* Get serial number */
  30609. if (wc_GetSerialNumber(source, &idx, single->status->serial,
  30610. &single->status->serialSz, size) < 0)
  30611. return ASN_PARSE_E;
  30612. single->rawCertIdSize = idx - certIdIdx;
  30613. if (idx >= size)
  30614. return BUFFER_E;
  30615. /* CertStatus */
  30616. switch (source[idx++])
  30617. {
  30618. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  30619. single->status->status = CERT_GOOD;
  30620. idx++;
  30621. break;
  30622. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  30623. single->status->status = CERT_REVOKED;
  30624. if (GetLength(source, &idx, &length, size) < 0)
  30625. return ASN_PARSE_E;
  30626. idx += length;
  30627. break;
  30628. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  30629. single->status->status = CERT_UNKNOWN;
  30630. idx++;
  30631. break;
  30632. default:
  30633. return ASN_PARSE_E;
  30634. }
  30635. if (idx >= size)
  30636. return BUFFER_E;
  30637. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30638. single->status->thisDateAsn = source + idx;
  30639. localIdx = 0;
  30640. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  30641. (byte*)&single->status->thisDateParsed.type,
  30642. &single->status->thisDateParsed.length, size - idx) < 0)
  30643. return ASN_PARSE_E;
  30644. if (idx + localIdx >= size)
  30645. return BUFFER_E;
  30646. XMEMCPY(single->status->thisDateParsed.data,
  30647. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  30648. single->status->thisDateParsed.length);
  30649. #endif
  30650. if (GetBasicDate(source, &idx, single->status->thisDate,
  30651. &single->status->thisDateFormat, size) < 0)
  30652. return ASN_PARSE_E;
  30653. #ifndef NO_ASN_TIME_CHECK
  30654. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30655. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  30656. return ASN_BEFORE_DATE_E;
  30657. #endif
  30658. #endif
  30659. /* The following items are optional. Only check for them if there is more
  30660. * unprocessed data in the singleResponse wrapper. */
  30661. localIdx = idx;
  30662. if (((int)(idx - prevIndex) < wrapperSz) &&
  30663. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30664. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  30665. {
  30666. idx++;
  30667. if (GetLength(source, &idx, &length, size) < 0)
  30668. return ASN_PARSE_E;
  30669. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  30670. single->status->nextDateAsn = source + idx;
  30671. localIdx = 0;
  30672. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  30673. (byte*)&single->status->nextDateParsed.type,
  30674. &single->status->nextDateParsed.length, size - idx) < 0)
  30675. return ASN_PARSE_E;
  30676. if (idx + localIdx >= size)
  30677. return BUFFER_E;
  30678. XMEMCPY(single->status->nextDateParsed.data,
  30679. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  30680. single->status->nextDateParsed.length);
  30681. #endif
  30682. if (GetBasicDate(source, &idx, single->status->nextDate,
  30683. &single->status->nextDateFormat, size) < 0)
  30684. return ASN_PARSE_E;
  30685. #ifndef NO_ASN_TIME_CHECK
  30686. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  30687. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  30688. return ASN_AFTER_DATE_E;
  30689. #endif
  30690. #endif
  30691. }
  30692. /* Skip the optional extensions in singleResponse. */
  30693. localIdx = idx;
  30694. if (((int)(idx - prevIndex) < wrapperSz) &&
  30695. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  30696. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30697. {
  30698. idx++;
  30699. if (GetLength(source, &idx, &length, size) < 0)
  30700. return ASN_PARSE_E;
  30701. idx += length;
  30702. }
  30703. *ioIndex = idx;
  30704. return 0;
  30705. #else
  30706. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  30707. int ret = 0;
  30708. word32 ocspDigestSize = OCSP_DIGEST_SIZE;
  30709. CertStatus* cs = NULL;
  30710. word32 serialSz;
  30711. word32 issuerHashLen;
  30712. word32 issuerKeyHashLen;
  30713. word32 thisDateLen;
  30714. word32 nextDateLen;
  30715. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30716. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30717. WOLFSSL_ASN1_TIME *at;
  30718. #endif
  30719. (void)wrapperSz;
  30720. WOLFSSL_ENTER("DecodeSingleResponse");
  30721. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  30722. if (ret == 0) {
  30723. /* Certificate Status field. */
  30724. cs = single->status;
  30725. /* Set maximum lengths for data. */
  30726. issuerHashLen = OCSP_DIGEST_SIZE;
  30727. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  30728. serialSz = EXTERNAL_SERIAL_SIZE;
  30729. thisDateLen = MAX_DATE_SIZE;
  30730. nextDateLen = MAX_DATE_SIZE;
  30731. /* Set OID type, buffers to hold data and variables to hold size. */
  30732. GetASN_OID(&dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID],
  30733. oidHashType);
  30734. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERHASH],
  30735. single->issuerHash, &issuerHashLen);
  30736. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_ISSUERKEYHASH],
  30737. single->issuerKeyHash, &issuerKeyHashLen);
  30738. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_CID_SERIAL], cs->serial,
  30739. &serialSz);
  30740. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT],
  30741. cs->thisDate, &thisDateLen);
  30742. GetASN_Buffer(&dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT],
  30743. cs->nextDate, &nextDateLen);
  30744. /* TODO: decode revoked time and reason. */
  30745. /* Decode OCSP single response. */
  30746. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  30747. 1, source, ioIndex, size);
  30748. }
  30749. if (ret == 0) {
  30750. single->hashAlgoOID =
  30751. dataASN[SINGLERESPONSEASN_IDX_CID_HASHALGO_OID].data.oid.sum;
  30752. ocspDigestSize = wc_HashGetDigestSize(
  30753. wc_OidGetHash(single->hashAlgoOID));
  30754. }
  30755. /* Validate the issuer hash length is the size required. */
  30756. if ((ret == 0) && (issuerHashLen != ocspDigestSize)) {
  30757. ret = ASN_PARSE_E;
  30758. }
  30759. /* Validate the issuer key hash length is the size required. */
  30760. if ((ret == 0) && (issuerKeyHashLen != ocspDigestSize)) {
  30761. ret = ASN_PARSE_E;
  30762. }
  30763. if (ret == 0) {
  30764. /* Store serial size. */
  30765. cs->serialSz = serialSz;
  30766. /* Determine status by which item was found. */
  30767. if (dataASN[SINGLERESPONSEASN_IDX_CS_GOOD].tag != 0) {
  30768. cs->status = CERT_GOOD;
  30769. }
  30770. if (dataASN[SINGLERESPONSEASN_IDX_CS_REVOKED].tag != 0) {
  30771. cs->status = CERT_REVOKED;
  30772. }
  30773. if (dataASN[SINGLERESPONSEASN_IDX_UNKNOWN].tag != 0) {
  30774. cs->status = CERT_UNKNOWN;
  30775. }
  30776. /* Store the thisDate format - only one possible. */
  30777. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  30778. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30779. /* Check date is a valid string and BEFORE now. */
  30780. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  30781. ret = ASN_BEFORE_DATE_E;
  30782. }
  30783. }
  30784. if (ret == 0) {
  30785. #endif
  30786. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30787. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30788. /* Store ASN.1 version of thisDate. */
  30789. cs->thisDateAsn = GetASNItem_Addr(
  30790. dataASN[SINGLERESPONSEASN_IDX_THISUPDATE_GT], source);
  30791. at = &cs->thisDateParsed;
  30792. at->type = ASN_GENERALIZED_TIME;
  30793. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  30794. at->length = thisDateLen;
  30795. #endif
  30796. }
  30797. if ((ret == 0) &&
  30798. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30799. /* Store the nextDate format - only one possible. */
  30800. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  30801. #if !defined(NO_ASN_TIME_CHECK) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  30802. /* Check date is a valid string and AFTER now. */
  30803. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  30804. ret = ASN_AFTER_DATE_E;
  30805. }
  30806. }
  30807. if ((ret == 0) &&
  30808. (dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT].tag != 0)) {
  30809. #endif
  30810. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  30811. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  30812. /* Store ASN.1 version of thisDate. */
  30813. cs->nextDateAsn = GetASNItem_Addr(
  30814. dataASN[SINGLERESPONSEASN_IDX_NEXTUPDATE_GT], source);
  30815. at = &cs->nextDateParsed;
  30816. at->type = ASN_GENERALIZED_TIME;
  30817. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  30818. at->length = nextDateLen;
  30819. #endif
  30820. }
  30821. if (ret == 0) {
  30822. /* OcspEntry now used. */
  30823. single->used = 1;
  30824. }
  30825. FREE_ASNGETDATA(dataASN, NULL);
  30826. return ret;
  30827. #endif
  30828. }
  30829. #ifdef WOLFSSL_ASN_TEMPLATE
  30830. /* ASN.1 template for OCSP response extension header.
  30831. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30832. */
  30833. static const ASNItem respExtHdrASN[] = {
  30834. /* responseExtensions */
  30835. /* EXT */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  30836. /* extensions */
  30837. /* EXT_SEQ */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  30838. };
  30839. enum {
  30840. RESPEXTHDRASN_IDX_EXT = 0,
  30841. RESPEXTHDRASN_IDX_EXT_SEQ,
  30842. };
  30843. /* Number of items in ASN.1 template for OCSP response extension header. */
  30844. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  30845. #endif
  30846. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  30847. OcspResponse* resp, word32 sz)
  30848. {
  30849. #ifndef WOLFSSL_ASN_TEMPLATE
  30850. word32 idx = *ioIndex;
  30851. int length;
  30852. int ext_bound; /* boundary index for the sequence of extensions */
  30853. word32 oid;
  30854. int ret;
  30855. byte tag;
  30856. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30857. if ((idx + 1) > sz)
  30858. return BUFFER_E;
  30859. if (GetASNTag(source, &idx, &tag, sz) < 0)
  30860. return ASN_PARSE_E;
  30861. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  30862. return ASN_PARSE_E;
  30863. if (GetLength(source, &idx, &length, sz) < 0)
  30864. return ASN_PARSE_E;
  30865. if (GetSequence(source, &idx, &length, sz) < 0)
  30866. return ASN_PARSE_E;
  30867. ext_bound = idx + length;
  30868. while (idx < (word32)ext_bound) {
  30869. word32 localIdx;
  30870. if (GetSequence(source, &idx, &length, sz) < 0) {
  30871. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  30872. return ASN_PARSE_E;
  30873. }
  30874. oid = 0;
  30875. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  30876. WOLFSSL_MSG("\tfail: OBJECT ID");
  30877. return ASN_PARSE_E;
  30878. }
  30879. /* check for critical flag */
  30880. if ((idx + 1) > (word32)sz) {
  30881. WOLFSSL_MSG("\tfail: malformed buffer");
  30882. return BUFFER_E;
  30883. }
  30884. localIdx = idx;
  30885. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  30886. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  30887. ret = GetBoolean(source, &idx, sz);
  30888. if (ret < 0)
  30889. return ret;
  30890. }
  30891. ret = GetOctetString(source, &idx, &length, sz);
  30892. if (ret < 0)
  30893. return ret;
  30894. if (oid == OCSP_NONCE_OID) {
  30895. /* get data inside extra OCTET_STRING */
  30896. ret = GetOctetString(source, &idx, &length, sz);
  30897. if (ret < 0)
  30898. return ret;
  30899. resp->nonce = source + idx;
  30900. resp->nonceSz = length;
  30901. }
  30902. idx += length;
  30903. }
  30904. *ioIndex = idx;
  30905. return 0;
  30906. #else
  30907. /* certExtASN_Length is greater than respExtHdrASN_Length */
  30908. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  30909. int ret = 0;
  30910. word32 idx = *ioIndex;
  30911. word32 maxIdx = 0;
  30912. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  30913. CALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  30914. if (ret == 0) {
  30915. /* Check for header and move past. */
  30916. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  30917. source, &idx, sz);
  30918. }
  30919. if (ret == 0) {
  30920. /* Keep end extensions index for total length check. */
  30921. maxIdx = idx + dataASN[RESPEXTHDRASN_IDX_EXT_SEQ].length;
  30922. }
  30923. /* Step through all extensions. */
  30924. while ((ret == 0) && (idx < maxIdx)) {
  30925. /* Clear dynamic data, set OID type to expect. */
  30926. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  30927. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidOcspType);
  30928. /* TODO: check criticality. */
  30929. /* Decode OCSP response extension. */
  30930. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  30931. source, &idx, sz);
  30932. if (ret == 0) {
  30933. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  30934. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  30935. if (oid == OCSP_NONCE_OID) {
  30936. /* Extract nonce data. */
  30937. ret = GetOctetString(source, &idx, &length, sz);
  30938. if (ret >= 0) {
  30939. ret = 0;
  30940. /* get data inside extra OCTET_STRING */
  30941. resp->nonce = source + idx;
  30942. resp->nonceSz = length;
  30943. }
  30944. }
  30945. /* Ignore all other extension types. */
  30946. /* Skip over rest of extension. */
  30947. idx += length;
  30948. }
  30949. }
  30950. /* Return index after extensions. */
  30951. *ioIndex = idx;
  30952. FREE_ASNGETDATA(dataASN, resp->heap);
  30953. return ret;
  30954. #endif
  30955. }
  30956. #ifdef WOLFSSL_ASN_TEMPLATE
  30957. /* ASN.1 template for OCSP ResponseData.
  30958. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  30959. */
  30960. static const ASNItem ocspRespDataASN[] = {
  30961. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  30962. /* version DEFAULT v1 */
  30963. /* VER_PRESENT */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  30964. /* VER */ { 2, ASN_INTEGER, 1, 0, 0 },
  30965. /* byName */
  30966. /* BYNAME */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  30967. /* byKey */
  30968. /* BYKEY */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  30969. /* producedAt */
  30970. /* PA */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  30971. /* responses */
  30972. /* RESP */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  30973. /* responseExtensions */
  30974. /* RESPEXT */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  30975. };
  30976. enum {
  30977. OCSPRESPDATAASN_IDX_SEQ = 0,
  30978. OCSPRESPDATAASN_IDX_VER_PRESENT,
  30979. OCSPRESPDATAASN_IDX_VER,
  30980. OCSPRESPDATAASN_IDX_BYNAME,
  30981. OCSPRESPDATAASN_IDX_BYKEY,
  30982. OCSPRESPDATAASN_IDX_PA,
  30983. OCSPRESPDATAASN_IDX_RESP,
  30984. OCSPRESPDATAASN_IDX_RESPEXT,
  30985. };
  30986. /* Number of items in ASN.1 template for OCSP ResponseData. */
  30987. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  30988. #endif
  30989. static int DecodeResponseData(byte* source, word32* ioIndex,
  30990. OcspResponse* resp, word32 size)
  30991. {
  30992. #ifndef WOLFSSL_ASN_TEMPLATE
  30993. word32 idx = *ioIndex, prev_idx, localIdx;
  30994. int length;
  30995. int version;
  30996. int ret;
  30997. byte tag;
  30998. int wrapperSz;
  30999. OcspEntry* single;
  31000. WOLFSSL_ENTER("DecodeResponseData");
  31001. resp->response = source + idx;
  31002. prev_idx = idx;
  31003. if (GetSequence(source, &idx, &length, size) < 0)
  31004. return ASN_PARSE_E;
  31005. resp->responseSz = length + idx - prev_idx;
  31006. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  31007. * item isn't an EXPLICIT[0], then set version to zero and move
  31008. * onto the next item.
  31009. */
  31010. localIdx = idx;
  31011. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31012. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  31013. {
  31014. idx += 2; /* Eat the value and length */
  31015. if (GetMyVersion(source, &idx, &version, size) < 0)
  31016. return ASN_PARSE_E;
  31017. } else
  31018. version = 0;
  31019. localIdx = idx;
  31020. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  31021. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  31022. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  31023. {
  31024. idx++; /* advance past ASN tag */
  31025. if (GetLength(source, &idx, &length, size) < 0)
  31026. return ASN_PARSE_E;
  31027. idx += length;
  31028. }
  31029. else
  31030. return ASN_PARSE_E;
  31031. /* save pointer to the producedAt time */
  31032. if (GetBasicDate(source, &idx, resp->producedDate,
  31033. &resp->producedDateFormat, size) < 0)
  31034. return ASN_PARSE_E;
  31035. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  31036. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  31037. return ASN_PARSE_E;
  31038. localIdx = idx;
  31039. single = resp->single;
  31040. while (idx - localIdx < (word32)wrapperSz) {
  31041. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  31042. if (ret < 0)
  31043. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31044. if (idx - localIdx < (word32)wrapperSz) {
  31045. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  31046. DYNAMIC_TYPE_OCSP_ENTRY);
  31047. if (single->next == NULL) {
  31048. return MEMORY_E;
  31049. }
  31050. XMEMSET(single->next, 0, sizeof(OcspEntry));
  31051. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  31052. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31053. if (single->next->status == NULL) {
  31054. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31055. single->next = NULL;
  31056. return MEMORY_E;
  31057. }
  31058. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  31059. single->next->isDynamic = 1;
  31060. single = single->next;
  31061. }
  31062. }
  31063. /*
  31064. * Check the length of the ResponseData against the current index to
  31065. * see if there are extensions, they are optional.
  31066. */
  31067. if (idx - prev_idx < resp->responseSz)
  31068. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  31069. return ASN_PARSE_E;
  31070. *ioIndex = idx;
  31071. return 0;
  31072. #else
  31073. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  31074. int ret = 0;
  31075. byte version;
  31076. word32 dateSz, idx = *ioIndex;
  31077. OcspEntry* single = NULL;
  31078. WOLFSSL_ENTER("DecodeResponseData");
  31079. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  31080. if (ret == 0) {
  31081. resp->response = source + idx;
  31082. /* Default, not present, is v1 = 0. */
  31083. version = 0;
  31084. /* Max size of date supported. */
  31085. dateSz = MAX_DATE_SIZE;
  31086. /* Set the where to put version an produced date. */
  31087. GetASN_Int8Bit(&dataASN[OCSPRESPDATAASN_IDX_VER], &version);
  31088. GetASN_Buffer(&dataASN[OCSPRESPDATAASN_IDX_PA], resp->producedDate,
  31089. &dateSz);
  31090. /* Decode the ResponseData. */
  31091. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  31092. 1, source, ioIndex, size);
  31093. }
  31094. /* Only support v1 == 0 */
  31095. if ((ret == 0) && (version != 0)) {
  31096. ret = ASN_PARSE_E;
  31097. }
  31098. /* Ensure date is a minimal size. */
  31099. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  31100. ret = ASN_PARSE_E;
  31101. }
  31102. if (ret == 0) {
  31103. /* TODO: use byName/byKey fields. */
  31104. /* Store size of response. */
  31105. resp->responseSz = *ioIndex - idx;
  31106. /* Store date format/tag. */
  31107. resp->producedDateFormat = dataASN[OCSPRESPDATAASN_IDX_PA].tag;
  31108. /* Get the index of the responses SEQUENCE. */
  31109. idx = GetASNItem_DataIdx(dataASN[OCSPRESPDATAASN_IDX_RESP], source);
  31110. /* Start with the pre-existing OcspEntry. */
  31111. single = resp->single;
  31112. }
  31113. while ((ret == 0) && (idx < dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset)) {
  31114. /* Allocate and use a new OCSP entry if this is used. */
  31115. if (single->used) {
  31116. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  31117. DYNAMIC_TYPE_OCSP_ENTRY);
  31118. if (single->next == NULL) {
  31119. ret = MEMORY_E;
  31120. }
  31121. else {
  31122. XMEMSET(single->next, 0, sizeof(OcspEntry));
  31123. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  31124. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31125. if (single->next->status == NULL) {
  31126. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31127. single->next = NULL;
  31128. ret = MEMORY_E;
  31129. }
  31130. else {
  31131. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  31132. /* Entry to be freed. */
  31133. single->next->isDynamic = 1;
  31134. /* used will be 0 (false) */
  31135. single = single->next;
  31136. }
  31137. }
  31138. }
  31139. if (ret == 0) {
  31140. /* Decode SingleResponse into OcspEntry. */
  31141. ret = DecodeSingleResponse(source, &idx,
  31142. dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset,
  31143. dataASN[OCSPRESPDATAASN_IDX_RESP].length, single);
  31144. /* single->used set on successful decode. */
  31145. }
  31146. }
  31147. /* Check if there were extensions. */
  31148. if ((ret == 0) &&
  31149. (dataASN[OCSPRESPDATAASN_IDX_RESPEXT].data.buffer.data != NULL)) {
  31150. /* Get index of [1] */
  31151. idx = dataASN[OCSPRESPDATAASN_IDX_RESPEXT].offset;
  31152. /* Decode the response extensions. */
  31153. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  31154. ret = ASN_PARSE_E;
  31155. }
  31156. }
  31157. FREE_ASNGETDATA(dataASN, resp->heap);
  31158. return ret;
  31159. #endif
  31160. }
  31161. #ifndef WOLFSSL_ASN_TEMPLATE
  31162. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31163. static int DecodeCerts(byte* source,
  31164. word32* ioIndex, OcspResponse* resp, word32 size)
  31165. {
  31166. word32 idx = *ioIndex;
  31167. byte tag;
  31168. WOLFSSL_ENTER("DecodeCerts");
  31169. if (GetASNTag(source, &idx, &tag, size) < 0)
  31170. return ASN_PARSE_E;
  31171. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  31172. {
  31173. int length;
  31174. if (GetLength(source, &idx, &length, size) < 0)
  31175. return ASN_PARSE_E;
  31176. if (GetSequence(source, &idx, &length, size) < 0)
  31177. return ASN_PARSE_E;
  31178. resp->cert = source + idx;
  31179. resp->certSz = length;
  31180. idx += length;
  31181. }
  31182. *ioIndex = idx;
  31183. return 0;
  31184. }
  31185. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31186. #endif /* !WOLFSSL_ASN_TEMPLATE */
  31187. #ifdef WOLFSSL_ASN_TEMPLATE
  31188. /* ASN.1 template for BasicOCSPResponse.
  31189. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31190. */
  31191. static const ASNItem ocspBasicRespASN[] = {
  31192. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31193. /* tbsResponseData */
  31194. /* TBS_SEQ */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  31195. /* signatureAlgorithm */
  31196. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  31197. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  31198. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  31199. /* parameters */
  31200. #ifdef WC_RSA_PSS
  31201. /* SIGALGO_PARAMS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  31202. #endif
  31203. /* signature */
  31204. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  31205. /* certs */
  31206. /* CERTS */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31207. /* CERTS_SEQ */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  31208. };
  31209. enum {
  31210. OCSPBASICRESPASN_IDX_SEQ = 0,
  31211. OCSPBASICRESPASN_IDX_TBS_SEQ,
  31212. OCSPBASICRESPASN_IDX_SIGALGO,
  31213. OCSPBASICRESPASN_IDX_SIGALGO_OID,
  31214. OCSPBASICRESPASN_IDX_SIGALGO_NULL,
  31215. #ifdef WC_RSA_PSS
  31216. OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS,
  31217. #endif
  31218. OCSPBASICRESPASN_IDX_SIGNATURE,
  31219. OCSPBASICRESPASN_IDX_CERTS,
  31220. OCSPBASICRESPASN_IDX_CERTS_SEQ,
  31221. };
  31222. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  31223. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  31224. #endif /* WOLFSSL_ASN_TEMPLATE */
  31225. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  31226. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  31227. {
  31228. #ifndef WOLFSSL_ASN_TEMPLATE
  31229. int length;
  31230. word32 idx = *ioIndex;
  31231. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31232. word32 end_index;
  31233. #endif
  31234. int ret;
  31235. int sigLength;
  31236. const byte* sigParams = NULL;
  31237. word32 sigParamsSz = 0;
  31238. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31239. (void)heap;
  31240. if (GetSequence(source, &idx, &length, size) < 0)
  31241. return ASN_PARSE_E;
  31242. if (idx + length > size)
  31243. return ASN_INPUT_E;
  31244. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31245. end_index = idx + length;
  31246. #endif
  31247. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  31248. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  31249. /* Get the signature algorithm */
  31250. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0) {
  31251. return ASN_PARSE_E;
  31252. }
  31253. #ifdef WC_RSA_PSS
  31254. else if (resp->sigOID == CTC_RSASSAPSS) {
  31255. word32 sz;
  31256. int len;
  31257. const byte* params;
  31258. sz = idx;
  31259. params = source + idx;
  31260. if (GetSequence(source, &idx, &len, size) < 0)
  31261. ret = ASN_PARSE_E;
  31262. if (ret == 0) {
  31263. idx += len;
  31264. sigParams = params;
  31265. sigParamsSz = idx - sz;
  31266. }
  31267. }
  31268. #endif
  31269. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  31270. if (ret != 0)
  31271. return ret;
  31272. resp->sigSz = sigLength;
  31273. resp->sig = source + idx;
  31274. idx += sigLength;
  31275. /*
  31276. * Check the length of the BasicOcspResponse against the current index to
  31277. * see if there are certificates, they are optional.
  31278. */
  31279. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31280. if (idx < end_index)
  31281. {
  31282. int cert_inited = 0;
  31283. #ifdef WOLFSSL_SMALL_STACK
  31284. DecodedCert *cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  31285. DYNAMIC_TYPE_TMP_BUFFER);
  31286. if (cert == NULL)
  31287. return MEMORY_E;
  31288. #else
  31289. DecodedCert cert[1];
  31290. #endif
  31291. do {
  31292. if (DecodeCerts(source, &idx, resp, size) < 0) {
  31293. ret = ASN_PARSE_E;
  31294. break;
  31295. }
  31296. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31297. cert_inited = 1;
  31298. /* Don't verify if we don't have access to Cert Manager. */
  31299. ret = ParseCertRelative(cert, CERT_TYPE,
  31300. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT,
  31301. cm);
  31302. if (ret < 0) {
  31303. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31304. break;
  31305. }
  31306. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  31307. if ((cert->extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  31308. if (XMEMCMP(cert->subjectHash,
  31309. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  31310. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  31311. }
  31312. else {
  31313. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  31314. #ifdef OPENSSL_EXTRA
  31315. resp->verifyError = OCSP_BAD_ISSUER;
  31316. #else
  31317. ret = BAD_OCSP_RESPONDER;
  31318. break;
  31319. #endif
  31320. }
  31321. }
  31322. #endif
  31323. /* ConfirmSignature is blocking here */
  31324. ret = ConfirmSignature(
  31325. &cert->sigCtx,
  31326. resp->response, resp->responseSz,
  31327. cert->publicKey, cert->pubKeySize, cert->keyOID,
  31328. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31329. NULL);
  31330. if (ret != 0) {
  31331. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31332. ret = ASN_OCSP_CONFIRM_E;
  31333. break;
  31334. }
  31335. } while(0);
  31336. if (cert_inited)
  31337. FreeDecodedCert(cert);
  31338. #ifdef WOLFSSL_SMALL_STACK
  31339. XFREE(cert, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  31340. #endif
  31341. if (ret != 0)
  31342. return ret;
  31343. }
  31344. else
  31345. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31346. {
  31347. Signer* ca;
  31348. int sigValid = -1;
  31349. #ifndef NO_SKID
  31350. ca = GetCA(cm, resp->single->issuerKeyHash);
  31351. #else
  31352. ca = GetCA(cm, resp->single->issuerHash);
  31353. #endif
  31354. if (ca) {
  31355. SignatureCtx sigCtx;
  31356. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31357. /* ConfirmSignature is blocking here */
  31358. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31359. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31360. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31361. NULL);
  31362. }
  31363. if (ca == NULL || sigValid != 0) {
  31364. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31365. return ASN_OCSP_CONFIRM_E;
  31366. }
  31367. (void)noVerify;
  31368. }
  31369. *ioIndex = idx;
  31370. return 0;
  31371. #else
  31372. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  31373. int ret = 0;
  31374. word32 idx = *ioIndex;
  31375. const byte* sigParams = NULL;
  31376. word32 sigParamsSz = 0;
  31377. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31378. #ifdef WOLFSSL_SMALL_STACK
  31379. DecodedCert* cert = NULL;
  31380. #else
  31381. DecodedCert cert[1];
  31382. #endif
  31383. int certInit = 0;
  31384. #endif
  31385. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  31386. (void)heap;
  31387. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  31388. if (ret == 0) {
  31389. /* Set expecting signature OID. */
  31390. GetASN_OID(&dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID], oidSigType);
  31391. /* Decode BasicOCSPResponse. */
  31392. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  31393. 1, source, &idx, size);
  31394. }
  31395. if (ret == 0) {
  31396. word32 dataIdx = 0;
  31397. /* Decode the response data. */
  31398. if (DecodeResponseData(
  31399. GetASNItem_Addr(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source),
  31400. &dataIdx, resp,
  31401. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_TBS_SEQ], source)
  31402. ) < 0) {
  31403. ret = ASN_PARSE_E;
  31404. }
  31405. }
  31406. #ifdef WC_RSA_PSS
  31407. if (ret == 0 && (dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS].tag != 0)) {
  31408. sigParams = GetASNItem_Addr(
  31409. dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31410. source);
  31411. sigParamsSz =
  31412. GetASNItem_Length(dataASN[OCSPBASICRESPASN_IDX_SIGNATURE_PARAMS],
  31413. source);
  31414. }
  31415. #endif
  31416. if (ret == 0) {
  31417. /* Get the signature OID and signature. */
  31418. resp->sigOID = dataASN[OCSPBASICRESPASN_IDX_SIGALGO_OID].data.oid.sum;
  31419. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_SIGNATURE], &resp->sig,
  31420. &resp->sigSz);
  31421. }
  31422. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31423. if ((ret == 0) &&
  31424. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31425. /* TODO: support more than one certificate. */
  31426. /* Store reference to certificate BER data. */
  31427. GetASN_GetRef(&dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ], &resp->cert,
  31428. &resp->certSz);
  31429. /* Allocate a certificate object to decode cert into. */
  31430. #ifdef WOLFSSL_SMALL_STACK
  31431. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  31432. DYNAMIC_TYPE_TMP_BUFFER);
  31433. if (cert == NULL) {
  31434. ret = MEMORY_E;
  31435. }
  31436. }
  31437. if ((ret == 0) &&
  31438. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31439. #endif
  31440. /* Initialize the crtificate object. */
  31441. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  31442. certInit = 1;
  31443. /* Parse the certificate and don't verify if we don't have access to
  31444. * Cert Manager. */
  31445. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  31446. cm);
  31447. if (ret < 0) {
  31448. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  31449. }
  31450. }
  31451. if ((ret == 0) &&
  31452. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data != NULL)) {
  31453. /* TODO: ConfirmSignature is blocking here */
  31454. /* Check the signature of the response. */
  31455. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  31456. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  31457. resp->sigSz, resp->sigOID, NULL, 0, NULL);
  31458. if (ret != 0) {
  31459. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31460. ret = ASN_OCSP_CONFIRM_E;
  31461. }
  31462. }
  31463. if ((ret == 0) &&
  31464. (dataASN[OCSPBASICRESPASN_IDX_CERTS_SEQ].data.ref.data == NULL))
  31465. #else
  31466. if (ret == 0)
  31467. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  31468. {
  31469. Signer* ca;
  31470. int sigValid = -1;
  31471. /* Resonse didn't have a certificate - lookup CA. */
  31472. #ifndef NO_SKID
  31473. ca = GetCA(cm, resp->single->issuerKeyHash);
  31474. #else
  31475. ca = GetCA(cm, resp->single->issuerHash);
  31476. #endif
  31477. if (ca) {
  31478. SignatureCtx sigCtx;
  31479. /* Initialize he signature context. */
  31480. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  31481. /* TODO: ConfirmSignature is blocking here */
  31482. /* Check the signature of the response CA public key. */
  31483. sigValid = ConfirmSignature(&sigCtx, resp->response,
  31484. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  31485. resp->sig, resp->sigSz, resp->sigOID, sigParams, sigParamsSz,
  31486. NULL);
  31487. }
  31488. if ((ca == NULL) || (sigValid != 0)) {
  31489. /* Didn't find certificate or signature verificate failed. */
  31490. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  31491. ret = ASN_OCSP_CONFIRM_E;
  31492. }
  31493. }
  31494. if (ret == 0) {
  31495. /* Update the position to after response data. */
  31496. *ioIndex = idx;
  31497. }
  31498. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  31499. if (certInit) {
  31500. FreeDecodedCert(cert);
  31501. }
  31502. #ifdef WOLFSSL_SMALL_STACK
  31503. if (cert != NULL) {
  31504. /* Dispose of certificate object. */
  31505. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  31506. }
  31507. #endif
  31508. #endif
  31509. FREE_ASNGETDATA(dataASN, heap);
  31510. return ret;
  31511. #endif /* WOLFSSL_ASN_TEMPLATE */
  31512. }
  31513. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  31514. byte* source, word32 inSz, void* heap)
  31515. {
  31516. WOLFSSL_ENTER("InitOcspResponse");
  31517. XMEMSET(status, 0, sizeof(CertStatus));
  31518. XMEMSET(single, 0, sizeof(OcspEntry));
  31519. XMEMSET(resp, 0, sizeof(OcspResponse));
  31520. single->status = status;
  31521. resp->responseStatus = -1;
  31522. resp->single = single;
  31523. resp->source = source;
  31524. resp->maxIdx = inSz;
  31525. resp->heap = heap;
  31526. }
  31527. void FreeOcspResponse(OcspResponse* resp)
  31528. {
  31529. OcspEntry *single, *next;
  31530. if (resp != NULL) {
  31531. for (single = resp->single; single; single = next) {
  31532. next = single->next;
  31533. if (single->isDynamic) {
  31534. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  31535. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  31536. }
  31537. }
  31538. }
  31539. }
  31540. #ifdef WOLFSSL_ASN_TEMPLATE
  31541. /* ASN.1 template for OCSPResponse.
  31542. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  31543. */
  31544. static const ASNItem ocspResponseASN[] = {
  31545. /* OCSPResponse ::= SEQUENCE */
  31546. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31547. /* responseStatus OCSPResponseStatus */
  31548. /* STATUS */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  31549. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  31550. /* BYTES */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  31551. /* ResponseBytes ::= SEQUENCE */
  31552. /* BYTES_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31553. /* responseType OBJECT IDENTIFIER */
  31554. /* BYTES_TYPE */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  31555. /* response OCTET STRING */
  31556. /* BYTES_VAL */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  31557. };
  31558. enum {
  31559. OCSPRESPONSEASN_IDX_SEQ = 0,
  31560. OCSPRESPONSEASN_IDX_STATUS,
  31561. OCSPRESPONSEASN_IDX_BYTES,
  31562. OCSPRESPONSEASN_IDX_BYTES_SEQ,
  31563. OCSPRESPONSEASN_IDX_BYTES_TYPE,
  31564. OCSPRESPONSEASN_IDX_BYTES_VAL,
  31565. };
  31566. /* Number of items in ASN.1 template for OCSPResponse. */
  31567. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  31568. #endif /* WOLFSSL_ASN_TEMPLATE */
  31569. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  31570. {
  31571. #ifndef WOLFSSL_ASN_TEMPLATE
  31572. int ret;
  31573. int length = 0;
  31574. word32 idx = 0;
  31575. byte* source = resp->source;
  31576. word32 size = resp->maxIdx;
  31577. word32 oid;
  31578. byte tag;
  31579. WOLFSSL_ENTER("OcspResponseDecode");
  31580. /* peel the outer SEQUENCE wrapper */
  31581. if (GetSequence(source, &idx, &length, size) < 0) {
  31582. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31583. return ASN_PARSE_E;
  31584. }
  31585. /* First get the responseStatus, an ENUMERATED */
  31586. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0) {
  31587. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31588. return ASN_PARSE_E;
  31589. }
  31590. if (resp->responseStatus != OCSP_SUCCESSFUL) {
  31591. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31592. return 0;
  31593. }
  31594. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  31595. if (idx >= size) {
  31596. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31597. return ASN_PARSE_E;
  31598. }
  31599. if (GetASNTag(source, &idx, &tag, size) < 0) {
  31600. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31601. return ASN_PARSE_E;
  31602. }
  31603. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC)) {
  31604. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31605. return ASN_PARSE_E;
  31606. }
  31607. if (GetLength(source, &idx, &length, size) < 0) {
  31608. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31609. return ASN_PARSE_E;
  31610. }
  31611. /* Get the responseBytes SEQUENCE */
  31612. if (GetSequence(source, &idx, &length, size) < 0) {
  31613. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31614. return ASN_PARSE_E;
  31615. }
  31616. /* Check ObjectID for the resposeBytes */
  31617. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0) {
  31618. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31619. return ASN_PARSE_E;
  31620. }
  31621. if (oid != OCSP_BASIC_OID) {
  31622. WOLFSSL_LEAVE("OcspResponseDecode", ASN_PARSE_E);
  31623. return ASN_PARSE_E;
  31624. }
  31625. ret = GetOctetString(source, &idx, &length, size);
  31626. if (ret < 0) {
  31627. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31628. return ret;
  31629. }
  31630. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  31631. if (ret < 0) {
  31632. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31633. return ret;
  31634. }
  31635. WOLFSSL_LEAVE("OcspResponseDecode", 0);
  31636. return 0;
  31637. #else
  31638. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  31639. int ret = 0;
  31640. word32 idx = 0, size = resp->maxIdx;
  31641. byte* source = resp->source;
  31642. byte status;
  31643. byte* basic;
  31644. word32 basicSz;
  31645. WOLFSSL_ENTER("OcspResponseDecode");
  31646. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  31647. if (ret == 0) {
  31648. /* Set variable to put status in and expect OCSP OID. */
  31649. GetASN_Int8Bit(&dataASN[OCSPRESPONSEASN_IDX_STATUS], &status);
  31650. GetASN_OID(&dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE], oidOcspType);
  31651. /* Decode OCSPResponse (and ResponseBytes). */
  31652. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  31653. source, &idx, size);
  31654. }
  31655. if (ret == 0) {
  31656. /* Get response. */
  31657. resp->responseStatus = status;
  31658. if (dataASN[OCSPRESPONSEASN_IDX_BYTES_TYPE].data.oid.sum
  31659. == OCSP_BASIC_OID) {
  31660. /* Get reference to BasicOCSPResponse. */
  31661. GetASN_GetRef(&dataASN[OCSPRESPONSEASN_IDX_BYTES_VAL], &basic,
  31662. &basicSz);
  31663. idx = 0;
  31664. /* Decode BasicOCSPResponse. */
  31665. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  31666. noVerify);
  31667. }
  31668. /* Only support BasicOCSPResponse. */
  31669. else {
  31670. ret = ASN_PARSE_E;
  31671. }
  31672. }
  31673. FREE_ASNGETDATA(dataASN, resp->heap);
  31674. WOLFSSL_LEAVE("OcspResponseDecode", ret);
  31675. return ret;
  31676. #endif /* WOLFSSL_ASN_TEMPLATE */
  31677. }
  31678. #ifdef WOLFSSL_ASN_TEMPLATE
  31679. /* ASN.1 template for OCSP nonce extension.
  31680. * RFC 6960, 4.4.1 - Nonce
  31681. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  31682. */
  31683. static const ASNItem ocspNonceExtASN[] = {
  31684. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31685. /* Extension */
  31686. /* EXT */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31687. /* extnId */
  31688. /* EXT_OID */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  31689. /* critcal not encoded. */
  31690. /* extnValue */
  31691. /* EXT_VAL */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  31692. /* nonce */
  31693. /* EXT_NONCE */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  31694. };
  31695. enum {
  31696. OCSPNONCEEXTASN_IDX_SEQ = 0,
  31697. OCSPNONCEEXTASN_IDX_EXT,
  31698. OCSPNONCEEXTASN_IDX_EXT_OID,
  31699. OCSPNONCEEXTASN_IDX_EXT_VAL,
  31700. OCSPNONCEEXTASN_IDX_EXT_NONCE,
  31701. };
  31702. /* Number of items in ASN.1 template for OCSP nonce extension. */
  31703. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  31704. #endif /* WOLFSSL_ASN_TEMPLATE */
  31705. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  31706. {
  31707. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  31708. 0x30, 0x01, 0x02 };
  31709. #ifndef WOLFSSL_ASN_TEMPLATE
  31710. byte seqArray[5][MAX_SEQ_SZ];
  31711. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  31712. WOLFSSL_ENTER("SetOcspReqExtensions");
  31713. if (!req || !output || !req->nonceSz)
  31714. return 0;
  31715. totalSz += req->nonceSz;
  31716. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  31717. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  31718. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  31719. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  31720. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  31721. if (totalSz > size)
  31722. return 0;
  31723. totalSz = 0;
  31724. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  31725. totalSz += seqSz[4];
  31726. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  31727. totalSz += seqSz[3];
  31728. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  31729. totalSz += seqSz[2];
  31730. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  31731. totalSz += (word32)sizeof(NonceObjId);
  31732. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  31733. totalSz += seqSz[1];
  31734. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  31735. totalSz += seqSz[0];
  31736. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  31737. totalSz += req->nonceSz;
  31738. return totalSz;
  31739. #else
  31740. int ret = 0;
  31741. WOLFSSL_ENTER("SetOcspReqExtensions");
  31742. /* Check request has nonce to write in extension. */
  31743. if (req != NULL && req->nonceSz != 0) {
  31744. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  31745. int sz;
  31746. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  31747. /* Set nonce extension OID and nonce. */
  31748. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_OID], NonceObjId,
  31749. sizeof(NonceObjId));
  31750. SetASN_Buffer(&dataASN[OCSPNONCEEXTASN_IDX_EXT_NONCE], req->nonce,
  31751. req->nonceSz);
  31752. /* Calculate size of nonce extension. */
  31753. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31754. &sz);
  31755. /* Check buffer big enough for encoding if supplied. */
  31756. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31757. ret = BUFFER_E;
  31758. }
  31759. if ((ret == 0) && (output != NULL)) {
  31760. /* Encode nonce extension. */
  31761. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  31762. output);
  31763. }
  31764. if (ret == 0) {
  31765. /* Return size of encoding. */
  31766. ret = sz;
  31767. }
  31768. FREE_ASNSETDATA(dataASN, req->heap);
  31769. }
  31770. return ret;
  31771. #endif /* WOLFSSL_ASN_TEMPLATE */
  31772. }
  31773. #ifdef WOLFSSL_ASN_TEMPLATE
  31774. /* ASN.1 template for OCSPRequest.
  31775. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  31776. */
  31777. static const ASNItem ocspRequestASN[] = {
  31778. /* OCSPRequest */
  31779. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  31780. /* tbsRequest */
  31781. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  31782. /* version not written - v1 */
  31783. /* requestorName not written */
  31784. /* requestList */
  31785. /* TBS_SEQ */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  31786. /* Request */
  31787. /* TBS_LIST */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  31788. /* reqCert */
  31789. /* TBS_REQ_CID */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  31790. /* hashAlgorithm */
  31791. /* TBS_REQ_HASH */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  31792. /* TBS_REQ_HASH_OID */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  31793. /* issuerNameHash */
  31794. /* TBS_REQ_ISSUER */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31795. /* issuerKeyHash */
  31796. /* TBS_REQ_ISSUERKEY */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  31797. /* serialNumber */
  31798. /* TBS_REQ_SERIAL */ { 5, ASN_INTEGER, 0, 0, 0 },
  31799. /* requestExtensions */
  31800. /* TBS_REQEXT */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  31801. /* optionalSignature not written. */
  31802. };
  31803. enum {
  31804. OCSPREQUESTASN_IDX_SEQ = 0,
  31805. OCSPREQUESTASN_IDX_TBS,
  31806. OCSPREQUESTASN_IDX_TBS_SEQ,
  31807. OCSPREQUESTASN_IDX_TBS_LIST,
  31808. OCSPREQUESTASN_IDX_TBS_REQ_CID,
  31809. OCSPREQUESTASN_IDX_TBS_REQ_HASH,
  31810. OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID,
  31811. OCSPREQUESTASN_IDX_TBS_REQ_ISSUER,
  31812. OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY,
  31813. OCSPREQUESTASN_IDX_TBS_REQ_SERIAL,
  31814. OCSPREQUESTASN_IDX_TBS_REQEXT,
  31815. };
  31816. /* Number of items in ASN.1 template for OCSPRequest. */
  31817. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  31818. #endif
  31819. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  31820. {
  31821. #ifndef WOLFSSL_ASN_TEMPLATE
  31822. byte seqArray[5][MAX_SEQ_SZ];
  31823. /* The ASN.1 of the OCSP Request is an onion of sequences */
  31824. byte algoArray[MAX_ALGO_SZ];
  31825. byte issuerArray[MAX_ENCODED_DIG_SZ];
  31826. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  31827. byte snArray[MAX_SN_SZ];
  31828. byte extArray[MAX_OCSP_EXT_SZ];
  31829. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  31830. int i, snSz;
  31831. int keyIdSz;
  31832. WOLFSSL_ENTER("EncodeOcspRequest");
  31833. #ifdef NO_SHA
  31834. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  31835. keyIdSz = WC_SHA256_DIGEST_SIZE;
  31836. #else
  31837. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  31838. keyIdSz = WC_SHA_DIGEST_SIZE;
  31839. #endif
  31840. issuerSz = SetDigest(req->issuerHash, keyIdSz, issuerArray);
  31841. issuerKeySz = SetDigest(req->issuerKeyHash, keyIdSz, issuerKeyArray);
  31842. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  31843. MAX_SN_SZ, MAX_SN_SZ);
  31844. extSz = 0;
  31845. if (snSz < 0)
  31846. return snSz;
  31847. if (req->nonceSz) {
  31848. /* TLS Extensions use this function too - put extensions after
  31849. * ASN.1: Context Specific [2].
  31850. */
  31851. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  31852. OCSP_NONCE_EXT_SZ);
  31853. extSz += SetExplicit(2, extSz, extArray);
  31854. }
  31855. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  31856. for (i = 4; i >= 0; i--) {
  31857. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  31858. totalSz += seqSz[i];
  31859. if (i == 2) totalSz += extSz;
  31860. }
  31861. if (output == NULL)
  31862. return totalSz;
  31863. if (totalSz > size)
  31864. return BUFFER_E;
  31865. totalSz = 0;
  31866. for (i = 0; i < 5; i++) {
  31867. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  31868. totalSz += seqSz[i];
  31869. }
  31870. XMEMCPY(output + totalSz, algoArray, algoSz);
  31871. totalSz += algoSz;
  31872. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  31873. totalSz += issuerSz;
  31874. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  31875. totalSz += issuerKeySz;
  31876. XMEMCPY(output + totalSz, snArray, snSz);
  31877. totalSz += snSz;
  31878. if (extSz != 0) {
  31879. XMEMCPY(output + totalSz, extArray, extSz);
  31880. totalSz += extSz;
  31881. }
  31882. return totalSz;
  31883. #else
  31884. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  31885. word32 extSz = 0;
  31886. int sz = 0;
  31887. int ret = 0;
  31888. int keyIdSz;
  31889. WOLFSSL_ENTER("EncodeOcspRequest");
  31890. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  31891. if (ret == 0) {
  31892. /* Set OID of hash algorithm use on issuer and key. */
  31893. #ifdef NO_SHA
  31894. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHA256h,
  31895. oidHashType);
  31896. keyIdSz = WC_SHA256_DIGEST_SIZE;
  31897. #else
  31898. SetASN_OID(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_HASH_OID], SHAh,
  31899. oidHashType);
  31900. keyIdSz = WC_SHA_DIGEST_SIZE;
  31901. #endif
  31902. /* Set issuer, issuer key hash and serial number of certificate being
  31903. * checked. */
  31904. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUER],
  31905. req->issuerHash, keyIdSz);
  31906. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_ISSUERKEY],
  31907. req->issuerKeyHash, keyIdSz);
  31908. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQ_SERIAL],
  31909. req->serial, req->serialSz);
  31910. /* Only extension to write is nonce - check if one to encode. */
  31911. if (req->nonceSz) {
  31912. /* Get size of extensions and leave space for them in encoding. */
  31913. ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
  31914. SetASN_Buffer(&dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT], NULL, extSz);
  31915. if (ret > 0) {
  31916. ret = 0;
  31917. }
  31918. }
  31919. else {
  31920. /* Don't write out extensions. */
  31921. dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].noOut = 1;
  31922. }
  31923. }
  31924. if (ret == 0) {
  31925. /* Calculate size of encoding. */
  31926. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  31927. &sz);
  31928. }
  31929. /* Check buffer big enough for encoding if supplied. */
  31930. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  31931. ret = BUFFER_E;
  31932. }
  31933. if ((ret == 0) && (output != NULL)) {
  31934. /* Encode OCSPRequest. */
  31935. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  31936. if (req->nonceSz) {
  31937. /* Encode extensions into space provided. */
  31938. ret = EncodeOcspRequestExtensions(req,
  31939. (byte*)dataASN[OCSPREQUESTASN_IDX_TBS_REQEXT].data.buffer.data,
  31940. extSz);
  31941. if (ret > 0) {
  31942. ret = 0;
  31943. }
  31944. }
  31945. }
  31946. if (ret == 0) {
  31947. /* Return size of encoding. */
  31948. ret = sz;
  31949. }
  31950. FREE_ASNSETDATA(dataASN, req->heap);
  31951. return ret;
  31952. #endif /* WOLFSSL_ASN_TEMPLATE */
  31953. }
  31954. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  31955. void* heap)
  31956. {
  31957. int ret;
  31958. WOLFSSL_ENTER("InitOcspRequest");
  31959. if (req == NULL)
  31960. return BAD_FUNC_ARG;
  31961. XMEMSET(req, 0, sizeof(OcspRequest));
  31962. req->heap = heap;
  31963. if (cert) {
  31964. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  31965. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  31966. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  31967. DYNAMIC_TYPE_OCSP_REQUEST);
  31968. if (req->serial == NULL)
  31969. return MEMORY_E;
  31970. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  31971. req->serialSz = cert->serialSz;
  31972. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  31973. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  31974. DYNAMIC_TYPE_OCSP_REQUEST);
  31975. if (req->url == NULL) {
  31976. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  31977. req->serial = NULL;
  31978. return MEMORY_E;
  31979. }
  31980. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  31981. req->urlSz = cert->extAuthInfoSz;
  31982. req->url[req->urlSz] = 0;
  31983. }
  31984. }
  31985. if (useNonce) {
  31986. WC_RNG rng;
  31987. #ifndef HAVE_FIPS
  31988. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  31989. #else
  31990. ret = wc_InitRng(&rng);
  31991. #endif
  31992. if (ret != 0) {
  31993. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OCSP Nonce.");
  31994. } else {
  31995. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  31996. WOLFSSL_MSG("\tCannot run RNG. Skipping the OCSP Nonce.");
  31997. else
  31998. req->nonceSz = MAX_OCSP_NONCE_SZ;
  31999. wc_FreeRng(&rng);
  32000. }
  32001. }
  32002. return 0;
  32003. }
  32004. void FreeOcspRequest(OcspRequest* req)
  32005. {
  32006. WOLFSSL_ENTER("FreeOcspRequest");
  32007. if (req) {
  32008. if (req->serial)
  32009. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32010. req->serial = NULL;
  32011. #ifdef OPENSSL_EXTRA
  32012. if (req->serialInt) {
  32013. if (req->serialInt->isDynamic) {
  32014. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  32015. }
  32016. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  32017. }
  32018. req->serialInt = NULL;
  32019. #endif
  32020. if (req->url)
  32021. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  32022. req->url = NULL;
  32023. }
  32024. }
  32025. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  32026. {
  32027. int cmp = -1; /* default as not matching, cmp gets set on each check */
  32028. int ocspDigestSize;
  32029. OcspEntry *single, *next, *prev = NULL, *top;
  32030. WOLFSSL_ENTER("CompareOcspReqResp");
  32031. if (req == NULL) {
  32032. WOLFSSL_MSG("\tReq missing");
  32033. return -1;
  32034. }
  32035. if (resp == NULL || resp->single == NULL) {
  32036. WOLFSSL_MSG("\tResp missing");
  32037. return 1;
  32038. }
  32039. /* Nonces are not critical. The responder may not necessarily add
  32040. * the nonce to the response. */
  32041. if (req->nonceSz && resp->nonce != NULL
  32042. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  32043. && resp->nonceSz != 0
  32044. #endif
  32045. ) {
  32046. cmp = req->nonceSz - resp->nonceSz;
  32047. if (cmp != 0) {
  32048. WOLFSSL_MSG("\tnonceSz mismatch");
  32049. return cmp;
  32050. }
  32051. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  32052. if (cmp != 0) {
  32053. WOLFSSL_MSG("\tnonce mismatch");
  32054. return cmp;
  32055. }
  32056. }
  32057. /* match based on found status and return */
  32058. for (single = resp->single; single; single = next) {
  32059. #if defined(WOLFSSL_SM2) && defined(WOLFSSL_SM3)
  32060. ocspDigestSize = wc_HashGetDigestSize(
  32061. wc_OidGetHash(single->hashAlgoOID));
  32062. #else
  32063. ocspDigestSize = OCSP_DIGEST_SIZE;
  32064. #endif
  32065. cmp = req->serialSz - single->status->serialSz;
  32066. if (cmp == 0) {
  32067. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  32068. || XMEMCMP(req->issuerHash, single->issuerHash, ocspDigestSize)
  32069. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, ocspDigestSize);
  32070. if (cmp == 0) {
  32071. /* match found */
  32072. if (resp->single != single && prev) {
  32073. /* move to top of list */
  32074. top = resp->single;
  32075. resp->single = single;
  32076. prev->next = single->next;
  32077. single->next = top;
  32078. }
  32079. break;
  32080. }
  32081. }
  32082. next = single->next;
  32083. prev = single;
  32084. }
  32085. if (cmp != 0) {
  32086. WOLFSSL_MSG("\trequest and response mismatch");
  32087. return cmp;
  32088. }
  32089. return 0;
  32090. }
  32091. #endif /* HAVE_OCSP */
  32092. #ifdef WOLFSSL_ASN_TEMPLATE
  32093. /* ASN.1 template for certificate name hash. */
  32094. static const ASNItem nameHashASN[] = {
  32095. /* OID */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  32096. /* NAME */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  32097. };
  32098. enum {
  32099. NAMEHASHASN_IDX_OID = 0,
  32100. NAMEHASHASN_IDX_NAME
  32101. };
  32102. /* Number of items in ASN.1 template for certificate name hash. */
  32103. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  32104. #endif /* WOLFSSL_ASN_TEMPLATE */
  32105. /* store WC_SHA hash of NAME */
  32106. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  32107. {
  32108. /* Use summy signature OID. */
  32109. return GetNameHash_ex(source, idx, hash, maxIdx, 0);
  32110. }
  32111. /* store WC_SHA hash of NAME */
  32112. int GetNameHash_ex(const byte* source, word32* idx, byte* hash, int maxIdx,
  32113. int sigOID)
  32114. {
  32115. #ifndef WOLFSSL_ASN_TEMPLATE
  32116. int length; /* length of all distinguished names */
  32117. int ret;
  32118. word32 dummy;
  32119. byte tag;
  32120. WOLFSSL_ENTER("GetNameHash");
  32121. dummy = *idx;
  32122. if (GetASNTag(source, &dummy, &tag, (word32)maxIdx) == 0 &&
  32123. tag == ASN_OBJECT_ID) {
  32124. WOLFSSL_MSG("Trying optional prefix...");
  32125. if (GetLength(source, idx, &length, (word32)maxIdx) < 0)
  32126. return ASN_PARSE_E;
  32127. *idx += (word32)length;
  32128. WOLFSSL_MSG("Got optional prefix");
  32129. }
  32130. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  32131. * calculated over the entire DER encoding of the Name field, including
  32132. * the tag and length. */
  32133. dummy = *idx;
  32134. if (GetSequence(source, idx, &length, (word32)maxIdx) < 0)
  32135. return ASN_PARSE_E;
  32136. ret = CalcHashId_ex(source + dummy, (word32)length + *idx - dummy, hash,
  32137. HashIdAlg(sigOID));
  32138. *idx += (word32)length;
  32139. return ret;
  32140. #else
  32141. ASNGetData dataASN[nameHashASN_Length];
  32142. int ret;
  32143. XMEMSET(dataASN, 0, sizeof(dataASN));
  32144. /* Ignore the OID even when present. */
  32145. GetASN_OID(&dataASN[NAMEHASHASN_IDX_OID], oidIgnoreType);
  32146. /* Decode certificate name. */
  32147. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  32148. (word32)maxIdx);
  32149. if (ret == 0) {
  32150. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  32151. * calculated over the entire DER encoding of the Name field, including
  32152. * the tag and length. */
  32153. /* Calculate hash of complete name including SEQUENCE. */
  32154. ret = CalcHashId_ex(
  32155. GetASNItem_Addr(dataASN[NAMEHASHASN_IDX_NAME], source),
  32156. GetASNItem_Length(dataASN[NAMEHASHASN_IDX_NAME], source),
  32157. hash, HashIdAlg(sigOID));
  32158. }
  32159. return ret;
  32160. #endif /* WOLFSSL_ASN_TEMPLATE */
  32161. }
  32162. #if defined(HAVE_CRL) && !defined(WOLFCRYPT_ONLY)
  32163. #ifdef OPENSSL_EXTRA
  32164. static char* GetNameFromDer(const byte* source, int sz)
  32165. {
  32166. char* out;
  32167. out = (char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_OPENSSL);
  32168. if (out == NULL) {
  32169. WOLFSSL_MSG("Name malloc failed");
  32170. return NULL;
  32171. }
  32172. XMEMCPY(out, source, sz);
  32173. return out;
  32174. }
  32175. #endif
  32176. /* initialize decoded CRL */
  32177. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  32178. {
  32179. WOLFSSL_MSG("InitDecodedCRL");
  32180. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  32181. dcrl->heap = heap;
  32182. #ifdef WOLFSSL_HEAP_TEST
  32183. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  32184. #endif
  32185. }
  32186. /* free decoded CRL resources */
  32187. void FreeDecodedCRL(DecodedCRL* dcrl)
  32188. {
  32189. RevokedCert* tmp = dcrl->certs;
  32190. WOLFSSL_MSG("FreeDecodedCRL");
  32191. while(tmp) {
  32192. RevokedCert* next = tmp->next;
  32193. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32194. tmp = next;
  32195. }
  32196. #ifdef OPENSSL_EXTRA
  32197. if (dcrl->issuer != NULL)
  32198. XFREE(dcrl->issuer, NULL, DYNAMIC_TYPE_OPENSSL);
  32199. #endif
  32200. }
  32201. #ifdef WOLFSSL_ASN_TEMPLATE
  32202. /* ASN.1 template for revoked certificates.
  32203. * X.509: RFC 5280, 5.1 - CRL Fields
  32204. */
  32205. static const ASNItem revokedASN[] = {
  32206. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32207. /* userCertificate CertificateSerialNumber */
  32208. /* CERT */ { 1, ASN_INTEGER, 0, 0, 0 },
  32209. /* revocationDate Time */
  32210. /* TIME_UTC */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  32211. /* TIME_GT */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32212. /* crlEntryExensions Extensions */
  32213. /* TIME_EXT */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  32214. };
  32215. enum {
  32216. REVOKEDASN_IDX_SEQ = 0,
  32217. REVOKEDASN_IDX_CERT,
  32218. REVOKEDASN_IDX_TIME_UTC,
  32219. REVOKEDASN_IDX_TIME_GT,
  32220. REVOKEDASN_IDX_TIME_EXT,
  32221. };
  32222. /* Number of items in ASN.1 template for revoked certificates. */
  32223. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  32224. #endif
  32225. /* Get Revoked Cert list, 0 on success */
  32226. static int GetRevoked(RevokedCert* rcert, const byte* buff, word32* idx,
  32227. DecodedCRL* dcrl, int maxIdx)
  32228. {
  32229. #ifndef WOLFSSL_ASN_TEMPLATE
  32230. int ret;
  32231. int len;
  32232. word32 end;
  32233. RevokedCert* rc;
  32234. #ifdef CRL_STATIC_REVOKED_LIST
  32235. int totalCerts = 0;
  32236. #endif
  32237. WOLFSSL_ENTER("GetRevoked");
  32238. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  32239. return ASN_PARSE_E;
  32240. end = *idx + len;
  32241. #ifdef CRL_STATIC_REVOKED_LIST
  32242. totalCerts = dcrl->totalCerts;
  32243. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32244. return MEMORY_E;
  32245. }
  32246. rc = &rcert[totalCerts];
  32247. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32248. if (ret < 0) {
  32249. WOLFSSL_MSG("wc_GetSerialNumber error");
  32250. return ret;
  32251. }
  32252. #else
  32253. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32254. DYNAMIC_TYPE_REVOKED);
  32255. if (rc == NULL) {
  32256. WOLFSSL_MSG("Alloc Revoked Cert failed");
  32257. return MEMORY_E;
  32258. }
  32259. ret = wc_GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,maxIdx);
  32260. if (ret < 0) {
  32261. WOLFSSL_MSG("wc_GetSerialNumber error");
  32262. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  32263. return ret;
  32264. }
  32265. /* add to list */
  32266. rc->next = dcrl->certs;
  32267. dcrl->certs = rc;
  32268. (void)rcert;
  32269. #endif /* CRL_STATIC_REVOKED_LIST */
  32270. dcrl->totalCerts++;
  32271. /* get date */
  32272. #ifndef NO_ASN_TIME
  32273. ret = GetBasicDate(buff, idx, rc->revDate, &rc->revDateFormat, maxIdx);
  32274. if (ret < 0) {
  32275. WOLFSSL_MSG("Expecting Date");
  32276. return ret;
  32277. }
  32278. #endif
  32279. /* skip extensions */
  32280. *idx = end;
  32281. return 0;
  32282. #else
  32283. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  32284. int ret = 0;
  32285. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  32286. word32 revDateSz = MAX_DATE_SIZE;
  32287. RevokedCert* rc;
  32288. #ifdef CRL_STATIC_REVOKED_LIST
  32289. int totalCerts = dcrl->totalCerts;
  32290. if (totalCerts >= CRL_MAX_REVOKED_CERTS) {
  32291. return MEMORY_E;
  32292. }
  32293. rc = &rcert[totalCerts];
  32294. #else
  32295. /* Allocate a new revoked certificate object. */
  32296. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  32297. DYNAMIC_TYPE_CRL);
  32298. if (rc == NULL) {
  32299. ret = MEMORY_E;
  32300. }
  32301. #endif /* CRL_STATIC_REVOKED_LIST */
  32302. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  32303. if (ret == 0) {
  32304. /* Set buffer to place serial number into. */
  32305. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_CERT], rc->serialNumber,
  32306. &serialSz);
  32307. /* Set buffer to store revocation date. */
  32308. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_UTC], rc->revDate,
  32309. &revDateSz);
  32310. GetASN_Buffer(&dataASN[REVOKEDASN_IDX_TIME_GT], rc->revDate,
  32311. &revDateSz);
  32312. /* Decode the Revoked */
  32313. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  32314. maxIdx);
  32315. }
  32316. if (ret == 0) {
  32317. /* Store size of serial number. */
  32318. rc->serialSz = serialSz;
  32319. rc->revDateFormat = (dataASN[REVOKEDASN_IDX_TIME_UTC].tag != 0)
  32320. ? dataASN[REVOKEDASN_IDX_TIME_UTC].tag
  32321. : dataASN[REVOKEDASN_IDX_TIME_GT].tag;
  32322. /* TODO: use extensions, only v2 */
  32323. /* Add revoked certificate to chain. */
  32324. #ifndef CRL_STATIC_REVOKED_LIST
  32325. rc->next = dcrl->certs;
  32326. dcrl->certs = rc;
  32327. #endif
  32328. dcrl->totalCerts++;
  32329. }
  32330. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32331. #ifndef CRL_STATIC_REVOKED_LIST
  32332. if ((ret != 0) && (rc != NULL)) {
  32333. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  32334. }
  32335. (void)rcert;
  32336. #endif
  32337. return ret;
  32338. #endif /* WOLFSSL_ASN_TEMPLATE */
  32339. }
  32340. #ifdef WOLFSSL_ASN_TEMPLATE
  32341. /* Parse the revoked certificates of a CRL.
  32342. *
  32343. * @param [in] dcrl Decoded CRL object.
  32344. * @param [in] buff Buffer holding CRL.
  32345. * @param [in] idx Index into buffer of revoked certificates.
  32346. * @param [in] maxIdx Maximum index of revoked cartificates data.
  32347. * @return 0 on success.
  32348. * @return ASN_PARSE_E on failure.
  32349. */
  32350. static int ParseCRL_RevokedCerts(RevokedCert* rcert, DecodedCRL* dcrl,
  32351. const byte* buff, word32 idx, word32 maxIdx)
  32352. {
  32353. int ret = 0;
  32354. /* Parse each revoked cerificate. */
  32355. while ((ret == 0) && (idx < maxIdx)) {
  32356. /* Parse a revoked certificate. */
  32357. if (GetRevoked(rcert, buff, &idx, dcrl, maxIdx) < 0) {
  32358. ret = ASN_PARSE_E;
  32359. }
  32360. }
  32361. return ret;
  32362. }
  32363. #endif /* WOLFSSL_ASN_TEMPLATE */
  32364. #ifndef WOLFSSL_ASN_TEMPLATE
  32365. /* Get CRL Signature, 0 on success */
  32366. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  32367. int maxIdx)
  32368. {
  32369. int length;
  32370. int ret;
  32371. WOLFSSL_ENTER("GetCRL_Signature");
  32372. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  32373. if (ret != 0)
  32374. return ret;
  32375. dcrl->sigLength = length;
  32376. dcrl->signature = (byte*)&source[*idx];
  32377. *idx += dcrl->sigLength;
  32378. return 0;
  32379. }
  32380. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32381. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  32382. word32 tbsSz, const byte* signature, word32 sigSz,
  32383. word32 signatureOID, Signer *ca, void* heap)
  32384. {
  32385. /* try to confirm/verify signature */
  32386. #ifndef IGNORE_KEY_EXTENSIONS
  32387. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  32388. WOLFSSL_MSG("CA cannot sign CRLs");
  32389. WOLFSSL_ERROR_VERBOSE(ASN_CRL_NO_SIGNER_E);
  32390. return ASN_CRL_NO_SIGNER_E;
  32391. }
  32392. #endif /* IGNORE_KEY_EXTENSIONS */
  32393. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  32394. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  32395. ca->pubKeySize, ca->keyOID, signature, sigSz,
  32396. signatureOID, NULL, 0, NULL) != 0) {
  32397. WOLFSSL_MSG("CRL Confirm signature failed");
  32398. WOLFSSL_ERROR_VERBOSE(ASN_CRL_CONFIRM_E);
  32399. return ASN_CRL_CONFIRM_E;
  32400. }
  32401. return 0;
  32402. }
  32403. #ifdef WOLFSSL_ASN_TEMPLATE
  32404. /* Find the signer for the CRL and verify the signature.
  32405. *
  32406. * @param [in] dcrl Decoded CRL object.
  32407. * @param [in] buff Buffer holding CRL.
  32408. * @param [in] cm Certificate manager object.
  32409. * @return 0 on success.
  32410. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  32411. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  32412. */
  32413. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  32414. {
  32415. int ret = 0;
  32416. Signer* ca = NULL;
  32417. SignatureCtx sigCtx;
  32418. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  32419. * If experiencing issues uncomment NO_SKID define in CRL section of
  32420. * wolfssl/wolfcrypt/settings.h */
  32421. #ifndef NO_SKID
  32422. if (dcrl->extAuthKeyIdSet) {
  32423. /* more unique than issuerHash */
  32424. ca = GetCA(cm, dcrl->extAuthKeyId);
  32425. }
  32426. /* Check issuerHash matched CA's subjectNameHash. */
  32427. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32428. KEYID_SIZE) != 0)) {
  32429. ca = NULL;
  32430. }
  32431. if (ca == NULL) {
  32432. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32433. /* If AKID is available then this CA doesn't have the public
  32434. * key required */
  32435. if (ca && dcrl->extAuthKeyIdSet) {
  32436. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32437. ca = NULL;
  32438. }
  32439. }
  32440. #else
  32441. ca = GetCA(cm, dcrl->issuerHash);
  32442. #endif /* !NO_SKID */
  32443. WOLFSSL_MSG("About to verify CRL signature");
  32444. if (ca == NULL) {
  32445. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32446. ret = ASN_CRL_NO_SIGNER_E;
  32447. WOLFSSL_ERROR_VERBOSE(ret);
  32448. }
  32449. if (ret == 0) {
  32450. WOLFSSL_MSG("Found CRL issuer CA");
  32451. /* Verify CRL signature with CA. */
  32452. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32453. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32454. dcrl->signatureOID, ca, dcrl->heap);
  32455. }
  32456. return ret;
  32457. }
  32458. #endif
  32459. #ifndef WOLFSSL_ASN_TEMPLATE
  32460. static int ParseCRL_CertList(RevokedCert* rcert, DecodedCRL* dcrl,
  32461. const byte* buf,word32* inOutIdx, int sz, int verify)
  32462. {
  32463. word32 oid, dateIdx, idx, checkIdx;
  32464. int length;
  32465. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32466. int doNextDate = 1;
  32467. #endif
  32468. byte tag;
  32469. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  32470. return BAD_FUNC_ARG;
  32471. }
  32472. /* may have version */
  32473. idx = *inOutIdx;
  32474. checkIdx = idx;
  32475. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  32476. if (GetMyVersion(buf, &idx, &dcrl->version, sz) < 0)
  32477. return ASN_PARSE_E;
  32478. dcrl->version++;
  32479. }
  32480. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  32481. return ASN_PARSE_E;
  32482. checkIdx = idx;
  32483. if (GetSequence(buf, &checkIdx, &length, sz) < 0) {
  32484. return ASN_PARSE_E;
  32485. }
  32486. #ifdef OPENSSL_EXTRA
  32487. dcrl->issuerSz = length + (checkIdx - idx);
  32488. dcrl->issuer = (byte*)GetNameFromDer(buf + idx, (int)dcrl->issuerSz);
  32489. #endif
  32490. if (GetNameHash_ex(buf, &idx, dcrl->issuerHash, sz, oid) < 0)
  32491. return ASN_PARSE_E;
  32492. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  32493. return ASN_PARSE_E;
  32494. dateIdx = idx;
  32495. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  32496. {
  32497. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  32498. (void)dateIdx;
  32499. return ASN_PARSE_E;
  32500. #else
  32501. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  32502. doNextDate = 0;
  32503. idx = dateIdx;
  32504. #endif
  32505. }
  32506. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  32507. if (doNextDate)
  32508. #endif
  32509. {
  32510. #ifndef NO_ASN_TIME
  32511. if (verify != NO_VERIFY &&
  32512. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32513. WOLFSSL_MSG("CRL after date is no longer valid");
  32514. WOLFSSL_ERROR_VERBOSE(CRL_CERT_DATE_ERR);
  32515. return CRL_CERT_DATE_ERR;
  32516. }
  32517. #else
  32518. (void)verify;
  32519. #endif
  32520. }
  32521. checkIdx = idx;
  32522. if (idx != dcrl->sigIndex &&
  32523. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  32524. int len;
  32525. if (GetSequence(buf, &idx, &len, sz) < 0)
  32526. return ASN_PARSE_E;
  32527. len += idx;
  32528. while (idx < (word32)len) {
  32529. if (GetRevoked(rcert, buf, &idx, dcrl, len) < 0)
  32530. return ASN_PARSE_E;
  32531. }
  32532. }
  32533. *inOutIdx = idx;
  32534. return 0;
  32535. }
  32536. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32537. #ifndef NO_SKID
  32538. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  32539. {
  32540. #ifndef WOLFSSL_ASN_TEMPLATE
  32541. word32 idx = 0;
  32542. int length = 0, ret = 0;
  32543. byte tag;
  32544. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32545. if (GetSequence(input, &idx, &length, sz) < 0) {
  32546. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32547. return ASN_PARSE_E;
  32548. }
  32549. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  32550. return ASN_PARSE_E;
  32551. }
  32552. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  32553. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32554. return 0;
  32555. }
  32556. if (GetLength(input, &idx, &length, sz) <= 0) {
  32557. WOLFSSL_MSG("\tfail: extension data length");
  32558. return ASN_PARSE_E;
  32559. }
  32560. dcrl->extAuthKeyIdSet = 1;
  32561. /* Get the hash or hash of the hash if wrong size. */
  32562. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId,
  32563. HashIdAlg(dcrl->signatureOID));
  32564. return ret;
  32565. #else
  32566. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  32567. int ret = 0;
  32568. word32 idx = 0;
  32569. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  32570. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  32571. if (ret == 0) {
  32572. /* Parse an authority key identifier. */
  32573. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  32574. &idx, sz);
  32575. }
  32576. if (ret == 0) {
  32577. /* Key id is optional. */
  32578. if (dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data == NULL) {
  32579. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  32580. }
  32581. else {
  32582. /* Get the hash or hash of the hash if wrong size. */
  32583. ret = GetHashId(dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.data,
  32584. dataASN[AUTHKEYIDASN_IDX_KEYID].data.ref.length,
  32585. dcrl->extAuthKeyId, HashIdAlg(dcrl->signatureOID));
  32586. }
  32587. }
  32588. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32589. return ret;
  32590. #endif /* WOLFSSL_ASN_TEMPLATE */
  32591. }
  32592. #endif
  32593. #ifndef WOLFSSL_ASN_TEMPLATE
  32594. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  32595. word32* inOutIdx, word32 sz)
  32596. {
  32597. int length;
  32598. word32 idx;
  32599. word32 ext_bound; /* boundary index for the sequence of extensions */
  32600. word32 oid;
  32601. byte tag;
  32602. WOLFSSL_ENTER("ParseCRL_Extensions");
  32603. (void)dcrl;
  32604. if (inOutIdx == NULL)
  32605. return BAD_FUNC_ARG;
  32606. idx = *inOutIdx;
  32607. /* CRL Extensions are optional */
  32608. if ((idx + 1) > sz)
  32609. return 0;
  32610. /* CRL Extensions are optional */
  32611. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  32612. return 0;
  32613. /* CRL Extensions are optional */
  32614. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  32615. return 0;
  32616. if (GetLength(buf, &idx, &length, sz) < 0)
  32617. return ASN_PARSE_E;
  32618. if (GetSequence(buf, &idx, &length, sz) < 0)
  32619. return ASN_PARSE_E;
  32620. ext_bound = idx + length;
  32621. while (idx < (word32)ext_bound) {
  32622. word32 localIdx;
  32623. int ret;
  32624. if (GetSequence(buf, &idx, &length, sz) < 0) {
  32625. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  32626. return ASN_PARSE_E;
  32627. }
  32628. oid = 0;
  32629. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  32630. WOLFSSL_MSG("\tfail: OBJECT ID");
  32631. return ASN_PARSE_E;
  32632. }
  32633. /* check for critical flag */
  32634. if ((idx + 1) > (word32)sz) {
  32635. WOLFSSL_MSG("\tfail: malformed buffer");
  32636. return BUFFER_E;
  32637. }
  32638. localIdx = idx;
  32639. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  32640. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  32641. ret = GetBoolean(buf, &idx, sz);
  32642. if (ret < 0)
  32643. return ret;
  32644. }
  32645. ret = GetOctetString(buf, &idx, &length, sz);
  32646. if (ret < 0)
  32647. return ret;
  32648. if (oid == AUTH_KEY_OID) {
  32649. #ifndef NO_SKID
  32650. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32651. if (ret < 0) {
  32652. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32653. return ret;
  32654. }
  32655. #endif
  32656. }
  32657. else if (oid == CRL_NUMBER_OID) {
  32658. localIdx = idx;
  32659. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 &&
  32660. tag == ASN_INTEGER) {
  32661. ret = GetASNInt(buf, &idx, &length, sz);
  32662. if (ret < 0) {
  32663. WOLFSSL_MSG("\tcouldn't parse CRL number extension");
  32664. return ret;
  32665. }
  32666. else {
  32667. if (length > 1) {
  32668. int i;
  32669. #ifdef WOLFSSL_SMALL_STACK
  32670. mp_int* m = (mp_int*)XMALLOC(sizeof(*m), NULL,
  32671. DYNAMIC_TYPE_BIGINT);
  32672. if (m == NULL) {
  32673. return MEMORY_E;
  32674. }
  32675. #else
  32676. mp_int m[1];
  32677. #endif
  32678. if (mp_init(m) != MP_OKAY) {
  32679. ret = MP_INIT_E;
  32680. }
  32681. if (ret == 0)
  32682. ret = mp_read_unsigned_bin(m, buf + idx, length);
  32683. if (ret != MP_OKAY)
  32684. ret = BUFFER_E;
  32685. if (ret == 0) {
  32686. dcrl->crlNumber = 0;
  32687. for (i = 0; i < (int)(*m).used; ++i) {
  32688. if (i > (CHAR_BIT *
  32689. (int)sizeof(word32) / DIGIT_BIT)) {
  32690. break;
  32691. }
  32692. dcrl->crlNumber |= ((word32)(*m).dp[i]) <<
  32693. (DIGIT_BIT * i);
  32694. }
  32695. }
  32696. mp_free(m);
  32697. #ifdef WOLFSSL_SMALL_STACK
  32698. XFREE(m, NULL, DYNAMIC_TYPE_BIGINT);
  32699. #endif
  32700. if (ret != 0)
  32701. return ret;
  32702. }
  32703. else if (length == 1) {
  32704. dcrl->crlNumber = buf[idx];
  32705. }
  32706. }
  32707. }
  32708. }
  32709. idx += length;
  32710. }
  32711. *inOutIdx = idx;
  32712. return 0;
  32713. }
  32714. #else
  32715. /* Parse the extensions of a CRL.
  32716. *
  32717. * @param [in] dcrl Decoded CRL object.
  32718. * @param [in] buff Buffer holding CRL.
  32719. * @param [in] idx Index into buffer of extensions.
  32720. * @param [in] maxIdx Maximum index of extension data.
  32721. * @return 0 on success.
  32722. * @return ASN_PARSE_E on failure.
  32723. */
  32724. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  32725. word32 maxIdx)
  32726. {
  32727. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  32728. int ret = 0;
  32729. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  32730. while ((ret == 0) && (idx < maxIdx)) {
  32731. byte critical = 0;
  32732. /* Clear dynamic data. */
  32733. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  32734. /* Ensure OID is an extention type. */
  32735. GetASN_OID(&dataASN[CERTEXTASN_IDX_OID], oidCertExtType);
  32736. /* Set criticality variable. */
  32737. GetASN_Int8Bit(&dataASN[CERTEXTASN_IDX_CRIT], &critical);
  32738. /* Parse extension wrapper. */
  32739. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  32740. maxIdx);
  32741. if (ret == 0) {
  32742. /* OID in extension. */
  32743. word32 oid = dataASN[CERTEXTASN_IDX_OID].data.oid.sum;
  32744. /* Length of extension data. */
  32745. int length = dataASN[CERTEXTASN_IDX_VAL].length;
  32746. if (oid == AUTH_KEY_OID) {
  32747. #ifndef NO_SKID
  32748. /* Parse Authority Key Id extesion.
  32749. * idx is at start of OCTET_STRING data. */
  32750. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  32751. if (ret != 0) {
  32752. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  32753. }
  32754. #endif
  32755. }
  32756. /* TODO: Parse CRL Number extension */
  32757. /* TODO: check criticality */
  32758. /* Move index on to next extension. */
  32759. idx += length;
  32760. }
  32761. }
  32762. if (ret < 0) {
  32763. ret = ASN_PARSE_E;
  32764. }
  32765. FREE_ASNGETDATA(dataASN, dcrl->heap);
  32766. return ret;
  32767. }
  32768. #endif /* !WOLFSSL_ASN_TEMPLATE */
  32769. #ifdef WOLFSSL_ASN_TEMPLATE
  32770. /* ASN.1 template for a CRL- CertificateList.
  32771. * X.509: RFC 5280, 5.1 - CRL Fields
  32772. */
  32773. static const ASNItem crlASN[] = {
  32774. /* CertificateList */
  32775. /* SEQ */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  32776. /* tbsCertList */
  32777. /* TBS */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32778. /* version Version OPTIONAL if present must be v2 */
  32779. /* TBS_VER */ { 2, ASN_INTEGER, 0, 0, 1 },
  32780. /* signature */
  32781. /* TBS_SIGALGO */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  32782. /* TBS_SIGALGO_OID */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  32783. /* TBS_SIGALGO_NULL */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  32784. /* issuer */
  32785. /* TBS_ISSUER */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  32786. /* thisUpdate */
  32787. /* TBS_THISUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  32788. /* TBS_THISUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  32789. /* nextUpdate */
  32790. /* TBS_NEXTUPDATE_UTC */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  32791. /* TBS_NEXTUPDATE_GT */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  32792. /* revokedCertificates */
  32793. /* TBS_REVOKEDCERTS */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  32794. /* crlExtensions */
  32795. /* TBS_EXT */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  32796. /* TBS_EXT_SEQ */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  32797. /* signatureAlgorithm */
  32798. /* SIGALGO */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  32799. /* SIGALGO_OID */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  32800. /* SIGALGO_NULL */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  32801. /* signatureValue */
  32802. /* SIGNATURE */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  32803. };
  32804. enum {
  32805. CRLASN_IDX_SEQ = 0,
  32806. CRLASN_IDX_TBS,
  32807. CRLASN_IDX_TBS_VER,
  32808. CRLASN_IDX_TBS_SIGALGO,
  32809. CRLASN_IDX_TBS_SIGALGO_OID,
  32810. CRLASN_IDX_TBS_SIGALGO_NULL,
  32811. CRLASN_IDX_TBS_ISSUER,
  32812. CRLASN_IDX_TBS_THISUPDATE_UTC,
  32813. CRLASN_IDX_TBS_THISUPDATE_GT,
  32814. CRLASN_IDX_TBS_NEXTUPDATE_UTC,
  32815. CRLASN_IDX_TBS_NEXTUPDATE_GT,
  32816. CRLASN_IDX_TBS_REVOKEDCERTS,
  32817. CRLASN_IDX_TBS_EXT,
  32818. CRLASN_IDX_TBS_EXT_SEQ,
  32819. CRLASN_IDX_SIGALGO,
  32820. CRLASN_IDX_SIGALGO_OID,
  32821. CRLASN_IDX_SIGALGO_NULL,
  32822. CRLASN_IDX_SIGNATURE,
  32823. };
  32824. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  32825. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  32826. #endif
  32827. /* parse crl buffer into decoded state, 0 on success */
  32828. int ParseCRL(RevokedCert* rcert, DecodedCRL* dcrl, const byte* buff, word32 sz,
  32829. int verify, void* cm)
  32830. {
  32831. #ifndef WOLFSSL_ASN_TEMPLATE
  32832. Signer* ca = NULL;
  32833. SignatureCtx sigCtx;
  32834. int ret = 0;
  32835. int len;
  32836. word32 idx = 0;
  32837. WOLFSSL_MSG("ParseCRL");
  32838. /* raw crl hash */
  32839. /* hash here if needed for optimized comparisons
  32840. * wc_Sha sha;
  32841. * wc_InitSha(&sha);
  32842. * wc_ShaUpdate(&sha, buff, sz);
  32843. * wc_ShaFinal(&sha, dcrl->crlHash); */
  32844. if (GetSequence(buff, &idx, &len, sz) < 0)
  32845. return ASN_PARSE_E;
  32846. dcrl->certBegin = idx;
  32847. /* Normalize sz for the length inside the outer sequence. */
  32848. sz = len + idx;
  32849. if (GetSequence(buff, &idx, &len, sz) < 0)
  32850. return ASN_PARSE_E;
  32851. dcrl->sigIndex = len + idx;
  32852. if (ParseCRL_CertList(rcert, dcrl, buff, &idx, dcrl->sigIndex, verify) < 0)
  32853. return ASN_PARSE_E;
  32854. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  32855. return ASN_PARSE_E;
  32856. idx = dcrl->sigIndex;
  32857. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  32858. return ASN_PARSE_E;
  32859. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  32860. return ASN_PARSE_E;
  32861. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  32862. if experiencing issues uncomment NO_SKID define in CRL section of
  32863. wolfssl/wolfcrypt/settings.h */
  32864. #ifndef NO_SKID
  32865. if (dcrl->extAuthKeyIdSet) {
  32866. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  32867. }
  32868. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  32869. KEYID_SIZE) != 0) {
  32870. ca = NULL;
  32871. }
  32872. if (ca == NULL) {
  32873. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  32874. /* If AKID is available then this CA doesn't have the public
  32875. * key required */
  32876. if (ca && dcrl->extAuthKeyIdSet) {
  32877. WOLFSSL_MSG("CA SKID doesn't match AKID");
  32878. ca = NULL;
  32879. }
  32880. }
  32881. #else
  32882. ca = GetCA(cm, dcrl->issuerHash);
  32883. #endif /* !NO_SKID */
  32884. WOLFSSL_MSG("About to verify CRL signature");
  32885. if (ca == NULL) {
  32886. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  32887. ret = ASN_CRL_NO_SIGNER_E;
  32888. WOLFSSL_ERROR_VERBOSE(ret);
  32889. goto end;
  32890. }
  32891. WOLFSSL_MSG("Found CRL issuer CA");
  32892. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  32893. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  32894. dcrl->signatureOID, ca, dcrl->heap);
  32895. end:
  32896. return ret;
  32897. #else
  32898. DECL_ASNGETDATA(dataASN, crlASN_Length);
  32899. int ret = 0;
  32900. /* Default version - v1 = 0 */
  32901. byte version = 0;
  32902. word32 idx = 0;
  32903. /* Size of buffer for date. */
  32904. word32 lastDateSz = MAX_DATE_SIZE;
  32905. word32 nextDateSz = MAX_DATE_SIZE;
  32906. /* When NO_ASN_TIME is defined, verify not used. */
  32907. (void)verify;
  32908. WOLFSSL_MSG("ParseCRL");
  32909. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  32910. if (ret == 0) {
  32911. /* Set variable to store version. */
  32912. GetASN_Int8Bit(&dataASN[CRLASN_IDX_TBS_VER], &version);
  32913. /* Set expecting signature OID. */
  32914. GetASN_OID(&dataASN[CRLASN_IDX_TBS_SIGALGO_OID], oidSigType);
  32915. /* Set buffer to put last and next date into. */
  32916. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC], dcrl->lastDate,
  32917. &lastDateSz);
  32918. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_THISUPDATE_GT], dcrl->lastDate,
  32919. &lastDateSz);
  32920. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC], dcrl->nextDate,
  32921. &nextDateSz);
  32922. GetASN_Buffer(&dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT], dcrl->nextDate,
  32923. &nextDateSz);
  32924. /* Set expecting signature OID. */
  32925. GetASN_OID(&dataASN[CRLASN_IDX_SIGALGO_OID], oidSigType);
  32926. /* Decode the CRL. */
  32927. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  32928. }
  32929. /* Version must be v2 = 1 if present. */
  32930. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_VER].tag != 0) &&
  32931. (version != 1)) {
  32932. ret = ASN_PARSE_E;
  32933. }
  32934. /* Check minimum size of last date. */
  32935. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  32936. ret = ASN_PARSE_E;
  32937. }
  32938. /* Check minimum size of next date. */
  32939. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  32940. ret = ASN_PARSE_E;
  32941. }
  32942. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  32943. if ((ret == 0) && (dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum !=
  32944. dataASN[CRLASN_IDX_TBS_SIGALGO_OID].data.oid.sum)) {
  32945. ret = ASN_PARSE_E;
  32946. }
  32947. if (ret == 0) {
  32948. /* Store version */
  32949. dcrl->version = ++version;
  32950. /* Store offset of to be signed part. */
  32951. dcrl->certBegin = dataASN[CRLASN_IDX_TBS].offset;
  32952. /* Store index of signature. */
  32953. dcrl->sigIndex = dataASN[CRLASN_IDX_SIGALGO].offset;
  32954. /* Store address and length of signature data. */
  32955. GetASN_GetRef(&dataASN[CRLASN_IDX_SIGNATURE], &dcrl->signature,
  32956. &dcrl->sigLength);
  32957. /* Get the signature OID. */
  32958. dcrl->signatureOID = dataASN[CRLASN_IDX_SIGALGO_OID].data.oid.sum;
  32959. /* Get the format/tag of the last and next date. */
  32960. dcrl->lastDateFormat = (dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag != 0)
  32961. ? dataASN[CRLASN_IDX_TBS_THISUPDATE_UTC].tag
  32962. : dataASN[CRLASN_IDX_TBS_THISUPDATE_GT].tag;
  32963. dcrl->nextDateFormat = (dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag != 0)
  32964. ? dataASN[CRLASN_IDX_TBS_NEXTUPDATE_UTC].tag
  32965. : dataASN[CRLASN_IDX_TBS_NEXTUPDATE_GT].tag;
  32966. #ifndef NO_ASN_TIME
  32967. if (dcrl->nextDateFormat != 0) {
  32968. /* Next date was set, so validate it. */
  32969. if (verify != NO_VERIFY &&
  32970. !XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  32971. WOLFSSL_MSG("CRL after date is no longer valid");
  32972. ret = CRL_CERT_DATE_ERR;
  32973. WOLFSSL_ERROR_VERBOSE(ret);
  32974. }
  32975. }
  32976. }
  32977. if (ret == 0) {
  32978. #endif
  32979. #ifdef OPENSSL_EXTRA
  32980. /* Parse and store the issuer name. */
  32981. dcrl->issuerSz = GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER],
  32982. buff);
  32983. dcrl->issuer = (byte*)GetNameFromDer((byte*)GetASNItem_Addr(
  32984. dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32985. (int)dcrl->issuerSz);
  32986. #endif
  32987. /* Calculate the Hash id from the issuer name. */
  32988. ret = CalcHashId_ex(
  32989. GetASNItem_Addr(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32990. GetASNItem_Length(dataASN[CRLASN_IDX_TBS_ISSUER], buff),
  32991. dcrl->issuerHash, HashIdAlg(dcrl->signatureOID));
  32992. if (ret < 0) {
  32993. ret = ASN_PARSE_E;
  32994. }
  32995. }
  32996. if ((ret == 0) && (dataASN[CRLASN_IDX_TBS_REVOKEDCERTS].tag != 0)) {
  32997. /* Parse revoked cerificates - starting after SEQUENCE OF. */
  32998. ret = ParseCRL_RevokedCerts(rcert, dcrl, buff,
  32999. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff),
  33000. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_REVOKEDCERTS], buff));
  33001. }
  33002. if (ret == 0) {
  33003. /* Parse the extensions - starting after SEQUENCE OF. */
  33004. ret = ParseCRL_Extensions(dcrl, buff,
  33005. GetASNItem_DataIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff),
  33006. GetASNItem_EndIdx(dataASN[CRLASN_IDX_TBS_EXT_SEQ], buff));
  33007. }
  33008. if (ret == 0) {
  33009. /* Find signer and verify signature. */
  33010. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  33011. }
  33012. FREE_ASNGETDATA(dataASN, dcrl->heap);
  33013. return ret;
  33014. #endif /* WOLFSSL_ASN_TEMPLATE */
  33015. }
  33016. #endif /* HAVE_CRL */
  33017. #ifdef WOLFSSL_CERT_PIV
  33018. #ifdef WOLFSSL_ASN_TEMPLATE
  33019. /* Template for PIV. */
  33020. static const ASNItem pivASN[] = {
  33021. /* CERT */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  33022. /* NONCE */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  33023. /* SIGNEDNONCE */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  33024. };
  33025. enum {
  33026. PIVASN_IDX_CERT = 0,
  33027. PIVASN_IDX_NONCE,
  33028. PIVASN_IDX_SIGNEDNONCE,
  33029. };
  33030. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  33031. static const ASNItem pivCertASN[] = {
  33032. /* 0x53 = 0x40 | 0x13 */
  33033. /* CERT */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  33034. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  33035. /* X509 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  33036. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  33037. /* INFO */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  33038. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  33039. /* ERR */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  33040. };
  33041. enum {
  33042. PIVCERTASN_IDX_CERT,
  33043. PIVCERTASN_IDX_X509,
  33044. PIVCERTASN_IDX_INFO,
  33045. PIVCERTASN_IDX_ERR,
  33046. };
  33047. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  33048. #endif
  33049. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  33050. {
  33051. #ifndef WOLFSSL_ASN_TEMPLATE
  33052. int length = 0;
  33053. word32 idx = 0;
  33054. WOLFSSL_ENTER("wc_ParseCertPIV");
  33055. if (piv == NULL || buf == NULL || totalSz == 0)
  33056. return BAD_FUNC_ARG;
  33057. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  33058. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  33059. /* Certificate (0A 82 05FA) */
  33060. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  33061. /* Identiv Type PIV card */
  33062. piv->isIdentiv = 1;
  33063. piv->cert = &buf[idx];
  33064. piv->certSz = length;
  33065. idx += length;
  33066. /* Nonce (0B 14) */
  33067. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  33068. piv->nonce = &buf[idx];
  33069. piv->nonceSz = length;
  33070. idx += length;
  33071. }
  33072. /* Signed Nonce (0C 82 0100) */
  33073. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  33074. piv->signedNonce = &buf[idx];
  33075. piv->signedNonceSz = length;
  33076. }
  33077. idx = 0;
  33078. buf = piv->cert;
  33079. totalSz = piv->certSz;
  33080. }
  33081. /* Certificate Buffer Total Size (53 82 05F6) */
  33082. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  33083. &length, totalSz) < 0) {
  33084. return ASN_PARSE_E;
  33085. }
  33086. /* PIV Certificate (70 82 05ED) */
  33087. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  33088. totalSz) < 0) {
  33089. return ASN_PARSE_E;
  33090. }
  33091. /* Capture certificate buffer pointer and length */
  33092. piv->cert = &buf[idx];
  33093. piv->certSz = length;
  33094. idx += length;
  33095. /* PIV Certificate Info (71 01 00) */
  33096. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  33097. totalSz) >= 0) {
  33098. if (length >= 1) {
  33099. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  33100. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  33101. }
  33102. idx += length;
  33103. }
  33104. /* PIV Error Detection (FE 00) */
  33105. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  33106. totalSz) >= 0) {
  33107. piv->certErrDet = &buf[idx];
  33108. piv->certErrDetSz = length;
  33109. idx += length;
  33110. }
  33111. return 0;
  33112. #else
  33113. /* pivCertASN_Length is longer than pivASN_Length */
  33114. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  33115. int ret = 0;
  33116. word32 idx;
  33117. byte info;
  33118. WOLFSSL_ENTER("wc_ParseCertPIV");
  33119. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  33120. if (ret == 0) {
  33121. /* Clear dynamic data. */
  33122. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  33123. /* Start parsing from start of buffer. */
  33124. idx = 0;
  33125. /* Parse Identiv wrapper. */
  33126. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  33127. totalSz);
  33128. if (ret == 0) {
  33129. /* Identiv wrapper found. */
  33130. piv->isIdentiv = 1;
  33131. /* Get nonce reference. */
  33132. if (dataASN[PIVASN_IDX_NONCE].tag != 0) {
  33133. GetASN_GetConstRef(&dataASN[PIVASN_IDX_NONCE], &piv->nonce,
  33134. &piv->nonceSz);
  33135. }
  33136. /* Get signedNonce reference. */
  33137. if (dataASN[PIVASN_IDX_SIGNEDNONCE].tag != 0) {
  33138. GetASN_GetConstRef(&dataASN[PIVASN_IDX_SIGNEDNONCE],
  33139. &piv->signedNonce, &piv->signedNonceSz);
  33140. }
  33141. /* Get the certificate data for parsing. */
  33142. GetASN_GetConstRef(&dataASN[PIVASN_IDX_CERT], &buf, &totalSz);
  33143. }
  33144. ret = 0;
  33145. }
  33146. if (ret == 0) {
  33147. /* Clear dynamic data and set variable to put cert info into. */
  33148. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  33149. GetASN_Int8Bit(&dataASN[PIVCERTASN_IDX_INFO], &info);
  33150. /* Start parsing from start of buffer. */
  33151. idx = 0;
  33152. /* Parse PIV cetificate data. */
  33153. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  33154. totalSz);
  33155. if (ret == 0) {
  33156. /* Get X.509 certificate reference. */
  33157. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_X509], &piv->cert,
  33158. &piv->certSz);
  33159. /* Set the certificate info if available. */
  33160. if (dataASN[PIVCERTASN_IDX_INFO].tag != 0) {
  33161. /* Bits 1 and 2 are compression. */
  33162. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  33163. /* Bits 3 is X509 flag. */
  33164. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  33165. }
  33166. /* Get X.509 certificate error detection reference. */
  33167. GetASN_GetConstRef(&dataASN[PIVCERTASN_IDX_ERR], &piv->certErrDet,
  33168. &piv->certErrDetSz);
  33169. }
  33170. ret = 0;
  33171. }
  33172. FREE_ASNGETDATA(dataASN, NULL);
  33173. return ret;
  33174. #endif /* WOLFSSL_ASN_TEMPLATE */
  33175. }
  33176. #endif /* WOLFSSL_CERT_PIV */
  33177. #ifdef HAVE_SMIME
  33178. /*****************************************************************************
  33179. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  33180. * and parameters into headers. Will continue until in has no more content.
  33181. *
  33182. * RETURNS:
  33183. * returns zero on success, non-zero on error.
  33184. */
  33185. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  33186. {
  33187. MimeHdr* nextHdr = NULL;
  33188. MimeHdr* curHdr = NULL;
  33189. MimeParam* nextParam = NULL;
  33190. size_t start = 0;
  33191. size_t end = 0;
  33192. char* nameAttr = NULL;
  33193. char* bodyVal = NULL;
  33194. MimeTypes mimeType = MIME_HDR;
  33195. MimeStatus mimeStatus = MIME_NAMEATTR;
  33196. int ret = -1;
  33197. size_t pos = 0;
  33198. size_t lineLen = 0;
  33199. char* curLine = NULL;
  33200. char* ptr = NULL;
  33201. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  33202. ret = BAD_FUNC_ARG;
  33203. goto error;
  33204. }
  33205. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  33206. if (nextHdr == NULL) {
  33207. ret = MEMORY_E;
  33208. goto error;
  33209. }
  33210. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33211. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33212. DYNAMIC_TYPE_PKCS7);
  33213. if (nextParam == NULL) {
  33214. ret = MEMORY_E;
  33215. goto error;
  33216. }
  33217. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33218. curLine = XSTRTOK(in, "\r\n", &ptr);
  33219. if (curLine == NULL) {
  33220. ret = ASN_PARSE_E;
  33221. goto error;
  33222. }
  33223. while (curLine != NULL) {
  33224. /* Leftover from previous line, add params to previous header. */
  33225. if (curLine[0] == ' ' && curHdr) {
  33226. mimeType = MIME_PARAM;
  33227. }
  33228. else {
  33229. mimeType = MIME_HDR;
  33230. }
  33231. start = 0;
  33232. lineLen = XSTRLEN(curLine);
  33233. if (lineLen == 0) {
  33234. ret = BAD_FUNC_ARG;
  33235. goto error;
  33236. }
  33237. for (pos = 0; pos < lineLen; pos++) {
  33238. char cur = curLine[pos];
  33239. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  33240. mimeType == MIME_HDR) || (cur == '=' &&
  33241. mimeType == MIME_PARAM)) && pos >= 1) {
  33242. mimeStatus = MIME_BODYVAL;
  33243. end = pos-1;
  33244. if (nameAttr != NULL)
  33245. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33246. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  33247. if (ret) {
  33248. goto error;
  33249. }
  33250. start = pos+1;
  33251. }
  33252. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  33253. end = pos-1;
  33254. if (bodyVal != NULL)
  33255. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33256. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33257. if (ret) {
  33258. goto error;
  33259. }
  33260. if (mimeType == MIME_HDR) {
  33261. nextHdr->name = nameAttr;
  33262. nameAttr = NULL;
  33263. nextHdr->body = bodyVal;
  33264. bodyVal = NULL;
  33265. nextHdr->next = curHdr;
  33266. curHdr = nextHdr;
  33267. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33268. DYNAMIC_TYPE_PKCS7);
  33269. if (nextHdr == NULL) {
  33270. ret = MEMORY_E;
  33271. goto error;
  33272. }
  33273. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33274. }
  33275. else {
  33276. nextParam->attribute = nameAttr;
  33277. nameAttr = NULL;
  33278. nextParam->value = bodyVal;
  33279. bodyVal = NULL;
  33280. nextParam->next = curHdr->params;
  33281. curHdr->params = nextParam;
  33282. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33283. DYNAMIC_TYPE_PKCS7);
  33284. if (nextParam == NULL) {
  33285. ret = MEMORY_E;
  33286. goto error;
  33287. }
  33288. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33289. }
  33290. mimeType = MIME_PARAM;
  33291. mimeStatus = MIME_NAMEATTR;
  33292. start = pos+1;
  33293. }
  33294. }
  33295. end = lineLen-1;
  33296. /* Omit newline characters. */
  33297. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  33298. end--;
  33299. }
  33300. if (end >= start && mimeStatus == MIME_BODYVAL) {
  33301. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  33302. if (ret) {
  33303. goto error;
  33304. }
  33305. if (mimeType == MIME_HDR) {
  33306. nextHdr->name = nameAttr;
  33307. nameAttr = NULL;
  33308. nextHdr->body = bodyVal;
  33309. bodyVal = NULL;
  33310. nextHdr->next = curHdr;
  33311. curHdr = nextHdr;
  33312. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  33313. DYNAMIC_TYPE_PKCS7);
  33314. if (nextHdr == NULL) {
  33315. ret = MEMORY_E;
  33316. goto error;
  33317. }
  33318. XMEMSET(nextHdr, 0, sizeof(MimeHdr));
  33319. } else {
  33320. nextParam->attribute = nameAttr;
  33321. nameAttr = NULL;
  33322. nextParam->value = bodyVal;
  33323. bodyVal = NULL;
  33324. nextParam->next = curHdr->params;
  33325. curHdr->params = nextParam;
  33326. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  33327. DYNAMIC_TYPE_PKCS7);
  33328. if (nextParam == NULL) {
  33329. ret = MEMORY_E;
  33330. goto error;
  33331. }
  33332. XMEMSET(nextParam, 0, sizeof(MimeParam));
  33333. }
  33334. }
  33335. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  33336. mimeStatus = MIME_NAMEATTR;
  33337. }
  33338. *headers = curHdr;
  33339. ret = 0; /* success if at this point */
  33340. error:
  33341. if (ret != 0)
  33342. wc_MIME_free_hdrs(curHdr);
  33343. wc_MIME_free_hdrs(nextHdr);
  33344. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  33345. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  33346. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  33347. return ret;
  33348. }
  33349. /*****************************************************************************
  33350. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  33351. * out disallowed/separator characters and places the rest into *out.
  33352. *
  33353. * RETURNS:
  33354. * returns zero on success, non-zero on error.
  33355. */
  33356. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  33357. {
  33358. size_t inPos = start;
  33359. size_t outPos = 0;
  33360. size_t inLen = 0;
  33361. if (end < start || in == NULL || out == NULL) {
  33362. return BAD_FUNC_ARG;
  33363. }
  33364. inLen = XSTRLEN(in);
  33365. if (start > inLen || end > inLen) {
  33366. return BAD_FUNC_ARG;
  33367. }
  33368. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  33369. DYNAMIC_TYPE_PKCS7);
  33370. if (*out == NULL) {
  33371. return MEMORY_E;
  33372. }
  33373. while (inPos <= end) {
  33374. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  33375. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  33376. (*out)[outPos] = in[inPos];
  33377. outPos++;
  33378. }
  33379. inPos++;
  33380. }
  33381. (*out)[outPos] = '\0';
  33382. return 0;
  33383. }
  33384. /*****************************************************************************
  33385. * wc_MIME_find_header_name - Searches through all given headers until a header with
  33386. * a name matching the provided name is found.
  33387. *
  33388. * RETURNS:
  33389. * returns a pointer to the found header, if no match was found, returns NULL.
  33390. */
  33391. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  33392. {
  33393. while (header) {
  33394. if (!XSTRCMP(name, header->name)) {
  33395. return header;
  33396. }
  33397. header = header->next;
  33398. }
  33399. return header;
  33400. }
  33401. /*****************************************************************************
  33402. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  33403. * with a attribute matching the provided attribute is found.
  33404. *
  33405. * RETURNS:
  33406. * returns a pointer to the found parameter, if no match was found,
  33407. * returns NULL.
  33408. */
  33409. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  33410. MimeParam* param)
  33411. {
  33412. while (param) {
  33413. if (!XSTRCMP(attribute, param->attribute)) {
  33414. return param;
  33415. }
  33416. param = param->next;
  33417. }
  33418. return param;
  33419. }
  33420. /*****************************************************************************
  33421. * wc_MIME_single_canonicalize - Canonicalize a line by converting the trailing
  33422. * line ending to CRLF.
  33423. *
  33424. * line - input line to canonicalize
  33425. * len - length of line in chars on input, length of output array on return
  33426. *
  33427. * RETURNS:
  33428. * returns a pointer to a canonicalized line on success, NULL on error.
  33429. */
  33430. char* wc_MIME_single_canonicalize(const char* line, word32* len)
  33431. {
  33432. size_t end = 0;
  33433. char* canonLine = NULL;
  33434. if (line == NULL || len == NULL || *len == 0) {
  33435. return NULL;
  33436. }
  33437. end = *len;
  33438. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  33439. end--;
  33440. }
  33441. /* Need 2 chars for \r\n and 1 for EOL */
  33442. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  33443. if (canonLine == NULL) {
  33444. return NULL;
  33445. }
  33446. XMEMCPY(canonLine, line, end);
  33447. canonLine[end] = '\r';
  33448. canonLine[end+1] = '\n';
  33449. canonLine[end+2] = '\0';
  33450. *len = (word32)(end + 3);
  33451. return canonLine;
  33452. }
  33453. /*****************************************************************************
  33454. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  33455. * the provided header pointer.
  33456. *
  33457. * RETURNS:
  33458. * returns zero on success, non-zero on error.
  33459. */
  33460. int wc_MIME_free_hdrs(MimeHdr* head)
  33461. {
  33462. MimeHdr* curHdr = NULL;
  33463. MimeParam* curParam = NULL;
  33464. while (head) {
  33465. while (head->params) {
  33466. curParam = head->params;
  33467. head->params = head->params->next;
  33468. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  33469. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  33470. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  33471. }
  33472. curHdr = head;
  33473. head = head->next;
  33474. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  33475. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  33476. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  33477. }
  33478. return 0;
  33479. }
  33480. #endif /* HAVE_SMIME */
  33481. #undef ERROR_OUT
  33482. #ifdef WOLFSSL_ASN_PRINT
  33483. /*******************************************************************************
  33484. * ASN.1 Parsing and Printing Implemenation
  33485. ******************************************************************************/
  33486. /* Initialize ASN.1 print options.
  33487. *
  33488. * @param [in, out] opts ASN.1 options for printing.
  33489. * @return 0 on success.
  33490. * @return BAD_FUNC_ARG when asn1 is NULL.
  33491. */
  33492. int wc_Asn1PrintOptions_Init(Asn1PrintOptions* opts)
  33493. {
  33494. int ret = 0;
  33495. if (opts == NULL) {
  33496. ret = BAD_FUNC_ARG;
  33497. }
  33498. else {
  33499. XMEMSET(opts, 0, sizeof(*opts));
  33500. }
  33501. return ret;
  33502. }
  33503. /* Set a print option into Asn1PrintOptions object.
  33504. *
  33505. * @param [in, out] opts ASN.1 options for printing.
  33506. * @param [in] opt Option to set value of.
  33507. * @param [in] val Value to set for option.
  33508. * @return 0 on success.
  33509. * @return BAD_FUNC_ARG when asn1 is NULL.
  33510. * @return BAD_FUNC_ARG when val is out of range for option.
  33511. */
  33512. int wc_Asn1PrintOptions_Set(Asn1PrintOptions* opts, enum Asn1PrintOpt opt,
  33513. word32 val)
  33514. {
  33515. int ret = 0;
  33516. /* Validate parameters. */
  33517. if (opts == NULL) {
  33518. ret = BAD_FUNC_ARG;
  33519. }
  33520. if (ret == 0) {
  33521. switch (opt) {
  33522. /* Offset into DER/BER data to start decoding from. */
  33523. case ASN1_PRINT_OPT_OFFSET:
  33524. opts->offset = val;
  33525. break;
  33526. /* Length of DER/BER encoding to parse. */
  33527. case ASN1_PRINT_OPT_LENGTH:
  33528. opts->length = val;
  33529. break;
  33530. /* Number of spaces to indent for each change in depth. */
  33531. case ASN1_PRINT_OPT_INDENT:
  33532. /* Only 4 bits allowed for value. */
  33533. if (val >= (1 << 4)) {
  33534. ret = BAD_FUNC_ARG;
  33535. }
  33536. else {
  33537. opts->indent = (word8)val;
  33538. }
  33539. break;
  33540. /* Draw branches instead of indenting. */
  33541. case ASN1_PRINT_OPT_DRAW_BRANCH:
  33542. /* Boolean value. */
  33543. opts->draw_branch = (val > 0);
  33544. break;
  33545. /* Show raw data of primitive types as octets. */
  33546. case ASN1_PRINT_OPT_SHOW_DATA:
  33547. /* Boolean value. */
  33548. opts->show_data = (val > 0);
  33549. break;
  33550. /* Show header data as octets. */
  33551. case ASN1_PRINT_OPT_SHOW_HEADER_DATA:
  33552. /* Boolean value. */
  33553. opts->show_header_data = (val > 0);
  33554. break;
  33555. /* Show the wolfSSL OID value for OBJECT_ID. */
  33556. case ASN1_PRINT_OPT_SHOW_OID:
  33557. /* Boolean value. */
  33558. opts->show_oid = (val > 0);
  33559. break;
  33560. /* Don't show text representations of primitive types. */
  33561. case ASN1_PRINT_OPT_SHOW_NO_TEXT:
  33562. /* Boolean value. */
  33563. opts->show_no_text = (val > 0);
  33564. break;
  33565. /* Don't show dump text representations of primitive types. */
  33566. case ASN1_PRINT_OPT_SHOW_NO_DUMP_TEXT:
  33567. /* Boolean value. */
  33568. opts->show_no_dump_text = (val > 0);
  33569. break;
  33570. }
  33571. }
  33572. return ret;
  33573. }
  33574. /* Initialize an ASN.1 parse object.
  33575. *
  33576. * @param [in, out] asn1 ASN.1 parse object.
  33577. * @return 0 on success.
  33578. * @return BAD_FUNC_ARG when asn1 is NULL.
  33579. */
  33580. int wc_Asn1_Init(Asn1* asn1)
  33581. {
  33582. int ret = 0;
  33583. if (asn1 == NULL) {
  33584. ret = BAD_FUNC_ARG;
  33585. }
  33586. else {
  33587. XMEMSET(asn1, 0, sizeof(*asn1));
  33588. asn1->file = XBADFILE;
  33589. }
  33590. return ret;
  33591. }
  33592. /* Set the file to use when printing.
  33593. *
  33594. * @param [in, out] asn1 ASN.1 parse object.
  33595. * @param [in] file File to print to.
  33596. * @return 0 on success.
  33597. * @return BAD_FUNC_ARG when asn1 is NULL.
  33598. * @return BAD_FUNC_ARG when file is XBADFILE.
  33599. */
  33600. int wc_Asn1_SetFile(Asn1* asn1, XFILE file)
  33601. {
  33602. int ret = 0;
  33603. if ((asn1 == NULL) || (file == XBADFILE)) {
  33604. ret = BAD_FUNC_ARG;
  33605. }
  33606. else {
  33607. asn1->file = file;
  33608. }
  33609. return ret;
  33610. }
  33611. /* Maximum OID dotted form size. */
  33612. #define ASN1_OID_DOTTED_MAX_SZ 16
  33613. /* Print OID in dotted form or as hex bytes.
  33614. *
  33615. * @param [in] file File pointer to write to.
  33616. * @param [in] oid OBJECT_ID data.
  33617. * @param [in] oid_len Length of OBJECT_ID data.
  33618. */
  33619. static void PrintObjectIdNum(XFILE file, unsigned char* oid, word32 len)
  33620. {
  33621. word16 dotted_nums[ASN1_OID_DOTTED_MAX_SZ];
  33622. word32 num = ASN1_OID_DOTTED_MAX_SZ;
  33623. word32 i;
  33624. /* Decode OBJECT_ID into dotted form array. */
  33625. if (DecodeObjectId(oid, len, dotted_nums, &num) == 0) {
  33626. /* Print out each number of dotted form. */
  33627. for (i = 0; i < num; i++) {
  33628. XFPRINTF(file, "%d", dotted_nums[i]);
  33629. /* Add separetor. */
  33630. if (i < num - 1) {
  33631. XFPRINTF(file, ".");
  33632. }
  33633. }
  33634. }
  33635. else {
  33636. /* Print out bytes as we couldn't decode. */
  33637. for (i = 0; i < len; i++) {
  33638. XFPRINTF(file, "%02x", oid[i]);
  33639. /* Add separetor. */
  33640. if (i < len - 1) {
  33641. XFPRINTF(file, ":");
  33642. }
  33643. }
  33644. }
  33645. }
  33646. /* OID value to name mapping. */
  33647. typedef struct OidName {
  33648. /* wolfSSL OID value. */
  33649. word32 oid;
  33650. /* Long name to print when OID seen. */
  33651. const char* name;
  33652. } OidName;
  33653. /* Extra OID to name mappings. */
  33654. static const OidName extraOids[] = {
  33655. { 0x005c, "commonName" },
  33656. { 0x005d, "surname" },
  33657. { 0x005e, "serialNumber" },
  33658. { 0x005f, "countryName" },
  33659. { 0x0060, "localityName" },
  33660. { 0x0061, "stateOrProvinceName" },
  33661. { 0x0062, "streetAddress" },
  33662. { 0x0063, "organizationName" },
  33663. { 0x0064, "organizationUnitName" },
  33664. { 0x0065, "title" },
  33665. { 0x0086, "certificateExtension" },
  33666. { 0x028d, "emailAddress" },
  33667. { 0x0293, "challengePassword" },
  33668. { 0x029a, "extensionReq" },
  33669. };
  33670. /* Length of table of extra OID to name mappings. */
  33671. #define EXTRA_OIDS_LEN ((int)(sizeof(extraOids) / sizeof(*extraOids)))
  33672. /* Convert OID value to long name.
  33673. *
  33674. * @param [in] oid OID value.
  33675. * @param [out] name Long name for OID when known.
  33676. * @return 1 when OID known.
  33677. * @return 0 when OID not known.
  33678. */
  33679. static int Oid2LongName(word32 oid, const char** name)
  33680. {
  33681. int ret = 0;
  33682. int i;
  33683. /* Step through each entry in table. */
  33684. for (i = 0; i < EXTRA_OIDS_LEN; i++) {
  33685. if (extraOids[i].oid == oid) {
  33686. /* Return the name associated with the OID value. */
  33687. *name = extraOids[i].name;
  33688. ret = 1;
  33689. break;
  33690. }
  33691. }
  33692. return ret;
  33693. }
  33694. /* Print the text version of the OBJECT_ID.
  33695. *
  33696. * @param [in] asn1 ASN.1 parse object.
  33697. * @param [in] opts ASN.1 options for printing.
  33698. */
  33699. static void PrintObjectIdText(Asn1* asn1, Asn1PrintOptions* opts)
  33700. {
  33701. word32 oid = (word32)-1;
  33702. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33703. int nid;
  33704. #endif
  33705. const char* ln = NULL;
  33706. word32 i = 0;
  33707. int known = 1;
  33708. /* Get the OID value for the OBJECT_ID. */
  33709. if (GetObjectId(asn1->data + asn1->offset, &i, &oid, oidIgnoreType,
  33710. asn1->item.len + 2) == ASN_PARSE_E) {
  33711. known = 0;
  33712. }
  33713. else
  33714. #if !defined(WOLFCRYPT_ONLY) && defined(OPENSSL_EXTRA)
  33715. /* Lookup NID for OID value. */
  33716. if ((nid = oid2nid(oid, oidIgnoreType)) != -1) {
  33717. /* Lookup long name for NID. */
  33718. ln = wolfSSL_OBJ_nid2ln(nid);
  33719. }
  33720. else
  33721. #endif
  33722. /* Lookup long name for extra known OID values. */
  33723. if (!Oid2LongName(oid, &ln)) {
  33724. /* Unknown OID value. */
  33725. ln = NULL;
  33726. known = 0;
  33727. }
  33728. XFPRINTF(asn1->file, ":");
  33729. /* Show OID value if not known or asked to. */
  33730. if ((!known) || opts->show_oid) {
  33731. XFPRINTF(asn1->file, "(0x%x) ", oid);
  33732. }
  33733. if (ln != NULL) {
  33734. /* Print long name. */
  33735. XFPRINTF(asn1->file, "%s", ln);
  33736. }
  33737. else {
  33738. /* Print out as numbers - either dotted or hex values. */
  33739. PrintObjectIdNum(asn1->file, asn1->data + asn1->item.data_idx,
  33740. asn1->item.len);
  33741. }
  33742. }
  33743. /* Print ASN.1 data as a character string.
  33744. *
  33745. * @param [in] asn1 ASN.1 parse object.
  33746. */
  33747. static void PrintText(Asn1* asn1)
  33748. {
  33749. word32 i;
  33750. XFPRINTF(asn1->file, ":");
  33751. /* Print all data bytes as characters. */
  33752. for (i = 0; i < asn1->item.len; i++) {
  33753. XFPRINTF(asn1->file, "%c", asn1->data[asn1->item.data_idx + i]);
  33754. }
  33755. }
  33756. /* Print data as a hex bytes.
  33757. *
  33758. * @param [in] file File pointer to write to.
  33759. * @param [in] data Data to print.
  33760. * @param [in] len Number of bytes to print.
  33761. */
  33762. static void PrintHex(XFILE file, unsigned char* data, word32 len)
  33763. {
  33764. word32 i;
  33765. /* Print data bytes as hex numbers. */
  33766. for (i = 0; i < len; i++) {
  33767. XFPRINTF(file, "%02x", data[i]);
  33768. }
  33769. }
  33770. /* Print ASN.1 data as a hex bytes.
  33771. *
  33772. * @param [in] asn1 ASN.1 parse object.
  33773. */
  33774. static void PrintHexText(Asn1* asn1)
  33775. {
  33776. XFPRINTF(asn1->file, ":");
  33777. PrintHex(asn1->file, asn1->data + asn1->item.data_idx, asn1->item.len);
  33778. }
  33779. /* Print ASN.1 BIT_STRING data as hex bytes noting special first byte.
  33780. *
  33781. * @param [in] asn1 ASN.1 parse object.
  33782. */
  33783. static void PrintBitStringText(Asn1* asn1)
  33784. {
  33785. if (asn1->item.len > 0) {
  33786. XFPRINTF(asn1->file, ":[%02x]", asn1->data[asn1->item.data_idx]);
  33787. PrintHex(asn1->file, asn1->data + asn1->item.data_idx + 1,
  33788. asn1->item.len - 1);
  33789. }
  33790. }
  33791. /* Print ASN.1 BOOLEAN data as text with value.
  33792. *
  33793. * @param [in] asn1 ASN.1 parse object.
  33794. */
  33795. static void PrintBooleanText(Asn1* asn1)
  33796. {
  33797. /* Booleans should be 1 byte of data. */
  33798. if (asn1->item.len == 1) {
  33799. XFPRINTF(asn1->file, ":%s (%d)",
  33800. (asn1->data[asn1->item.data_idx] == 0) ? "FALSE" : "TRUE",
  33801. asn1->data[asn1->item.data_idx]);
  33802. }
  33803. }
  33804. /* Print ASN.1 data as single byte +/- number.
  33805. *
  33806. * @param [in] asn1 ASN.1 parse object.
  33807. */
  33808. static void PrintNumberText(Asn1* asn1)
  33809. {
  33810. /* Only supporting 1 byte of data for now. */
  33811. if (asn1->item.len == 1) {
  33812. int num = asn1->data[asn1->item.data_idx];
  33813. XFPRINTF(asn1->file, ":%d", num >= 0x80 ? num - 0x100 : num);
  33814. }
  33815. }
  33816. /* Print ASN.1 data as a text based on the tag.
  33817. *
  33818. * TODO: handle more tags.
  33819. *
  33820. * @param [in] asn1 ASN.1 parse object.
  33821. * @param [in] opts ASN.1 options for printing.
  33822. */
  33823. static void PrintAsn1Text(Asn1* asn1, Asn1PrintOptions* opts)
  33824. {
  33825. /* Get the long name for OBJECT_ID where possible. */
  33826. if (asn1->item.tag == ASN_OBJECT_ID) {
  33827. PrintObjectIdText(asn1, opts);
  33828. }
  33829. /* Data is an array of printable characters. */
  33830. else if ((asn1->item.tag == ASN_UTF8STRING) ||
  33831. (asn1->item.tag == ASN_IA5_STRING) ||
  33832. (asn1->item.tag == ASN_PRINTABLE_STRING) ||
  33833. (asn1->item.tag == ASN_T61STRING) ||
  33834. (asn1->item.tag == ASN_BMPSTRING) ||
  33835. (asn1->item.tag == ASN_UTC_TIME) ||
  33836. (asn1->item.tag == ASN_GENERALIZED_TIME) ||
  33837. (asn1->item.tag == ASN_UNIVERSALSTRING) ||
  33838. (asn1->item.tag == ASN_OBJECT_DESC) ||
  33839. (asn1->item.tag == ASN_CHARACTER_STRING)) {
  33840. PrintText(asn1);
  33841. }
  33842. /* Show TRUE and FALSE with number. */
  33843. else if (asn1->item.tag == ASN_BOOLEAN) {
  33844. PrintBooleanText(asn1);
  33845. }
  33846. /* Show number. */
  33847. else if (asn1->item.tag == ASN_ENUMERATED) {
  33848. PrintNumberText(asn1);
  33849. }
  33850. /* Dumping potentially long string of hex digites. */
  33851. else if (!opts->show_no_dump_text) {
  33852. /* Dump all bytes. */
  33853. if ((asn1->item.tag == ASN_INTEGER) ||
  33854. (asn1->item.tag == ASN_OCTET_STRING) ||
  33855. ((asn1->item.tag > ASN_APPLICATION) && (asn1->item.cons))) {
  33856. PrintHexText(asn1);
  33857. }
  33858. /* First byte is number of unused bits in last byte.
  33859. * Print first specially and dump rest of the bytes. */
  33860. else if (asn1->item.tag == ASN_BIT_STRING) {
  33861. PrintBitStringText(asn1);
  33862. }
  33863. }
  33864. }
  33865. #define HexToChar(n) ((((n) >= 32) && ((n) < 127)) ? (n) : '.')
  33866. /* Dump data as hex bytes.
  33867. *
  33868. * @param [in] file File pointer to write to.
  33869. * @param [in] data Data to print.
  33870. * @param [in] len Number of bytes to print.
  33871. */
  33872. static void DumpData(XFILE file, unsigned char* data, word32 len)
  33873. {
  33874. word32 i;
  33875. word32 j;
  33876. for (i = 0; i < len; i += j) {
  33877. /* Print offset. */
  33878. XFPRINTF(file, " %04x:", i);
  33879. for (j = 0; (j < 16) && (i + j < len); j++) {
  33880. /* Print byte as hex number. */
  33881. XFPRINTF(file, "%s%02x", (j == 8) ? " " : " ", data[i + j]);
  33882. }
  33883. /* Print spaces between hex and characters. */
  33884. XFPRINTF(file, " %*s", (16 - j) * 3 + ((j < 8) ? 1 : 0), "");
  33885. for (j = 0; (j < 16) && (i + j < len); j++) {
  33886. /* Print byte as hex number. */
  33887. XFPRINTF(file, "%c", HexToChar(data[i + j]));
  33888. }
  33889. XFPRINTF(file, "\n");
  33890. }
  33891. }
  33892. /* Update current depth based on the current position.
  33893. *
  33894. * @param [in, out] asn1 ASN.1 parse object.
  33895. */
  33896. static void UpdateDepth(Asn1* asn1)
  33897. {
  33898. /* If current index is greater than or equal end index then it is done. */
  33899. while ((asn1->depth > 0) &&
  33900. (asn1->end_idx[asn1->depth-1] <= asn1->curr)) {
  33901. /* Move up a depth. */
  33902. asn1->depth--;
  33903. }
  33904. }
  33905. /* Check validity of end index of constructed ASN.1 items.
  33906. *
  33907. * @param [in, out] asn1 ASN.1 parse object.
  33908. * @return 0 on success.
  33909. * @return ASN_DEPTH_E when end offset invalid.
  33910. */
  33911. static int CheckDepth(Asn1* asn1)
  33912. {
  33913. int ret = 0;
  33914. int i;
  33915. word32 curr_end = asn1->curr + asn1->item.len;
  33916. for (i = 0; (ret == 0) && (i < asn1->depth); i++) {
  33917. /* Each end index must be at least as large as the current one. */
  33918. if (asn1->end_idx[i] < asn1->end_idx[asn1->depth]) {
  33919. ret = ASN_DEPTH_E;
  33920. }
  33921. /* Each end index must be at least as large as current index. */
  33922. if (asn1->end_idx[i] < curr_end) {
  33923. ret = ASN_DEPTH_E;
  33924. }
  33925. }
  33926. return ret;
  33927. }
  33928. /* Draw branching based on depth for an ASN.1 item.
  33929. *
  33930. * @param [in] asn1 ASN.1 parse object.
  33931. */
  33932. static void DrawBranch(Asn1* asn1)
  33933. {
  33934. int i;
  33935. word32 end = asn1->curr + asn1->item.len;
  33936. /* Write out the character for all depths but current. */
  33937. for (i = 0; i < asn1->depth; i++) {
  33938. if (asn1->item.cons || (end < asn1->end_idx[i])) {
  33939. if (i < asn1->depth - 1) {
  33940. /* Constructed or not end index and not current depth: | */
  33941. XFPRINTF(asn1->file, "\xe2\x94\x82");
  33942. }
  33943. else {
  33944. /* Constructed or not end index and current depth: |- */
  33945. XFPRINTF(asn1->file, "\xe2\x94\x9c");
  33946. }
  33947. }
  33948. else if ((i > 1) && (end >= asn1->end_idx[i-1])) {
  33949. /* End index for previous: _|_ (in top half) */
  33950. XFPRINTF(asn1->file, "\xe2\x94\xb4");
  33951. }
  33952. else {
  33953. /* End index but not for previous: L (in top half) */
  33954. XFPRINTF(asn1->file, "\xe2\x94\x94");
  33955. }
  33956. }
  33957. /* Prefix to tag name. */
  33958. if (asn1->item.cons) {
  33959. if (asn1->depth > 0) {
  33960. /* Have other line to connect to: T (in bottom half) */
  33961. XFPRINTF(asn1->file, "\xe2\x94\xac");
  33962. }
  33963. else {
  33964. /* Have no other line to connect to: r */
  33965. XFPRINTF(asn1->file, "\xe2\x94\x8c");
  33966. }
  33967. }
  33968. else {
  33969. /* In a sequence: - */
  33970. XFPRINTF(asn1->file, "\xe2\x94\x80");
  33971. }
  33972. }
  33973. /* Print data as hex bytes separated by space.
  33974. *
  33975. * @param [in] file File pointer to write to.
  33976. * @param [in] data Data to print.
  33977. * @param [in] len Number of bytes to print.
  33978. */
  33979. static void PrintHexBytes(XFILE file, unsigned char* data, word32 len)
  33980. {
  33981. word32 i;
  33982. for (i = 0; i < len; i++) {
  33983. XFPRINTF(file, " %02x", data[i]);
  33984. }
  33985. }
  33986. /* Dump header data.
  33987. *
  33988. * @param [in] asn1 ASN.1 parse object.
  33989. * @param [in] opts ASN.1 options for printing.
  33990. */
  33991. static void DumpHeader(Asn1* asn1, Asn1PrintOptions* opts)
  33992. {
  33993. /* Put on same line when not showing data too and not showing text data. */
  33994. if ((!opts->show_data) && opts->show_no_text) {
  33995. XFPRINTF(asn1->file, "%10s", "");
  33996. }
  33997. else {
  33998. /* Align with start of data. */
  33999. XFPRINTF(asn1->file, "\n%12s", "");
  34000. }
  34001. XFPRINTF(asn1->file, " %02x", asn1->item.tag);
  34002. if (asn1->curr >= asn1->offset + 1) {
  34003. /* Print the header bytes as hex bytes separated by a space. */
  34004. PrintHexBytes(asn1->file, asn1->data + asn1->offset + 1,
  34005. asn1->curr - (asn1->offset + 1));
  34006. }
  34007. }
  34008. /* Print ASN.1 item info based on header and indeces.
  34009. *
  34010. * @param [in] asn1 ASN.1 parse object.
  34011. * @param [in] opts ASN.1 options for printing.
  34012. */
  34013. static void PrintInfo(Asn1* asn1, Asn1PrintOptions* opts)
  34014. {
  34015. /* Print offset of this ASN.1 item. */
  34016. XFPRINTF(asn1->file, "%4d: ", asn1->offset);
  34017. /* Print length of header. */
  34018. XFPRINTF(asn1->file, "%1d ", asn1->curr - asn1->offset);
  34019. /* Print data length. */
  34020. XFPRINTF(asn1->file, "%c%4d%c", asn1->item.cons ? '[' : '+', asn1->item.len,
  34021. asn1->item.cons ? ']' : ' ');
  34022. /* Print depth. */
  34023. XFPRINTF(asn1->file, " %s(%d)", (asn1->depth < 10) ? " " : "", asn1->depth);
  34024. if (!opts->draw_branch) {
  34025. /* Indent to depth as required. */
  34026. XFPRINTF(asn1->file, "%*s ", asn1->depth * opts->indent, "");
  34027. if (!opts->indent) {
  34028. /* Indicate constructed if no indent. */
  34029. XFPRINTF(asn1->file, "%c", asn1->item.cons ? '+' : ' ');
  34030. }
  34031. }
  34032. else {
  34033. /* Draw branch structure for ASN.1 item. */
  34034. XFPRINTF(asn1->file, " ");
  34035. DrawBranch(asn1);
  34036. }
  34037. /* Print tag name. */
  34038. XFPRINTF(asn1->file, "%-16s", TagString(asn1->item.tag));
  34039. }
  34040. /* Expecting tag part of ASN.1 item. */
  34041. #define ASN_PART_TAG 0
  34042. /* Expecting length part of ASN.1 item. */
  34043. #define ASN_PART_LENGTH 1
  34044. /* Expecting data part of ASN.1 item. */
  34045. #define ASN_PART_DATA 2
  34046. /* Print next ASN.1 item.
  34047. *
  34048. * @param [in, out] asn1 ASN.1 parse object.
  34049. * @param [in] opts ASN.1 print options.
  34050. * @return 0 on success.
  34051. * @return BAD_FUNC_ARG when asn1 or opts is NULL.
  34052. * @return ASN_LEN_E when ASN.1 item's length too long.
  34053. * @return ASN_DEPTH_E when end offset invalid.
  34054. */
  34055. static int wc_Asn1_Print(Asn1* asn1, Asn1PrintOptions* opts)
  34056. {
  34057. int ret = 0;
  34058. /* Process tag. */
  34059. if (asn1->part == ASN_PART_TAG) {
  34060. /* Recalculate which depth we are at. */
  34061. UpdateDepth(asn1);
  34062. /* Get tag. */
  34063. asn1->item.tag = asn1->data[asn1->curr] & (byte)~ASN_CONSTRUCTED;
  34064. /* Store whether tag indicates constructed. */
  34065. asn1->item.cons = (asn1->data[asn1->curr] & ASN_CONSTRUCTED) ==
  34066. ASN_CONSTRUCTED;
  34067. /* Start of ASN.1 item is current index. */
  34068. asn1->offset = asn1->curr;
  34069. /* Step over tag. */
  34070. asn1->curr++;
  34071. /* Next part is length. */
  34072. asn1->part = ASN_PART_LENGTH;
  34073. }
  34074. /* Process length. */
  34075. if (asn1->part == ASN_PART_LENGTH) {
  34076. int len;
  34077. /* Decode length and step over it. */
  34078. if (GetLength(asn1->data, &asn1->curr, &len, asn1->max) < 0) {
  34079. ret = ASN_LEN_E;
  34080. }
  34081. else {
  34082. /* Store ASN.1 item data offset. */
  34083. asn1->item.data_idx = asn1->curr;
  34084. /* Store ASN.1 item data length. */
  34085. asn1->item.len = (word32)len;
  34086. /* Print info about ASN.1 item. */
  34087. PrintInfo(asn1, opts);
  34088. if (!asn1->item.cons) {
  34089. /* Move on to print data. */
  34090. asn1->part = ASN_PART_DATA;
  34091. }
  34092. else {
  34093. /* Print header now if not printing data. */
  34094. if (opts->show_header_data) {
  34095. DumpHeader(asn1, opts);
  34096. }
  34097. XFPRINTF(asn1->file, "\n");
  34098. /* Record end offset for this depth. */
  34099. asn1->end_idx[asn1->depth++] = asn1->curr + asn1->item.len;
  34100. /* Done with this ASN.1 item. */
  34101. asn1->part = ASN_PART_TAG;
  34102. }
  34103. /* Check end indeces are valid. */
  34104. ret = CheckDepth(asn1);
  34105. }
  34106. }
  34107. /* Process data. */
  34108. if ((ret == 0) && (asn1->part == ASN_PART_DATA)) {
  34109. if (!opts->show_no_text) {
  34110. /* Print text representation of data. */
  34111. PrintAsn1Text(asn1, opts);
  34112. }
  34113. if (opts->show_header_data) {
  34114. /* Dump header bytes. */
  34115. DumpHeader(asn1, opts);
  34116. }
  34117. XFPRINTF(asn1->file, "\n");
  34118. if (opts->show_data) {
  34119. /* Dump data bytes. */
  34120. DumpData(asn1->file, asn1->data + asn1->item.data_idx,
  34121. asn1->item.len);
  34122. }
  34123. /* Step past data to next ASN.1 item. */
  34124. asn1->curr += asn1->item.len;
  34125. /* Update the depth based on end indeces. */
  34126. UpdateDepth(asn1);
  34127. /* Done with this ASN.1 item. */
  34128. asn1->part = ASN_PART_TAG;
  34129. }
  34130. /* Make ASN.1 item printing go out. */
  34131. fflush(asn1->file);
  34132. return ret;
  34133. }
  34134. /* Print all ASN.1 items.
  34135. *
  34136. * @param [in, out] asn1 ASN.1 parse object.
  34137. * @param [in] opts ASN.1 print options.
  34138. * @param [in] data BER/DER data to print.
  34139. * @param [in] len Length of data to print in bytes.
  34140. * @return 0 on success.
  34141. * @return BAD_FUNC_ARG when asn1, opts or data is NULL.
  34142. * @return ASN_LEN_E when ASN.1 item's length too long.
  34143. * @return ASN_DEPTH_E when end offset invalid.
  34144. * @return ASN_PARSE_E when not all of an ASN.1 item parsed.
  34145. */
  34146. int wc_Asn1_PrintAll(Asn1* asn1, Asn1PrintOptions* opts, unsigned char* data,
  34147. word32 len)
  34148. {
  34149. int ret = 0;
  34150. if ((asn1 == NULL) || (opts == NULL) || (data == NULL)) {
  34151. ret = BAD_FUNC_ARG;
  34152. }
  34153. if (ret == 0) {
  34154. /* Initialize start position. */
  34155. asn1->curr = 0;
  34156. /* Start parsing at tag. */
  34157. asn1->part = ASN_PART_TAG;
  34158. /* Start depth at 0. */
  34159. asn1->depth = 0;
  34160. /* Store the starting point of the data to parse. */
  34161. asn1->data = data + opts->offset;
  34162. if (opts->length > 0) {
  34163. /* Use user specified maximum length. */
  34164. asn1->max = opts->length;
  34165. }
  34166. else {
  34167. /* Maximum length is up to end from offset. */
  34168. asn1->max = len - opts->offset;
  34169. }
  34170. /* Keep going while no error and have data to parse. */
  34171. while ((ret == 0) && (asn1->curr < asn1->max)) {
  34172. /* Print an ASN.1 item. */
  34173. ret = wc_Asn1_Print(asn1, opts);
  34174. }
  34175. }
  34176. if ((ret == 0) && (asn1->part != ASN_PART_TAG)) {
  34177. /* Stopped before finishing ASN.1 item. */
  34178. ret = ASN_PARSE_E;
  34179. }
  34180. if ((ret == 0) && (asn1->depth != 0)) {
  34181. /* Stopped without seeing all items in a constructed item. */
  34182. ret = ASN_DEPTH_E;
  34183. }
  34184. return ret;
  34185. }
  34186. #endif /* WOLFSSL_ASN_PRINT */
  34187. #endif /* !NO_ASN */
  34188. /* Functions that parse, but are not using ASN.1 */
  34189. #if !defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  34190. (!defined(NO_BIG_INT) || defined(WOLFSSL_SP_MATH))
  34191. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  34192. /* this function does not use any ASN.1 parsing */
  34193. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  34194. word32 eSz, RsaKey* key)
  34195. {
  34196. if (n == NULL || e == NULL || key == NULL)
  34197. return BAD_FUNC_ARG;
  34198. key->type = RSA_PUBLIC;
  34199. if (mp_init(&key->n) != MP_OKAY)
  34200. return MP_INIT_E;
  34201. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  34202. mp_clear(&key->n);
  34203. return ASN_GETINT_E;
  34204. }
  34205. #ifdef HAVE_WOLF_BIGINT
  34206. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  34207. mp_clear(&key->n);
  34208. return ASN_GETINT_E;
  34209. }
  34210. #endif /* HAVE_WOLF_BIGINT */
  34211. if (mp_init(&key->e) != MP_OKAY) {
  34212. mp_clear(&key->n);
  34213. return MP_INIT_E;
  34214. }
  34215. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  34216. mp_clear(&key->n);
  34217. mp_clear(&key->e);
  34218. return ASN_GETINT_E;
  34219. }
  34220. #ifdef HAVE_WOLF_BIGINT
  34221. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  34222. mp_clear(&key->n);
  34223. mp_clear(&key->e);
  34224. return ASN_GETINT_E;
  34225. }
  34226. #endif /* HAVE_WOLF_BIGINT */
  34227. #ifdef WOLFSSL_XILINX_CRYPT
  34228. if (wc_InitRsaHw(key) != 0) {
  34229. return BAD_STATE_E;
  34230. }
  34231. #endif
  34232. return 0;
  34233. }
  34234. #endif /* !NO_RSA && !HAVE_USER_RSA && (!NO_BIG_INT || WOLFSSL_SP_MATH) */
  34235. #ifdef WOLFSSL_SEP
  34236. #endif /* WOLFSSL_SEP */