asn.c 972 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2021 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: Disables time parts of the ASN code for systems without an RTC
  43. or wishing to save space.
  44. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  45. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  46. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  47. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  48. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
  49. restore 3.13.0 behavior.
  50. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  51. must still be trusted)
  52. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  53. chain is not loaded. This only matches on subject and public key and
  54. does not perform a PKI validation, so it is not a secure solution.
  55. Only enabled for OCSP.
  56. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  57. disable checking of OCSP subject hash with issuer hash.
  58. * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
  59. DecodedCert. Doubles up on some code but allows smaller dynamic memory
  60. usage.
  61. * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
  62. may be required when the system's real-time clock is not very accurate.
  63. It is recommended to enforce the nonce check instead if possible.
  64. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  65. responses. The nonces are optional and may not be supported by all
  66. responders. If it can be ensured that the used responder sends nonces this
  67. option may improve security.
  68. * WOLFSSL_ASN_TEMPLATE: Encoding and decoding using a template.
  69. * WOLFSSL_DEBUG_ASN_TEMPLATE: Enables debugging output when using ASN.1
  70. templates.
  71. * WOLFSSL_ASN_TEMPLATE_TYPE_CHECK: Use ASN functions to better test compiler
  72. type issues for testing
  73. * CRLDP_VALIDATE_DATA: For ASN template only, validates the reason data
  74. * WOLFSSL_AKID_NAME: Enable support for full AuthorityKeyIdentifier extension.
  75. * Only supports copying full AKID from an existing certificate.
  76. */
  77. #ifndef NO_ASN
  78. #include <wolfssl/wolfcrypt/asn.h>
  79. #include <wolfssl/wolfcrypt/coding.h>
  80. #include <wolfssl/wolfcrypt/md2.h>
  81. #include <wolfssl/wolfcrypt/hmac.h>
  82. #include <wolfssl/wolfcrypt/error-crypt.h>
  83. #include <wolfssl/wolfcrypt/pwdbased.h>
  84. #include <wolfssl/wolfcrypt/des3.h>
  85. #include <wolfssl/wolfcrypt/aes.h>
  86. #include <wolfssl/wolfcrypt/rc2.h>
  87. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  88. #include <wolfssl/wolfcrypt/logging.h>
  89. #include <wolfssl/wolfcrypt/random.h>
  90. #include <wolfssl/wolfcrypt/hash.h>
  91. #ifdef NO_INLINE
  92. #include <wolfssl/wolfcrypt/misc.h>
  93. #else
  94. #define WOLFSSL_MISC_INCLUDED
  95. #include <wolfcrypt/src/misc.c>
  96. #endif
  97. #ifndef NO_RC4
  98. #include <wolfssl/wolfcrypt/arc4.h>
  99. #endif
  100. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  101. #include <wolfssl/wolfcrypt/sha512.h>
  102. #endif
  103. #ifndef NO_SHA256
  104. #include <wolfssl/wolfcrypt/sha256.h>
  105. #endif
  106. #ifdef HAVE_ECC
  107. #include <wolfssl/wolfcrypt/ecc.h>
  108. #endif
  109. #ifdef HAVE_ED25519
  110. #include <wolfssl/wolfcrypt/ed25519.h>
  111. #endif
  112. #ifdef HAVE_CURVE25519
  113. #include <wolfssl/wolfcrypt/curve25519.h>
  114. #endif
  115. #ifdef HAVE_ED448
  116. #include <wolfssl/wolfcrypt/ed448.h>
  117. #endif
  118. #ifdef HAVE_CURVE448
  119. #include <wolfssl/wolfcrypt/curve448.h>
  120. #endif
  121. #ifdef HAVE_LIBOQS
  122. #include <wolfssl/wolfcrypt/falcon.h>
  123. #endif
  124. #ifdef WOLFSSL_QNX_CAAM
  125. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  126. #endif
  127. #ifndef NO_RSA
  128. #include <wolfssl/wolfcrypt/rsa.h>
  129. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  130. extern int wc_InitRsaHw(RsaKey* key);
  131. #endif
  132. #endif
  133. #ifndef NO_DSA
  134. #include <wolfssl/wolfcrypt/dsa.h>
  135. #else
  136. typedef void* DsaKey;
  137. #endif
  138. #ifdef WOLF_CRYPTO_CB
  139. #include <wolfssl/wolfcrypt/cryptocb.h>
  140. #endif
  141. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  142. #include <wolfssl/internal.h>
  143. #include <wolfssl/openssl/objects.h>
  144. #endif
  145. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  146. !defined(WOLFCRYPT_ONLY)
  147. #define WOLFSSL_X509_NAME_AVAILABLE
  148. #endif
  149. #ifdef _MSC_VER
  150. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  151. #pragma warning(disable: 4996)
  152. #endif
  153. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  154. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  155. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  156. (!defined(HAVE_SELFTEST_VERSION) || \
  157. HAVE_SELFTEST_VERSION < 2))
  158. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  159. #define WOLFSSL_AES_KEY_SIZE_ENUM
  160. enum Asn_Misc {
  161. AES_IV_SIZE = 16,
  162. AES_128_KEY_SIZE = 16,
  163. AES_192_KEY_SIZE = 24,
  164. AES_256_KEY_SIZE = 32
  165. };
  166. #endif
  167. #endif /* HAVE_SELFTEST */
  168. #endif
  169. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  170. void tsip_inform_key_position(const word32 key_n_start,
  171. const word32 key_n_len, const word32 key_e_start,
  172. const word32 key_e_len);
  173. int tsip_tls_CertVerify(const byte *cert, word32 certSz,
  174. const byte *signature, word32 sigSz,
  175. word32 key_n_start, word32 key_n_len,
  176. word32 key_e_start, word32 key_e_len,
  177. byte *tsip_encRsaKeyIdx);
  178. #endif
  179. /* Calculates the minimum number of bytes required to encode the value.
  180. *
  181. * @param [in] value Value to be encoded.
  182. * @return Number of bytes to encode value.
  183. */
  184. static word32 BytePrecision(word32 value)
  185. {
  186. word32 i;
  187. for (i = (word32)sizeof(value); i; --i)
  188. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  189. break;
  190. return i;
  191. }
  192. /* DER encodes the length value in output buffer.
  193. *
  194. * 0 -> 2^7-1: <len byte>.
  195. * 2^7 -> : <0x80 + #bytes> <len big-endian bytes>
  196. *
  197. * @param [in] length Value to encode.
  198. * @param [in, out] output Buffer to encode into.
  199. * @return Number of bytes used in encoding.
  200. */
  201. WOLFSSL_LOCAL word32 SetASNLength(word32 length, byte* output)
  202. {
  203. word32 i = 0, j;
  204. if (length < ASN_LONG_LENGTH)
  205. output[i++] = (byte)length;
  206. else {
  207. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  208. for (j = BytePrecision(length); j; --j) {
  209. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  210. i++;
  211. }
  212. }
  213. return i;
  214. }
  215. #ifdef WOLFSSL_ASN_TEMPLATE
  216. /* Calculate the size of a DER encoded length value.
  217. *
  218. * 0 -> 2^7-1: <length byte>.
  219. * 2^7 -> : <0x80 + #bytes> <big-endian length bytes>
  220. *
  221. * @param [in] length Value to encode.
  222. * @return Number of bytes required to encode.
  223. */
  224. static word32 SizeASNLength(word32 length)
  225. {
  226. return 1 + ((length >= ASN_LONG_LENGTH) ? BytePrecision(length) : 0);
  227. }
  228. /* Calculate the size of a DER encoded header.
  229. *
  230. * Header = Tag | Encoded length
  231. *
  232. * @param [in] length Length value to encode.
  233. * @return Number of bytes required to encode a DER header.
  234. */
  235. #define SizeASNHeader(length) \
  236. (1 + SizeASNLength(length))
  237. #endif
  238. #ifdef WOLFSSL_ASN_TEMPLATE
  239. #ifdef WOLFSSL_SMALL_STACK
  240. /* Declare the variable that is the dynamic data for decoding BER data.
  241. *
  242. * @param [in] name Variable name to declare.
  243. * @param [in] cnt Number of elements required.
  244. */
  245. #define DECL_ASNGETDATA(name, cnt) \
  246. ASNGetData* name = NULL;
  247. /* Allocates the dynamic BER decoding data.
  248. *
  249. * @param [in] name Variable name to declare.
  250. * @param [in] cnt Number of elements required.
  251. * @param [in, out] err Error variable.
  252. * @param [in] heap Dynamic memory allocation hint.
  253. */
  254. #define ALLOC_ASNGETDATA(name, cnt, err, heap) \
  255. do { \
  256. if (err == 0) { \
  257. name = (ASNGetData*)XMALLOC(sizeof(ASNGetData) * cnt, heap, \
  258. DYNAMIC_TYPE_TMP_BUFFER); \
  259. if (name == NULL) { \
  260. err = MEMORY_E; \
  261. } \
  262. } \
  263. } \
  264. while (0)
  265. /* Allocates the dynamic BER decoding data and clears the memory.
  266. *
  267. * @param [in] name Variable name to declare.
  268. * @param [in] cnt Number of elements required.
  269. * @param [in, out] err Error variable.
  270. * @param [in] heap Dynamic memory allocation hint.
  271. */
  272. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  273. do { \
  274. ALLOC_ASNGETDATA(name, cnt, err, heap); \
  275. if (err == 0) { \
  276. XMEMSET(name, 0, sizeof(ASNGetData) * cnt); \
  277. } \
  278. } \
  279. while (0)
  280. /* Disposes of the dynamic BER decoding data.
  281. *
  282. * @param [in] name Variable name to declare.
  283. * @param [in] heap Dynamic memory allocation hint.
  284. */
  285. #define FREE_ASNGETDATA(name, heap) \
  286. do { \
  287. if (name != NULL) { \
  288. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  289. } \
  290. } \
  291. while (0)
  292. /* Declare the variable that is the dynamic data for encoding DER data.
  293. *
  294. * @param [in] name Variable name to declare.
  295. * @param [in] cnt Number of elements required.
  296. */
  297. #define DECL_ASNSETDATA(name, cnt) \
  298. ASNSetData* name = NULL;
  299. /* Allocates the dynamic DER encoding data.
  300. *
  301. * @param [in] name Variable name to declare.
  302. * @param [in] cnt Number of elements required.
  303. * @param [in, out] err Error variable.
  304. * @param [in] heap Dynamic memory allocation hint.
  305. */
  306. #define ALLOC_ASNSETDATA(name, cnt, err, heap) \
  307. do { \
  308. if (err == 0) { \
  309. name = (ASNSetData*)XMALLOC(sizeof(ASNGetData) * cnt, heap, \
  310. DYNAMIC_TYPE_TMP_BUFFER); \
  311. if (name == NULL) { \
  312. err = MEMORY_E; \
  313. } \
  314. } \
  315. } \
  316. while (0)
  317. /* Allocates the dynamic DER encoding data and clears the memory.
  318. *
  319. * @param [in] name Variable name to declare.
  320. * @param [in] cnt Number of elements required.
  321. * @param [in, out] err Error variable.
  322. * @param [in] heap Dynamic memory allocation hint.
  323. */
  324. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  325. do { \
  326. ALLOC_ASNSETDATA(name, cnt, err, heap); \
  327. if (err == 0) { \
  328. XMEMSET(name, 0, sizeof(ASNSetData) * cnt); \
  329. } \
  330. } \
  331. while (0)
  332. /* Disposes of the dynamic DER encoding data.
  333. *
  334. * @param [in] name Variable name to declare.
  335. * @param [in] heap Dynamic memory allocation hint.
  336. */
  337. #define FREE_ASNSETDATA(name, heap) \
  338. do { \
  339. if (name != NULL) { \
  340. XFREE(name, heap, DYNAMIC_TYPE_TMP_BUFFER); \
  341. } \
  342. } \
  343. while (0)
  344. #else
  345. /* Declare the variable that is the dynamic data for decoding BER data.
  346. *
  347. * @param [in] name Variable name to declare.
  348. * @param [in] cnt Number of elements required.
  349. */
  350. #define DECL_ASNGETDATA(name, cnt) \
  351. ASNGetData name[cnt];
  352. /* No implementation as declartion is static.
  353. *
  354. * @param [in] name Variable name to declare.
  355. * @param [in] cnt Number of elements required.
  356. * @param [in, out] err Error variable.
  357. * @param [in] heap Dynamic memory allocation hint.
  358. */
  359. #define ALLOC_ASNGETDATA(name, cnt, err, heap)
  360. /* Clears the memory of the dynamic BER encoding data.
  361. *
  362. * @param [in] name Variable name to declare.
  363. * @param [in] cnt Number of elements required.
  364. * @param [in, out] err Error variable.
  365. * @param [in] heap Dynamic memory allocation hint.
  366. */
  367. #define CALLOC_ASNGETDATA(name, cnt, err, heap) \
  368. XMEMSET(name, 0, sizeof(name));
  369. /* No implementation as declartion is static.
  370. *
  371. * @param [in] name Variable name to declare.
  372. * @param [in] heap Dynamic memory allocation hint.
  373. */
  374. #define FREE_ASNGETDATA(name, heap)
  375. /* Declare the variable that is the dynamic data for encoding DER data.
  376. *
  377. * @param [in] name Variable name to declare.
  378. * @param [in] cnt Number of elements required.
  379. */
  380. #define DECL_ASNSETDATA(name, cnt) \
  381. ASNSetData name[cnt];
  382. /* No implementation as declartion is static.
  383. *
  384. * @param [in] name Variable name to declare.
  385. * @param [in] cnt Number of elements required.
  386. * @param [in, out] err Error variable.
  387. * @param [in] heap Dynamic memory allocation hint.
  388. */
  389. #define ALLOC_ASNSETDATA(name, cnt, err, heap)
  390. /* Clears the memory of the dynamic BER encoding data.
  391. *
  392. * @param [in] name Variable name to declare.
  393. * @param [in] cnt Number of elements required.
  394. * @param [in, out] err Error variable.
  395. * @param [in] heap Dynamic memory allocation hint.
  396. */
  397. #define CALLOC_ASNSETDATA(name, cnt, err, heap) \
  398. XMEMSET(name, 0, sizeof(name));
  399. /* No implementation as declartion is static.
  400. *
  401. * @param [in] name Variable name to declare.
  402. * @param [in] heap Dynamic memory allocation hint.
  403. */
  404. #define FREE_ASNSETDATA(name, heap)
  405. #endif
  406. #ifdef DEBUG_WOLFSSL
  407. /* Enable this when debugging the parsing or creation of ASN.1 data. */
  408. #if 0
  409. #define WOLFSSL_DEBUG_ASN_TEMPLATE
  410. #endif
  411. #endif
  412. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  413. /* String representations of tags. */
  414. static const char* tagString[4][32] = {
  415. /* Universal */
  416. {
  417. "EOC",
  418. "BOOLEAN",
  419. "INTEGER",
  420. "BIT STRING",
  421. "OCTET STRING",
  422. "NULL",
  423. "OBJECT ID",
  424. "ObjectDescriptor",
  425. "INSTANCE OF",
  426. "REAL",
  427. "ENUMERATED",
  428. "EMBEDDED PDV",
  429. "UT8String",
  430. "RELATIVE-OID",
  431. "(0x0e) 14",
  432. "(0x0f) 15",
  433. "SEQUENCE",
  434. "SET",
  435. "NumericString",
  436. "PrintableString",
  437. "T61String",
  438. "VideotexString",
  439. "IA5String",
  440. "UTCTime",
  441. "GeneralizedTime",
  442. "GraphicString",
  443. "ISO646String",
  444. "GeneralString",
  445. "UniversalString",
  446. "CHARACTER STRING",
  447. "BMPString",
  448. "(0x1f) 31",
  449. },
  450. /* Application */
  451. {
  452. "[A 0]", "[A 1]", "[A 2]", "[A 3]",
  453. "[A 4]", "[A 5]", "[A 6]", "[A 7]",
  454. "[A 8]", "[A 9]", "[A 10]", "[A 11]",
  455. "[A 12]", "[A 13]", "[A 14]", "[A 15]",
  456. "[A 16]", "[A 17]", "[A 18]", "[A 19]",
  457. "[A 20]", "[A 21]", "[A 22]", "[A 23]",
  458. "[A 24]", "[A 25]", "[A 26]", "[A 27]",
  459. "[A 28]", "[A 20]", "[A 30]", "[A 31]"
  460. },
  461. /* Context-Specific */
  462. {
  463. "[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]",
  464. "[8]", "[9]", "[10]", "[11]", "[12]", "[13]", "[14]", "[15]",
  465. "[16]", "[17]", "[18]", "[19]", "[20]", "[21]", "[22]", "[23]",
  466. "[24]", "[25]", "[26]", "[27]", "[28]", "[20]", "[30]", "[31]"
  467. },
  468. /* Private */
  469. {
  470. "[P 0]", "[P 1]", "[P 2]", "[P 3]",
  471. "[P 4]", "[P 5]", "[P 6]", "[P 7]",
  472. "[P 8]", "[P 9]", "[P 10]", "[P 11]",
  473. "[P 12]", "[P 13]", "[P 14]", "[P 15]",
  474. "[P 16]", "[P 17]", "[P 18]", "[P 19]",
  475. "[P 20]", "[P 21]", "[P 22]", "[P 23]",
  476. "[P 24]", "[P 25]", "[P 26]", "[P 27]",
  477. "[P 28]", "[P 20]", "[P 30]", "[P 31]"
  478. }
  479. };
  480. /* Converts a tag byte to string.
  481. *
  482. * @param [in] tag BER tag value to interpret.
  483. * @return String corresponding to tag.
  484. */
  485. static const char* TagString(byte tag)
  486. {
  487. return tagString[tag >> 6][tag & ASN_TYPE_MASK];
  488. }
  489. #include <stdarg.h>
  490. /* Log a message that has the printf format string.
  491. *
  492. * @param [in] <va_args> printf style arguments.
  493. */
  494. #define WOLFSSL_MSG_VSNPRINTF(...) \
  495. do { \
  496. char line[81]; \
  497. snprintf(line, sizeof(line) - 1, __VA_ARGS__); \
  498. line[sizeof(line) - 1] = '\0'; \
  499. WOLFSSL_MSG(line); \
  500. } \
  501. while (0)
  502. #endif
  503. /* Returns whether ASN.1 item is an integer and the Most-Significant Bit is set.
  504. *
  505. * @param [in] asn ASN.1 items to encode.
  506. * @param [in] data Data to place in each item. Lengths set were not known.
  507. * @param [in] i Index of item to check.
  508. * @return 1 when ASN.1 item is an integer and MSB is 1.
  509. * @erturn 0 otherwise.
  510. */
  511. #define ASNIntMSBSet(asn, data, i) \
  512. ((asn[i].tag == ASN_INTEGER) && \
  513. (data[i].data.buffer.data != NULL && \
  514. (data[i].data.buffer.data[0] & 0x80) == 0x80))
  515. /* Calculate the size of a DER encoded number.
  516. *
  517. * @param [in] n Number to be encoded.
  518. * @param [in] bits Maximum number of bits to encode.
  519. * @param [in] tag BER tag e.g. INTEGER, BIT_STRING, etc.
  520. * @return Number of bytes to the ASN.1 item.
  521. */
  522. static word32 SizeASN_Num(word32 n, int bits, byte tag)
  523. {
  524. int j;
  525. word32 len;
  526. len = 1 + 1 + bits / 8;
  527. /* Discover actual size by checking for high zeros. */
  528. for (j = bits - 8; j > 0; j -= 8) {
  529. if (n >> j)
  530. break;
  531. len--;
  532. }
  533. if (tag == ASN_BIT_STRING)
  534. len++;
  535. else if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80))
  536. len++;
  537. return len;
  538. }
  539. /* Calculate the size of the data in the constructed item based on the
  540. * length of the ASN.1 items below.
  541. *
  542. * @param [in] asn ASN.1 items to encode.
  543. * @param [in, out] data Data to place in each item. Lengths set were not
  544. * known.
  545. * @param [in] idx Index of item working on.
  546. */
  547. static void SizeASN_CalcDataLength(const ASNItem* asn, ASNSetData *data,
  548. int idx, int max)
  549. {
  550. int j;
  551. data[idx].data.buffer.length = 0;
  552. /* Sum the item length of all items underneath. */
  553. for (j = idx + 1; j < max; j++) {
  554. /* Stop looking if the next ASN.1 is same level or higher. */
  555. if (asn[j].depth <= asn[idx].depth)
  556. break;
  557. /* Only add in length if it is one level below. */
  558. if (asn[j].depth - 1 == asn[idx].depth) {
  559. data[idx].data.buffer.length += data[j].length;
  560. /* The length of a header only item doesn't include the data unless
  561. * a replacement buffer is supplied.
  562. */
  563. if (asn[j].headerOnly && data[j].data.buffer.data == NULL &&
  564. data[j].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  565. data[idx].data.buffer.length += data[j].data.buffer.length;
  566. }
  567. }
  568. }
  569. }
  570. /* Calculate the size of the DER encoding.
  571. *
  572. * Call SetASN_Items() to write encoding to a buffer.
  573. *
  574. * @param [in] asn ASN.1 items to encode.
  575. * @param [in, out] data Data to place in each item. Lengths set were not
  576. * known.
  577. * @param [in] count Count of items to encode.
  578. * @param [out] encSz Length of the DER encoding.
  579. * @return 0 on success.
  580. * @return BAD_STATE_E when the data type is not supported.
  581. */
  582. int SizeASN_Items(const ASNItem* asn, ASNSetData *data, int count, int* encSz)
  583. {
  584. int i;
  585. word32 sz = 0;
  586. word32 len;
  587. word32 dataLen;
  588. int length;
  589. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  590. WOLFSSL_ENTER("SizeASN_Items");
  591. #endif
  592. for (i = count - 1; i >= 0; i--) {
  593. /* Skip this ASN.1 item when encoding. */
  594. if (data[i].noOut) {
  595. /* Set the offset to the current size - used in writing DER. */
  596. data[i].offset = sz;
  597. continue;
  598. }
  599. len = 0;
  600. switch (data[i].dataType) {
  601. /* Calculate the size of the number of different sizes. */
  602. case ASN_DATA_TYPE_WORD8:
  603. len = SizeASN_Num(data[i].data.u8, 8, asn[i].tag);
  604. break;
  605. case ASN_DATA_TYPE_WORD16:
  606. len = SizeASN_Num(data[i].data.u16, 16, asn[i].tag);
  607. break;
  608. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  609. /* Not used yet! */
  610. case ASN_DATA_TYPE_WORD32:
  611. len = SizeASN_Num(data[i].data.u32, 32, asn[i].tag);
  612. break;
  613. #endif
  614. case ASN_DATA_TYPE_MP:
  615. /* Calculate the size of the MP integer data. */
  616. length = mp_unsigned_bin_size(data[i].data.mp);
  617. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  618. len = SizeASNHeader(length) + length;
  619. break;
  620. case ASN_DATA_TYPE_REPLACE_BUFFER:
  621. /* Buffer is put in directly - use the length. */
  622. len = data[i].data.buffer.length;
  623. break;
  624. case ASN_DATA_TYPE_NONE:
  625. /* Calculate the size based on the data to be included.
  626. * Mostly used for constructed items.
  627. */
  628. if (asn[i].headerOnly) {
  629. if (data[i].data.buffer.data != NULL) {
  630. /* Force all child nodes to be ignored. Buffer
  631. * overwrites children. */
  632. SetASNItem_NoOutBelow(data, asn, i, count);
  633. }
  634. else {
  635. /* Calculate data length from items below if no buffer
  636. * supplied. */
  637. SizeASN_CalcDataLength(asn, data, i, count);
  638. }
  639. }
  640. if (asn[i].tag == ASN_BOOLEAN) {
  641. dataLen = 1;
  642. }
  643. else {
  644. dataLen = data[i].data.buffer.length;
  645. }
  646. /* BIT_STRING and INTEGER have one byte prepended. */
  647. if ((asn[i].tag == ASN_BIT_STRING) ||
  648. ASNIntMSBSet(asn, data, i)) {
  649. dataLen++;
  650. /* ASN.1 items are below and cannot include extra byte. */
  651. if (asn[i].headerOnly) {
  652. len++;
  653. }
  654. }
  655. /* Add in the size of tag and length. */
  656. len += SizeASNHeader(dataLen);
  657. /* Include data in length if not header only or if
  658. * buffer supplied. */
  659. if (!asn[i].headerOnly || data[i].data.buffer.data != NULL) {
  660. len += dataLen;
  661. }
  662. break;
  663. #ifdef DEBUG_WOLFSSL
  664. default:
  665. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  666. WOLFSSL_MSG_VSNPRINTF("%2d: %d", i, data[i].dataType);
  667. WOLFSSL_MSG("Bad data type");
  668. #endif
  669. return BAD_STATE_E;
  670. #endif
  671. }
  672. /* Set the total length of the item. */
  673. data[i].length = len;
  674. /* Add length to total size. */
  675. sz += len;
  676. /* Set the offset to the current size - used in writing DER. */
  677. data[i].offset = sz;
  678. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  679. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  680. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  681. asn[i].depth, "", TagString(asn[i].tag));
  682. #endif
  683. }
  684. *encSz = sz;
  685. return 0;
  686. }
  687. /* Create the DER encoding of a number.
  688. *
  689. * Assumes that the out buffer is large enough for encoding.
  690. *
  691. * @param [in] n Number to be encoded.
  692. * @param [in] bits Maximum number of bits to encode.
  693. * @param [in] tag DER tag e.g. INTEGER, BIT_STRING, etc.
  694. */
  695. static void SetASN_Num(word32 n, int bits, byte* out, byte tag)
  696. {
  697. int j;
  698. word32 idx;
  699. byte len;
  700. /* Encoding: Tag (1 byte) | Length (1 byte) | Data (number) */
  701. /* Data will start at index 2 unless BIT_STRING or INTEGER */
  702. idx = 2;
  703. /* Set the length of the number based on maximum bit length. */
  704. len = bits / 8;
  705. /* Discover actual size by checking for leading zero bytes. */
  706. for (j = bits - 8; j > 0; j -= 8) {
  707. if ((n >> j) != 0) {
  708. break;
  709. }
  710. len--;
  711. }
  712. /* Keep j, index of first non-zero byte, for writing out. */
  713. /* A BIT_STRING has the number of unused bits in last byte prepended to
  714. * data.
  715. */
  716. if (tag == ASN_BIT_STRING) {
  717. byte unusedBits = 0;
  718. byte lastByte = n >> j;
  719. /* Quick check last bit. */
  720. if ((lastByte & 0x01) == 0x00) {
  721. unusedBits++;
  722. /* Check each bit for first least significant bit set. */
  723. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  724. unusedBits++;
  725. }
  726. /* Add unused bits byte. */
  727. len++;
  728. out[idx++] = unusedBits;
  729. }
  730. /* An INTEGER has a prepended byte if MSB of number is 1 - makes encoded
  731. * value positive. */
  732. if ((tag == ASN_INTEGER) && (((n >> j) & 0x80) == 0x80)) {
  733. len++;
  734. out[idx++] = 0;
  735. }
  736. /* Go back and put in length. */
  737. out[1] = len;
  738. /* Place in the required bytes of the number. */
  739. for (; j >= 0; j -= 8)
  740. out[idx++] = n >> j;
  741. }
  742. /* Creates the DER encoding of the ASN.1 items.
  743. *
  744. * Assumes the output buffer is large enough to hold encoding.
  745. * Must call SizeASN_Items() to determine size of encoding and offsets.
  746. *
  747. * @param [in] asn ASN.1 items to encode.
  748. * @param [in] data Data to place in each item.
  749. * @param [in] count Count of items to encode.
  750. * @param [in, out] output Buffer to write encoding into.
  751. * @return Size of the DER encoding in bytes.
  752. */
  753. int SetASN_Items(const ASNItem* asn, ASNSetData *data, int count, byte* output)
  754. {
  755. int i;
  756. int length;
  757. int err;
  758. word32 sz;
  759. word32 idx;
  760. byte* out;
  761. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  762. WOLFSSL_ENTER("SetASN_Items");
  763. #endif
  764. /* Offset of first item is the total length.
  765. * SizeASN_Items() calculated this. */
  766. sz = data[0].offset;
  767. /* Write out each item. */
  768. for (i = 0; i < count; i++) {
  769. /* Skip items not writing out. */
  770. if (data[i].noOut)
  771. continue;
  772. /* Start position to write item based on reverse offsets. */
  773. out = output + sz - data[i].offset;
  774. /* Index from start of item out. */
  775. idx = 0;
  776. if (data[i].dataType != ASN_DATA_TYPE_REPLACE_BUFFER) {
  777. /* Put in the tag - not dumping in DER from buffer. */
  778. out[idx++] = asn[i].tag |
  779. (asn[i].constructed ? ASN_CONSTRUCTED : 0);
  780. }
  781. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  782. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  783. sz - data[i].offset,
  784. data[i].length, asn[i].constructed ? '+' : ' ', asn[i].depth,
  785. "", TagString(asn[i].tag));
  786. #endif
  787. switch (data[i].dataType) {
  788. /* Write out the length and data of a number. */
  789. case ASN_DATA_TYPE_WORD8:
  790. SetASN_Num(data[i].data.u8, 8, out, asn[i].tag);
  791. break;
  792. case ASN_DATA_TYPE_WORD16:
  793. SetASN_Num(data[i].data.u16, 16, out, asn[i].tag);
  794. break;
  795. #ifdef WOLFSSL_ASN_TEMPLATE_NEED_SET_INT32
  796. /* Not used yet! */
  797. case ASN_DATA_TYPE_WORD32:
  798. SetASN_Num(data[i].data.u32, 32, out, asn[i].tag);
  799. break;
  800. #endif
  801. /* Write out the length and data of a multi-precision number. */
  802. case ASN_DATA_TYPE_MP:
  803. /* Get length in bytes. */
  804. length = mp_unsigned_bin_size(data[i].data.mp);
  805. /* Add one for leading zero to make encoding a positive num. */
  806. length += mp_leading_bit(data[i].data.mp) ? 1 : 0;
  807. /* Write out length. */
  808. idx += SetASNLength(length, out + idx);
  809. /* Write out leading zero to make positive. */
  810. if (mp_leading_bit(data[i].data.mp)) {
  811. out[idx++] = 0;
  812. }
  813. /* Encode number in big-endian byte array. */
  814. err = mp_to_unsigned_bin(data[i].data.mp, out + idx);
  815. if (err != MP_OKAY) {
  816. WOLFSSL_MSG("SetASN_Items: Failed to write mp_int");
  817. return MP_TO_E;
  818. }
  819. break;
  820. case ASN_DATA_TYPE_REPLACE_BUFFER:
  821. if (data[i].data.buffer.data == NULL) {
  822. /* Return pointer for caller to use. */
  823. data[i].data.buffer.data = out + idx;
  824. }
  825. else {
  826. /* Dump in the DER encoded data. */
  827. XMEMCPY(out + idx, data[i].data.buffer.data,
  828. data[i].data.buffer.length);
  829. }
  830. break;
  831. case ASN_DATA_TYPE_NONE:
  832. if (asn[i].tag == ASN_BOOLEAN) {
  833. /* Always one byte of data. */
  834. out[idx++] = 1;
  835. /* TRUE = 0xff, FALSE = 0x00 */
  836. out[idx] = data[i].data.u8 ? -1 : 0;
  837. }
  838. else if (asn[i].tag == ASN_TAG_NULL) {
  839. /* NULL tag is always a zero length item. */
  840. out[idx] = 0;
  841. }
  842. else {
  843. word32 dataLen = data[i].data.buffer.length;
  844. /* Add one to data length for BIT_STRING unused bits and
  845. * INTEGER leading zero to make positive.
  846. */
  847. if ((asn[i].tag == ASN_BIT_STRING) ||
  848. ASNIntMSBSet(asn, data, i)) {
  849. dataLen++;
  850. }
  851. /* Write out length. */
  852. idx += SetASNLength(dataLen, out + idx);
  853. if ((asn[i].tag == ASN_BIT_STRING) ||
  854. ASNIntMSBSet(asn, data, i)) {
  855. /* Write out leading byte. BIT_STRING has no unused bits
  856. * - use number data types if needed. */
  857. out[idx++] = 0x00;
  858. }
  859. /* Record pointer for caller if data not supplied. */
  860. if (data[i].data.buffer.data == NULL) {
  861. data[i].data.buffer.data = out + idx;
  862. }
  863. /* Copy supplied data if not putting out header only or
  864. * if buffer supplied. */
  865. else if (!asn[i].headerOnly ||
  866. data[i].data.buffer.data != NULL) {
  867. /* Allow data to come from output buffer. */
  868. XMEMMOVE(out + idx, data[i].data.buffer.data,
  869. data[i].data.buffer.length);
  870. }
  871. }
  872. break;
  873. #ifdef DEBUG_WOLFSSL
  874. default:
  875. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  876. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data[i].dataType);
  877. #endif
  878. return BAD_STATE_E;
  879. #endif
  880. }
  881. }
  882. return sz;
  883. }
  884. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  885. word32 oidType, int length);
  886. /* Maximum supported depth in ASN.1 description. */
  887. #define GET_ASN_MAX_DEPTH 7
  888. /* Maximum number of checked numbered choices. Only one of the items with the
  889. * number is allowed.
  890. */
  891. #define GET_ASN_MAX_CHOICES 2
  892. /* Use existing function to decode BER length encoding. */
  893. #define GetASN_Length GetLength_ex
  894. /* Check an INTEGER's first byte - must be a positive number.
  895. *
  896. * @param [in] input BER encoded data.
  897. * @param [in] idx Index of BIT_STRING data.
  898. * @param [in] length Length of input data.
  899. * @param [in] positive Indicates number must be positive.
  900. * @return 0 on success.
  901. * @return ASN_PARSE_E when 0 is not required but seen.
  902. * @return ASN_EXPECT_0_E when 0 is required and not seen.
  903. */
  904. static int GetASN_Integer(const byte* input, word32 idx, int length,
  905. int positive)
  906. {
  907. if (input[idx] == 0) {
  908. /* Check leading zero byte required. */
  909. if ((length > 1) && ((input[idx + 1] & 0x80) == 0)) {
  910. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  911. WOLFSSL_MSG("Zero not required on INTEGER");
  912. #endif
  913. return ASN_PARSE_E;
  914. }
  915. }
  916. /* Check whether a leading zero byte was required. */
  917. else if (positive && (input[idx] & 0x80)) {
  918. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  919. WOLFSSL_MSG("INTEGER is negative");
  920. #endif
  921. return ASN_EXPECT_0_E;
  922. }
  923. return 0;
  924. }
  925. /* Check a BIT_STRING's first byte - unused bits.
  926. *
  927. * @param [in] input BER encoded data.
  928. * @param [in] idx Index of BIT_STRING data.
  929. * @param [in] length Length of input data.
  930. * @return 0 on success.
  931. * @return ASN_PARSE_E when unused bits is invalid.
  932. */
  933. static int GetASN_BitString(const byte* input, word32 idx, int length)
  934. {
  935. /* Ensure unused bits value is valid range. */
  936. if (input[idx] > 7) {
  937. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  938. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits too big: %d > 7",
  939. input[idx]);
  940. #endif
  941. return ASN_PARSE_E;
  942. }
  943. /* Ensure unused bits are zero. */
  944. if ((byte)(input[idx + length - 1] << (8 - input[idx])) != 0) {
  945. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  946. WOLFSSL_MSG_VSNPRINTF("BIT STRING unused bits used: %d %02x",
  947. input[idx], input[idx + length - 1]);
  948. #endif
  949. return ASN_PARSE_E;
  950. }
  951. return 0;
  952. }
  953. /* Get the ASN.1 items from the BER encoding.
  954. *
  955. * @param [in] asn ASN.1 item expected.
  956. * @param [in] data Data array to place found item into.
  957. * @param [in] input BER encoded data.
  958. * @param [in] idx Starting index of item data.
  959. * @param [in] len Length of input buffer upto end of this item's data.
  960. * @param [in] zeroPadded INTEGER was zero padded to make positive.
  961. * @return 0 on success.
  962. * @return ASN_PARSE_E when BER encoded data is invalid.
  963. * @return ASN_EXPECT_0_E when NULL tagged item has a non-zero length.
  964. * @return MP_INIT_E when the unable to initialize an mp_int.
  965. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  966. * @return BAD_STATE_E when the data type is not supported.
  967. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  968. */
  969. static int GetASN_StoreData(const ASNItem* asn, ASNGetData* data,
  970. const byte* input, word32 idx, int len,
  971. int zeroPadded)
  972. {
  973. int i;
  974. int err;
  975. /* Parse data based on data type to extract. */
  976. switch (data->dataType) {
  977. /* Parse a data into a number of specified bits. */
  978. case ASN_DATA_TYPE_WORD8:
  979. /* Check data is small enough to fit. */
  980. if (len != 1) {
  981. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  982. WOLFSSL_MSG_VSNPRINTF("Expecting one byte: %d", len);
  983. #endif
  984. return ASN_PARSE_E;
  985. }
  986. /* Fill number with all of data. */
  987. *data->data.u8 = input[idx];
  988. break;
  989. case ASN_DATA_TYPE_WORD16:
  990. /* Check data is small enough to fit. */
  991. if (len == 0 || len > 2) {
  992. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  993. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", len);
  994. #endif
  995. return ASN_PARSE_E;
  996. }
  997. /* Fill number with all of data. */
  998. *data->data.u16 = 0;
  999. for (i = 0; i < len; i++) {
  1000. *data->data.u16 <<= 8;
  1001. *data->data.u16 |= input[idx + i] ;
  1002. }
  1003. break;
  1004. case ASN_DATA_TYPE_WORD32:
  1005. /* Check data is small enough to fit. */
  1006. if (len == 0 || len > 4) {
  1007. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1008. WOLFSSL_MSG_VSNPRINTF("Expecting 1 to 4 bytes: %d", len);
  1009. #endif
  1010. return ASN_PARSE_E;
  1011. }
  1012. /* Fill number with all of data. */
  1013. *data->data.u32 = 0;
  1014. for (i = 0; i < len; i++) {
  1015. *data->data.u32 <<= 8;
  1016. *data->data.u32 |= input[idx + i] ;
  1017. }
  1018. break;
  1019. case ASN_DATA_TYPE_BUFFER:
  1020. /* Check buffer is big enough to hold data. */
  1021. if (len > (int)*data->data.buffer.length) {
  1022. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1023. WOLFSSL_MSG_VSNPRINTF("Buffer too small for data: %d %d", len,
  1024. *data->data.buffer.length);
  1025. #endif
  1026. return ASN_PARSE_E;
  1027. }
  1028. /* Copy in data and record actual length seen. */
  1029. XMEMCPY(data->data.buffer.data, input + idx, len);
  1030. *data->data.buffer.length = len;
  1031. break;
  1032. case ASN_DATA_TYPE_EXP_BUFFER:
  1033. /* Check data is same size expected. */
  1034. if (len != (int)data->data.ref.length) {
  1035. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1036. WOLFSSL_MSG_VSNPRINTF("Data not expected length: %d %d", len,
  1037. data->data.ref.length);
  1038. #endif
  1039. return ASN_PARSE_E;
  1040. }
  1041. /* Check data is same as expected. */
  1042. if (XMEMCMP(data->data.ref.data, input + idx, len) != 0) {
  1043. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1044. WOLFSSL_MSG("Data not as expected");
  1045. #endif
  1046. return ASN_PARSE_E;
  1047. }
  1048. break;
  1049. case ASN_DATA_TYPE_MP:
  1050. case ASN_DATA_TYPE_MP_POS_NEG:
  1051. /* Initialize mp_int and read in big-endian byte array. */
  1052. if (mp_init(data->data.mp) != MP_OKAY) {
  1053. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1054. WOLFSSL_MSG_VSNPRINTF("Failed to init mp: %p", data->data.mp);
  1055. #endif
  1056. return MP_INIT_E;
  1057. }
  1058. err = mp_read_unsigned_bin(data->data.mp, (byte*)input + idx, len);
  1059. if (err != 0) {
  1060. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1061. WOLFSSL_MSG_VSNPRINTF("Failed to read mp: %d", err);
  1062. #endif
  1063. mp_clear(data->data.mp);
  1064. return ASN_GETINT_E;
  1065. }
  1066. #ifdef HAVE_WOLF_BIGINT
  1067. err = wc_bigint_from_unsigned_bin(&data->data.mp->raw, input + idx,
  1068. len);
  1069. if (err != 0) {
  1070. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1071. WOLFSSL_MSG_VSNPRINTF("Failed to create bigint: %d", err);
  1072. #endif
  1073. mp_clear(data->data.mp);
  1074. return ASN_GETINT_E;
  1075. }
  1076. #endif /* HAVE_WOLF_BIGINT */
  1077. /* Don't always read as positive. */
  1078. if ((data->dataType == ASN_DATA_TYPE_MP_POS_NEG) && (!zeroPadded) &&
  1079. (input[idx] & 0x80)) {
  1080. data->data.mp->sign = MP_NEG;
  1081. }
  1082. break;
  1083. case ASN_DATA_TYPE_CHOICE:
  1084. /* Check if tag matched any of the choices specified. */
  1085. for (i = 0; data->data.choice[i] != 0; i++)
  1086. if (data->data.choice[i] == data->tag)
  1087. break;
  1088. if (data->data.choice[i] == 0) {
  1089. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1090. WOLFSSL_MSG("Tag didn't match a choice");
  1091. #endif
  1092. return ASN_PARSE_E;
  1093. }
  1094. /* Store data pointer and length for caller. */
  1095. data->data.ref.data = input + idx;
  1096. data->data.ref.length = len;
  1097. break;
  1098. case ASN_DATA_TYPE_NONE:
  1099. /* Default behaviour based on tag. */
  1100. if (asn->tag == ASN_BOOLEAN) {
  1101. /* BOOLEAN has only one byte of data in BER. */
  1102. if (len != 1) {
  1103. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1104. WOLFSSL_MSG_VSNPRINTF("BOOLEAN length too long: %d", len);
  1105. #endif
  1106. return ASN_PARSE_E;
  1107. }
  1108. /* Store C boolean value. */
  1109. *data->data.u8 = (input[idx] != 0);
  1110. break;
  1111. }
  1112. if (asn->tag == ASN_TAG_NULL) {
  1113. /* NULL has no data in BER. */
  1114. if (len != 0) {
  1115. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1116. WOLFSSL_MSG_VSNPRINTF("NULL length too long: %d", len);
  1117. #endif
  1118. return ASN_EXPECT_0_E;
  1119. }
  1120. data->data.ref.data = input + idx;
  1121. break;
  1122. }
  1123. if (asn->tag == ASN_OBJECT_ID) {
  1124. word32 oidIdx = 0;
  1125. /* Store OID data pointer and length */
  1126. data->data.oid.data = input + idx;
  1127. data->data.oid.length = len;
  1128. /* Get the OID sum. */
  1129. err = GetOID(input + idx, &oidIdx, &data->data.oid.sum,
  1130. data->data.oid.type, len);
  1131. if (err < 0) {
  1132. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1133. WOLFSSL_MSG_VSNPRINTF("OID check failed: %d", err);
  1134. #endif
  1135. return err;
  1136. }
  1137. break;
  1138. }
  1139. /* Otherwise store data pointer and length. */
  1140. data->data.ref.data = input + idx;
  1141. data->data.ref.length = len;
  1142. break;
  1143. #ifdef DEBUG_WOLFSSL
  1144. default:
  1145. /* Bad ASN data type. */
  1146. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1147. WOLFSSL_MSG_VSNPRINTF("Bad data type: %d", data->dataType);
  1148. #endif
  1149. return BAD_STATE_E;
  1150. #endif
  1151. }
  1152. return 0;
  1153. }
  1154. /* Get the ASN.1 items from the BER encoding.
  1155. *
  1156. * @param [in] asn ASN.1 items expected.
  1157. * @param [in] data Data array to place found items into.
  1158. * @param [in] count Count of items to parse.
  1159. * @param [in] complete Whether the whole buffer is to be used up.
  1160. * @param [in] input BER encoded data.
  1161. * @param [in, out] inOutIdx On in, starting index of data.
  1162. * On out, end of parsed data.
  1163. * @param [in] length Length of input buffer.
  1164. * @return 0 on success.
  1165. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1166. * is invalid.
  1167. * @return BUFFER_E when data in buffer is too small.
  1168. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1169. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1170. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1171. * non-zero length.
  1172. * @return MP_INIT_E when the unable to initialize an mp_int.
  1173. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1174. * @return BAD_STATE_E when the data type is not supported.
  1175. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  1176. */
  1177. int GetASN_Items(const ASNItem* asn, ASNGetData *data, int count, int complete,
  1178. const byte* input, word32* inOutIdx, word32 length)
  1179. {
  1180. int i;
  1181. int j;
  1182. int err;
  1183. int len;
  1184. /* Current index into buffer. */
  1185. word32 idx = *inOutIdx;
  1186. /* Initialize the end index at each depth to be the length. */
  1187. word32 endIdx[GET_ASN_MAX_DEPTH] = { length, length, length, length, length,
  1188. length, length };
  1189. /* Set choices to -1 to indicate they haven't been seen or found. */
  1190. char choiceMet[GET_ASN_MAX_CHOICES] = { -1, -1 };
  1191. /* Not matching a choice right now. */
  1192. int choice = 0;
  1193. /* Current depth of ASN.1 item. */
  1194. int depth;
  1195. /* Minimum depth value seen. */
  1196. int minDepth;
  1197. /* Integer had a zero prepended. */
  1198. int zeroPadded;
  1199. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1200. WOLFSSL_ENTER("GetASN_Items");
  1201. #endif
  1202. /* Start depth at first items depth. */
  1203. minDepth = depth = asn[0].depth;
  1204. /* Check every ASN.1 item. */
  1205. for (i = 0; i < count; i++) {
  1206. /* Store offset of ASN.1 item. */
  1207. data[i].offset = idx;
  1208. /* Length of data in ASN.1 item starts empty. */
  1209. data[i].length = 0;
  1210. /* Get current item depth. */
  1211. depth = asn[i].depth;
  1212. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1213. if (depth > GET_ASN_MAX_DEPTH) {
  1214. WOLFSSL_MSG("Depth in template too large");
  1215. return ASN_PARSE_E;
  1216. }
  1217. #endif
  1218. /* Keep track of minimum depth. */
  1219. if (depth < minDepth) {
  1220. minDepth = depth;
  1221. }
  1222. /* Reset choice if different from previous. */
  1223. if (choice > 0 && asn[i].optional != choice) {
  1224. choice = 0;
  1225. }
  1226. /* Check if first of numbered choice. */
  1227. if (choice == 0 && asn[i].optional > 1) {
  1228. choice = asn[i].optional;
  1229. if (choiceMet[choice - 2] == -1) {
  1230. /* Choice seen but not found a match yet. */
  1231. choiceMet[choice - 2] = 0;
  1232. }
  1233. }
  1234. /* Check for end of data or not a choice and tag not matching. */
  1235. if (idx == endIdx[depth] || (data[i].dataType != ASN_DATA_TYPE_CHOICE &&
  1236. (input[idx] & ~ASN_CONSTRUCTED) != asn[i].tag)) {
  1237. if (asn[i].optional) {
  1238. /* Skip over ASN.1 items underneath this optional item. */
  1239. for (j = i + 1; j < count; j++) {
  1240. if (asn[i].depth >= asn[j].depth)
  1241. break;
  1242. data[j].offset = idx;
  1243. data[j].length = 0;
  1244. }
  1245. i = j - 1;
  1246. continue;
  1247. }
  1248. /* Check for end of data. */
  1249. if (idx == length) {
  1250. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1251. WOLFSSL_MSG_VSNPRINTF(
  1252. "%2d: %4d %4d %c %*s %-16s%*s (index past end)",
  1253. i, data[i].offset, data[i].length,
  1254. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1255. TagString(asn[i].tag), 6 - asn[i].depth, "");
  1256. WOLFSSL_MSG_VSNPRINTF("Index past end of data: %d %d", idx,
  1257. length);
  1258. #endif
  1259. return BUFFER_E;
  1260. }
  1261. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1262. /* Show expected versus found. */
  1263. WOLFSSL_MSG_VSNPRINTF(
  1264. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1265. i, data[i].offset, data[i].length,
  1266. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1267. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1268. input[idx], TagString(input[idx]));
  1269. #endif
  1270. /* Check for end of data at this depth. */
  1271. if (idx == endIdx[depth]) {
  1272. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1273. WOLFSSL_MSG_VSNPRINTF("Index past outer item: %d %d", idx,
  1274. endIdx[depth]);
  1275. #endif
  1276. return ASN_PARSE_E;
  1277. }
  1278. /* Expecting an OBJECT_ID */
  1279. if (asn[i].tag == ASN_OBJECT_ID) {
  1280. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1281. WOLFSSL_MSG("Expecting OBJECT ID");
  1282. #endif
  1283. return ASN_OBJECT_ID_E;
  1284. }
  1285. /* Expecting a BIT_STRING */
  1286. if (asn[i].tag == ASN_BIT_STRING) {
  1287. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1288. WOLFSSL_MSG("Expecting BIT STRING");
  1289. #endif
  1290. return ASN_BITSTR_E;
  1291. }
  1292. /* Not the expected tag. */
  1293. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1294. WOLFSSL_MSG("Bad tag");
  1295. #endif
  1296. return ASN_PARSE_E;
  1297. }
  1298. /* Store found tag in data. */
  1299. data[i].tag = input[idx];
  1300. if (data[i].dataType != ASN_DATA_TYPE_CHOICE) {
  1301. int constructed = (input[idx] & ASN_CONSTRUCTED) == ASN_CONSTRUCTED;
  1302. /* Check constructed match expected for non-choice ASN.1 item. */
  1303. if (asn[i].constructed != constructed) {
  1304. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1305. WOLFSSL_MSG_VSNPRINTF(
  1306. "%2d: %4d %4d %c %*s %-16s%*s Tag=0x%02x (%s)",
  1307. i, data[i].offset, data[i].length,
  1308. asn[i].constructed ? '+' : ' ', asn[i].depth, "",
  1309. TagString(asn[i].tag), 6 - asn[i].depth, "",
  1310. input[idx], TagString(input[idx]));
  1311. if (!constructed) {
  1312. WOLFSSL_MSG("Not constructed");
  1313. }
  1314. else {
  1315. WOLFSSL_MSG("Not expected to be constructed");
  1316. }
  1317. #endif
  1318. return ASN_PARSE_E;
  1319. }
  1320. }
  1321. /* Move index to start of length. */
  1322. idx++;
  1323. /* Get the encoded length. */
  1324. if ((err = GetASN_Length(input, &idx, &len, endIdx[depth], 1)) < 0) {
  1325. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1326. WOLFSSL_MSG_VSNPRINTF("%2d: idx=%d len=%d end=%d", i, idx, len,
  1327. endIdx[depth]);
  1328. #endif
  1329. return ASN_PARSE_E;
  1330. }
  1331. /* Store length of data. */
  1332. data[i].length = len;
  1333. /* Note the max length of items under this one. */
  1334. endIdx[depth + 1] = idx + len;
  1335. if (choice > 1) {
  1336. /* Note we found a number choice. */
  1337. choiceMet[choice - 2] = 1;
  1338. }
  1339. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1340. WOLFSSL_MSG_VSNPRINTF("%2d: %4d %4d %c %*s %-16s", i,
  1341. data[i].offset, data[i].length, asn[i].constructed ? '+' : ' ',
  1342. asn[i].depth, "", TagString(data[i].tag));
  1343. #endif
  1344. /* Assume no zero padding on INTEGER. */
  1345. zeroPadded = 0;
  1346. /* Check data types that prepended a byte. */
  1347. if (asn[i].tag == ASN_INTEGER) {
  1348. /* Check validity of first byte. */
  1349. err = GetASN_Integer(input, idx, len,
  1350. data[i].dataType == ASN_DATA_TYPE_MP);
  1351. if (err != 0)
  1352. return err;
  1353. if (len > 1 && input[idx] == 0) {
  1354. zeroPadded = 1;
  1355. /* Move over prepended byte. */
  1356. idx++;
  1357. len--;
  1358. }
  1359. }
  1360. else if (asn[i].tag == ASN_BIT_STRING) {
  1361. /* Check prepended byte is correct. */
  1362. err = GetASN_BitString(input, idx, len);
  1363. if (err != 0)
  1364. return err;
  1365. /* Move over prepended byte. */
  1366. idx++;
  1367. len--;
  1368. }
  1369. /* Don't parse data if only header required. */
  1370. if (asn[i].headerOnly) {
  1371. /* Store reference to data and length. */
  1372. data[i].data.ref.data = input + idx;
  1373. data[i].data.ref.length = len;
  1374. continue;
  1375. }
  1376. /* Store the data at idx in the ASN data item. */
  1377. err = GetASN_StoreData(&asn[i], &data[i], input, idx, len, zeroPadded);
  1378. if (err != 0) {
  1379. return err;
  1380. }
  1381. /* Move index to next item. */
  1382. idx += len;
  1383. /* When matched numbered choice ... */
  1384. if (asn[i].optional > 1) {
  1385. /* Skip over other ASN.1 items of the same number. */
  1386. for (j = i + 1; j < count; j++) {
  1387. if (asn[j].depth <= asn[i].depth &&
  1388. asn[j].optional != asn[i].optional) {
  1389. break;
  1390. }
  1391. }
  1392. i = j - 1;
  1393. }
  1394. }
  1395. if (complete) {
  1396. /* When expecting ASN.1 items to completely use data, check we did. */
  1397. for (j = depth; j > minDepth; j--) {
  1398. if (idx < endIdx[j]) {
  1399. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1400. WOLFSSL_MSG_VSNPRINTF(
  1401. "More data in constructed item at depth: %d", j - 1);
  1402. #endif
  1403. return ASN_PARSE_E;
  1404. }
  1405. }
  1406. }
  1407. /* Check all choices where met - found an item for them. */
  1408. for (j = 0; j < GET_ASN_MAX_CHOICES; j++) {
  1409. if (choiceMet[j] == 0) {
  1410. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1411. WOLFSSL_MSG_VSNPRINTF("No choice seen: %d", j + 2);
  1412. #endif
  1413. return ASN_PARSE_E;
  1414. }
  1415. }
  1416. /* Return index after ASN.1 data has been parsed. */
  1417. *inOutIdx = idx;
  1418. return 0;
  1419. }
  1420. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1421. /* Calculate the size of the DER encoding.
  1422. *
  1423. * Call SetASN_Items() to write encoding to a buffer.
  1424. *
  1425. * @param [in] asn ASN.1 items to encode.
  1426. * @param [in, out] data Data to place in each item. Lengths set were not
  1427. * known.
  1428. * @param [in] count Count of items to encode.
  1429. * @param [out] len Length of the DER encoding.
  1430. * @return Size of the DER encoding in bytes.
  1431. */
  1432. static int SizeASN_ItemsDebug(const char* name, const ASNItem* asn,
  1433. ASNSetData *data, int count, int* encSz)
  1434. {
  1435. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1436. return SizeASN_Items(asn, data, count, encSz);
  1437. }
  1438. /* Creates the DER encoding of the ASN.1 items.
  1439. *
  1440. * Assumes the output buffer is large enough to hold encoding.
  1441. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1442. *
  1443. * Displays the template name first.
  1444. *
  1445. * @param [in] name Name of ASN.1 template.
  1446. * @param [in] asn ASN.1 items to encode.
  1447. * @param [in] data Data to place in each item.
  1448. * @param [in] count Count of items to encode.
  1449. * @param [in, out] output Buffer to write encoding into.
  1450. * @return Size of the DER encoding in bytes.
  1451. */
  1452. static int SetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1453. ASNSetData *data, int count, byte* output)
  1454. {
  1455. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1456. return SetASN_Items(asn, data, count, output);
  1457. }
  1458. /* Get the ASN.1 items from the BER encoding.
  1459. *
  1460. * Displays the template name first.
  1461. *
  1462. * @param [in] name Name of ASN.1 template.
  1463. * @param [in] asn ASN.1 items expected.
  1464. * @param [in] data Data array to place found items into.
  1465. * @param [in] count Count of items to parse.
  1466. * @param [in] complete Whether the whole buffer is to be used up.
  1467. * @param [in] input BER encoded data.
  1468. * @param [in, out] inOutIdx On in, starting index of data.
  1469. * On out, end of parsed data.
  1470. * @param [in] maxIdx Maximum index of input data.
  1471. * @return 0 on success.
  1472. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1473. * is invalid.
  1474. * @return BUFFER_E when data in buffer is too small.
  1475. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1476. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1477. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1478. * non-zero length.
  1479. * @return MP_INIT_E when the unable to initialize an mp_int.
  1480. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1481. * @return BAD_STATE_E when the data type is not supported.
  1482. */
  1483. static int GetASN_ItemsDebug(const char* name, const ASNItem* asn,
  1484. ASNGetData *data, int count, int complete, const byte* input,
  1485. word32* inOutIdx, word32 maxIdx)
  1486. {
  1487. WOLFSSL_MSG_VSNPRINTF("TEMPLATE: %s", name);
  1488. return GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx);
  1489. }
  1490. /* Calculate the size of the DER encoding.
  1491. *
  1492. * Call SetASN_Items() to write encoding to a buffer.
  1493. *
  1494. * @param [in] asn ASN.1 items to encode.
  1495. * @param [in, out] data Data to place in each item. Lengths set were not
  1496. * known.
  1497. * @param [in] count Count of items to encode.
  1498. * @param [out] len Length of the DER encoding.
  1499. * @return Size of the DER encoding in bytes.
  1500. */
  1501. #define SizeASN_Items(asn, data, count, encSz) \
  1502. SizeASN_ItemsDebug(#asn, asn, data, count, encSz)
  1503. /* Creates the DER encoding of the ASN.1 items.
  1504. *
  1505. * Assumes the output buffer is large enough to hold encoding.
  1506. * Must call SizeASN_Items() to determine size of encoding and offsets.
  1507. *
  1508. * Displays the template name first.
  1509. *
  1510. * @param [in] name Name of ASN.1 template.
  1511. * @param [in] asn ASN.1 items to encode.
  1512. * @param [in] data Data to place in each item.
  1513. * @param [in] count Count of items to encode.
  1514. * @param [in, out] output Buffer to write encoding into.
  1515. * @return Size of the DER encoding in bytes.
  1516. */
  1517. #define SetASN_Items(asn, data, count, output) \
  1518. SetASN_ItemsDebug(#asn, asn, data, count, output)
  1519. /* Get the ASN.1 items from the BER encoding.
  1520. *
  1521. * Displays the template name first.
  1522. *
  1523. * @param [in] name Name of ASN.1 template.
  1524. * @param [in] asn ASN.1 items expected.
  1525. * @param [in] data Data array to place found items into.
  1526. * @param [in] count Count of items to parse.
  1527. * @param [in] complete Whether the whole buffer is to be used up.
  1528. * @param [in] input BER encoded data.
  1529. * @param [in, out] inOutIdx On in, starting index of data.
  1530. * On out, end of parsed data.
  1531. * @param [in] maxIdx Maximum index of input data.
  1532. * @return 0 on success.
  1533. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  1534. * is invalid.
  1535. * @return BUFFER_E when data in buffer is too small.
  1536. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  1537. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  1538. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  1539. * non-zero length.
  1540. * @return MP_INIT_E when the unable to initialize an mp_int.
  1541. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  1542. * @return BAD_STATE_E when the data type is not supported.
  1543. */
  1544. #define GetASN_Items(asn, data, count, complete, input, inOutIdx, maxIdx) \
  1545. GetASN_ItemsDebug(#asn, asn, data, count, complete, input, inOutIdx, maxIdx)
  1546. #endif /* WOLFSSL_DEBUG_ASN_TEMPLATE */
  1547. /* Decode a BER encoded constructed sequence.
  1548. *
  1549. * @param [in] input Buffer of BER encoded data.
  1550. * @param [in, out] inOutIdx On in, index to start decoding from.
  1551. * On out, index of next encoded byte.
  1552. * @param [out] len Length of data under SEQUENCE.
  1553. * @param [in] maxIdx Maximim index of data. Index of byte after SEQ.
  1554. * @param [in] complete All data used with SEQUENCE and data under.
  1555. * @return 0 on success.
  1556. * @return BUFFER_E when not enough data to complete decode.
  1557. * @return ASN_PARSE when decoding failed.
  1558. */
  1559. static int GetASN_Sequence(const byte* input, word32* inOutIdx, int* len,
  1560. word32 maxIdx, int complete)
  1561. {
  1562. int ret = 0;
  1563. word32 idx = *inOutIdx;
  1564. /* Check buffer big enough for tag. */
  1565. if (idx + 1 > maxIdx) {
  1566. ret = BUFFER_E;
  1567. }
  1568. /* Check it is a constructed SEQUENCE. */
  1569. if ((ret == 0) && (input[idx++] != (ASN_SEQUENCE | ASN_CONSTRUCTED))) {
  1570. ret = ASN_PARSE_E;
  1571. }
  1572. /* Get the length. */
  1573. if ((ret == 0) && (GetASN_Length(input, &idx, len, maxIdx, 1) < 0)) {
  1574. ret = ASN_PARSE_E;
  1575. }
  1576. /* Check all data used if complete set. */
  1577. if ((ret == 0) && complete && (idx + *len != maxIdx)) {
  1578. ret = ASN_PARSE_E;
  1579. }
  1580. if (ret == 0) {
  1581. /* Return index of next byte of encoded data. */
  1582. *inOutIdx = idx;
  1583. }
  1584. return ret;
  1585. }
  1586. #ifdef WOLFSSL_ASN_TEMPLATE_TYPE_CHECK
  1587. /* Setup ASN data item to get an 8-bit number.
  1588. *
  1589. * @param [in] dataASN Dynamic ASN data item.
  1590. * @param [in] num Pointer to an 8-bit variable.
  1591. */
  1592. void GetASN_Int8Bit(ASNGetData *dataASN, byte* num)
  1593. {
  1594. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1595. dataASN->data.u8 = num;
  1596. }
  1597. /* Setup ASN data item to get a 16-bit number.
  1598. *
  1599. * @param [in] dataASN Dynamic ASN data item.
  1600. * @param [in] num Pointer to a 16-bit variable.
  1601. */
  1602. void GetASN_Int16Bit(ASNGetData *dataASN, word16* num)
  1603. {
  1604. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1605. dataASN->data.u16 = num;
  1606. }
  1607. /* Setup ASN data item to get a 32-bit number.
  1608. *
  1609. * @param [in] dataASN Dynamic ASN data item.
  1610. * @param [in] num Pointer to a 32-bit variable.
  1611. */
  1612. void GetASN_Int32Bit(ASNGetData *dataASN, word32* num)
  1613. {
  1614. dataASN->dataType = ASN_DATA_TYPE_WORD32;
  1615. dataASN->data.u32 = num;
  1616. }
  1617. /* Setup ASN data item to get data into a buffer of a specific length.
  1618. *
  1619. * @param [in] dataASN Dynamic ASN data item.
  1620. * @param [in] data Buffer to hold data.
  1621. * @param [in] length Length of buffer in bytes.
  1622. */
  1623. void GetASN_Buffer(ASNGetData *dataASN, byte* data, word32* length)
  1624. {
  1625. dataASN->dataType = ASN_DATA_TYPE_BUFFER;
  1626. dataASN->data.buffer.data = data;
  1627. dataASN->data.buffer.length = length;
  1628. }
  1629. /* Setup ASN data item to check parsed data against expected buffer.
  1630. *
  1631. * @param [in] dataASN Dynamic ASN data item.
  1632. * @param [in] data Buffer containing expected data.
  1633. * @param [in] length Length of buffer in bytes.
  1634. */
  1635. void GetASN_ExpBuffer(ASNGetData *dataASN, const byte* data, word32 length)
  1636. {
  1637. dataASN->dataType = ASN_DATA_TYPE_EXP_BUFFER;
  1638. dataASN->data.ref.data = data;
  1639. dataASN->data.ref.length = length;
  1640. }
  1641. /* Setup ASN data item to get a number into an mp_int.
  1642. *
  1643. * @param [in] dataASN Dynamic ASN data item.
  1644. * @param [in] num Multi-precision number object.
  1645. */
  1646. void GetASN_MP(ASNGetData *dataASN, mp_int* num)
  1647. {
  1648. dataASN->dataType = ASN_DATA_TYPE_MP;
  1649. dataASN->data.mp = num;
  1650. }
  1651. /* Setup ASN data item to get a positive or negative number into an mp_int.
  1652. *
  1653. * @param [in] dataASN Dynamic ASN data item.
  1654. * @param [in] num Multi-precision number object.
  1655. */
  1656. void GetASN_MP_PosNeg(ASNGetData *dataASN, mp_int* num)
  1657. {
  1658. dataASN->dataType = ASN_DATA_TYPE_MP_POS_NEG;
  1659. dataASN->data.mp = num;
  1660. }
  1661. /* Setup ASN data item to be a choice of tags.
  1662. *
  1663. * @param [in] dataASN Dynamic ASN data item.
  1664. * @param [in] options 0 terminated list of tags that are valid.
  1665. */
  1666. void GetASN_Choice(ASNGetData *dataASN, const byte* options)
  1667. {
  1668. dataASN->dataType = ASN_DATA_TYPE_CHOICE;
  1669. dataASN->data.choice = options;
  1670. }
  1671. /* Setup ASN data item to get a boolean value.
  1672. *
  1673. * @param [in] dataASN Dynamic ASN data item.
  1674. * @param [in] num Pointer to an 8-bit variable.
  1675. */
  1676. void GetASN_Boolean(ASNGetData *dataASN, byte* num)
  1677. {
  1678. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1679. dataASN->data.choice = num;
  1680. }
  1681. /* Setup ASN data item to be a an OID of a specific type.
  1682. *
  1683. * @param [in] dataASN Dynamic ASN data item.
  1684. * @param [in] oidType Type of OID to expect.
  1685. */
  1686. void GetASN_OID(ASNGetData *dataASN, int oidType)
  1687. {
  1688. dataASN->data.oid.type = oidType;
  1689. }
  1690. /* Get the data and length from an ASN data item.
  1691. *
  1692. * @param [in] dataASN Dynamic ASN data item.
  1693. * @param [out] data Pointer to data of item.
  1694. * @param [out] length Length of buffer in bytes.
  1695. */
  1696. void GetASN_GetConstRef(ASNGetData * dataASN, const byte** data, word32* length)
  1697. {
  1698. *data = dataASN->data.ref.data;
  1699. *length = dataASN->data.ref.length;
  1700. }
  1701. /* Get the data and length from an ASN data item.
  1702. *
  1703. * @param [in] dataASN Dynamic ASN data item.
  1704. * @param [out] data Pointer to data of item.
  1705. * @param [out] length Length of buffer in bytes.
  1706. */
  1707. void GetASN_GetRef(ASNGetData * dataASN, byte** data, word32* length)
  1708. {
  1709. *data = (byte*)dataASN->data.ref.data;
  1710. *length = dataASN->data.ref.length;
  1711. }
  1712. /* Get the data and length from an ASN data item that is an OID.
  1713. *
  1714. * @param [in] dataASN Dynamic ASN data item.
  1715. * @param [out] data Pointer to .
  1716. * @param [out] length Length of buffer in bytes.
  1717. */
  1718. void GetASN_OIDData(ASNGetData * dataASN, byte** data, word32* length)
  1719. {
  1720. *data = (byte*)dataASN->data.oid.data;
  1721. *length = dataASN->data.oid.length;
  1722. }
  1723. /* Setup an ASN data item to set a boolean.
  1724. *
  1725. * @param [in] dataASN Dynamic ASN data item.
  1726. * @param [in] val Boolean value.
  1727. */
  1728. void SetASN_Boolean(ASNSetData *dataASN, byte val)
  1729. {
  1730. dataASN->dataType = ASN_DATA_TYPE_NONE;
  1731. dataASN->data.u8 = val;
  1732. }
  1733. /* Setup an ASN data item to set an 8-bit number.
  1734. *
  1735. * @param [in] dataASN Dynamic ASN data item.
  1736. * @param [in] num 8-bit number to set.
  1737. */
  1738. void SetASN_Int8Bit(ASNSetData *dataASN, byte num)
  1739. {
  1740. dataASN->dataType = ASN_DATA_TYPE_WORD8;
  1741. dataASN->data.u8 = num;
  1742. }
  1743. /* Setup an ASN data item to set a 16-bit number.
  1744. *
  1745. * @param [in] dataASN Dynamic ASN data item.
  1746. * @param [in] num 16-bit number to set.
  1747. */
  1748. void SetASN_Int16Bit(ASNSetData *dataASN, word16 num)
  1749. {
  1750. dataASN->dataType = ASN_DATA_TYPE_WORD16;
  1751. dataASN->data.u16 = num;
  1752. }
  1753. /* Setup an ASN data item to set the data in a buffer.
  1754. *
  1755. * @param [in] dataASN Dynamic ASN data item.
  1756. * @param [in] data Buffer containing data to set.
  1757. * @param [in] length Length of data in buffer in bytes.
  1758. */
  1759. void SetASN_Buffer(ASNSetData *dataASN, const byte* data, word32 length)
  1760. {
  1761. dataASN->data.buffer.data = data;
  1762. dataASN->data.buffer.length = length;
  1763. }
  1764. /* Setup an ASN data item to set the DER encode data in a buffer.
  1765. *
  1766. * @param [in] dataASN Dynamic ASN data item.
  1767. * @param [in] data Buffer containing BER encoded data to set.
  1768. * @param [in] length Length of data in buffer in bytes.
  1769. */
  1770. void SetASN_ReplaceBuffer(ASNSetData *dataASN, const byte* data, word32 length)
  1771. {
  1772. dataASN->dataType = ASN_DATA_TYPE_REPLACE_BUFFER;
  1773. dataASN->data.buffer.data = data;
  1774. dataASN->data.buffer.length = length;
  1775. }
  1776. /* Setup an ASN data item to set an multi-precision number.
  1777. *
  1778. * @param [in] dataASN Dynamic ASN data item.
  1779. * @param [in] num Multi-precision number.
  1780. */
  1781. void SetASN_MP(ASNSetData *dataASN, mp_int* num)
  1782. {
  1783. dataASN->dataType = ASN_DATA_TYPE_MP;
  1784. dataASN->data.mp = num;
  1785. }
  1786. /* Setup an ASN data item to set an OID based on id and type.
  1787. *
  1788. * oid and oidType pair are unique.
  1789. *
  1790. * @param [in] dataASN Dynamic ASN data item.
  1791. * @param [in] oid OID identifier.
  1792. * @param [in] oidType Type of OID.
  1793. */
  1794. void SetASN_OID(ASNSetData *dataASN, int oid, int oidType)
  1795. {
  1796. dataASN->data.buffer.data = OidFromId(oid, oidType,
  1797. &dataASN->data.buffer.length);
  1798. }
  1799. #endif /* WOLFSSL_ASN_TEMPLATE_TYPE_CHECK */
  1800. #ifdef CRLDP_VALIDATE_DATA
  1801. /* Get the data of the BIT_STRING as a 16-bit number.
  1802. *
  1803. * @param [in] dataASN Dynamic ASN data item.
  1804. * @param [out] val ASN.1 item's data as a 16-bit number.
  1805. * @return 0 on success.
  1806. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  1807. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  1808. */
  1809. static int GetASN_BitString_Int16Bit(ASNGetData* dataASN, word16* val)
  1810. {
  1811. int ret;
  1812. int i;
  1813. const byte* input = dataASN->data.ref.data;
  1814. int length = dataASN->data.ref.length;
  1815. /* Validate the BIT_STRING data. */
  1816. ret = GetASN_BitString(input, 0, length);
  1817. if (ret == 0) {
  1818. /* Skip unused bits byte. */
  1819. input++;
  1820. length--;
  1821. /* Check the data is usable. */
  1822. if (length == 0 || length > 2) {
  1823. #ifdef WOLFSSL_DEBUG_ASN_TEMPLATE
  1824. WOLFSSL_MSG_VSNPRINTF("Expecting 1 or 2 bytes: %d", length);
  1825. #endif
  1826. ret = ASN_PARSE_E;
  1827. }
  1828. }
  1829. if (ret == 0) {
  1830. /* Fill 16-bit var with all the data. */
  1831. *val = 0;
  1832. for (i = 0; i < length; i++) {
  1833. *val <<= 8;
  1834. *val |= input[i];
  1835. }
  1836. }
  1837. return ret;
  1838. }
  1839. #endif /* CRLDP_VALIDATE_DATA */
  1840. #endif /* WOLFSSL_ASN_TEMPLATE */
  1841. /* Decode the BER/DER length field.
  1842. *
  1843. * @param [in] input BER encoded data.
  1844. * @param [in, out] inOutIdx On in, starting index of length.
  1845. * On out, end of parsed length.
  1846. * @param [out] len Length value decoded.
  1847. * @param [in] maxIdx Maximum index of input data.
  1848. * @return 0 on success.
  1849. * @return ASN_PARSE_E if the encoding is invalid.
  1850. * @return BUFFER_E when not enough data to complete decode.
  1851. */
  1852. int GetLength(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  1853. {
  1854. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  1855. }
  1856. /* Decode the BER/DER length field and check the length is valid on request.
  1857. *
  1858. * BER/DER has Type-Length-Value triplets.
  1859. * When requested will check that the Length decoded, indicating the number
  1860. * of bytes in the Value, is available in the buffer after the Length bytes.
  1861. *
  1862. * Only supporting a length upto INT_MAX.
  1863. *
  1864. * @param [in] input BER encoded data.
  1865. * @param [in, out] inOutIdx On in, starting index of length.
  1866. * On out, end of parsed length.
  1867. * @param [out] len Length value decoded.
  1868. * @param [in] maxIdx Maximum index of input data.
  1869. * @param [in] check Whether to check the buffer has at least the
  1870. * decoded length of bytes remaining.
  1871. * @return 0 on success.
  1872. * @return ASN_PARSE_E if the encoding is invalid.
  1873. * @return BUFFER_E when not enough data to complete decode.
  1874. */
  1875. int GetLength_ex(const byte* input, word32* inOutIdx, int* len, word32 maxIdx,
  1876. int check)
  1877. {
  1878. int length = 0;
  1879. word32 idx = *inOutIdx;
  1880. byte b;
  1881. /* Ensure zero return length on error. */
  1882. *len = 0;
  1883. /* Check there is at least on byte available containing length information.
  1884. */
  1885. if ((idx + 1) > maxIdx) {
  1886. WOLFSSL_MSG("GetLength - bad index on input");
  1887. return BUFFER_E;
  1888. }
  1889. /* Get the first length byte. */
  1890. b = input[idx++];
  1891. /* Check if the first byte indicates the count of bytes. */
  1892. if (b >= ASN_LONG_LENGTH) {
  1893. /* Bottom 7 bits are the number of bytes to calculate length with.
  1894. * Note: 0 indicates indefinte length encoding *not* 0 bytes of length.
  1895. */
  1896. word32 bytes = b & 0x7F;
  1897. /* Check the number of bytes required are available. */
  1898. if ((idx + bytes) > maxIdx) {
  1899. WOLFSSL_MSG("GetLength - bad long length");
  1900. return BUFFER_E;
  1901. }
  1902. /* Only support up to the number of bytes that fit into return var. */
  1903. if (bytes > sizeof(length)) {
  1904. return ASN_PARSE_E;
  1905. }
  1906. /* Big-endian encoding of number. */
  1907. while (bytes--) {
  1908. b = input[idx++];
  1909. length = (length << 8) | b;
  1910. }
  1911. /* Negative value indicates we overflowed the signed int. */
  1912. if (length < 0) {
  1913. return ASN_PARSE_E;
  1914. }
  1915. }
  1916. else {
  1917. /* Length in first byte. */
  1918. length = b;
  1919. }
  1920. /* When request, check the buffer has at least length bytes left. */
  1921. if (check && ((idx + length) > maxIdx)) {
  1922. WOLFSSL_MSG("GetLength - value exceeds buffer length");
  1923. return BUFFER_E;
  1924. }
  1925. /* Return index after length encoding. */
  1926. *inOutIdx = idx;
  1927. /* Return length if valid. */
  1928. if (length > 0) {
  1929. *len = length;
  1930. }
  1931. /* Return length calculated or error code. */
  1932. return length;
  1933. }
  1934. /* Gets the tag of next BER/DER encoded item.
  1935. *
  1936. * Checks there is enough data in the buffer for the tag byte.
  1937. *
  1938. * @param [in] input BER encoded data.
  1939. * @param [in, out] inOutIdx On in, starting index of tag.
  1940. * On out, end of parsed tag.
  1941. * @param [out] tag Tag value found.
  1942. * @param [in] maxIdx Maximum index of input data.
  1943. *
  1944. * return 0 on success
  1945. * return BAD_FUNC_ARG when tag, inOutIdx or input is NULL.
  1946. * return BUFFER_E when not enough space in buffer for tag.
  1947. */
  1948. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  1949. {
  1950. int ret = 0;
  1951. word32 idx = 0;
  1952. /* Check validity of parameters. */
  1953. if ((tag == NULL) || (inOutIdx == NULL) || (input == NULL)) {
  1954. ret = BAD_FUNC_ARG;
  1955. }
  1956. if (ret == 0) {
  1957. /* Get index and ensure space for tag. */
  1958. idx = *inOutIdx;
  1959. if (idx + ASN_TAG_SZ > maxIdx) {
  1960. WOLFSSL_MSG("Buffer too small for ASN tag");
  1961. ret = BUFFER_E;
  1962. }
  1963. }
  1964. if (ret == 0) {
  1965. /* Return the tag and the index after tag. */
  1966. *tag = input[idx];
  1967. *inOutIdx = idx + ASN_TAG_SZ;
  1968. }
  1969. /* Return error code. */
  1970. return ret;
  1971. }
  1972. /* Decode the DER/BER header (Type-Length) and check the length when requested.
  1973. *
  1974. * BER/DER has Type-Length-Value triplets.
  1975. * Check that the tag/type is the required value.
  1976. * When requested will check that the Length decoded, indicating the number
  1977. * of bytes in the Value, is available in the buffer after the Length bytes.
  1978. *
  1979. * Only supporting a length upto INT_MAX.
  1980. *
  1981. * @param [in] input Buffer holding DER/BER encoded data.
  1982. * @param [in] tag ASN.1 tag value expected in header.
  1983. * @param [in, out] inOutIdx On in, starting index of header.
  1984. * On out, end of parsed header.
  1985. * @param [out] len Number of bytes in the ASN.1 data.
  1986. * @param [in] maxIdx Length of data in buffer.
  1987. * @param [in] check Whether to check the buffer has at least the
  1988. * decoded length of bytes remaining.
  1989. * @return Number of bytes in the ASN.1 data on success.
  1990. * @return BUFFER_E when there is not enough data to parse.
  1991. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  1992. */
  1993. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx,
  1994. int* len, word32 maxIdx, int check)
  1995. {
  1996. int ret = 0;
  1997. word32 idx = *inOutIdx;
  1998. byte tagFound;
  1999. int length = 0;
  2000. /* Get tag/type. */
  2001. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0) {
  2002. ret = ASN_PARSE_E;
  2003. }
  2004. /* Ensure tag is the expected value. */
  2005. if ((ret == 0) && (tagFound != tag)) {
  2006. ret = ASN_PARSE_E;
  2007. }
  2008. /* Get the encoded length. */
  2009. if ((ret == 0) && (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)) {
  2010. ret = ASN_PARSE_E;
  2011. }
  2012. if (ret == 0) {
  2013. /* Return the length of data and index after header. */
  2014. *len = length;
  2015. *inOutIdx = idx;
  2016. ret = length;
  2017. }
  2018. /* Return number of data bytes or error code. */
  2019. return ret;
  2020. }
  2021. /* Decode the DER/BER header (Type-Length) and check the length.
  2022. *
  2023. * BER/DER has Type-Length-Value triplets.
  2024. * Check that the tag/type is the required value.
  2025. * Checks that the Length decoded, indicating the number of bytes in the Value,
  2026. * is available in the buffer after the Length bytes.
  2027. *
  2028. * @param [in] input Buffer holding DER/BER encoded data.
  2029. * @param [in] tag ASN.1 tag value expected in header.
  2030. * @param [in, out] inOutIdx On in, starting index of header.
  2031. * On out, end of parsed header.
  2032. * @param [out] len Number of bytes in the ASN.1 data.
  2033. * @param [in] maxIdx Length of data in buffer.
  2034. * @return Number of bytes in the ASN.1 data on success.
  2035. * @return BUFFER_E when there is not enough data to parse.
  2036. * @return ASN_PARSE_E when the expected tag is not found or length is invalid.
  2037. */
  2038. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  2039. word32 maxIdx)
  2040. {
  2041. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  2042. }
  2043. #ifndef WOLFSSL_ASN_TEMPLATE
  2044. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  2045. word32 maxIdx, int check)
  2046. {
  2047. word32 idx = *inOutIdx;
  2048. int length;
  2049. if ((idx + 1) > maxIdx)
  2050. return BUFFER_E;
  2051. *tag = input[idx++];
  2052. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  2053. return ASN_PARSE_E;
  2054. *len = length;
  2055. *inOutIdx = idx;
  2056. return length;
  2057. }
  2058. #endif
  2059. /* Decode the header of a BER/DER encoded SEQUENCE.
  2060. *
  2061. * @param [in] input Buffer holding DER/BER encoded data.
  2062. * @param [in, out] inOutIdx On in, starting index of header.
  2063. * On out, end of parsed header.
  2064. * @param [out] len Number of bytes in the ASN.1 data.
  2065. * @param [in] maxIdx Length of data in buffer.
  2066. * @return Number of bytes in the ASN.1 data on success.
  2067. * @return BUFFER_E when there is not enough data to parse.
  2068. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2069. */
  2070. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  2071. word32 maxIdx)
  2072. {
  2073. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2074. maxIdx);
  2075. }
  2076. /* Decode the header of a BER/DER encoded SEQUENCE.
  2077. *
  2078. * @param [in] input Buffer holding DER/BER encoded data.
  2079. * @param [in, out] inOutIdx On in, starting index of header.
  2080. * On out, end of parsed header.
  2081. * @param [out] len Number of bytes in the ASN.1 data.
  2082. * @param [in] maxIdx Length of data in buffer.
  2083. * @param [in] check Whether to check the buffer has at least the
  2084. * decoded length of bytes remaining.
  2085. * @return Number of bytes in the ASN.1 data on success.
  2086. * @return BUFFER_E when there is not enough data to parse.
  2087. * @return ASN_PARSE_E when the tag is not a SEQUENCE or length is invalid.
  2088. */
  2089. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  2090. word32 maxIdx, int check)
  2091. {
  2092. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  2093. maxIdx, check);
  2094. }
  2095. /* Decode the header of a BER/DER encoded SET.
  2096. *
  2097. * @param [in] input Buffer holding DER/BER encoded data.
  2098. * @param [in, out] inOutIdx On in, starting index of header.
  2099. * On out, end of parsed header.
  2100. * @param [out] len Number of bytes in the ASN.1 data.
  2101. * @param [in] maxIdx Length of data in buffer.
  2102. * @return Number of bytes in the ASN.1 data on success.
  2103. * @return BUFFER_E when there is not enough data to parse.
  2104. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2105. */
  2106. int GetSet(const byte* input, word32* inOutIdx, int* len,
  2107. word32 maxIdx)
  2108. {
  2109. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2110. maxIdx);
  2111. }
  2112. /* Decode the header of a BER/DER encoded SET.
  2113. *
  2114. * @param [in] input Buffer holding DER/BER encoded data.
  2115. * @param [in, out] inOutIdx On in, starting index of header.
  2116. * On out, end of parsed header.
  2117. * @param [out] len Number of bytes in the ASN.1 data.
  2118. * @param [in] maxIdx Length of data in buffer.
  2119. * @param [in] check Whether to check the buffer has at least the
  2120. * decoded length of bytes remaining.
  2121. * @return Number of bytes in the ASN.1 data on success.
  2122. * @return BUFFER_E when there is not enough data to parse.
  2123. * @return ASN_PARSE_E when the tag is not a SET or length is invalid.
  2124. */
  2125. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  2126. word32 maxIdx, int check)
  2127. {
  2128. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  2129. maxIdx, check);
  2130. }
  2131. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_OCSP)
  2132. /* Decode the BER/DER encoded NULL.
  2133. *
  2134. * No data in a NULL ASN.1 item.
  2135. * Ensure that the all fields are as expected and move index past the element.
  2136. *
  2137. * @param [in] input Buffer holding DER/BER encoded data.
  2138. * @param [in, out] inOutIdx On in, starting index of NULL item.
  2139. * On out, end of parsed NULL item.
  2140. * @param [in] maxIdx Length of data in buffer.
  2141. * @return 0 on success.
  2142. * @return BUFFER_E when there is not enough data to parse.
  2143. * @return ASN_TAG_NULL_E when the NULL tag is not found.
  2144. * @return ASN_EXPECT_0_E when the length is not zero.
  2145. */
  2146. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  2147. {
  2148. int ret = 0;
  2149. word32 idx = *inOutIdx;
  2150. /* Check buffer has enough data for a NULL item. */
  2151. if ((idx + 2) > maxIdx) {
  2152. ret = BUFFER_E;
  2153. }
  2154. /* Check the tag is NULL. */
  2155. if ((ret == 0) && (input[idx++] != ASN_TAG_NULL)) {
  2156. ret = ASN_TAG_NULL_E;
  2157. }
  2158. /* Check the length is zero. */
  2159. if ((ret == 0) && (input[idx++] != 0)) {
  2160. ret = ASN_EXPECT_0_E;
  2161. }
  2162. if (ret == 0) {
  2163. /* Return the index after NULL tag. */
  2164. *inOutIdx = idx;
  2165. }
  2166. /* Return error code. */
  2167. return ret;
  2168. }
  2169. #endif
  2170. #ifndef WOLFSSL_ASN_TEMPLATE
  2171. /* Set the DER/BER encoding of the ASN.1 NULL element.
  2172. *
  2173. * output Buffer to write into.
  2174. * returns the number of bytes added to the buffer.
  2175. */
  2176. static int SetASNNull(byte* output)
  2177. {
  2178. output[0] = ASN_TAG_NULL;
  2179. output[1] = 0;
  2180. return 2;
  2181. }
  2182. #endif
  2183. #ifndef NO_CERTS
  2184. #ifndef WOLFSSL_ASN_TEMPLATE
  2185. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  2186. *
  2187. * input Buffer holding DER/BER encoded data.
  2188. * inOutIdx Current index into buffer to parse.
  2189. * maxIdx Length of data in buffer.
  2190. * returns BUFFER_E when there is not enough data to parse.
  2191. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  2192. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  2193. */
  2194. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  2195. {
  2196. word32 idx = *inOutIdx;
  2197. byte b;
  2198. if ((idx + 3) > maxIdx)
  2199. return BUFFER_E;
  2200. b = input[idx++];
  2201. if (b != ASN_BOOLEAN)
  2202. return ASN_PARSE_E;
  2203. if (input[idx++] != 1)
  2204. return ASN_PARSE_E;
  2205. b = input[idx++] != 0;
  2206. *inOutIdx = idx;
  2207. return b;
  2208. }
  2209. #endif
  2210. #endif /* !NO_CERTS*/
  2211. /* Decode the header of a BER/DER encoded OCTET STRING.
  2212. *
  2213. * @param [in] input Buffer holding DER/BER encoded data.
  2214. * @param [in, out] inOutIdx On in, starting index of header.
  2215. * On out, end of parsed header.
  2216. * @param [out] len Number of bytes in the ASN.1 data.
  2217. * @param [in] maxIdx Length of data in buffer.
  2218. * @return Number of bytes in the ASN.1 data on success.
  2219. * @return BUFFER_E when there is not enough data to parse.
  2220. * @return ASN_PARSE_E when the tag is not a OCTET STRING or length is invalid.
  2221. */
  2222. int GetOctetString(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  2223. {
  2224. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  2225. }
  2226. #ifndef WOLFSSL_ASN_TEMPLATE
  2227. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  2228. *
  2229. * Removes the leading zero byte when found.
  2230. *
  2231. * input Buffer holding DER/BER encoded data.
  2232. * inOutIdx Current index into buffer to parse.
  2233. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  2234. * maxIdx Length of data in buffer.
  2235. * returns BUFFER_E when there is not enough data to parse.
  2236. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  2237. * or invalid use of or missing leading zero.
  2238. * Otherwise, 0 to indicate success.
  2239. */
  2240. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  2241. word32 maxIdx)
  2242. {
  2243. int ret;
  2244. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  2245. if (ret < 0)
  2246. return ret;
  2247. if (*len > 0) {
  2248. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2249. /* check for invalid padding on negative integer.
  2250. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  2251. */
  2252. if (*len > 1) {
  2253. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  2254. return ASN_PARSE_E;
  2255. }
  2256. #endif
  2257. /* remove leading zero, unless there is only one 0x00 byte */
  2258. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  2259. (*inOutIdx)++;
  2260. (*len)--;
  2261. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  2262. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  2263. return ASN_PARSE_E;
  2264. #endif
  2265. }
  2266. }
  2267. return 0;
  2268. }
  2269. #ifndef NO_CERTS
  2270. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  2271. * 7 bits.
  2272. *
  2273. * input Buffer holding DER/BER encoded data.
  2274. * inOutIdx Current index into buffer to parse.
  2275. * maxIdx Length of data in buffer.
  2276. * returns BUFFER_E when there is not enough data to parse.
  2277. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  2278. * Otherwise, the 7-bit value.
  2279. */
  2280. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  2281. {
  2282. word32 idx = *inOutIdx;
  2283. byte b;
  2284. if ((idx + 3) > maxIdx)
  2285. return BUFFER_E;
  2286. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  2287. return ASN_PARSE_E;
  2288. if (b != ASN_INTEGER)
  2289. return ASN_PARSE_E;
  2290. if (input[idx++] != 1)
  2291. return ASN_PARSE_E;
  2292. b = input[idx++];
  2293. *inOutIdx = idx;
  2294. return b;
  2295. }
  2296. #endif /* !NO_CERTS */
  2297. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2298. #if !defined(NO_DSA) && !defined(NO_SHA)
  2299. static const char sigSha1wDsaName[] = "SHAwDSA";
  2300. static const char sigSha256wDsaName[] = "SHA256wDSA";
  2301. #endif /* NO_DSA */
  2302. #ifndef NO_RSA
  2303. #ifdef WOLFSSL_MD2
  2304. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  2305. #endif
  2306. #ifndef NO_MD5
  2307. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  2308. #endif
  2309. #ifndef NO_SHA
  2310. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  2311. #endif
  2312. #ifdef WOLFSSL_SHA224
  2313. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  2314. #endif
  2315. #ifndef NO_SHA256
  2316. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  2317. #endif
  2318. #ifdef WOLFSSL_SHA384
  2319. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  2320. #endif
  2321. #ifdef WOLFSSL_SHA512
  2322. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  2323. #endif
  2324. #ifdef WOLFSSL_SHA3
  2325. #ifndef WOLFSSL_NOSHA3_224
  2326. static const char sigSha3_224wRsaName[] = "sha3_224WithRSAEncryption";
  2327. #endif
  2328. #ifndef WOLFSSL_NOSHA3_256
  2329. static const char sigSha3_256wRsaName[] = "sha3_256WithRSAEncryption";
  2330. #endif
  2331. #ifndef WOLFSSL_NOSHA3_384
  2332. static const char sigSha3_384wRsaName[] = "sha3_384WithRSAEncryption";
  2333. #endif
  2334. #ifndef WOLFSSL_NOSHA3_512
  2335. static const char sigSha3_512wRsaName[] = "sha3_512WithRSAEncryption";
  2336. #endif
  2337. #endif
  2338. #endif /* NO_RSA */
  2339. #ifdef HAVE_ECC
  2340. #ifndef NO_SHA
  2341. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  2342. #endif
  2343. #ifdef WOLFSSL_SHA224
  2344. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  2345. #endif
  2346. #ifndef NO_SHA256
  2347. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  2348. #endif
  2349. #ifdef WOLFSSL_SHA384
  2350. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  2351. #endif
  2352. #ifdef WOLFSSL_SHA512
  2353. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  2354. #endif
  2355. #ifdef WOLFSSL_SHA3
  2356. #ifndef WOLFSSL_NOSHA3_224
  2357. static const char sigSha3_224wEcdsaName[] = "SHA3_224wECDSA";
  2358. #endif
  2359. #ifndef WOLFSSL_NOSHA3_256
  2360. static const char sigSha3_256wEcdsaName[] = "SHA3_256wECDSA";
  2361. #endif
  2362. #ifndef WOLFSSL_NOSHA3_384
  2363. static const char sigSha3_384wEcdsaName[] = "SHA3_384wECDSA";
  2364. #endif
  2365. #ifndef WOLFSSL_NOSHA3_512
  2366. static const char sigSha3_512wEcdsaName[] = "SHA3_512wECDSA";
  2367. #endif
  2368. #endif
  2369. #endif /* HAVE_ECC */
  2370. static const char sigUnknownName[] = "Unknown";
  2371. /* Get the human readable string for a signature type
  2372. *
  2373. * oid Oid value for signature
  2374. */
  2375. const char* GetSigName(int oid) {
  2376. switch (oid) {
  2377. #if !defined(NO_DSA) && !defined(NO_SHA)
  2378. case CTC_SHAwDSA:
  2379. return sigSha1wDsaName;
  2380. case CTC_SHA256wDSA:
  2381. return sigSha256wDsaName;
  2382. #endif /* NO_DSA && NO_SHA */
  2383. #ifndef NO_RSA
  2384. #ifdef WOLFSSL_MD2
  2385. case CTC_MD2wRSA:
  2386. return sigMd2wRsaName;
  2387. #endif
  2388. #ifndef NO_MD5
  2389. case CTC_MD5wRSA:
  2390. return sigMd5wRsaName;
  2391. #endif
  2392. #ifndef NO_SHA
  2393. case CTC_SHAwRSA:
  2394. return sigSha1wRsaName;
  2395. #endif
  2396. #ifdef WOLFSSL_SHA224
  2397. case CTC_SHA224wRSA:
  2398. return sigSha224wRsaName;
  2399. #endif
  2400. #ifndef NO_SHA256
  2401. case CTC_SHA256wRSA:
  2402. return sigSha256wRsaName;
  2403. #endif
  2404. #ifdef WOLFSSL_SHA384
  2405. case CTC_SHA384wRSA:
  2406. return sigSha384wRsaName;
  2407. #endif
  2408. #ifdef WOLFSSL_SHA512
  2409. case CTC_SHA512wRSA:
  2410. return sigSha512wRsaName;
  2411. #endif
  2412. #ifdef WOLFSSL_SHA3
  2413. #ifndef WOLFSSL_NOSHA3_224
  2414. case CTC_SHA3_224wRSA:
  2415. return sigSha3_224wRsaName;
  2416. #endif
  2417. #ifndef WOLFSSL_NOSHA3_256
  2418. case CTC_SHA3_256wRSA:
  2419. return sigSha3_256wRsaName;
  2420. #endif
  2421. #ifndef WOLFSSL_NOSHA3_384
  2422. case CTC_SHA3_384wRSA:
  2423. return sigSha3_384wRsaName;
  2424. #endif
  2425. #ifndef WOLFSSL_NOSHA3_512
  2426. case CTC_SHA3_512wRSA:
  2427. return sigSha3_512wRsaName;
  2428. #endif
  2429. #endif
  2430. #endif /* NO_RSA */
  2431. #ifdef HAVE_ECC
  2432. #ifndef NO_SHA
  2433. case CTC_SHAwECDSA:
  2434. return sigSha1wEcdsaName;
  2435. #endif
  2436. #ifdef WOLFSSL_SHA224
  2437. case CTC_SHA224wECDSA:
  2438. return sigSha224wEcdsaName;
  2439. #endif
  2440. #ifndef NO_SHA256
  2441. case CTC_SHA256wECDSA:
  2442. return sigSha256wEcdsaName;
  2443. #endif
  2444. #ifdef WOLFSSL_SHA384
  2445. case CTC_SHA384wECDSA:
  2446. return sigSha384wEcdsaName;
  2447. #endif
  2448. #ifdef WOLFSSL_SHA512
  2449. case CTC_SHA512wECDSA:
  2450. return sigSha512wEcdsaName;
  2451. #endif
  2452. #ifdef WOLFSSL_SHA3
  2453. #ifndef WOLFSSL_NOSHA3_224
  2454. case CTC_SHA3_224wECDSA:
  2455. return sigSha3_224wEcdsaName;
  2456. #endif
  2457. #ifndef WOLFSSL_NOSHA3_256
  2458. case CTC_SHA3_256wECDSA:
  2459. return sigSha3_256wEcdsaName;
  2460. #endif
  2461. #ifndef WOLFSSL_NOSHA3_384
  2462. case CTC_SHA3_384wECDSA:
  2463. return sigSha3_384wEcdsaName;
  2464. #endif
  2465. #ifndef WOLFSSL_NOSHA3_512
  2466. case CTC_SHA3_512wECDSA:
  2467. return sigSha3_512wEcdsaName;
  2468. #endif
  2469. #endif
  2470. #endif /* HAVE_ECC */
  2471. default:
  2472. return sigUnknownName;
  2473. }
  2474. }
  2475. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7) || \
  2476. defined(OPENSSL_EXTRA)
  2477. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  2478. (!defined(NO_RSA) && \
  2479. (defined(WOLFSSL_CERT_GEN) || \
  2480. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  2481. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  2482. *
  2483. * When output is NULL, calculate the header length only.
  2484. *
  2485. * @param [in] len Length of INTEGER data in bytes.
  2486. * @param [in] firstByte First byte of data, most significant byte of integer,
  2487. * to encode.
  2488. * @param [out] output Buffer to write into.
  2489. * @return Number of bytes added to the buffer.
  2490. */
  2491. int SetASNInt(int len, byte firstByte, byte* output)
  2492. {
  2493. word32 idx = 0;
  2494. if (output) {
  2495. /* Write out tag. */
  2496. output[idx] = ASN_INTEGER;
  2497. }
  2498. /* Step over tag. */
  2499. idx += ASN_TAG_SZ;
  2500. /* Check if first byte has top bit set in which case a 0 is needed to
  2501. * maintain positive value. */
  2502. if (firstByte & 0x80) {
  2503. /* Add pre-prepended byte to length of data in INTEGER. */
  2504. len++;
  2505. }
  2506. /* Encode length - passing NULL for output will not encode. */
  2507. idx += SetLength(len, output ? output + idx : NULL);
  2508. /* Put out pre-pended 0 as well. */
  2509. if (firstByte & 0x80) {
  2510. if (output) {
  2511. /* Write out 0 byte. */
  2512. output[idx] = 0x00;
  2513. }
  2514. /* Update index. */
  2515. idx++;
  2516. }
  2517. /* Return index after header. */
  2518. return idx;
  2519. }
  2520. #endif
  2521. #endif
  2522. #ifndef WOLFSSL_ASN_TEMPLATE
  2523. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  2524. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  2525. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  2526. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  2527. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  2528. * The number is assumed to be positive.
  2529. *
  2530. * n Multi-precision integer to encode.
  2531. * maxSz Maximum size of the encoded integer.
  2532. * A negative value indicates no check of length requested.
  2533. * output Buffer to write into.
  2534. * returns BUFFER_E when the data is too long for the buffer.
  2535. * MP_TO_E when encoding the integer fails.
  2536. * Otherwise, the number of bytes added to the buffer.
  2537. */
  2538. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  2539. {
  2540. int idx = 0;
  2541. int leadingBit;
  2542. int length;
  2543. int err;
  2544. leadingBit = mp_leading_bit(n);
  2545. length = mp_unsigned_bin_size(n);
  2546. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  2547. return BUFFER_E;
  2548. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2549. if (maxSz >= 0 && (idx + length) > maxSz)
  2550. return BUFFER_E;
  2551. if (output) {
  2552. err = mp_to_unsigned_bin(n, output + idx);
  2553. if (err != MP_OKAY)
  2554. return MP_TO_E;
  2555. }
  2556. idx += length;
  2557. return idx;
  2558. }
  2559. #endif
  2560. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  2561. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  2562. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  2563. * an RSA key.
  2564. * The number is assumed to be positive.
  2565. *
  2566. * n Multi-precision integer to encode.
  2567. * output Buffer to write into.
  2568. * returns BUFFER_E when the data is too long for the buffer.
  2569. * MP_TO_E when encoding the integer fails.
  2570. * Otherwise, the number of bytes added to the buffer.
  2571. */
  2572. static int SetASNIntRSA(void* n, byte* output)
  2573. {
  2574. int idx = 0;
  2575. int leadingBit;
  2576. int length;
  2577. int err;
  2578. leadingBit = wc_Rsa_leading_bit(n);
  2579. length = wc_Rsa_unsigned_bin_size(n);
  2580. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  2581. if ((idx + length) > MAX_RSA_INT_SZ)
  2582. return BUFFER_E;
  2583. if (output) {
  2584. err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  2585. if (err != MP_OKAY)
  2586. return MP_TO_E;
  2587. }
  2588. idx += length;
  2589. return idx;
  2590. }
  2591. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  2592. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2593. #ifdef WOLFSSL_ASN_TEMPLATE
  2594. /* ASN.1 template for an INTEGER. */
  2595. static const ASNItem intASN[] = {
  2596. { 0, ASN_INTEGER, 0, 0, 0 }
  2597. };
  2598. /* Number of items in ASN.1 template for an INTEGER. */
  2599. #define intASN_Length (sizeof(intASN) / sizeof(ASNItem))
  2600. #endif /* WOLFSSL_ASN_TEMPLATE */
  2601. /* Windows header clash for WinCE using GetVersion */
  2602. /* Decode Version - one byte INTEGER.
  2603. *
  2604. * @param [in] input Buffer of BER data.
  2605. * @param [in, out] inOutIdx On in, start of encoded Version.
  2606. * On out, start of next encode ASN.1 item.
  2607. * @param [out] version Number encoded in INTEGER.
  2608. * @param [in] maxIdx Maximum index of data in buffer.
  2609. * @return 0 on success.
  2610. * @return ASN_PARSE_E when encoding is invalid.
  2611. * @return BUFFER_E when data in buffer is too small.
  2612. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2613. */
  2614. int GetMyVersion(const byte* input, word32* inOutIdx,
  2615. int* version, word32 maxIdx)
  2616. {
  2617. #ifndef WOLFSSL_ASN_TEMPLATE
  2618. word32 idx = *inOutIdx;
  2619. byte tag;
  2620. if ((idx + MIN_VERSION_SZ) > maxIdx)
  2621. return ASN_PARSE_E;
  2622. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2623. return ASN_PARSE_E;
  2624. if (tag != ASN_INTEGER)
  2625. return ASN_PARSE_E;
  2626. if (input[idx++] != 0x01)
  2627. return ASN_VERSION_E;
  2628. *version = input[idx++];
  2629. *inOutIdx = idx;
  2630. return *version;
  2631. #else
  2632. ASNGetData dataASN[intASN_Length];
  2633. int ret;
  2634. byte num;
  2635. /* Clear dynamic data and set the version number variable. */
  2636. XMEMSET(dataASN, 0, sizeof(dataASN));
  2637. GetASN_Int8Bit(&dataASN[0], &num);
  2638. /* Decode the version (INTEGER). */
  2639. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2640. maxIdx);
  2641. if (ret == 0) {
  2642. /* Return version through variable and return value. */
  2643. *version = num;
  2644. ret = num;
  2645. }
  2646. return ret;
  2647. #endif /* WOLFSSL_ASN_TEMPLATE */
  2648. }
  2649. #ifndef NO_PWDBASED
  2650. /* Decode small integer, 32 bits or less.
  2651. *
  2652. * @param [in] input Buffer of BER data.
  2653. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2654. * On out, start of next encode ASN.1 item.
  2655. * @param [out] number Number encoded in INTEGER.
  2656. * @param [in] maxIdx Maximum index of data in buffer.
  2657. * @return 0 on success.
  2658. * @return ASN_PARSE_E when encoding is invalid.
  2659. * @return BUFFER_E when data in buffer is too small.
  2660. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2661. */
  2662. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  2663. {
  2664. #ifndef WOLFSSL_ASN_TEMPLATE
  2665. word32 idx = *inOutIdx;
  2666. word32 len;
  2667. byte tag;
  2668. *number = 0;
  2669. /* check for type and length bytes */
  2670. if ((idx + 2) > maxIdx)
  2671. return BUFFER_E;
  2672. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2673. return ASN_PARSE_E;
  2674. if (tag != ASN_INTEGER)
  2675. return ASN_PARSE_E;
  2676. len = input[idx++];
  2677. if (len > 4)
  2678. return ASN_PARSE_E;
  2679. if (len + idx > maxIdx)
  2680. return ASN_PARSE_E;
  2681. while (len--) {
  2682. *number = *number << 8 | input[idx++];
  2683. }
  2684. *inOutIdx = idx;
  2685. return *number;
  2686. #else
  2687. ASNGetData dataASN[intASN_Length];
  2688. int ret;
  2689. word32 num;
  2690. /* Clear dynamic data and set the 32-bit number variable. */
  2691. XMEMSET(dataASN, 0, sizeof(dataASN));
  2692. GetASN_Int32Bit(&dataASN[0], &num);
  2693. /* Decode the short int (INTEGER). */
  2694. ret = GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2695. maxIdx);
  2696. if (ret == 0) {
  2697. /* Return number through variable and return value. */
  2698. *number = num;
  2699. ret = num;
  2700. }
  2701. return ret;
  2702. #endif
  2703. }
  2704. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS12)
  2705. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  2706. * returns total amount written including ASN tag and length byte on success */
  2707. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  2708. {
  2709. word32 idx = *inOutIdx;
  2710. word32 len = 0;
  2711. int i;
  2712. byte ar[MAX_LENGTH_SZ];
  2713. /* check for room for type and length bytes */
  2714. if ((idx + 2) > maxIdx)
  2715. return BUFFER_E;
  2716. input[idx++] = ASN_INTEGER;
  2717. idx++; /* place holder for length byte */
  2718. if (MAX_LENGTH_SZ + idx > maxIdx)
  2719. return ASN_PARSE_E;
  2720. /* find first non zero byte */
  2721. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  2722. c32toa(number, ar);
  2723. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  2724. if (ar[i] != 0) {
  2725. break;
  2726. }
  2727. }
  2728. /* handle case of 0 */
  2729. if (i == MAX_LENGTH_SZ) {
  2730. input[idx++] = 0; len++;
  2731. }
  2732. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  2733. input[idx++] = ar[i]; len++;
  2734. }
  2735. /* jump back to beginning of input buffer using unaltered inOutIdx value
  2736. * and set number of bytes for integer, then update the index value */
  2737. input[*inOutIdx + 1] = (byte)len;
  2738. *inOutIdx = idx;
  2739. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  2740. }
  2741. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2742. #endif /* !NO_PWDBASED */
  2743. #ifndef WOLFSSL_ASN_TEMPLATE
  2744. /* May not have one, not an error */
  2745. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  2746. word32 maxIdx)
  2747. {
  2748. word32 idx = *inOutIdx;
  2749. byte tag;
  2750. WOLFSSL_ENTER("GetExplicitVersion");
  2751. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2752. return ASN_PARSE_E;
  2753. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  2754. int ret;
  2755. *inOutIdx = ++idx; /* skip header */
  2756. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  2757. if (ret >= 0) {
  2758. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  2759. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  2760. WOLFSSL_MSG("Unexpected certificate version");
  2761. ret = ASN_VERSION_E;
  2762. }
  2763. }
  2764. return ret;
  2765. }
  2766. /* go back as is */
  2767. *version = 0;
  2768. return 0;
  2769. }
  2770. #endif
  2771. /* Decode small integer, 32 bits or less.
  2772. *
  2773. * mp_int is initialized.
  2774. *
  2775. * @param [out] mpi mp_int to hold number.
  2776. * @param [in] input Buffer of BER data.
  2777. * @param [in, out] inOutIdx On in, start of encoded INTEGER.
  2778. * On out, start of next encode ASN.1 item.
  2779. * @param [in] maxIdx Maximum index of data in buffer.
  2780. * @return 0 on success.
  2781. * @return ASN_PARSE_E when encoding is invalid.
  2782. * @return BUFFER_E when data in buffer is too small.
  2783. * @return ASN_EXPECT_0_E when the most significant bit is set.
  2784. * @return MP_INIT_E when the unable to initialize an mp_int.
  2785. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  2786. */
  2787. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  2788. {
  2789. #ifndef WOLFSSL_ASN_TEMPLATE
  2790. word32 idx = *inOutIdx;
  2791. int ret;
  2792. int length;
  2793. ret = GetASNInt(input, &idx, &length, maxIdx);
  2794. if (ret != 0)
  2795. return ret;
  2796. if (mp_init(mpi) != MP_OKAY)
  2797. return MP_INIT_E;
  2798. if (mp_read_unsigned_bin(mpi, input + idx, length) != 0) {
  2799. mp_clear(mpi);
  2800. return ASN_GETINT_E;
  2801. }
  2802. #ifdef HAVE_WOLF_BIGINT
  2803. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  2804. mp_clear(mpi);
  2805. return ASN_GETINT_E;
  2806. }
  2807. #endif /* HAVE_WOLF_BIGINT */
  2808. *inOutIdx = idx + length;
  2809. return 0;
  2810. #else
  2811. ASNGetData dataASN[intASN_Length];
  2812. /* Clear dynamic data and set the mp_int to fill with value. */
  2813. XMEMSET(dataASN, 0, sizeof(dataASN));
  2814. GetASN_MP_PosNeg(&dataASN[0], mpi);
  2815. /* Decode the big number (INTEGER). */
  2816. return GetASN_Items(intASN, dataASN, intASN_Length, 0, input, inOutIdx,
  2817. maxIdx);
  2818. #endif
  2819. }
  2820. #ifndef WOLFSSL_ASN_TEMPLATE
  2821. #if (!defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)) \
  2822. || defined(WOLFSSL_RSA_PUBLIC_ONLY) || (!defined(NO_DSA))
  2823. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  2824. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  2825. {
  2826. word32 idx = *inOutIdx;
  2827. int ret;
  2828. int length;
  2829. ret = GetASNInt(input, &idx, &length, maxIdx);
  2830. if (ret != 0)
  2831. return ret;
  2832. *inOutIdx = idx + length;
  2833. return 0;
  2834. }
  2835. #endif
  2836. #endif
  2837. #endif /* !WOLFSSL_ASN_TEMPLATE */
  2838. #ifdef WOLFSSL_ASN_TEMPLATE
  2839. /* ASN.1 template for a BIT_STRING. */
  2840. static const ASNItem bitStringASN[] = {
  2841. { 0, ASN_BIT_STRING, 0, 1, 0 }
  2842. };
  2843. /* Number of items in ASN.1 template for a BIT_STRING. */
  2844. #define bitStringASN_Length (sizeof(bitStringASN) / sizeof(ASNItem))
  2845. #endif
  2846. /* Decode and check the BIT_STRING is valid. Return length and unused bits.
  2847. *
  2848. * @param [in] input Buffer holding BER encoding.
  2849. * @param [in, out] inOutIdx On in, start of BIT_STRING.
  2850. * On out, start of ASN.1 item after BIT_STRING.
  2851. * @param [out] len Length of BIT_STRING data.
  2852. * @param [in] maxIdx Maximum index of data in buffer.
  2853. * @param [in] zeroBits Indicates whether zero unused bits is expected.
  2854. * @param [in] unusedBits Number of unused bits in last byte.
  2855. * @return 0 on success.
  2856. * @return ASN_PARSE_E when encoding is invalid.
  2857. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  2858. * @return BUFFER_E when data in buffer is too small.
  2859. * @return ASN_EXPECT_0_E when unused bits is not zero when expected.
  2860. */
  2861. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  2862. word32 maxIdx, int zeroBits, byte* unusedBits)
  2863. {
  2864. #ifndef WOLFSSL_ASN_TEMPLATE
  2865. word32 idx = *inOutIdx;
  2866. int length;
  2867. byte b;
  2868. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  2869. return ASN_BITSTR_E;
  2870. }
  2871. if (b != ASN_BIT_STRING) {
  2872. return ASN_BITSTR_E;
  2873. }
  2874. if (GetLength(input, &idx, &length, maxIdx) < 0)
  2875. return ASN_PARSE_E;
  2876. /* extra sanity check that length is greater than 0 */
  2877. if (length <= 0) {
  2878. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  2879. return BUFFER_E;
  2880. }
  2881. if (idx + 1 > maxIdx) {
  2882. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  2883. return BUFFER_E;
  2884. }
  2885. b = input[idx];
  2886. if (zeroBits && b != 0x00)
  2887. return ASN_EXPECT_0_E;
  2888. if (b >= 0x08)
  2889. return ASN_PARSE_E;
  2890. if (b != 0) {
  2891. if ((byte)(input[idx + length - 1] << (8 - b)) != 0)
  2892. return ASN_PARSE_E;
  2893. }
  2894. idx++;
  2895. length--; /* length has been checked for greater than 0 */
  2896. *inOutIdx = idx;
  2897. if (len != NULL)
  2898. *len = length;
  2899. if (unusedBits != NULL)
  2900. *unusedBits = b;
  2901. return 0;
  2902. #else
  2903. ASNGetData dataASN[bitStringASN_Length];
  2904. int ret;
  2905. int bits;
  2906. /* Parse BIT_STRING and check validity of unused bits. */
  2907. XMEMSET(dataASN, 0, sizeof(dataASN));
  2908. /* Decode BIT_STRING. */
  2909. ret = GetASN_Items(bitStringASN, dataASN, bitStringASN_Length, 0, input,
  2910. inOutIdx, maxIdx);
  2911. if (ret == 0) {
  2912. /* Get unused bits from dynamic ASN.1 data. */
  2913. bits = GetASNItem_UnusedBits(dataASN[0]);
  2914. /* Check unused bits is 0 when expected. */
  2915. if (zeroBits && (bits != 0)) {
  2916. ret = ASN_EXPECT_0_E;
  2917. }
  2918. }
  2919. if (ret == 0) {
  2920. /* Return length of data and unused bits if required. */
  2921. if (len != NULL) {
  2922. *len = dataASN[0].data.ref.length;
  2923. }
  2924. if (unusedBits != NULL) {
  2925. *unusedBits = bits;
  2926. }
  2927. }
  2928. return ret;
  2929. #endif
  2930. }
  2931. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  2932. * KeyGen) */
  2933. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  2934. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  2935. defined(OPENSSL_EXTRA))) || \
  2936. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  2937. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  2938. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || \
  2939. defined(OPENSSL_EXTRA))) || \
  2940. (defined(WC_ENABLE_ASYM_KEY_EXPORT) && !defined(NO_CERT)) || \
  2941. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN))
  2942. /* Set the DER/BER encoding of the ASN.1 BIT STRING header.
  2943. *
  2944. * When output is NULL, calculate the header length only.
  2945. *
  2946. * @param [in] len Length of BIT STRING data.
  2947. * That is, the number of least significant zero bits
  2948. * before a one.
  2949. * The last byte is the most-significant non-zero byte
  2950. * of a number.
  2951. * @param [out] output Buffer to write into.
  2952. * @return Number of bytes added to the buffer.
  2953. */
  2954. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  2955. {
  2956. word32 idx = 0;
  2957. if (output) {
  2958. /* Write out tag. */
  2959. output[idx] = ASN_BIT_STRING;
  2960. }
  2961. /* Step over tag. */
  2962. idx += ASN_TAG_SZ;
  2963. /* Encode length - passing NULL for output will not encode.
  2964. * Add one to length for unused bits. */
  2965. idx += SetLength(len + 1, output ? output + idx : NULL);
  2966. if (output) {
  2967. /* Write out unused bits. */
  2968. output[idx] = unusedBits;
  2969. }
  2970. /* Skip over unused bits. */
  2971. idx++;
  2972. /* Return index after header. */
  2973. return idx;
  2974. }
  2975. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  2976. #ifdef ASN_BER_TO_DER
  2977. /* Convert BER to DER */
  2978. /* Pull informtation from the ASN.1 BER encoded item header */
  2979. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  2980. byte* pTag, word32* pLen, int* indef)
  2981. {
  2982. int len = 0;
  2983. byte tag;
  2984. word32 i = *idx;
  2985. *indef = 0;
  2986. /* Check there is enough data for a minimal header */
  2987. if (i + 2 > maxIdx) {
  2988. return ASN_PARSE_E;
  2989. }
  2990. /* Retrieve tag */
  2991. tag = data[i++];
  2992. /* Indefinite length handled specially */
  2993. if (data[i] == 0x80) {
  2994. /* Check valid tag for indefinite */
  2995. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  2996. return ASN_PARSE_E;
  2997. }
  2998. i++;
  2999. *indef = 1;
  3000. }
  3001. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  3002. return ASN_PARSE_E;
  3003. }
  3004. /* Return tag, length and index after BER item header */
  3005. *pTag = tag;
  3006. *pLen = len;
  3007. *idx = i;
  3008. return 0;
  3009. }
  3010. #ifndef INDEF_ITEMS_MAX
  3011. #define INDEF_ITEMS_MAX 20
  3012. #endif
  3013. /* Indef length item data */
  3014. typedef struct Indef {
  3015. word32 start;
  3016. int depth;
  3017. int headerLen;
  3018. word32 len;
  3019. } Indef;
  3020. /* Indef length items */
  3021. typedef struct IndefItems
  3022. {
  3023. Indef len[INDEF_ITEMS_MAX];
  3024. int cnt;
  3025. int idx;
  3026. int depth;
  3027. } IndefItems;
  3028. /* Get header length of current item */
  3029. static int IndefItems_HeaderLen(IndefItems* items)
  3030. {
  3031. return items->len[items->idx].headerLen;
  3032. }
  3033. /* Get data length of current item */
  3034. static word32 IndefItems_Len(IndefItems* items)
  3035. {
  3036. return items->len[items->idx].len;
  3037. }
  3038. /* Add a indefinite length item */
  3039. static int IndefItems_AddItem(IndefItems* items, word32 start)
  3040. {
  3041. int ret = 0;
  3042. int i;
  3043. if (items->cnt == INDEF_ITEMS_MAX) {
  3044. ret = MEMORY_E;
  3045. }
  3046. else {
  3047. i = items->cnt++;
  3048. items->len[i].start = start;
  3049. items->len[i].depth = items->depth++;
  3050. items->len[i].headerLen = 1;
  3051. items->len[i].len = 0;
  3052. items->idx = i;
  3053. }
  3054. return ret;
  3055. }
  3056. /* Increase data length of current item */
  3057. static void IndefItems_AddData(IndefItems* items, word32 length)
  3058. {
  3059. items->len[items->idx].len += length;
  3060. }
  3061. /* Update header length of current item to reflect data length */
  3062. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  3063. {
  3064. items->len[items->idx].headerLen +=
  3065. SetLength(items->len[items->idx].len, NULL);
  3066. }
  3067. /* Go to indefinite parent of current item */
  3068. static void IndefItems_Up(IndefItems* items)
  3069. {
  3070. int i;
  3071. int depth = items->len[items->idx].depth - 1;
  3072. for (i = items->cnt - 1; i >= 0; i--) {
  3073. if (items->len[i].depth == depth) {
  3074. break;
  3075. }
  3076. }
  3077. items->idx = i;
  3078. items->depth = depth + 1;
  3079. }
  3080. /* Calculate final length by adding length of indefinite child items */
  3081. static void IndefItems_CalcLength(IndefItems* items)
  3082. {
  3083. int i;
  3084. int idx = items->idx;
  3085. for (i = idx + 1; i < items->cnt; i++) {
  3086. if (items->len[i].depth == items->depth) {
  3087. items->len[idx].len += items->len[i].headerLen;
  3088. items->len[idx].len += items->len[i].len;
  3089. }
  3090. }
  3091. items->len[idx].headerLen += SetLength(items->len[idx].len, NULL);
  3092. }
  3093. /* Add more data to indefinite length item */
  3094. static void IndefItems_MoreData(IndefItems* items, word32 length)
  3095. {
  3096. if (items->cnt > 0 && items->idx >= 0) {
  3097. items->len[items->idx].len += length;
  3098. }
  3099. }
  3100. /* Convert a BER encoding with indefinite length items to DER.
  3101. *
  3102. * ber BER encoded data.
  3103. * berSz Length of BER encoded data.
  3104. * der Buffer to hold DER encoded version of data.
  3105. * NULL indicates only the length is required.
  3106. * derSz The size of the buffer to hold the DER encoded data.
  3107. * Will be set if der is NULL, otherwise the value is checked as der is
  3108. * filled.
  3109. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  3110. * derSz are NULL.
  3111. */
  3112. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  3113. {
  3114. int ret = 0;
  3115. word32 i, j;
  3116. #ifdef WOLFSSL_SMALL_STACK
  3117. IndefItems* indefItems = NULL;
  3118. #else
  3119. IndefItems indefItems[1];
  3120. #endif
  3121. byte tag, basic;
  3122. word32 length;
  3123. int indef;
  3124. if (ber == NULL || derSz == NULL)
  3125. return BAD_FUNC_ARG;
  3126. #ifdef WOLFSSL_SMALL_STACK
  3127. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL,
  3128. DYNAMIC_TYPE_TMP_BUFFER);
  3129. if (indefItems == NULL) {
  3130. ret = MEMORY_E;
  3131. goto end;
  3132. }
  3133. #endif
  3134. XMEMSET(indefItems, 0, sizeof(*indefItems));
  3135. /* Calculate indefinite item lengths */
  3136. for (i = 0; i < berSz; ) {
  3137. word32 start = i;
  3138. /* Get next BER item */
  3139. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3140. if (ret != 0) {
  3141. goto end;
  3142. }
  3143. if (indef) {
  3144. /* Indefinite item - add to list */
  3145. ret = IndefItems_AddItem(indefItems, i);
  3146. if (ret != 0) {
  3147. goto end;
  3148. }
  3149. if ((tag & 0xC0) == 0 &&
  3150. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3151. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3152. /* Constructed basic type - get repeating tag */
  3153. basic = tag & (~ASN_CONSTRUCTED);
  3154. /* Add up lengths of each item below */
  3155. for (; i < berSz; ) {
  3156. /* Get next BER_item */
  3157. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3158. if (ret != 0) {
  3159. goto end;
  3160. }
  3161. /* End of content closes item */
  3162. if (tag == ASN_EOC) {
  3163. /* Must be zero length */
  3164. if (length != 0) {
  3165. ret = ASN_PARSE_E;
  3166. goto end;
  3167. }
  3168. break;
  3169. }
  3170. /* Must not be indefinite and tag must match parent */
  3171. if (indef || tag != basic) {
  3172. ret = ASN_PARSE_E;
  3173. goto end;
  3174. }
  3175. /* Add to length */
  3176. IndefItems_AddData(indefItems, length);
  3177. /* Skip data */
  3178. i += length;
  3179. }
  3180. /* Ensure we got an EOC and not end of data */
  3181. if (tag != ASN_EOC) {
  3182. ret = ASN_PARSE_E;
  3183. goto end;
  3184. }
  3185. /* Set the header length to include the length field */
  3186. IndefItems_UpdateHeaderLen(indefItems);
  3187. /* Go to indefinte parent item */
  3188. IndefItems_Up(indefItems);
  3189. }
  3190. }
  3191. else if (tag == ASN_EOC) {
  3192. /* End-of-content must be 0 length */
  3193. if (length != 0) {
  3194. ret = ASN_PARSE_E;
  3195. goto end;
  3196. }
  3197. /* Check there is an item to close - missing EOC */
  3198. if (indefItems->depth == 0) {
  3199. ret = ASN_PARSE_E;
  3200. goto end;
  3201. }
  3202. /* Finish calculation of data length for indefinite item */
  3203. IndefItems_CalcLength(indefItems);
  3204. /* Go to indefinte parent item */
  3205. IndefItems_Up(indefItems);
  3206. }
  3207. else {
  3208. /* Known length item to add in - make sure enough data for it */
  3209. if (i + length > berSz) {
  3210. ret = ASN_PARSE_E;
  3211. goto end;
  3212. }
  3213. /* Include all data - can't have indefinite inside definite */
  3214. i += length;
  3215. /* Add entire item to current indefinite item */
  3216. IndefItems_MoreData(indefItems, i - start);
  3217. }
  3218. }
  3219. /* Check we had a EOC for each indefinite item */
  3220. if (indefItems->depth != 0) {
  3221. ret = ASN_PARSE_E;
  3222. goto end;
  3223. }
  3224. /* Write out DER */
  3225. j = 0;
  3226. /* Reset index */
  3227. indefItems->idx = 0;
  3228. for (i = 0; i < berSz; ) {
  3229. word32 start = i;
  3230. /* Get item - checked above */
  3231. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3232. if (indef) {
  3233. if (der != NULL) {
  3234. /* Check enough space for header */
  3235. if (j + IndefItems_HeaderLen(indefItems) > *derSz) {
  3236. ret = BUFFER_E;
  3237. goto end;
  3238. }
  3239. if ((tag & 0xC0) == 0 &&
  3240. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3241. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3242. /* Remove constructed tag for basic types */
  3243. tag &= ~ASN_CONSTRUCTED;
  3244. }
  3245. /* Add tag and length */
  3246. der[j] = tag;
  3247. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  3248. }
  3249. /* Add header length of indefinite item */
  3250. j += IndefItems_HeaderLen(indefItems);
  3251. if ((tag & 0xC0) == 0 &&
  3252. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  3253. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  3254. /* For basic type - get each child item and add data */
  3255. for (; i < berSz; ) {
  3256. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  3257. if (tag == ASN_EOC) {
  3258. break;
  3259. }
  3260. if (der != NULL) {
  3261. if (j + length > *derSz) {
  3262. ret = BUFFER_E;
  3263. goto end;
  3264. }
  3265. XMEMCPY(der + j, ber + i, length);
  3266. }
  3267. j += length;
  3268. i += length;
  3269. }
  3270. }
  3271. /* Move to next indef item in list */
  3272. indefItems->idx++;
  3273. }
  3274. else if (tag == ASN_EOC) {
  3275. /* End-Of-Content is not written out in DER */
  3276. }
  3277. else {
  3278. /* Write out definite length item as is. */
  3279. i += length;
  3280. if (der != NULL) {
  3281. /* Ensure space for item */
  3282. if (j + i - start > *derSz) {
  3283. ret = BUFFER_E;
  3284. goto end;
  3285. }
  3286. /* Copy item as is */
  3287. XMEMCPY(der + j, ber + start, i - start);
  3288. }
  3289. j += i - start;
  3290. }
  3291. }
  3292. /* Return the length of the DER encoded ASN.1 */
  3293. *derSz = j;
  3294. if (der == NULL) {
  3295. ret = LENGTH_ONLY_E;
  3296. }
  3297. end:
  3298. #ifdef WOLFSSL_SMALL_STACK
  3299. if (indefItems != NULL) {
  3300. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3301. }
  3302. #endif
  3303. return ret;
  3304. }
  3305. #endif
  3306. #ifndef WOLFSSL_ASN_TEMPLATE
  3307. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  3308. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  3309. *
  3310. * val 16-bit value to encode.
  3311. * output Buffer to write into.
  3312. * returns the number of bytes added to the buffer.
  3313. */
  3314. static word32 SetBitString16Bit(word16 val, byte* output)
  3315. {
  3316. word32 idx;
  3317. int len;
  3318. byte lastByte;
  3319. byte unusedBits = 0;
  3320. if ((val >> 8) != 0) {
  3321. len = 2;
  3322. lastByte = (byte)(val >> 8);
  3323. }
  3324. else {
  3325. len = 1;
  3326. lastByte = (byte)val;
  3327. }
  3328. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  3329. unusedBits++;
  3330. idx = SetBitString(len, unusedBits, output);
  3331. output[idx++] = (byte)val;
  3332. if (len > 1)
  3333. output[idx++] = (byte)(val >> 8);
  3334. return idx;
  3335. }
  3336. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  3337. #endif /* !WOLFSSL_ASN_TEMPLATE */
  3338. /* hashType */
  3339. #ifdef WOLFSSL_MD2
  3340. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  3341. #endif
  3342. #ifndef NO_MD5
  3343. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  3344. #endif
  3345. #ifndef NO_SHA
  3346. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  3347. #endif
  3348. #ifdef WOLFSSL_SHA224
  3349. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  3350. #endif
  3351. #ifndef NO_SHA256
  3352. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  3353. #endif
  3354. #ifdef WOLFSSL_SHA384
  3355. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  3356. #endif
  3357. #ifdef WOLFSSL_SHA512
  3358. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  3359. #endif
  3360. #ifdef WOLFSSL_SHA3
  3361. #ifndef WOLFSSL_NOSHA3_224
  3362. static const byte hashSha3_224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 7};
  3363. #endif /* WOLFSSL_NOSHA3_224 */
  3364. #ifndef WOLFSSL_NOSHA3_256
  3365. static const byte hashSha3_256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 8};
  3366. #endif /* WOLFSSL_NOSHA3_256 */
  3367. #ifndef WOLFSSL_NOSHA3_384
  3368. static const byte hashSha3_384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 9};
  3369. #endif /* WOLFSSL_NOSHA3_384 */
  3370. #ifndef WOLFSSL_NOSHA3_512
  3371. static const byte hashSha3_512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 10};
  3372. #endif /* WOLFSSL_NOSHA3_512 */
  3373. #endif /* WOLFSSL_SHA3 */
  3374. /* hmacType */
  3375. #ifndef NO_HMAC
  3376. #ifdef WOLFSSL_SHA224
  3377. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  3378. #endif
  3379. #ifndef NO_SHA256
  3380. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  3381. #endif
  3382. #ifdef WOLFSSL_SHA384
  3383. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  3384. #endif
  3385. #ifdef WOLFSSL_SHA512
  3386. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  3387. #endif
  3388. #endif
  3389. /* sigType */
  3390. #if !defined(NO_DSA) && !defined(NO_SHA)
  3391. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  3392. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  3393. #endif /* NO_DSA */
  3394. #ifndef NO_RSA
  3395. #ifdef WOLFSSL_MD2
  3396. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  3397. #endif
  3398. #ifndef NO_MD5
  3399. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  3400. #endif
  3401. #ifndef NO_SHA
  3402. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  3403. #endif
  3404. #ifdef WOLFSSL_SHA224
  3405. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  3406. #endif
  3407. #ifndef NO_SHA256
  3408. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  3409. #endif
  3410. #ifdef WOLFSSL_SHA384
  3411. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  3412. #endif
  3413. #ifdef WOLFSSL_SHA512
  3414. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  3415. #endif
  3416. #ifdef WOLFSSL_SHA3
  3417. #ifndef WOLFSSL_NOSHA3_224
  3418. static const byte sigSha3_224wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 13};
  3419. #endif
  3420. #ifndef WOLFSSL_NOSHA3_256
  3421. static const byte sigSha3_256wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 14};
  3422. #endif
  3423. #ifndef WOLFSSL_NOSHA3_384
  3424. static const byte sigSha3_384wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 15};
  3425. #endif
  3426. #ifndef WOLFSSL_NOSHA3_512
  3427. static const byte sigSha3_512wRsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 16};
  3428. #endif
  3429. #endif
  3430. #endif /* NO_RSA */
  3431. #ifdef HAVE_ECC
  3432. #ifndef NO_SHA
  3433. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  3434. #endif
  3435. #ifdef WOLFSSL_SHA224
  3436. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  3437. #endif
  3438. #ifndef NO_SHA256
  3439. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  3440. #endif
  3441. #ifdef WOLFSSL_SHA384
  3442. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  3443. #endif
  3444. #ifdef WOLFSSL_SHA512
  3445. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  3446. #endif
  3447. #ifdef WOLFSSL_SHA3
  3448. #ifndef WOLFSSL_NOSHA3_224
  3449. static const byte sigSha3_224wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 9};
  3450. #endif
  3451. #ifndef WOLFSSL_NOSHA3_256
  3452. static const byte sigSha3_256wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 10};
  3453. #endif
  3454. #ifndef WOLFSSL_NOSHA3_384
  3455. static const byte sigSha3_384wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 11};
  3456. #endif
  3457. #ifndef WOLFSSL_NOSHA3_512
  3458. static const byte sigSha3_512wEcdsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 12};
  3459. #endif
  3460. #endif
  3461. #endif /* HAVE_ECC */
  3462. #ifdef HAVE_ED25519
  3463. static const byte sigEd25519Oid[] = {43, 101, 112};
  3464. #endif /* HAVE_ED25519 */
  3465. #ifdef HAVE_ED448
  3466. static const byte sigEd448Oid[] = {43, 101, 113};
  3467. #endif /* HAVE_ED448 */
  3468. #ifdef HAVE_LIBOQS
  3469. /* Falcon Level 1: 1 3 9999 3 1 */
  3470. static const byte sigFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3471. /* Falcon Level 5: 1 3 9999 3 4 */
  3472. static const byte sigFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3473. #endif /* HAVE_LIBOQS */
  3474. /* keyType */
  3475. #ifndef NO_DSA
  3476. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  3477. #endif /* NO_DSA */
  3478. #ifndef NO_RSA
  3479. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  3480. #endif /* NO_RSA */
  3481. #ifdef HAVE_ECC
  3482. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  3483. #endif /* HAVE_ECC */
  3484. #ifdef HAVE_ED25519
  3485. static const byte keyEd25519Oid[] = {43, 101, 112};
  3486. #endif /* HAVE_ED25519 */
  3487. #ifdef HAVE_CURVE25519
  3488. static const byte keyCurve25519Oid[] = {43, 101, 110};
  3489. #endif
  3490. #ifdef HAVE_ED448
  3491. static const byte keyEd448Oid[] = {43, 101, 113};
  3492. #endif /* HAVE_ED448 */
  3493. #ifdef HAVE_CURVE448
  3494. static const byte keyCurve448Oid[] = {43, 101, 111};
  3495. #endif /* HAVE_CURVE448 */
  3496. #ifndef NO_DH
  3497. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  3498. #endif /* !NO_DH */
  3499. #ifdef HAVE_LIBOQS
  3500. /* Falcon Level 1: 1 3 9999 3 1 */
  3501. static const byte keyFalcon_Level1Oid[] = {43, 206, 15, 3, 1};
  3502. /* Falcon Level 5: 1 3 9999 3 4 */
  3503. static const byte keyFalcon_Level5Oid[] = {43, 206, 15, 3, 4};
  3504. #endif /* HAVE_LIBOQS */
  3505. /* curveType */
  3506. #ifdef HAVE_ECC
  3507. /* See "ecc_sets" table in ecc.c */
  3508. #endif /* HAVE_ECC */
  3509. #ifdef HAVE_AES_CBC
  3510. /* blkType */
  3511. #ifdef WOLFSSL_AES_128
  3512. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  3513. #endif
  3514. #ifdef WOLFSSL_AES_192
  3515. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  3516. #endif
  3517. #ifdef WOLFSSL_AES_256
  3518. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  3519. #endif
  3520. #endif /* HAVE_AES_CBC */
  3521. #ifdef HAVE_AESGCM
  3522. #ifdef WOLFSSL_AES_128
  3523. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  3524. #endif
  3525. #ifdef WOLFSSL_AES_192
  3526. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  3527. #endif
  3528. #ifdef WOLFSSL_AES_256
  3529. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  3530. #endif
  3531. #endif /* HAVE_AESGCM */
  3532. #ifdef HAVE_AESCCM
  3533. #ifdef WOLFSSL_AES_128
  3534. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  3535. #endif
  3536. #ifdef WOLFSSL_AES_192
  3537. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  3538. #endif
  3539. #ifdef WOLFSSL_AES_256
  3540. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  3541. #endif
  3542. #endif /* HAVE_AESCCM */
  3543. #ifndef NO_DES3
  3544. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  3545. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  3546. #endif
  3547. /* keyWrapType */
  3548. #ifdef WOLFSSL_AES_128
  3549. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  3550. #endif
  3551. #ifdef WOLFSSL_AES_192
  3552. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  3553. #endif
  3554. #ifdef WOLFSSL_AES_256
  3555. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  3556. #endif
  3557. #ifdef HAVE_PKCS7
  3558. /* From RFC 3211 */
  3559. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  3560. #endif
  3561. /* cmsKeyAgreeType */
  3562. #ifndef NO_SHA
  3563. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  3564. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  3565. #endif
  3566. #ifdef WOLFSSL_SHA224
  3567. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  3568. #endif
  3569. #ifndef NO_SHA256
  3570. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  3571. #endif
  3572. #ifdef WOLFSSL_SHA384
  3573. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  3574. #endif
  3575. #ifdef WOLFSSL_SHA512
  3576. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  3577. #endif
  3578. /* ocspType */
  3579. #ifdef HAVE_OCSP
  3580. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  3581. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  3582. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  3583. #endif /* HAVE_OCSP */
  3584. /* certExtType */
  3585. static const byte extBasicCaOid[] = {85, 29, 19};
  3586. static const byte extAltNamesOid[] = {85, 29, 17};
  3587. static const byte extCrlDistOid[] = {85, 29, 31};
  3588. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  3589. static const byte extAuthKeyOid[] = {85, 29, 35};
  3590. static const byte extSubjKeyOid[] = {85, 29, 14};
  3591. static const byte extCertPolicyOid[] = {85, 29, 32};
  3592. static const byte extKeyUsageOid[] = {85, 29, 15};
  3593. static const byte extInhibitAnyOid[] = {85, 29, 54};
  3594. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  3595. #ifndef IGNORE_NAME_CONSTRAINTS
  3596. static const byte extNameConsOid[] = {85, 29, 30};
  3597. #endif
  3598. #ifdef HAVE_CRL
  3599. static const byte extCrlNumberOid[] = {85, 29, 20};
  3600. #endif
  3601. /* certAuthInfoType */
  3602. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  3603. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  3604. /* certPolicyType */
  3605. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  3606. /* certAltNameType */
  3607. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  3608. /* certKeyUseType */
  3609. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  3610. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  3611. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  3612. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  3613. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  3614. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  3615. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  3616. #ifdef WOLFSSL_CERT_REQ
  3617. /* csrAttrType */
  3618. static const byte attrUnstructuredNameOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 2};
  3619. static const byte attrPkcs9ContentTypeOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 3};
  3620. static const byte attrChallengePasswordOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 7};
  3621. static const byte attrExtensionRequestOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 14};
  3622. static const byte attrSerialNumberOid[] = {85, 4, 5};
  3623. #endif
  3624. /* kdfType */
  3625. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  3626. /* PKCS5 */
  3627. #if !defined(NO_DES3) && !defined(NO_MD5)
  3628. static const byte pbeMd5Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 3};
  3629. #endif
  3630. #if !defined(NO_DES3) && !defined(NO_SHA)
  3631. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  3632. #endif
  3633. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  3634. /* PKCS12 */
  3635. #if !defined(NO_RC4) && !defined(NO_SHA)
  3636. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  3637. #endif
  3638. #if !defined(NO_DES3) && !defined(NO_SHA)
  3639. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  3640. #endif
  3641. #ifdef HAVE_LIBZ
  3642. /* zlib compression */
  3643. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  3644. #endif
  3645. #ifdef WOLFSSL_APACHE_HTTPD
  3646. /* tlsExtType */
  3647. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  3648. /* certNameType */
  3649. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  3650. #endif
  3651. /* Looks up the ID/type of an OID.
  3652. *
  3653. * When known returns the OID as a byte array and its length.
  3654. * ID-type are unique.
  3655. *
  3656. * Use oidIgnoreType to autofail.
  3657. *
  3658. * @param [in] id OID id.
  3659. * @param [in] type Type of OID (enum Oid_Types).
  3660. * @param [out] oidSz Length of OID byte array returned.
  3661. * @return Array of bytes for the OID.
  3662. * @return NULL when ID/type not recognized.
  3663. */
  3664. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  3665. {
  3666. const byte* oid = NULL;
  3667. *oidSz = 0;
  3668. switch (type) {
  3669. case oidHashType:
  3670. switch (id) {
  3671. #ifdef WOLFSSL_MD2
  3672. case MD2h:
  3673. oid = hashMd2hOid;
  3674. *oidSz = sizeof(hashMd2hOid);
  3675. break;
  3676. #endif
  3677. #ifndef NO_MD5
  3678. case MD5h:
  3679. oid = hashMd5hOid;
  3680. *oidSz = sizeof(hashMd5hOid);
  3681. break;
  3682. #endif
  3683. #ifndef NO_SHA
  3684. case SHAh:
  3685. oid = hashSha1hOid;
  3686. *oidSz = sizeof(hashSha1hOid);
  3687. break;
  3688. #endif
  3689. #ifdef WOLFSSL_SHA224
  3690. case SHA224h:
  3691. oid = hashSha224hOid;
  3692. *oidSz = sizeof(hashSha224hOid);
  3693. break;
  3694. #endif
  3695. #ifndef NO_SHA256
  3696. case SHA256h:
  3697. oid = hashSha256hOid;
  3698. *oidSz = sizeof(hashSha256hOid);
  3699. break;
  3700. #endif
  3701. #ifdef WOLFSSL_SHA384
  3702. case SHA384h:
  3703. oid = hashSha384hOid;
  3704. *oidSz = sizeof(hashSha384hOid);
  3705. break;
  3706. #endif
  3707. #ifdef WOLFSSL_SHA512
  3708. case SHA512h:
  3709. oid = hashSha512hOid;
  3710. *oidSz = sizeof(hashSha512hOid);
  3711. break;
  3712. #endif
  3713. #ifdef WOLFSSL_SHA3
  3714. #ifndef WOLFSSL_NOSHA3_224
  3715. case SHA3_224h:
  3716. oid = hashSha3_224hOid;
  3717. *oidSz = sizeof(hashSha3_224hOid);
  3718. break;
  3719. #endif /* WOLFSSL_NOSHA3_224 */
  3720. #ifndef WOLFSSL_NOSHA3_256
  3721. case SHA3_256h:
  3722. oid = hashSha3_256hOid;
  3723. *oidSz = sizeof(hashSha3_256hOid);
  3724. break;
  3725. #endif /* WOLFSSL_NOSHA3_256 */
  3726. #ifndef WOLFSSL_NOSHA3_384
  3727. case SHA3_384h:
  3728. oid = hashSha3_384hOid;
  3729. *oidSz = sizeof(hashSha3_384hOid);
  3730. break;
  3731. #endif /* WOLFSSL_NOSHA3_384 */
  3732. #ifndef WOLFSSL_NOSHA3_512
  3733. case SHA3_512h:
  3734. oid = hashSha3_512hOid;
  3735. *oidSz = sizeof(hashSha3_512hOid);
  3736. break;
  3737. #endif /* WOLFSSL_NOSHA3_512 */
  3738. #endif /* WOLFSSL_SHA3 */
  3739. default:
  3740. break;
  3741. }
  3742. break;
  3743. case oidSigType:
  3744. switch (id) {
  3745. #if !defined(NO_DSA) && !defined(NO_SHA)
  3746. case CTC_SHAwDSA:
  3747. oid = sigSha1wDsaOid;
  3748. *oidSz = sizeof(sigSha1wDsaOid);
  3749. break;
  3750. case CTC_SHA256wDSA:
  3751. oid = sigSha256wDsaOid;
  3752. *oidSz = sizeof(sigSha256wDsaOid);
  3753. break;
  3754. #endif /* NO_DSA */
  3755. #ifndef NO_RSA
  3756. #ifdef WOLFSSL_MD2
  3757. case CTC_MD2wRSA:
  3758. oid = sigMd2wRsaOid;
  3759. *oidSz = sizeof(sigMd2wRsaOid);
  3760. break;
  3761. #endif
  3762. #ifndef NO_MD5
  3763. case CTC_MD5wRSA:
  3764. oid = sigMd5wRsaOid;
  3765. *oidSz = sizeof(sigMd5wRsaOid);
  3766. break;
  3767. #endif
  3768. #ifndef NO_SHA
  3769. case CTC_SHAwRSA:
  3770. oid = sigSha1wRsaOid;
  3771. *oidSz = sizeof(sigSha1wRsaOid);
  3772. break;
  3773. #endif
  3774. #ifdef WOLFSSL_SHA224
  3775. case CTC_SHA224wRSA:
  3776. oid = sigSha224wRsaOid;
  3777. *oidSz = sizeof(sigSha224wRsaOid);
  3778. break;
  3779. #endif
  3780. #ifndef NO_SHA256
  3781. case CTC_SHA256wRSA:
  3782. oid = sigSha256wRsaOid;
  3783. *oidSz = sizeof(sigSha256wRsaOid);
  3784. break;
  3785. #endif
  3786. #ifdef WOLFSSL_SHA384
  3787. case CTC_SHA384wRSA:
  3788. oid = sigSha384wRsaOid;
  3789. *oidSz = sizeof(sigSha384wRsaOid);
  3790. break;
  3791. #endif
  3792. #ifdef WOLFSSL_SHA512
  3793. case CTC_SHA512wRSA:
  3794. oid = sigSha512wRsaOid;
  3795. *oidSz = sizeof(sigSha512wRsaOid);
  3796. break;
  3797. #endif /* WOLFSSL_SHA512 */
  3798. #ifdef WOLFSSL_SHA3
  3799. #ifndef WOLFSSL_NOSHA3_224
  3800. case CTC_SHA3_224wRSA:
  3801. oid = sigSha3_224wRsaOid;
  3802. *oidSz = sizeof(sigSha3_224wRsaOid);
  3803. break;
  3804. #endif
  3805. #ifndef WOLFSSL_NOSHA3_256
  3806. case CTC_SHA3_256wRSA:
  3807. oid = sigSha3_256wRsaOid;
  3808. *oidSz = sizeof(sigSha3_256wRsaOid);
  3809. break;
  3810. #endif
  3811. #ifndef WOLFSSL_NOSHA3_384
  3812. case CTC_SHA3_384wRSA:
  3813. oid = sigSha3_384wRsaOid;
  3814. *oidSz = sizeof(sigSha3_384wRsaOid);
  3815. break;
  3816. #endif
  3817. #ifndef WOLFSSL_NOSHA3_512
  3818. case CTC_SHA3_512wRSA:
  3819. oid = sigSha3_512wRsaOid;
  3820. *oidSz = sizeof(sigSha3_512wRsaOid);
  3821. break;
  3822. #endif
  3823. #endif
  3824. #endif /* NO_RSA */
  3825. #ifdef HAVE_ECC
  3826. #ifndef NO_SHA
  3827. case CTC_SHAwECDSA:
  3828. oid = sigSha1wEcdsaOid;
  3829. *oidSz = sizeof(sigSha1wEcdsaOid);
  3830. break;
  3831. #endif
  3832. #ifdef WOLFSSL_SHA224
  3833. case CTC_SHA224wECDSA:
  3834. oid = sigSha224wEcdsaOid;
  3835. *oidSz = sizeof(sigSha224wEcdsaOid);
  3836. break;
  3837. #endif
  3838. #ifndef NO_SHA256
  3839. case CTC_SHA256wECDSA:
  3840. oid = sigSha256wEcdsaOid;
  3841. *oidSz = sizeof(sigSha256wEcdsaOid);
  3842. break;
  3843. #endif
  3844. #ifdef WOLFSSL_SHA384
  3845. case CTC_SHA384wECDSA:
  3846. oid = sigSha384wEcdsaOid;
  3847. *oidSz = sizeof(sigSha384wEcdsaOid);
  3848. break;
  3849. #endif
  3850. #ifdef WOLFSSL_SHA512
  3851. case CTC_SHA512wECDSA:
  3852. oid = sigSha512wEcdsaOid;
  3853. *oidSz = sizeof(sigSha512wEcdsaOid);
  3854. break;
  3855. #endif
  3856. #ifdef WOLFSSL_SHA3
  3857. #ifndef WOLFSSL_NOSHA3_224
  3858. case CTC_SHA3_224wECDSA:
  3859. oid = sigSha3_224wEcdsaOid;
  3860. *oidSz = sizeof(sigSha3_224wEcdsaOid);
  3861. break;
  3862. #endif
  3863. #ifndef WOLFSSL_NOSHA3_256
  3864. case CTC_SHA3_256wECDSA:
  3865. oid = sigSha3_256wEcdsaOid;
  3866. *oidSz = sizeof(sigSha3_256wEcdsaOid);
  3867. break;
  3868. #endif
  3869. #ifndef WOLFSSL_NOSHA3_384
  3870. case CTC_SHA3_384wECDSA:
  3871. oid = sigSha3_384wEcdsaOid;
  3872. *oidSz = sizeof(sigSha3_384wEcdsaOid);
  3873. break;
  3874. #endif
  3875. #ifndef WOLFSSL_NOSHA3_512
  3876. case CTC_SHA3_512wECDSA:
  3877. oid = sigSha3_512wEcdsaOid;
  3878. *oidSz = sizeof(sigSha3_512wEcdsaOid);
  3879. break;
  3880. #endif
  3881. #endif
  3882. #endif /* HAVE_ECC */
  3883. #ifdef HAVE_ED25519
  3884. case CTC_ED25519:
  3885. oid = sigEd25519Oid;
  3886. *oidSz = sizeof(sigEd25519Oid);
  3887. break;
  3888. #endif
  3889. #ifdef HAVE_ED448
  3890. case CTC_ED448:
  3891. oid = sigEd448Oid;
  3892. *oidSz = sizeof(sigEd448Oid);
  3893. break;
  3894. #endif
  3895. #ifdef HAVE_LIBOQS
  3896. case CTC_FALCON_LEVEL1:
  3897. oid = sigFalcon_Level1Oid;
  3898. *oidSz = sizeof(sigFalcon_Level1Oid);
  3899. break;
  3900. case CTC_FALCON_LEVEL5:
  3901. oid = sigFalcon_Level5Oid;
  3902. *oidSz = sizeof(sigFalcon_Level5Oid);
  3903. break;
  3904. #endif
  3905. default:
  3906. break;
  3907. }
  3908. break;
  3909. case oidKeyType:
  3910. switch (id) {
  3911. #ifndef NO_DSA
  3912. case DSAk:
  3913. oid = keyDsaOid;
  3914. *oidSz = sizeof(keyDsaOid);
  3915. break;
  3916. #endif /* NO_DSA */
  3917. #ifndef NO_RSA
  3918. case RSAk:
  3919. oid = keyRsaOid;
  3920. *oidSz = sizeof(keyRsaOid);
  3921. break;
  3922. #endif /* NO_RSA */
  3923. #ifdef HAVE_ECC
  3924. case ECDSAk:
  3925. oid = keyEcdsaOid;
  3926. *oidSz = sizeof(keyEcdsaOid);
  3927. break;
  3928. #endif /* HAVE_ECC */
  3929. #ifdef HAVE_ED25519
  3930. case ED25519k:
  3931. oid = keyEd25519Oid;
  3932. *oidSz = sizeof(keyEd25519Oid);
  3933. break;
  3934. #endif /* HAVE_ED25519 */
  3935. #ifdef HAVE_CURVE25519
  3936. case X25519k:
  3937. oid = keyCurve25519Oid;
  3938. *oidSz = sizeof(keyCurve25519Oid);
  3939. break;
  3940. #endif /* HAVE_CURVE25519 */
  3941. #ifdef HAVE_ED448
  3942. case ED448k:
  3943. oid = keyEd448Oid;
  3944. *oidSz = sizeof(keyEd448Oid);
  3945. break;
  3946. #endif /* HAVE_ED448 */
  3947. #ifdef HAVE_CURVE448
  3948. case X448k:
  3949. oid = keyCurve448Oid;
  3950. *oidSz = sizeof(keyCurve448Oid);
  3951. break;
  3952. #endif /* HAVE_CURVE448 */
  3953. #ifndef NO_DH
  3954. case DHk:
  3955. oid = keyDhOid;
  3956. *oidSz = sizeof(keyDhOid);
  3957. break;
  3958. #endif /* !NO_DH */
  3959. #ifdef HAVE_LIBOQS
  3960. case FALCON_LEVEL1k:
  3961. oid = keyFalcon_Level1Oid;
  3962. *oidSz = sizeof(keyFalcon_Level1Oid);
  3963. break;
  3964. case FALCON_LEVEL5k:
  3965. oid = keyFalcon_Level5Oid;
  3966. *oidSz = sizeof(keyFalcon_Level5Oid);
  3967. break;
  3968. #endif
  3969. default:
  3970. break;
  3971. }
  3972. break;
  3973. #ifdef HAVE_ECC
  3974. case oidCurveType:
  3975. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  3976. WOLFSSL_MSG("ECC OID not found");
  3977. }
  3978. break;
  3979. #endif /* HAVE_ECC */
  3980. case oidBlkType:
  3981. switch (id) {
  3982. #ifdef HAVE_AES_CBC
  3983. #ifdef WOLFSSL_AES_128
  3984. case AES128CBCb:
  3985. oid = blkAes128CbcOid;
  3986. *oidSz = sizeof(blkAes128CbcOid);
  3987. break;
  3988. #endif
  3989. #ifdef WOLFSSL_AES_192
  3990. case AES192CBCb:
  3991. oid = blkAes192CbcOid;
  3992. *oidSz = sizeof(blkAes192CbcOid);
  3993. break;
  3994. #endif
  3995. #ifdef WOLFSSL_AES_256
  3996. case AES256CBCb:
  3997. oid = blkAes256CbcOid;
  3998. *oidSz = sizeof(blkAes256CbcOid);
  3999. break;
  4000. #endif
  4001. #endif /* HAVE_AES_CBC */
  4002. #ifdef HAVE_AESGCM
  4003. #ifdef WOLFSSL_AES_128
  4004. case AES128GCMb:
  4005. oid = blkAes128GcmOid;
  4006. *oidSz = sizeof(blkAes128GcmOid);
  4007. break;
  4008. #endif
  4009. #ifdef WOLFSSL_AES_192
  4010. case AES192GCMb:
  4011. oid = blkAes192GcmOid;
  4012. *oidSz = sizeof(blkAes192GcmOid);
  4013. break;
  4014. #endif
  4015. #ifdef WOLFSSL_AES_256
  4016. case AES256GCMb:
  4017. oid = blkAes256GcmOid;
  4018. *oidSz = sizeof(blkAes256GcmOid);
  4019. break;
  4020. #endif
  4021. #endif /* HAVE_AESGCM */
  4022. #ifdef HAVE_AESCCM
  4023. #ifdef WOLFSSL_AES_128
  4024. case AES128CCMb:
  4025. oid = blkAes128CcmOid;
  4026. *oidSz = sizeof(blkAes128CcmOid);
  4027. break;
  4028. #endif
  4029. #ifdef WOLFSSL_AES_192
  4030. case AES192CCMb:
  4031. oid = blkAes192CcmOid;
  4032. *oidSz = sizeof(blkAes192CcmOid);
  4033. break;
  4034. #endif
  4035. #ifdef WOLFSSL_AES_256
  4036. case AES256CCMb:
  4037. oid = blkAes256CcmOid;
  4038. *oidSz = sizeof(blkAes256CcmOid);
  4039. break;
  4040. #endif
  4041. #endif /* HAVE_AESCCM */
  4042. #ifndef NO_DES3
  4043. case DESb:
  4044. oid = blkDesCbcOid;
  4045. *oidSz = sizeof(blkDesCbcOid);
  4046. break;
  4047. case DES3b:
  4048. oid = blkDes3CbcOid;
  4049. *oidSz = sizeof(blkDes3CbcOid);
  4050. break;
  4051. #endif /* !NO_DES3 */
  4052. default:
  4053. break;
  4054. }
  4055. break;
  4056. #ifdef HAVE_OCSP
  4057. case oidOcspType:
  4058. switch (id) {
  4059. case OCSP_BASIC_OID:
  4060. oid = ocspBasicOid;
  4061. *oidSz = sizeof(ocspBasicOid);
  4062. break;
  4063. case OCSP_NONCE_OID:
  4064. oid = ocspNonceOid;
  4065. *oidSz = sizeof(ocspNonceOid);
  4066. break;
  4067. default:
  4068. break;
  4069. }
  4070. break;
  4071. #endif /* HAVE_OCSP */
  4072. case oidCertExtType:
  4073. switch (id) {
  4074. case BASIC_CA_OID:
  4075. oid = extBasicCaOid;
  4076. *oidSz = sizeof(extBasicCaOid);
  4077. break;
  4078. case ALT_NAMES_OID:
  4079. oid = extAltNamesOid;
  4080. *oidSz = sizeof(extAltNamesOid);
  4081. break;
  4082. case CRL_DIST_OID:
  4083. oid = extCrlDistOid;
  4084. *oidSz = sizeof(extCrlDistOid);
  4085. break;
  4086. case AUTH_INFO_OID:
  4087. oid = extAuthInfoOid;
  4088. *oidSz = sizeof(extAuthInfoOid);
  4089. break;
  4090. case AUTH_KEY_OID:
  4091. oid = extAuthKeyOid;
  4092. *oidSz = sizeof(extAuthKeyOid);
  4093. break;
  4094. case SUBJ_KEY_OID:
  4095. oid = extSubjKeyOid;
  4096. *oidSz = sizeof(extSubjKeyOid);
  4097. break;
  4098. case CERT_POLICY_OID:
  4099. oid = extCertPolicyOid;
  4100. *oidSz = sizeof(extCertPolicyOid);
  4101. break;
  4102. case KEY_USAGE_OID:
  4103. oid = extKeyUsageOid;
  4104. *oidSz = sizeof(extKeyUsageOid);
  4105. break;
  4106. case INHIBIT_ANY_OID:
  4107. oid = extInhibitAnyOid;
  4108. *oidSz = sizeof(extInhibitAnyOid);
  4109. break;
  4110. case EXT_KEY_USAGE_OID:
  4111. oid = extExtKeyUsageOid;
  4112. *oidSz = sizeof(extExtKeyUsageOid);
  4113. break;
  4114. #ifndef IGNORE_NAME_CONSTRAINTS
  4115. case NAME_CONS_OID:
  4116. oid = extNameConsOid;
  4117. *oidSz = sizeof(extNameConsOid);
  4118. break;
  4119. #endif
  4120. #ifdef HAVE_OCSP
  4121. case OCSP_NOCHECK_OID:
  4122. oid = ocspNoCheckOid;
  4123. *oidSz = sizeof(ocspNoCheckOid);
  4124. break;
  4125. #endif
  4126. default:
  4127. break;
  4128. }
  4129. break;
  4130. case oidCrlExtType:
  4131. #ifdef HAVE_CRL
  4132. switch (id) {
  4133. case AUTH_KEY_OID:
  4134. oid = extAuthKeyOid;
  4135. *oidSz = sizeof(extAuthKeyOid);
  4136. break;
  4137. case CRL_NUMBER_OID:
  4138. oid = extCrlNumberOid;
  4139. *oidSz = sizeof(extCrlNumberOid);
  4140. break;
  4141. default:
  4142. break;
  4143. }
  4144. #endif
  4145. break;
  4146. case oidCertAuthInfoType:
  4147. switch (id) {
  4148. case AIA_OCSP_OID:
  4149. oid = extAuthInfoOcspOid;
  4150. *oidSz = sizeof(extAuthInfoOcspOid);
  4151. break;
  4152. case AIA_CA_ISSUER_OID:
  4153. oid = extAuthInfoCaIssuerOid;
  4154. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  4155. break;
  4156. default:
  4157. break;
  4158. }
  4159. break;
  4160. case oidCertPolicyType:
  4161. switch (id) {
  4162. case CP_ANY_OID:
  4163. oid = extCertPolicyAnyOid;
  4164. *oidSz = sizeof(extCertPolicyAnyOid);
  4165. break;
  4166. default:
  4167. break;
  4168. }
  4169. break;
  4170. case oidCertAltNameType:
  4171. switch (id) {
  4172. case HW_NAME_OID:
  4173. oid = extAltNamesHwNameOid;
  4174. *oidSz = sizeof(extAltNamesHwNameOid);
  4175. break;
  4176. default:
  4177. break;
  4178. }
  4179. break;
  4180. case oidCertKeyUseType:
  4181. switch (id) {
  4182. case EKU_ANY_OID:
  4183. oid = extExtKeyUsageAnyOid;
  4184. *oidSz = sizeof(extExtKeyUsageAnyOid);
  4185. break;
  4186. case EKU_SERVER_AUTH_OID:
  4187. oid = extExtKeyUsageServerAuthOid;
  4188. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  4189. break;
  4190. case EKU_CLIENT_AUTH_OID:
  4191. oid = extExtKeyUsageClientAuthOid;
  4192. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  4193. break;
  4194. case EKU_CODESIGNING_OID:
  4195. oid = extExtKeyUsageCodeSigningOid;
  4196. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  4197. break;
  4198. case EKU_EMAILPROTECT_OID:
  4199. oid = extExtKeyUsageEmailProtectOid;
  4200. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  4201. break;
  4202. case EKU_TIMESTAMP_OID:
  4203. oid = extExtKeyUsageTimestampOid;
  4204. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  4205. break;
  4206. case EKU_OCSP_SIGN_OID:
  4207. oid = extExtKeyUsageOcspSignOid;
  4208. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  4209. break;
  4210. default:
  4211. break;
  4212. }
  4213. break;
  4214. case oidKdfType:
  4215. switch (id) {
  4216. case PBKDF2_OID:
  4217. oid = pbkdf2Oid;
  4218. *oidSz = sizeof(pbkdf2Oid);
  4219. break;
  4220. default:
  4221. break;
  4222. }
  4223. break;
  4224. case oidPBEType:
  4225. switch (id) {
  4226. #if !defined(NO_SHA) && !defined(NO_RC4)
  4227. case PBE_SHA1_RC4_128_SUM:
  4228. case PBE_SHA1_RC4_128:
  4229. oid = pbeSha1RC4128;
  4230. *oidSz = sizeof(pbeSha1RC4128);
  4231. break;
  4232. #endif
  4233. #if !defined(NO_MD5) && !defined(NO_DES3)
  4234. case PBE_MD5_DES_SUM:
  4235. case PBE_MD5_DES:
  4236. oid = pbeMd5Des;
  4237. *oidSz = sizeof(pbeMd5Des);
  4238. break;
  4239. #endif
  4240. #if !defined(NO_SHA) && !defined(NO_DES3)
  4241. case PBE_SHA1_DES_SUM:
  4242. case PBE_SHA1_DES:
  4243. oid = pbeSha1Des;
  4244. *oidSz = sizeof(pbeSha1Des);
  4245. break;
  4246. #endif
  4247. #if !defined(NO_SHA) && !defined(NO_DES3)
  4248. case PBE_SHA1_DES3_SUM:
  4249. case PBE_SHA1_DES3:
  4250. oid = pbeSha1Des3;
  4251. *oidSz = sizeof(pbeSha1Des3);
  4252. break;
  4253. #endif
  4254. case PBES2_SUM:
  4255. case PBES2:
  4256. oid = pbes2;
  4257. *oidSz = sizeof(pbes2);
  4258. break;
  4259. default:
  4260. break;
  4261. }
  4262. break;
  4263. case oidKeyWrapType:
  4264. switch (id) {
  4265. #ifdef WOLFSSL_AES_128
  4266. case AES128_WRAP:
  4267. oid = wrapAes128Oid;
  4268. *oidSz = sizeof(wrapAes128Oid);
  4269. break;
  4270. #endif
  4271. #ifdef WOLFSSL_AES_192
  4272. case AES192_WRAP:
  4273. oid = wrapAes192Oid;
  4274. *oidSz = sizeof(wrapAes192Oid);
  4275. break;
  4276. #endif
  4277. #ifdef WOLFSSL_AES_256
  4278. case AES256_WRAP:
  4279. oid = wrapAes256Oid;
  4280. *oidSz = sizeof(wrapAes256Oid);
  4281. break;
  4282. #endif
  4283. #ifdef HAVE_PKCS7
  4284. case PWRI_KEK_WRAP:
  4285. oid = wrapPwriKekOid;
  4286. *oidSz = sizeof(wrapPwriKekOid);
  4287. break;
  4288. #endif
  4289. default:
  4290. break;
  4291. }
  4292. break;
  4293. case oidCmsKeyAgreeType:
  4294. switch (id) {
  4295. #ifndef NO_SHA
  4296. case dhSinglePass_stdDH_sha1kdf_scheme:
  4297. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  4298. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  4299. break;
  4300. #endif
  4301. #ifdef WOLFSSL_SHA224
  4302. case dhSinglePass_stdDH_sha224kdf_scheme:
  4303. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  4304. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  4305. break;
  4306. #endif
  4307. #ifndef NO_SHA256
  4308. case dhSinglePass_stdDH_sha256kdf_scheme:
  4309. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  4310. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  4311. break;
  4312. #endif
  4313. #ifdef WOLFSSL_SHA384
  4314. case dhSinglePass_stdDH_sha384kdf_scheme:
  4315. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  4316. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  4317. break;
  4318. #endif
  4319. #ifdef WOLFSSL_SHA512
  4320. case dhSinglePass_stdDH_sha512kdf_scheme:
  4321. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  4322. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  4323. break;
  4324. #endif
  4325. default:
  4326. break;
  4327. }
  4328. break;
  4329. #ifndef NO_HMAC
  4330. case oidHmacType:
  4331. switch (id) {
  4332. #ifdef WOLFSSL_SHA224
  4333. case HMAC_SHA224_OID:
  4334. oid = hmacSha224Oid;
  4335. *oidSz = sizeof(hmacSha224Oid);
  4336. break;
  4337. #endif
  4338. #ifndef NO_SHA256
  4339. case HMAC_SHA256_OID:
  4340. oid = hmacSha256Oid;
  4341. *oidSz = sizeof(hmacSha256Oid);
  4342. break;
  4343. #endif
  4344. #ifdef WOLFSSL_SHA384
  4345. case HMAC_SHA384_OID:
  4346. oid = hmacSha384Oid;
  4347. *oidSz = sizeof(hmacSha384Oid);
  4348. break;
  4349. #endif
  4350. #ifdef WOLFSSL_SHA512
  4351. case HMAC_SHA512_OID:
  4352. oid = hmacSha512Oid;
  4353. *oidSz = sizeof(hmacSha512Oid);
  4354. break;
  4355. #endif
  4356. default:
  4357. break;
  4358. }
  4359. break;
  4360. #endif /* !NO_HMAC */
  4361. #ifdef HAVE_LIBZ
  4362. case oidCompressType:
  4363. switch (id) {
  4364. case ZLIBc:
  4365. oid = zlibCompress;
  4366. *oidSz = sizeof(zlibCompress);
  4367. break;
  4368. default:
  4369. break;
  4370. }
  4371. break;
  4372. #endif /* HAVE_LIBZ */
  4373. #ifdef WOLFSSL_APACHE_HTTPD
  4374. case oidCertNameType:
  4375. switch (id) {
  4376. case NID_id_on_dnsSRV:
  4377. oid = dnsSRVOid;
  4378. *oidSz = sizeof(dnsSRVOid);
  4379. break;
  4380. default:
  4381. break;
  4382. }
  4383. break;
  4384. case oidTlsExtType:
  4385. switch (id) {
  4386. case TLS_FEATURE_OID:
  4387. oid = tlsFeatureOid;
  4388. *oidSz = sizeof(tlsFeatureOid);
  4389. break;
  4390. default:
  4391. break;
  4392. }
  4393. break;
  4394. #endif /* WOLFSSL_APACHE_HTTPD */
  4395. #ifdef WOLFSSL_CERT_REQ
  4396. case oidCsrAttrType:
  4397. switch (id) {
  4398. case UNSTRUCTURED_NAME_OID:
  4399. oid = attrUnstructuredNameOid;
  4400. *oidSz = sizeof(attrUnstructuredNameOid);
  4401. break;
  4402. case PKCS9_CONTENT_TYPE_OID:
  4403. oid = attrPkcs9ContentTypeOid;
  4404. *oidSz = sizeof(attrPkcs9ContentTypeOid);
  4405. break;
  4406. case CHALLENGE_PASSWORD_OID:
  4407. oid = attrChallengePasswordOid;
  4408. *oidSz = sizeof(attrChallengePasswordOid);
  4409. break;
  4410. case SERIAL_NUMBER_OID:
  4411. oid = attrSerialNumberOid;
  4412. *oidSz = sizeof(attrSerialNumberOid);
  4413. break;
  4414. case EXTENSION_REQUEST_OID:
  4415. oid = attrExtensionRequestOid;
  4416. *oidSz = sizeof(attrExtensionRequestOid);
  4417. break;
  4418. default:
  4419. break;
  4420. }
  4421. break;
  4422. #endif
  4423. case oidIgnoreType:
  4424. default:
  4425. break;
  4426. }
  4427. return oid;
  4428. }
  4429. #ifdef HAVE_ECC
  4430. /* Check the OID id is for a known elliptic curve.
  4431. *
  4432. * @param [in] oid OID id.
  4433. * @return ECC set id on success.
  4434. * @return ALGO_ID_E when OID id is 0 or not supported.
  4435. */
  4436. static int CheckCurve(word32 oid)
  4437. {
  4438. int ret;
  4439. word32 oidSz;
  4440. /* Lookup OID id. */
  4441. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  4442. /* Check for error or zero length OID size (can't get OID for encoding). */
  4443. if ((ret < 0) || (oidSz == 0)) {
  4444. WOLFSSL_MSG("CheckCurve not found");
  4445. ret = ALGO_ID_E;
  4446. }
  4447. /* Return ECC set id or error code. */
  4448. return ret;
  4449. }
  4450. #endif
  4451. #ifdef HAVE_OID_ENCODING
  4452. /* Encode dotted form of OID into byte array version.
  4453. *
  4454. * @param [in] in Dotted form of OID.
  4455. * @param [in] inSz Count of numbers in dotted form.
  4456. * @param [in] out Buffer to hold OID.
  4457. * @param [in, out] outSz On in, size of buffer.
  4458. * On out, number of bytes in buffer.
  4459. * @return 0 on success
  4460. * @return BAD_FUNC_ARG when in or outSz is NULL.
  4461. * @return BUFFER_E when buffer too small.
  4462. */
  4463. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  4464. {
  4465. int i, x, len;
  4466. word32 d, t;
  4467. /* check args */
  4468. if (in == NULL || outSz == NULL) {
  4469. return BAD_FUNC_ARG;
  4470. }
  4471. /* compute length of encoded OID */
  4472. d = (in[0] * 40) + in[1];
  4473. len = 0;
  4474. for (i = 1; i < (int)inSz; i++) {
  4475. x = 0;
  4476. t = d;
  4477. while (t) {
  4478. x++;
  4479. t >>= 1;
  4480. }
  4481. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  4482. if (i < (int)inSz - 1) {
  4483. d = in[i + 1];
  4484. }
  4485. }
  4486. if (out) {
  4487. /* verify length */
  4488. if ((int)*outSz < len) {
  4489. return BUFFER_E; /* buffer provided is not large enough */
  4490. }
  4491. /* calc first byte */
  4492. d = (in[0] * 40) + in[1];
  4493. /* encode bytes */
  4494. x = 0;
  4495. for (i = 1; i < (int)inSz; i++) {
  4496. if (d) {
  4497. int y = x, z;
  4498. byte mask = 0;
  4499. while (d) {
  4500. out[x++] = (byte)((d & 0x7F) | mask);
  4501. d >>= 7;
  4502. mask |= 0x80; /* upper bit is set on all but the last byte */
  4503. }
  4504. /* now swap bytes y...x-1 */
  4505. z = x - 1;
  4506. while (y < z) {
  4507. mask = out[y];
  4508. out[y] = out[z];
  4509. out[z] = mask;
  4510. ++y;
  4511. --z;
  4512. }
  4513. }
  4514. else {
  4515. out[x++] = 0x00; /* zero value */
  4516. }
  4517. /* next word */
  4518. if (i < (int)inSz - 1) {
  4519. d = in[i + 1];
  4520. }
  4521. }
  4522. }
  4523. /* return length */
  4524. *outSz = len;
  4525. return 0;
  4526. }
  4527. #endif /* HAVE_OID_ENCODING */
  4528. #ifdef HAVE_OID_DECODING
  4529. /* Encode dotted form of OID into byte array version.
  4530. *
  4531. * @param [in] in Byte array containing OID.
  4532. * @param [in] inSz Size of OID in bytes.
  4533. * @param [in] out Array to hold dotted form of OID.
  4534. * @param [in, out] outSz On in, number of elemnts in array.
  4535. * On out, count of numbers in dotted form.
  4536. * @return 0 on success
  4537. * @return BAD_FUNC_ARG when in or outSz is NULL.
  4538. * @return BUFFER_E when dotted form buffer too small.
  4539. */
  4540. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  4541. {
  4542. int x = 0, y = 0;
  4543. word32 t = 0;
  4544. /* check args */
  4545. if (in == NULL || outSz == NULL) {
  4546. return BAD_FUNC_ARG;
  4547. }
  4548. /* decode bytes */
  4549. while (inSz--) {
  4550. t = (t << 7) | (in[x] & 0x7F);
  4551. if (!(in[x] & 0x80)) {
  4552. if (y >= (int)*outSz) {
  4553. return BUFFER_E;
  4554. }
  4555. if (y == 0) {
  4556. out[0] = (t / 40);
  4557. out[1] = (t % 40);
  4558. y = 2;
  4559. }
  4560. else {
  4561. out[y++] = t;
  4562. }
  4563. t = 0; /* reset tmp */
  4564. }
  4565. x++;
  4566. }
  4567. /* return length */
  4568. *outSz = y;
  4569. return 0;
  4570. }
  4571. #endif /* HAVE_OID_DECODING */
  4572. /* Decode the header of a BER/DER encoded OBJECT ID.
  4573. *
  4574. * @param [in] input Buffer holding DER/BER encoded data.
  4575. * @param [in, out] inOutIdx On in, starting index of header.
  4576. * On out, end of parsed header.
  4577. * @param [out] len Number of bytes in the ASN.1 data.
  4578. * @param [in] maxIdx Length of data in buffer.
  4579. * @return 0 on success.
  4580. * @return BUFFER_E when there is not enough data to parse.
  4581. * @return ASN_PARSE_E when the tag is not a OBJECT ID or length is invalid.
  4582. */
  4583. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len, word32 maxIdx)
  4584. {
  4585. int ret = GetASNHeader(input, ASN_OBJECT_ID, inOutIdx, len, maxIdx);
  4586. if (ret > 0) {
  4587. /* Only return 0 on success. */
  4588. ret = 0;
  4589. }
  4590. return ret;
  4591. }
  4592. /* Set the DER/BER encoding of the ASN.1 OBJECT ID header.
  4593. *
  4594. * When output is NULL, calculate the header length only.
  4595. *
  4596. * @param [in] len Length of OBJECT ID data in bytes.
  4597. * @param [out] output Buffer to write into.
  4598. * @return Number of bytes added to the buffer.
  4599. */
  4600. int SetObjectId(int len, byte* output)
  4601. {
  4602. int idx = 0;
  4603. if (output) {
  4604. /* Write out tag. */
  4605. output[idx] = ASN_OBJECT_ID;
  4606. }
  4607. /* Skip tag. */
  4608. idx += ASN_TAG_SZ;
  4609. /* Encode length - passing NULL for output will not encode. */
  4610. idx += SetLength(len, output ? output + idx : NULL);
  4611. /* Return index after header. */
  4612. return idx;
  4613. }
  4614. #ifdef ASN_DUMP_OID
  4615. /* Dump the OID information.
  4616. *
  4617. * Decode the OID too if function available.
  4618. *
  4619. * @param [in] oidData OID data from buffer.
  4620. * @param [in] oidSz Size of OID data in buffer.
  4621. * @param [in] oid OID id.
  4622. * @param [in] oidType Type of OID.
  4623. * @return 0 on success.
  4624. * @return BUFFER_E when not enough bytes for proper decode.
  4625. * (HAVE_OID_DECODING)
  4626. */
  4627. static int DumpOID(const byte* oidData, word32 oidSz, word32 oid,
  4628. word32 oidType)
  4629. {
  4630. int ret = 0;
  4631. word32 i;
  4632. /* support for dumping OID information */
  4633. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, oidSz, oid);
  4634. /* Dump bytes in decimal. */
  4635. for (i = 0; i < oidSz; i++) {
  4636. printf("%d, ", oidData[i]);
  4637. }
  4638. printf("\n");
  4639. /* Dump bytes in hexadecimal. */
  4640. for (i = 0; i < oidSz; i++) {
  4641. printf("%02x, ", oidData[i]);
  4642. }
  4643. printf("\n");
  4644. #ifdef HAVE_OID_DECODING
  4645. {
  4646. word16 decOid[16];
  4647. word32 decOidSz = sizeof(decOid);
  4648. /* Decode the OID into dotted form. */
  4649. ret = DecodeObjectId(oidData, oidSz, decOid, &decOidSz);
  4650. if (ret == 0) {
  4651. printf(" Decoded (Sz %d): ", decOidSz);
  4652. for (i=0; i<decOidSz; i++) {
  4653. printf("%d.", decOid[i]);
  4654. }
  4655. printf("\n");
  4656. }
  4657. else {
  4658. printf("DecodeObjectId failed: %d\n", ret);
  4659. }
  4660. }
  4661. #endif /* HAVE_OID_DECODING */
  4662. return ret;
  4663. }
  4664. #endif /* ASN_DUMP_OID */
  4665. /* Get the OID data and verify it is of the type specified when compiled in.
  4666. *
  4667. * @param [in] input Buffer holding OID.
  4668. * @param [in, out] inOutIdx On in, starting index of OID.
  4669. * On out, end of parsed OID.
  4670. * @param [out] oid OID id.
  4671. * @param [in] oidType Expected type of OID. Define NO_VERIFY_OID to
  4672. * not compile in check.
  4673. * @param [in] length Length of OID data in buffer.
  4674. * @return 0 on success.
  4675. * @return ASN_UNKNOWN_OID_E when OID is not recognized.
  4676. * @return BUFFER_E when not enough bytes for proper decode. (ASN_DUMP_OID and
  4677. * HAVE_OID_DECODING)
  4678. */
  4679. static int GetOID(const byte* input, word32* inOutIdx, word32* oid,
  4680. word32 oidType, int length)
  4681. {
  4682. int ret = 0;
  4683. word32 idx = *inOutIdx;
  4684. #ifndef NO_VERIFY_OID
  4685. word32 actualOidSz;
  4686. const byte* actualOid;
  4687. const byte* checkOid = NULL;
  4688. word32 checkOidSz;
  4689. #endif /* NO_VERIFY_OID */
  4690. (void)oidType;
  4691. *oid = 0;
  4692. #ifndef NO_VERIFY_OID
  4693. /* Keep references to OID data and length for check. */
  4694. actualOid = &input[idx];
  4695. actualOidSz = (word32)length;
  4696. #endif /* NO_VERIFY_OID */
  4697. /* Sum it up for now. */
  4698. while (length--) {
  4699. /* odd HC08 compiler behavior here when input[idx++] */
  4700. *oid += (word32)input[idx];
  4701. idx++;
  4702. }
  4703. /* Return the index after the OID data. */
  4704. *inOutIdx = idx;
  4705. #ifndef NO_VERIFY_OID
  4706. /* 'Ignore' type means we don't care which OID it is. */
  4707. if (oidType != oidIgnoreType) {
  4708. /* Get the OID data for the id-type. */
  4709. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  4710. #ifdef ASN_DUMP_OID
  4711. /* Dump out the data for debug. */
  4712. ret = DumpOID(actualOid, actualOidSz, *oid, oidType);
  4713. #endif
  4714. /* TODO: Want to fail when checkOid is NULL.
  4715. * Can't as too many situations where unknown OID is to be
  4716. * supported. Extra parameter for must not be NULL?
  4717. */
  4718. /* Check that the OID data matches what we found for the OID id. */
  4719. if ((ret == 0) && (checkOid != NULL) && ((checkOidSz != actualOidSz) ||
  4720. (XMEMCMP(actualOid, checkOid, checkOidSz) != 0))) {
  4721. WOLFSSL_MSG("OID Check Failed");
  4722. ret = ASN_UNKNOWN_OID_E;
  4723. }
  4724. }
  4725. #endif /* NO_VERIFY_OID */
  4726. return ret;
  4727. }
  4728. #ifdef WOLFSSL_ASN_TEMPLATE
  4729. /* ASN.1 template for an OBJECT_ID. */
  4730. static const ASNItem objectIdASN[] = {
  4731. { 0, ASN_OBJECT_ID, 0, 0, 0 }
  4732. };
  4733. /* Number of items in ASN.1 template for an OBJECT_ID. */
  4734. #define objectIdASN_Length (sizeof(objectIdASN) / sizeof(ASNItem))
  4735. #endif
  4736. /* Get the OID id/sum from the BER encoded OBJECT_ID.
  4737. *
  4738. * @param [in] input Buffer holding BER encoded data.
  4739. * @param [in, out] inOutIdx On in, start of OBJECT_ID.
  4740. * On out, start of ASN.1 item after OBJECT_ID.
  4741. * @param [out] oid Id of OID in OBJECT_ID data.
  4742. * @param [in] oidType Type of OID to expect.
  4743. * @param [in] maxIdx Maximum index of data in buffer.
  4744. * @return 0 on success.
  4745. * @return ASN_PARSE_E when encoding is invalid.
  4746. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  4747. */
  4748. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  4749. word32 oidType, word32 maxIdx)
  4750. {
  4751. #ifndef WOLFSSL_ASN_TEMPLATE
  4752. int ret, length;
  4753. WOLFSSL_ENTER("GetObjectId()");
  4754. ret = GetASNObjectId(input, inOutIdx, &length, maxIdx);
  4755. if (ret != 0)
  4756. return ret;
  4757. return GetOID(input, inOutIdx, oid, oidType, length);
  4758. #else
  4759. ASNGetData dataASN[objectIdASN_Length];
  4760. int ret;
  4761. WOLFSSL_ENTER("GetObjectId()");
  4762. /* Clear dynamic data and set OID type expected. */
  4763. XMEMSET(dataASN, 0, sizeof(dataASN));
  4764. GetASN_OID(&dataASN[0], oidType);
  4765. /* Decode OBJECT_ID. */
  4766. ret = GetASN_Items(objectIdASN, dataASN, objectIdASN_Length, 0, input,
  4767. inOutIdx, maxIdx);
  4768. if (ret == 0) {
  4769. /* Return the id/sum. */
  4770. *oid = dataASN[0].data.oid.sum;
  4771. }
  4772. return ret;
  4773. #endif /* WOLFSSL_ASN_TEMPLATE */
  4774. }
  4775. #ifndef WOLFSSL_ASN_TEMPLATE
  4776. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  4777. {
  4778. word32 idx = *inOutIdx;
  4779. int length;
  4780. int ret;
  4781. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  4782. if (ret != 0)
  4783. return ret;
  4784. idx += length;
  4785. *inOutIdx = idx;
  4786. return 0;
  4787. }
  4788. #endif
  4789. #ifdef WOLFSSL_ASN_TEMPLATE
  4790. /* ASN.1 template for an algorithm identifier. */
  4791. static const ASNItem algoIdASN[] = {
  4792. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  4793. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  4794. /* 2 */ { 1, ASN_TAG_NULL, 0, 0, 1 },
  4795. };
  4796. /* Number of items in ASN.1 template for an algorithm identifier. */
  4797. #define algoIdASN_Length (sizeof(algoIdASN) / sizeof(ASNItem))
  4798. #endif
  4799. /* Get the OID id/sum from the BER encoding of an algorithm identifier.
  4800. *
  4801. * NULL tag is skipped if present.
  4802. *
  4803. * @param [in] input Buffer holding BER encoded data.
  4804. * @param [in, out] inOutIdx On in, start of algorithm identifier.
  4805. * On out, start of ASN.1 item after algorithm id.
  4806. * @param [out] oid Id of OID in algorithm identifier data.
  4807. * @param [in] oidType Type of OID to expect.
  4808. * @param [in] maxIdx Maximum index of data in buffer.
  4809. * @return 0 on success.
  4810. * @return ASN_PARSE_E when encoding is invalid.
  4811. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  4812. */
  4813. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  4814. word32 oidType, word32 maxIdx)
  4815. {
  4816. #ifndef WOLFSSL_ASN_TEMPLATE
  4817. int length;
  4818. word32 idx = *inOutIdx;
  4819. int ret;
  4820. *oid = 0;
  4821. WOLFSSL_ENTER("GetAlgoId");
  4822. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  4823. return ASN_PARSE_E;
  4824. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  4825. return ASN_OBJECT_ID_E;
  4826. /* could have NULL tag and 0 terminator, but may not */
  4827. if (idx < maxIdx) {
  4828. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  4829. byte tag;
  4830. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  4831. if (tag == ASN_TAG_NULL) {
  4832. ret = GetASNNull(input, &idx, maxIdx);
  4833. if (ret != 0)
  4834. return ret;
  4835. }
  4836. }
  4837. }
  4838. *inOutIdx = idx;
  4839. return 0;
  4840. #else
  4841. ASNGetData dataASN[algoIdASN_Length];
  4842. int ret;
  4843. WOLFSSL_ENTER("GetAlgoId");
  4844. /* Clear dynamic data and set OID type expected. */
  4845. XMEMSET(dataASN, 0, sizeof(*dataASN) * algoIdASN_Length);
  4846. GetASN_OID(&dataASN[1], oidType);
  4847. /* Decode the algorithm identifier. */
  4848. ret = GetASN_Items(algoIdASN, dataASN, algoIdASN_Length, 0, input, inOutIdx,
  4849. maxIdx);
  4850. if (ret == 0) {
  4851. /* Return the OID id/sum. */
  4852. *oid = dataASN[1].data.oid.sum;
  4853. }
  4854. return ret;
  4855. #endif /* WOLFSSL_ASN_TEMPLATE */
  4856. }
  4857. #ifndef NO_RSA
  4858. #ifndef HAVE_USER_RSA
  4859. #if defined(WOLFSSL_ASN_TEMPLATE) || (!defined(NO_CERTS) && \
  4860. (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)))
  4861. /* Byte offset of numbers in RSA key. */
  4862. size_t rsaIntOffset[] = {
  4863. OFFSETOF(RsaKey, n),
  4864. OFFSETOF(RsaKey, e),
  4865. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  4866. OFFSETOF(RsaKey, d),
  4867. OFFSETOF(RsaKey, p),
  4868. OFFSETOF(RsaKey, q),
  4869. OFFSETOF(RsaKey, dP),
  4870. OFFSETOF(RsaKey, dQ),
  4871. OFFSETOF(RsaKey, u)
  4872. #endif
  4873. };
  4874. /* Get a number from the RSA key based on an index.
  4875. *
  4876. * Order: { n, e, d, p, q, dP, dQ, u }
  4877. *
  4878. * Caller must ensure index is not invalid!
  4879. *
  4880. * @param [in] key RSA key object.
  4881. * @param [in] idx Index of number.
  4882. * @return A pointer to an mp_int when valid index.
  4883. * @return NULL when invalid index.
  4884. */
  4885. static mp_int* GetRsaInt(RsaKey* key, byte idx)
  4886. {
  4887. /* Cast key to byte array to and use offset to get to mp_int field. */
  4888. return (mp_int*)(((byte*)key) + rsaIntOffset[idx]);
  4889. }
  4890. #endif
  4891. #ifdef WOLFSSL_ASN_TEMPLATE
  4892. /* ASN.1 template for an RSA private key.
  4893. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  4894. */
  4895. static const ASNItem rsaKeyASN[] = {
  4896. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  4897. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4898. /* 2 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4899. /* 3 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4900. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_KEY_GEN)
  4901. /* 4 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4902. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4903. /* 6 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4904. /* 7 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4905. /* 8 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4906. /* 9 */ { 1, ASN_INTEGER, 0, 0, 0 },
  4907. /* otherPrimeInfos OtherPrimeInfos OPTIONAL
  4908. * v2 - multiprime */
  4909. #endif
  4910. };
  4911. /* Number of items in ASN.1 template for an RSA private key. */
  4912. #define rsaKeyASN_Length (sizeof(rsaKeyASN) / sizeof(ASNItem))
  4913. #endif
  4914. /* Decode RSA private key.
  4915. *
  4916. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  4917. *
  4918. * Compiling with WOLFSSL_RSA_PUBLIC_ONLY will result in only the public fields
  4919. * being extracted.
  4920. *
  4921. * @param [in] input Buffer holding BER encoded data.
  4922. * @param [in, out] inOutIdx On in, start of RSA private key.
  4923. * On out, start of ASN.1 item after RSA private key.
  4924. * @param [in, out] key RSA key object.
  4925. * @param [in] inSz Number of bytes in buffer.
  4926. * @return 0 on success.
  4927. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  4928. * is invalid.
  4929. * @return BUFFER_E when data in buffer is too small.
  4930. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  4931. * non-zero length.
  4932. * @return MP_INIT_E when the unable to initialize an mp_int.
  4933. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  4934. */
  4935. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  4936. word32 inSz)
  4937. {
  4938. #ifndef WOLFSSL_ASN_TEMPLATE
  4939. int version, length;
  4940. word32 algId = 0;
  4941. if (inOutIdx == NULL || input == NULL || key == NULL) {
  4942. return BAD_FUNC_ARG;
  4943. }
  4944. /* if has pkcs8 header skip it */
  4945. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  4946. /* ignore error, did not have pkcs8 header */
  4947. }
  4948. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4949. return ASN_PARSE_E;
  4950. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  4951. return ASN_PARSE_E;
  4952. key->type = RSA_PRIVATE;
  4953. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  4954. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  4955. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  4956. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  4957. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  4958. GetInt(&key->q, input, inOutIdx, inSz) < 0
  4959. #else
  4960. SkipInt(input, inOutIdx, inSz) < 0 ||
  4961. SkipInt(input, inOutIdx, inSz) < 0 ||
  4962. SkipInt(input, inOutIdx, inSz) < 0
  4963. #endif
  4964. ) {
  4965. return ASN_RSA_KEY_E;
  4966. }
  4967. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  4968. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  4969. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  4970. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  4971. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  4972. #else
  4973. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  4974. SkipInt(input, inOutIdx, inSz) < 0 ||
  4975. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  4976. #endif
  4977. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  4978. if (wc_InitRsaHw(key) != 0) {
  4979. return BAD_STATE_E;
  4980. }
  4981. #endif
  4982. return 0;
  4983. #else
  4984. DECL_ASNGETDATA(dataASN, rsaKeyASN_Length);
  4985. int ret = 0;
  4986. byte i;
  4987. byte version;
  4988. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  4989. word32 algId = 0;
  4990. #endif
  4991. /* Check validity of parameters. */
  4992. if (inOutIdx == NULL || input == NULL || key == NULL) {
  4993. ret = BAD_FUNC_ARG;
  4994. }
  4995. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  4996. if (ret == 0) {
  4997. /* if has pkcs8 header skip it */
  4998. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  4999. /* ignore error, did not have pkcs8 header */
  5000. }
  5001. }
  5002. #endif
  5003. CALLOC_ASNGETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  5004. if (ret == 0) {
  5005. /* Register variable to hold version field. */
  5006. GetASN_Int8Bit(&dataASN[1], &version);
  5007. /* Setup data to store INTEGER data in mp_int's in RSA object. */
  5008. #if defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5009. /* Extract all public fields. */
  5010. for (i = 0; i < RSA_PUB_INTS; i++) {
  5011. GetASN_MP(&dataASN[2 + i], GetRsaInt(key, i));
  5012. }
  5013. /* Not extracting all data from BER encoding. */
  5014. #define RSA_ASN_COMPLETE 0
  5015. #else
  5016. /* Extract all private fields. */
  5017. for (i = 0; i < RSA_INTS; i++) {
  5018. GetASN_MP(&dataASN[2 + i], GetRsaInt(key, i));
  5019. }
  5020. /* Extracting all data from BER encoding. */
  5021. #define RSA_ASN_COMPLETE 1
  5022. #endif
  5023. /* Parse BER encoding for RSA private key. */
  5024. ret = GetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length,
  5025. RSA_ASN_COMPLETE, input, inOutIdx, inSz);
  5026. }
  5027. /* Check version: 0 - two prime, 1 - multi-prime
  5028. * Multi-prime has optional sequence after coefficient for extra primes.
  5029. * If extra primes, parsing will fail as not all the buffer was used.
  5030. */
  5031. if ((ret == 0) && (version > PKCS1v1)) {
  5032. ret = ASN_PARSE_E;
  5033. }
  5034. if (ret == 0) {
  5035. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  5036. /* RSA key object has all private key values. */
  5037. key->type = RSA_PRIVATE;
  5038. #else
  5039. /* RSA key object has all public key values. */
  5040. key->type = RSA_PUBLIC;
  5041. #endif
  5042. #ifdef WOLFSSL_XILINX_CRYPT
  5043. if (wc_InitRsaHw(key) != 0)
  5044. ret = BAD_STATE_E;
  5045. #endif
  5046. }
  5047. FREE_ASNGETDATA(dataASN, key->heap);
  5048. return ret;
  5049. #endif /* WOLFSSL_ASN_TEMPLATE */
  5050. }
  5051. #endif /* HAVE_USER_RSA */
  5052. #endif /* NO_RSA */
  5053. #ifdef WOLFSSL_ASN_TEMPLATE
  5054. /* ASN.1 template for a PKCS #8 key.
  5055. * Ignoring optional attributes and public key.
  5056. * PKCS #8: RFC 5958, 2 - PrivateKeyInfo
  5057. */
  5058. static const ASNItem pkcs8KeyASN[] = {
  5059. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  5060. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  5061. /* 2 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  5062. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  5063. /* 4 */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  5064. /* 5 */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  5065. /* 6 */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  5066. /* attributes [0] Attributes OPTIONAL */
  5067. /* [[2: publicKey [1] PublicKey OPTIONAL ]] */
  5068. };
  5069. /* Number of items in ASN.1 template for a PKCS #8 key. */
  5070. #define pkcs8KeyASN_Length (sizeof(pkcs8KeyASN) / sizeof(ASNItem))
  5071. #endif
  5072. /* Remove PKCS #8 header around an RSA, ECDSA, Ed25519, Ed448, or Falcon key.
  5073. *
  5074. * @param [in] input Buffer holding BER data.
  5075. * @param [in, out] inOutIdx On in, start of PKCS #8 encoding.
  5076. * On out, start of encoded key.
  5077. * @param [in] sz Size of data in buffer.
  5078. * @param [out] algId Key's algorithm id from PKCS #8 header.
  5079. * @return Length of key data on success.
  5080. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  5081. * is invalid.
  5082. * @return BUFFER_E when data in buffer is too small.
  5083. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  5084. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  5085. * non-zero length.
  5086. */
  5087. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  5088. word32* algId)
  5089. {
  5090. #ifndef WOLFSSL_ASN_TEMPLATE
  5091. word32 idx;
  5092. int version, length;
  5093. int ret;
  5094. byte tag;
  5095. if (input == NULL || inOutIdx == NULL)
  5096. return BAD_FUNC_ARG;
  5097. idx = *inOutIdx;
  5098. if (GetSequence(input, &idx, &length, sz) < 0)
  5099. return ASN_PARSE_E;
  5100. if (GetMyVersion(input, &idx, &version, sz) < 0)
  5101. return ASN_PARSE_E;
  5102. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  5103. return ASN_PARSE_E;
  5104. if (GetASNTag(input, &idx, &tag, sz) < 0)
  5105. return ASN_PARSE_E;
  5106. idx = idx - 1; /* reset idx after finding tag */
  5107. if (tag == ASN_OBJECT_ID) {
  5108. if (SkipObjectId(input, &idx, sz) < 0)
  5109. return ASN_PARSE_E;
  5110. }
  5111. ret = GetOctetString(input, &idx, &length, sz);
  5112. if (ret < 0) {
  5113. if (ret == BUFFER_E)
  5114. return ASN_PARSE_E;
  5115. /* Some private keys don't expect an octet string */
  5116. WOLFSSL_MSG("Couldn't find Octet string");
  5117. }
  5118. *inOutIdx = idx;
  5119. return length;
  5120. #else
  5121. DECL_ASNGETDATA(dataASN, pkcs8KeyASN_Length);
  5122. int ret = 0;
  5123. word32 oid = 9;
  5124. byte version;
  5125. word32 idx = *inOutIdx;
  5126. /* Check validity of parameters. */
  5127. if (input == NULL || inOutIdx == NULL) {
  5128. ret = BAD_FUNC_ARG;
  5129. }
  5130. CALLOC_ASNGETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  5131. if (ret == 0) {
  5132. /* Get version, check key type and curve type. */
  5133. GetASN_Int8Bit(&dataASN[1], &version);
  5134. GetASN_OID(&dataASN[3], oidKeyType);
  5135. GetASN_OID(&dataASN[4], oidCurveType);
  5136. /* Parse data. */
  5137. ret = GetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, 1, input,
  5138. &idx, sz);
  5139. }
  5140. if (ret == 0) {
  5141. /* Key type OID. */
  5142. oid = dataASN[3].data.oid.sum;
  5143. /* Version 1 includes an optional public key.
  5144. * If public key is included then the parsing will fail as it did not
  5145. * use all the data.
  5146. */
  5147. if (version > PKCS8v1) {
  5148. ret = ASN_PARSE_E;
  5149. }
  5150. }
  5151. if (ret == 0) {
  5152. switch (oid) {
  5153. #ifndef NO_RSA
  5154. case RSAk:
  5155. /* Must have NULL item but not OBJECT_ID item. */
  5156. if ((dataASN[5].tag == 0) ||
  5157. (dataASN[4].tag != 0)) {
  5158. ret = ASN_PARSE_E;
  5159. }
  5160. break;
  5161. #endif
  5162. #ifdef HAVE_ECC
  5163. case ECDSAk:
  5164. /* Must not have NULL item. */
  5165. if (dataASN[5].tag != 0) {
  5166. ret = ASN_PARSE_E;
  5167. }
  5168. break;
  5169. #endif
  5170. #ifdef HAVE_ED25519
  5171. case ED25519k:
  5172. /* Neither NULL item nor OBJECT_ID item allowed. */
  5173. if ((dataASN[5].tag != 0) ||
  5174. (dataASN[4].tag != 0)) {
  5175. ret = ASN_PARSE_E;
  5176. }
  5177. break;
  5178. #endif
  5179. #ifdef HAVE_CURVE25519
  5180. case X25519k:
  5181. /* Neither NULL item nor OBJECT_ID item allowed. */
  5182. if ((dataASN[5].tag != 0) ||
  5183. (dataASN[4].tag != 0)) {
  5184. ret = ASN_PARSE_E;
  5185. }
  5186. break;
  5187. #endif
  5188. #ifdef HAVE_ED448
  5189. case ED448k:
  5190. /* Neither NULL item nor OBJECT_ID item allowed. */
  5191. if ((dataASN[5].tag != 0) ||
  5192. (dataASN[4].tag != 0)) {
  5193. ret = ASN_PARSE_E;
  5194. }
  5195. break;
  5196. #endif
  5197. #ifdef HAVE_CURVE448
  5198. case X448k:
  5199. /* Neither NULL item nor OBJECT_ID item allowed. */
  5200. if ((dataASN[5].tag != 0) ||
  5201. (dataASN[4].tag != 0)) {
  5202. ret = ASN_PARSE_E;
  5203. }
  5204. break;
  5205. #endif
  5206. /* DSAk not supported. */
  5207. /* Ignore OID lookup failures. */
  5208. default:
  5209. break;
  5210. }
  5211. }
  5212. if (ret == 0) {
  5213. /* Return algorithm id of internal key. */
  5214. *algId = oid;
  5215. /* Return index to start of internal key. */
  5216. *inOutIdx = GetASNItem_DataIdx(dataASN[6], input);
  5217. /* Return value is length of internal key. */
  5218. ret = dataASN[6].data.ref.length;
  5219. }
  5220. FREE_ASNGETDATA(dataASN, NULL);
  5221. return ret;
  5222. #endif
  5223. }
  5224. /* TODO: test case */
  5225. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  5226. {
  5227. word32 oid;
  5228. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  5229. }
  5230. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5231. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  5232. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  5233. {
  5234. word32 inOutIdx = 0;
  5235. int length;
  5236. if (input == NULL)
  5237. return BAD_FUNC_ARG;
  5238. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  5239. if (length < 0)
  5240. return length;
  5241. if (length + inOutIdx > sz)
  5242. return BUFFER_E;
  5243. XMEMMOVE(input, input + inOutIdx, length);
  5244. return length;
  5245. }
  5246. int ToTraditional(byte* input, word32 sz)
  5247. {
  5248. word32 oid;
  5249. return ToTraditional_ex(input, sz, &oid);
  5250. }
  5251. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  5252. #if defined(HAVE_PKCS8) && !defined(NO_CERTS)
  5253. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  5254. {
  5255. int length;
  5256. word32 algId;
  5257. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  5258. return BAD_FUNC_ARG;
  5259. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  5260. return length;
  5261. }
  5262. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  5263. int algoID, const byte* curveOID, word32 oidSz)
  5264. {
  5265. #ifndef WOLFSSL_ASN_TEMPLATE
  5266. word32 keyIdx = 0;
  5267. word32 tmpSz = 0;
  5268. word32 sz;
  5269. word32 tmpAlgId = 0;
  5270. /* If out is NULL then return the max size needed
  5271. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  5272. if (out == NULL && outSz != NULL) {
  5273. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  5274. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  5275. if (curveOID != NULL)
  5276. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  5277. WOLFSSL_MSG("Checking size of PKCS8");
  5278. return LENGTH_ONLY_E;
  5279. }
  5280. WOLFSSL_ENTER("wc_CreatePKCS8Key()");
  5281. if (key == NULL || out == NULL || outSz == NULL) {
  5282. return BAD_FUNC_ARG;
  5283. }
  5284. /* check the buffer has enough room for largest possible size */
  5285. if (curveOID != NULL) {
  5286. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  5287. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  5288. return BUFFER_E;
  5289. }
  5290. else {
  5291. oidSz = 0; /* with no curveOID oid size must be 0 */
  5292. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  5293. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  5294. return BUFFER_E;
  5295. }
  5296. /* sanity check: make sure the key doesn't already have a PKCS 8 header */
  5297. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  5298. (void)tmpAlgId;
  5299. return ASN_PARSE_E;
  5300. }
  5301. /* PrivateKeyInfo ::= SEQUENCE */
  5302. keyIdx = MAX_SEQ_SZ; /* save room for sequence */
  5303. /* version Version
  5304. * no header information just INTEGER */
  5305. sz = SetMyVersion(PKCS8v0, out + keyIdx, 0);
  5306. tmpSz += sz; keyIdx += sz;
  5307. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  5308. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  5309. if (curveOID != NULL && oidSz > 0) {
  5310. byte buf[MAX_LENGTH_SZ];
  5311. sz = SetLength(oidSz, buf);
  5312. sz += 1; /* plus one for ASN object id */
  5313. }
  5314. sz = SetAlgoID(algoID, out + keyIdx, oidKeyType, oidSz + sz);
  5315. tmpSz += sz; keyIdx += sz;
  5316. /* privateKey PrivateKey *
  5317. * pkcs8 ecc uses slightly different format. Places curve oid in
  5318. * buffer */
  5319. if (curveOID != NULL && oidSz > 0) {
  5320. sz = SetObjectId(oidSz, out + keyIdx);
  5321. keyIdx += sz; tmpSz += sz;
  5322. XMEMCPY(out + keyIdx, curveOID, oidSz);
  5323. keyIdx += oidSz; tmpSz += oidSz;
  5324. }
  5325. sz = SetOctetString(keySz, out + keyIdx);
  5326. keyIdx += sz; tmpSz += sz;
  5327. XMEMCPY(out + keyIdx, key, keySz);
  5328. tmpSz += keySz;
  5329. /* attributes optional
  5330. * No attributes currently added */
  5331. /* rewind and add sequence */
  5332. sz = SetSequence(tmpSz, out);
  5333. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  5334. *outSz = tmpSz + sz;
  5335. return tmpSz + sz;
  5336. #else
  5337. DECL_ASNSETDATA(dataASN, pkcs8KeyASN_Length);
  5338. int sz;
  5339. int ret = 0;
  5340. word32 keyIdx = 0;
  5341. word32 tmpAlgId = 0;
  5342. WOLFSSL_ENTER("wc_CreatePKCS8Key()");
  5343. /* Check validity of parameters. */
  5344. if (out == NULL && outSz != NULL) {
  5345. }
  5346. else if (key == NULL || out == NULL || outSz == NULL) {
  5347. ret = BAD_FUNC_ARG;
  5348. }
  5349. /* Sanity check: make sure key doesn't have PKCS #8 header. */
  5350. if (ToTraditionalInline_ex(key, &keyIdx, keySz, &tmpAlgId) >= 0) {
  5351. (void)tmpAlgId;
  5352. ret = ASN_PARSE_E;
  5353. }
  5354. CALLOC_ASNSETDATA(dataASN, pkcs8KeyASN_Length, ret, NULL);
  5355. if (ret == 0) {
  5356. /* Only support default PKCS #8 format - v0. */
  5357. SetASN_Int8Bit(&dataASN[1], PKCS8v0);
  5358. /* Set key OID that corresponds to key data. */
  5359. SetASN_OID(&dataASN[3], algoID, oidKeyType);
  5360. if (curveOID != NULL && oidSz > 0) {
  5361. /* ECC key and curveOID set to write. */
  5362. SetASN_Buffer(&dataASN[4], curveOID, oidSz);
  5363. }
  5364. else {
  5365. /* EC curve OID to encode. */
  5366. dataASN[4].noOut = 1;
  5367. }
  5368. /* Only RSA keys have NULL tagged item after OID. */
  5369. dataASN[5].noOut = (algoID != RSAk);
  5370. /* Set key data to encode. */
  5371. SetASN_Buffer(&dataASN[6], key, keySz);
  5372. /* Get the size of the DER encoding. */
  5373. ret = SizeASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, &sz);
  5374. }
  5375. if (ret == 0) {
  5376. /* Always return the calculated size. */
  5377. *outSz = sz;
  5378. }
  5379. /* Check for buffer to encoded into. */
  5380. if ((ret == 0) && (out == NULL)) {
  5381. WOLFSSL_MSG("Checking size of PKCS8");
  5382. ret = LENGTH_ONLY_E;
  5383. }
  5384. if (ret == 0) {
  5385. /* Encode PKCS #8 key into buffer. */
  5386. SetASN_Items(pkcs8KeyASN, dataASN, pkcs8KeyASN_Length, out);
  5387. ret = sz;
  5388. }
  5389. FREE_ASNSETDATA(dataASN, NULL);
  5390. return ret;
  5391. #endif /* WOLFSSL_ASN_TEMPLATE */
  5392. }
  5393. #endif /* HAVE_PKCS8 && !NO_CERTS */
  5394. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  5395. /* check that the private key is a pair for the public key
  5396. * return 1 (true) on match
  5397. * return 0 or negative value on failure/error
  5398. *
  5399. * privKey : buffer holding DER format private key
  5400. * privKeySz : size of private key buffer
  5401. * pubKey : buffer holding DER format public key
  5402. * pubKeySz : size of public key buffer
  5403. * ks : type of key */
  5404. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  5405. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  5406. {
  5407. int ret;
  5408. (void)privKeySz;
  5409. (void)pubKeySz;
  5410. (void)ks;
  5411. if (privKey == NULL || pubKey == NULL) {
  5412. return BAD_FUNC_ARG;
  5413. }
  5414. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  5415. /* test if RSA key */
  5416. if (ks == RSAk) {
  5417. #ifdef WOLFSSL_SMALL_STACK
  5418. RsaKey* a;
  5419. RsaKey* b = NULL;
  5420. #else
  5421. RsaKey a[1], b[1];
  5422. #endif
  5423. word32 keyIdx = 0;
  5424. #ifdef WOLFSSL_SMALL_STACK
  5425. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  5426. if (a == NULL)
  5427. return MEMORY_E;
  5428. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  5429. if (b == NULL) {
  5430. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  5431. return MEMORY_E;
  5432. }
  5433. #endif
  5434. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  5435. #ifdef WOLFSSL_SMALL_STACK
  5436. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  5437. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  5438. #endif
  5439. return ret;
  5440. }
  5441. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  5442. wc_FreeRsaKey(a);
  5443. #ifdef WOLFSSL_SMALL_STACK
  5444. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  5445. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  5446. #endif
  5447. return ret;
  5448. }
  5449. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  5450. WOLFSSL_MSG("Checking RSA key pair");
  5451. keyIdx = 0; /* reset to 0 for parsing public key */
  5452. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  5453. pubKeySz)) == 0) {
  5454. /* limit for user RSA crypto because of RsaKey
  5455. * dereference. */
  5456. #if defined(HAVE_USER_RSA)
  5457. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  5458. ret = 1; /* return first RSA cert as match */
  5459. #else
  5460. /* both keys extracted successfully now check n and e
  5461. * values are the same. This is dereferencing RsaKey */
  5462. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  5463. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  5464. ret = MP_CMP_E;
  5465. }
  5466. else
  5467. ret = 1;
  5468. #endif
  5469. }
  5470. }
  5471. wc_FreeRsaKey(b);
  5472. wc_FreeRsaKey(a);
  5473. #ifdef WOLFSSL_SMALL_STACK
  5474. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  5475. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  5476. #endif
  5477. }
  5478. else
  5479. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  5480. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  5481. if (ks == ECDSAk) {
  5482. #ifdef WOLFSSL_SMALL_STACK
  5483. ecc_key* key_pair;
  5484. byte* privDer;
  5485. #else
  5486. ecc_key key_pair[1];
  5487. byte privDer[MAX_ECC_BYTES];
  5488. #endif
  5489. word32 privSz = MAX_ECC_BYTES;
  5490. word32 keyIdx = 0;
  5491. #ifdef WOLFSSL_SMALL_STACK
  5492. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  5493. if (key_pair == NULL)
  5494. return MEMORY_E;
  5495. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5496. if (privDer == NULL) {
  5497. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  5498. return MEMORY_E;
  5499. }
  5500. #endif
  5501. if ((ret = wc_ecc_init(key_pair)) < 0) {
  5502. #ifdef WOLFSSL_SMALL_STACK
  5503. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5504. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  5505. #endif
  5506. return ret;
  5507. }
  5508. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  5509. privKeySz)) == 0) {
  5510. WOLFSSL_MSG("Checking ECC key pair");
  5511. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  5512. == 0) {
  5513. wc_ecc_free(key_pair);
  5514. ret = wc_ecc_init(key_pair);
  5515. if (ret == 0) {
  5516. ret = wc_ecc_import_private_key(privDer,
  5517. privSz, pubKey,
  5518. pubKeySz, key_pair);
  5519. }
  5520. /* public and private extracted successfully now check if is
  5521. * a pair and also do sanity checks on key. wc_ecc_check_key
  5522. * checks that private * base generator equals pubkey */
  5523. if (ret == 0) {
  5524. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  5525. ret = 1;
  5526. }
  5527. }
  5528. ForceZero(privDer, privSz);
  5529. }
  5530. }
  5531. wc_ecc_free(key_pair);
  5532. #ifdef WOLFSSL_SMALL_STACK
  5533. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5534. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  5535. #endif
  5536. }
  5537. else
  5538. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  5539. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  5540. if (ks == ED25519k) {
  5541. #ifdef WOLFSSL_SMALL_STACK
  5542. ed25519_key* key_pair;
  5543. #else
  5544. ed25519_key key_pair[1];
  5545. #endif
  5546. word32 keyIdx = 0;
  5547. #ifdef WOLFSSL_SMALL_STACK
  5548. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  5549. DYNAMIC_TYPE_ED25519);
  5550. if (key_pair == NULL)
  5551. return MEMORY_E;
  5552. #endif
  5553. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  5554. #ifdef WOLFSSL_SMALL_STACK
  5555. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  5556. #endif
  5557. return ret;
  5558. }
  5559. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  5560. privKeySz)) == 0) {
  5561. WOLFSSL_MSG("Checking ED25519 key pair");
  5562. keyIdx = 0;
  5563. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  5564. key_pair)) == 0) {
  5565. /* public and private extracted successfully no check if is
  5566. * a pair and also do sanity checks on key. wc_ecc_check_key
  5567. * checks that private * base generator equals pubkey */
  5568. if ((ret = wc_ed25519_check_key(key_pair)) == 0)
  5569. ret = 1;
  5570. }
  5571. }
  5572. wc_ed25519_free(key_pair);
  5573. #ifdef WOLFSSL_SMALL_STACK
  5574. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  5575. #endif
  5576. }
  5577. else
  5578. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  5579. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  5580. if (ks == ED448k) {
  5581. #ifdef WOLFSSL_SMALL_STACK
  5582. ed448_key* key_pair = NULL;
  5583. #else
  5584. ed448_key key_pair[1];
  5585. #endif
  5586. word32 keyIdx = 0;
  5587. #ifdef WOLFSSL_SMALL_STACK
  5588. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  5589. DYNAMIC_TYPE_ED448);
  5590. if (key_pair == NULL)
  5591. return MEMORY_E;
  5592. #endif
  5593. if ((ret = wc_ed448_init(key_pair)) < 0) {
  5594. #ifdef WOLFSSL_SMALL_STACK
  5595. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  5596. #endif
  5597. return ret;
  5598. }
  5599. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  5600. privKeySz)) == 0) {
  5601. WOLFSSL_MSG("Checking ED448 key pair");
  5602. keyIdx = 0;
  5603. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  5604. key_pair)) == 0) {
  5605. /* public and private extracted successfully no check if is
  5606. * a pair and also do sanity checks on key. wc_ecc_check_key
  5607. * checks that private * base generator equals pubkey */
  5608. if ((ret = wc_ed448_check_key(key_pair)) == 0)
  5609. ret = 1;
  5610. }
  5611. }
  5612. wc_ed448_free(key_pair);
  5613. #ifdef WOLFSSL_SMALL_STACK
  5614. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  5615. #endif
  5616. }
  5617. else
  5618. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  5619. #if defined(HAVE_LIBOQS)
  5620. if ((ks == FALCON_LEVEL1k) || (ks == FALCON_LEVEL5k)) {
  5621. #ifdef WOLFSSL_SMALL_STACK
  5622. falcon_key* key_pair = NULL;
  5623. #else
  5624. falcon_key key_pair[1];
  5625. #endif
  5626. word32 keyIdx = 0;
  5627. #ifdef WOLFSSL_SMALL_STACK
  5628. key_pair = (falcon_key*)XMALLOC(sizeof(falcon_key), NULL,
  5629. DYNAMIC_TYPE_FALCON);
  5630. if (key_pair == NULL)
  5631. return MEMORY_E;
  5632. #endif
  5633. ret = wc_falcon_init(key_pair);
  5634. if (ret < 0) {
  5635. #ifdef WOLFSSL_SMALL_STACK
  5636. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  5637. #endif
  5638. return ret;
  5639. }
  5640. if (ks == FALCON_LEVEL1k) {
  5641. ret = wc_falcon_set_level(key_pair, 1);
  5642. }
  5643. else if (ks == FALCON_LEVEL5k) {
  5644. ret = wc_falcon_set_level(key_pair, 5);
  5645. }
  5646. if (ret < 0) {
  5647. #ifdef WOLFSSL_SMALL_STACK
  5648. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  5649. #endif
  5650. return ret;
  5651. }
  5652. if ((ret = wc_Falcon_PrivateKeyDecode(privKey, &keyIdx, key_pair,
  5653. privKeySz)) == 0) {
  5654. WOLFSSL_MSG("Checking Falcon_ key pair");
  5655. keyIdx = 0;
  5656. if ((ret = wc_falcon_import_public(pubKey, pubKeySz,
  5657. key_pair)) == 0) {
  5658. /* public and private extracted successfully no check if is
  5659. * a pair and also do sanity checks on key. wc_ecc_check_key
  5660. * checks that private * base generator equals pubkey */
  5661. if ((ret = wc_falcon_check_key(key_pair)) == 0)
  5662. ret = 1;
  5663. }
  5664. }
  5665. wc_falcon_free(key_pair);
  5666. #ifdef WOLFSSL_SMALL_STACK
  5667. XFREE(key_pair, NULL, DYNAMIC_TYPE_FALCON);
  5668. #endif
  5669. }
  5670. else
  5671. #endif /* HAVE_LIBOQS */
  5672. {
  5673. ret = 0;
  5674. }
  5675. (void)ks;
  5676. return ret;
  5677. }
  5678. /* check that the private key is a pair for the public key in certificate
  5679. * return 1 (true) on match
  5680. * return 0 or negative value on failure/error
  5681. *
  5682. * key : buffer holding DER format key
  5683. * keySz : size of key buffer
  5684. * der : a initialized and parsed DecodedCert holding a certificate */
  5685. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  5686. {
  5687. if (key == NULL || der == NULL) {
  5688. return BAD_FUNC_ARG;
  5689. }
  5690. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  5691. der->pubKeySize, (enum Key_Sum) der->keyOID);
  5692. }
  5693. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  5694. #ifndef NO_PWDBASED
  5695. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5696. /* Check the PBE algorithm is supported and return wolfSSL id, version and block
  5697. * size of encryption algorithm.
  5698. *
  5699. * When PBES2, version is PKCS5v2, CheckAlgoV2() must be called to get id and
  5700. * blockSz based on encryption algorithm.
  5701. *
  5702. * @param [in] first First byte of OID to use in check.
  5703. * @param [in] second Second byte of OID to use in check.
  5704. * @param [out] id wolfSSL id for PBE algorithm.
  5705. * @param [out] version Version of PBE OID:
  5706. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  5707. * @param [out] blockSz Block size of encryption algorithm.
  5708. * @return 0 on success.
  5709. * @return ALGO_ID_E when OID not supported.
  5710. * @return ASN_INPUT_E when first byte is invalid.
  5711. */
  5712. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  5713. {
  5714. int ret = 0;
  5715. (void)id;
  5716. (void)version;
  5717. (void)blockSz;
  5718. /* pkcs-12 1 = pkcs-12PbeIds */
  5719. if (first == 1) {
  5720. /* PKCS #12: Appendix C */
  5721. switch (second) {
  5722. #if !defined(NO_SHA)
  5723. #ifndef NO_RC4
  5724. case PBE_SHA1_RC4_128:
  5725. *id = PBE_SHA1_RC4_128;
  5726. *version = PKCS12v1;
  5727. if (blockSz != NULL) {
  5728. *blockSz = 1;
  5729. }
  5730. break;
  5731. #endif
  5732. #ifndef NO_DES3
  5733. case PBE_SHA1_DES3:
  5734. *id = PBE_SHA1_DES3;
  5735. *version = PKCS12v1;
  5736. if (blockSz != NULL) {
  5737. *blockSz = DES_BLOCK_SIZE;
  5738. }
  5739. break;
  5740. #endif
  5741. #ifdef WC_RC2
  5742. case PBE_SHA1_40RC2_CBC:
  5743. *id = PBE_SHA1_40RC2_CBC;
  5744. *version = PKCS12v1;
  5745. if (blockSz != NULL) {
  5746. *blockSz = RC2_BLOCK_SIZE;
  5747. }
  5748. break;
  5749. #endif
  5750. #endif /* !NO_SHA */
  5751. default:
  5752. ret = ALGO_ID_E;
  5753. break;
  5754. }
  5755. }
  5756. else if (first != PKCS5) {
  5757. /* Bad OID. */
  5758. ret = ASN_INPUT_E;
  5759. }
  5760. /* PKCS #5 PBES2: Appendix A.4
  5761. * pkcs-5 13 = id-PBES2 */
  5762. else if (second == PBES2) {
  5763. *version = PKCS5v2;
  5764. /* Id and block size come from CheckAlgoV2() */
  5765. }
  5766. else {
  5767. /* PKCS #5 PBES1: Appendix A.3 */
  5768. /* see RFC 2898 for ids */
  5769. switch (second) {
  5770. #ifndef NO_DES3
  5771. #ifndef NO_MD5
  5772. case PBES1_MD5_DES:
  5773. *id = PBE_MD5_DES;
  5774. *version = PKCS5;
  5775. if (blockSz != NULL) {
  5776. *blockSz = DES_BLOCK_SIZE;
  5777. }
  5778. break;
  5779. #endif
  5780. #ifndef NO_SHA
  5781. case PBES1_SHA1_DES:
  5782. *id = PBE_SHA1_DES;
  5783. *version = PKCS5;
  5784. if (blockSz != NULL) {
  5785. *blockSz = DES_BLOCK_SIZE;
  5786. }
  5787. break;
  5788. #endif
  5789. #endif /* !NO_DES3 */
  5790. default:
  5791. ret = ALGO_ID_E;
  5792. break;
  5793. }
  5794. }
  5795. /* Return error code. */
  5796. return ret;
  5797. }
  5798. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  5799. #ifdef HAVE_PKCS8
  5800. /* Check the encryption algorithm with PBES2 is supported and return block size
  5801. * and wolfSSL id for the PBE.
  5802. *
  5803. * @param [in] oid Encryption algorithm OID id.
  5804. * @param [out] id wolfSSL id for PBE algorithm.
  5805. * @param [out] version Version of PBE OID:
  5806. * PKCS12v1 (PBE), PKCS5 (PBES1), PKCS5v2 (PBES2).
  5807. * @return 0 on success.
  5808. * @return ALGO_ID_E when encryption algorithm is not supported with PBES2.
  5809. */
  5810. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  5811. {
  5812. int ret = 0;
  5813. (void)id;
  5814. (void)blockSz;
  5815. switch (oid) {
  5816. #if !defined(NO_DES3) && !defined(NO_SHA)
  5817. case DESb:
  5818. *id = PBE_SHA1_DES;
  5819. if (blockSz != NULL) {
  5820. *blockSz = DES_BLOCK_SIZE;
  5821. }
  5822. break;
  5823. case DES3b:
  5824. *id = PBE_SHA1_DES3;
  5825. if (blockSz != NULL) {
  5826. *blockSz = DES_BLOCK_SIZE;
  5827. }
  5828. break;
  5829. #endif
  5830. #ifdef WOLFSSL_AES_256
  5831. case AES256CBCb:
  5832. *id = PBE_AES256_CBC;
  5833. if (blockSz != NULL) {
  5834. *blockSz = AES_BLOCK_SIZE;
  5835. }
  5836. break;
  5837. #endif
  5838. #ifdef WOLFSSL_AES_128
  5839. case AES128CBCb:
  5840. *id = PBE_AES128_CBC;
  5841. if (blockSz != NULL) {
  5842. *blockSz = AES_BLOCK_SIZE;
  5843. }
  5844. break;
  5845. #endif
  5846. default:
  5847. WOLFSSL_MSG("No PKCS v2 algo found");
  5848. ret = ALGO_ID_E;
  5849. break;
  5850. }
  5851. /* Return error code. */
  5852. return ret;
  5853. }
  5854. #endif /* HAVE_PKCS8 */
  5855. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5856. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  5857. int* algoID, void* heap)
  5858. {
  5859. word32 tmpIdx = 0;
  5860. if (key == NULL || algoID == NULL)
  5861. return BAD_FUNC_ARG;
  5862. *algoID = 0;
  5863. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  5864. {
  5865. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5866. if (rsa == NULL)
  5867. return MEMORY_E;
  5868. wc_InitRsaKey(rsa, heap);
  5869. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  5870. *algoID = RSAk;
  5871. }
  5872. else {
  5873. WOLFSSL_MSG("Not RSA DER key");
  5874. }
  5875. wc_FreeRsaKey(rsa);
  5876. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5877. }
  5878. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  5879. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  5880. if (*algoID == 0) {
  5881. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5882. if (ecc == NULL)
  5883. return MEMORY_E;
  5884. tmpIdx = 0;
  5885. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  5886. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  5887. *algoID = ECDSAk;
  5888. /* now find oid */
  5889. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  5890. WOLFSSL_MSG("Error getting ECC curve OID");
  5891. wc_ecc_free(ecc);
  5892. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5893. return BAD_FUNC_ARG;
  5894. }
  5895. }
  5896. else {
  5897. WOLFSSL_MSG("Not ECC DER key either");
  5898. }
  5899. wc_ecc_free(ecc);
  5900. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5901. }
  5902. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  5903. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  5904. if (*algoID == 0) {
  5905. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap,
  5906. DYNAMIC_TYPE_TMP_BUFFER);
  5907. if (ed25519 == NULL)
  5908. return MEMORY_E;
  5909. tmpIdx = 0;
  5910. if (wc_ed25519_init_ex(ed25519, heap, INVALID_DEVID) == 0) {
  5911. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  5912. *algoID = ED25519k;
  5913. }
  5914. else {
  5915. WOLFSSL_MSG("Not ED25519 DER key");
  5916. }
  5917. wc_ed25519_free(ed25519);
  5918. }
  5919. else {
  5920. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  5921. }
  5922. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5923. }
  5924. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT && !NO_ASN_CRYPT */
  5925. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT) && !defined(NO_ASN_CRYPT)
  5926. if (*algoID == 0) {
  5927. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap,
  5928. DYNAMIC_TYPE_TMP_BUFFER);
  5929. if (ed448 == NULL)
  5930. return MEMORY_E;
  5931. tmpIdx = 0;
  5932. if (wc_ed448_init(ed448) == 0) {
  5933. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  5934. *algoID = ED448k;
  5935. }
  5936. else {
  5937. WOLFSSL_MSG("Not ED448 DER key");
  5938. }
  5939. wc_ed448_free(ed448);
  5940. }
  5941. else {
  5942. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  5943. }
  5944. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5945. }
  5946. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT && !NO_ASN_CRYPT */
  5947. #if defined(HAVE_LIBOQS)
  5948. if (*algoID == 0) {
  5949. falcon_key *falcon = (falcon_key *)XMALLOC(sizeof(*falcon), heap,
  5950. DYNAMIC_TYPE_TMP_BUFFER);
  5951. if (falcon == NULL)
  5952. return MEMORY_E;
  5953. if (wc_falcon_init(falcon) != 0) {
  5954. tmpIdx = 0;
  5955. if (wc_falcon_set_level(falcon, 1) == 0) {
  5956. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  5957. == 0) {
  5958. *algoID = FALCON_LEVEL1k;
  5959. }
  5960. else {
  5961. WOLFSSL_MSG("Not Falcon Level 1 DER key");
  5962. }
  5963. }
  5964. else if (wc_falcon_set_level(falcon, 5) == 0) {
  5965. if (wc_Falcon_PrivateKeyDecode(key, &tmpIdx, falcon, keySz)
  5966. == 0) {
  5967. *algoID = FALCON_LEVEL5k;
  5968. }
  5969. else {
  5970. WOLFSSL_MSG("Not Falcon Level 5 DER key");
  5971. }
  5972. }
  5973. else {
  5974. WOLFSSL_MSG("GetKeyOID falcon initialization failed");
  5975. }
  5976. wc_falcon_free(falcon);
  5977. }
  5978. XFREE(falcon, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5979. }
  5980. #endif /* HAVE_LIBOQS */
  5981. /* if flag is not set then this is not a key that we understand. */
  5982. if (*algoID == 0) {
  5983. WOLFSSL_MSG("Bad key DER or compile options");
  5984. return BAD_FUNC_ARG;
  5985. }
  5986. (void)tmpIdx;
  5987. (void)curveOID;
  5988. (void)oidSz;
  5989. (void)keySz;
  5990. (void)heap;
  5991. return 1;
  5992. }
  5993. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  5994. #ifdef WOLFSSL_ASN_TEMPLATE
  5995. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  5996. /* ASN.1 template for PBES2 parameters.
  5997. * PKCS #5: RFC 8018, A.4 - PBES2-params without outer SEQUENCE
  5998. * A.2 - PBKDF2-params
  5999. * B.2 - Encryption schemes
  6000. */
  6001. static const ASNItem pbes2ParamsASN[] = {
  6002. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6003. /* PBKDF2 */
  6004. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  6005. /* 2 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6006. /* Salt */
  6007. /* 3 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  6008. /* Iteration count */
  6009. /* 4 */ { 2, ASN_INTEGER, 0, 0, 0 },
  6010. /* Key length */
  6011. /* 5 */ { 2, ASN_INTEGER, 0, 0, 1 },
  6012. /* PRF - default is HMAC-SHA1 */
  6013. /* 6 */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  6014. /* 7 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  6015. /* 8 */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  6016. /* 9 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6017. /* Encryption algorithm */
  6018. /* 10 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  6019. /* IV for CBC */
  6020. /* 11 */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6021. };
  6022. /* Number of items in ASN.1 template for PBES2 parameters. */
  6023. #define pbes2ParamsASN_Length (sizeof(pbes2ParamsASN) / sizeof(ASNItem))
  6024. /* ASN.1 template for PBES1 parameters.
  6025. * PKCS #5: RFC 8018, A.3. - PBEParameter without outer SEQUENCE
  6026. */
  6027. static const ASNItem pbes1ParamsASN[] = {
  6028. /* Salt */
  6029. /* 0 */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  6030. /* Iteration count */
  6031. /* 1 */ { 0, ASN_INTEGER, 0, 0, 0 },
  6032. };
  6033. /* Number of items in ASN.1 template for PBES1 parameters. */
  6034. #define pbes1ParamsASN_Length (sizeof(pbes1ParamsASN) / sizeof(ASNItem))
  6035. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  6036. #endif /* WOLFSSL_ASN_TEMPLATE */
  6037. #ifdef HAVE_PKCS8
  6038. /*
  6039. * Equivalent to calling TraditionalEnc with the same parameters but with
  6040. * encAlgId set to 0. This function must be kept alive because it's sometimes
  6041. * part of the API (WOLFSSL_ASN_API).
  6042. */
  6043. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  6044. const char* password, int passwordSz, int vPKCS, int vAlgo,
  6045. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  6046. {
  6047. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz,
  6048. vPKCS, vAlgo, 0, salt, saltSz, itt, rng, heap);
  6049. }
  6050. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  6051. int *blkSz)
  6052. {
  6053. int ret = 0;
  6054. switch (encAlgId) {
  6055. #if !defined(NO_DES3) && !defined(NO_SHA)
  6056. case DESb:
  6057. *len = sizeof(blkDesCbcOid);
  6058. *oid = blkDesCbcOid;
  6059. *id = PBE_SHA1_DES;
  6060. *blkSz = 8;
  6061. break;
  6062. case DES3b:
  6063. *len = sizeof(blkDes3CbcOid);
  6064. *oid = blkDes3CbcOid;
  6065. *id = PBE_SHA1_DES3;
  6066. *blkSz = 8;
  6067. break;
  6068. #endif
  6069. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  6070. case AES256CBCb:
  6071. *len = sizeof(blkAes256CbcOid);
  6072. *oid = blkAes256CbcOid;
  6073. *id = PBE_AES256_CBC;
  6074. *blkSz = 16;
  6075. break;
  6076. #endif
  6077. default:
  6078. (void)len;
  6079. (void)oid;
  6080. (void)id;
  6081. (void)blkSz;
  6082. ret = ALGO_ID_E;
  6083. }
  6084. return ret;
  6085. }
  6086. int wc_EncryptPKCS8Key(byte* key, word32 keySz, byte* out, word32* outSz,
  6087. const char* password, int passwordSz, int vPKCS, int pbeOid,
  6088. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  6089. void* heap)
  6090. {
  6091. #ifdef WOLFSSL_SMALL_STACK
  6092. byte* saltTmp = NULL;
  6093. #else
  6094. byte saltTmp[MAX_SALT_SIZE];
  6095. #endif
  6096. int genSalt = 0;
  6097. int ret = 0;
  6098. int version = 0;
  6099. int pbeId = 0;
  6100. int blockSz = 0;
  6101. const byte* encOid = NULL;
  6102. int encOidSz = 0;
  6103. word32 padSz = 0;
  6104. word32 innerLen = 0;
  6105. word32 outerLen = 0;
  6106. const byte* pbeOidBuf = NULL;
  6107. word32 pbeOidBufSz = 0;
  6108. word32 pbeLen = 0;
  6109. word32 kdfLen = 0;
  6110. word32 encLen = 0;
  6111. byte cbcIv[MAX_IV_SIZE];
  6112. word32 idx = 0;
  6113. word32 encIdx = 0;
  6114. (void)heap;
  6115. WOLFSSL_ENTER("wc_EncryptPKCS8Key");
  6116. if (key == NULL || outSz == NULL || password == NULL) {
  6117. ret = BAD_FUNC_ARG;
  6118. }
  6119. if (ret == 0) {
  6120. ret = CheckAlgo(vPKCS, pbeOid, &pbeId, &version, &blockSz);
  6121. }
  6122. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  6123. genSalt = 1;
  6124. saltSz = 8;
  6125. }
  6126. if (ret == 0 && version == PKCS5v2) {
  6127. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &pbeId, &blockSz);
  6128. }
  6129. if (ret == 0) {
  6130. padSz = (blockSz - (keySz & (blockSz - 1))) & (blockSz - 1);
  6131. /* inner = OCT salt INT itt */
  6132. innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2);
  6133. if (version != PKCS5v2) {
  6134. pbeOidBuf = OidFromId(pbeId, oidPBEType, &pbeOidBufSz);
  6135. /* pbe = OBJ pbse1 SEQ [ inner ] */
  6136. pbeLen = 2 + pbeOidBufSz + 2 + innerLen;
  6137. }
  6138. else {
  6139. pbeOidBuf = pbes2;
  6140. pbeOidBufSz = sizeof(pbes2);
  6141. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  6142. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  6143. /* enc = OBJ enc_alg OCT iv */
  6144. encLen = 2 + encOidSz + 2 + blockSz;
  6145. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  6146. pbeLen = 2 + sizeof(pbes2) + 2 + 2 + kdfLen + 2 + encLen;
  6147. ret = wc_RNG_GenerateBlock(rng, cbcIv, blockSz);
  6148. }
  6149. }
  6150. if (ret == 0) {
  6151. /* outerLen = length of PBE encoding + octet string data */
  6152. /* Plus 2 for tag and length for pbe */
  6153. outerLen = 2 + pbeLen;
  6154. /* Octet string tag, length */
  6155. outerLen += 1 + SetLength(keySz + padSz, NULL);
  6156. /* Octet string bytes */
  6157. outerLen += keySz + padSz;
  6158. if (out == NULL) {
  6159. /* Sequence tag, length */
  6160. *outSz = 1 + SetLength(outerLen, NULL) + outerLen;
  6161. return LENGTH_ONLY_E;
  6162. }
  6163. SetOctetString(keySz + padSz, out);
  6164. idx += SetSequence(outerLen, out + idx);
  6165. encIdx = idx + outerLen - keySz - padSz;
  6166. /* Put Encrypted content in place. */
  6167. XMEMCPY(out + encIdx, key, keySz);
  6168. if (padSz > 0) {
  6169. XMEMSET(out + encIdx + keySz, padSz, padSz);
  6170. keySz += padSz;
  6171. }
  6172. if (genSalt == 1) {
  6173. #ifdef WOLFSSL_SMALL_STACK
  6174. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6175. if (saltTmp == NULL) {
  6176. ret = MEMORY_E;
  6177. }
  6178. else
  6179. #endif
  6180. {
  6181. salt = saltTmp;
  6182. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  6183. WOLFSSL_MSG("Error generating random salt");
  6184. }
  6185. }
  6186. }
  6187. }
  6188. if (ret == 0) {
  6189. ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, pbeId,
  6190. out + encIdx, keySz, version, cbcIv, 1, 0);
  6191. }
  6192. if (ret == 0) {
  6193. if (version != PKCS5v2) {
  6194. /* PBE algorithm */
  6195. idx += SetSequence(pbeLen, out + idx);
  6196. idx += SetObjectId(pbeOidBufSz, out + idx);
  6197. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  6198. idx += pbeOidBufSz;
  6199. }
  6200. else {
  6201. /* PBES2 algorithm identifier */
  6202. idx += SetSequence(pbeLen, out + idx);
  6203. idx += SetObjectId(pbeOidBufSz, out + idx);
  6204. XMEMCPY(out + idx, pbeOidBuf, pbeOidBufSz);
  6205. idx += pbeOidBufSz;
  6206. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  6207. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  6208. /* KDF Algorithm Identifier */
  6209. idx += SetSequence(kdfLen, out + idx);
  6210. idx += SetObjectId(sizeof(pbkdf2Oid), out + idx);
  6211. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  6212. idx += sizeof(pbkdf2Oid);
  6213. }
  6214. idx += SetSequence(innerLen, out + idx);
  6215. idx += SetOctetString(saltSz, out + idx);
  6216. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  6217. ret = SetShortInt(out, &idx, itt, *outSz);
  6218. if (ret > 0)
  6219. ret = 0;
  6220. }
  6221. if (ret == 0) {
  6222. if (version == PKCS5v2) {
  6223. /* Encryption Algorithm Identifier */
  6224. idx += SetSequence(encLen, out + idx);
  6225. idx += SetObjectId(encOidSz, out + idx);
  6226. XMEMCPY(out + idx, encOid, encOidSz);
  6227. idx += encOidSz;
  6228. /* Encryption Algorithm Parameter: CBC IV */
  6229. idx += SetOctetString(blockSz, out + idx);
  6230. XMEMCPY(out + idx, cbcIv, blockSz);
  6231. idx += blockSz;
  6232. }
  6233. idx += SetOctetString(keySz, out + idx);
  6234. /* Default PRF - no need to write out OID */
  6235. idx += keySz;
  6236. ret = idx;
  6237. }
  6238. #ifdef WOLFSSL_SMALL_STACK
  6239. if (saltTmp != NULL) {
  6240. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6241. }
  6242. #endif
  6243. WOLFSSL_LEAVE("wc_EncryptPKCS8Key", ret);
  6244. return ret;
  6245. }
  6246. int wc_DecryptPKCS8Key(byte* input, word32 sz, const char* password,
  6247. int passwordSz)
  6248. {
  6249. int ret;
  6250. int length;
  6251. word32 inOutIdx = 0;
  6252. if (input == NULL || password == NULL) {
  6253. return BAD_FUNC_ARG;
  6254. }
  6255. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  6256. ret = ASN_PARSE_E;
  6257. }
  6258. else {
  6259. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  6260. passwordSz);
  6261. if (ret > 0) {
  6262. XMEMMOVE(input, input + inOutIdx, ret);
  6263. }
  6264. }
  6265. if (ret > 0) {
  6266. /* DecryptContent will decrypt the data, but it will leave any padding
  6267. * bytes intact. This code calculates the length without the padding
  6268. * and we return that to the user. */
  6269. inOutIdx = 0;
  6270. if (GetSequence(input, &inOutIdx, &length, ret) < 0) {
  6271. ret = ASN_PARSE_E;
  6272. }
  6273. else {
  6274. ret = inOutIdx + length;
  6275. }
  6276. }
  6277. return ret;
  6278. }
  6279. /* Takes an unencrypted, traditional DER-encoded key and converts it to a PKCS#8
  6280. * encrypted key. If out is not NULL, it will hold the encrypted key. If it's
  6281. * NULL, LENGTH_ONLY_E will be returned and outSz will have the required out
  6282. * buffer size. */
  6283. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  6284. const char* password, int passwordSz, int vPKCS, int vAlgo,
  6285. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  6286. void* heap)
  6287. {
  6288. int ret = 0;
  6289. byte *pkcs8Key = NULL;
  6290. word32 pkcs8KeySz = 0;
  6291. int algId = 0;
  6292. const byte* curveOid = NULL;
  6293. word32 curveOidSz = 0;
  6294. if (ret == 0) {
  6295. /* check key type and get OID if ECC */
  6296. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  6297. if (ret == 1)
  6298. ret = 0;
  6299. }
  6300. if (ret == 0) {
  6301. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  6302. curveOidSz);
  6303. if (ret == LENGTH_ONLY_E)
  6304. ret = 0;
  6305. }
  6306. if (ret == 0) {
  6307. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6308. if (pkcs8Key == NULL)
  6309. ret = MEMORY_E;
  6310. }
  6311. if (ret == 0) {
  6312. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  6313. curveOid, curveOidSz);
  6314. if (ret >= 0) {
  6315. pkcs8KeySz = ret;
  6316. ret = 0;
  6317. }
  6318. }
  6319. if (ret == 0) {
  6320. ret = wc_EncryptPKCS8Key(pkcs8Key, pkcs8KeySz, out, outSz, password,
  6321. passwordSz, vPKCS, vAlgo, encAlgId, salt, saltSz, itt, rng, heap);
  6322. }
  6323. if (pkcs8Key != NULL) {
  6324. ForceZero(pkcs8Key, pkcs8KeySz);
  6325. XFREE(pkcs8Key, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6326. }
  6327. (void)rng;
  6328. return ret;
  6329. }
  6330. /* Same as TraditionalEnc, but in the public API. */
  6331. int wc_CreateEncryptedPKCS8Key(byte* key, word32 keySz, byte* out,
  6332. word32* outSz, const char* password, int passwordSz, int vPKCS,
  6333. int pbeOid, int encAlgId, byte* salt, word32 saltSz, int itt,
  6334. WC_RNG* rng, void* heap)
  6335. {
  6336. return TraditionalEnc(key, keySz, out, outSz, password, passwordSz, vPKCS,
  6337. pbeOid, encAlgId, salt, saltSz, itt, rng, heap);
  6338. }
  6339. #ifdef WOLFSSL_ASN_TEMPLATE
  6340. /* ASN.1 template for PKCS #8/#7 encrypted key for decrypting
  6341. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  6342. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  6343. */
  6344. static const ASNItem pkcs8DecASN[] = {
  6345. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6346. /* 1 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6347. /* 2 */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  6348. /* PKCS #7 */
  6349. /* 3 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  6350. /* PKCS #8 */
  6351. /* 4 */ { 1, ASN_OCTET_STRING, 0, 0, 2 },
  6352. };
  6353. /* Number of items in ASN.1 template for PKCS #8/#7 encrypted key. */
  6354. #define pkcs8DecASN_Length (sizeof(pkcs8DecASN) / sizeof(ASNItem))
  6355. #endif
  6356. /* Decrypt data using PBE algorithm.
  6357. *
  6358. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo without outer SEQUENCE
  6359. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo without outer SEQUENCE
  6360. *
  6361. * Note: input buffer is overwritten with decrypted data!
  6362. *
  6363. * Salt is in KDF parameters and IV is PBE parameters when needed.
  6364. *
  6365. * @param [in] input Data to decrypt and unwrap.
  6366. * @param [in] sz Size of encrypted data.
  6367. * @param [in] password Password to derive encryption key with.
  6368. * @param [in] passwordSz Size of password in bytes.
  6369. * @return Length of decrypted data on success.
  6370. * @return MEMORY_E when dynamic memory allocation fails.
  6371. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6372. * is invalid.
  6373. * @return BUFFER_E when data in buffer is too small.
  6374. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6375. * @return Other when decryption fails.
  6376. */
  6377. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  6378. {
  6379. #ifndef WOLFSSL_ASN_TEMPLATE
  6380. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  6381. int ret = 0, first, second, length = 0, version, saltSz, id = 0;
  6382. int iterations = 0, keySz = 0;
  6383. #ifdef WOLFSSL_SMALL_STACK
  6384. byte* salt = NULL;
  6385. byte* cbcIv = NULL;
  6386. #else
  6387. byte salt[MAX_SALT_SIZE];
  6388. byte cbcIv[MAX_IV_SIZE];
  6389. #endif
  6390. byte tag;
  6391. if (passwordSz < 0) {
  6392. WOLFSSL_MSG("Bad password size");
  6393. return BAD_FUNC_ARG;
  6394. }
  6395. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  6396. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6397. }
  6398. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  6399. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  6400. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  6401. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  6402. }
  6403. if (version == PKCS5v2) {
  6404. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  6405. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6406. }
  6407. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  6408. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6409. }
  6410. if (oid != PBKDF2_OID) {
  6411. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6412. }
  6413. }
  6414. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  6415. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6416. }
  6417. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  6418. * DEFAULT items. */
  6419. seqEnd = inOutIdx + length;
  6420. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  6421. if (ret < 0)
  6422. goto exit_dc;
  6423. if (saltSz > MAX_SALT_SIZE) {
  6424. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6425. }
  6426. #ifdef WOLFSSL_SMALL_STACK
  6427. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6428. if (salt == NULL) {
  6429. ERROR_OUT(MEMORY_E, exit_dc);
  6430. }
  6431. #endif
  6432. XMEMCPY(salt, &input[inOutIdx], saltSz);
  6433. inOutIdx += saltSz;
  6434. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  6435. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6436. }
  6437. /* OPTIONAL key length */
  6438. if (seqEnd > inOutIdx) {
  6439. word32 localIdx = inOutIdx;
  6440. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  6441. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6442. }
  6443. if (tag == ASN_INTEGER &&
  6444. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  6445. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6446. }
  6447. }
  6448. /* DEFAULT HMAC is SHA-1 */
  6449. if (seqEnd > inOutIdx) {
  6450. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  6451. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6452. }
  6453. shaOid = oid;
  6454. }
  6455. #ifdef WOLFSSL_SMALL_STACK
  6456. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6457. if (cbcIv == NULL) {
  6458. ERROR_OUT(MEMORY_E, exit_dc);
  6459. }
  6460. #endif
  6461. if (version == PKCS5v2) {
  6462. /* get encryption algo */
  6463. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  6464. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6465. }
  6466. if (CheckAlgoV2(oid, &id, NULL) < 0) {
  6467. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  6468. }
  6469. if (shaOid == 0)
  6470. shaOid = oid;
  6471. ret = GetOctetString(input, &inOutIdx, &length, sz);
  6472. if (ret < 0)
  6473. goto exit_dc;
  6474. if (length > MAX_IV_SIZE) {
  6475. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6476. }
  6477. XMEMCPY(cbcIv, &input[inOutIdx], length);
  6478. inOutIdx += length;
  6479. }
  6480. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  6481. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6482. }
  6483. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  6484. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6485. }
  6486. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  6487. ERROR_OUT(ASN_PARSE_E, exit_dc);
  6488. }
  6489. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  6490. input + inOutIdx, length, version, cbcIv, 0, shaOid);
  6491. exit_dc:
  6492. #ifdef WOLFSSL_SMALL_STACK
  6493. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6494. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6495. #endif
  6496. if (ret == 0) {
  6497. XMEMMOVE(input, input + inOutIdx, length);
  6498. ret = length;
  6499. }
  6500. return ret;
  6501. #else
  6502. /* pbes2ParamsASN longer than pkcs8DecASN_Length/pbes1ParamsASN_Length. */
  6503. DECL_ASNGETDATA(dataASN, pbes2ParamsASN_Length);
  6504. int ret = 0;
  6505. int id;
  6506. int version;
  6507. word32 idx = 0;
  6508. word32 pIdx = 0;
  6509. word32 iterations;
  6510. word32 keySz = 0;
  6511. word32 saltSz;
  6512. word32 shaOid = 0;
  6513. byte* salt = NULL;
  6514. byte* key = NULL;
  6515. byte cbcIv[MAX_IV_SIZE];
  6516. byte* params;
  6517. WOLFSSL_ENTER("DecryptContent");
  6518. ALLOC_ASNGETDATA(dataASN, pbes2ParamsASN_Length, ret, NULL);
  6519. if (ret == 0) {
  6520. /* Check OID is a PBE Type */
  6521. XMEMSET(dataASN, 0, sizeof(*dataASN) * pkcs8DecASN_Length);
  6522. GetASN_OID(&dataASN[1], oidPBEType);
  6523. ret = GetASN_Items(pkcs8DecASN, dataASN, pkcs8DecASN_Length, 0, input,
  6524. &idx, sz);
  6525. }
  6526. if (ret == 0) {
  6527. /* Check the PBE algorithm and get the version and id. */
  6528. idx = dataASN[1].data.oid.length;
  6529. /* Second last byte: 1 (PKCS #12 PBE Id) or 5 (PKCS #5)
  6530. * Last byte: Alg or PBES2 */
  6531. CheckAlgo(dataASN[1].data.oid.data[idx - 2],
  6532. dataASN[1].data.oid.data[idx - 1], &id, &version, NULL);
  6533. /* Get the parameters data. */
  6534. GetASN_GetRef(&dataASN[2], &params, &sz);
  6535. /* Having a numbered choice means none or both will have errored out. */
  6536. if (dataASN[3].tag != 0)
  6537. GetASN_GetRef(&dataASN[3], &key, &keySz);
  6538. else if (dataASN[4].tag != 0)
  6539. GetASN_GetRef(&dataASN[4], &key, &keySz);
  6540. }
  6541. if (ret == 0) {
  6542. if (version != PKCS5v2) {
  6543. /* Initialize for PBES1 parameters and put iterations in var. */
  6544. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes1ParamsASN_Length);
  6545. GetASN_Int32Bit(&dataASN[1], &iterations);
  6546. /* Parse the PBES1 parameters. */
  6547. ret = GetASN_Items(pbes1ParamsASN, dataASN, pbes1ParamsASN_Length,
  6548. 0, params, &pIdx, sz);
  6549. if (ret == 0) {
  6550. /* Get the salt data. */
  6551. GetASN_GetRef(&dataASN[0], &salt, &saltSz);
  6552. }
  6553. }
  6554. else {
  6555. word32 ivSz = MAX_IV_SIZE;
  6556. /* Initialize for PBES2 parameters. Put iterations in var; match
  6557. * KDF, HMAC and cipher, and copy CBC into buffer. */
  6558. XMEMSET(dataASN, 0, sizeof(*dataASN) * pbes2ParamsASN_Length);
  6559. GetASN_ExpBuffer(&dataASN[1], pbkdf2Oid, sizeof(pbkdf2Oid));
  6560. GetASN_Int32Bit(&dataASN[4], &iterations);
  6561. GetASN_OID(&dataASN[7], oidHmacType);
  6562. GetASN_OID(&dataASN[10], oidBlkType);
  6563. GetASN_Buffer(&dataASN[11], cbcIv, &ivSz);
  6564. /* Parse the PBES2 parameters */
  6565. ret = GetASN_Items(pbes2ParamsASN, dataASN, pbes2ParamsASN_Length,
  6566. 0, params, &pIdx, sz);
  6567. if (ret == 0) {
  6568. /* Get the salt data. */
  6569. GetASN_GetRef(&dataASN[3], &salt, &saltSz);
  6570. /* Get the digest and encryption algorithm id. */
  6571. shaOid = dataASN[7].data.oid.sum; /* Default HMAC-SHA1 */
  6572. id = dataASN[10].data.oid.sum;
  6573. /* Convert encryption algorithm to a PBE algorithm if needed. */
  6574. CheckAlgoV2(id, &id, NULL);
  6575. }
  6576. }
  6577. }
  6578. if (ret == 0) {
  6579. /* Decrypt the key. */
  6580. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  6581. key, keySz, version, cbcIv, 0, shaOid);
  6582. }
  6583. if (ret == 0) {
  6584. /* Copy the decrypted key into the input (inline). */
  6585. XMEMMOVE(input, key, keySz);
  6586. ret = keySz;
  6587. }
  6588. FREE_ASNGETDATA(dataASN, NULL);
  6589. return ret;
  6590. #endif
  6591. }
  6592. /* Decrypt data using PBE algorithm and get key from PKCS#8 wrapping.
  6593. *
  6594. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  6595. * PKCS #7: RFC 2315, 10.1 - EncryptedContentInfo
  6596. *
  6597. * Note: input buffer is overwritten with decrypted key!
  6598. *
  6599. * Salt is in KDF parameters and IV is PBE parameters when needed.
  6600. *
  6601. * @param [in] input Data to decrypt and unwrap.
  6602. * @param [in] sz Size of encrypted data.
  6603. * @param [in] password Password to derive encryption key with.
  6604. * @param [in] passwordSz Size of password in bytes.
  6605. * @param [out] algId Key algorithm from PKCS#8 wrapper.
  6606. * @return Length of decrypted data on success.
  6607. * @return MEMORY_E when dynamic memory allocation fails.
  6608. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  6609. * is invalid.
  6610. * @return BUFFER_E when data in buffer is too small.
  6611. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  6612. * @return Other when decryption fails.
  6613. */
  6614. int ToTraditionalEnc(byte* input, word32 sz, const char* password,
  6615. int passwordSz, word32* algId)
  6616. {
  6617. int ret;
  6618. ret = wc_DecryptPKCS8Key(input, sz, password, passwordSz);
  6619. if (ret > 0) {
  6620. ret = ToTraditional_ex(input, ret, algId);
  6621. }
  6622. return ret;
  6623. }
  6624. #endif /* HAVE_PKCS8 */
  6625. #ifdef HAVE_PKCS12
  6626. #define PKCS8_MIN_BLOCK_SIZE 8
  6627. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  6628. {
  6629. int i, padSz;
  6630. /* calculate pad size */
  6631. padSz = blockSz - (sz & (blockSz - 1));
  6632. /* pad with padSz value */
  6633. if (buf) {
  6634. for (i = 0; i < padSz; i++) {
  6635. buf[sz+i] = (byte)(padSz & 0xFF);
  6636. }
  6637. }
  6638. /* return adjusted length */
  6639. return sz + padSz;
  6640. }
  6641. #ifdef WOLFSSL_ASN_TEMPLATE
  6642. /* ASN.1 template for PKCS #8 encrypted key with PBES1 parameters.
  6643. * PKCS #8: RFC 5958, 3 - EncryptedPrivateKeyInfo
  6644. * PKCS #5: RFC 8018, A.3 - PBEParameter
  6645. */
  6646. static const ASNItem p8EncPbes1ASN[] = {
  6647. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  6648. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  6649. /* PBE algorithm */
  6650. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  6651. /* 3 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  6652. /* Salt */
  6653. /* 4 */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  6654. /* Iteration Count */
  6655. /* 5 */ { 3, ASN_INTEGER, 0, 0, 0 },
  6656. /* 6 */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  6657. };
  6658. #define p8EncPbes1ASN_Length (sizeof(p8EncPbes1ASN) / sizeof(ASNItem))
  6659. #endif
  6660. /* Wrap a private key in PKCS#8 and encrypt.
  6661. *
  6662. * Used for PKCS#12 and PKCS#7.
  6663. * vPKCS is the version of PKCS to use.
  6664. * vAlgo is the algorithm version to use.
  6665. *
  6666. * When salt is NULL, a random number is generated.
  6667. *
  6668. * data returned is :
  6669. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  6670. *
  6671. * @param [in] input Data to encrypt.
  6672. * @param [in] inputSz Length of data in bytes.
  6673. * @param [out] out Buffer to write wrapped encrypted data into.
  6674. * @param [out] outSz Length of encrypted data in bytes.
  6675. * @param [in] password Password used to create encryption key.
  6676. * @param [in] passwordSz Length of password in bytes.
  6677. * @param [in] vPKCS First byte used to determine PBE algorithm.
  6678. * @param [in] vAlgo Second byte used to determine PBE algorithm.
  6679. * @param [in] salt Salt to use with KDF.
  6680. * @param [in] saltSz Length of salt in bytes.
  6681. * @param [in] itt Number of iterations to use in KDF.
  6682. * @param [in] rng Random number generator to use to generate salt.
  6683. * @param [in] heap Dynamic memory allocator hint.
  6684. * @return The size of encrypted data on success
  6685. * @return LENGTH_ONLY_E when out is NULL and able to encode.
  6686. * @return ASN_PARSE_E when the salt size is too large.
  6687. * @return ASN_VERSION_E when attempting to use a PBES2 algorithm (use
  6688. * TraditionalEnc).
  6689. * @return MEMORY_E when dynamic memory allocation fails.
  6690. * @return Other when encryption or random number generation fails.
  6691. */
  6692. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  6693. const char* password, int passwordSz, int vPKCS, int vAlgo,
  6694. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  6695. {
  6696. #ifndef WOLFSSL_ASN_TEMPLATE
  6697. word32 sz;
  6698. word32 inOutIdx = 0;
  6699. word32 tmpIdx = 0;
  6700. word32 totalSz = 0;
  6701. word32 seqSz;
  6702. word32 innerSz;
  6703. int ret;
  6704. int version, id, blockSz = 0;
  6705. #ifdef WOLFSSL_SMALL_STACK
  6706. byte* saltTmp = NULL;
  6707. byte* cbcIv = NULL;
  6708. #else
  6709. byte saltTmp[MAX_SALT_SIZE];
  6710. byte cbcIv[MAX_IV_SIZE];
  6711. #endif
  6712. byte seq[MAX_SEQ_SZ];
  6713. byte shr[MAX_SHORT_SZ];
  6714. word32 maxShr = MAX_SHORT_SZ;
  6715. word32 algoSz;
  6716. const byte* algoName;
  6717. (void)heap;
  6718. WOLFSSL_ENTER("EncryptContent()");
  6719. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  6720. return ASN_INPUT_E; /* Algo ID error */
  6721. if (version == PKCS5v2) {
  6722. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  6723. return BAD_FUNC_ARG;
  6724. }
  6725. if (saltSz > MAX_SALT_SIZE)
  6726. return ASN_PARSE_E;
  6727. if (outSz == NULL) {
  6728. return BAD_FUNC_ARG;
  6729. }
  6730. /* calculate size */
  6731. /* size of constructed string at end */
  6732. sz = Pkcs8Pad(NULL, inputSz, blockSz);
  6733. totalSz = ASN_TAG_SZ;
  6734. totalSz += SetLength(sz, seq);
  6735. totalSz += sz;
  6736. /* size of sequence holding object id and sub sequence of salt and itt */
  6737. algoName = OidFromId(id, oidPBEType, &algoSz);
  6738. if (algoName == NULL) {
  6739. WOLFSSL_MSG("Unknown Algorithm");
  6740. return 0;
  6741. }
  6742. innerSz = SetObjectId(algoSz, seq);
  6743. innerSz += algoSz;
  6744. /* get subsequence of salt and itt */
  6745. if (salt == NULL || saltSz == 0) {
  6746. sz = 8;
  6747. }
  6748. else {
  6749. sz = saltSz;
  6750. }
  6751. seqSz = SetOctetString(sz, seq);
  6752. seqSz += sz;
  6753. tmpIdx = 0;
  6754. ret = SetShortInt(shr, &tmpIdx, itt, maxShr);
  6755. if (ret >= 0) {
  6756. seqSz += ret;
  6757. }
  6758. else {
  6759. return ret;
  6760. }
  6761. innerSz += seqSz + SetSequence(seqSz, seq);
  6762. totalSz += innerSz + SetSequence(innerSz, seq);
  6763. if (out == NULL) {
  6764. *outSz = totalSz;
  6765. return LENGTH_ONLY_E;
  6766. }
  6767. inOutIdx = 0;
  6768. if (totalSz > *outSz)
  6769. return BUFFER_E;
  6770. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  6771. inOutIdx += SetObjectId(algoSz, out + inOutIdx);
  6772. XMEMCPY(out + inOutIdx, algoName, algoSz);
  6773. inOutIdx += algoSz;
  6774. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  6775. /* create random salt if one not provided */
  6776. if (salt == NULL || saltSz == 0) {
  6777. saltSz = 8;
  6778. #ifdef WOLFSSL_SMALL_STACK
  6779. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6780. if (saltTmp == NULL)
  6781. return MEMORY_E;
  6782. #endif
  6783. salt = saltTmp;
  6784. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  6785. WOLFSSL_MSG("Error generating random salt");
  6786. #ifdef WOLFSSL_SMALL_STACK
  6787. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6788. #endif
  6789. return ret;
  6790. }
  6791. }
  6792. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  6793. if (saltSz + inOutIdx > *outSz) {
  6794. #ifdef WOLFSSL_SMALL_STACK
  6795. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6796. #endif
  6797. return BUFFER_E;
  6798. }
  6799. XMEMCPY(out + inOutIdx, salt, saltSz);
  6800. inOutIdx += saltSz;
  6801. /* place iteration setting in buffer */
  6802. ret = SetShortInt(out, &inOutIdx, itt, *outSz);
  6803. if (ret < 0) {
  6804. #ifdef WOLFSSL_SMALL_STACK
  6805. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6806. #endif
  6807. return ret;
  6808. }
  6809. if (inOutIdx + 1 > *outSz) {
  6810. #ifdef WOLFSSL_SMALL_STACK
  6811. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6812. #endif
  6813. return BUFFER_E;
  6814. }
  6815. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  6816. /* get pad size and verify buffer room */
  6817. sz = Pkcs8Pad(NULL, inputSz, blockSz);
  6818. if (sz + inOutIdx > *outSz) {
  6819. #ifdef WOLFSSL_SMALL_STACK
  6820. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6821. #endif
  6822. return BUFFER_E;
  6823. }
  6824. inOutIdx += SetLength(sz, out + inOutIdx);
  6825. /* copy input to output buffer and pad end */
  6826. XMEMCPY(out + inOutIdx, input, inputSz);
  6827. sz = Pkcs8Pad(out + inOutIdx, inputSz, blockSz);
  6828. #ifdef WOLFSSL_SMALL_STACK
  6829. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6830. if (cbcIv == NULL) {
  6831. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6832. return MEMORY_E;
  6833. }
  6834. #endif
  6835. /* encrypt */
  6836. if ((ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id,
  6837. out + inOutIdx, sz, version, cbcIv, 1, 0)) < 0) {
  6838. #ifdef WOLFSSL_SMALL_STACK
  6839. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6840. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6841. #endif
  6842. return ret; /* encrypt failure */
  6843. }
  6844. #ifdef WOLFSSL_SMALL_STACK
  6845. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6846. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6847. #endif
  6848. (void)rng;
  6849. return inOutIdx + sz;
  6850. #else
  6851. DECL_ASNSETDATA(dataASN, p8EncPbes1ASN_Length);
  6852. int ret = 0;
  6853. int sz;
  6854. int version;
  6855. int id;
  6856. int blockSz = 0;
  6857. byte* pkcs8;
  6858. word32 pkcs8Sz;
  6859. byte cbcIv[MAX_IV_SIZE];
  6860. (void)heap;
  6861. WOLFSSL_ENTER("EncryptContent()");
  6862. /* Must have a output size to return or check. */
  6863. if (outSz == NULL) {
  6864. ret = BAD_FUNC_ARG;
  6865. }
  6866. /* Check salt size is valid. */
  6867. if ((ret == 0) && (saltSz > MAX_SALT_SIZE)) {
  6868. ret = ASN_PARSE_E;
  6869. }
  6870. /* Get algorithm parameters for algorithm identifier. */
  6871. if ((ret == 0) && CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  6872. ret = ASN_INPUT_E;
  6873. }
  6874. /* Check PKCS #5 version - only PBSE1 parameters supported. */
  6875. if ((ret == 0) && (version == PKCS5v2)) {
  6876. ret = BAD_FUNC_ARG;
  6877. }
  6878. CALLOC_ASNSETDATA(dataASN, p8EncPbes1ASN_Length, ret, heap);
  6879. if (ret == 0) {
  6880. /* Setup data to go into encoding including PBE algorithm, salt,
  6881. * iteration count, and padded key length. */
  6882. SetASN_OID(&dataASN[2], id, oidPBEType);
  6883. if (salt == NULL || saltSz == 0) {
  6884. salt = NULL;
  6885. saltSz = PKCS5_SALT_SZ;
  6886. /* Salt generated into encoding below. */
  6887. }
  6888. SetASN_Buffer(&dataASN[4], salt, saltSz);
  6889. SetASN_Int16Bit(&dataASN[5], itt);
  6890. pkcs8Sz = Pkcs8Pad(NULL, inputSz, blockSz);
  6891. SetASN_Buffer(&dataASN[6], NULL, pkcs8Sz);
  6892. /* Calculate size of encoding. */
  6893. ret = SizeASN_Items(p8EncPbes1ASN + 1, dataASN + 1,
  6894. p8EncPbes1ASN_Length - 1, &sz);
  6895. }
  6896. /* Return size when no output buffer. */
  6897. if ((ret == 0) && (out == NULL)) {
  6898. *outSz = sz;
  6899. ret = LENGTH_ONLY_E;
  6900. }
  6901. /* Check output buffer is big enough for encoded data. */
  6902. if ((ret == 0) && (sz > (int)*outSz)) {
  6903. ret = BAD_FUNC_ARG;
  6904. }
  6905. if (ret == 0) {
  6906. /* Encode PKCS#8 key. */
  6907. SetASN_Items(p8EncPbes1ASN + 1, dataASN + 1, p8EncPbes1ASN_Length - 1,
  6908. out);
  6909. if (salt == NULL) {
  6910. /* Generate salt into encoding. */
  6911. salt = (byte*)dataASN[4].data.buffer.data;
  6912. ret = wc_RNG_GenerateBlock(rng, salt, saltSz);
  6913. }
  6914. }
  6915. if (ret == 0) {
  6916. /* Store PKCS#8 key in output buffer. */
  6917. pkcs8 = (byte*)dataASN[6].data.buffer.data;
  6918. XMEMCPY(pkcs8, input, inputSz);
  6919. /* Encrypt PKCS#8 key inline. */
  6920. ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id, pkcs8,
  6921. pkcs8Sz, version, cbcIv, 1, 0);
  6922. }
  6923. if (ret == 0) {
  6924. /* Returning size on success. */
  6925. ret = sz;
  6926. }
  6927. FREE_ASNSETDATA(dataASN, heap);
  6928. return ret;
  6929. #endif /* WOLFSSL_ASN_TEMPLATE */
  6930. }
  6931. #endif /* HAVE_PKCS12 */
  6932. #endif /* NO_PWDBASED */
  6933. #ifndef NO_RSA
  6934. #ifndef HAVE_USER_RSA
  6935. #ifdef WOLFSSL_RENESAS_TSIP
  6936. /* This function is to retrieve key position information in a cert.*
  6937. * The information will be used to call TSIP TLS-linked API for *
  6938. * certificate verification. */
  6939. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  6940. word32 inSz, word32* key_n,
  6941. word32* key_n_len, word32* key_e,
  6942. word32* key_e_len)
  6943. {
  6944. int ret = 0;
  6945. int length = 0;
  6946. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  6947. byte b;
  6948. #endif
  6949. if (input == NULL || inOutIdx == NULL)
  6950. return BAD_FUNC_ARG;
  6951. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  6952. return ASN_PARSE_E;
  6953. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  6954. if ((*inOutIdx + 1) > inSz)
  6955. return BUFFER_E;
  6956. b = input[*inOutIdx];
  6957. if (b != ASN_INTEGER) {
  6958. /* not from decoded cert, will have algo id, skip past */
  6959. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  6960. return ASN_PARSE_E;
  6961. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  6962. return ASN_PARSE_E;
  6963. /* Option NULL ASN.1 tag */
  6964. if (*inOutIdx >= inSz) {
  6965. return BUFFER_E;
  6966. }
  6967. if (input[*inOutIdx] == ASN_TAG_NULL) {
  6968. ret = GetASNNull(input, inOutIdx, inSz);
  6969. if (ret != 0)
  6970. return ret;
  6971. }
  6972. /* should have bit tag length and seq next */
  6973. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  6974. if (ret != 0)
  6975. return ret;
  6976. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  6977. return ASN_PARSE_E;
  6978. }
  6979. #endif /* OPENSSL_EXTRA */
  6980. /* Get modulus */
  6981. ret = GetASNInt(input, inOutIdx, &length, inSz);
  6982. *key_n += *inOutIdx;
  6983. if (ret < 0) {
  6984. return ASN_RSA_KEY_E;
  6985. }
  6986. if (key_n_len)
  6987. *key_n_len = length;
  6988. *inOutIdx += length;
  6989. /* Get exponent */
  6990. ret = GetASNInt(input, inOutIdx, &length, inSz);
  6991. *key_e += *inOutIdx;
  6992. if (ret < 0) {
  6993. return ASN_RSA_KEY_E;
  6994. }
  6995. if (key_e_len)
  6996. *key_e_len = length;
  6997. return ret;
  6998. }
  6999. #endif /* WOLFSSL_RENESAS_TSIP */
  7000. #ifdef WOLFSSL_ASN_TEMPLATE
  7001. /* ASN.1 template for an RSA public key.
  7002. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  7003. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  7004. */
  7005. static const ASNItem rsaPublicKeyASN[] = {
  7006. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7007. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7008. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7009. /* 3 */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  7010. /* 4 */ { 1, ASN_BIT_STRING, 0, 1, 0 },
  7011. /* RSAPublicKey */
  7012. /* 5 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  7013. /* 6 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7014. /* 7 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7015. };
  7016. /* Number of items in ASN.1 template for an RSA public key. */
  7017. #define rsaPublicKeyASN_Length (sizeof(rsaPublicKeyASN) / sizeof(ASNItem))
  7018. #endif
  7019. /* Decode RSA public key.
  7020. *
  7021. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  7022. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  7023. *
  7024. * @param [in] input Buffer holding BER encoded data.
  7025. * @param [in, out] inOutIdx On in, start of RSA public key.
  7026. * On out, start of ASN.1 item after RSA public key.
  7027. * @param [in] inSz Number of bytes in buffer.
  7028. * @param [out] n Pointer to modulus in buffer.
  7029. * @param [out] nSz Size of modulus in bytes.
  7030. * @param [out] e Pointer to exponent in buffer.
  7031. * @param [out] eSz Size of exponent in bytes.
  7032. * @return 0 on success.
  7033. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7034. * is invalid.
  7035. * @return BUFFER_E when data in buffer is too small.
  7036. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7037. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  7038. * non-zero length.
  7039. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  7040. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  7041. */
  7042. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  7043. const byte** n, word32* nSz, const byte** e, word32* eSz)
  7044. {
  7045. #ifndef WOLFSSL_ASN_TEMPLATE
  7046. int ret = 0;
  7047. int length = 0;
  7048. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  7049. word32 localIdx;
  7050. byte tag;
  7051. #endif
  7052. if (input == NULL || inOutIdx == NULL)
  7053. return BAD_FUNC_ARG;
  7054. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7055. return ASN_PARSE_E;
  7056. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  7057. localIdx = *inOutIdx;
  7058. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  7059. return BUFFER_E;
  7060. if (tag != ASN_INTEGER) {
  7061. /* not from decoded cert, will have algo id, skip past */
  7062. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7063. return ASN_PARSE_E;
  7064. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  7065. return ASN_PARSE_E;
  7066. /* Option NULL ASN.1 tag */
  7067. if (*inOutIdx >= inSz) {
  7068. return BUFFER_E;
  7069. }
  7070. localIdx = *inOutIdx;
  7071. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  7072. return ASN_PARSE_E;
  7073. if (tag == ASN_TAG_NULL) {
  7074. ret = GetASNNull(input, inOutIdx, inSz);
  7075. if (ret != 0)
  7076. return ret;
  7077. }
  7078. /* should have bit tag length and seq next */
  7079. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  7080. if (ret != 0)
  7081. return ret;
  7082. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7083. return ASN_PARSE_E;
  7084. }
  7085. #endif /* OPENSSL_EXTRA */
  7086. /* Get modulus */
  7087. ret = GetASNInt(input, inOutIdx, &length, inSz);
  7088. if (ret < 0) {
  7089. return ASN_RSA_KEY_E;
  7090. }
  7091. if (nSz)
  7092. *nSz = length;
  7093. if (n)
  7094. *n = &input[*inOutIdx];
  7095. *inOutIdx += length;
  7096. /* Get exponent */
  7097. ret = GetASNInt(input, inOutIdx, &length, inSz);
  7098. if (ret < 0) {
  7099. return ASN_RSA_KEY_E;
  7100. }
  7101. if (eSz)
  7102. *eSz = length;
  7103. if (e)
  7104. *e = &input[*inOutIdx];
  7105. *inOutIdx += length;
  7106. return ret;
  7107. #else
  7108. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  7109. int ret = 0;
  7110. /* Check validity of parameters. */
  7111. if (input == NULL || inOutIdx == NULL) {
  7112. ret = BAD_FUNC_ARG;
  7113. }
  7114. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  7115. if (ret == 0) {
  7116. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  7117. ret = GetASN_Items(&rsaPublicKeyASN[5], &dataASN[5],
  7118. rsaPublicKeyASN_Length - 5, 0, input, inOutIdx,
  7119. inSz);
  7120. if (ret != 0) {
  7121. /* Didn't work - try whole SubjectKeyInfo instead. */
  7122. /* Set the OID to expect. */
  7123. GetASN_ExpBuffer(&dataASN[2], keyRsaOid, sizeof(keyRsaOid));
  7124. /* Decode SubjectKeyInfo. */
  7125. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  7126. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  7127. inSz);
  7128. }
  7129. }
  7130. if (ret == 0) {
  7131. /* Return the buffers and lengths asked for. */
  7132. if (n != NULL) {
  7133. *n = dataASN[6].data.ref.data;
  7134. }
  7135. if (nSz != NULL) {
  7136. *nSz = dataASN[6].data.ref.length;
  7137. }
  7138. if (e != NULL) {
  7139. *e = dataASN[7].data.ref.data;
  7140. }
  7141. if (eSz != NULL) {
  7142. *eSz = dataASN[7].data.ref.length;
  7143. }
  7144. }
  7145. FREE_ASNGETDATA(dataASN, NULL);
  7146. return ret;
  7147. #endif /* WOLFSSL_ASN_TEMPLATE */
  7148. }
  7149. /* Decode RSA public key.
  7150. *
  7151. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  7152. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  7153. *
  7154. * @param [in] input Buffer holding BER encoded data.
  7155. * @param [in, out] inOutIdx On in, start of RSA public key.
  7156. * On out, start of ASN.1 item after RSA public key.
  7157. * @param [in, out] key RSA key object.
  7158. * @param [in] inSz Number of bytes in buffer.
  7159. * @return 0 on success.
  7160. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7161. * is invalid.
  7162. * @return BUFFER_E when data in buffer is too small.
  7163. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7164. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  7165. * non-zero length.
  7166. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  7167. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  7168. */
  7169. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  7170. word32 inSz)
  7171. {
  7172. #ifndef WOLFSSL_ASN_TEMPLATE
  7173. int ret;
  7174. const byte *n = NULL, *e = NULL;
  7175. word32 nSz = 0, eSz = 0;
  7176. if (key == NULL)
  7177. return BAD_FUNC_ARG;
  7178. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  7179. if (ret == 0) {
  7180. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  7181. }
  7182. return ret;
  7183. #else
  7184. DECL_ASNGETDATA(dataASN, rsaPublicKeyASN_Length);
  7185. int ret = 0;
  7186. /* Check validity of parameters. */
  7187. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  7188. ret = BAD_FUNC_ARG;
  7189. }
  7190. CALLOC_ASNGETDATA(dataASN, rsaPublicKeyASN_Length, ret, NULL);
  7191. if (ret == 0) {
  7192. /* Set mp_ints to fill with modulus and exponent data. */
  7193. GetASN_MP(&dataASN[6], &key->n);
  7194. GetASN_MP(&dataASN[7], &key->e);
  7195. /* Try decoding PKCS #1 public key by ignoring rest of ASN.1. */
  7196. ret = GetASN_Items(&rsaPublicKeyASN[5], &dataASN[5],
  7197. rsaPublicKeyASN_Length - 5, 0, input, inOutIdx,
  7198. inSz);
  7199. if (ret != 0) {
  7200. /* Didn't work - try whole SubjectKeyInfo instead. */
  7201. /* Set the OID to expect. */
  7202. GetASN_ExpBuffer(&dataASN[2], keyRsaOid, sizeof(keyRsaOid));
  7203. /* Decode SubjectKeyInfo. */
  7204. ret = GetASN_Items(rsaPublicKeyASN, dataASN,
  7205. rsaPublicKeyASN_Length, 1, input, inOutIdx,
  7206. inSz);
  7207. }
  7208. }
  7209. FREE_ASNGETDATA(dataASN, NULL);
  7210. return ret;
  7211. #endif
  7212. }
  7213. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  7214. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  7215. word32 eSz, RsaKey* key)
  7216. {
  7217. if (n == NULL || e == NULL || key == NULL)
  7218. return BAD_FUNC_ARG;
  7219. key->type = RSA_PUBLIC;
  7220. if (mp_init(&key->n) != MP_OKAY)
  7221. return MP_INIT_E;
  7222. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  7223. mp_clear(&key->n);
  7224. return ASN_GETINT_E;
  7225. }
  7226. #ifdef HAVE_WOLF_BIGINT
  7227. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  7228. mp_clear(&key->n);
  7229. return ASN_GETINT_E;
  7230. }
  7231. #endif /* HAVE_WOLF_BIGINT */
  7232. if (mp_init(&key->e) != MP_OKAY) {
  7233. mp_clear(&key->n);
  7234. return MP_INIT_E;
  7235. }
  7236. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  7237. mp_clear(&key->n);
  7238. mp_clear(&key->e);
  7239. return ASN_GETINT_E;
  7240. }
  7241. #ifdef HAVE_WOLF_BIGINT
  7242. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  7243. mp_clear(&key->n);
  7244. mp_clear(&key->e);
  7245. return ASN_GETINT_E;
  7246. }
  7247. #endif /* HAVE_WOLF_BIGINT */
  7248. #ifdef WOLFSSL_XILINX_CRYPT
  7249. if (wc_InitRsaHw(key) != 0) {
  7250. return BAD_STATE_E;
  7251. }
  7252. #endif
  7253. return 0;
  7254. }
  7255. #endif /* HAVE_USER_RSA */
  7256. #endif /* !NO_RSA */
  7257. #ifndef NO_DH
  7258. #if defined(WOLFSSL_DH_EXTRA)
  7259. /*
  7260. * Decodes DH public key to fill specified DhKey.
  7261. *
  7262. * return 0 on success, negative on failure
  7263. */
  7264. int wc_DhPublicKeyDecode(const byte* input, word32* inOutIdx,
  7265. DhKey* key, word32 inSz)
  7266. {
  7267. int ret = 0;
  7268. int length;
  7269. word32 oid = 0;
  7270. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  7271. return BAD_FUNC_ARG;
  7272. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7273. return ASN_PARSE_E;
  7274. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7275. return ASN_PARSE_E;
  7276. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  7277. if (oid != DHk || ret < 0)
  7278. return ASN_DH_KEY_E;
  7279. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7280. return ASN_PARSE_E;
  7281. if (GetInt(&key->p, input, inOutIdx, inSz) < 0)
  7282. return ASN_DH_KEY_E;
  7283. if (GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  7284. mp_clear(&key->p);
  7285. return ASN_DH_KEY_E;
  7286. }
  7287. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  7288. if (ret > 0) {
  7289. /* Found Bit String WOLFSSL_DH_EXTRA is required to access DhKey.pub */
  7290. if (GetInt(&key->pub, input, inOutIdx, inSz) < 0) {
  7291. mp_clear(&key->p);
  7292. mp_clear(&key->g);
  7293. return ASN_DH_KEY_E;
  7294. }
  7295. }
  7296. else {
  7297. mp_clear(&key->p);
  7298. mp_clear(&key->g);
  7299. return ASN_DH_KEY_E;
  7300. }
  7301. return 0;
  7302. }
  7303. #endif /* WOLFSSL_DH_EXTRA */
  7304. #ifdef WOLFSSL_ASN_TEMPLATE
  7305. /* ASN.1 template for DH key.
  7306. * PKCS #3, 9 - DHParameter.
  7307. * (Also in: RFC 2786, 3)
  7308. */
  7309. static const ASNItem dhParamASN[] = {
  7310. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7311. /* prime */
  7312. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7313. /* base */
  7314. /* 2 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7315. /* privateValueLength */
  7316. /* 3 */ { 1, ASN_INTEGER, 0, 0, 1 },
  7317. };
  7318. /* Number of items in ASN.1 template for DH key. */
  7319. #define dhParamASN_Length (sizeof(dhParamASN) / sizeof(ASNItem))
  7320. #ifdef WOLFSSL_DH_EXTRA
  7321. /* ASN.1 template for DH key wrapped in PKCS #8 or SubjectPublicKeyInfo.
  7322. * PKCS #8: RFC 5208, 5 - PrivateKeyInfo
  7323. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  7324. * RFC 3279, 2.3.2 - DH in SubjectPublicKeyInfo
  7325. */
  7326. static const ASNItem dhKeyPkcs8ASN[] = {
  7327. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7328. /* 1 */ { 1, ASN_INTEGER, 0, 0, 1 },
  7329. /* 2 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7330. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7331. /* DHParameter */
  7332. /* 4 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  7333. /* p */
  7334. /* 5 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7335. /* g */
  7336. /* 6 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7337. /* q - factor of p-1 */
  7338. /* 7 */ { 3, ASN_INTEGER, 0, 0, 1 },
  7339. /* j - subgroup factor */
  7340. /* 8 */ { 3, ASN_INTEGER, 0, 0, 1 },
  7341. /* 9 */ { 3, ASN_SEQUENCE, 0, 0, 1 },
  7342. /* PrivateKey - PKCS #8 */
  7343. /* 10 */ { 1, ASN_OCTET_STRING, 0, 1, 2 },
  7344. /* 11 */ { 2, ASN_INTEGER, 0, 0, 0 },
  7345. /* PublicKey - SubjectPublicKeyInfo. */
  7346. /* 12 */ { 1, ASN_BIT_STRING, 0, 1, 2 },
  7347. /* 13 */ { 2, ASN_INTEGER, 0, 0, 0 },
  7348. };
  7349. #define dhKeyPkcs8ASN_Length (sizeof(dhKeyPkcs8ASN) / sizeof(ASNItem))
  7350. #endif
  7351. #endif
  7352. /* Decodes either PKCS#3 DH parameters or PKCS#8 DH key file (WOLFSSL_DH_EXTRA).
  7353. *
  7354. * See also wc_DhParamsLoad(). Loads directly into buffers rather than key
  7355. * object.
  7356. *
  7357. * @param [in] input BER/DER encoded data.
  7358. * @param [in, out] inOutIdx On in, start of DH key data.
  7359. * On out, end of DH key data.
  7360. * @param [in, out] key DH key object.
  7361. * @param [in] inSz Size of data in bytes.
  7362. * @return 0 on success.
  7363. * @return BAD_FUNC_ARG when input, inOutIDx or key is NULL.
  7364. * @return MEMORY_E when dynamic memory allocation fails.
  7365. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7366. * is invalid.
  7367. * @return BUFFER_E when data in buffer is too small.
  7368. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7369. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  7370. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  7371. * non-zero length.
  7372. * @return MP_INIT_E when the unable to initialize an mp_int.
  7373. * @return ASN_GETINT_E when the unable to convert data to an mp_int.
  7374. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  7375. */
  7376. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  7377. {
  7378. #ifndef WOLFSSL_ASN_TEMPLATE
  7379. int ret = 0;
  7380. int length;
  7381. #ifdef WOLFSSL_DH_EXTRA
  7382. #if !defined(HAVE_FIPS) || \
  7383. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  7384. word32 oid = 0, temp = 0;
  7385. #endif
  7386. #endif
  7387. WOLFSSL_ENTER("wc_DhKeyDecode");
  7388. if (inOutIdx == NULL)
  7389. return BAD_FUNC_ARG;
  7390. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7391. return ASN_PARSE_E;
  7392. #ifdef WOLFSSL_DH_EXTRA
  7393. #if !defined(HAVE_FIPS) || \
  7394. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  7395. temp = *inOutIdx;
  7396. #endif
  7397. #endif
  7398. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  7399. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  7400. ret = ASN_DH_KEY_E;
  7401. }
  7402. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  7403. mp_clear(&key->p);
  7404. ret = ASN_DH_KEY_E;
  7405. }
  7406. #ifdef WOLFSSL_DH_EXTRA
  7407. #if !defined(HAVE_FIPS) || \
  7408. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  7409. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  7410. if (ret == ASN_DH_KEY_E) {
  7411. *inOutIdx = temp;
  7412. /* the version (0) - private only (for public skip) */
  7413. if (GetASNInt(input, inOutIdx, &length, inSz) == 0) {
  7414. *inOutIdx += length;
  7415. }
  7416. /* Size of dhKeyAgreement section */
  7417. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7418. return ASN_PARSE_E;
  7419. /* Check for dhKeyAgreement */
  7420. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  7421. if (oid != DHk || ret < 0)
  7422. return ASN_DH_KEY_E;
  7423. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7424. return ASN_PARSE_E;
  7425. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  7426. return ASN_DH_KEY_E;
  7427. }
  7428. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  7429. mp_clear(&key->p);
  7430. return ASN_DH_KEY_E;
  7431. }
  7432. }
  7433. temp = *inOutIdx;
  7434. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  7435. if (ret > 0) {
  7436. /* Found Bit String */
  7437. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  7438. WOLFSSL_MSG("Found Public Key");
  7439. ret = 0;
  7440. }
  7441. } else {
  7442. *inOutIdx = temp;
  7443. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  7444. if (ret > 0) {
  7445. /* Found Octet String */
  7446. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  7447. WOLFSSL_MSG("Found Private Key");
  7448. /* Compute public */
  7449. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  7450. }
  7451. } else {
  7452. /* Don't use length from failed CheckBitString/GetOctetString */
  7453. *inOutIdx = temp;
  7454. ret = 0;
  7455. }
  7456. }
  7457. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  7458. #endif /* WOLFSSL_DH_EXTRA */
  7459. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  7460. return ret;
  7461. #else
  7462. #ifdef WOLFSSL_DH_EXTRA
  7463. DECL_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length);
  7464. #else
  7465. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  7466. #endif
  7467. int ret = 0;
  7468. /* Check input parameters are valid. */
  7469. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  7470. ret = BAD_FUNC_ARG;
  7471. }
  7472. #ifdef WOLFSSL_DH_EXTRA
  7473. ALLOC_ASNGETDATA(dataASN, dhKeyPkcs8ASN_Length, ret, key->heap);
  7474. #else
  7475. ALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, key->heap);
  7476. #endif
  7477. if (ret == 0) {
  7478. /* Initialize data and set mp_ints to hold p and g. */
  7479. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhParamASN_Length);
  7480. GetASN_MP(&dataASN[1], &key->p);
  7481. GetASN_MP(&dataASN[2], &key->g);
  7482. /* Try simple PKCS #3 template. */
  7483. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  7484. inOutIdx, inSz);
  7485. #ifdef WOLFSSL_DH_EXTRA
  7486. if (ret != 0) {
  7487. /* Initialize data and set mp_ints to hold p, g, q, priv and pub. */
  7488. XMEMSET(dataASN, 0, sizeof(*dataASN) * dhKeyPkcs8ASN_Length);
  7489. GetASN_ExpBuffer(&dataASN[3], keyDhOid, sizeof(keyDhOid));
  7490. GetASN_MP(&dataASN[5], &key->p);
  7491. GetASN_MP(&dataASN[6], &key->g);
  7492. GetASN_MP(&dataASN[7], &key->q);
  7493. GetASN_MP(&dataASN[11], &key->priv);
  7494. GetASN_MP(&dataASN[13], &key->pub);
  7495. /* Try PKCS #8 wrapped template. */
  7496. ret = GetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, 1,
  7497. input, inOutIdx, inSz);
  7498. if (ret == 0) {
  7499. if ((dataASN[11].length != 0) && (dataASN[1].length == 0)) {
  7500. ret = ASN_PARSE_E;
  7501. }
  7502. else if ((dataASN[13].length != 0) &&
  7503. (dataASN[1].length != 0)) {
  7504. ret = ASN_PARSE_E;
  7505. }
  7506. }
  7507. }
  7508. #endif
  7509. }
  7510. FREE_ASNGETDATA(dataASN, key->heap);
  7511. return ret;
  7512. #endif /* WOLFSSL_ASN_TEMPLATE */
  7513. }
  7514. #ifdef WOLFSSL_DH_EXTRA
  7515. /* Export DH Key (private or public) */
  7516. int wc_DhKeyToDer(DhKey* key, byte* output, word32* outSz, int exportPriv)
  7517. {
  7518. #ifndef WOLFSSL_ASN_TEMPLATE
  7519. int ret, privSz = 0, pubSz = 0, keySz;
  7520. word32 idx, total;
  7521. if (key == NULL || outSz == NULL) {
  7522. return BAD_FUNC_ARG;
  7523. }
  7524. /* determine size */
  7525. if (exportPriv) {
  7526. /* octect string: priv */
  7527. privSz = SetASNIntMP(&key->priv, -1, NULL);
  7528. idx = 1 + SetLength(privSz, NULL) + privSz; /* +1 for ASN_OCTET_STRING */
  7529. }
  7530. else {
  7531. /* bit string: public */
  7532. pubSz = SetASNIntMP(&key->pub, -1, NULL);
  7533. idx = SetBitString(pubSz, 0, NULL) + pubSz;
  7534. }
  7535. keySz = idx;
  7536. /* DH Parameters sequence with P and G */
  7537. total = 0;
  7538. ret = wc_DhParamsToDer(key, NULL, &total);
  7539. if (ret != LENGTH_ONLY_E)
  7540. return ret;
  7541. idx += total;
  7542. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  7543. idx += SetObjectId(sizeof(keyDhOid), NULL);
  7544. idx += sizeof(keyDhOid);
  7545. /* sequence - all but pub/priv */
  7546. idx += SetSequence(idx - keySz, NULL);
  7547. if (exportPriv) {
  7548. /* version: 0 (ASN_INTEGER, 0x01, 0x00) */
  7549. idx += 3;
  7550. }
  7551. /* sequence */
  7552. total = idx + SetSequence(idx, NULL);
  7553. /* if no output, then just getting size */
  7554. if (output == NULL) {
  7555. *outSz = total;
  7556. return LENGTH_ONLY_E;
  7557. }
  7558. /* make sure output fits in buffer */
  7559. if (total > *outSz) {
  7560. return BUFFER_E;
  7561. }
  7562. total = idx;
  7563. /* sequence */
  7564. idx = SetSequence(total, output);
  7565. if (exportPriv) {
  7566. /* version: 0 */
  7567. idx += SetMyVersion(0, output + idx, 0);
  7568. }
  7569. /* sequence - all but pub/priv */
  7570. idx += SetSequence(total - keySz - idx, output + idx);
  7571. /* object dhKeyAgreement 1.2.840.113549.1.3.1 */
  7572. idx += SetObjectId(sizeof(keyDhOid), output + idx);
  7573. XMEMCPY(output + idx, keyDhOid, sizeof(keyDhOid));
  7574. idx += sizeof(keyDhOid);
  7575. /* DH Parameters sequence with P and G */
  7576. total = *outSz - idx;
  7577. ret = wc_DhParamsToDer(key, output + idx, &total);
  7578. if (ret < 0)
  7579. return ret;
  7580. idx += total;
  7581. /* octect string: priv */
  7582. if (exportPriv) {
  7583. idx += SetOctetString(privSz, output + idx);
  7584. idx += SetASNIntMP(&key->priv, -1, output + idx);
  7585. }
  7586. else {
  7587. /* bit string: public */
  7588. idx += SetBitString(pubSz, 0, output + idx);
  7589. idx += SetASNIntMP(&key->pub, -1, output + idx);
  7590. }
  7591. *outSz = idx;
  7592. return idx;
  7593. #else
  7594. ASNSetData dataASN[dhKeyPkcs8ASN_Length];
  7595. int ret = 0;
  7596. int sz;
  7597. WOLFSSL_ENTER("wc_DhKeyToDer");
  7598. XMEMSET(dataASN, 0, sizeof(dataASN));
  7599. SetASN_Int8Bit(&dataASN[1], 0);
  7600. SetASN_OID(&dataASN[3], DHk, oidKeyType);
  7601. /* Set mp_int containing p and g. */
  7602. SetASN_MP(&dataASN[5], &key->p);
  7603. SetASN_MP(&dataASN[6], &key->g);
  7604. dataASN[7].noOut = 1;
  7605. dataASN[8].noOut = 1;
  7606. dataASN[9].noOut = 1;
  7607. if (exportPriv) {
  7608. SetASN_MP(&dataASN[11], &key->priv);
  7609. dataASN[12].noOut = 1;
  7610. dataASN[13].noOut = 1;
  7611. }
  7612. else {
  7613. dataASN[1].noOut = 1;
  7614. dataASN[10].noOut = 1;
  7615. dataASN[11].noOut = 1;
  7616. SetASN_MP(&dataASN[13], &key->pub);
  7617. }
  7618. /* Calculate the size of the DH parameters. */
  7619. ret = SizeASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, &sz);
  7620. if (output == NULL) {
  7621. *outSz = sz;
  7622. ret = LENGTH_ONLY_E;
  7623. }
  7624. /* Check buffer is big enough for encoding. */
  7625. if ((ret == 0) && ((int)*outSz < sz)) {
  7626. ret = BUFFER_E;
  7627. }
  7628. if (ret == 0) {
  7629. /* Encode the DH parameters into buffer. */
  7630. SetASN_Items(dhKeyPkcs8ASN, dataASN, dhKeyPkcs8ASN_Length, output);
  7631. /* Set the actual encoding size. */
  7632. *outSz = sz;
  7633. /* Return the actual encoding size. */
  7634. ret = sz;
  7635. }
  7636. return ret;
  7637. #endif
  7638. }
  7639. int wc_DhPubKeyToDer(DhKey* key, byte* out, word32* outSz)
  7640. {
  7641. return wc_DhKeyToDer(key, out, outSz, 0);
  7642. }
  7643. int wc_DhPrivKeyToDer(DhKey* key, byte* out, word32* outSz)
  7644. {
  7645. return wc_DhKeyToDer(key, out, outSz, 1);
  7646. }
  7647. /* Convert DH key parameters to DER format, write to output (outSz)
  7648. * If output is NULL then max expected size is set to outSz and LENGTH_ONLY_E is
  7649. * returned.
  7650. *
  7651. * Note : static function due to redefinition complications with DhKey and FIPS
  7652. * version 2 build.
  7653. *
  7654. * return bytes written on success */
  7655. int wc_DhParamsToDer(DhKey* key, byte* output, word32* outSz)
  7656. {
  7657. #ifndef WOLFSSL_ASN_TEMPLATE
  7658. word32 idx, total;
  7659. if (key == NULL || outSz == NULL) {
  7660. return BAD_FUNC_ARG;
  7661. }
  7662. /* determine size */
  7663. /* integer - g */
  7664. idx = SetASNIntMP(&key->g, -1, NULL);
  7665. /* integer - p */
  7666. idx += SetASNIntMP(&key->p, -1, NULL);
  7667. total = idx;
  7668. /* sequence */
  7669. idx += SetSequence(idx, NULL);
  7670. if (output == NULL) {
  7671. *outSz = idx;
  7672. return LENGTH_ONLY_E;
  7673. }
  7674. /* make sure output fits in buffer */
  7675. if (idx > *outSz) {
  7676. return BUFFER_E;
  7677. }
  7678. /* write DH parameters */
  7679. /* sequence - for P and G only */
  7680. idx = SetSequence(total, output);
  7681. /* integer - p */
  7682. idx += SetASNIntMP(&key->p, -1, output + idx);
  7683. /* integer - g */
  7684. idx += SetASNIntMP(&key->g, -1, output + idx);
  7685. *outSz = idx;
  7686. return idx;
  7687. #else
  7688. ASNSetData dataASN[dhParamASN_Length];
  7689. int ret = 0;
  7690. int sz;
  7691. WOLFSSL_ENTER("wc_DhParamsToDer");
  7692. if (key == NULL || outSz == NULL) {
  7693. ret = BAD_FUNC_ARG;
  7694. }
  7695. if (ret == 0) {
  7696. XMEMSET(dataASN, 0, sizeof(dataASN));
  7697. /* Set mp_int containing p and g. */
  7698. SetASN_MP(&dataASN[1], &key->p);
  7699. SetASN_MP(&dataASN[2], &key->g);
  7700. /* privateValueLength not encoded. */
  7701. dataASN[3].noOut = 1;
  7702. /* Calculate the size of the DH parameters. */
  7703. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  7704. }
  7705. if ((ret == 0) && (output == NULL)) {
  7706. *outSz = sz;
  7707. ret = LENGTH_ONLY_E;
  7708. }
  7709. /* Check buffer is big enough for encoding. */
  7710. if ((ret == 0) && ((int)*outSz < sz)) {
  7711. ret = BUFFER_E;
  7712. }
  7713. if (ret == 0) {
  7714. /* Encode the DH parameters into buffer. */
  7715. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, output);
  7716. /* Set the actual encoding size. */
  7717. *outSz = sz;
  7718. /* Return count of bytes written. */
  7719. ret = sz;
  7720. }
  7721. return ret;
  7722. #endif
  7723. }
  7724. #endif /* WOLFSSL_DH_EXTRA */
  7725. /* Decode DH parameters.
  7726. *
  7727. * PKCS #3, 9 - DHParameter.
  7728. * (Also in: RFC 2786, 3)
  7729. *
  7730. * @param [in] input Buffer holding BER encoded data.
  7731. * @param [in, out] inOutIdx On in, start of RSA public key.
  7732. * On out, start of ASN.1 item after RSA public key.
  7733. * @param [in] inSz Number of bytes in buffer.
  7734. * @param [in, out] p Buffer to hold prime.
  7735. * @param [out] pInOutSz On in, size of buffer to hold prime in bytes.
  7736. * On out, size of prime in bytes.
  7737. * @param [in, out] g Buffer to hold base.
  7738. * @param [out] gInOutSz On in, size of buffer to hold base in bytes.
  7739. * On out, size of base in bytes.
  7740. * @return 0 on success.
  7741. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7742. * is invalid.
  7743. * @return BUFFER_E when data in buffer is too small.
  7744. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  7745. */
  7746. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  7747. byte* g, word32* gInOutSz)
  7748. {
  7749. #ifndef WOLFSSL_ASN_TEMPLATE
  7750. word32 idx = 0;
  7751. int ret;
  7752. int length;
  7753. if (GetSequence(input, &idx, &length, inSz) <= 0)
  7754. return ASN_PARSE_E;
  7755. ret = GetASNInt(input, &idx, &length, inSz);
  7756. if (ret != 0)
  7757. return ret;
  7758. if (length <= (int)*pInOutSz) {
  7759. XMEMCPY(p, &input[idx], length);
  7760. *pInOutSz = length;
  7761. }
  7762. else {
  7763. return BUFFER_E;
  7764. }
  7765. idx += length;
  7766. ret = GetASNInt(input, &idx, &length, inSz);
  7767. if (ret != 0)
  7768. return ret;
  7769. if (length <= (int)*gInOutSz) {
  7770. XMEMCPY(g, &input[idx], length);
  7771. *gInOutSz = length;
  7772. }
  7773. else {
  7774. return BUFFER_E;
  7775. }
  7776. return 0;
  7777. #else
  7778. DECL_ASNGETDATA(dataASN, dhParamASN_Length);
  7779. word32 idx = 0;
  7780. int ret = 0;
  7781. /* Make sure pointers are valid before use. */
  7782. if ((input == NULL) || (p == NULL) || (pInOutSz == NULL) || (g == NULL) ||
  7783. (gInOutSz == NULL)) {
  7784. ret = BAD_FUNC_ARG;
  7785. }
  7786. CALLOC_ASNGETDATA(dataASN, dhParamASN_Length, ret, NULL);
  7787. if (ret == 0) {
  7788. /* Set the buffers to copy p and g into. */
  7789. GetASN_Buffer(&dataASN[1], p, pInOutSz);
  7790. GetASN_Buffer(&dataASN[2], g, gInOutSz);
  7791. /* Decode the DH Parameters. */
  7792. ret = GetASN_Items(dhParamASN, dataASN, dhParamASN_Length, 1, input,
  7793. &idx, inSz);
  7794. }
  7795. FREE_ASNGETDATA(dataASN, NULL);
  7796. return ret;
  7797. #endif /* WOLFSSL_ASN_TEMPLATE */
  7798. }
  7799. #endif /* !NO_DH */
  7800. #ifndef NO_DSA
  7801. static mp_int* GetDsaInt(DsaKey* key, int idx)
  7802. {
  7803. if (idx == 0)
  7804. return &key->p;
  7805. if (idx == 1)
  7806. return &key->q;
  7807. if (idx == 2)
  7808. return &key->g;
  7809. if (idx == 3)
  7810. return &key->y;
  7811. if (idx == 4)
  7812. return &key->x;
  7813. return NULL;
  7814. }
  7815. #ifdef WOLFSSL_ASN_TEMPLATE
  7816. /* ASN.1 template for DSA public and private keys.
  7817. * Public key: seq, p, q, g, y
  7818. * Private key: seq, version, p, q, g, y, x
  7819. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  7820. */
  7821. static const ASNItem dsaKeyASN[] = {
  7822. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7823. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7824. /* 2 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7825. /* 3 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7826. /* 4 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7827. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7828. /* 6 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7829. };
  7830. /* Number of items in ASN.1 template for DSA private key. */
  7831. #define dsaKeyASN_Length (sizeof(dsaKeyASN) / sizeof(ASNItem))
  7832. /* Number of items in ASN.1 template for DSA public key. */
  7833. #define dsaPublicKeyASN_Length ((sizeof(dsaKeyASN) / sizeof(ASNItem)) - 2)
  7834. /* ASN.1 template for PublicKeyInfo with DSA.
  7835. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  7836. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  7837. */
  7838. static const ASNItem dsaPubKeyASN[] = {
  7839. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7840. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  7841. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  7842. /* 3 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  7843. /* p */
  7844. /* 4 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7845. /* q */
  7846. /* 5 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7847. /* g */
  7848. /* 6 */ { 3, ASN_INTEGER, 0, 0, 0 },
  7849. /* 7 */ { 1, ASN_BIT_STRING, 0, 1, 1 },
  7850. /* y */
  7851. /* 8 */ { 2, ASN_INTEGER, 0, 0, 0 },
  7852. };
  7853. /* Number of items in ASN.1 template for PublicKeyInfo with DSA. */
  7854. #define dsaPubKeyASN_Length (sizeof(dsaPubKeyASN) / sizeof(ASNItem))
  7855. #endif /* WOLFSSL_ASN_TEMPLATE */
  7856. /* Decode DSA public key.
  7857. *
  7858. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  7859. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  7860. *
  7861. * @param [in] input Buffer holding BER encoded data.
  7862. * @param [in, out] inOutIdx On in, start of DSA public key.
  7863. * On out, start of ASN.1 item after DSA public key.
  7864. * @param [in, out] key DSA key object.
  7865. * @param [in] inSz Number of bytes in buffer.
  7866. * @return 0 on success.
  7867. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7868. * is invalid.
  7869. * @return BUFFER_E when data in buffer is too small.
  7870. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  7871. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  7872. * non-zero length.
  7873. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  7874. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  7875. */
  7876. int wc_DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  7877. word32 inSz)
  7878. {
  7879. #ifndef WOLFSSL_ASN_TEMPLATE
  7880. int length;
  7881. int ret = 0;
  7882. word32 oid;
  7883. word32 maxIdx;
  7884. if (input == NULL || inOutIdx == NULL || key == NULL)
  7885. return BAD_FUNC_ARG;
  7886. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7887. return ASN_PARSE_E;
  7888. maxIdx = (word32)(*inOutIdx + length);
  7889. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  7890. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  7891. GetInt(&key->g, input, inOutIdx, maxIdx) < 0 ||
  7892. GetInt(&key->y, input, inOutIdx, maxIdx) < 0 )
  7893. ret = ASN_DH_KEY_E;
  7894. if (ret != 0) {
  7895. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7896. return ASN_PARSE_E;
  7897. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  7898. if (ret != 0)
  7899. return ret;
  7900. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7901. return ASN_PARSE_E;
  7902. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  7903. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  7904. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  7905. return ASN_DH_KEY_E;
  7906. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  7907. return ASN_PARSE_E;
  7908. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  7909. return ASN_DH_KEY_E;
  7910. ret = 0;
  7911. }
  7912. key->type = DSA_PUBLIC;
  7913. return ret;
  7914. #else
  7915. /* dsaPubKeyASN is longer than dsaPublicKeyASN. */
  7916. DECL_ASNGETDATA(dataASN, dsaPubKeyASN_Length);
  7917. int ret = 0;
  7918. int i;
  7919. /* Validated parameters. */
  7920. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  7921. ret = BAD_FUNC_ARG;
  7922. }
  7923. ALLOC_ASNGETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  7924. if (ret == 0) {
  7925. /* Clear dynamic data items. */
  7926. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPublicKeyASN_Length);
  7927. /* p, q, g, y */
  7928. for (i = 0; i < DSA_INTS - 1; i++)
  7929. GetASN_MP(&dataASN[1 + i], GetDsaInt(key, i));
  7930. /* Parse as simple form. */
  7931. ret = GetASN_Items(dsaKeyASN, dataASN, dsaPublicKeyASN_Length, 1, input,
  7932. inOutIdx, inSz);
  7933. if (ret != 0) {
  7934. /* Clear dynamic data items. */
  7935. XMEMSET(dataASN, 0, sizeof(ASNGetData) * dsaPubKeyASN_Length);
  7936. /* Set DSA OID to expect. */
  7937. GetASN_ExpBuffer(&dataASN[2], keyDsaOid, sizeof(keyDsaOid));
  7938. /* p, q, g */
  7939. for (i = 0; i < DSA_INTS - 2; i++)
  7940. GetASN_MP(&dataASN[4 + i], GetDsaInt(key, i));
  7941. /* y */
  7942. GetASN_MP(&dataASN[8], GetDsaInt(key, i));
  7943. /* Parse as SubjectPublicKeyInfo. */
  7944. ret = GetASN_Items(dsaPubKeyASN, dataASN, dsaPubKeyASN_Length, 1,
  7945. input, inOutIdx, inSz);
  7946. }
  7947. }
  7948. if (ret == 0) {
  7949. /* Data parsed - set type of key parsed. */
  7950. key->type = DSA_PUBLIC;
  7951. }
  7952. FREE_ASNGETDATA(dataASN, key->heap);
  7953. return ret;
  7954. #endif
  7955. }
  7956. int wc_DsaParamsDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  7957. word32 inSz)
  7958. {
  7959. int length;
  7960. word32 maxIdx;
  7961. if (input == NULL || inOutIdx == NULL || key == NULL)
  7962. return BAD_FUNC_ARG;
  7963. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  7964. return ASN_PARSE_E;
  7965. maxIdx = (word32)(*inOutIdx + length);
  7966. if (GetInt(&key->p, input, inOutIdx, maxIdx) < 0 ||
  7967. GetInt(&key->q, input, inOutIdx, maxIdx) < 0 ||
  7968. GetInt(&key->g, input, inOutIdx, maxIdx) < 0)
  7969. return ASN_DH_KEY_E;
  7970. return 0;
  7971. }
  7972. #ifdef WOLFSSL_ASN_TEMPLATE
  7973. /* ASN.1 template for a DSA key holding private key in an OCTET_STRING. */
  7974. static const ASNItem dsaKeyOctASN[] = {
  7975. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  7976. /* p */
  7977. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7978. /* q */
  7979. /* 2 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7980. /* g */
  7981. /* 3 */ { 1, ASN_INTEGER, 0, 0, 0 },
  7982. /* Private key */
  7983. /* 4 */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  7984. /* x */
  7985. /* 5 */ { 2, ASN_INTEGER, 0, 0, 0 },
  7986. };
  7987. /* Number of items in ASN.1 template for a DSA key (OCTET_STRING version). */
  7988. #define dsaKeyOctASN_Length (sizeof(dsaKeyOctASN) / sizeof(ASNItem))
  7989. #endif
  7990. /* Decode DSA private key.
  7991. *
  7992. * @param [in] input Buffer holding BER encoded data.
  7993. * @param [in, out] inOutIdx On in, start of DSA public key.
  7994. * On out, start of ASN.1 item after DSA public key.
  7995. * @param [in, out] key DSA key object.
  7996. * @param [in] inSz Number of bytes in buffer.
  7997. * @return 0 on success.
  7998. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  7999. * is invalid.
  8000. * @return BUFFER_E when data in buffer is too small.
  8001. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8002. * non-zero length.
  8003. */
  8004. int wc_DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  8005. word32 inSz)
  8006. {
  8007. #ifndef WOLFSSL_ASN_TEMPLATE
  8008. int length, version, ret = 0, temp = 0;
  8009. word32 algId = 0;
  8010. /* Sanity checks on input */
  8011. if (input == NULL || inOutIdx == NULL || key == NULL) {
  8012. return BAD_FUNC_ARG;
  8013. }
  8014. /* if has pkcs8 header skip it */
  8015. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  8016. /* ignore error, did not have pkcs8 header */
  8017. }
  8018. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8019. return ASN_PARSE_E;
  8020. temp = (int)*inOutIdx;
  8021. /* Default case expects a certificate with OctetString but no version ID */
  8022. ret = GetInt(&key->p, input, inOutIdx, inSz);
  8023. if (ret < 0) {
  8024. mp_clear(&key->p);
  8025. ret = ASN_PARSE_E;
  8026. }
  8027. else {
  8028. ret = GetInt(&key->q, input, inOutIdx, inSz);
  8029. if (ret < 0) {
  8030. mp_clear(&key->p);
  8031. mp_clear(&key->q);
  8032. ret = ASN_PARSE_E;
  8033. }
  8034. else {
  8035. ret = GetInt(&key->g, input, inOutIdx, inSz);
  8036. if (ret < 0) {
  8037. mp_clear(&key->p);
  8038. mp_clear(&key->q);
  8039. mp_clear(&key->g);
  8040. ret = ASN_PARSE_E;
  8041. }
  8042. else {
  8043. ret = GetOctetString(input, inOutIdx, &length, inSz);
  8044. if (ret < 0) {
  8045. mp_clear(&key->p);
  8046. mp_clear(&key->q);
  8047. mp_clear(&key->g);
  8048. ret = ASN_PARSE_E;
  8049. }
  8050. else {
  8051. ret = GetInt(&key->y, input, inOutIdx, inSz);
  8052. if (ret < 0) {
  8053. mp_clear(&key->p);
  8054. mp_clear(&key->q);
  8055. mp_clear(&key->g);
  8056. mp_clear(&key->y);
  8057. ret = ASN_PARSE_E;
  8058. }
  8059. }
  8060. }
  8061. }
  8062. }
  8063. /* An alternate pass if default certificate fails parsing */
  8064. if (ret == ASN_PARSE_E) {
  8065. *inOutIdx = temp;
  8066. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  8067. return ASN_PARSE_E;
  8068. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  8069. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  8070. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  8071. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  8072. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  8073. return ASN_DH_KEY_E;
  8074. }
  8075. key->type = DSA_PRIVATE;
  8076. return 0;
  8077. #else
  8078. /* dsaKeyASN is longer than dsaKeyOctASN. */
  8079. DECL_ASNGETDATA(dataASN, dsaKeyASN_Length);
  8080. int ret = 0;
  8081. int i;
  8082. byte version = 0;
  8083. /* Sanity checks on input */
  8084. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL)) {
  8085. ret = BAD_FUNC_ARG;
  8086. }
  8087. ALLOC_ASNGETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  8088. if (ret == 0) {
  8089. /* Initialize key data and set mp_ints for params and priv/pub. */
  8090. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyOctASN_Length);
  8091. GetASN_Int8Bit(&dataASN[1], &version);
  8092. for (i = 0; i < DSA_INTS - 2; i++) {
  8093. GetASN_MP(&dataASN[1 + i], GetDsaInt(key, i));
  8094. }
  8095. GetASN_MP(&dataASN[2 + i], GetDsaInt(key, i));
  8096. /* Try simple form. */
  8097. ret = GetASN_Items(dsaKeyOctASN, dataASN, dsaKeyOctASN_Length, 1, input,
  8098. inOutIdx, inSz);
  8099. if ((ret == 0) && (version != 0)) {
  8100. ret = ASN_PARSE_E;
  8101. }
  8102. else if (ret != 0) {
  8103. /* Initialize key data and set mp_ints for params and priv/pub. */
  8104. XMEMSET(dataASN, 0, sizeof(*dataASN) * dsaKeyASN_Length);
  8105. for (i = 0; i < DSA_INTS; i++) {
  8106. GetASN_MP(&dataASN[2 + i], GetDsaInt(key, i));
  8107. }
  8108. /* Try simple OCTET_STRING form. */
  8109. ret = GetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, 1, input,
  8110. inOutIdx, inSz);
  8111. }
  8112. }
  8113. if (ret == 0) {
  8114. /* Set the contents to be a private key. */
  8115. key->type = DSA_PRIVATE;
  8116. }
  8117. FREE_ASNGETDATA(dataASN, key->heap);
  8118. return ret;
  8119. #endif
  8120. }
  8121. #ifndef WOLFSSL_ASN_TEMPLATE
  8122. /* Release Tmp DSA resources */
  8123. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap, int ints)
  8124. {
  8125. int i;
  8126. for (i = 0; i < ints; i++)
  8127. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  8128. (void)heap;
  8129. }
  8130. #endif /* !WOLFSSL_ASN_TEMPLATE */
  8131. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  8132. defined(WOLFSSL_CERT_GEN))
  8133. /* Encode a DSA public key into buffer.
  8134. *
  8135. * @param [out] output Buffer to hold encoded data.
  8136. * @param [in] key DSA key object.
  8137. * @param [out] outLen Length of buffer.
  8138. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  8139. * @return Size of encoded data in bytes on success.
  8140. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  8141. * than a minimal size (5 bytes), or buffer size is smaller than
  8142. * encoding size.
  8143. * @return MEMORY_E when dynamic memory allocation fails.
  8144. */
  8145. int wc_SetDsaPublicKey(byte* output, DsaKey* key, int outLen, int with_header)
  8146. {
  8147. #ifndef WOLFSSL_ASN_TEMPLATE
  8148. /* p, g, q = DSA params, y = public exponent */
  8149. #ifdef WOLFSSL_SMALL_STACK
  8150. byte* p = NULL;
  8151. byte* g = NULL;
  8152. byte* q = NULL;
  8153. byte* y = NULL;
  8154. #else
  8155. byte p[MAX_DSA_INT_SZ];
  8156. byte g[MAX_DSA_INT_SZ];
  8157. byte q[MAX_DSA_INT_SZ];
  8158. byte y[MAX_DSA_INT_SZ];
  8159. #endif
  8160. byte innerSeq[MAX_SEQ_SZ];
  8161. byte outerSeq[MAX_SEQ_SZ];
  8162. byte bitString[1 + MAX_LENGTH_SZ + 1];
  8163. int idx, pSz, gSz, qSz, ySz, innerSeqSz, outerSeqSz, bitStringSz = 0;
  8164. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  8165. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  8166. return BAD_FUNC_ARG;
  8167. }
  8168. /* p */
  8169. #ifdef WOLFSSL_SMALL_STACK
  8170. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8171. if (p == NULL)
  8172. return MEMORY_E;
  8173. #endif
  8174. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  8175. WOLFSSL_MSG("SetASNIntMP Error with p");
  8176. #ifdef WOLFSSL_SMALL_STACK
  8177. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8178. #endif
  8179. return pSz;
  8180. }
  8181. /* q */
  8182. #ifdef WOLFSSL_SMALL_STACK
  8183. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8184. if (q == NULL)
  8185. return MEMORY_E;
  8186. #endif
  8187. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  8188. WOLFSSL_MSG("SetASNIntMP Error with q");
  8189. #ifdef WOLFSSL_SMALL_STACK
  8190. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8191. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8192. #endif
  8193. return qSz;
  8194. }
  8195. /* g */
  8196. #ifdef WOLFSSL_SMALL_STACK
  8197. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8198. if (g == NULL)
  8199. return MEMORY_E;
  8200. #endif
  8201. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  8202. WOLFSSL_MSG("SetASNIntMP Error with g");
  8203. #ifdef WOLFSSL_SMALL_STACK
  8204. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8205. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8206. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8207. #endif
  8208. return gSz;
  8209. }
  8210. /* y */
  8211. #ifdef WOLFSSL_SMALL_STACK
  8212. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8213. if (y == NULL)
  8214. return MEMORY_E;
  8215. #endif
  8216. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  8217. WOLFSSL_MSG("SetASNIntMP Error with y");
  8218. #ifdef WOLFSSL_SMALL_STACK
  8219. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8220. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8221. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8222. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8223. #endif
  8224. return ySz;
  8225. }
  8226. innerSeqSz = SetSequence(pSz + qSz + gSz, innerSeq);
  8227. /* check output size */
  8228. if ((innerSeqSz + pSz + qSz + gSz) > outLen) {
  8229. #ifdef WOLFSSL_SMALL_STACK
  8230. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8231. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8232. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8233. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8234. #endif
  8235. WOLFSSL_MSG("Error, output size smaller than outlen");
  8236. return BUFFER_E;
  8237. }
  8238. if (with_header) {
  8239. int algoSz;
  8240. #ifdef WOLFSSL_SMALL_STACK
  8241. byte* algo = NULL;
  8242. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8243. if (algo == NULL) {
  8244. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8245. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8246. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8247. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8248. return MEMORY_E;
  8249. }
  8250. #else
  8251. byte algo[MAX_ALGO_SZ];
  8252. #endif
  8253. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  8254. bitStringSz = SetBitString(ySz, 0, bitString);
  8255. outerSeqSz = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz,
  8256. outerSeq);
  8257. idx = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz + bitStringSz +
  8258. ySz + outerSeqSz, output);
  8259. /* check output size */
  8260. if ((idx + algoSz + bitStringSz + innerSeqSz + pSz + qSz + gSz + ySz) >
  8261. outLen) {
  8262. #ifdef WOLFSSL_SMALL_STACK
  8263. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8264. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8265. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8266. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8267. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8268. #endif
  8269. WOLFSSL_MSG("Error, output size smaller than outlen");
  8270. return BUFFER_E;
  8271. }
  8272. /* outerSeq */
  8273. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  8274. idx += outerSeqSz;
  8275. /* algo */
  8276. XMEMCPY(output + idx, algo, algoSz);
  8277. idx += algoSz;
  8278. #ifdef WOLFSSL_SMALL_STACK
  8279. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8280. #endif
  8281. } else {
  8282. idx = 0;
  8283. }
  8284. /* innerSeq */
  8285. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  8286. idx += innerSeqSz;
  8287. /* p */
  8288. XMEMCPY(output + idx, p, pSz);
  8289. idx += pSz;
  8290. /* q */
  8291. XMEMCPY(output + idx, q, qSz);
  8292. idx += qSz;
  8293. /* g */
  8294. XMEMCPY(output + idx, g, gSz);
  8295. idx += gSz;
  8296. /* bit string */
  8297. if (bitStringSz > 0) {
  8298. XMEMCPY(output + idx, bitString, bitStringSz);
  8299. idx += bitStringSz;
  8300. }
  8301. /* y */
  8302. XMEMCPY(output + idx, y, ySz);
  8303. idx += ySz;
  8304. #ifdef WOLFSSL_SMALL_STACK
  8305. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8306. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8307. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8308. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8309. #endif
  8310. return idx;
  8311. #else
  8312. DECL_ASNSETDATA(dataASN, dsaPubKeyASN_Length);
  8313. int ret = 0;
  8314. int i;
  8315. int sz;
  8316. int o;
  8317. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  8318. if ((output == NULL) || (key == NULL) || (outLen < MAX_SEQ_SZ)) {
  8319. ret = BAD_FUNC_ARG;
  8320. }
  8321. CALLOC_ASNSETDATA(dataASN, dsaPubKeyASN_Length, ret, key->heap);
  8322. if (ret == 0) {
  8323. /* With header - include the SubjectPublicKeyInfo wrapping. */
  8324. if (with_header) {
  8325. o = 0;
  8326. /* Set the algorithm OID to write out. */
  8327. SetASN_OID(&dataASN[2], DSAk, oidKeyType);
  8328. }
  8329. else {
  8330. o = 3;
  8331. /* Skip BIT_STRING but include 'y'. */
  8332. dataASN[7].noOut = 1;
  8333. }
  8334. /* Set the mp_ints to encode - parameters and public value. */
  8335. for (i = 0; i < DSA_INTS - 2; i++) {
  8336. SetASN_MP(&dataASN[4 + i], GetDsaInt(key, i));
  8337. }
  8338. SetASN_MP(&dataASN[5 + i], GetDsaInt(key, i));
  8339. /* Calculate size of the encoding. */
  8340. ret = SizeASN_Items(dsaPubKeyASN + o, dataASN, dsaPubKeyASN_Length - o,
  8341. &sz);
  8342. }
  8343. /* Check buffer is big enough for encoding. */
  8344. if ((ret == 0) && (sz > (int)outLen)) {
  8345. ret = BAD_FUNC_ARG;
  8346. }
  8347. if (ret == 0) {
  8348. /* Encode the DSA public key into output buffer.
  8349. * 'o' indicates offset when no header.
  8350. */
  8351. SetASN_Items(dsaPubKeyASN + o, dataASN, dsaPubKeyASN_Length - o,
  8352. output);
  8353. /* Return the size of the encoding. */
  8354. ret = sz;
  8355. }
  8356. FREE_ASNSETDATA(dataASN, key->heap);
  8357. return ret;
  8358. #endif /* WOLFSSL_ASN_TEMPLATE */
  8359. }
  8360. /* Encode a DSA public key into buffer.
  8361. *
  8362. * @param [out] output Buffer to hold encoded data.
  8363. * @param [in] key DSA key object.
  8364. * @param [out] outLen Length of buffer.
  8365. * @param [out] with_header Whether to encode in SubjectPublicKeyInfo block.
  8366. * @return Size of encoded data in bytes on success.
  8367. * @return BAD_FUNC_ARG when output or key is NULL, or buffer size is less
  8368. * than a minimal size (5 bytes), or buffer size is smaller than
  8369. * encoding size.
  8370. * @return MEMORY_E when dynamic memory allocation fails.
  8371. */
  8372. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  8373. {
  8374. return wc_SetDsaPublicKey(output, key, inLen, 1);
  8375. }
  8376. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  8377. static int DsaKeyIntsToDer(DsaKey* key, byte* output, word32* inLen,
  8378. int ints, int includeVersion)
  8379. {
  8380. #ifndef WOLFSSL_ASN_TEMPLATE
  8381. word32 seqSz = 0, verSz = 0, rawLen, intTotalLen = 0;
  8382. word32 sizes[DSA_INTS];
  8383. int i, j, outLen, ret = 0, mpSz;
  8384. byte seq[MAX_SEQ_SZ];
  8385. byte ver[MAX_VERSION_SZ];
  8386. byte* tmps[DSA_INTS];
  8387. if (ints > DSA_INTS || inLen == NULL)
  8388. return BAD_FUNC_ARG;
  8389. XMEMSET(sizes, 0, sizeof(sizes));
  8390. for (i = 0; i < ints; i++)
  8391. tmps[i] = NULL;
  8392. /* write all big ints from key to DER tmps */
  8393. for (i = 0; i < ints; i++) {
  8394. mp_int* keyInt = GetDsaInt(key, i);
  8395. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  8396. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  8397. DYNAMIC_TYPE_DSA);
  8398. if (tmps[i] == NULL) {
  8399. ret = MEMORY_E;
  8400. break;
  8401. }
  8402. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  8403. if (mpSz < 0) {
  8404. ret = mpSz;
  8405. break;
  8406. }
  8407. intTotalLen += (sizes[i] = mpSz);
  8408. }
  8409. if (ret != 0) {
  8410. FreeTmpDsas(tmps, key->heap, ints);
  8411. return ret;
  8412. }
  8413. /* make headers */
  8414. if (includeVersion)
  8415. verSz = SetMyVersion(0, ver, FALSE);
  8416. seqSz = SetSequence(verSz + intTotalLen, seq);
  8417. outLen = seqSz + verSz + intTotalLen;
  8418. *inLen = outLen;
  8419. if (output == NULL) {
  8420. FreeTmpDsas(tmps, key->heap, ints);
  8421. return LENGTH_ONLY_E;
  8422. }
  8423. if (outLen > (int)*inLen) {
  8424. FreeTmpDsas(tmps, key->heap, ints);
  8425. return BAD_FUNC_ARG;
  8426. }
  8427. /* write to output */
  8428. XMEMCPY(output, seq, seqSz);
  8429. j = seqSz;
  8430. if (includeVersion) {
  8431. XMEMCPY(output + j, ver, verSz);
  8432. j += verSz;
  8433. }
  8434. for (i = 0; i < ints; i++) {
  8435. XMEMCPY(output + j, tmps[i], sizes[i]);
  8436. j += sizes[i];
  8437. }
  8438. FreeTmpDsas(tmps, key->heap, ints);
  8439. return outLen;
  8440. #else
  8441. DECL_ASNSETDATA(dataASN, dsaKeyASN_Length);
  8442. int ret = 0;
  8443. int i;
  8444. int sz;
  8445. (void)ints;
  8446. if ((key == NULL) || (inLen == NULL)) {
  8447. ret = BAD_FUNC_ARG;
  8448. }
  8449. if ((ret == 0) && (ints > DSA_INTS)) {
  8450. ret = BAD_FUNC_ARG;
  8451. }
  8452. CALLOC_ASNSETDATA(dataASN, dsaKeyASN_Length, ret, key->heap);
  8453. if (ret == 0) {
  8454. if (includeVersion) {
  8455. /* Set the version. */
  8456. SetASN_Int8Bit(&dataASN[1], 0);
  8457. }
  8458. else {
  8459. dataASN[1].noOut = 1;
  8460. }
  8461. dataASN[5].noOut = mp_iszero(&key->y);
  8462. dataASN[6].noOut = mp_iszero(&key->x);
  8463. /* Set the mp_ints to encode - params, public and private value. */
  8464. for (i = 0; i < DSA_INTS; i++) {
  8465. SetASN_MP(&dataASN[2 + i], GetDsaInt(key, i));
  8466. }
  8467. /* Calculate size of the encoding. */
  8468. ret = SizeASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, &sz);
  8469. }
  8470. if ((ret == 0) && (output == NULL)) {
  8471. *inLen = sz;
  8472. ret = LENGTH_ONLY_E;
  8473. }
  8474. /* Check buffer is big enough for encoding. */
  8475. if ((ret == 0) && (sz > (int)*inLen)) {
  8476. ret = BAD_FUNC_ARG;
  8477. }
  8478. if (ret == 0) {
  8479. /* Encode the DSA private key into output buffer. */
  8480. SetASN_Items(dsaKeyASN, dataASN, dsaKeyASN_Length, output);
  8481. /* Return the size of the encoding. */
  8482. ret = sz;
  8483. }
  8484. FREE_ASNSETDATA(dataASN, key->heap);
  8485. return ret;
  8486. #endif /* WOLFSSL_ASN_TEMPLATE */
  8487. }
  8488. /* Encode a DSA private key into buffer.
  8489. *
  8490. * @param [in] key DSA key object.
  8491. * @param [out] output Buffer to hold encoded data.
  8492. * @param [out] inLen Length of buffer.
  8493. * @return Size of encoded data in bytes on success.
  8494. * @return BAD_FUNC_ARG when key or output is NULL, or key is not a private key
  8495. * or, buffer size is smaller than encoding size.
  8496. * @return MEMORY_E when dynamic memory allocation fails.
  8497. */
  8498. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  8499. {
  8500. if (!key || !output)
  8501. return BAD_FUNC_ARG;
  8502. if (key->type != DSA_PRIVATE)
  8503. return BAD_FUNC_ARG;
  8504. return DsaKeyIntsToDer(key, output, &inLen, DSA_INTS, 1);
  8505. }
  8506. /* Convert DsaKey parameters to DER format, write to output (inLen),
  8507. return bytes written. Version is excluded to be compatible with
  8508. OpenSSL d2i_DSAparams */
  8509. int wc_DsaKeyToParamsDer(DsaKey* key, byte* output, word32 inLen)
  8510. {
  8511. if (!key || !output)
  8512. return BAD_FUNC_ARG;
  8513. return DsaKeyIntsToDer(key, output, &inLen, DSA_PARAM_INTS, 0);
  8514. }
  8515. /* This version of the function allows output to be NULL. In that case, the
  8516. DsaKeyIntsToDer will return LENGTH_ONLY_E and the required output buffer
  8517. size will be pointed to by inLen. */
  8518. int wc_DsaKeyToParamsDer_ex(DsaKey* key, byte* output, word32* inLen)
  8519. {
  8520. if (!key || !inLen)
  8521. return BAD_FUNC_ARG;
  8522. return DsaKeyIntsToDer(key, output, inLen, DSA_PARAM_INTS, 0);
  8523. }
  8524. #endif /* NO_DSA */
  8525. /* Initialize decoded certificate object with buffer of DER encoding.
  8526. *
  8527. * @param [in, out] cert Decoded certificate object.
  8528. * @param [in] source Buffer containing DER encoded certificate.
  8529. * @param [in] inSz Size of DER data in buffer in bytes.
  8530. * @param [in] heap Dynamic memory hint.
  8531. */
  8532. void InitDecodedCert(DecodedCert* cert,
  8533. const byte* source, word32 inSz, void* heap)
  8534. {
  8535. if (cert != NULL) {
  8536. XMEMSET(cert, 0, sizeof(DecodedCert));
  8537. cert->subjectCNEnc = CTC_UTF8;
  8538. cert->issuer[0] = '\0';
  8539. cert->subject[0] = '\0';
  8540. cert->source = source; /* don't own */
  8541. cert->maxIdx = inSz; /* can't go over this index */
  8542. cert->heap = heap;
  8543. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  8544. #ifdef WOLFSSL_CERT_GEN
  8545. cert->subjectSNEnc = CTC_UTF8;
  8546. cert->subjectCEnc = CTC_PRINTABLE;
  8547. cert->subjectLEnc = CTC_UTF8;
  8548. cert->subjectSTEnc = CTC_UTF8;
  8549. cert->subjectOEnc = CTC_UTF8;
  8550. cert->subjectOUEnc = CTC_UTF8;
  8551. #endif /* WOLFSSL_CERT_GEN */
  8552. #ifndef NO_CERTS
  8553. InitSignatureCtx(&cert->sigCtx, heap, INVALID_DEVID);
  8554. #endif
  8555. }
  8556. }
  8557. /* Free the alternative names object.
  8558. *
  8559. * Frees each linked list items and its name.
  8560. *
  8561. * @param [in, out] altNames Alternative names.
  8562. * @param [in] heap Dynamic memory hint.
  8563. */
  8564. void FreeAltNames(DNS_entry* altNames, void* heap)
  8565. {
  8566. (void)heap;
  8567. while (altNames) {
  8568. DNS_entry* tmp = altNames->next;
  8569. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  8570. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  8571. altNames = tmp;
  8572. }
  8573. }
  8574. /* malloc and initialize a new alt name structure */
  8575. DNS_entry* AltNameNew(void* heap)
  8576. {
  8577. DNS_entry* ret;
  8578. ret = (DNS_entry*)XMALLOC(sizeof(DNS_entry), heap, DYNAMIC_TYPE_ALTNAME);
  8579. if (ret != NULL) {
  8580. XMEMSET(ret, 0, sizeof(DNS_entry));
  8581. }
  8582. (void)heap;
  8583. return ret;
  8584. }
  8585. #ifndef IGNORE_NAME_CONSTRAINTS
  8586. /* Free the subtree names object.
  8587. *
  8588. * Frees each linked list items and its name.
  8589. *
  8590. * @param [in, out] names Subtree names.
  8591. * @param [in] heap Dynamic memory hint.
  8592. */
  8593. void FreeNameSubtrees(Base_entry* names, void* heap)
  8594. {
  8595. (void)heap;
  8596. while (names) {
  8597. Base_entry* tmp = names->next;
  8598. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  8599. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  8600. names = tmp;
  8601. }
  8602. }
  8603. #endif /* IGNORE_NAME_CONSTRAINTS */
  8604. /* Free the decoded cert object's dynamic data.
  8605. *
  8606. * @param [in, out] cert Decoded certificate object.
  8607. */
  8608. void FreeDecodedCert(DecodedCert* cert)
  8609. {
  8610. if (cert == NULL)
  8611. return;
  8612. if (cert->subjectCNStored == 1)
  8613. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  8614. if (cert->pubKeyStored == 1)
  8615. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  8616. if (cert->weOwnAltNames && cert->altNames)
  8617. FreeAltNames(cert->altNames, cert->heap);
  8618. #ifndef IGNORE_NAME_CONSTRAINTS
  8619. if (cert->altEmailNames)
  8620. FreeAltNames(cert->altEmailNames, cert->heap);
  8621. if (cert->altDirNames)
  8622. FreeAltNames(cert->altDirNames, cert->heap);
  8623. if (cert->permittedNames)
  8624. FreeNameSubtrees(cert->permittedNames, cert->heap);
  8625. if (cert->excludedNames)
  8626. FreeNameSubtrees(cert->excludedNames, cert->heap);
  8627. #endif /* IGNORE_NAME_CONSTRAINTS */
  8628. #ifdef WOLFSSL_SEP
  8629. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  8630. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  8631. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  8632. #endif /* WOLFSSL_SEP */
  8633. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  8634. if (cert->issuerName != NULL)
  8635. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  8636. if (cert->subjectName != NULL)
  8637. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  8638. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  8639. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  8640. if (cert->tsip_encRsaKeyIdx != NULL)
  8641. XFREE(cert->tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  8642. #endif
  8643. #ifndef NO_CERTS
  8644. FreeSignatureCtx(&cert->sigCtx);
  8645. #endif
  8646. }
  8647. #ifndef WOLFSSL_ASN_TEMPLATE
  8648. static int GetCertHeader(DecodedCert* cert)
  8649. {
  8650. int ret = 0, len;
  8651. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  8652. return ASN_PARSE_E;
  8653. /* Reset the max index for the size indicated in the outer wrapper. */
  8654. cert->maxIdx = len + cert->srcIdx;
  8655. cert->certBegin = cert->srcIdx;
  8656. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  8657. return ASN_PARSE_E;
  8658. cert->sigIndex = len + cert->srcIdx;
  8659. if (cert->sigIndex > cert->maxIdx)
  8660. return ASN_PARSE_E;
  8661. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  8662. cert->sigIndex) < 0)
  8663. return ASN_PARSE_E;
  8664. if (GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  8665. &cert->serialSz, cert->sigIndex) < 0)
  8666. return ASN_PARSE_E;
  8667. return ret;
  8668. }
  8669. #endif
  8670. #if defined(HAVE_ED25519) || defined(HAVE_ED448) || defined(HAVE_LIBOQS)
  8671. /* Store the key data under the BIT_STRING in dynamicly allocated data.
  8672. *
  8673. * @param [in, out] cert Certificate object.
  8674. * @param [in] source Buffer containing encoded key.
  8675. * @param [in, out] srcIdx On in, start of key data.
  8676. * On out, start of element after key data.
  8677. * @param [in] maxIdx Maximum index of certificate data.
  8678. */
  8679. static int StoreKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  8680. word32 maxIdx)
  8681. {
  8682. int ret;
  8683. int length;
  8684. byte* publicKey;
  8685. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  8686. if (ret == 0) {
  8687. #ifdef HAVE_OCSP
  8688. ret = CalcHashId(source + *srcIdx, length, cert->subjectKeyHash);
  8689. }
  8690. if (ret == 0) {
  8691. #endif
  8692. publicKey = (byte*)XMALLOC(length, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  8693. if (publicKey == NULL) {
  8694. ret = MEMORY_E;
  8695. }
  8696. else {
  8697. XMEMCPY(publicKey, &source[*srcIdx], length);
  8698. cert->publicKey = publicKey;
  8699. cert->pubKeyStored = 1;
  8700. cert->pubKeySize = length;
  8701. *srcIdx += length;
  8702. }
  8703. }
  8704. return ret;
  8705. }
  8706. #endif /* HAVE_ED25519 || HAVE_ED448 */
  8707. #if !defined(NO_RSA)
  8708. #ifdef WOLFSSL_ASN_TEMPLATE
  8709. /* ASN.1 template for header before RSA key in certificate. */
  8710. static const ASNItem rsaCertKeyASN[] = {
  8711. /* 0 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  8712. /* 1 */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  8713. };
  8714. /* Number of items in ASN.1 template for header before RSA key in cert. */
  8715. #define rsaCertKeyASN_Length (sizeof(rsaCertKeyASN) / sizeof(ASNItem))
  8716. #endif
  8717. /* Store RSA key pointer and length in certificate object.
  8718. *
  8719. * @param [in, out] cert Certificate object.
  8720. * @param [in] source Buffer containing encoded key.
  8721. * @param [in, out] srcIdx On in, start of RSA key data.
  8722. * On out, start of element after RSA key data.
  8723. * @param [in] maxIdx Maximum index of key data.
  8724. * @return 0 on success.
  8725. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8726. * is invalid.
  8727. * @return BUFFER_E when data in buffer is too small.
  8728. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8729. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8730. * non-zero length.
  8731. */
  8732. static int StoreRsaKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  8733. word32 maxIdx)
  8734. {
  8735. #ifndef WOLFSSL_ASN_TEMPLATE
  8736. int length;
  8737. int pubLen;
  8738. word32 pubIdx;
  8739. if (CheckBitString(source, srcIdx, &pubLen, maxIdx, 1, NULL) != 0)
  8740. return ASN_PARSE_E;
  8741. pubIdx = *srcIdx;
  8742. if (GetSequence(source, srcIdx, &length, pubIdx + pubLen) < 0)
  8743. return ASN_PARSE_E;
  8744. #if defined(WOLFSSL_RENESAS_TSIP)
  8745. cert->sigCtx.pubkey_n_start = cert->sigCtx.pubkey_e_start = pubIdx;
  8746. #endif
  8747. cert->pubKeySize = pubLen;
  8748. cert->publicKey = source + pubIdx;
  8749. *srcIdx += length;
  8750. #ifdef HAVE_OCSP
  8751. return CalcHashId(cert->publicKey, cert->pubKeySize, cert->subjectKeyHash);
  8752. #else
  8753. return 0;
  8754. #endif
  8755. #else
  8756. ASNGetData dataASN[rsaCertKeyASN_Length];
  8757. int ret;
  8758. /* No dynamic data. */
  8759. XMEMSET(dataASN, 0, sizeof(dataASN));
  8760. /* Decode the header before the key data. */
  8761. ret = GetASN_Items(rsaCertKeyASN, dataASN, rsaCertKeyASN_Length, 1, source,
  8762. srcIdx, maxIdx);
  8763. if (ret == 0) {
  8764. /* Store the pointer and length in certificate object starting at
  8765. * SEQUENCE. */
  8766. GetASN_GetConstRef(&dataASN[0], &cert->publicKey, &cert->pubKeySize);
  8767. #if defined(WOLFSSL_RENESAS_TSIP)
  8768. /* Start of SEQUENCE. */
  8769. cert->sigCtx.pubkey_n_start = cert->sigCtx.pubkey_e_start =
  8770. dataASN[1].offset;
  8771. #endif
  8772. #ifdef HAVE_OCSP
  8773. /* Calculate the hash of the public key for OCSP. */
  8774. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  8775. cert->subjectKeyHash);
  8776. #endif
  8777. }
  8778. return ret;
  8779. #endif /* WOLFSSL_ASN_TEMPLATE */
  8780. }
  8781. #endif /* !NO_RSA */
  8782. #ifdef HAVE_ECC
  8783. #ifdef WOLFSSL_ASN_TEMPLATE
  8784. /* ASN.1 template for header before ECC key in certificate. */
  8785. static const ASNItem eccCertKeyASN[] = {
  8786. /* 0 */ { 1, ASN_OBJECT_ID, 0, 0, 2 },
  8787. /* 1 */ { 1, ASN_SEQUENCE, 1, 0, 2 },
  8788. /* 2 */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  8789. };
  8790. /* Number of items in ASN.1 template for header before ECC key in cert. */
  8791. #define eccCertKeyASN_Length (sizeof(eccCertKeyASN) / sizeof(ASNItem))
  8792. #endif /* WOLFSSL_ASN_TEMPLATE */
  8793. /* Store public ECC key in certificate object.
  8794. *
  8795. * Parse parameters and store public key data.
  8796. *
  8797. * @param [in, out] cert Certificate object.
  8798. * @param [in] source Buffer containing encoded key.
  8799. * @param [in, out] srcIdx On in, start of ECC key data.
  8800. * On out, start of element after ECC key data.
  8801. * @param [in] maxIdx Maximum index of key data.
  8802. * @param [in] pubKey Buffer holding encoded public key.
  8803. * @param [in] pubKeyLen Length of encoded public key in bytes.
  8804. * @return 0 on success.
  8805. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8806. * is invalid.
  8807. * @return BUFFER_E when data in buffer is too small.
  8808. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  8809. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8810. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8811. * non-zero length.
  8812. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  8813. */
  8814. static int StoreEccKey(DecodedCert* cert, const byte* source, word32* srcIdx,
  8815. word32 maxIdx, const byte* pubKey, word32 pubKeyLen)
  8816. {
  8817. #ifndef WOLFSSL_ASN_TEMPLATE
  8818. int ret;
  8819. word32 localIdx;
  8820. byte* publicKey;
  8821. byte tag;
  8822. int length;
  8823. localIdx = *srcIdx;
  8824. if (GetASNTag(source, &localIdx, &tag, maxIdx) < 0)
  8825. return ASN_PARSE_E;
  8826. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  8827. if (GetObjectId(source, srcIdx, &cert->pkCurveOID, oidCurveType,
  8828. maxIdx) < 0)
  8829. return ASN_PARSE_E;
  8830. if (CheckCurve(cert->pkCurveOID) < 0)
  8831. return ECC_CURVE_OID_E;
  8832. /* key header */
  8833. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  8834. if (ret != 0)
  8835. return ret;
  8836. #ifdef HAVE_OCSP
  8837. ret = CalcHashId(source + *srcIdx, length, cert->subjectKeyHash);
  8838. if (ret != 0)
  8839. return ret;
  8840. #endif
  8841. *srcIdx += length;
  8842. }
  8843. publicKey = (byte*)XMALLOC(pubKeyLen, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  8844. if (publicKey == NULL)
  8845. return MEMORY_E;
  8846. XMEMCPY(publicKey, pubKey, pubKeyLen);
  8847. cert->publicKey = publicKey;
  8848. cert->pubKeyStored = 1;
  8849. cert->pubKeySize = pubKeyLen;
  8850. return 0;
  8851. #else
  8852. ASNGetData dataASN[eccCertKeyASN_Length];
  8853. int ret;
  8854. byte* publicKey;
  8855. /* Clear dynamic data and check OID is a curve. */
  8856. XMEMSET(dataASN, 0, sizeof(dataASN));
  8857. GetASN_OID(&dataASN[0], oidCurveType);
  8858. /* Parse ECC public key header. */
  8859. ret = GetASN_Items(eccCertKeyASN, dataASN, eccCertKeyASN_Length, 1, source,
  8860. srcIdx, maxIdx);
  8861. if (ret == 0) {
  8862. if (dataASN[0].tag != 0) {
  8863. /* Store curve OID. */
  8864. cert->pkCurveOID = dataASN[0].data.oid.sum;
  8865. }
  8866. /* Ignore explicit parameters. */
  8867. #ifdef HAVE_OCSP
  8868. /* Calculate the hash of the subject public key for OCSP. */
  8869. ret = CalcHashId(dataASN[2].data.ref.data, dataASN[2].data.ref.length,
  8870. cert->subjectKeyHash);
  8871. }
  8872. if (ret == 0) {
  8873. #endif
  8874. /* Store public key data length. */
  8875. cert->pubKeySize = pubKeyLen;
  8876. /* Must allocated space for key.
  8877. * Don't memcpy into constant pointer so use temp. */
  8878. publicKey = (byte*)XMALLOC(cert->pubKeySize, cert->heap,
  8879. DYNAMIC_TYPE_PUBLIC_KEY);
  8880. if (publicKey == NULL) {
  8881. ret = MEMORY_E;
  8882. }
  8883. else {
  8884. /* Copy in whole public key and store pointer. */
  8885. XMEMCPY(publicKey, pubKey, cert->pubKeySize);
  8886. cert->publicKey = publicKey;
  8887. /* Indicate publicKey needs to be freed. */
  8888. cert->pubKeyStored = 1;
  8889. }
  8890. }
  8891. return ret;
  8892. #endif /* WOLFSSL_ASN_TEMPLATE */
  8893. }
  8894. #endif /* HAVE_ECC */
  8895. #if !defined(NO_DSA)
  8896. #ifdef WOLFSSL_ASN_TEMPLATE
  8897. /* ASN.1 template for DSA key in certificate.
  8898. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  8899. * RFC 3279, 2.3.2 - DSA in SubjectPublicKeyInfo
  8900. */
  8901. static const ASNItem dsaCertKeyASN[] = {
  8902. /* 0 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  8903. /* 1 */ { 2, ASN_INTEGER, 0, 0, 0 },
  8904. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  8905. /* 3 */ { 2, ASN_INTEGER, 0, 0, 0 },
  8906. /* 4 */ { 0, ASN_BIT_STRING, 0, 1, 0 },
  8907. /* 5 */ { 1, ASN_INTEGER, 0, 0, 0 },
  8908. };
  8909. /* Number of items in ASN.1 template for DSA key in certificate. */
  8910. #define dsaCertKeyASN_Length (sizeof(dsaCertKeyASN) / sizeof(ASNItem))
  8911. #endif /* WOLFSSL_ASN_TEMPLATE */
  8912. /* Parse DSA parameters to ensure valid.
  8913. *
  8914. * @param [in] source Buffer containing encoded key.
  8915. * @param [in, out] srcIdx On in, start of DSA key data.
  8916. * On out, start of element after DSA key data.
  8917. * @param [in] maxIdx Maximum index of key data.
  8918. * @param [in] heap Dynamic memory hint.
  8919. * @return 0 on success.
  8920. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8921. * is invalid.
  8922. * @return BUFFER_E when data in buffer is too small.
  8923. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  8924. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  8925. * non-zero length.
  8926. */
  8927. static int ParseDsaKey(const byte* source, word32* srcIdx, word32 maxIdx,
  8928. void* heap)
  8929. {
  8930. #ifndef WOLFSSL_ASN_TEMPLATE
  8931. int ret;
  8932. int length;
  8933. (void)heap;
  8934. ret = GetSequence(source, srcIdx, &length, maxIdx);
  8935. if (ret < 0)
  8936. return ret;
  8937. ret = SkipInt(source, srcIdx, maxIdx);
  8938. if (ret != 0)
  8939. return ret;
  8940. ret = SkipInt(source, srcIdx, maxIdx);
  8941. if (ret != 0)
  8942. return ret;
  8943. ret = SkipInt(source, srcIdx, maxIdx);
  8944. if (ret != 0)
  8945. return ret;
  8946. ret = CheckBitString(source, srcIdx, &length, maxIdx, 1, NULL);
  8947. if (ret != 0)
  8948. return ret;
  8949. ret = GetASNInt(source, srcIdx, &length, maxIdx);
  8950. if (ret != 0)
  8951. return ASN_PARSE_E;
  8952. *srcIdx += length;
  8953. return 0;
  8954. #else
  8955. DECL_ASNGETDATA(dataASN, dsaCertKeyASN_Length);
  8956. int ret = 0;
  8957. (void)heap;
  8958. CALLOC_ASNGETDATA(dataASN, dsaCertKeyASN_Length, ret, heap);
  8959. if (ret == 0) {
  8960. /* Parse the DSA key data to ensure valid. */
  8961. ret = GetASN_Items(dsaCertKeyASN, dataASN, dsaCertKeyASN_Length, 1,
  8962. source, srcIdx, maxIdx);
  8963. }
  8964. FREE_ASNGETDATA(dataASN, heap);
  8965. return ret;
  8966. #endif /* WOLFSSL_ASN_TEMPLATE */
  8967. }
  8968. #endif /* !NO_DSA */
  8969. /* Decode the SubjectPublicKeyInfo block in a certificate.
  8970. *
  8971. * Stores the public key in fields of the certificate object.
  8972. * Validates the BER/DER items and does not store in a key object.
  8973. *
  8974. * @param [in, out] cert Decoded certificate oject.
  8975. * @param [in] source BER/DER encoded SubjectPublicKeyInfo block.
  8976. * @param [in, out] inOutIdx On in, start of public key.
  8977. * On out, start of ASN.1 item after public key.
  8978. * @param [in] maxIdx Maximum index of key data.
  8979. * @return 0 on success.
  8980. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  8981. * is invalid.
  8982. * @return BUFFER_E when data in buffer is too small.
  8983. */
  8984. static int GetCertKey(DecodedCert* cert, const byte* source, word32* inOutIdx,
  8985. word32 maxIdx)
  8986. {
  8987. word32 srcIdx = *inOutIdx;
  8988. #if defined(HAVE_ECC) || !defined(NO_DSA)
  8989. int pubLen;
  8990. #endif
  8991. #if defined(HAVE_ECC) || !defined(NO_DSA)
  8992. int pubIdx = srcIdx;
  8993. #endif
  8994. int ret = 0;
  8995. int length;
  8996. #ifndef WOLFSSL_ASN_TEMPLATE
  8997. if (GetSequence(source, &srcIdx, &length, maxIdx) < 0)
  8998. #else
  8999. /* Get SEQUENCE and expect all data to be accounted for. */
  9000. if (GetASN_Sequence(source, &srcIdx, &length, maxIdx, 1) != 0)
  9001. #endif
  9002. {
  9003. return ASN_PARSE_E;
  9004. }
  9005. #if defined(HAVE_ECC) || !defined(NO_DSA)
  9006. pubLen = srcIdx - pubIdx + length;
  9007. #endif
  9008. maxIdx = srcIdx + length;
  9009. /* Decode the algorithm identifier for the key. */
  9010. if (GetAlgoId(source, &srcIdx, &cert->keyOID, oidKeyType, maxIdx) < 0) {
  9011. return ASN_PARSE_E;
  9012. }
  9013. (void)length;
  9014. /* Parse each type of public key. */
  9015. switch (cert->keyOID) {
  9016. #ifndef NO_RSA
  9017. case RSAk:
  9018. ret = StoreRsaKey(cert, source, &srcIdx, maxIdx);
  9019. break;
  9020. #endif /* NO_RSA */
  9021. #ifdef HAVE_ECC
  9022. case ECDSAk:
  9023. ret = StoreEccKey(cert, source, &srcIdx, maxIdx, source + pubIdx,
  9024. pubLen);
  9025. break;
  9026. #endif /* HAVE_ECC */
  9027. #ifdef HAVE_ED25519
  9028. case ED25519k:
  9029. cert->pkCurveOID = ED25519k;
  9030. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  9031. break;
  9032. #endif /* HAVE_ED25519 */
  9033. #ifdef HAVE_ED448
  9034. case ED448k:
  9035. cert->pkCurveOID = ED448k;
  9036. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  9037. break;
  9038. #endif /* HAVE_ED448 */
  9039. #ifdef HAVE_LIBOQS
  9040. case FALCON_LEVEL1k:
  9041. cert->pkCurveOID = FALCON_LEVEL1k;
  9042. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  9043. break;
  9044. case FALCON_LEVEL5k:
  9045. cert->pkCurveOID = FALCON_LEVEL5k;
  9046. ret = StoreKey(cert, source, &srcIdx, maxIdx);
  9047. break;
  9048. #endif /* HAVE_LIBOQS */
  9049. #ifndef NO_DSA
  9050. case DSAk:
  9051. cert->publicKey = source + pubIdx;
  9052. cert->pubKeySize = pubLen;
  9053. ret = ParseDsaKey(source, &srcIdx, maxIdx, cert->heap);
  9054. break;
  9055. #endif /* NO_DSA */
  9056. default:
  9057. WOLFSSL_MSG("Unknown or not compiled in key OID");
  9058. ret = ASN_UNKNOWN_OID_E;
  9059. }
  9060. /* Return index after public key. */
  9061. *inOutIdx = srcIdx;
  9062. /* Return error code. */
  9063. return ret;
  9064. }
  9065. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9066. #if defined(HAVE_ECC)
  9067. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  9068. * value.
  9069. *
  9070. * @param [in] n ECC curve id.
  9071. * @return ECC curve NID (OpenSSL compatable value).
  9072. */
  9073. WOLFSSL_API int EccEnumToNID(int n)
  9074. {
  9075. WOLFSSL_ENTER("EccEnumToNID()");
  9076. switch(n) {
  9077. case ECC_SECP192R1:
  9078. return NID_X9_62_prime192v1;
  9079. case ECC_PRIME192V2:
  9080. return NID_X9_62_prime192v2;
  9081. case ECC_PRIME192V3:
  9082. return NID_X9_62_prime192v3;
  9083. case ECC_PRIME239V1:
  9084. return NID_X9_62_prime239v1;
  9085. case ECC_PRIME239V2:
  9086. return NID_X9_62_prime239v2;
  9087. case ECC_PRIME239V3:
  9088. return NID_X9_62_prime239v3;
  9089. case ECC_SECP256R1:
  9090. return NID_X9_62_prime256v1;
  9091. case ECC_SECP112R1:
  9092. return NID_secp112r1;
  9093. case ECC_SECP112R2:
  9094. return NID_secp112r2;
  9095. case ECC_SECP128R1:
  9096. return NID_secp128r1;
  9097. case ECC_SECP128R2:
  9098. return NID_secp128r2;
  9099. case ECC_SECP160R1:
  9100. return NID_secp160r1;
  9101. case ECC_SECP160R2:
  9102. return NID_secp160r2;
  9103. case ECC_SECP224R1:
  9104. return NID_secp224r1;
  9105. case ECC_SECP384R1:
  9106. return NID_secp384r1;
  9107. case ECC_SECP521R1:
  9108. return NID_secp521r1;
  9109. case ECC_SECP160K1:
  9110. return NID_secp160k1;
  9111. case ECC_SECP192K1:
  9112. return NID_secp192k1;
  9113. case ECC_SECP224K1:
  9114. return NID_secp224k1;
  9115. case ECC_SECP256K1:
  9116. return NID_secp256k1;
  9117. case ECC_BRAINPOOLP160R1:
  9118. return NID_brainpoolP160r1;
  9119. case ECC_BRAINPOOLP192R1:
  9120. return NID_brainpoolP192r1;
  9121. case ECC_BRAINPOOLP224R1:
  9122. return NID_brainpoolP224r1;
  9123. case ECC_BRAINPOOLP256R1:
  9124. return NID_brainpoolP256r1;
  9125. case ECC_BRAINPOOLP320R1:
  9126. return NID_brainpoolP320r1;
  9127. case ECC_BRAINPOOLP384R1:
  9128. return NID_brainpoolP384r1;
  9129. case ECC_BRAINPOOLP512R1:
  9130. return NID_brainpoolP512r1;
  9131. default:
  9132. WOLFSSL_MSG("NID not found");
  9133. return -1;
  9134. }
  9135. }
  9136. #endif /* HAVE_ECC */
  9137. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  9138. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  9139. && !defined(WOLFCRYPT_ONLY)
  9140. /* Convert shortname to NID.
  9141. *
  9142. * For OpenSSL compatability.
  9143. *
  9144. * @param [in] sn Short name of OID.
  9145. * @return NID corresponding to shortname on success.
  9146. * @return NID_undef when not recognized.
  9147. */
  9148. int wc_OBJ_sn2nid(const char *sn)
  9149. {
  9150. const struct {
  9151. const char *sn;
  9152. int nid;
  9153. } sn2nid[] = {
  9154. {WOLFSSL_COMMON_NAME, NID_commonName},
  9155. {WOLFSSL_COUNTRY_NAME, NID_countryName},
  9156. {WOLFSSL_LOCALITY_NAME, NID_localityName},
  9157. {WOLFSSL_STATE_NAME, NID_stateOrProvinceName},
  9158. {WOLFSSL_ORG_NAME, NID_organizationName},
  9159. {WOLFSSL_ORGUNIT_NAME, NID_organizationalUnitName},
  9160. {WOLFSSL_EMAIL_ADDR, NID_emailAddress},
  9161. {"SHA1", NID_sha1},
  9162. {NULL, -1}};
  9163. int i;
  9164. #ifdef HAVE_ECC
  9165. char curveName[16]; /* Same as MAX_CURVE_NAME_SZ but can't include that
  9166. * symbol in this file */
  9167. int eccEnum;
  9168. #endif
  9169. WOLFSSL_ENTER("OBJ_sn2nid");
  9170. for(i=0; sn2nid[i].sn != NULL; i++) {
  9171. if(XSTRNCMP(sn, sn2nid[i].sn, XSTRLEN(sn2nid[i].sn)) == 0) {
  9172. return sn2nid[i].nid;
  9173. }
  9174. }
  9175. #ifdef HAVE_ECC
  9176. /* Nginx uses this OpenSSL string. */
  9177. if (XSTRNCMP(sn, "prime256v1", 10) == 0)
  9178. sn = "SECP256R1";
  9179. /* OpenSSL allows lowercase curve names */
  9180. for (i = 0; i < (int)(sizeof(curveName) - 1) && *sn; i++) {
  9181. curveName[i] = (char)XTOUPPER(*sn++);
  9182. }
  9183. curveName[i] = '\0';
  9184. /* find based on name and return NID */
  9185. for (i = 0;
  9186. #ifndef WOLFSSL_ECC_CURVE_STATIC
  9187. ecc_sets[i].size != 0 && ecc_sets[i].name != NULL;
  9188. #else
  9189. ecc_sets[i].size != 0;
  9190. #endif
  9191. i++) {
  9192. if (XSTRNCMP(curveName, ecc_sets[i].name, ECC_MAXNAME) == 0) {
  9193. eccEnum = ecc_sets[i].id;
  9194. /* Convert enum value in ecc_curve_id to OpenSSL NID */
  9195. return EccEnumToNID(eccEnum);
  9196. }
  9197. }
  9198. #endif
  9199. return NID_undef;
  9200. }
  9201. #endif
  9202. /* Calculate hash of the id using the SHA-1 or SHA-256.
  9203. *
  9204. * @param [in] data Data to hash.
  9205. * @param [in] len Length of data to hash.
  9206. * @param [out] hash Buffer to hold hash.
  9207. * @return 0 on success.
  9208. * @return MEMORY_E when dynamic memory allocation fails.
  9209. */
  9210. int CalcHashId(const byte* data, word32 len, byte* hash)
  9211. {
  9212. int ret;
  9213. #if defined(NO_SHA) && !defined(NO_SHA256)
  9214. ret = wc_Sha256Hash(data, len, hash);
  9215. #elif !defined(NO_SHA)
  9216. ret = wc_ShaHash(data, len, hash);
  9217. #else
  9218. ret = NOT_COMPILED_IN;
  9219. (void)data;
  9220. (void)len;
  9221. (void)hash;
  9222. #endif
  9223. return ret;
  9224. }
  9225. #ifndef NO_CERTS
  9226. /* Get the hash of the id using the SHA-1 or SHA-256.
  9227. *
  9228. * If the id is not the length of the hash, then hash it.
  9229. *
  9230. * @param [in] id Id to get hash for.
  9231. * @param [in] len Length of id in bytes.
  9232. * @param [out] hash Buffer to hold hash.
  9233. * @return 0 on success.
  9234. * @return MEMORY_E when dynamic memory allocation fails.
  9235. */
  9236. static int GetHashId(const byte* id, int length, byte* hash)
  9237. {
  9238. int ret;
  9239. if (length == KEYID_SIZE) {
  9240. XMEMCPY(hash, id, length);
  9241. ret = 0;
  9242. }
  9243. else {
  9244. ret = CalcHashId(id, length, hash);
  9245. }
  9246. return ret;
  9247. }
  9248. #endif /* !NO_CERTS */
  9249. #ifdef WOLFSSL_ASN_TEMPLATE
  9250. /* Id for email address. */
  9251. #define ASN_EMAIL 0x100
  9252. /* Id for user id. */
  9253. #define ASN_UID 0x101
  9254. /* Id for domain component. */
  9255. #define ASN_DC 0x102
  9256. /* Id for jurisdiction country. */
  9257. #define ASN_JURIS_C 0x203
  9258. /* Id for jurisdiction state. */
  9259. #define ASN_JURIS_ST 0x203
  9260. /* Set the string for a name component into the subject name. */
  9261. #define SetCertNameSubject(cert, id, val) \
  9262. *((char**)(((byte *)cert) + certNameSubject[(id) - 3].data)) = val
  9263. /* Set the string length for a name component into the subject name. */
  9264. #define SetCertNameSubjectLen(cert, id, val) \
  9265. *((int*)(((byte *)cert) + certNameSubject[(id) - 3].len)) = val
  9266. /* Set the encoding for a name component into the subject name. */
  9267. #define SetCertNameSubjectEnc(cert, id, val) \
  9268. *((byte*)(((byte *)cert) + certNameSubject[(id) - 3].enc)) = val
  9269. /* Get the string of a name component from the subject name. */
  9270. #define GetCertNameSubjectStr(id) \
  9271. (certNameSubject[(id) - 3].str)
  9272. /* Get the string length of a name component from the subject name. */
  9273. #define GetCertNameSubjectStrLen(id) \
  9274. (certNameSubject[(id) - 3].strLen)
  9275. /* Get the NID of a name component from the subject name. */
  9276. #define GetCertNameSubjectNID(id) \
  9277. (certNameSubject[(id) - 3].nid)
  9278. #define ValidCertNameSubject(id) \
  9279. ((id - 3) >= 0 && (id - 3) < certNameSubjectSz && \
  9280. (certNameSubject[(id) - 3].strLen > 0))
  9281. /* Mapping of certificate name component to useful information. */
  9282. typedef struct CertNameData {
  9283. /* Type string of name component. */
  9284. const char* str;
  9285. /* Length of type string of name component. */
  9286. byte strLen;
  9287. #ifdef WOLFSSL_CERT_GEN
  9288. /* Offset of data in subject name component. */
  9289. size_t data;
  9290. /* Offset of length in subject name component. */
  9291. size_t len;
  9292. /* Offset of encoding in subject name component. */
  9293. size_t enc;
  9294. #endif
  9295. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9296. /* NID of type for subject name component. */
  9297. int nid;
  9298. #endif
  9299. } CertNameData;
  9300. /* List of data for common name components. */
  9301. static const CertNameData certNameSubject[] = {
  9302. /* Common Name */
  9303. {
  9304. "/CN=", 4,
  9305. #ifdef WOLFSSL_CERT_GEN
  9306. OFFSETOF(DecodedCert, subjectCN),
  9307. OFFSETOF(DecodedCert, subjectCNLen),
  9308. OFFSETOF(DecodedCert, subjectCNEnc),
  9309. #endif
  9310. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9311. NID_commonName
  9312. #endif
  9313. },
  9314. /* Surname */
  9315. {
  9316. "/SN=", 4,
  9317. #ifdef WOLFSSL_CERT_GEN
  9318. OFFSETOF(DecodedCert, subjectSN),
  9319. OFFSETOF(DecodedCert, subjectSNLen),
  9320. OFFSETOF(DecodedCert, subjectSNEnc),
  9321. #endif
  9322. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9323. NID_surname
  9324. #endif
  9325. },
  9326. /* Serial Number */
  9327. {
  9328. "/serialNumber=", 14,
  9329. #ifdef WOLFSSL_CERT_GEN
  9330. OFFSETOF(DecodedCert, subjectSND),
  9331. OFFSETOF(DecodedCert, subjectSNDLen),
  9332. OFFSETOF(DecodedCert, subjectSNDEnc),
  9333. #endif
  9334. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9335. NID_serialNumber
  9336. #endif
  9337. },
  9338. /* Country Name */
  9339. {
  9340. "/C=", 3,
  9341. #ifdef WOLFSSL_CERT_GEN
  9342. OFFSETOF(DecodedCert, subjectC),
  9343. OFFSETOF(DecodedCert, subjectCLen),
  9344. OFFSETOF(DecodedCert, subjectCEnc),
  9345. #endif
  9346. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9347. NID_countryName
  9348. #endif
  9349. },
  9350. /* Locality Name */
  9351. {
  9352. "/L=", 3,
  9353. #ifdef WOLFSSL_CERT_GEN
  9354. OFFSETOF(DecodedCert, subjectL),
  9355. OFFSETOF(DecodedCert, subjectLLen),
  9356. OFFSETOF(DecodedCert, subjectLEnc),
  9357. #endif
  9358. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9359. NID_localityName
  9360. #endif
  9361. },
  9362. /* State Name */
  9363. {
  9364. "/ST=", 4,
  9365. #ifdef WOLFSSL_CERT_GEN
  9366. OFFSETOF(DecodedCert, subjectST),
  9367. OFFSETOF(DecodedCert, subjectSTLen),
  9368. OFFSETOF(DecodedCert, subjectSTEnc),
  9369. #endif
  9370. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9371. NID_stateOrProvinceName
  9372. #endif
  9373. },
  9374. /* Street Address */
  9375. {
  9376. "/street=", 8,
  9377. #ifdef WOLFSSL_CERT_GEN
  9378. OFFSETOF(DecodedCert, subjectStreet),
  9379. OFFSETOF(DecodedCert, subjectStreetLen),
  9380. OFFSETOF(DecodedCert, subjectStreetEnc),
  9381. #endif
  9382. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9383. NID_streetAddress
  9384. #endif
  9385. },
  9386. /* Organization Name */
  9387. {
  9388. "/O=", 3,
  9389. #ifdef WOLFSSL_CERT_GEN
  9390. OFFSETOF(DecodedCert, subjectO),
  9391. OFFSETOF(DecodedCert, subjectOLen),
  9392. OFFSETOF(DecodedCert, subjectOEnc),
  9393. #endif
  9394. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9395. NID_organizationName
  9396. #endif
  9397. },
  9398. /* Organization Unit Name */
  9399. {
  9400. "/OU=", 4,
  9401. #ifdef WOLFSSL_CERT_GEN
  9402. OFFSETOF(DecodedCert, subjectOU),
  9403. OFFSETOF(DecodedCert, subjectOULen),
  9404. OFFSETOF(DecodedCert, subjectOUEnc),
  9405. #endif
  9406. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9407. NID_organizationalUnitName
  9408. #endif
  9409. },
  9410. /* Title */
  9411. {
  9412. NULL, 0,
  9413. #ifdef WOLFSSL_CERT_GEN
  9414. 0,
  9415. 0,
  9416. 0,
  9417. #endif
  9418. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9419. 0,
  9420. #endif
  9421. },
  9422. /* Undefined */
  9423. {
  9424. NULL, 0,
  9425. #ifdef WOLFSSL_CERT_GEN
  9426. 0,
  9427. 0,
  9428. 0,
  9429. #endif
  9430. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9431. 0,
  9432. #endif
  9433. },
  9434. /* Undefined */
  9435. {
  9436. NULL, 0,
  9437. #ifdef WOLFSSL_CERT_GEN
  9438. 0,
  9439. 0,
  9440. 0,
  9441. #endif
  9442. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9443. 0,
  9444. #endif
  9445. },
  9446. /* Business Category */
  9447. {
  9448. "/businessCategory=", 18,
  9449. #ifdef WOLFSSL_CERT_GEN
  9450. #ifdef WOLFSSL_CERT_EXT
  9451. OFFSETOF(DecodedCert, subjectBC),
  9452. OFFSETOF(DecodedCert, subjectBCLen),
  9453. OFFSETOF(DecodedCert, subjectBCEnc),
  9454. #else
  9455. 0,
  9456. 0,
  9457. 0,
  9458. #endif
  9459. #endif
  9460. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9461. NID_businessCategory
  9462. #endif
  9463. },
  9464. /* Undefined */
  9465. {
  9466. NULL, 0,
  9467. #ifdef WOLFSSL_CERT_GEN
  9468. 0,
  9469. 0,
  9470. 0,
  9471. #endif
  9472. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9473. 0,
  9474. #endif
  9475. },
  9476. /* Postal Code */
  9477. {
  9478. "/postalCode=", 12,
  9479. #ifdef WOLFSSL_CERT_GEN
  9480. #ifdef WOLFSSL_CERT_EXT
  9481. OFFSETOF(DecodedCert, subjectPC),
  9482. OFFSETOF(DecodedCert, subjectPCLen),
  9483. OFFSETOF(DecodedCert, subjectPCEnc),
  9484. #else
  9485. 0,
  9486. 0,
  9487. 0,
  9488. #endif
  9489. #endif
  9490. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9491. NID_postalCode
  9492. #endif
  9493. },
  9494. };
  9495. static const int certNameSubjectSz =
  9496. (int) (sizeof(certNameSubject) / sizeof(CertNameData));
  9497. /* Full email OID. */
  9498. static const byte emailOid[] = {
  9499. 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01
  9500. };
  9501. /* Full user id OID. */
  9502. static const byte uidOid[] = {
  9503. 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x01
  9504. };
  9505. /* Full domain component OID. */
  9506. static const byte dcOid[] = {
  9507. 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01, 0x19
  9508. };
  9509. /* ASN.1 template for an RDN.
  9510. * X.509: RFC 5280, 4.1.2.4 - RelativeDistinguishedName
  9511. */
  9512. static const ASNItem rdnASN[] = {
  9513. /* 0 */ { 1, ASN_SET, 1, 1, 0 },
  9514. /* AttributeTypeAndValue */
  9515. /* 1 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  9516. /* AttributeType */
  9517. /* 2 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  9518. /* AttributeValue: Choice of tags - rdnChoice. */
  9519. /* 3 */ { 3, 0, 0, 0, 0 },
  9520. };
  9521. /* Number of items in ASN.1 template for an RDN. */
  9522. #define rdnASN_Length (sizeof(rdnASN) / sizeof(ASNItem))
  9523. /* Supported types of encodings (tags) for RDN strings.
  9524. * X.509: RFC 5280, 4.1.2.4 - DirectoryString
  9525. * (IA5 String not listed in RFC but required for alternative types)
  9526. */
  9527. static const byte rdnChoice[] = {
  9528. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, ASN_T61STRING,
  9529. ASN_UNIVERSALSTRING, ASN_BMPSTRING, 0
  9530. };
  9531. #endif
  9532. #ifdef WOLFSSL_ASN_TEMPLATE
  9533. #if defined(WOLFSSL_CERT_GEN) || \
  9534. (!defined(NO_CERTS) && !defined(IGNORE_NAME_CONSTRAINTS))
  9535. /* Allocate a DNS entry and set the fields.
  9536. *
  9537. * @param [in] cert Certificate object.
  9538. * @param [in] str DNS name string.
  9539. * @param [in] strLen Length of DNS name string.
  9540. * @param [in] type Type of DNS name string.
  9541. * @param [in, out] entries Linked list of DNS name entries.
  9542. * @return 0 on success.
  9543. * @return MEMORY_E when dynamic memory allocation fails.
  9544. */
  9545. static int SetDNSEntry(DecodedCert* cert, const char* str, int strLen,
  9546. int type, DNS_entry** entries)
  9547. {
  9548. DNS_entry* dnsEntry;
  9549. int ret = 0;
  9550. /* Only used for heap. */
  9551. (void)cert;
  9552. /* TODO: consider one malloc. */
  9553. /* Allocate DNS Entry object. */
  9554. dnsEntry = AltNameNew(cert->heap);
  9555. if (dnsEntry == NULL) {
  9556. ret = MEMORY_E;
  9557. }
  9558. if (ret == 0) {
  9559. /* Allocate DNS Entry name - length of string plus 1 for NUL. */
  9560. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  9561. DYNAMIC_TYPE_ALTNAME);
  9562. if (dnsEntry->name == NULL) {
  9563. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  9564. ret = MEMORY_E;
  9565. }
  9566. }
  9567. if (ret == 0) {
  9568. /* Set tag type, name length, name and NUL terminate name. */
  9569. dnsEntry->type = type;
  9570. dnsEntry->len = strLen;
  9571. XMEMCPY(dnsEntry->name, str, strLen);
  9572. dnsEntry->name[strLen] = '\0';
  9573. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  9574. dnsEntry->next = NULL;
  9575. if (*entries == NULL) {
  9576. /* First on list */
  9577. *entries = dnsEntry;
  9578. }
  9579. else {
  9580. DNS_entry* temp = *entries;
  9581. /* Find end */
  9582. for (; (temp->next != NULL); temp = temp->next);
  9583. /* Add to end */
  9584. temp->next = dnsEntry;
  9585. }
  9586. #else
  9587. /* Prepend entry to linked list. */
  9588. dnsEntry->next = *entries;
  9589. *entries = dnsEntry;
  9590. #endif
  9591. }
  9592. return ret;
  9593. }
  9594. #endif
  9595. /* Set the details of a subject name component into a certificate.
  9596. *
  9597. * @param [in, out] cert Certificate object.
  9598. * @param [in] id Id of component.
  9599. * @param [in] str String for component.
  9600. * @param [in] strLen Length of string.
  9601. * @param [in] tag BER tag representing encoding of string.
  9602. * @return 0 on success.
  9603. * @return MEMORY_E when dynamic memory allocation fails.
  9604. */
  9605. static int SetSubject(DecodedCert* cert, int id, byte* str, word32 strLen,
  9606. byte tag)
  9607. {
  9608. int ret = 0;
  9609. /* Put string and encoding into certificate. */
  9610. if (id == ASN_COMMON_NAME) {
  9611. cert->subjectCN = (char *)str;
  9612. cert->subjectCNLen = strLen;
  9613. cert->subjectCNEnc = tag;
  9614. }
  9615. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_CERT_EXT)
  9616. else if (id > ASN_COMMON_NAME && id <= ASN_BUS_CAT) {
  9617. /* Use table and offsets to put data into appropriate fields. */
  9618. SetCertNameSubject(cert, id, (char*)str);
  9619. SetCertNameSubjectLen(cert, id, strLen);
  9620. SetCertNameSubjectEnc(cert, id, tag);
  9621. }
  9622. else if (id == ASN_EMAIL) {
  9623. cert->subjectEmail = (char*)str;
  9624. cert->subjectEmailLen = strLen;
  9625. #if !defined(IGNORE_NAME_CONSTRAINTS)
  9626. ret = SetDNSEntry(cert, cert->subjectEmail, strLen, 0,
  9627. &cert->altEmailNames);
  9628. #endif
  9629. }
  9630. #ifdef WOLFSSL_CERT_EXT
  9631. /* TODO: consider mapping id to an index and using SetCertNameSubect*(). */
  9632. else if (id == ASN_JURIS_C) {
  9633. cert->subjectJC = (char*)str;
  9634. cert->subjectJCLen = strLen;
  9635. cert->subjectJCEnc = tag;
  9636. }
  9637. else if (id == ASN_JURIS_ST) {
  9638. cert->subjectJS = (char*)str;
  9639. cert->subjectJSLen = strLen;
  9640. cert->subjectJSEnc = tag;
  9641. }
  9642. #endif
  9643. #endif
  9644. return ret;
  9645. }
  9646. /* Get a RelativeDistinguishedName from the encoding and put in certificate.
  9647. *
  9648. * @param [in, out] cert Certificate object.
  9649. * @param [in, out] full Full name string. ([/<type>=<value>]*)
  9650. * @param [in, out] idx Index int full name to place next component.
  9651. * @param [in, out] nid NID of component type.
  9652. * @param [in] isSubject Whether this data is for a subject name.
  9653. * @param [in] dataASN Decoded data of RDN.
  9654. * @return 0 on success.
  9655. * @return MEMORY_E when dynamic memory allocation fails.
  9656. * @return ASN_PARSE_E when type not supported.
  9657. */
  9658. static int GetRDN(DecodedCert* cert, char* full, word32* idx, int* nid,
  9659. int isSubject, ASNGetData* dataASN)
  9660. {
  9661. int ret = 0;
  9662. const char* typeStr = NULL;
  9663. byte typeStrLen = 0;
  9664. byte* oid;
  9665. word32 oidSz;
  9666. int id = 0;
  9667. (void)nid;
  9668. /* Get name type OID from data items. */
  9669. GetASN_OIDData(&dataASN[2], &oid, &oidSz);
  9670. /* v1 name types */
  9671. if ((oidSz == 3) && (oid[0] == 0x55) && (oid[1] == 0x04)) {
  9672. id = oid[2];
  9673. /* Check range of supported ids in table. */
  9674. if (ValidCertNameSubject(id)) {
  9675. /* Get the type string, length and NID from table. */
  9676. typeStr = GetCertNameSubjectStr(id);
  9677. typeStrLen = GetCertNameSubjectStrLen(id);
  9678. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9679. *nid = GetCertNameSubjectNID(id);
  9680. #endif
  9681. }
  9682. }
  9683. else if (oidSz == sizeof(emailOid) && XMEMCMP(oid, emailOid, oidSz) == 0) {
  9684. /* Set the email id, type string, length and NID. */
  9685. id = ASN_EMAIL;
  9686. typeStr = WOLFSSL_EMAIL_ADDR;
  9687. typeStrLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  9688. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9689. *nid = NID_emailAddress;
  9690. #endif
  9691. }
  9692. else if (oidSz == sizeof(uidOid) && XMEMCMP(oid, uidOid, oidSz) == 0) {
  9693. /* Set the user id, type string, length and NID. */
  9694. id = ASN_UID;
  9695. typeStr = WOLFSSL_USER_ID;
  9696. typeStrLen = sizeof(WOLFSSL_USER_ID) - 1;
  9697. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9698. *nid = NID_userId;
  9699. #endif
  9700. }
  9701. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz) == 0) {
  9702. /* Set the domain component, type string, length and NID. */
  9703. id = ASN_DC;
  9704. typeStr = WOLFSSL_DOMAIN_COMPONENT;
  9705. typeStrLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  9706. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9707. *nid = NID_domainComponent;
  9708. #endif
  9709. }
  9710. /* Other OIDs that start with the same values. */
  9711. else if (oidSz == sizeof(dcOid) && XMEMCMP(oid, dcOid, oidSz-1) == 0) {
  9712. WOLFSSL_MSG("Unknown pilot attribute type");
  9713. ret = ASN_PARSE_E;
  9714. }
  9715. else if (oidSz == ASN_JOI_PREFIX_SZ + 1 &&
  9716. XMEMCMP(oid, ASN_JOI_PREFIX, ASN_JOI_PREFIX_SZ) == 0) {
  9717. /* Set the jurisdiction id. */
  9718. id = 0x200 + oid[ASN_JOI_PREFIX_SZ];
  9719. /* Set the jurisdiction type string, length and NID if known. */
  9720. if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_C) {
  9721. typeStr = WOLFSSL_JOI_C;
  9722. typeStrLen = sizeof(WOLFSSL_JOI_C) - 1;
  9723. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9724. *nid = NID_jurisdictionCountryName;
  9725. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  9726. }
  9727. else if (oid[ASN_JOI_PREFIX_SZ] == ASN_JOI_ST) {
  9728. typeStr = WOLFSSL_JOI_ST;
  9729. typeStrLen = sizeof(WOLFSSL_JOI_ST) - 1;
  9730. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  9731. *nid = NID_jurisdictionStateOrProvinceName;
  9732. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  9733. }
  9734. else {
  9735. WOLFSSL_MSG("Unknown Jurisdiction, skipping");
  9736. }
  9737. }
  9738. if ((ret == 0) && (typeStr != NULL)) {
  9739. /* OID type to store for subject name and add to full string. */
  9740. byte* str;
  9741. word32 strLen;
  9742. byte tag = dataASN[3].tag;
  9743. /* Get the string reference and length. */
  9744. GetASN_GetRef(&dataASN[3], &str, &strLen);
  9745. if (isSubject) {
  9746. /* Store subject field components. */
  9747. ret = SetSubject(cert, id, str, strLen, tag);
  9748. }
  9749. if (ret == 0) {
  9750. /* Check there is space for this in the full name string and
  9751. * terminating NUL character. */
  9752. if ((typeStrLen + strLen) < (word32)(ASN_NAME_MAX - *idx))
  9753. {
  9754. /* Add RDN to full string. */
  9755. XMEMCPY(&full[*idx], typeStr, typeStrLen);
  9756. *idx += typeStrLen;
  9757. XMEMCPY(&full[*idx], str, strLen);
  9758. *idx += strLen;
  9759. }
  9760. else {
  9761. WOLFSSL_MSG("ASN Name too big, skipping");
  9762. }
  9763. }
  9764. }
  9765. return ret;
  9766. }
  9767. #endif /* WOLFSSL_ASN_TEMPLATE */
  9768. /* Get a certificate name into the certificate object.
  9769. *
  9770. * @param [in, out] cert Decoded certificate object.
  9771. * @param [out] full Buffer to hold full name as a string.
  9772. * @param [out] hash Buffer to hold hash of name.
  9773. * @param [in] nameType ISSUER or SUBJECT.
  9774. * @param [in] input Buffer holding certificate name.
  9775. * @param [in, out] inOutIdx On in, start of certificate name.
  9776. * On out, start of ASN.1 item after cert name.
  9777. * @param [in] maxIdx Index of next item after certificate name.
  9778. * @return 0 on success.
  9779. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  9780. * is invalid.
  9781. * @return BUFFER_E when data in buffer is too small.
  9782. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  9783. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  9784. * @return MEMORY_E when dynamic memory allocation fails.
  9785. */
  9786. static int GetCertName(DecodedCert* cert, char* full, byte* hash, int nameType,
  9787. const byte* input, word32* inOutIdx, word32 maxIdx)
  9788. {
  9789. #ifndef WOLFSSL_ASN_TEMPLATE
  9790. int length; /* length of all distinguished names */
  9791. int dummy;
  9792. int ret;
  9793. word32 idx;
  9794. word32 srcIdx = *inOutIdx;
  9795. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9796. !defined(WOLFCRYPT_ONLY)
  9797. WOLFSSL_X509_NAME* dName = NULL;
  9798. #endif
  9799. WOLFSSL_MSG("Getting Cert Name");
  9800. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  9801. * calculated over the entire DER encoding of the Name field, including
  9802. * the tag and length. */
  9803. if (CalcHashId(input + *inOutIdx, maxIdx - *inOutIdx, hash) != 0)
  9804. return ASN_PARSE_E;
  9805. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9806. !defined(WOLFCRYPT_ONLY)
  9807. dName = wolfSSL_X509_NAME_new();
  9808. if (dName == NULL) {
  9809. return MEMORY_E;
  9810. }
  9811. #endif /* OPENSSL_EXTRA */
  9812. if (GetSequence(input, &srcIdx, &length, maxIdx) < 0) {
  9813. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9814. !defined(WOLFCRYPT_ONLY)
  9815. wolfSSL_X509_NAME_free(dName);
  9816. #endif /* OPENSSL_EXTRA */
  9817. return ASN_PARSE_E;
  9818. }
  9819. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  9820. /* store pointer to raw issuer */
  9821. if (nameType == ISSUER) {
  9822. cert->issuerRaw = &input[srcIdx];
  9823. cert->issuerRawLen = length;
  9824. }
  9825. #endif
  9826. #ifndef IGNORE_NAME_CONSTRAINTS
  9827. if (nameType == SUBJECT) {
  9828. cert->subjectRaw = &input[srcIdx];
  9829. cert->subjectRawLen = length;
  9830. }
  9831. #endif
  9832. length += srcIdx;
  9833. idx = 0;
  9834. while (srcIdx < (word32)length) {
  9835. byte b = 0;
  9836. byte joint[3];
  9837. byte tooBig = FALSE;
  9838. int oidSz;
  9839. const char* copy = NULL;
  9840. int copyLen = 0;
  9841. int strLen = 0;
  9842. byte id = 0;
  9843. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  9844. && !defined(WOLFCRYPT_ONLY)
  9845. int nid = NID_undef;
  9846. int enc;
  9847. #endif /* OPENSSL_EXTRA */
  9848. if (GetSet(input, &srcIdx, &dummy, maxIdx) < 0) {
  9849. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  9850. }
  9851. if (GetSequence(input, &srcIdx, &dummy, maxIdx) <= 0) {
  9852. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9853. !defined(WOLFCRYPT_ONLY)
  9854. wolfSSL_X509_NAME_free(dName);
  9855. #endif /* OPENSSL_EXTRA */
  9856. return ASN_PARSE_E;
  9857. }
  9858. ret = GetASNObjectId(input, &srcIdx, &oidSz, maxIdx);
  9859. if (ret != 0) {
  9860. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9861. !defined(WOLFCRYPT_ONLY)
  9862. wolfSSL_X509_NAME_free(dName);
  9863. #endif /* OPENSSL_EXTRA */
  9864. return ret;
  9865. }
  9866. /* make sure there is room for joint */
  9867. if ((srcIdx + sizeof(joint)) > (word32)maxIdx) {
  9868. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9869. !defined(WOLFCRYPT_ONLY)
  9870. wolfSSL_X509_NAME_free(dName);
  9871. #endif /* OPENSSL_EXTRA */
  9872. return ASN_PARSE_E;
  9873. }
  9874. XMEMCPY(joint, &input[srcIdx], sizeof(joint));
  9875. /* v1 name types */
  9876. if (joint[0] == 0x55 && joint[1] == 0x04) {
  9877. srcIdx += 3;
  9878. id = joint[2];
  9879. if (GetHeader(input, &b, &srcIdx, &strLen, maxIdx, 1) < 0) {
  9880. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  9881. !defined(WOLFCRYPT_ONLY)
  9882. wolfSSL_X509_NAME_free(dName);
  9883. #endif /* OPENSSL_EXTRA */
  9884. return ASN_PARSE_E;
  9885. }
  9886. if (id == ASN_COMMON_NAME) {
  9887. if (nameType == SUBJECT) {
  9888. cert->subjectCN = (char *)&input[srcIdx];
  9889. cert->subjectCNLen = strLen;
  9890. cert->subjectCNEnc = b;
  9891. }
  9892. copy = WOLFSSL_COMMON_NAME;
  9893. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  9894. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  9895. && !defined(WOLFCRYPT_ONLY)
  9896. nid = NID_commonName;
  9897. #endif /* OPENSSL_EXTRA */
  9898. }
  9899. else if (id == ASN_SUR_NAME) {
  9900. copy = WOLFSSL_SUR_NAME;
  9901. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  9902. #ifdef WOLFSSL_CERT_GEN
  9903. if (nameType == SUBJECT) {
  9904. cert->subjectSN = (char*)&input[srcIdx];
  9905. cert->subjectSNLen = strLen;
  9906. cert->subjectSNEnc = b;
  9907. }
  9908. #endif /* WOLFSSL_CERT_GEN */
  9909. #if (defined(OPENSSL_EXTRA) || \
  9910. defined(OPENSSL_EXTRA_X509_SMALL)) \
  9911. && !defined(WOLFCRYPT_ONLY)
  9912. nid = NID_surname;
  9913. #endif /* OPENSSL_EXTRA */
  9914. }
  9915. else if (id == ASN_COUNTRY_NAME) {
  9916. copy = WOLFSSL_COUNTRY_NAME;
  9917. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  9918. #ifdef WOLFSSL_CERT_GEN
  9919. if (nameType == SUBJECT) {
  9920. cert->subjectC = (char*)&input[srcIdx];
  9921. cert->subjectCLen = strLen;
  9922. cert->subjectCEnc = b;
  9923. }
  9924. #endif /* WOLFSSL_CERT_GEN */
  9925. #if (defined(OPENSSL_EXTRA) || \
  9926. defined(OPENSSL_EXTRA_X509_SMALL)) \
  9927. && !defined(WOLFCRYPT_ONLY)
  9928. nid = NID_countryName;
  9929. #endif /* OPENSSL_EXTRA */
  9930. }
  9931. else if (id == ASN_LOCALITY_NAME) {
  9932. copy = WOLFSSL_LOCALITY_NAME;
  9933. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  9934. #ifdef WOLFSSL_CERT_GEN
  9935. if (nameType == SUBJECT) {
  9936. cert->subjectL = (char*)&input[srcIdx];
  9937. cert->subjectLLen = strLen;
  9938. cert->subjectLEnc = b;
  9939. }
  9940. #endif /* WOLFSSL_CERT_GEN */
  9941. #if (defined(OPENSSL_EXTRA) || \
  9942. defined(OPENSSL_EXTRA_X509_SMALL)) \
  9943. && !defined(WOLFCRYPT_ONLY)
  9944. nid = NID_localityName;
  9945. #endif /* OPENSSL_EXTRA */
  9946. }
  9947. else if (id == ASN_STATE_NAME) {
  9948. copy = WOLFSSL_STATE_NAME;
  9949. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  9950. #ifdef WOLFSSL_CERT_GEN
  9951. if (nameType == SUBJECT) {
  9952. cert->subjectST = (char*)&input[srcIdx];
  9953. cert->subjectSTLen = strLen;
  9954. cert->subjectSTEnc = b;
  9955. }
  9956. #endif /* WOLFSSL_CERT_GEN */
  9957. #if (defined(OPENSSL_EXTRA) || \
  9958. defined(OPENSSL_EXTRA_X509_SMALL)) \
  9959. && !defined(WOLFCRYPT_ONLY)
  9960. nid = NID_stateOrProvinceName;
  9961. #endif /* OPENSSL_EXTRA */
  9962. }
  9963. else if (id == ASN_ORG_NAME) {
  9964. copy = WOLFSSL_ORG_NAME;
  9965. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  9966. #ifdef WOLFSSL_CERT_GEN
  9967. if (nameType == SUBJECT) {
  9968. cert->subjectO = (char*)&input[srcIdx];
  9969. cert->subjectOLen = strLen;
  9970. cert->subjectOEnc = b;
  9971. }
  9972. #endif /* WOLFSSL_CERT_GEN */
  9973. #if (defined(OPENSSL_EXTRA) || \
  9974. defined(OPENSSL_EXTRA_X509_SMALL)) \
  9975. && !defined(WOLFCRYPT_ONLY)
  9976. nid = NID_organizationName;
  9977. #endif /* OPENSSL_EXTRA */
  9978. }
  9979. else if (id == ASN_ORGUNIT_NAME) {
  9980. copy = WOLFSSL_ORGUNIT_NAME;
  9981. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  9982. #ifdef WOLFSSL_CERT_GEN
  9983. if (nameType == SUBJECT) {
  9984. cert->subjectOU = (char*)&input[srcIdx];
  9985. cert->subjectOULen = strLen;
  9986. cert->subjectOUEnc = b;
  9987. }
  9988. #endif /* WOLFSSL_CERT_GEN */
  9989. #if (defined(OPENSSL_EXTRA) || \
  9990. defined(OPENSSL_EXTRA_X509_SMALL)) \
  9991. && !defined(WOLFCRYPT_ONLY)
  9992. nid = NID_organizationalUnitName;
  9993. #endif /* OPENSSL_EXTRA */
  9994. }
  9995. else if (id == ASN_SERIAL_NUMBER) {
  9996. copy = WOLFSSL_SERIAL_NUMBER;
  9997. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  9998. #ifdef WOLFSSL_CERT_GEN
  9999. if (nameType == SUBJECT) {
  10000. cert->subjectSND = (char*)&input[srcIdx];
  10001. cert->subjectSNDLen = strLen;
  10002. cert->subjectSNDEnc = b;
  10003. }
  10004. #endif /* WOLFSSL_CERT_GEN */
  10005. #if (defined(OPENSSL_EXTRA) || \
  10006. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10007. && !defined(WOLFCRYPT_ONLY)
  10008. nid = NID_serialNumber;
  10009. #endif /* OPENSSL_EXTRA */
  10010. }
  10011. #ifdef WOLFSSL_CERT_EXT
  10012. else if (id == ASN_STREET_ADDR) {
  10013. copy = WOLFSSL_STREET_ADDR_NAME;
  10014. copyLen = sizeof(WOLFSSL_STREET_ADDR_NAME) - 1;
  10015. #ifdef WOLFSSL_CERT_GEN
  10016. if (nameType == SUBJECT) {
  10017. cert->subjectStreet = (char*)&input[srcIdx];
  10018. cert->subjectStreetLen = strLen;
  10019. cert->subjectStreetEnc = b;
  10020. }
  10021. #endif /* WOLFSSL_CERT_GEN */
  10022. #if (defined(OPENSSL_EXTRA) || \
  10023. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10024. && !defined(WOLFCRYPT_ONLY)
  10025. nid = NID_streetAddress;
  10026. #endif /* OPENSSL_EXTRA */
  10027. }
  10028. else if (id == ASN_BUS_CAT) {
  10029. copy = WOLFSSL_BUS_CAT;
  10030. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  10031. #ifdef WOLFSSL_CERT_GEN
  10032. if (nameType == SUBJECT) {
  10033. cert->subjectBC = (char*)&input[srcIdx];
  10034. cert->subjectBCLen = strLen;
  10035. cert->subjectBCEnc = b;
  10036. }
  10037. #endif /* WOLFSSL_CERT_GEN */
  10038. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  10039. && !defined(WOLFCRYPT_ONLY)
  10040. nid = NID_businessCategory;
  10041. #endif /* OPENSSL_EXTRA */
  10042. }
  10043. else if (id == ASN_POSTAL_CODE) {
  10044. copy = WOLFSSL_POSTAL_NAME;
  10045. copyLen = sizeof(WOLFSSL_POSTAL_NAME) - 1;
  10046. #ifdef WOLFSSL_CERT_GEN
  10047. if (nameType == SUBJECT) {
  10048. cert->subjectPC = (char*)&input[srcIdx];
  10049. cert->subjectPCLen = strLen;
  10050. cert->subjectPCEnc = b;
  10051. }
  10052. #endif /* WOLFSSL_CERT_GEN */
  10053. #if (defined(OPENSSL_EXTRA) || \
  10054. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10055. && !defined(WOLFCRYPT_ONLY)
  10056. nid = NID_postalCode;
  10057. #endif /* OPENSSL_EXTRA */
  10058. }
  10059. #endif /* WOLFSSL_CERT_EXT */
  10060. }
  10061. #ifdef WOLFSSL_CERT_EXT
  10062. else if ((srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  10063. (0 == XMEMCMP(&input[srcIdx], ASN_JOI_PREFIX,
  10064. ASN_JOI_PREFIX_SZ)) &&
  10065. ((input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  10066. (input[srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  10067. {
  10068. srcIdx += ASN_JOI_PREFIX_SZ;
  10069. id = input[srcIdx++];
  10070. b = input[srcIdx++]; /* encoding */
  10071. if (GetLength(input, &srcIdx, &strLen,
  10072. maxIdx) < 0) {
  10073. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10074. !defined(WOLFCRYPT_ONLY)
  10075. wolfSSL_X509_NAME_free(dName);
  10076. #endif /* OPENSSL_EXTRA */
  10077. return ASN_PARSE_E;
  10078. }
  10079. /* Check for jurisdiction of incorporation country name */
  10080. if (id == ASN_JOI_C) {
  10081. copy = WOLFSSL_JOI_C;
  10082. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  10083. #ifdef WOLFSSL_CERT_GEN
  10084. if (nameType == SUBJECT) {
  10085. cert->subjectJC = (char*)&input[srcIdx];
  10086. cert->subjectJCLen = strLen;
  10087. cert->subjectJCEnc = b;
  10088. }
  10089. #endif /* WOLFSSL_CERT_GEN */
  10090. #if (defined(OPENSSL_EXTRA) || \
  10091. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10092. && !defined(WOLFCRYPT_ONLY)
  10093. nid = NID_jurisdictionCountryName;
  10094. #endif /* OPENSSL_EXTRA */
  10095. }
  10096. /* Check for jurisdiction of incorporation state name */
  10097. else if (id == ASN_JOI_ST) {
  10098. copy = WOLFSSL_JOI_ST;
  10099. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  10100. #ifdef WOLFSSL_CERT_GEN
  10101. if (nameType == SUBJECT) {
  10102. cert->subjectJS = (char*)&input[srcIdx];
  10103. cert->subjectJSLen = strLen;
  10104. cert->subjectJSEnc = b;
  10105. }
  10106. #endif /* WOLFSSL_CERT_GEN */
  10107. #if (defined(OPENSSL_EXTRA) || \
  10108. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10109. && !defined(WOLFCRYPT_ONLY)
  10110. nid = NID_jurisdictionStateOrProvinceName;
  10111. #endif /* OPENSSL_EXTRA */
  10112. }
  10113. if ((strLen + copyLen) > (int)(ASN_NAME_MAX - idx)) {
  10114. WOLFSSL_MSG("ASN Name too big, skipping");
  10115. tooBig = TRUE;
  10116. }
  10117. }
  10118. #endif /* WOLFSSL_CERT_EXT */
  10119. else {
  10120. /* skip */
  10121. byte email = FALSE;
  10122. byte pilot = FALSE;
  10123. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr */
  10124. id = ASN_EMAIL_NAME;
  10125. email = TRUE;
  10126. }
  10127. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr */
  10128. /* last value of OID is the type of pilot attribute */
  10129. id = input[srcIdx + oidSz - 1];
  10130. pilot = TRUE;
  10131. }
  10132. srcIdx += oidSz + 1;
  10133. if (GetLength(input, &srcIdx, &strLen, maxIdx) < 0) {
  10134. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10135. !defined(WOLFCRYPT_ONLY)
  10136. wolfSSL_X509_NAME_free(dName);
  10137. #endif /* OPENSSL_EXTRA */
  10138. return ASN_PARSE_E;
  10139. }
  10140. if (strLen > (int)(ASN_NAME_MAX - idx)) {
  10141. WOLFSSL_MSG("ASN name too big, skipping");
  10142. tooBig = TRUE;
  10143. }
  10144. if (email) {
  10145. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  10146. if ((copyLen + strLen) > (int)(ASN_NAME_MAX - idx)) {
  10147. WOLFSSL_MSG("ASN name too big, skipping");
  10148. tooBig = TRUE;
  10149. }
  10150. else {
  10151. copy = WOLFSSL_EMAIL_ADDR;
  10152. }
  10153. #ifdef WOLFSSL_CERT_GEN
  10154. if (nameType == SUBJECT) {
  10155. cert->subjectEmail = (char*)&input[srcIdx];
  10156. cert->subjectEmailLen = strLen;
  10157. }
  10158. #endif /* WOLFSSL_CERT_GEN */
  10159. #if (defined(OPENSSL_EXTRA) || \
  10160. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10161. && !defined(WOLFCRYPT_ONLY)
  10162. nid = NID_emailAddress;
  10163. #endif /* OPENSSL_EXTRA */
  10164. #ifndef IGNORE_NAME_CONSTRAINTS
  10165. {
  10166. DNS_entry* emailName;
  10167. emailName = AltNameNew(cert->heap);
  10168. if (emailName == NULL) {
  10169. WOLFSSL_MSG("\tOut of Memory");
  10170. #if (defined(OPENSSL_EXTRA) || \
  10171. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10172. !defined(WOLFCRYPT_ONLY)
  10173. wolfSSL_X509_NAME_free(dName);
  10174. #endif /* OPENSSL_EXTRA */
  10175. return MEMORY_E;
  10176. }
  10177. emailName->type = 0;
  10178. emailName->name = (char*)XMALLOC(strLen + 1,
  10179. cert->heap, DYNAMIC_TYPE_ALTNAME);
  10180. if (emailName->name == NULL) {
  10181. WOLFSSL_MSG("\tOut of Memory");
  10182. XFREE(emailName, cert->heap, DYNAMIC_TYPE_ALTNAME);
  10183. #if (defined(OPENSSL_EXTRA) || \
  10184. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10185. !defined(WOLFCRYPT_ONLY)
  10186. wolfSSL_X509_NAME_free(dName);
  10187. #endif /* OPENSSL_EXTRA */
  10188. return MEMORY_E;
  10189. }
  10190. emailName->len = strLen;
  10191. XMEMCPY(emailName->name, &input[srcIdx], strLen);
  10192. emailName->name[strLen] = '\0';
  10193. emailName->next = cert->altEmailNames;
  10194. cert->altEmailNames = emailName;
  10195. }
  10196. #endif /* IGNORE_NAME_CONSTRAINTS */
  10197. }
  10198. if (pilot) {
  10199. switch (id) {
  10200. case ASN_USER_ID:
  10201. copy = WOLFSSL_USER_ID;
  10202. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  10203. #if (defined(OPENSSL_EXTRA) || \
  10204. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10205. && !defined(WOLFCRYPT_ONLY)
  10206. nid = NID_userId;
  10207. #endif /* OPENSSL_EXTRA */
  10208. break;
  10209. case ASN_DOMAIN_COMPONENT:
  10210. copy = WOLFSSL_DOMAIN_COMPONENT;
  10211. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  10212. #if (defined(OPENSSL_EXTRA) || \
  10213. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10214. && !defined(WOLFCRYPT_ONLY)
  10215. nid = NID_domainComponent;
  10216. #endif /* OPENSSL_EXTRA */
  10217. break;
  10218. case ASN_FAVOURITE_DRINK:
  10219. copy = WOLFSSL_FAVOURITE_DRINK;
  10220. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  10221. #if (defined(OPENSSL_EXTRA) || \
  10222. defined(OPENSSL_EXTRA_X509_SMALL)) \
  10223. && !defined(WOLFCRYPT_ONLY)
  10224. nid = NID_favouriteDrink;
  10225. #endif /* OPENSSL_EXTRA */
  10226. break;
  10227. default:
  10228. WOLFSSL_MSG("Unknown pilot attribute type");
  10229. #if (defined(OPENSSL_EXTRA) || \
  10230. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10231. !defined(WOLFCRYPT_ONLY)
  10232. wolfSSL_X509_NAME_free(dName);
  10233. #endif /* OPENSSL_EXTRA */
  10234. return ASN_PARSE_E;
  10235. }
  10236. }
  10237. }
  10238. if ((copyLen + strLen) > (int)(ASN_NAME_MAX - idx))
  10239. {
  10240. WOLFSSL_MSG("ASN Name too big, skipping");
  10241. tooBig = TRUE;
  10242. }
  10243. if ((copy != NULL) && !tooBig) {
  10244. XMEMCPY(&full[idx], copy, copyLen);
  10245. idx += copyLen;
  10246. XMEMCPY(&full[idx], &input[srcIdx], strLen);
  10247. idx += strLen;
  10248. }
  10249. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10250. !defined(WOLFCRYPT_ONLY)
  10251. switch (b) {
  10252. case CTC_UTF8:
  10253. enc = MBSTRING_UTF8;
  10254. break;
  10255. case CTC_PRINTABLE:
  10256. enc = V_ASN1_PRINTABLESTRING;
  10257. break;
  10258. default:
  10259. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  10260. enc = MBSTRING_UTF8;
  10261. }
  10262. if (nid != NID_undef) {
  10263. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  10264. &input[srcIdx], strLen, -1, -1) !=
  10265. WOLFSSL_SUCCESS) {
  10266. wolfSSL_X509_NAME_free(dName);
  10267. return ASN_PARSE_E;
  10268. }
  10269. }
  10270. #endif /* OPENSSL_EXTRA */
  10271. srcIdx += strLen;
  10272. }
  10273. full[idx++] = 0;
  10274. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  10275. !defined(WOLFCRYPT_ONLY)
  10276. if (nameType == ISSUER) {
  10277. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(HAVE_LIGHTY)) && \
  10278. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  10279. dName->rawLen = min(cert->issuerRawLen, ASN_NAME_MAX);
  10280. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  10281. #endif
  10282. cert->issuerName = dName;
  10283. }
  10284. else {
  10285. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  10286. dName->rawLen = min(cert->subjectRawLen, ASN_NAME_MAX);
  10287. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  10288. #endif
  10289. cert->subjectName = dName;
  10290. }
  10291. #endif
  10292. *inOutIdx = srcIdx;
  10293. return 0;
  10294. #else
  10295. DECL_ASNGETDATA(dataASN, rdnASN_Length);
  10296. int ret = 0;
  10297. word32 idx = 0;
  10298. int len;
  10299. word32 srcIdx = *inOutIdx;
  10300. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10301. WOLFSSL_X509_NAME* dName = NULL;
  10302. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10303. WOLFSSL_MSG("Getting Cert Name");
  10304. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  10305. * calculated over the entire DER encoding of the Name field, including
  10306. * the tag and length. */
  10307. if (CalcHashId(input + srcIdx, maxIdx - srcIdx, hash) != 0) {
  10308. ret = ASN_PARSE_E;
  10309. }
  10310. ALLOC_ASNGETDATA(dataASN, rdnASN_Length, ret, cert->heap);
  10311. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10312. if (ret == 0) {
  10313. /* Create an X509_NAME to hold data for OpenSSL compatability APIs. */
  10314. dName = wolfSSL_X509_NAME_new();
  10315. if (dName == NULL) {
  10316. ret = MEMORY_E;
  10317. }
  10318. }
  10319. #endif /* WOLFSSL_X509_NAME_AVAILABLE */
  10320. if (ret == 0) {
  10321. /* Expecting a SEQUENCE using up all data. */
  10322. ret = GetASN_Sequence(input, &srcIdx, &len, maxIdx, 1);
  10323. }
  10324. if (ret == 0) {
  10325. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  10326. /* Store pointer and length to raw issuer. */
  10327. if (nameType == ISSUER) {
  10328. cert->issuerRaw = &input[srcIdx];
  10329. cert->issuerRawLen = len;
  10330. }
  10331. #endif
  10332. #ifndef IGNORE_NAME_CONSTRAINTS
  10333. /* Store pointer and length to raw subject. */
  10334. if (nameType == SUBJECT) {
  10335. cert->subjectRaw = &input[srcIdx];
  10336. cert->subjectRawLen = len;
  10337. }
  10338. #endif
  10339. /* Process all RDNs in name. */
  10340. while ((ret == 0) && (srcIdx < maxIdx)) {
  10341. int nid = 0;
  10342. /* Initialize for data and setup RDN choice. */
  10343. XMEMSET(dataASN, 0, sizeof(*dataASN) * rdnASN_Length);
  10344. GetASN_Choice(&dataASN[3], rdnChoice);
  10345. /* Ignore type OID as too many to store in table. */
  10346. GetASN_OID(&dataASN[2], oidIgnoreType);
  10347. /* Parse RDN. */
  10348. ret = GetASN_Items(rdnASN, dataASN, rdnASN_Length, 1, input,
  10349. &srcIdx, maxIdx);
  10350. if (ret == 0) {
  10351. /* Put RDN data into certificate. */
  10352. ret = GetRDN(cert, full, &idx, &nid, nameType == SUBJECT,
  10353. dataASN);
  10354. }
  10355. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10356. /* TODO: push this back up to ssl.c
  10357. * (do parsing for WOLFSSL_X509_NAME on demand) */
  10358. if (ret == 0) {
  10359. int enc;
  10360. byte* str;
  10361. word32 strLen;
  10362. byte tag = dataASN[3].tag;
  10363. /* Get string reference. */
  10364. GetASN_GetRef(&dataASN[3], &str, &strLen);
  10365. /* Convert BER tag to a OpenSSL type. */
  10366. switch (tag) {
  10367. case CTC_UTF8:
  10368. enc = MBSTRING_UTF8;
  10369. break;
  10370. case CTC_PRINTABLE:
  10371. enc = V_ASN1_PRINTABLESTRING;
  10372. break;
  10373. default:
  10374. WOLFSSL_MSG("Unknown encoding type, default UTF8");
  10375. enc = MBSTRING_UTF8;
  10376. }
  10377. if (nid != 0) {
  10378. /* Add an entry to the X509_NAME. */
  10379. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc, str,
  10380. strLen, -1, -1) != WOLFSSL_SUCCESS) {
  10381. ret = ASN_PARSE_E;
  10382. }
  10383. }
  10384. }
  10385. #endif
  10386. }
  10387. }
  10388. if (ret == 0) {
  10389. /* Terminate string. */
  10390. full[idx] = 0;
  10391. /* Return index into encoding after name. */
  10392. *inOutIdx = srcIdx;
  10393. #ifdef WOLFSSL_X509_NAME_AVAILABLE
  10394. /* Store X509_NAME in certificate. */
  10395. if (nameType == ISSUER) {
  10396. #if (defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  10397. defined(HAVE_LIGHTY)) && \
  10398. (defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT))
  10399. dName->rawLen = min(cert->issuerRawLen, ASN_NAME_MAX);
  10400. XMEMCPY(dName->raw, cert->issuerRaw, dName->rawLen);
  10401. #endif
  10402. cert->issuerName = dName;
  10403. }
  10404. else {
  10405. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX)
  10406. dName->rawLen = min(cert->subjectRawLen, ASN_NAME_MAX);
  10407. XMEMCPY(dName->raw, cert->subjectRaw, dName->rawLen);
  10408. #endif
  10409. cert->subjectName = dName;
  10410. }
  10411. }
  10412. else {
  10413. /* Dispose of unused X509_NAME. */
  10414. wolfSSL_X509_NAME_free(dName);
  10415. #endif
  10416. }
  10417. FREE_ASNGETDATA(dataASN, cert->heap);
  10418. return ret;
  10419. #endif /* WOLFSSL_ASN_TEMPLATE */
  10420. }
  10421. #ifdef WOLFSSL_ASN_TEMPLATE
  10422. /* ASN.1 template for certificate name. */
  10423. static const ASNItem certNameASN[] = {
  10424. /* 0 */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  10425. /* 1 */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  10426. };
  10427. /* Number of items in ASN.1 template for certificate name. */
  10428. #define certNameASN_Length (sizeof(certNameASN) / sizeof(ASNItem))
  10429. #endif
  10430. /* Get a certificate name into the certificate object.
  10431. *
  10432. * Either the issuer or subject name.
  10433. *
  10434. * @param [in, out] cert Decoded certificate object.
  10435. * @param [in] nameType Type of name being decoded: ISSUER or SUBJECT.
  10436. * @param [in] maxIdx Index of next item after certificate name.
  10437. * @return 0 on success.
  10438. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10439. * is invalid.
  10440. * @return BUFFER_E when data in buffer is too small.
  10441. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  10442. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  10443. * @return MEMORY_E when dynamic memory allocation fails.
  10444. */
  10445. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  10446. {
  10447. #ifndef WOLFSSL_ASN_TEMPLATE
  10448. char* full;
  10449. byte* hash;
  10450. int length;
  10451. word32 localIdx;
  10452. byte tag;
  10453. WOLFSSL_MSG("Getting Cert Name");
  10454. if (nameType == ISSUER) {
  10455. full = cert->issuer;
  10456. hash = cert->issuerHash;
  10457. }
  10458. else {
  10459. full = cert->subject;
  10460. hash = cert->subjectHash;
  10461. }
  10462. if (cert->srcIdx >= (word32)maxIdx) {
  10463. return BUFFER_E;
  10464. }
  10465. localIdx = cert->srcIdx;
  10466. if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) {
  10467. return ASN_PARSE_E;
  10468. }
  10469. if (tag == ASN_OBJECT_ID) {
  10470. WOLFSSL_MSG("Trying optional prefix...");
  10471. if (SkipObjectId(cert->source, &cert->srcIdx, maxIdx) < 0)
  10472. return ASN_PARSE_E;
  10473. WOLFSSL_MSG("Got optional prefix");
  10474. }
  10475. localIdx = cert->srcIdx;
  10476. if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) {
  10477. return ASN_PARSE_E;
  10478. }
  10479. localIdx = cert->srcIdx + 1;
  10480. if (GetLength(cert->source, &localIdx, &length, maxIdx) < 0) {
  10481. return ASN_PARSE_E;
  10482. }
  10483. length += localIdx - cert->srcIdx;
  10484. return GetCertName(cert, full, hash, nameType, cert->source, &cert->srcIdx,
  10485. cert->srcIdx + length);
  10486. #else
  10487. ASNGetData dataASN[certNameASN_Length];
  10488. word32 idx = cert->srcIdx;
  10489. int ret;
  10490. char* full;
  10491. byte* hash;
  10492. WOLFSSL_MSG("Getting Cert Name");
  10493. /* Initialize for data and don't check optional prefix OID. */
  10494. XMEMSET(dataASN, 0, sizeof(dataASN));
  10495. GetASN_OID(&dataASN[0], oidIgnoreType);
  10496. ret = GetASN_Items(certNameASN, dataASN, certNameASN_Length, 0,
  10497. cert->source, &idx, maxIdx);
  10498. if (ret == 0) {
  10499. /* Store offset of SEQUENCE that is start of name. */
  10500. cert->srcIdx = dataASN[1].offset;
  10501. /* Get fields to fill in based on name type. */
  10502. if (nameType == ISSUER) {
  10503. full = cert->issuer;
  10504. hash = cert->issuerHash;
  10505. }
  10506. else {
  10507. full = cert->subject;
  10508. hash = cert->subjectHash;
  10509. }
  10510. /* Parse certificate name. */
  10511. ret = GetCertName(cert, full, hash, nameType, cert->source,
  10512. &cert->srcIdx, idx);
  10513. }
  10514. return ret;
  10515. #endif
  10516. }
  10517. #ifndef NO_ASN_TIME
  10518. /* two byte date/time, add to value */
  10519. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  10520. {
  10521. int i = *idx;
  10522. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  10523. date[i+1] > 0x39) {
  10524. return ASN_PARSE_E;
  10525. }
  10526. *value += btoi(date[i++]) * 10;
  10527. *value += btoi(date[i++]);
  10528. *idx = i;
  10529. return 0;
  10530. }
  10531. #ifdef WOLFSSL_LINUXKM
  10532. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  10533. {
  10534. int i = *idx;
  10535. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  10536. date[i+1] > 0x39) {
  10537. return ASN_PARSE_E;
  10538. }
  10539. *value += (long)btoi(date[i++]) * 10;
  10540. *value += (long)btoi(date[i++]);
  10541. *idx = i;
  10542. return 0;
  10543. }
  10544. #endif
  10545. int ExtractDate(const unsigned char* date, unsigned char format,
  10546. struct tm* certTime, int* idx)
  10547. {
  10548. XMEMSET(certTime, 0, sizeof(struct tm));
  10549. if (format == ASN_UTC_TIME) {
  10550. if (btoi(date[*idx]) >= 5)
  10551. certTime->tm_year = 1900;
  10552. else
  10553. certTime->tm_year = 2000;
  10554. }
  10555. else { /* format == GENERALIZED_TIME */
  10556. #ifdef WOLFSSL_LINUXKM
  10557. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  10558. #else
  10559. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  10560. #endif
  10561. certTime->tm_year *= 100;
  10562. }
  10563. #ifdef AVR
  10564. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  10565. /* AVR libc stores these as uint8_t instead of int */
  10566. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  10567. int tm_year = certTime->tm_year - 2000;
  10568. int tm_mon = certTime->tm_mon - 1;
  10569. int tm_mday = certTime->tm_mday;
  10570. int tm_hour = certTime->tm_hour;
  10571. int tm_min = certTime->tm_min;
  10572. int tm_sec = certTime->tm_sec;
  10573. #ifdef WOLFSSL_LINUXKM
  10574. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  10575. #else
  10576. if (GetTime(&tm_year, date, idx) != 0) return 0;
  10577. #endif
  10578. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  10579. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  10580. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  10581. if (GetTime(&tm_min , date, idx) != 0) return 0;
  10582. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  10583. /* Re-populate certTime with computed values */
  10584. certTime->tm_year = tm_year;
  10585. certTime->tm_mon = tm_mon;
  10586. certTime->tm_mday = tm_mday;
  10587. certTime->tm_hour = tm_hour;
  10588. certTime->tm_min = tm_min;
  10589. certTime->tm_sec = tm_sec;
  10590. #else
  10591. /* adjust tm_year, tm_mon */
  10592. #ifdef WOLFSSL_LINUXKM
  10593. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  10594. #else
  10595. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  10596. #endif
  10597. certTime->tm_year -= 1900;
  10598. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  10599. certTime->tm_mon -= 1;
  10600. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  10601. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  10602. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  10603. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  10604. #endif
  10605. return 1;
  10606. }
  10607. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  10608. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  10609. int GetTimeString(byte* date, int format, char* buf, int len)
  10610. {
  10611. struct tm t;
  10612. int idx = 0;
  10613. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  10614. return 0;
  10615. }
  10616. if (date[idx] != 'Z') {
  10617. WOLFSSL_MSG("UTCtime, not Zulu") ;
  10618. return 0;
  10619. }
  10620. /* place month in buffer */
  10621. buf[0] = '\0';
  10622. switch(t.tm_mon) {
  10623. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  10624. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  10625. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  10626. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  10627. case 4: XSTRNCAT(buf, "May ", 5); break;
  10628. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  10629. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  10630. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  10631. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  10632. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  10633. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  10634. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  10635. default:
  10636. return 0;
  10637. }
  10638. idx = 4; /* use idx now for char buffer */
  10639. XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  10640. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900);
  10641. return 1;
  10642. }
  10643. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  10644. #if !defined(NO_ASN_TIME) && defined(HAVE_PKCS7)
  10645. /* Set current time string, either UTC or GeneralizedTime.
  10646. * (void*) tm should be a pointer to time_t, output is placed in buf.
  10647. *
  10648. * Return time string length placed in buf on success, negative on error */
  10649. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  10650. {
  10651. struct tm* ts = NULL;
  10652. struct tm* tmpTime = NULL;
  10653. byte* data_ptr = buf;
  10654. word32 data_len = 0;
  10655. int year, mon, day, hour, mini, sec;
  10656. #if defined(NEED_TMP_TIME)
  10657. struct tm tmpTimeStorage;
  10658. tmpTime = &tmpTimeStorage;
  10659. #else
  10660. (void)tmpTime;
  10661. #endif
  10662. WOLFSSL_ENTER("SetAsnTimeString");
  10663. if (buf == NULL || len == 0)
  10664. return BAD_FUNC_ARG;
  10665. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  10666. if (ts == NULL){
  10667. WOLFSSL_MSG("failed to get time data.");
  10668. return ASN_TIME_E;
  10669. }
  10670. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  10671. * the null terminator. ASN encoded values leave off the terminator. */
  10672. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  10673. /* UTC Time */
  10674. char utc_str[ASN_UTC_TIME_SIZE];
  10675. data_len = ASN_UTC_TIME_SIZE - 1 + 2;
  10676. if (len < data_len)
  10677. return BUFFER_E;
  10678. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  10679. year = ts->tm_year;
  10680. } else if (ts->tm_year >= 100 && ts->tm_year < 150) {
  10681. year = ts->tm_year - 100;
  10682. }
  10683. else {
  10684. WOLFSSL_MSG("unsupported year range");
  10685. return BAD_FUNC_ARG;
  10686. }
  10687. mon = ts->tm_mon + 1;
  10688. day = ts->tm_mday;
  10689. hour = ts->tm_hour;
  10690. mini = ts->tm_min;
  10691. sec = ts->tm_sec;
  10692. XSNPRINTF((char *)utc_str, ASN_UTC_TIME_SIZE,
  10693. "%02d%02d%02d%02d%02d%02dZ", year, mon, day, hour, mini, sec);
  10694. *data_ptr = (byte) ASN_UTC_TIME; data_ptr++;
  10695. /* -1 below excludes null terminator */
  10696. *data_ptr = (byte) ASN_UTC_TIME_SIZE - 1; data_ptr++;
  10697. XMEMCPY(data_ptr,(byte *)utc_str, ASN_UTC_TIME_SIZE - 1);
  10698. } else {
  10699. /* GeneralizedTime */
  10700. char gt_str[ASN_GENERALIZED_TIME_SIZE];
  10701. data_len = ASN_GENERALIZED_TIME_SIZE - 1 + 2;
  10702. if (len < data_len)
  10703. return BUFFER_E;
  10704. year = ts->tm_year + 1900;
  10705. mon = ts->tm_mon + 1;
  10706. day = ts->tm_mday;
  10707. hour = ts->tm_hour;
  10708. mini = ts->tm_min;
  10709. sec = ts->tm_sec;
  10710. XSNPRINTF((char *)gt_str, ASN_GENERALIZED_TIME_SIZE,
  10711. "%4d%02d%02d%02d%02d%02dZ", year, mon, day, hour, mini, sec);
  10712. *data_ptr = (byte) ASN_GENERALIZED_TIME; data_ptr++;
  10713. /* -1 below excludes null terminator */
  10714. *data_ptr = (byte) ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++;
  10715. XMEMCPY(data_ptr,(byte *)gt_str, ASN_GENERALIZED_TIME_SIZE - 1);
  10716. }
  10717. return data_len;
  10718. }
  10719. #endif /* !NO_ASN_TIME && HAVE_PKCS7 */
  10720. #if defined(USE_WOLF_VALIDDATE)
  10721. /* to the second */
  10722. int DateGreaterThan(const struct tm* a, const struct tm* b)
  10723. {
  10724. if (a->tm_year > b->tm_year)
  10725. return 1;
  10726. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  10727. return 1;
  10728. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  10729. a->tm_mday > b->tm_mday)
  10730. return 1;
  10731. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  10732. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  10733. return 1;
  10734. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  10735. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  10736. a->tm_min > b->tm_min)
  10737. return 1;
  10738. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  10739. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  10740. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  10741. return 1;
  10742. return 0; /* false */
  10743. }
  10744. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  10745. {
  10746. return DateGreaterThan(b,a);
  10747. }
  10748. /* like atoi but only use first byte */
  10749. /* Make sure before and after dates are valid */
  10750. int wc_ValidateDate(const byte* date, byte format, int dateType)
  10751. {
  10752. time_t ltime;
  10753. struct tm certTime;
  10754. struct tm* localTime;
  10755. struct tm* tmpTime;
  10756. int i = 0;
  10757. int timeDiff = 0 ;
  10758. int diffHH = 0 ; int diffMM = 0 ;
  10759. int diffSign = 0 ;
  10760. #if defined(NEED_TMP_TIME)
  10761. struct tm tmpTimeStorage;
  10762. tmpTime = &tmpTimeStorage;
  10763. #else
  10764. tmpTime = NULL;
  10765. #endif
  10766. (void)tmpTime;
  10767. ltime = XTIME(0);
  10768. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  10769. if (dateType == BEFORE) {
  10770. WOLFSSL_MSG("Skewing local time for before date check");
  10771. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  10772. }
  10773. #endif
  10774. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  10775. if (dateType == AFTER) {
  10776. WOLFSSL_MSG("Skewing local time for after date check");
  10777. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  10778. }
  10779. #endif
  10780. if (!ExtractDate(date, format, &certTime, &i)) {
  10781. WOLFSSL_MSG("Error extracting the date");
  10782. return 0;
  10783. }
  10784. if ((date[i] == '+') || (date[i] == '-')) {
  10785. WOLFSSL_MSG("Using time differential, not Zulu") ;
  10786. diffSign = date[i++] == '+' ? 1 : -1 ;
  10787. if (GetTime(&diffHH, date, &i) != 0)
  10788. return 0;
  10789. if (GetTime(&diffMM, date, &i) != 0)
  10790. return 0;
  10791. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  10792. } else if (date[i] != 'Z') {
  10793. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  10794. return 0;
  10795. }
  10796. ltime -= (time_t)timeDiff ;
  10797. localTime = XGMTIME(&ltime, tmpTime);
  10798. if (localTime == NULL) {
  10799. WOLFSSL_MSG("XGMTIME failed");
  10800. return 0;
  10801. }
  10802. if (dateType == BEFORE) {
  10803. if (DateLessThan(localTime, &certTime)) {
  10804. WOLFSSL_MSG("Date BEFORE check failed");
  10805. return 0;
  10806. }
  10807. }
  10808. else { /* dateType == AFTER */
  10809. if (DateGreaterThan(localTime, &certTime)) {
  10810. WOLFSSL_MSG("Date AFTER check failed");
  10811. return 0;
  10812. }
  10813. }
  10814. return 1;
  10815. }
  10816. #endif /* USE_WOLF_VALIDDATE */
  10817. int wc_GetTime(void* timePtr, word32 timeSize)
  10818. {
  10819. time_t* ltime = (time_t*)timePtr;
  10820. if (timePtr == NULL) {
  10821. return BAD_FUNC_ARG;
  10822. }
  10823. if ((word32)sizeof(time_t) > timeSize) {
  10824. return BUFFER_E;
  10825. }
  10826. *ltime = XTIME(0);
  10827. return 0;
  10828. }
  10829. #endif /* !NO_ASN_TIME */
  10830. #ifdef WOLFSSL_ASN_TEMPLATE
  10831. /* TODO: use a CHOICE instead of two items? */
  10832. /* ASN.1 template for a date - either UTC or Generalized Time. */
  10833. static const ASNItem dateASN[] = {
  10834. /* 0 */ { 0, ASN_UTC_TIME, 0, 0, 2 },
  10835. /* 1 */ { 0, ASN_GENERALIZED_TIME, 0, 0, 2 },
  10836. };
  10837. /* Number of items in ASN.1 template for a date. */
  10838. #define dateASN_Length (sizeof(dateASN) / sizeof(ASNItem))
  10839. #endif /* WOLFSSL_ASN_TEMPLATE */
  10840. /* Get date buffer, format and length. Returns 0=success or error */
  10841. /* Decode a DateInfo - choice of UTC TIME or GENERALIZED TIME.
  10842. *
  10843. * @param [in] source Buffer containing encoded date.
  10844. * @param [in, out] idx On in, the index of the date.
  10845. * On out, index after date.
  10846. * @param [out] pDate Pointer into buffer of data bytes.
  10847. * @param [out] pFormat Format of date - BER/DER tag.
  10848. * @param [out] pLength Length of date bytes.
  10849. * @param [in] maxIdx Index of next item after date.
  10850. * @return 0 on success.
  10851. * @return BAD_FUNC_ARG when source or idx is NULL.
  10852. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  10853. * is invalid.
  10854. * @return BUFFER_E when data in buffer is too small.
  10855. */
  10856. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  10857. byte* pFormat, int* pLength, word32 maxIdx)
  10858. {
  10859. #ifndef WOLFSSL_ASN_TEMPLATE
  10860. int length;
  10861. byte format;
  10862. if (source == NULL || idx == NULL)
  10863. return BAD_FUNC_ARG;
  10864. /* get ASN format header */
  10865. if (*idx+1 > maxIdx)
  10866. return BUFFER_E;
  10867. format = source[*idx];
  10868. *idx += 1;
  10869. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME)
  10870. return ASN_TIME_E;
  10871. /* get length */
  10872. if (GetLength(source, idx, &length, maxIdx) < 0)
  10873. return ASN_PARSE_E;
  10874. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  10875. return ASN_DATE_SZ_E;
  10876. /* return format, date and length */
  10877. if (pFormat)
  10878. *pFormat = format;
  10879. if (pDate)
  10880. *pDate = &source[*idx];
  10881. if (pLength)
  10882. *pLength = length;
  10883. *idx += length;
  10884. return 0;
  10885. #else
  10886. ASNGetData dataASN[dateASN_Length];
  10887. int i;
  10888. int ret = 0;
  10889. if ((source == NULL) || (idx == NULL)) {
  10890. ret = BAD_FUNC_ARG;
  10891. }
  10892. if (ret == 0) {
  10893. /* Initialize data. */
  10894. XMEMSET(dataASN, 0, sizeof(dataASN));
  10895. /* Parse date. */
  10896. ret = GetASN_Items(dateASN, dataASN, dateASN_Length, 0, source, idx,
  10897. maxIdx);
  10898. }
  10899. if (ret == 0) {
  10900. /* Determine which tag was seen. */
  10901. i = (dataASN[0].tag != 0) ? 0 : 1;
  10902. /* Return data from seen item. */
  10903. if (pFormat != NULL) {
  10904. *pFormat = dataASN[i].tag;
  10905. }
  10906. if (pDate != NULL) {
  10907. *pDate = dataASN[i].data.ref.data;
  10908. }
  10909. if (pLength != NULL) {
  10910. *pLength = dataASN[i].data.ref.length;
  10911. }
  10912. }
  10913. return ret;
  10914. #endif
  10915. }
  10916. #ifndef WOLFSSL_ASN_TEMPLATE
  10917. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  10918. {
  10919. int ret, length;
  10920. const byte *datePtr = NULL;
  10921. byte date[MAX_DATE_SIZE];
  10922. byte format;
  10923. word32 startIdx = 0;
  10924. if (dateType == BEFORE)
  10925. cert->beforeDate = &cert->source[cert->srcIdx];
  10926. else
  10927. cert->afterDate = &cert->source[cert->srcIdx];
  10928. startIdx = cert->srcIdx;
  10929. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  10930. &length, maxIdx);
  10931. if (ret < 0)
  10932. return ret;
  10933. XMEMSET(date, 0, MAX_DATE_SIZE);
  10934. XMEMCPY(date, datePtr, length);
  10935. if (dateType == BEFORE)
  10936. cert->beforeDateLen = cert->srcIdx - startIdx;
  10937. else
  10938. cert->afterDateLen = cert->srcIdx - startIdx;
  10939. #ifndef NO_ASN_TIME
  10940. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  10941. !XVALIDATE_DATE(date, format, dateType)) {
  10942. if (dateType == BEFORE)
  10943. return ASN_BEFORE_DATE_E;
  10944. else
  10945. return ASN_AFTER_DATE_E;
  10946. }
  10947. #else
  10948. (void)verify;
  10949. #endif
  10950. return 0;
  10951. }
  10952. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  10953. {
  10954. int length;
  10955. int badDate = 0;
  10956. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  10957. return ASN_PARSE_E;
  10958. maxIdx = cert->srcIdx + length;
  10959. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  10960. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  10961. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  10962. return ASN_AFTER_DATE_E;
  10963. if (badDate != 0)
  10964. return badDate;
  10965. return 0;
  10966. }
  10967. #endif /* !WOLFSSL_ASN_TEMPLATE */
  10968. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  10969. byte* format, int* length)
  10970. {
  10971. int ret;
  10972. word32 idx = 0;
  10973. ret = GetDateInfo(certDate, &idx, date, format, length, certDateSz);
  10974. if (ret < 0)
  10975. return ret;
  10976. return 0;
  10977. }
  10978. #ifndef NO_ASN_TIME
  10979. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  10980. struct tm* timearg)
  10981. {
  10982. int idx = 0;
  10983. (void)length;
  10984. if (!ExtractDate(date, format, timearg, &idx))
  10985. return ASN_TIME_E;
  10986. return 0;
  10987. }
  10988. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  10989. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  10990. {
  10991. int ret = 0;
  10992. const byte* date;
  10993. byte format;
  10994. int length;
  10995. if (cert == NULL)
  10996. return BAD_FUNC_ARG;
  10997. if (before && cert->beforeDateSz > 0) {
  10998. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  10999. &format, &length);
  11000. if (ret == 0)
  11001. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  11002. }
  11003. if (after && cert->afterDateSz > 0) {
  11004. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  11005. &format, &length);
  11006. if (ret == 0)
  11007. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  11008. }
  11009. return ret;
  11010. }
  11011. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  11012. #endif /* !NO_ASN_TIME */
  11013. #ifdef WOLFSSL_ASN_TEMPLATE
  11014. /* TODO: move code around to not require this. */
  11015. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  11016. int* badDateRet, int stopAtPubKey,
  11017. int stopAfterPubKey);
  11018. #endif
  11019. /* Parse the certificate up to the X.509 public key.
  11020. *
  11021. * If cert data is invalid then badDate get set to error value.
  11022. *
  11023. * @param [in, out] cert Decoded certificate object.
  11024. * @param [in] verify Whether to verify dates.
  11025. * @param [out] badDate Error code when verify dates.
  11026. * @return 0 on success.
  11027. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  11028. * @return ASN_DATE_SZ_E when time data is not supported.
  11029. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11030. * is invalid.
  11031. * @return BUFFER_E when data in buffer is too small.
  11032. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11033. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  11034. */
  11035. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  11036. {
  11037. #ifndef WOLFSSL_ASN_TEMPLATE
  11038. int ret;
  11039. if (cert == NULL || badDate == NULL)
  11040. return BAD_FUNC_ARG;
  11041. *badDate = 0;
  11042. if ( (ret = GetCertHeader(cert)) < 0)
  11043. return ret;
  11044. WOLFSSL_MSG("Got Cert Header");
  11045. #ifdef WOLFSSL_CERT_REQ
  11046. if (!cert->isCSR) {
  11047. #endif
  11048. /* Using the sigIndex as the upper bound because that's where the
  11049. * actual certificate data ends. */
  11050. if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
  11051. oidSigType, cert->sigIndex)) < 0)
  11052. return ret;
  11053. WOLFSSL_MSG("Got Algo ID");
  11054. if ( (ret = GetName(cert, ISSUER, cert->sigIndex)) < 0)
  11055. return ret;
  11056. if ( (ret = GetValidity(cert, verify, cert->sigIndex)) < 0)
  11057. *badDate = ret;
  11058. #ifdef WOLFSSL_CERT_REQ
  11059. }
  11060. #endif
  11061. if ( (ret = GetName(cert, SUBJECT, cert->sigIndex)) < 0)
  11062. return ret;
  11063. WOLFSSL_MSG("Got Subject Name");
  11064. return ret;
  11065. #else
  11066. /* Use common decode routine and stop at public key. */
  11067. int ret;
  11068. *badDate = 0;
  11069. ret = DecodeCertInternal(cert, verify, NULL, badDate, 1, 0);
  11070. if (ret >= 0) {
  11071. /* Store current index: public key. */
  11072. cert->srcIdx = ret;
  11073. }
  11074. return ret;
  11075. #endif /* WOLFSSL_ASN_TEMPLATE */
  11076. }
  11077. /* Parse the certificate up to and including X.509 public key.
  11078. *
  11079. * @param [in, out] cert Decoded certificate object.
  11080. * @param [in] verify Whether to verify dates.
  11081. * @return 0 on success.
  11082. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  11083. * @return ASN_DATE_SZ_E when time data is not supported.
  11084. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  11085. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  11086. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  11087. * is invalid.
  11088. * @return BUFFER_E when data in buffer is too small.
  11089. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  11090. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  11091. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set.
  11092. */
  11093. int DecodeToKey(DecodedCert* cert, int verify)
  11094. {
  11095. #ifndef WOLFSSL_ASN_TEMPLATE
  11096. int badDate = 0;
  11097. int ret;
  11098. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  11099. return ret;
  11100. /* Determine if self signed */
  11101. cert->selfSigned = XMEMCMP(cert->issuerHash,
  11102. cert->subjectHash,
  11103. KEYID_SIZE) == 0 ? 1 : 0;
  11104. ret = GetCertKey(cert, cert->source, &cert->srcIdx, cert->maxIdx);
  11105. if (ret != 0)
  11106. return ret;
  11107. WOLFSSL_MSG("Got Key");
  11108. if (badDate != 0)
  11109. return badDate;
  11110. return ret;
  11111. #else
  11112. int ret;
  11113. int badDate = 0;
  11114. /* Call internal version and stop after public key. */
  11115. ret = DecodeCertInternal(cert, verify, NULL, &badDate, 0, 1);
  11116. /* Always return date errors. */
  11117. if (ret == 0) {
  11118. ret = badDate;
  11119. }
  11120. return ret;
  11121. #endif /* WOLFSSL_ASN_TEMPLATE */
  11122. }
  11123. #if !defined(NO_CERTS) && !defined(WOLFSSL_ASN_TEMPLATE)
  11124. static int GetSignature(DecodedCert* cert)
  11125. {
  11126. int length;
  11127. int ret;
  11128. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  11129. NULL);
  11130. if (ret != 0)
  11131. return ret;
  11132. cert->sigLength = length;
  11133. cert->signature = &cert->source[cert->srcIdx];
  11134. cert->srcIdx += cert->sigLength;
  11135. if (cert->srcIdx != cert->maxIdx)
  11136. return ASN_PARSE_E;
  11137. return 0;
  11138. }
  11139. #endif /* !NO_CERTS && !WOLFSSL_ASN_TEMPLATE */
  11140. #ifndef WOLFSSL_ASN_TEMPLATE
  11141. static word32 SetOctetString8Bit(word32 len, byte* output)
  11142. {
  11143. output[0] = ASN_OCTET_STRING;
  11144. output[1] = (byte)len;
  11145. return 2;
  11146. }
  11147. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  11148. {
  11149. word32 idx = SetOctetString8Bit(digSz, output);
  11150. XMEMCPY(&output[idx], digest, digSz);
  11151. return idx + digSz;
  11152. }
  11153. #endif
  11154. /* Encode a length for DER.
  11155. *
  11156. * @param [in] length Value to encode.
  11157. * @param [out] output Buffer to encode into.
  11158. * @return Number of bytes encoded.
  11159. */
  11160. word32 SetLength(word32 length, byte* output)
  11161. {
  11162. /* Start encoding at start of buffer. */
  11163. word32 i = 0;
  11164. if (length < ASN_LONG_LENGTH) {
  11165. /* Only one byte needed to encode. */
  11166. if (output) {
  11167. /* Write out length value. */
  11168. output[i] = (byte)length;
  11169. }
  11170. /* Skip over length. */
  11171. i++;
  11172. }
  11173. else {
  11174. /* Calculate the number of bytes required to encode value. */
  11175. byte j = (byte)BytePrecision(length);
  11176. if (output) {
  11177. /* Encode count byte. */
  11178. output[i] = j | ASN_LONG_LENGTH;
  11179. }
  11180. /* Skip over count byte. */
  11181. i++;
  11182. /* Encode value as a big-endian byte array. */
  11183. for (; j > 0; --j) {
  11184. if (output) {
  11185. /* Encode next most-significant byte. */
  11186. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  11187. }
  11188. /* Skip over byte. */
  11189. i++;
  11190. }
  11191. }
  11192. /* Return number of bytes in encoded length. */
  11193. return i;
  11194. }
  11195. /* Encode a DER header - type/tag and length.
  11196. *
  11197. * @param [in] tag DER tag of ASN.1 item.
  11198. * @param [in] len Length of data in ASN.1 item.
  11199. * @param [out] output Buffer to encode into.
  11200. * @return Number of bytes encoded.
  11201. */
  11202. static word32 SetHeader(byte tag, word32 len, byte* output)
  11203. {
  11204. if (output) {
  11205. /* Encode tag first. */
  11206. output[0] = tag;
  11207. }
  11208. /* Encode the length. */
  11209. return SetLength(len, output ? output + ASN_TAG_SZ : NULL) + ASN_TAG_SZ;
  11210. }
  11211. /* Encode a SEQUENCE header in DER.
  11212. *
  11213. * @param [in] len Length of data in SEQUENCE.
  11214. * @param [out] output Buffer to encode into.
  11215. * @return Number of bytes encoded.
  11216. */
  11217. word32 SetSequence(word32 len, byte* output)
  11218. {
  11219. return SetHeader(ASN_SEQUENCE | ASN_CONSTRUCTED, len, output);
  11220. }
  11221. /* Encode an OCTET STRING header in DER.
  11222. *
  11223. * @param [in] len Length of data in OCTET STRING.
  11224. * @param [out] output Buffer to encode into.
  11225. * @return Number of bytes encoded.
  11226. */
  11227. word32 SetOctetString(word32 len, byte* output)
  11228. {
  11229. return SetHeader(ASN_OCTET_STRING, len, output);
  11230. }
  11231. /* Encode a SET header in DER.
  11232. *
  11233. * @param [in] len Length of data in SET.
  11234. * @param [out] output Buffer to encode into.
  11235. * @return Number of bytes encoded.
  11236. */
  11237. word32 SetSet(word32 len, byte* output)
  11238. {
  11239. return SetHeader(ASN_SET | ASN_CONSTRUCTED, len, output);
  11240. }
  11241. /* Encode an implicit context specific header in DER.
  11242. *
  11243. * Implicit means that it is constructed only if the included ASN.1 item is.
  11244. *
  11245. * @param [in] tag Tag for the implicit ASN.1 item.
  11246. * @param [in] number Context specific number.
  11247. * @param [in] len Length of data in SET.
  11248. * @param [out] output Buffer to encode into.
  11249. * @return Number of bytes encoded.
  11250. */
  11251. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  11252. {
  11253. tag = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  11254. | ASN_CONTEXT_SPECIFIC | number;
  11255. return SetHeader(tag, len, output);
  11256. }
  11257. /* Encode an explicit context specific header in DER.
  11258. *
  11259. * Explicit means that there will be an ASN.1 item underneath.
  11260. *
  11261. * @param [in] number Context specific number.
  11262. * @param [in] len Length of data in SET.
  11263. * @param [out] output Buffer to encode into.
  11264. * @return Number of bytes encoded.
  11265. */
  11266. word32 SetExplicit(byte number, word32 len, byte* output)
  11267. {
  11268. return SetHeader(ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | number, len,
  11269. output);
  11270. }
  11271. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  11272. #ifndef WOLFSSL_ASN_TEMPLATE
  11273. static int SetCurve(ecc_key* key, byte* output)
  11274. {
  11275. #ifdef HAVE_OID_ENCODING
  11276. int ret;
  11277. #endif
  11278. int idx = 0;
  11279. word32 oidSz = 0;
  11280. /* validate key */
  11281. if (key == NULL || key->dp == NULL) {
  11282. return BAD_FUNC_ARG;
  11283. }
  11284. #ifdef HAVE_OID_ENCODING
  11285. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  11286. if (ret != 0) {
  11287. return ret;
  11288. }
  11289. #else
  11290. oidSz = key->dp->oidSz;
  11291. #endif
  11292. idx += SetObjectId(oidSz, output);
  11293. #ifdef HAVE_OID_ENCODING
  11294. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  11295. if (ret != 0) {
  11296. return ret;
  11297. }
  11298. #else
  11299. XMEMCPY(output+idx, key->dp->oid, oidSz);
  11300. #endif
  11301. idx += oidSz;
  11302. return idx;
  11303. }
  11304. #endif /* !WOLFSSL_ASN_TEMPLATE */
  11305. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  11306. #ifdef HAVE_ECC
  11307. /* Determines whether the signature algorithm is using ECDSA.
  11308. *
  11309. * @param [in] algoOID Signature algorithm identifier.
  11310. * @return 1 when algorithm is using ECDSA.
  11311. * @return 0 otherwise.
  11312. */
  11313. static WC_INLINE int IsSigAlgoECDSA(int algoOID)
  11314. {
  11315. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  11316. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  11317. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  11318. return 1;
  11319. }
  11320. return 0;
  11321. }
  11322. #endif
  11323. /* Determines if OID is for an EC signing algorithm including ECDSA and EdDSA.
  11324. *
  11325. * @param [in] algoOID Algorithm OID.
  11326. * @return 1 when is EC signing algorithm.
  11327. * @return 0 otherwise.
  11328. */
  11329. static WC_INLINE int IsSigAlgoECC(int algoOID)
  11330. {
  11331. (void)algoOID;
  11332. return (0
  11333. #ifdef HAVE_ECC
  11334. || IsSigAlgoECDSA(algoOID)
  11335. #endif
  11336. #ifdef HAVE_ED25519
  11337. || (algoOID == ED25519k)
  11338. #endif
  11339. #ifdef HAVE_CURVE25519
  11340. || (algoOID == X25519k)
  11341. #endif
  11342. #ifdef HAVE_ED448
  11343. || (algoOID == ED448k)
  11344. #endif
  11345. #ifdef HAVE_CURVE448
  11346. || (algoOID == X448k)
  11347. #endif
  11348. #ifdef HAVE_LIBOQS
  11349. || (algoOID == FALCON_LEVEL1k)
  11350. || (algoOID == FALCON_LEVEL5k)
  11351. #endif
  11352. );
  11353. }
  11354. /* Encode an algorithm identifier.
  11355. *
  11356. * [algoOID, type] is unique.
  11357. *
  11358. * @param [in] algoOID Algorithm identifier.
  11359. * @param [out] output Buffer to hold encoding.
  11360. * @param [in] type Type of OID being encoded.
  11361. * @param [in] curveSz Add extra space for curve data.
  11362. * @return Encoded data size on success.
  11363. * @return 0 when dynamic memory allocation fails.
  11364. */
  11365. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  11366. {
  11367. #ifndef WOLFSSL_ASN_TEMPLATE
  11368. word32 tagSz, idSz, seqSz, algoSz = 0;
  11369. const byte* algoName = 0;
  11370. byte ID_Length[1 + MAX_LENGTH_SZ];
  11371. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  11372. int length = 0;
  11373. tagSz = (type == oidHashType ||
  11374. (type == oidSigType && !IsSigAlgoECC(algoOID)) ||
  11375. (type == oidKeyType && algoOID == RSAk)) ? 2 : 0;
  11376. algoName = OidFromId(algoOID, type, &algoSz);
  11377. if (algoName == NULL) {
  11378. WOLFSSL_MSG("Unknown Algorithm");
  11379. return 0;
  11380. }
  11381. idSz = SetObjectId(algoSz, ID_Length);
  11382. seqSz = SetSequence(idSz + algoSz + tagSz + curveSz, seqArray);
  11383. /* Copy only algo to output for DSA keys */
  11384. if (algoOID == DSAk && output) {
  11385. XMEMCPY(output, ID_Length, idSz);
  11386. XMEMCPY(output + idSz, algoName, algoSz);
  11387. if (tagSz == 2)
  11388. SetASNNull(&output[seqSz + idSz + algoSz]);
  11389. }
  11390. else if (output) {
  11391. XMEMCPY(output, seqArray, seqSz);
  11392. XMEMCPY(output + seqSz, ID_Length, idSz);
  11393. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  11394. if (tagSz == 2)
  11395. SetASNNull(&output[seqSz + idSz + algoSz]);
  11396. }
  11397. if (algoOID == DSAk)
  11398. length = idSz + algoSz + tagSz;
  11399. else
  11400. length = seqSz + idSz + algoSz + tagSz;
  11401. return length;
  11402. #else
  11403. DECL_ASNSETDATA(dataASN, algoIdASN_Length);
  11404. int sz;
  11405. int ret = 0;
  11406. int o = 0;
  11407. CALLOC_ASNSETDATA(dataASN, algoIdASN_Length, ret, NULL);
  11408. /* Set the OID and OID type to encode. */
  11409. SetASN_OID(&dataASN[1], algoOID, type);
  11410. /* Hashes, signatures not ECC and keys not RSA put put NULL tag. */
  11411. if (!(type == oidHashType ||
  11412. (type == oidSigType && !IsSigAlgoECC(algoOID)) ||
  11413. (type == oidKeyType && algoOID == RSAk))) {
  11414. /* Don't put out NULL DER item. */
  11415. dataASN[2].noOut = 1;
  11416. }
  11417. if (algoOID == DSAk) {
  11418. /* Don't include SEQUENCE for DSA keys. */
  11419. o = 1;
  11420. }
  11421. else if (curveSz > 0) {
  11422. /* Don't put out NULL DER item. */
  11423. dataASN[2].noOut = 0;
  11424. /* Include space for extra data of length curveSz.
  11425. * Subtract 1 for sequence and 1 for length encoding. */
  11426. SetASN_Buffer(&dataASN[2], NULL, curveSz - 2);
  11427. }
  11428. /* Calculate size of encoding. */
  11429. ret = SizeASN_Items(algoIdASN + o, dataASN + o, algoIdASN_Length - o, &sz);
  11430. if (ret == 0 && output != NULL) {
  11431. /* Encode into buffer. */
  11432. SetASN_Items(algoIdASN + o, dataASN + o, algoIdASN_Length - o, output);
  11433. if (curveSz > 0) {
  11434. /* Return size excluding curve data. */
  11435. sz = dataASN[o].offset - dataASN[2].offset;
  11436. }
  11437. }
  11438. if (ret == 0) {
  11439. /* Return encoded size. */
  11440. ret = sz;
  11441. }
  11442. else {
  11443. /* Unsigned return type so 0 indicates error. */
  11444. ret = 0;
  11445. }
  11446. FREE_ASNSETDATA(dataASN, NULL);
  11447. return ret;
  11448. #endif /* WOLFSSL_ASN_TEMPLATE */
  11449. }
  11450. #ifdef WOLFSSL_ASN_TEMPLATE
  11451. /* Always encode PKCS#1 v1.5 RSA signature and compare to encoded data. */
  11452. /* ASN.1 template for DigestInfo for a PKCS#1 v1.5 RSA signature.
  11453. * PKCS#1 v2.2: RFC 8017, A.2.4 - DigestInfo
  11454. */
  11455. static const ASNItem digestInfoASN[] = {
  11456. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  11457. /* digestAlgorithm */
  11458. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  11459. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  11460. /* 3 */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  11461. /* digest */
  11462. /* 4 */ { 1, ASN_OCTET_STRING, 0, 0, 0 }
  11463. };
  11464. /* Number of items in ASN.1 template for DigestInfo for RSA. */
  11465. #define digestInfoASN_Length (sizeof(digestInfoASN) / sizeof(ASNItem))
  11466. #endif
  11467. /* Encode signature.
  11468. *
  11469. * @param [out] out Buffer to hold encoding.
  11470. * @param [in] digest Buffer holding digest.
  11471. * @param [in] digSz Length of digest in bytes.
  11472. * @return Encoded data size on success.
  11473. * @return 0 when dynamic memory allocation fails.
  11474. */
  11475. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  11476. int hashOID)
  11477. {
  11478. #ifndef WOLFSSL_ASN_TEMPLATE
  11479. byte digArray[MAX_ENCODED_DIG_SZ];
  11480. byte algoArray[MAX_ALGO_SZ];
  11481. byte seqArray[MAX_SEQ_SZ];
  11482. word32 encDigSz, algoSz, seqSz;
  11483. encDigSz = SetDigest(digest, digSz, digArray);
  11484. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  11485. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  11486. XMEMCPY(out, seqArray, seqSz);
  11487. XMEMCPY(out + seqSz, algoArray, algoSz);
  11488. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  11489. return encDigSz + algoSz + seqSz;
  11490. #else
  11491. DECL_ASNSETDATA(dataASN, digestInfoASN_Length);
  11492. int ret = 0;
  11493. int sz;
  11494. CALLOC_ASNSETDATA(dataASN, digestInfoASN_Length, ret, NULL);
  11495. if (ret == 0) {
  11496. /* Set hash OID and type. */
  11497. SetASN_OID(&dataASN[2], hashOID, oidHashType);
  11498. /* Set digest. */
  11499. SetASN_Buffer(&dataASN[4], digest, digSz);
  11500. /* Calculate size of encoding. */
  11501. ret = SizeASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, &sz);
  11502. }
  11503. if (ret == 0) {
  11504. /* Encode PKCS#1 v1.5 RSA signature. */
  11505. SetASN_Items(digestInfoASN, dataASN, digestInfoASN_Length, out);
  11506. ret = sz;
  11507. }
  11508. else {
  11509. /* Unsigned return type so 0 indicates error. */
  11510. ret = 0;
  11511. }
  11512. FREE_ASNSETDATA(dataASN, NULL);
  11513. return ret;
  11514. #endif
  11515. }
  11516. #ifndef NO_CERTS
  11517. int wc_GetCTC_HashOID(int type)
  11518. {
  11519. int ret;
  11520. enum wc_HashType hType;
  11521. hType = wc_HashTypeConvert(type);
  11522. ret = wc_HashGetOID(hType);
  11523. if (ret < 0) {
  11524. ret = 0; /* backwards compatibility */
  11525. }
  11526. return ret;
  11527. }
  11528. /* Initialize a signature context object.
  11529. *
  11530. * Object used for signing and verifying a certificate signature.
  11531. *
  11532. * @param [in, out] sigCtx Signature context object.
  11533. * @param [in] heap Dynamic memory hint.
  11534. * @param [in] devId Hardware device identifier.
  11535. */
  11536. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  11537. {
  11538. if (sigCtx) {
  11539. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  11540. sigCtx->devId = devId;
  11541. sigCtx->heap = heap;
  11542. }
  11543. }
  11544. /* Free dynamic data in a signature context object.
  11545. *
  11546. * @param [in, out] sigCtx Signature context object.
  11547. */
  11548. void FreeSignatureCtx(SignatureCtx* sigCtx)
  11549. {
  11550. if (sigCtx == NULL)
  11551. return;
  11552. if (sigCtx->digest) {
  11553. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  11554. sigCtx->digest = NULL;
  11555. }
  11556. #if !(defined(NO_RSA) && defined(NO_DSA))
  11557. if (sigCtx->sigCpy) {
  11558. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  11559. sigCtx->sigCpy = NULL;
  11560. }
  11561. #endif
  11562. #ifndef NO_ASN_CRYPT
  11563. if (sigCtx->key.ptr) {
  11564. switch (sigCtx->keyOID) {
  11565. #ifndef NO_RSA
  11566. case RSAk:
  11567. wc_FreeRsaKey(sigCtx->key.rsa);
  11568. XFREE(sigCtx->key.rsa, sigCtx->heap, DYNAMIC_TYPE_RSA);
  11569. sigCtx->key.rsa = NULL;
  11570. break;
  11571. #endif /* !NO_RSA */
  11572. #ifndef NO_DSA
  11573. case DSAk:
  11574. wc_FreeDsaKey(sigCtx->key.dsa);
  11575. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  11576. sigCtx->key.dsa = NULL;
  11577. break;
  11578. #endif
  11579. #ifdef HAVE_ECC
  11580. case ECDSAk:
  11581. wc_ecc_free(sigCtx->key.ecc);
  11582. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  11583. sigCtx->key.ecc = NULL;
  11584. break;
  11585. #endif /* HAVE_ECC */
  11586. #ifdef HAVE_ED25519
  11587. case ED25519k:
  11588. wc_ed25519_free(sigCtx->key.ed25519);
  11589. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  11590. sigCtx->key.ed25519 = NULL;
  11591. break;
  11592. #endif /* HAVE_ED25519 */
  11593. #ifdef HAVE_ED448
  11594. case ED448k:
  11595. wc_ed448_free(sigCtx->key.ed448);
  11596. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  11597. sigCtx->key.ed448 = NULL;
  11598. break;
  11599. #endif /* HAVE_ED448 */
  11600. #ifdef HAVE_LIBOQS
  11601. case FALCON_LEVEL1k:
  11602. case FALCON_LEVEL5k:
  11603. wc_falcon_free(sigCtx->key.falcon);
  11604. XFREE(sigCtx->key.falcon, sigCtx->heap,
  11605. DYNAMIC_TYPE_FALCON);
  11606. sigCtx->key.falcon = NULL;
  11607. break;
  11608. #endif /* HAVE_LIBOQS */
  11609. default:
  11610. break;
  11611. } /* switch (keyOID) */
  11612. sigCtx->key.ptr = NULL;
  11613. }
  11614. #endif
  11615. /* reset state, we are done */
  11616. sigCtx->state = SIG_STATE_BEGIN;
  11617. }
  11618. #ifndef NO_ASN_CRYPT
  11619. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  11620. byte* digest, int* typeH, int* digestSz, int verify)
  11621. {
  11622. int ret = 0;
  11623. switch (sigOID) {
  11624. #if defined(WOLFSSL_MD2)
  11625. case CTC_MD2wRSA:
  11626. if (!verify) {
  11627. ret = HASH_TYPE_E;
  11628. WOLFSSL_MSG("MD2 not supported for signing");
  11629. }
  11630. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  11631. *typeH = MD2h;
  11632. *digestSz = MD2_DIGEST_SIZE;
  11633. }
  11634. break;
  11635. #endif
  11636. #ifndef NO_MD5
  11637. case CTC_MD5wRSA:
  11638. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  11639. *typeH = MD5h;
  11640. *digestSz = WC_MD5_DIGEST_SIZE;
  11641. }
  11642. break;
  11643. #endif
  11644. #ifndef NO_SHA
  11645. case CTC_SHAwRSA:
  11646. case CTC_SHAwDSA:
  11647. case CTC_SHAwECDSA:
  11648. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  11649. *typeH = SHAh;
  11650. *digestSz = WC_SHA_DIGEST_SIZE;
  11651. }
  11652. break;
  11653. #endif
  11654. #ifdef WOLFSSL_SHA224
  11655. case CTC_SHA224wRSA:
  11656. case CTC_SHA224wECDSA:
  11657. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  11658. *typeH = SHA224h;
  11659. *digestSz = WC_SHA224_DIGEST_SIZE;
  11660. }
  11661. break;
  11662. #endif
  11663. #ifndef NO_SHA256
  11664. case CTC_SHA256wRSA:
  11665. case CTC_SHA256wECDSA:
  11666. case CTC_SHA256wDSA:
  11667. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  11668. *typeH = SHA256h;
  11669. *digestSz = WC_SHA256_DIGEST_SIZE;
  11670. }
  11671. break;
  11672. #endif
  11673. #ifdef WOLFSSL_SHA384
  11674. case CTC_SHA384wRSA:
  11675. case CTC_SHA384wECDSA:
  11676. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  11677. *typeH = SHA384h;
  11678. *digestSz = WC_SHA384_DIGEST_SIZE;
  11679. }
  11680. break;
  11681. #endif
  11682. #ifdef WOLFSSL_SHA512
  11683. case CTC_SHA512wRSA:
  11684. case CTC_SHA512wECDSA:
  11685. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  11686. *typeH = SHA512h;
  11687. *digestSz = WC_SHA512_DIGEST_SIZE;
  11688. }
  11689. break;
  11690. #endif
  11691. #ifdef WOLFSSL_SHA3
  11692. #ifndef WOLFSSL_NOSHA3_224
  11693. case CTC_SHA3_224wRSA:
  11694. case CTC_SHA3_224wECDSA:
  11695. if ((ret = wc_Sha3_224Hash(buf, bufSz, digest)) == 0) {
  11696. *typeH = SHA3_224h;
  11697. *digestSz = WC_SHA3_224_DIGEST_SIZE;
  11698. }
  11699. break;
  11700. #endif
  11701. #ifndef WOLFSSL_NOSHA3_256
  11702. case CTC_SHA3_256wRSA:
  11703. case CTC_SHA3_256wECDSA:
  11704. if ((ret = wc_Sha3_256Hash(buf, bufSz, digest)) == 0) {
  11705. *typeH = SHA3_256h;
  11706. *digestSz = WC_SHA3_256_DIGEST_SIZE;
  11707. }
  11708. break;
  11709. #endif
  11710. #ifndef WOLFSSL_NOSHA3_384
  11711. case CTC_SHA3_384wRSA:
  11712. case CTC_SHA3_384wECDSA:
  11713. if ((ret = wc_Sha3_384Hash(buf, bufSz, digest)) == 0) {
  11714. *typeH = SHA3_384h;
  11715. *digestSz = WC_SHA3_384_DIGEST_SIZE;
  11716. }
  11717. break;
  11718. #endif
  11719. #ifndef WOLFSSL_NOSHA3_512
  11720. case CTC_SHA3_512wRSA:
  11721. case CTC_SHA3_512wECDSA:
  11722. if ((ret = wc_Sha3_512Hash(buf, bufSz, digest)) == 0) {
  11723. *typeH = SHA3_512h;
  11724. *digestSz = WC_SHA3_512_DIGEST_SIZE;
  11725. }
  11726. break;
  11727. #endif
  11728. #endif
  11729. #ifdef HAVE_ED25519
  11730. case CTC_ED25519:
  11731. /* Hashes done in signing operation.
  11732. * Two dependent hashes with prefixes performed.
  11733. */
  11734. break;
  11735. #endif
  11736. #ifdef HAVE_ED448
  11737. case CTC_ED448:
  11738. /* Hashes done in signing operation.
  11739. * Two dependent hashes with prefixes performed.
  11740. */
  11741. break;
  11742. #endif
  11743. #ifdef HAVE_LIBOQS
  11744. case CTC_FALCON_LEVEL1:
  11745. case CTC_FALCON_LEVEL5:
  11746. /* Hashes done in signing operation. */
  11747. break;
  11748. #endif
  11749. default:
  11750. ret = HASH_TYPE_E;
  11751. WOLFSSL_MSG("Hash for Signature has unsupported type");
  11752. }
  11753. (void)buf;
  11754. (void)bufSz;
  11755. (void)sigOID;
  11756. (void)digest;
  11757. (void)digestSz;
  11758. (void)typeH;
  11759. (void)verify;
  11760. return ret;
  11761. }
  11762. #endif /* !NO_ASN_CRYPT */
  11763. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  11764. static int ConfirmSignature(SignatureCtx* sigCtx,
  11765. const byte* buf, word32 bufSz,
  11766. const byte* key, word32 keySz, word32 keyOID,
  11767. const byte* sig, word32 sigSz, word32 sigOID, byte* rsaKeyIdx)
  11768. {
  11769. int ret = 0;
  11770. #ifndef WOLFSSL_RENESAS_TSIP_TLS
  11771. (void)rsaKeyIdx;
  11772. #endif
  11773. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  11774. keySz == 0 || sig == NULL || sigSz == 0) {
  11775. return BAD_FUNC_ARG;
  11776. }
  11777. (void)key;
  11778. (void)keySz;
  11779. (void)sig;
  11780. (void)sigSz;
  11781. WOLFSSL_ENTER("ConfirmSignature");
  11782. #ifndef NO_ASN_CRYPT
  11783. switch (sigCtx->state) {
  11784. case SIG_STATE_BEGIN:
  11785. {
  11786. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  11787. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  11788. DYNAMIC_TYPE_DIGEST);
  11789. if (sigCtx->digest == NULL) {
  11790. ERROR_OUT(MEMORY_E, exit_cs);
  11791. }
  11792. sigCtx->state = SIG_STATE_HASH;
  11793. } /* SIG_STATE_BEGIN */
  11794. FALL_THROUGH;
  11795. case SIG_STATE_HASH:
  11796. {
  11797. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  11798. &sigCtx->typeH, &sigCtx->digestSz, 1);
  11799. if (ret != 0) {
  11800. goto exit_cs;
  11801. }
  11802. sigCtx->state = SIG_STATE_KEY;
  11803. } /* SIG_STATE_HASH */
  11804. FALL_THROUGH;
  11805. case SIG_STATE_KEY:
  11806. {
  11807. switch (keyOID) {
  11808. #ifndef NO_RSA
  11809. case RSAk:
  11810. {
  11811. word32 idx = 0;
  11812. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  11813. sigCtx->heap, DYNAMIC_TYPE_RSA);
  11814. sigCtx->sigCpy = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  11815. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  11816. if (sigCtx->key.rsa == NULL || sigCtx->sigCpy == NULL) {
  11817. ERROR_OUT(MEMORY_E, exit_cs);
  11818. }
  11819. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  11820. sigCtx->devId)) != 0) {
  11821. goto exit_cs;
  11822. }
  11823. if (sigSz > MAX_ENCODED_SIG_SZ) {
  11824. WOLFSSL_MSG("Verify Signature is too big");
  11825. ERROR_OUT(BUFFER_E, exit_cs);
  11826. }
  11827. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  11828. keySz)) != 0) {
  11829. WOLFSSL_MSG("ASN Key decode error RSA");
  11830. goto exit_cs;
  11831. }
  11832. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  11833. sigCtx->out = NULL;
  11834. #ifdef WOLFSSL_ASYNC_CRYPT
  11835. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  11836. #endif
  11837. break;
  11838. }
  11839. #endif /* !NO_RSA */
  11840. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  11841. case DSAk:
  11842. {
  11843. word32 idx = 0;
  11844. if (sigSz < DSA_MIN_SIG_SIZE) {
  11845. WOLFSSL_MSG("Verify Signature is too small");
  11846. ERROR_OUT(BUFFER_E, exit_cs);
  11847. }
  11848. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  11849. sigCtx->heap, DYNAMIC_TYPE_DSA);
  11850. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  11851. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  11852. if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
  11853. ERROR_OUT(MEMORY_E, exit_cs);
  11854. }
  11855. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  11856. WOLFSSL_MSG("wc_InitDsaKey_h error");
  11857. goto exit_cs;
  11858. }
  11859. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  11860. keySz)) != 0) {
  11861. WOLFSSL_MSG("ASN Key decode error DSA");
  11862. goto exit_cs;
  11863. }
  11864. if (sigSz != DSA_160_SIG_SIZE &&
  11865. sigSz != DSA_256_SIG_SIZE) {
  11866. /* Try to parse it as the contents of a bitstring */
  11867. #ifdef WOLFSSL_SMALL_STACK
  11868. mp_int* r;
  11869. mp_int* s;
  11870. #else
  11871. mp_int r[1];
  11872. mp_int s[1];
  11873. #endif
  11874. int rSz;
  11875. int sSz;
  11876. #ifdef WOLFSSL_SMALL_STACK
  11877. r = (mp_int*)XMALLOC(sizeof(*r), sigCtx->heap,
  11878. DYNAMIC_TYPE_TMP_BUFFER);
  11879. if (r == NULL) {
  11880. ERROR_OUT(MEMORY_E, exit_cs);
  11881. }
  11882. s = (mp_int*)XMALLOC(sizeof(*s), sigCtx->heap,
  11883. DYNAMIC_TYPE_TMP_BUFFER);
  11884. if (s == NULL) {
  11885. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11886. ERROR_OUT(MEMORY_E, exit_cs);
  11887. }
  11888. #endif
  11889. mp_init(r);
  11890. mp_init(s);
  11891. idx = 0;
  11892. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx, r, s)
  11893. != 0) {
  11894. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  11895. "incorrect format");
  11896. mp_free(r);
  11897. mp_free(s);
  11898. #ifdef WOLFSSL_SMALL_STACK
  11899. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11900. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11901. #endif
  11902. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  11903. }
  11904. rSz = mp_unsigned_bin_size(r);
  11905. sSz = mp_unsigned_bin_size(s);
  11906. if (rSz + sSz > (int)sigSz) {
  11907. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  11908. "incorrect format");
  11909. mp_free(r);
  11910. mp_free(s);
  11911. #ifdef WOLFSSL_SMALL_STACK
  11912. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11913. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11914. #endif
  11915. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  11916. }
  11917. if (mp_to_unsigned_bin(r, sigCtx->sigCpy) != MP_OKAY ||
  11918. mp_to_unsigned_bin(s,
  11919. sigCtx->sigCpy + rSz) != MP_OKAY) {
  11920. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  11921. "incorrect format");
  11922. mp_free(r);
  11923. mp_free(s);
  11924. #ifdef WOLFSSL_SMALL_STACK
  11925. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11926. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11927. #endif
  11928. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  11929. }
  11930. mp_free(r);
  11931. mp_free(s);
  11932. #ifdef WOLFSSL_SMALL_STACK
  11933. XFREE(r, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11934. XFREE(s, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11935. #endif
  11936. }
  11937. else {
  11938. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  11939. }
  11940. break;
  11941. }
  11942. #endif /* !NO_DSA && !HAVE_SELFTEST */
  11943. #ifdef HAVE_ECC
  11944. case ECDSAk:
  11945. {
  11946. word32 idx = 0;
  11947. sigCtx->verify = 0;
  11948. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  11949. sigCtx->heap, DYNAMIC_TYPE_ECC);
  11950. if (sigCtx->key.ecc == NULL) {
  11951. ERROR_OUT(MEMORY_E, exit_cs);
  11952. }
  11953. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  11954. sigCtx->devId)) < 0) {
  11955. goto exit_cs;
  11956. }
  11957. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  11958. keySz);
  11959. if (ret < 0) {
  11960. WOLFSSL_MSG("ASN Key import error ECC");
  11961. goto exit_cs;
  11962. }
  11963. #ifdef WOLFSSL_ASYNC_CRYPT
  11964. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  11965. #endif
  11966. break;
  11967. }
  11968. #endif /* HAVE_ECC */
  11969. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  11970. case ED25519k:
  11971. {
  11972. sigCtx->verify = 0;
  11973. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  11974. sizeof(ed25519_key), sigCtx->heap,
  11975. DYNAMIC_TYPE_ED25519);
  11976. if (sigCtx->key.ed25519 == NULL) {
  11977. ERROR_OUT(MEMORY_E, exit_cs);
  11978. }
  11979. if ((ret = wc_ed25519_init_ex(sigCtx->key.ed25519,
  11980. sigCtx->heap, sigCtx->devId)) < 0) {
  11981. goto exit_cs;
  11982. }
  11983. if ((ret = wc_ed25519_import_public(key, keySz,
  11984. sigCtx->key.ed25519)) < 0) {
  11985. WOLFSSL_MSG("ASN Key import error ED25519");
  11986. goto exit_cs;
  11987. }
  11988. #ifdef WOLFSSL_ASYNC_CRYPT
  11989. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  11990. #endif
  11991. break;
  11992. }
  11993. #endif
  11994. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  11995. case ED448k:
  11996. {
  11997. sigCtx->verify = 0;
  11998. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  11999. sizeof(ed448_key), sigCtx->heap,
  12000. DYNAMIC_TYPE_ED448);
  12001. if (sigCtx->key.ed448 == NULL) {
  12002. ERROR_OUT(MEMORY_E, exit_cs);
  12003. }
  12004. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  12005. goto exit_cs;
  12006. }
  12007. if ((ret = wc_ed448_import_public(key, keySz,
  12008. sigCtx->key.ed448)) < 0) {
  12009. WOLFSSL_MSG("ASN Key import error ED448");
  12010. goto exit_cs;
  12011. }
  12012. #ifdef WOLFSSL_ASYNC_CRYPT
  12013. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  12014. #endif
  12015. break;
  12016. }
  12017. #endif
  12018. #if defined(HAVE_LIBOQS)
  12019. case FALCON_LEVEL1k:
  12020. {
  12021. sigCtx->verify = 0;
  12022. sigCtx->key.falcon =
  12023. (falcon_key*)XMALLOC(sizeof(falcon_key),
  12024. sigCtx->heap,
  12025. DYNAMIC_TYPE_FALCON);
  12026. if (sigCtx->key.falcon == NULL) {
  12027. ERROR_OUT(MEMORY_E, exit_cs);
  12028. }
  12029. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  12030. goto exit_cs;
  12031. }
  12032. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 1))
  12033. < 0) {
  12034. goto exit_cs;
  12035. }
  12036. if ((ret = wc_falcon_import_public(key, keySz,
  12037. sigCtx->key.falcon)) < 0) {
  12038. WOLFSSL_MSG("ASN Key import error Falcon Level 1");
  12039. goto exit_cs;
  12040. }
  12041. break;
  12042. }
  12043. case FALCON_LEVEL5k:
  12044. {
  12045. sigCtx->verify = 0;
  12046. sigCtx->key.falcon =
  12047. (falcon_key*)XMALLOC(sizeof(falcon_key),
  12048. sigCtx->heap,
  12049. DYNAMIC_TYPE_FALCON);
  12050. if (sigCtx->key.falcon == NULL) {
  12051. ERROR_OUT(MEMORY_E, exit_cs);
  12052. }
  12053. if ((ret = wc_falcon_init(sigCtx->key.falcon)) < 0) {
  12054. goto exit_cs;
  12055. }
  12056. if ((ret = wc_falcon_set_level(sigCtx->key.falcon, 5))
  12057. < 0) {
  12058. goto exit_cs;
  12059. }
  12060. if ((ret = wc_falcon_import_public(key, keySz,
  12061. sigCtx->key.falcon)) < 0) {
  12062. WOLFSSL_MSG("ASN Key import error Falcon Level 5");
  12063. goto exit_cs;
  12064. }
  12065. break;
  12066. }
  12067. #endif
  12068. default:
  12069. WOLFSSL_MSG("Verify Key type unknown");
  12070. ret = ASN_UNKNOWN_OID_E;
  12071. break;
  12072. } /* switch (keyOID) */
  12073. if (ret != 0) {
  12074. goto exit_cs;
  12075. }
  12076. sigCtx->state = SIG_STATE_DO;
  12077. #ifdef WOLFSSL_ASYNC_CRYPT
  12078. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  12079. /* make sure event is initialized */
  12080. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  12081. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  12082. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  12083. }
  12084. #endif
  12085. } /* SIG_STATE_KEY */
  12086. FALL_THROUGH;
  12087. case SIG_STATE_DO:
  12088. {
  12089. switch (keyOID) {
  12090. #ifndef NO_RSA
  12091. case RSAk:
  12092. {
  12093. #ifdef HAVE_PK_CALLBACKS
  12094. if (sigCtx->pkCbRsa) {
  12095. ret = sigCtx->pkCbRsa(
  12096. sigCtx->sigCpy, sigSz, &sigCtx->out,
  12097. key, keySz,
  12098. sigCtx->pkCtxRsa);
  12099. }
  12100. else
  12101. #endif /* HAVE_PK_CALLBACKS */
  12102. {
  12103. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  12104. if (rsaKeyIdx != NULL)
  12105. {
  12106. ret = tsip_tls_CertVerify(buf, bufSz, sigCtx->sigCpy,
  12107. sigSz,
  12108. sigCtx->pubkey_n_start - sigCtx->certBegin,
  12109. sigCtx->pubkey_n_len - 1,
  12110. sigCtx->pubkey_e_start - sigCtx->certBegin,
  12111. sigCtx->pubkey_e_len - 1,
  12112. rsaKeyIdx);
  12113. if (ret == 0){
  12114. sigCtx->verifyByTSIP = 1;
  12115. ret = 0;
  12116. } else {
  12117. WOLFSSL_MSG("RSA Verify by tsip didn't match");
  12118. ret = ASN_SIG_CONFIRM_E;
  12119. }
  12120. } else
  12121. #endif
  12122. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  12123. &sigCtx->out, sigCtx->key.rsa);
  12124. }
  12125. break;
  12126. }
  12127. #endif /* !NO_RSA */
  12128. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  12129. case DSAk:
  12130. {
  12131. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  12132. sigCtx->key.dsa, &sigCtx->verify);
  12133. break;
  12134. }
  12135. #endif /* !NO_DSA && !HAVE_SELFTEST */
  12136. #if defined(HAVE_ECC)
  12137. case ECDSAk:
  12138. {
  12139. #ifdef HAVE_PK_CALLBACKS
  12140. if (sigCtx->pkCbEcc) {
  12141. ret = sigCtx->pkCbEcc(
  12142. sig, sigSz,
  12143. sigCtx->digest, sigCtx->digestSz,
  12144. key, keySz, &sigCtx->verify,
  12145. sigCtx->pkCtxEcc);
  12146. }
  12147. else
  12148. #endif /* HAVE_PK_CALLBACKS */
  12149. {
  12150. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  12151. sigCtx->digestSz, &sigCtx->verify,
  12152. sigCtx->key.ecc);
  12153. }
  12154. break;
  12155. }
  12156. #endif /* HAVE_ECC */
  12157. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_VERIFY)
  12158. case ED25519k:
  12159. {
  12160. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  12161. &sigCtx->verify, sigCtx->key.ed25519);
  12162. break;
  12163. }
  12164. #endif
  12165. #if defined(HAVE_ED448) && defined(HAVE_ED448_VERIFY)
  12166. case ED448k:
  12167. {
  12168. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  12169. &sigCtx->verify, sigCtx->key.ed448,
  12170. NULL, 0);
  12171. break;
  12172. }
  12173. #endif
  12174. #if defined(HAVE_LIBOQS)
  12175. case FALCON_LEVEL1k:
  12176. case FALCON_LEVEL5k:
  12177. {
  12178. ret = wc_falcon_verify_msg(sig, sigSz, buf, bufSz,
  12179. &sigCtx->verify,
  12180. sigCtx->key.falcon);
  12181. break;
  12182. }
  12183. #endif
  12184. default:
  12185. break;
  12186. } /* switch (keyOID) */
  12187. #ifdef WOLFSSL_ASYNC_CRYPT
  12188. if (ret == WC_PENDING_E) {
  12189. goto exit_cs;
  12190. }
  12191. #endif
  12192. if (ret < 0) {
  12193. /* treat all RSA errors as ASN_SIG_CONFIRM_E */
  12194. ret = ASN_SIG_CONFIRM_E;
  12195. goto exit_cs;
  12196. }
  12197. sigCtx->state = SIG_STATE_CHECK;
  12198. } /* SIG_STATE_DO */
  12199. FALL_THROUGH;
  12200. case SIG_STATE_CHECK:
  12201. {
  12202. switch (keyOID) {
  12203. #ifndef NO_RSA
  12204. case RSAk:
  12205. {
  12206. int encodedSigSz, verifySz;
  12207. #ifdef WOLFSSL_RENESAS_TSIP
  12208. if (sigCtx->verifyByTSIP == 1) break;
  12209. #endif
  12210. #ifdef WOLFSSL_SMALL_STACK
  12211. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  12212. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12213. if (encodedSig == NULL) {
  12214. ERROR_OUT(MEMORY_E, exit_cs);
  12215. }
  12216. #else
  12217. byte encodedSig[MAX_ENCODED_SIG_SZ];
  12218. #endif
  12219. verifySz = ret;
  12220. /* make sure we're right justified */
  12221. encodedSigSz = wc_EncodeSignature(encodedSig,
  12222. sigCtx->digest, sigCtx->digestSz, sigCtx->typeH);
  12223. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  12224. XMEMCMP(sigCtx->out, encodedSig, encodedSigSz) == 0) {
  12225. ret = 0;
  12226. }
  12227. else {
  12228. WOLFSSL_MSG("RSA SSL verify match encode error");
  12229. ret = ASN_SIG_CONFIRM_E;
  12230. }
  12231. #ifdef WOLFSSL_SMALL_STACK
  12232. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12233. #endif
  12234. break;
  12235. }
  12236. #endif /* NO_RSA */
  12237. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  12238. case DSAk:
  12239. {
  12240. if (sigCtx->verify == 1) {
  12241. ret = 0;
  12242. }
  12243. else {
  12244. WOLFSSL_MSG("DSA Verify didn't match");
  12245. ret = ASN_SIG_CONFIRM_E;
  12246. }
  12247. break;
  12248. }
  12249. #endif /* !NO_DSA && !HAVE_SELFTEST */
  12250. #ifdef HAVE_ECC
  12251. case ECDSAk:
  12252. {
  12253. if (sigCtx->verify == 1) {
  12254. ret = 0;
  12255. }
  12256. else {
  12257. WOLFSSL_MSG("ECC Verify didn't match");
  12258. ret = ASN_SIG_CONFIRM_E;
  12259. }
  12260. break;
  12261. }
  12262. #endif /* HAVE_ECC */
  12263. #ifdef HAVE_ED25519
  12264. case ED25519k:
  12265. {
  12266. if (sigCtx->verify == 1) {
  12267. ret = 0;
  12268. }
  12269. else {
  12270. WOLFSSL_MSG("ED25519 Verify didn't match");
  12271. ret = ASN_SIG_CONFIRM_E;
  12272. }
  12273. break;
  12274. }
  12275. #endif /* HAVE_ED25519 */
  12276. #ifdef HAVE_ED448
  12277. case ED448k:
  12278. {
  12279. if (sigCtx->verify == 1) {
  12280. ret = 0;
  12281. }
  12282. else {
  12283. WOLFSSL_MSG("ED448 Verify didn't match");
  12284. ret = ASN_SIG_CONFIRM_E;
  12285. }
  12286. break;
  12287. }
  12288. #endif /* HAVE_ED448 */
  12289. #ifdef HAVE_LIBOQS
  12290. case FALCON_LEVEL1k:
  12291. {
  12292. if (sigCtx->verify == 1) {
  12293. ret = 0;
  12294. }
  12295. else {
  12296. WOLFSSL_MSG("FALCON_LEVEL1 Verify didn't match");
  12297. ret = ASN_SIG_CONFIRM_E;
  12298. }
  12299. break;
  12300. }
  12301. case FALCON_LEVEL5k:
  12302. {
  12303. if (sigCtx->verify == 1) {
  12304. ret = 0;
  12305. }
  12306. else {
  12307. WOLFSSL_MSG("FALCON_LEVEL5 Verify didn't match");
  12308. ret = ASN_SIG_CONFIRM_E;
  12309. }
  12310. break;
  12311. }
  12312. #endif /* HAVE_LIBOQS */
  12313. default:
  12314. break;
  12315. } /* switch (keyOID) */
  12316. break;
  12317. } /* SIG_STATE_CHECK */
  12318. default:
  12319. break;
  12320. } /* switch (sigCtx->state) */
  12321. exit_cs:
  12322. #endif /* !NO_ASN_CRYPT */
  12323. (void)keyOID;
  12324. (void)sigOID;
  12325. WOLFSSL_LEAVE("ConfirmSignature", ret);
  12326. #ifdef WOLFSSL_ASYNC_CRYPT
  12327. if (ret == WC_PENDING_E)
  12328. return ret;
  12329. #endif
  12330. FreeSignatureCtx(sigCtx);
  12331. return ret;
  12332. }
  12333. #ifndef IGNORE_NAME_CONSTRAINTS
  12334. static int MatchBaseName(int type, const char* name, int nameSz,
  12335. const char* base, int baseSz)
  12336. {
  12337. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  12338. name[0] == '.' || nameSz < baseSz ||
  12339. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE &&
  12340. type != ASN_DIR_TYPE)) {
  12341. return 0;
  12342. }
  12343. if (type == ASN_DIR_TYPE)
  12344. return XMEMCMP(name, base, baseSz) == 0;
  12345. /* If an email type, handle special cases where the base is only
  12346. * a domain, or is an email address itself. */
  12347. if (type == ASN_RFC822_TYPE) {
  12348. const char* p = NULL;
  12349. int count = 0;
  12350. if (base[0] != '.') {
  12351. p = base;
  12352. count = 0;
  12353. /* find the '@' in the base */
  12354. while (*p != '@' && count < baseSz) {
  12355. count++;
  12356. p++;
  12357. }
  12358. /* No '@' in base, reset p to NULL */
  12359. if (count >= baseSz)
  12360. p = NULL;
  12361. }
  12362. if (p == NULL) {
  12363. /* Base isn't an email address, it is a domain name,
  12364. * wind the name forward one character past its '@'. */
  12365. p = name;
  12366. count = 0;
  12367. while (*p != '@' && count < baseSz) {
  12368. count++;
  12369. p++;
  12370. }
  12371. if (count < baseSz && *p == '@') {
  12372. name = p + 1;
  12373. nameSz -= count + 1;
  12374. }
  12375. }
  12376. }
  12377. /* RFC 5280 section 4.2.1.10
  12378. * "...Any DNS name that can be constructed by simply adding zero or more
  12379. * labels to the left-hand side of the name satisfies the name constraint."
  12380. * i.e www.host.example.com works for host.example.com name constraint and
  12381. * host1.example.com does not. */
  12382. if (type == ASN_DNS_TYPE || (type == ASN_RFC822_TYPE && base[0] == '.')) {
  12383. int szAdjust = nameSz - baseSz;
  12384. name += szAdjust;
  12385. nameSz -= szAdjust;
  12386. }
  12387. while (nameSz > 0) {
  12388. if (XTOLOWER((unsigned char)*name++) !=
  12389. XTOLOWER((unsigned char)*base++))
  12390. return 0;
  12391. nameSz--;
  12392. }
  12393. return 1;
  12394. }
  12395. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  12396. {
  12397. const byte nameTypes[] = {ASN_RFC822_TYPE, ASN_DNS_TYPE, ASN_DIR_TYPE};
  12398. int i;
  12399. if (signer == NULL || cert == NULL)
  12400. return 0;
  12401. if (signer->excludedNames == NULL && signer->permittedNames == NULL)
  12402. return 1;
  12403. for (i=0; i < (int)sizeof(nameTypes); i++) {
  12404. byte nameType = nameTypes[i];
  12405. DNS_entry* name = NULL;
  12406. DNS_entry subjectDnsName;
  12407. Base_entry* base;
  12408. switch (nameType) {
  12409. case ASN_DNS_TYPE:
  12410. /* Should it also consider CN in subject? It could use
  12411. * subjectDnsName too */
  12412. name = cert->altNames;
  12413. break;
  12414. case ASN_RFC822_TYPE:
  12415. /* Shouldn't it validade E= in subject as well? */
  12416. name = cert->altEmailNames;
  12417. break;
  12418. case ASN_DIR_TYPE:
  12419. if (cert->subjectRaw != NULL) {
  12420. subjectDnsName.next = NULL;
  12421. subjectDnsName.type = ASN_DIR_TYPE;
  12422. subjectDnsName.len = cert->subjectRawLen;
  12423. subjectDnsName.name = (char *)cert->subjectRaw;
  12424. name = &subjectDnsName;
  12425. }
  12426. #ifndef WOLFSSL_NO_ASN_STRICT
  12427. /* RFC 5280 section 4.2.1.10
  12428. "Restrictions of the form directoryName MUST be
  12429. applied to the subject field .... and to any names
  12430. of type directoryName in the subjectAltName
  12431. extension"
  12432. */
  12433. if (name != NULL)
  12434. name->next = cert->altDirNames;
  12435. else
  12436. name = cert->altDirNames;
  12437. #endif
  12438. break;
  12439. default:
  12440. /* Other types of names are ignored for now.
  12441. * Shouldn't it be rejected if it there is a altNamesByType[nameType]
  12442. * and signer->extNameConstraintCrit is set? */
  12443. return 0;
  12444. }
  12445. while (name != NULL) {
  12446. int match = 0;
  12447. int need = 0;
  12448. base = signer->excludedNames;
  12449. /* Check against the excluded list */
  12450. while (base != NULL) {
  12451. if (base->type == nameType) {
  12452. if (name->len >= base->nameSz &&
  12453. MatchBaseName(nameType,
  12454. name->name, name->len,
  12455. base->name, base->nameSz)) {
  12456. return 0;
  12457. }
  12458. }
  12459. base = base->next;
  12460. }
  12461. /* Check against the permitted list */
  12462. base = signer->permittedNames;
  12463. while (base != NULL) {
  12464. if (base->type == nameType) {
  12465. need = 1;
  12466. if (name->len >= base->nameSz &&
  12467. MatchBaseName(nameType,
  12468. name->name, name->len,
  12469. base->name, base->nameSz)) {
  12470. match = 1;
  12471. break;
  12472. }
  12473. }
  12474. base = base->next;
  12475. }
  12476. if (need && !match)
  12477. return 0;
  12478. name = name->next;
  12479. }
  12480. }
  12481. return 1;
  12482. }
  12483. #endif /* IGNORE_NAME_CONSTRAINTS */
  12484. #ifndef WOLFSSL_ASN_TEMPLATE
  12485. static void AddAltName(DecodedCert* cert, DNS_entry* dnsEntry)
  12486. {
  12487. #if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_ALT_NAMES_NO_REV)
  12488. dnsEntry->next = NULL;
  12489. if (cert->altNames == NULL) {
  12490. /* First on list */
  12491. cert->altNames = dnsEntry;
  12492. }
  12493. else {
  12494. DNS_entry* temp = cert->altNames;
  12495. /* Find end */
  12496. for (; (temp->next != NULL); temp = temp->next);
  12497. /* Add to end */
  12498. temp->next = dnsEntry;
  12499. }
  12500. #else
  12501. dnsEntry->next = cert->altNames;
  12502. cert->altNames = dnsEntry;
  12503. #endif
  12504. }
  12505. #endif
  12506. #ifdef WOLFSSL_ASN_TEMPLATE
  12507. #ifdef WOLFSSL_SEP
  12508. /* ASN.1 template for OtherName of an X.509 certificate.
  12509. * X.509: RFC 5280, 4.2.1.6 - OtherName (without implicit outer SEQUENCE).
  12510. * Only support HW Name where the type is a HW serial number.
  12511. */
  12512. static const ASNItem otherNameASN[] = {
  12513. /* 0 */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  12514. /* 1 */ { 0, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 0 },
  12515. /* 2 */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  12516. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  12517. /* 4 */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  12518. };
  12519. /* Number of items in ASN.1 template for OtherName of an X.509 certificate. */
  12520. #define otherNameASN_Length (sizeof(otherNameASN) / sizeof(ASNItem))
  12521. /* Decode data with OtherName format from after implicit SEQUENCE.
  12522. *
  12523. * @param [in, out] cert Certificate object.
  12524. * @param [in] input Buffer containing encoded OtherName.
  12525. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  12526. * On out, index after OtherName.
  12527. * @param [in] maxIdx Maximum index of data in buffer.
  12528. * @return 0 on success.
  12529. * @return MEMORY_E on dynamic memory allocation failure.
  12530. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12531. * is invalid.
  12532. * @return ASN_PARSE_E when OID does is not HW Name.
  12533. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12534. * @return BUFFER_E when data in buffer is too small.
  12535. */
  12536. static int DecodeOtherName(DecodedCert* cert, const byte* input,
  12537. word32* inOutIdx, word32 maxIdx)
  12538. {
  12539. DECL_ASNGETDATA(dataASN, otherNameASN_Length);
  12540. int ret = 0;
  12541. word32 oidLen, serialLen;
  12542. CALLOC_ASNGETDATA(dataASN, otherNameASN_Length, ret, cert->heap);
  12543. if (ret == 0) {
  12544. /* Check the first OID is a recognized Alt Cert Name type. */
  12545. GetASN_OID(&dataASN[0], oidCertAltNameType);
  12546. /* Only support HW serial number. */
  12547. GetASN_OID(&dataASN[3], oidIgnoreType);
  12548. /* Parse OtherName. */
  12549. ret = GetASN_Items(otherNameASN, dataASN, otherNameASN_Length, 1, input,
  12550. inOutIdx, maxIdx);
  12551. }
  12552. if (ret == 0) {
  12553. /* Ensure expected OID. */
  12554. if (dataASN[0].data.oid.sum != HW_NAME_OID) {
  12555. WOLFSSL_MSG("\tincorrect OID");
  12556. ret = ASN_PARSE_E;
  12557. }
  12558. }
  12559. if (ret == 0) {
  12560. oidLen = dataASN[3].data.oid.length;
  12561. serialLen = dataASN[4].data.ref.length;
  12562. /* Allocate space for HW type OID. */
  12563. cert->hwType = (byte*)XMALLOC(oidLen, cert->heap,
  12564. DYNAMIC_TYPE_X509_EXT);
  12565. if (cert->hwType == NULL)
  12566. ret = MEMORY_E;
  12567. }
  12568. if (ret == 0) {
  12569. /* Copy, into cert HW type OID */
  12570. XMEMCPY(cert->hwType, dataASN[3].data.oid.data, oidLen);
  12571. cert->hwTypeSz = oidLen;
  12572. /* TODO: check this is the HW serial number OID - no test data. */
  12573. /* Allocate space for HW serial number. */
  12574. cert->hwSerialNum = (byte*)XMALLOC(serialLen, cert->heap,
  12575. DYNAMIC_TYPE_X509_EXT);
  12576. if (cert->hwSerialNum == NULL) {
  12577. WOLFSSL_MSG("\tOut of Memory");
  12578. ret = MEMORY_E;
  12579. }
  12580. }
  12581. if (ret == 0) {
  12582. /* Copy into cert HW serial number. */
  12583. XMEMCPY(cert->hwSerialNum, dataASN[4].data.ref.data, serialLen);
  12584. cert->hwSerialNum[serialLen] = '\0';
  12585. cert->hwSerialNumSz = serialLen;
  12586. }
  12587. FREE_ASNGETDATA(dataASN, cert->heap);
  12588. return ret;
  12589. }
  12590. #endif /* WOLFSSL_SEP */
  12591. /* Decode a GeneralName.
  12592. *
  12593. * @param [in] input Buffer containing encoded OtherName.
  12594. * @param [in, out] inOutIdx On in, the index of the start of the OtherName.
  12595. * On out, index after OtherName.
  12596. * @param [in] len Length of data in buffer.
  12597. * @param [in] cert Decoded certificate object.
  12598. * @return 0 on success.
  12599. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12600. * is invalid.
  12601. * @return BUFFER_E when data in buffer is too small.
  12602. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12603. * @return MEMORY_E when dynamic memory allocation fails.
  12604. */
  12605. static int DecodeGeneralName(const byte* input, word32* inOutIdx, byte tag,
  12606. int len, DecodedCert* cert)
  12607. {
  12608. int ret = 0;
  12609. word32 idx = *inOutIdx;
  12610. /* GeneralName choice: dnsName */
  12611. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  12612. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_DNS_TYPE,
  12613. &cert->altNames);
  12614. if (ret == 0) {
  12615. idx += len;
  12616. }
  12617. }
  12618. #ifndef IGNORE_NAME_CONSTRAINTS
  12619. /* GeneralName choice: directoryName */
  12620. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  12621. int strLen;
  12622. word32 idxDir = idx;
  12623. /* Expecting a SEQUENCE using up all data. */
  12624. if (GetASN_Sequence(input, &idxDir, &strLen, idx + len, 1) < 0) {
  12625. WOLFSSL_MSG("\tfail: seq length");
  12626. return ASN_PARSE_E;
  12627. }
  12628. ret = SetDNSEntry(cert, (const char*)(input + idxDir), strLen,
  12629. ASN_DIR_TYPE, &cert->altDirNames);
  12630. if (ret == 0) {
  12631. idx += len;
  12632. }
  12633. }
  12634. /* GeneralName choice: rfc822Name */
  12635. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  12636. ret = SetDNSEntry(cert, (const char*)(input + idx), len,
  12637. ASN_RFC822_TYPE, &cert->altEmailNames);
  12638. if (ret == 0) {
  12639. idx += len;
  12640. }
  12641. }
  12642. /* GeneralName choice: uniformResourceIdentifier */
  12643. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  12644. WOLFSSL_MSG("\tPutting URI into list but not using");
  12645. #ifndef WOLFSSL_NO_ASN_STRICT
  12646. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  12647. "The name MUST NOT be a relative URI" */
  12648. {
  12649. int i;
  12650. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  12651. for (i = 0; i < len; i++) {
  12652. if (input[idx + i] == ':') {
  12653. break;
  12654. }
  12655. if (input[idx + i] == '/') {
  12656. i = len; /* error, found relative path since '/' was
  12657. * encountered before ':'. Returning error
  12658. * value in next if statement. */
  12659. }
  12660. }
  12661. /* test if no ':' char was found and test that the next two
  12662. * chars are "//" to match the pattern "://" */
  12663. if (i >= len - 2 || (input[idx + i + 1] != '/' ||
  12664. input[idx + i + 2] != '/')) {
  12665. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  12666. return ASN_ALT_NAME_E;
  12667. }
  12668. }
  12669. #endif
  12670. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_URI_TYPE,
  12671. &cert->altNames);
  12672. if (ret == 0) {
  12673. idx += len;
  12674. }
  12675. }
  12676. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || \
  12677. defined(WOLFSSL_IP_ALT_NAME)
  12678. /* GeneralName choice: iPAddress */
  12679. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  12680. ret = SetDNSEntry(cert, (const char*)(input + idx), len, ASN_IP_TYPE,
  12681. &cert->altNames);
  12682. if (ret == 0) {
  12683. idx += len;
  12684. }
  12685. }
  12686. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  12687. #endif /* IGNORE_NAME_CONSTRAINTS */
  12688. #ifdef WOLFSSL_SEP
  12689. /* GeneralName choice: otherName */
  12690. else if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE)) {
  12691. /* TODO: test data for code path */
  12692. ret = DecodeOtherName(cert, input, &idx, idx + len);
  12693. }
  12694. #endif
  12695. /* GeneralName choice: dNSName, x400Address, ediPartyName,
  12696. * registeredID */
  12697. else {
  12698. WOLFSSL_MSG("\tUnsupported name type, skipping");
  12699. idx += len;
  12700. }
  12701. if (ret == 0) {
  12702. /* Return index of next encoded byte. */
  12703. *inOutIdx = idx;
  12704. }
  12705. return ret;
  12706. }
  12707. /* ASN.1 choices for GeneralName.
  12708. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  12709. */
  12710. static const byte generalNameChoice[] = {
  12711. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0,
  12712. ASN_CONTEXT_SPECIFIC | 1,
  12713. ASN_CONTEXT_SPECIFIC | 2,
  12714. ASN_CONTEXT_SPECIFIC | 3,
  12715. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 4,
  12716. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 5,
  12717. ASN_CONTEXT_SPECIFIC | 6,
  12718. ASN_CONTEXT_SPECIFIC | 7,
  12719. ASN_CONTEXT_SPECIFIC | 8,
  12720. 0
  12721. };
  12722. /* ASN.1 template for GeneralName.
  12723. * X.509: RFC 5280, 4.2.1.6 - GeneralName.
  12724. */
  12725. static const ASNItem altNameASN[] = {
  12726. { 0, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 0 }
  12727. };
  12728. /* Number of items in ASN.1 template for GeneralName. */
  12729. #define altNameASN_Length (sizeof(altNameASN) / sizeof(ASNItem))
  12730. #endif /* WOLFSSL_ASN_TEMPLATE */
  12731. /* Decode subject alternative names extension.
  12732. *
  12733. * RFC 5280 4.2.1.6. Subject Alternative Name
  12734. *
  12735. * @param [in] input Buffer holding encoded data.
  12736. * @param [in] sz Size of encoded data in bytes.
  12737. * @param [in, out] cert Decoded certificate object.
  12738. * @return 0 on success.
  12739. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  12740. * is invalid.
  12741. * @return BUFFER_E when data in buffer is too small.
  12742. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  12743. * @return MEMORY_E when dynamic memory allocation fails.
  12744. */
  12745. static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert)
  12746. {
  12747. #ifndef WOLFSSL_ASN_TEMPLATE
  12748. word32 idx = 0;
  12749. int length = 0;
  12750. WOLFSSL_ENTER("DecodeAltNames");
  12751. if (GetSequence(input, &idx, &length, sz) < 0) {
  12752. WOLFSSL_MSG("\tBad Sequence");
  12753. return ASN_PARSE_E;
  12754. }
  12755. if (length == 0) {
  12756. /* RFC 5280 4.2.1.6. Subject Alternative Name
  12757. If the subjectAltName extension is present, the sequence MUST
  12758. contain at least one entry. */
  12759. return ASN_PARSE_E;
  12760. }
  12761. #ifdef OPENSSL_ALL
  12762. cert->extSubjAltNameSrc = input;
  12763. cert->extSubjAltNameSz = sz;
  12764. #endif
  12765. cert->weOwnAltNames = 1;
  12766. while (length > 0) {
  12767. byte b = input[idx++];
  12768. length--;
  12769. /* Save DNS Type names in the altNames list. */
  12770. /* Save Other Type names in the cert's OidMap */
  12771. if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  12772. DNS_entry* dnsEntry;
  12773. int strLen;
  12774. word32 lenStartIdx = idx;
  12775. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12776. WOLFSSL_MSG("\tfail: str length");
  12777. return ASN_PARSE_E;
  12778. }
  12779. length -= (idx - lenStartIdx);
  12780. dnsEntry = AltNameNew(cert->heap);
  12781. if (dnsEntry == NULL) {
  12782. WOLFSSL_MSG("\tOut of Memory");
  12783. return MEMORY_E;
  12784. }
  12785. dnsEntry->type = ASN_DNS_TYPE;
  12786. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  12787. DYNAMIC_TYPE_ALTNAME);
  12788. if (dnsEntry->name == NULL) {
  12789. WOLFSSL_MSG("\tOut of Memory");
  12790. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12791. return MEMORY_E;
  12792. }
  12793. dnsEntry->len = strLen;
  12794. XMEMCPY(dnsEntry->name, &input[idx], strLen);
  12795. dnsEntry->name[strLen] = '\0';
  12796. AddAltName(cert, dnsEntry);
  12797. length -= strLen;
  12798. idx += strLen;
  12799. }
  12800. #ifndef IGNORE_NAME_CONSTRAINTS
  12801. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  12802. DNS_entry* dirEntry;
  12803. int strLen;
  12804. word32 lenStartIdx = idx;
  12805. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12806. WOLFSSL_MSG("\tfail: str length");
  12807. return ASN_PARSE_E;
  12808. }
  12809. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  12810. WOLFSSL_MSG("\tfail: seq length");
  12811. return ASN_PARSE_E;
  12812. }
  12813. length -= (idx - lenStartIdx);
  12814. dirEntry = AltNameNew(cert->heap);
  12815. if (dirEntry == NULL) {
  12816. WOLFSSL_MSG("\tOut of Memory");
  12817. return MEMORY_E;
  12818. }
  12819. dirEntry->type = ASN_DIR_TYPE;
  12820. dirEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  12821. DYNAMIC_TYPE_ALTNAME);
  12822. if (dirEntry->name == NULL) {
  12823. WOLFSSL_MSG("\tOut of Memory");
  12824. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12825. return MEMORY_E;
  12826. }
  12827. dirEntry->len = strLen;
  12828. XMEMCPY(dirEntry->name, &input[idx], strLen);
  12829. dirEntry->name[strLen] = '\0';
  12830. dirEntry->next = cert->altDirNames;
  12831. cert->altDirNames = dirEntry;
  12832. length -= strLen;
  12833. idx += strLen;
  12834. }
  12835. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  12836. DNS_entry* emailEntry;
  12837. int strLen;
  12838. word32 lenStartIdx = idx;
  12839. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12840. WOLFSSL_MSG("\tfail: str length");
  12841. return ASN_PARSE_E;
  12842. }
  12843. length -= (idx - lenStartIdx);
  12844. emailEntry = AltNameNew(cert->heap);
  12845. if (emailEntry == NULL) {
  12846. WOLFSSL_MSG("\tOut of Memory");
  12847. return MEMORY_E;
  12848. }
  12849. emailEntry->type = ASN_RFC822_TYPE;
  12850. emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  12851. DYNAMIC_TYPE_ALTNAME);
  12852. if (emailEntry->name == NULL) {
  12853. WOLFSSL_MSG("\tOut of Memory");
  12854. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12855. return MEMORY_E;
  12856. }
  12857. emailEntry->len = strLen;
  12858. XMEMCPY(emailEntry->name, &input[idx], strLen);
  12859. emailEntry->name[strLen] = '\0';
  12860. emailEntry->next = cert->altEmailNames;
  12861. cert->altEmailNames = emailEntry;
  12862. length -= strLen;
  12863. idx += strLen;
  12864. }
  12865. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  12866. DNS_entry* uriEntry;
  12867. int strLen;
  12868. word32 lenStartIdx = idx;
  12869. WOLFSSL_MSG("\tPutting URI into list but not using");
  12870. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12871. WOLFSSL_MSG("\tfail: str length");
  12872. return ASN_PARSE_E;
  12873. }
  12874. length -= (idx - lenStartIdx);
  12875. /* check that strLen at index is not past input buffer */
  12876. if (strLen + (int)idx > sz) {
  12877. return BUFFER_E;
  12878. }
  12879. #ifndef WOLFSSL_NO_ASN_STRICT
  12880. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  12881. "The name MUST NOT be a relative URI" */
  12882. {
  12883. int i;
  12884. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  12885. for (i = 0; i < strLen; i++) {
  12886. if (input[idx + i] == ':') {
  12887. break;
  12888. }
  12889. if (input[idx + i] == '/') {
  12890. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  12891. return ASN_ALT_NAME_E;
  12892. }
  12893. }
  12894. /* test if no ':' char was found and test that the next two
  12895. * chars are "//" to match the pattern "://" */
  12896. if (i >= strLen - 2 || (input[idx + i + 1] != '/' ||
  12897. input[idx + i + 2] != '/')) {
  12898. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  12899. return ASN_ALT_NAME_E;
  12900. }
  12901. }
  12902. #endif
  12903. uriEntry = AltNameNew(cert->heap);
  12904. if (uriEntry == NULL) {
  12905. WOLFSSL_MSG("\tOut of Memory");
  12906. return MEMORY_E;
  12907. }
  12908. uriEntry->type = ASN_URI_TYPE;
  12909. uriEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  12910. DYNAMIC_TYPE_ALTNAME);
  12911. if (uriEntry->name == NULL) {
  12912. WOLFSSL_MSG("\tOut of Memory");
  12913. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12914. return MEMORY_E;
  12915. }
  12916. uriEntry->len = strLen;
  12917. XMEMCPY(uriEntry->name, &input[idx], strLen);
  12918. uriEntry->name[strLen] = '\0';
  12919. AddAltName(cert, uriEntry);
  12920. length -= strLen;
  12921. idx += strLen;
  12922. }
  12923. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  12924. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  12925. DNS_entry* ipAddr;
  12926. int strLen;
  12927. word32 lenStartIdx = idx;
  12928. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  12929. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12930. WOLFSSL_MSG("\tfail: str length");
  12931. return ASN_PARSE_E;
  12932. }
  12933. length -= (idx - lenStartIdx);
  12934. /* check that strLen at index is not past input buffer */
  12935. if (strLen + (int)idx > sz) {
  12936. return BUFFER_E;
  12937. }
  12938. ipAddr = AltNameNew(cert->heap);
  12939. if (ipAddr == NULL) {
  12940. WOLFSSL_MSG("\tOut of Memory");
  12941. return MEMORY_E;
  12942. }
  12943. ipAddr->type = ASN_IP_TYPE;
  12944. ipAddr->name = (char*)XMALLOC(strLen + 1, cert->heap,
  12945. DYNAMIC_TYPE_ALTNAME);
  12946. if (ipAddr->name == NULL) {
  12947. WOLFSSL_MSG("\tOut of Memory");
  12948. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  12949. return MEMORY_E;
  12950. }
  12951. ipAddr->len = strLen;
  12952. XMEMCPY(ipAddr->name, &input[idx], strLen);
  12953. ipAddr->name[strLen] = '\0';
  12954. AddAltName(cert, ipAddr);
  12955. length -= strLen;
  12956. idx += strLen;
  12957. }
  12958. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  12959. #endif /* IGNORE_NAME_CONSTRAINTS */
  12960. #ifdef WOLFSSL_SEP
  12961. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE))
  12962. {
  12963. int strLen;
  12964. word32 lenStartIdx = idx;
  12965. word32 oid = 0;
  12966. int ret;
  12967. byte tag;
  12968. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12969. WOLFSSL_MSG("\tfail: other name length");
  12970. return ASN_PARSE_E;
  12971. }
  12972. /* Consume the rest of this sequence. */
  12973. length -= (strLen + idx - lenStartIdx);
  12974. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  12975. WOLFSSL_MSG("\tbad OID");
  12976. return ASN_PARSE_E;
  12977. }
  12978. if (oid != HW_NAME_OID) {
  12979. WOLFSSL_MSG("\tincorrect OID");
  12980. return ASN_PARSE_E;
  12981. }
  12982. /* Certificates issued with this OID in the subject alt name are for
  12983. * verifying signatures created on a module.
  12984. * RFC 4108 Section 5. */
  12985. if (cert->hwType != NULL) {
  12986. WOLFSSL_MSG("\tAlready seen Hardware Module Name");
  12987. return ASN_PARSE_E;
  12988. }
  12989. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  12990. return ASN_PARSE_E;
  12991. }
  12992. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  12993. WOLFSSL_MSG("\twrong type");
  12994. return ASN_PARSE_E;
  12995. }
  12996. if (GetLength(input, &idx, &strLen, sz) < 0) {
  12997. WOLFSSL_MSG("\tfail: str len");
  12998. return ASN_PARSE_E;
  12999. }
  13000. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  13001. WOLFSSL_MSG("\tBad Sequence");
  13002. return ASN_PARSE_E;
  13003. }
  13004. ret = GetASNObjectId(input, &idx, &strLen, sz);
  13005. if (ret != 0) {
  13006. WOLFSSL_MSG("\tbad OID");
  13007. return ret;
  13008. }
  13009. cert->hwType = (byte*)XMALLOC(strLen, cert->heap,
  13010. DYNAMIC_TYPE_X509_EXT);
  13011. if (cert->hwType == NULL) {
  13012. WOLFSSL_MSG("\tOut of Memory");
  13013. return MEMORY_E;
  13014. }
  13015. XMEMCPY(cert->hwType, &input[idx], strLen);
  13016. cert->hwTypeSz = strLen;
  13017. idx += strLen;
  13018. ret = GetOctetString(input, &idx, &strLen, sz);
  13019. if (ret < 0)
  13020. return ret;
  13021. cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap,
  13022. DYNAMIC_TYPE_X509_EXT);
  13023. if (cert->hwSerialNum == NULL) {
  13024. WOLFSSL_MSG("\tOut of Memory");
  13025. return MEMORY_E;
  13026. }
  13027. XMEMCPY(cert->hwSerialNum, &input[idx], strLen);
  13028. cert->hwSerialNum[strLen] = '\0';
  13029. cert->hwSerialNumSz = strLen;
  13030. idx += strLen;
  13031. }
  13032. #endif /* WOLFSSL_SEP */
  13033. else {
  13034. int strLen;
  13035. word32 lenStartIdx = idx;
  13036. WOLFSSL_MSG("\tUnsupported name type, skipping");
  13037. if (GetLength(input, &idx, &strLen, sz) < 0) {
  13038. WOLFSSL_MSG("\tfail: unsupported name length");
  13039. return ASN_PARSE_E;
  13040. }
  13041. length -= (strLen + idx - lenStartIdx);
  13042. idx += strLen;
  13043. }
  13044. }
  13045. return 0;
  13046. #else
  13047. word32 idx = 0;
  13048. int length = 0;
  13049. int ret = 0;
  13050. WOLFSSL_ENTER("DecodeAltNames");
  13051. /* Get SEQUENCE and expect all data to be accounted for. */
  13052. if (GetASN_Sequence(input, &idx, &length, sz, 1) != 0) {
  13053. WOLFSSL_MSG("\tBad Sequence");
  13054. ret = ASN_PARSE_E;
  13055. }
  13056. if ((ret == 0) && (length == 0)) {
  13057. /* RFC 5280 4.2.1.6. Subject Alternative Name
  13058. If the subjectAltName extension is present, the sequence MUST
  13059. contain at least one entry. */
  13060. ret = ASN_PARSE_E;
  13061. }
  13062. if (ret == 0) {
  13063. #ifdef OPENSSL_ALL
  13064. cert->extSubjAltNameSrc = input;
  13065. cert->extSubjAltNameSz = sz;
  13066. #endif
  13067. cert->weOwnAltNames = 1;
  13068. if (length + (int)idx != sz) {
  13069. ret = ASN_PARSE_E;
  13070. }
  13071. }
  13072. while ((ret == 0) && ((int)idx < sz)) {
  13073. ASNGetData dataASN[altNameASN_Length];
  13074. /* Clear dynamic data items. */
  13075. XMEMSET(dataASN, 0, sizeof(dataASN));
  13076. /* Parse GeneralName with the choices supported. */
  13077. GetASN_Choice(&dataASN[0], generalNameChoice);
  13078. /* Decode a GeneralName choice. */
  13079. ret = GetASN_Items(altNameASN, dataASN, altNameASN_Length, 0, input,
  13080. &idx, sz);
  13081. if (ret == 0) {
  13082. ret = DecodeGeneralName(input, &idx, dataASN[0].tag,
  13083. dataASN[0].length, cert);
  13084. }
  13085. }
  13086. return ret;
  13087. #endif
  13088. }
  13089. #ifdef WOLFSSL_ASN_TEMPLATE
  13090. /* ASN.1 template for BasicContraints.
  13091. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  13092. */
  13093. static const ASNItem basicConsASN[] = {
  13094. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13095. /* 1 */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  13096. /* 2 */ { 1, ASN_INTEGER, 0, 0, 1 }
  13097. };
  13098. /* Number of items in ASN.1 template for BasicContraints. */
  13099. #define basicConsASN_Length (sizeof(basicConsASN) / sizeof(ASNItem))
  13100. #endif
  13101. /* Decode basic constraints extension in a certificate.
  13102. *
  13103. * X.509: RFC 5280, 4.2.1.9 - BasicConstraints.
  13104. *
  13105. * @param [in] input Buffer holding data.
  13106. * @param [in] sz Size of data in buffer.
  13107. * @param [in, out] cert Certificate object.
  13108. * @return 0 on success.
  13109. * @return MEMORY_E on dynamic memory allocation failure.
  13110. * @return ASN_PARSE_E when CA boolean is present and false (default is false).
  13111. * @return ASN_PARSE_E when CA boolean is not present unless
  13112. * WOLFSSL_X509_BASICCONS_INT is defined. Only a CA extension.
  13113. * @return ASN_PARSE_E when path length more than 7 bits.
  13114. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13115. * is invalid.
  13116. * @return BUFFER_E when data in buffer is too small.
  13117. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  13118. * non-zero length.
  13119. */
  13120. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  13121. {
  13122. #ifndef WOLFSSL_ASN_TEMPLATE
  13123. word32 idx = 0;
  13124. int length = 0;
  13125. int ret;
  13126. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  13127. if (GetSequence(input, &idx, &length, sz) < 0) {
  13128. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  13129. return ASN_PARSE_E;
  13130. }
  13131. if (length == 0)
  13132. return 0;
  13133. /* If the basic ca constraint is false, this extension may be named, but
  13134. * left empty. So, if the length is 0, just return. */
  13135. ret = GetBoolean(input, &idx, sz);
  13136. /* Removed logic for WOLFSSL_X509_BASICCONS_INT which was mistreating the
  13137. * pathlen value as if it were the CA Boolean value 7/2/2021 - KH.
  13138. * When CA Boolean not asserted use the default value "False" */
  13139. if (ret < 0) {
  13140. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN, set default FALSE");
  13141. ret = 0;
  13142. }
  13143. cert->isCA = (byte)ret;
  13144. /* If there isn't any more data, return. */
  13145. if (idx >= (word32)sz) {
  13146. return 0;
  13147. }
  13148. ret = GetInteger7Bit(input, &idx, sz);
  13149. if (ret < 0)
  13150. return ret;
  13151. cert->pathLength = (byte)ret;
  13152. cert->pathLengthSet = 1;
  13153. return 0;
  13154. #else
  13155. DECL_ASNGETDATA(dataASN, basicConsASN_Length);
  13156. int ret = 0;
  13157. word32 idx = 0;
  13158. byte isCA = 0;
  13159. WOLFSSL_ENTER("DecodeBasicCaConstraints");
  13160. CALLOC_ASNGETDATA(dataASN, basicConsASN_Length, ret, cert->heap);
  13161. if (ret == 0) {
  13162. /* Get the CA boolean and path length when present. */
  13163. GetASN_Boolean(&dataASN[1], &isCA);
  13164. GetASN_Int8Bit(&dataASN[2], &cert->pathLength);
  13165. ret = GetASN_Items(basicConsASN, dataASN, basicConsASN_Length, 1, input,
  13166. &idx, sz);
  13167. }
  13168. /* Empty SEQUENCE is OK - nothing to store. */
  13169. if ((ret == 0) && (dataASN[0].length != 0)) {
  13170. /* Bad encoding when CA Boolean is false
  13171. * (default when not present). */
  13172. if ((dataASN[1].length != 0) && (!isCA)) {
  13173. ret = ASN_PARSE_E;
  13174. }
  13175. /* Path length must be a 7-bit value. */
  13176. if ((ret == 0) && (cert->pathLength >= (1 << 7))) {
  13177. ret = ASN_PARSE_E;
  13178. }
  13179. /* Store CA boolean and whether a path length was seen. */
  13180. if (ret == 0) {
  13181. /* isCA in certificate is a 1 bit of a byte. */
  13182. cert->isCA = isCA;
  13183. cert->pathLengthSet = (dataASN[2].length > 0);
  13184. }
  13185. }
  13186. FREE_ASNGETDATA(dataASN, cert->heap);
  13187. return ret;
  13188. #endif
  13189. }
  13190. static int DecodePolicyConstraints(const byte* input, int sz, DecodedCert* cert)
  13191. {
  13192. word32 idx = 0;
  13193. int length = 0;
  13194. int skipLength = 0;
  13195. int ret;
  13196. byte tag;
  13197. WOLFSSL_ENTER("DecodePolicyConstraints");
  13198. if (GetSequence(input, &idx, &length, sz) < 0) {
  13199. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  13200. return ASN_PARSE_E;
  13201. }
  13202. if (length == 0)
  13203. return ASN_PARSE_E;
  13204. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  13205. WOLFSSL_MSG("\tfail: bad TAG");
  13206. return ASN_PARSE_E;
  13207. }
  13208. if (tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  13209. /* requireExplicitPolicy */
  13210. cert->extPolicyConstRxpSet = 1;
  13211. }
  13212. else if (tag == (ASN_CONTEXT_SPECIFIC | 1)) {
  13213. /* inhibitPolicyMapping */
  13214. cert->extPolicyConstIpmSet = 1;
  13215. }
  13216. else {
  13217. WOLFSSL_MSG("\tfail: invalid TAG");
  13218. return ASN_PARSE_E;
  13219. }
  13220. ret = GetLength(input, &idx, &skipLength, sz);
  13221. if (ret < 0) {
  13222. WOLFSSL_MSG("\tfail: invalid length");
  13223. return ret;
  13224. }
  13225. if (skipLength > 1) {
  13226. WOLFSSL_MSG("\tfail: skip value too big");
  13227. return BUFFER_E;
  13228. }
  13229. cert->policyConstSkip = input[idx];
  13230. return 0;
  13231. }
  13232. /* Context-Specific value for: DistributionPoint.distributionPoint
  13233. * From RFC5280 SS4.2.1.13, Distribution Point */
  13234. #define DISTRIBUTION_POINT (ASN_CONTEXT_SPECIFIC | 0)
  13235. /* Context-Specific value for: DistributionPoint.DistributionPointName.fullName
  13236. * From RFC3280 SS4.2.1.13, Distribution Point Name */
  13237. #define CRLDP_FULL_NAME (ASN_CONTEXT_SPECIFIC | 0)
  13238. /* Context-Specific value for choice: GeneralName.uniformResourceIdentifier
  13239. * From RFC3280 SS4.2.1.7, GeneralName */
  13240. #define GENERALNAME_URI (ASN_CONTEXT_SPECIFIC | 6)
  13241. #ifdef WOLFSSL_ASN_TEMPLATE
  13242. /* ASN.1 template for CRL distribution points.
  13243. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  13244. */
  13245. static const ASNItem crlDistASN[] = {
  13246. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13247. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  13248. /* Distribution point name */
  13249. /* 2 */ { 2, DISTRIBUTION_POINT, 1, 1, 1 },
  13250. /* fullName */
  13251. /* 3 */ { 3, CRLDP_FULL_NAME, 1, 1, 2 },
  13252. /* 4 */ { 4, GENERALNAME_URI, 0, 0, 0 },
  13253. /* nameRelativeToCRLIssuer */
  13254. /* 5 */ { 3, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  13255. /* reasons: IMPLICIT BIT STRING */
  13256. /* 6 */ { 2, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  13257. /* cRLIssuer */
  13258. /* 7 */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 1 },
  13259. };
  13260. /* Number of items in ASN.1 template for CRL distribution points. */
  13261. #define crlDistASN_Length (sizeof(crlDistASN) / sizeof(ASNItem))
  13262. #endif
  13263. /* Decode CRL distribution point extension in a certificate.
  13264. *
  13265. * X.509: RFC 5280, 4.2.1.13 - CRL Distribution Points.
  13266. *
  13267. * @param [in] input Buffer holding data.
  13268. * @param [in] sz Size of data in buffer.
  13269. * @param [in, out] cert Certificate object.
  13270. * @return 0 on success.
  13271. * @return MEMORY_E on dynamic memory allocation failure.
  13272. * @return ASN_PARSE_E when invalid bits of reason are set.
  13273. * @return ASN_PARSE_E when BITSTRING value is more than 2 bytes.
  13274. * @return ASN_PARSE_E when unused bits of BITSTRING is invalid.
  13275. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13276. * is invalid.
  13277. * @return BUFFER_E when data in buffer is too small.
  13278. */
  13279. static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert)
  13280. {
  13281. #ifndef WOLFSSL_ASN_TEMPLATE
  13282. word32 idx = 0, localIdx;
  13283. int length = 0;
  13284. byte tag = 0;
  13285. WOLFSSL_ENTER("DecodeCrlDist");
  13286. cert->extCrlInfoRaw = input;
  13287. cert->extCrlInfoRawSz = sz;
  13288. /* Unwrap the list of Distribution Points*/
  13289. if (GetSequence(input, &idx, &length, sz) < 0)
  13290. return ASN_PARSE_E;
  13291. /* Unwrap a single Distribution Point */
  13292. if (GetSequence(input, &idx, &length, sz) < 0)
  13293. return ASN_PARSE_E;
  13294. /* The Distribution Point has three explicit optional members
  13295. * First check for a DistributionPointName
  13296. */
  13297. localIdx = idx;
  13298. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  13299. tag == (ASN_CONSTRUCTED | DISTRIBUTION_POINT))
  13300. {
  13301. idx++;
  13302. if (GetLength(input, &idx, &length, sz) < 0)
  13303. return ASN_PARSE_E;
  13304. localIdx = idx;
  13305. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  13306. tag == (ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  13307. {
  13308. idx++;
  13309. if (GetLength(input, &idx, &length, sz) < 0)
  13310. return ASN_PARSE_E;
  13311. localIdx = idx;
  13312. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  13313. tag == GENERALNAME_URI)
  13314. {
  13315. idx++;
  13316. if (GetLength(input, &idx, &length, sz) < 0)
  13317. return ASN_PARSE_E;
  13318. cert->extCrlInfoSz = length;
  13319. cert->extCrlInfo = input + idx;
  13320. idx += length;
  13321. }
  13322. else
  13323. /* This isn't a URI, skip it. */
  13324. idx += length;
  13325. }
  13326. else {
  13327. /* This isn't a FULLNAME, skip it. */
  13328. idx += length;
  13329. }
  13330. }
  13331. /* Check for reasonFlags */
  13332. localIdx = idx;
  13333. if (idx < (word32)sz &&
  13334. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  13335. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  13336. {
  13337. idx++;
  13338. if (GetLength(input, &idx, &length, sz) < 0)
  13339. return ASN_PARSE_E;
  13340. idx += length;
  13341. }
  13342. /* Check for cRLIssuer */
  13343. localIdx = idx;
  13344. if (idx < (word32)sz &&
  13345. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  13346. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  13347. {
  13348. idx++;
  13349. if (GetLength(input, &idx, &length, sz) < 0)
  13350. return ASN_PARSE_E;
  13351. idx += length;
  13352. }
  13353. if (idx < (word32)sz)
  13354. {
  13355. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  13356. "but we only use the first one.");
  13357. }
  13358. return 0;
  13359. #else
  13360. DECL_ASNGETDATA(dataASN, crlDistASN_Length);
  13361. word32 idx = 0;
  13362. int ret = 0;
  13363. #ifdef CRLDP_VALIDATE_DATA
  13364. word16 reason;
  13365. #endif
  13366. WOLFSSL_ENTER("DecodeCrlDist");
  13367. CALLOC_ASNGETDATA(dataASN, crlDistASN_Length, ret, cert->heap);
  13368. cert->extCrlInfoRaw = input;
  13369. cert->extCrlInfoRawSz = sz;
  13370. if (ret == 0) {
  13371. /* Get the GeneralName choice */
  13372. GetASN_Choice(&dataASN[4], generalNameChoice);
  13373. /* Parse CRL distribution point. */
  13374. ret = GetASN_Items(crlDistASN, dataASN, crlDistASN_Length, 0, input,
  13375. &idx, sz);
  13376. }
  13377. if (ret == 0) {
  13378. /* If the choice was a URI, store it in certificate. */
  13379. if (dataASN[4].tag == GENERALNAME_URI) {
  13380. word32 sz32;
  13381. GetASN_GetConstRef(&dataASN[4], &cert->extCrlInfo, &sz32);
  13382. cert->extCrlInfoSz = sz32;
  13383. }
  13384. #ifdef CRLDP_VALIDATE_DATA
  13385. if (dataASN[6].data.ref.data != NULL) {
  13386. /* TODO: test case */
  13387. /* Validate ReasonFlags. */
  13388. ret = GetASN_BitString_Int16Bit(&dataASN[6], &reason);
  13389. /* First bit (LSB) unused and eight other bits defined. */
  13390. if ((ret == 0) && ((reason >> 9) || (reason & 0x01))) {
  13391. ret = ASN_PARSE_E;
  13392. }
  13393. }
  13394. #endif
  13395. }
  13396. /* Only parsing the first one. */
  13397. if (ret == 0 && idx < (word32)sz) {
  13398. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  13399. "but we only use the first one.");
  13400. }
  13401. /* TODO: validate other points. */
  13402. FREE_ASNGETDATA(dataASN, cert->heap);
  13403. return ret;
  13404. #endif /* WOLFSSL_ASN_TEMPLATE */
  13405. }
  13406. #ifdef WOLFSSL_ASN_TEMPLATE
  13407. /* ASN.1 template for the access description.
  13408. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  13409. */
  13410. static const ASNItem accessDescASN[] = {
  13411. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13412. /* accessMethod */
  13413. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  13414. /* accessLocation: GeneralName */
  13415. /* 2 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  13416. };
  13417. /* Number of items in ASN.1 template for the access description. */
  13418. #define accessDescASN_Length (sizeof(accessDescASN) / sizeof(ASNItem))
  13419. #endif
  13420. /* Decode authority information access extension in a certificate.
  13421. *
  13422. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  13423. *
  13424. * @param [in] input Buffer holding data.
  13425. * @param [in] sz Size of data in buffer.
  13426. * @param [in, out] cert Certificate object.
  13427. * @return 0 on success.
  13428. * @return MEMORY_E on dynamic memory allocation failure.
  13429. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13430. * is invalid.
  13431. * @return BUFFER_E when data in buffer is too small.
  13432. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  13433. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  13434. */
  13435. static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert)
  13436. {
  13437. #ifndef WOLFSSL_ASN_TEMPLATE
  13438. word32 idx = 0;
  13439. int length = 0;
  13440. int count = 0;
  13441. byte b = 0;
  13442. word32 oid;
  13443. WOLFSSL_ENTER("DecodeAuthInfo");
  13444. /* Unwrap the list of AIAs */
  13445. if (GetSequence(input, &idx, &length, sz) < 0)
  13446. return ASN_PARSE_E;
  13447. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  13448. /* Unwrap a single AIA */
  13449. if (GetSequence(input, &idx, &length, sz) < 0)
  13450. return ASN_PARSE_E;
  13451. oid = 0;
  13452. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0) {
  13453. return ASN_PARSE_E;
  13454. }
  13455. /* Only supporting URIs right now. */
  13456. if (GetASNTag(input, &idx, &b, sz) < 0)
  13457. return ASN_PARSE_E;
  13458. if (GetLength(input, &idx, &length, sz) < 0)
  13459. return ASN_PARSE_E;
  13460. /* Set ocsp entry */
  13461. if (b == GENERALNAME_URI && oid == AIA_OCSP_OID)
  13462. {
  13463. cert->extAuthInfoSz = length;
  13464. cert->extAuthInfo = input + idx;
  13465. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  13466. count++;
  13467. #else
  13468. break;
  13469. #endif
  13470. }
  13471. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  13472. /* Set CaIssuers entry */
  13473. else if ((b == GENERALNAME_URI) && oid == AIA_CA_ISSUER_OID)
  13474. {
  13475. cert->extAuthInfoCaIssuerSz = length;
  13476. cert->extAuthInfoCaIssuer = input + idx;
  13477. count++;
  13478. }
  13479. #endif
  13480. idx += length;
  13481. }
  13482. return 0;
  13483. #else
  13484. word32 idx = 0;
  13485. int length = 0;
  13486. int count = 0;
  13487. int ret = 0;
  13488. WOLFSSL_ENTER("DecodeAuthInfo");
  13489. /* Unwrap the list of AIAs */
  13490. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  13491. ret = ASN_PARSE_E;
  13492. }
  13493. while ((ret == 0) && (idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  13494. ASNGetData dataASN[accessDescASN_Length];
  13495. word32 sz32;
  13496. /* Clear dynamic data and retrieve OID and name. */
  13497. XMEMSET(dataASN, 0, sizeof(dataASN));
  13498. GetASN_OID(&dataASN[1], oidCertAuthInfoType);
  13499. GetASN_Choice(&dataASN[2], generalNameChoice);
  13500. /* Parse AccessDescription. */
  13501. ret = GetASN_Items(accessDescASN, dataASN, accessDescASN_Length, 0,
  13502. input, &idx, sz);
  13503. if (ret == 0) {
  13504. /* Check we have OCSP and URI. */
  13505. if ((dataASN[1].data.oid.sum == AIA_OCSP_OID) &&
  13506. (dataASN[2].tag == GENERALNAME_URI)) {
  13507. /* Store URI for OCSP lookup. */
  13508. GetASN_GetConstRef(&dataASN[2], &cert->extAuthInfo, &sz32);
  13509. cert->extAuthInfoSz = sz32;
  13510. count++;
  13511. #if !defined(OPENSSL_ALL) || !defined(WOLFSSL_QT)
  13512. break;
  13513. #endif
  13514. }
  13515. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  13516. /* Check we have CA Issuer and URI. */
  13517. else if ((dataASN[1].data.oid.sum == AIA_CA_ISSUER_OID) &&
  13518. (dataASN[2].tag == GENERALNAME_URI)) {
  13519. /* Set CaIssuers entry */
  13520. GetASN_GetConstRef(&dataASN[2], &cert->extAuthInfoCaIssuer,
  13521. &sz32);
  13522. cert->extAuthInfoCaIssuerSz = sz32;
  13523. count++;
  13524. }
  13525. #endif
  13526. /* Otherwise skip. */
  13527. }
  13528. }
  13529. return ret;
  13530. #endif
  13531. }
  13532. #ifdef WOLFSSL_ASN_TEMPLATE
  13533. /* ASN.1 template for AuthorityKeyIdentifier.
  13534. * X.509: RFC 5280, 4.2.1.1 - Authority Key Identifier.
  13535. */
  13536. static const ASNItem authKeyIdASN[] = {
  13537. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13538. /* keyIdentifier */
  13539. /* 1 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 1 },
  13540. /* authorityCertIssuer */
  13541. /* 2 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  13542. /* authorityCertSerialNumber */
  13543. /* 3 */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  13544. };
  13545. /* Number of items in ASN.1 template for AuthorityKeyIdentifier. */
  13546. #define authKeyIdASN_Length (sizeof(authKeyIdASN) / sizeof(ASNItem))
  13547. #endif
  13548. /* Decode authority information access extension in a certificate.
  13549. *
  13550. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  13551. *
  13552. * @param [in] input Buffer holding data.
  13553. * @param [in] sz Size of data in buffer.
  13554. * @param [in, out] cert Certificate object.
  13555. * @return 0 on success.
  13556. * @return MEMORY_E on dynamic memory allocation failure.
  13557. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13558. * is invalid.
  13559. * @return BUFFER_E when data in buffer is too small.
  13560. */
  13561. static int DecodeAuthKeyId(const byte* input, int sz, DecodedCert* cert)
  13562. {
  13563. #ifndef WOLFSSL_ASN_TEMPLATE
  13564. word32 idx = 0;
  13565. int length = 0;
  13566. byte tag;
  13567. WOLFSSL_ENTER("DecodeAuthKeyId");
  13568. if (GetSequence(input, &idx, &length, sz) < 0) {
  13569. WOLFSSL_MSG("\tfail: should be a SEQUENCE\n");
  13570. return ASN_PARSE_E;
  13571. }
  13572. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  13573. return ASN_PARSE_E;
  13574. }
  13575. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  13576. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
  13577. cert->extAuthKeyIdSet = 0;
  13578. return 0;
  13579. }
  13580. if (GetLength(input, &idx, &length, sz) <= 0) {
  13581. WOLFSSL_MSG("\tfail: extension data length");
  13582. return ASN_PARSE_E;
  13583. }
  13584. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13585. #ifdef WOLFSSL_AKID_NAME
  13586. cert->extRawAuthKeyIdSrc = input;
  13587. cert->extRawAuthKeyIdSz = sz;
  13588. #endif
  13589. cert->extAuthKeyIdSrc = &input[idx];
  13590. cert->extAuthKeyIdSz = length;
  13591. #endif /* OPENSSL_EXTRA */
  13592. return GetHashId(input + idx, length, cert->extAuthKeyId);
  13593. #else
  13594. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  13595. int ret = 0;
  13596. word32 idx = 0;
  13597. WOLFSSL_ENTER("DecodeAuthKeyId");
  13598. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, cert->heap);
  13599. if (ret == 0) {
  13600. /* Parse an authority key identifier. */
  13601. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  13602. &idx, sz);
  13603. }
  13604. if (ret == 0) {
  13605. /* Key id is optional. */
  13606. if (dataASN[1].data.ref.data == NULL) {
  13607. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  13608. }
  13609. else {
  13610. #ifdef OPENSSL_EXTRA
  13611. /* Store the authority key id. */
  13612. #ifdef WOLFSSL_AKID_NAME
  13613. cert->extRawAuthKeyIdSrc = input;
  13614. cert->extRawAuthKeyIdSz = sz;
  13615. #endif
  13616. GetASN_GetConstRef(&dataASN[1], &cert->extAuthKeyIdSrc,
  13617. &cert->extAuthKeyIdSz);
  13618. #endif /* OPENSSL_EXTRA */
  13619. /* Get the hash or hash of the hash if wrong size. */
  13620. ret = GetHashId(dataASN[1].data.ref.data,
  13621. dataASN[1].data.ref.length, cert->extAuthKeyId);
  13622. }
  13623. }
  13624. FREE_ASNGETDATA(dataASN, cert->heap);
  13625. return ret;
  13626. #endif /* WOLFSSL_ASN_TEMPLATE */
  13627. }
  13628. /* Decode subject key id extension in a certificate.
  13629. *
  13630. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  13631. *
  13632. * @param [in] input Buffer holding data.
  13633. * @param [in] sz Size of data in buffer.
  13634. * @param [in, out] cert Certificate object.
  13635. * @return 0 on success.
  13636. * @return ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  13637. * invalid.
  13638. * @return MEMORY_E on dynamic memory allocation failure.
  13639. */
  13640. static int DecodeSubjKeyId(const byte* input, int sz, DecodedCert* cert)
  13641. {
  13642. word32 idx = 0;
  13643. int length = 0;
  13644. int ret = 0;
  13645. WOLFSSL_ENTER("DecodeSubjKeyId");
  13646. if (sz <= 0) {
  13647. ret = ASN_PARSE_E;
  13648. }
  13649. if (ret == 0) {
  13650. ret = GetOctetString(input, &idx, &length, sz);
  13651. }
  13652. if (ret > 0) {
  13653. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13654. cert->extSubjKeyIdSrc = &input[idx];
  13655. cert->extSubjKeyIdSz = length;
  13656. #endif /* OPENSSL_EXTRA */
  13657. /* Get the hash or hash of the hash if wrong size. */
  13658. ret = GetHashId(input + idx, length, cert->extSubjKeyId);
  13659. }
  13660. return ret;
  13661. }
  13662. #ifdef WOLFSSL_ASN_TEMPLATE
  13663. /* ASN.1 template for KeyUsage.
  13664. * X.509: RFC 5280, 4.2.1.3 - Key Usage.
  13665. */
  13666. static const ASNItem keyUsageASN[] = {
  13667. /* 0 */ { 0, ASN_BIT_STRING, 0, 0, 0 },
  13668. };
  13669. /* Number of items in ASN.1 template for KeyUsage. */
  13670. #define keyUsageASN_Length (sizeof(keyUsageASN) / sizeof(ASNItem))
  13671. #endif
  13672. /* Decode key usage extension in a certificate.
  13673. *
  13674. * X.509: RFC 5280, 4.2.2.1 - Authority Information Access.
  13675. *
  13676. * @param [in] input Buffer holding data.
  13677. * @param [in] sz Size of data in buffer.
  13678. * @param [in, out] cert Certificate object.
  13679. * @return 0 on success.
  13680. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13681. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13682. * is invalid.
  13683. * @return MEMORY_E on dynamic memory allocation failure.
  13684. */
  13685. static int DecodeKeyUsage(const byte* input, int sz, DecodedCert* cert)
  13686. {
  13687. #ifndef WOLFSSL_ASN_TEMPLATE
  13688. word32 idx = 0;
  13689. int length;
  13690. int ret;
  13691. WOLFSSL_ENTER("DecodeKeyUsage");
  13692. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  13693. if (ret != 0)
  13694. return ret;
  13695. if (length == 0 || length > 2)
  13696. return ASN_PARSE_E;
  13697. cert->extKeyUsage = (word16)(input[idx]);
  13698. if (length == 2)
  13699. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  13700. return 0;
  13701. #else
  13702. ASNGetData dataASN[keyUsageASN_Length];
  13703. word32 idx = 0;
  13704. WOLFSSL_ENTER("DecodeKeyUsage");
  13705. /* Clear dynamic data and set where to store extended key usage. */
  13706. XMEMSET(dataASN, 0, sizeof(dataASN));
  13707. GetASN_Int16Bit(&dataASN[0], &cert->extKeyUsage);
  13708. /* Parse key usage. */
  13709. return GetASN_Items(keyUsageASN, dataASN, keyUsageASN_Length, 0, input,
  13710. &idx, sz);
  13711. #endif /* WOLFSSL_ASN_TEMPLATE */
  13712. }
  13713. #ifdef WOLFSSL_ASN_TEMPLATE
  13714. /* ASN.1 template for KeyPurposeId.
  13715. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  13716. */
  13717. static const ASNItem keyPurposeIdASN[] = {
  13718. /* 0 */ { 0, ASN_OBJECT_ID, 0, 0, 0 },
  13719. };
  13720. /* Number of items in ASN.1 template for KeyPurposeId. */
  13721. #define keyPurposeIdASN_Length (sizeof(keyPurposeIdASN) / sizeof(ASNItem))
  13722. #endif
  13723. /* Decode extended key usage extension in a certificate.
  13724. *
  13725. * X.509: RFC 5280, 4.2.1.12 - Extended Key Usage.
  13726. *
  13727. * @param [in] input Buffer holding data.
  13728. * @param [in] sz Size of data in buffer.
  13729. * @param [in, out] cert Certificate object.
  13730. * @return 0 on success.
  13731. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  13732. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  13733. * is invalid.
  13734. * @return MEMORY_E on dynamic memory allocation failure.
  13735. */
  13736. static int DecodeExtKeyUsage(const byte* input, int sz, DecodedCert* cert)
  13737. {
  13738. #ifndef WOLFSSL_ASN_TEMPLATE
  13739. word32 idx = 0, oid;
  13740. int length, ret;
  13741. WOLFSSL_MSG("DecodeExtKeyUsage");
  13742. if (GetSequence(input, &idx, &length, sz) < 0) {
  13743. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  13744. return ASN_PARSE_E;
  13745. }
  13746. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13747. cert->extExtKeyUsageSrc = input + idx;
  13748. cert->extExtKeyUsageSz = length;
  13749. #endif
  13750. while (idx < (word32)sz) {
  13751. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  13752. if (ret == ASN_UNKNOWN_OID_E)
  13753. continue;
  13754. else if (ret < 0)
  13755. return ret;
  13756. switch (oid) {
  13757. case EKU_ANY_OID:
  13758. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  13759. break;
  13760. case EKU_SERVER_AUTH_OID:
  13761. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  13762. break;
  13763. case EKU_CLIENT_AUTH_OID:
  13764. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  13765. break;
  13766. case EKU_CODESIGNING_OID:
  13767. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  13768. break;
  13769. case EKU_EMAILPROTECT_OID:
  13770. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  13771. break;
  13772. case EKU_TIMESTAMP_OID:
  13773. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  13774. break;
  13775. case EKU_OCSP_SIGN_OID:
  13776. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  13777. break;
  13778. default:
  13779. break;
  13780. }
  13781. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13782. cert->extExtKeyUsageCount++;
  13783. #endif
  13784. }
  13785. return 0;
  13786. #else
  13787. word32 idx = 0;
  13788. int length;
  13789. int ret = 0;
  13790. WOLFSSL_MSG("DecodeExtKeyUsage");
  13791. /* Strip SEQUENCE OF and expect to account for all the data. */
  13792. if (GetASN_Sequence(input, &idx, &length, sz, 1) < 0) {
  13793. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  13794. ret = ASN_PARSE_E;
  13795. }
  13796. if (ret == 0) {
  13797. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13798. /* Keep reference for WOLFSSL_X509. */
  13799. cert->extExtKeyUsageSrc = input + idx;
  13800. cert->extExtKeyUsageSz = length;
  13801. #endif
  13802. }
  13803. /* Check all OIDs. */
  13804. while ((ret == 0) && (idx < (word32)sz)) {
  13805. ASNGetData dataASN[keyPurposeIdASN_Length];
  13806. /* Clear dynamic data items and set OID type expected. */
  13807. XMEMSET(dataASN, 0, sizeof(dataASN));
  13808. GetASN_OID(&dataASN[0], oidCertKeyUseType);
  13809. /* Decode KeyPurposeId. */
  13810. ret = GetASN_Items(keyPurposeIdASN, dataASN, keyPurposeIdASN_Length, 0,
  13811. input, &idx, sz);
  13812. /* Skip unknown OIDs. */
  13813. if (ret == ASN_UNKNOWN_OID_E) {
  13814. ret = 0;
  13815. }
  13816. else if (ret == 0) {
  13817. /* Store the bit for the OID. */
  13818. switch (dataASN[0].data.oid.sum) {
  13819. case EKU_ANY_OID:
  13820. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  13821. break;
  13822. case EKU_SERVER_AUTH_OID:
  13823. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  13824. break;
  13825. case EKU_CLIENT_AUTH_OID:
  13826. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  13827. break;
  13828. case EKU_CODESIGNING_OID:
  13829. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  13830. break;
  13831. case EKU_EMAILPROTECT_OID:
  13832. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  13833. break;
  13834. case EKU_TIMESTAMP_OID:
  13835. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  13836. break;
  13837. case EKU_OCSP_SIGN_OID:
  13838. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  13839. break;
  13840. }
  13841. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  13842. /* Keep count for WOLFSSL_X509. */
  13843. cert->extExtKeyUsageCount++;
  13844. #endif
  13845. }
  13846. }
  13847. return ret;
  13848. #endif /* WOLFSSL_ASN_TEMPLATE */
  13849. }
  13850. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  13851. static int DecodeNsCertType(const byte* input, int sz, DecodedCert* cert)
  13852. {
  13853. word32 idx = 0;
  13854. int len = 0;
  13855. WOLFSSL_ENTER("DecodeNsCertType");
  13856. if (CheckBitString(input, &idx, &len, (word32)sz, 0, NULL) < 0) {
  13857. return ASN_PARSE_E;
  13858. }
  13859. /* Don't need to worry about unused bits as CheckBitString makes sure
  13860. * they're zero. */
  13861. cert->nsCertType = input[idx];
  13862. return 0;
  13863. }
  13864. #endif
  13865. #ifndef IGNORE_NAME_CONSTRAINTS
  13866. #ifdef WOLFSSL_ASN_TEMPLATE
  13867. /* ASN.1 template for GeneralSubtree.
  13868. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  13869. */
  13870. static const ASNItem subTreeASN[] = {
  13871. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  13872. /* base GeneralName */
  13873. /* 1 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  13874. /* minimum BaseDistance DEFAULT 0*/
  13875. /* 2 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 1 },
  13876. /* maximum BaseDistance OPTIONAL */
  13877. /* 3 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  13878. };
  13879. /* Number of items in ASN.1 template for GeneralSubtree. */
  13880. #define subTreeASN_Length (sizeof(subTreeASN) / sizeof(ASNItem))
  13881. #endif
  13882. #ifdef WOLFSSL_ASN_TEMPLATE
  13883. /* Decode the Subtree's GeneralName.
  13884. *
  13885. * @param [in] input Buffer holding data.
  13886. * @param [in] sz Size of data in buffer.
  13887. * @param [in] tag BER tag on GeneralName.
  13888. * @param [in, out] head Linked list of subtree names.
  13889. * @param [in] heap Dynamic memory hint.
  13890. * @return 0 on success.
  13891. * @return MEMORY_E when dynamic memory allocation fails.
  13892. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  13893. */
  13894. static int DecodeSubtreeGeneralName(const byte* input, int sz, byte tag,
  13895. Base_entry** head, void* heap)
  13896. {
  13897. Base_entry* entry;
  13898. word32 nameIdx = 0;
  13899. word32 len = sz;
  13900. int strLen;
  13901. int ret = 0;
  13902. (void)heap;
  13903. /* if constructed has leading sequence */
  13904. if ((tag & ASN_CONSTRUCTED) == ASN_CONSTRUCTED) {
  13905. ret = GetASN_Sequence(input, &nameIdx, &strLen, sz, 0);
  13906. if (ret < 0) {
  13907. ret = ASN_PARSE_E;
  13908. }
  13909. else {
  13910. len = strLen;
  13911. ret = 0;
  13912. }
  13913. }
  13914. if (ret == 0) {
  13915. /* TODO: consider one malloc. */
  13916. /* Allocate Base Entry object. */
  13917. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  13918. DYNAMIC_TYPE_ALTNAME);
  13919. if (entry == NULL) {
  13920. ret = MEMORY_E;
  13921. }
  13922. }
  13923. if (ret == 0) {
  13924. /* Allocate name. */
  13925. entry->name = (char*)XMALLOC(len + 1, heap, DYNAMIC_TYPE_ALTNAME);
  13926. if (entry->name == NULL) {
  13927. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  13928. ret = MEMORY_E;
  13929. }
  13930. }
  13931. if (ret == 0) {
  13932. /* Store name, size and tag in object. */
  13933. XMEMCPY(entry->name, &input[nameIdx], len);
  13934. entry->name[len] = '\0';
  13935. entry->nameSz = len;
  13936. entry->type = tag & ASN_TYPE_MASK;
  13937. /* Put entry at front of linked list. */
  13938. entry->next = *head;
  13939. *head = entry;
  13940. }
  13941. return ret;
  13942. }
  13943. #endif
  13944. /* Decode a subtree of a name contraint in a certificate.
  13945. *
  13946. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  13947. *
  13948. * @param [in] input Buffer holding data.
  13949. * @param [in] sz Size of data in buffer.
  13950. * @param [in, out] head Linked list of subtree names.
  13951. * @param [in] heap Dynamic memory hint.
  13952. * @return 0 on success.
  13953. * @return MEMORY_E when dynamic memory allocation fails.
  13954. * @return ASN_PARSE_E when SEQUENCE is not found as expected.
  13955. */
  13956. static int DecodeSubtree(const byte* input, int sz, Base_entry** head,
  13957. void* heap)
  13958. {
  13959. #ifndef WOLFSSL_ASN_TEMPLATE
  13960. word32 idx = 0;
  13961. int ret = 0;
  13962. (void)heap;
  13963. while (idx < (word32)sz) {
  13964. int seqLength, strLength;
  13965. word32 nameIdx;
  13966. byte b, bType;
  13967. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  13968. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  13969. return ASN_PARSE_E;
  13970. }
  13971. nameIdx = idx;
  13972. b = input[nameIdx++];
  13973. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  13974. WOLFSSL_MSG("\tinvalid length");
  13975. return ASN_PARSE_E;
  13976. }
  13977. /* Get type, LSB 4-bits */
  13978. bType = (b & ASN_TYPE_MASK);
  13979. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  13980. bType == ASN_DIR_TYPE) {
  13981. Base_entry* entry;
  13982. /* if constructed has leading sequence */
  13983. if (b & ASN_CONSTRUCTED) {
  13984. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  13985. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  13986. return ASN_PARSE_E;
  13987. }
  13988. }
  13989. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  13990. DYNAMIC_TYPE_ALTNAME);
  13991. if (entry == NULL) {
  13992. WOLFSSL_MSG("allocate error");
  13993. return MEMORY_E;
  13994. }
  13995. entry->name = (char*)XMALLOC(strLength+1, heap, DYNAMIC_TYPE_ALTNAME);
  13996. if (entry->name == NULL) {
  13997. WOLFSSL_MSG("allocate error");
  13998. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  13999. return MEMORY_E;
  14000. }
  14001. XMEMCPY(entry->name, &input[nameIdx], strLength);
  14002. entry->name[strLength] = '\0';
  14003. entry->nameSz = strLength;
  14004. entry->type = bType;
  14005. entry->next = *head;
  14006. *head = entry;
  14007. }
  14008. idx += seqLength;
  14009. }
  14010. return ret;
  14011. #else
  14012. DECL_ASNGETDATA(dataASN, subTreeASN_Length);
  14013. word32 idx = 0;
  14014. int ret = 0;
  14015. (void)heap;
  14016. ALLOC_ASNGETDATA(dataASN, subTreeASN_Length, ret, heap);
  14017. /* Process all subtrees. */
  14018. while ((ret == 0) && (idx < (word32)sz)) {
  14019. byte minVal = 0;
  14020. byte maxVal = 0;
  14021. /* Clear dynamic data and set choice for GeneralName and location to
  14022. * store minimum and maximum.
  14023. */
  14024. XMEMSET(dataASN, 0, sizeof(*dataASN) * subTreeASN_Length);
  14025. GetASN_Choice(&dataASN[1], generalNameChoice);
  14026. GetASN_Int8Bit(&dataASN[2], &minVal);
  14027. GetASN_Int8Bit(&dataASN[3], &maxVal);
  14028. /* Parse GeneralSubtree. */
  14029. ret = GetASN_Items(subTreeASN, dataASN, subTreeASN_Length, 0, input,
  14030. &idx, sz);
  14031. if (ret == 0) {
  14032. byte t = dataASN[1].tag;
  14033. /* Check GeneralName tag is one of the types we can handle. */
  14034. if (t == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE) ||
  14035. t == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE) ||
  14036. t == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  14037. /* Parse the general name and store a new entry. */
  14038. ret = DecodeSubtreeGeneralName(input +
  14039. GetASNItem_DataIdx(dataASN[1], input),
  14040. dataASN[1].length, t, head, heap);
  14041. }
  14042. /* Skip entry. */
  14043. }
  14044. }
  14045. FREE_ASNGETDATA(dataASN, heap);
  14046. return ret;
  14047. #endif
  14048. }
  14049. #ifdef WOLFSSL_ASN_TEMPLATE
  14050. /* ASN.1 template for NameConstraints.
  14051. * X.509: RFC 5280, 4.2.1.10 - Name Contraints.
  14052. */
  14053. static const ASNItem nameConstraintsASN[] = {
  14054. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14055. /* permittedSubtrees */
  14056. /* 1 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  14057. /* excludededSubtrees */
  14058. /* 2 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  14059. };
  14060. /* Number of items in ASN.1 template for NameConstraints. */
  14061. #define nameConstraintsASN_Length (sizeof(nameConstraintsASN) / sizeof(ASNItem))
  14062. #endif
  14063. /* Decode name constraints extension in a certificate.
  14064. *
  14065. * X.509: RFC 5280, 4.2.1.10 - Name Constraints.
  14066. *
  14067. * @param [in] input Buffer holding data.
  14068. * @param [in] sz Size of data in buffer.
  14069. * @param [in, out] cert Certificate object.
  14070. * @return 0 on success.
  14071. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  14072. * is invalid.
  14073. * @return MEMORY_E on dynamic memory allocation failure.
  14074. */
  14075. static int DecodeNameConstraints(const byte* input, int sz, DecodedCert* cert)
  14076. {
  14077. #ifndef WOLFSSL_ASN_TEMPLATE
  14078. word32 idx = 0;
  14079. int length = 0;
  14080. WOLFSSL_ENTER("DecodeNameConstraints");
  14081. if (GetSequence(input, &idx, &length, sz) < 0) {
  14082. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  14083. return ASN_PARSE_E;
  14084. }
  14085. while (idx < (word32)sz) {
  14086. byte b = input[idx++];
  14087. Base_entry** subtree = NULL;
  14088. if (GetLength(input, &idx, &length, sz) <= 0) {
  14089. WOLFSSL_MSG("\tinvalid length");
  14090. return ASN_PARSE_E;
  14091. }
  14092. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  14093. subtree = &cert->permittedNames;
  14094. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  14095. subtree = &cert->excludedNames;
  14096. else {
  14097. WOLFSSL_MSG("\tinvalid subtree");
  14098. return ASN_PARSE_E;
  14099. }
  14100. if (DecodeSubtree(input + idx, length, subtree, cert->heap) < 0) {
  14101. WOLFSSL_MSG("\terror parsing subtree");
  14102. return ASN_PARSE_E;
  14103. }
  14104. idx += length;
  14105. }
  14106. return 0;
  14107. #else
  14108. ASNGetData dataASN[nameConstraintsASN_Length];
  14109. word32 idx = 0;
  14110. int ret = 0;
  14111. /* Clear dynamic data. */
  14112. XMEMSET(dataASN, 0, sizeof(dataASN));
  14113. /* Parse NameConstraints. */
  14114. ret = GetASN_Items(nameConstraintsASN, dataASN, nameConstraintsASN_Length,
  14115. 1, input, &idx, sz);
  14116. if (ret == 0) {
  14117. /* If there was a permittedSubtrees then parse it. */
  14118. if (dataASN[1].data.ref.data != NULL) {
  14119. ret = DecodeSubtree(dataASN[1].data.ref.data,
  14120. dataASN[1].data.ref.length, &cert->permittedNames, cert->heap);
  14121. }
  14122. }
  14123. if (ret == 0) {
  14124. /* If there was a excludedSubtrees then parse it. */
  14125. if (dataASN[2].data.ref.data != NULL) {
  14126. ret = DecodeSubtree(dataASN[2].data.ref.data,
  14127. dataASN[2].data.ref.length, &cert->excludedNames, cert->heap);
  14128. }
  14129. }
  14130. return ret;
  14131. #endif /* WOLFSSL_ASN_TEMPLATE */
  14132. }
  14133. #endif /* IGNORE_NAME_CONSTRAINTS */
  14134. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  14135. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14136. /* Decode ITU-T X.690 OID format to a string representation
  14137. * return string length */
  14138. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  14139. {
  14140. word32 val, inIdx = 0, outIdx = 0;
  14141. int w = 0;
  14142. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  14143. return BAD_FUNC_ARG;
  14144. /* The first byte expands into b/40 dot b%40. */
  14145. val = in[inIdx++];
  14146. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  14147. if (w < 0) {
  14148. w = BUFFER_E;
  14149. goto exit;
  14150. }
  14151. outIdx += w;
  14152. val = 0;
  14153. while (inIdx < inSz && outIdx < outSz) {
  14154. /* extract the next OID digit from in to val */
  14155. /* first bit is used to set if value is coded on 1 or multiple bytes */
  14156. if (in[inIdx] & 0x80) {
  14157. val += in[inIdx] & 0x7F;
  14158. val *= 128;
  14159. }
  14160. else {
  14161. /* write val as text into out */
  14162. val += in[inIdx];
  14163. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  14164. if (w < 0 || (word32)w > outSz - outIdx) {
  14165. w = BUFFER_E;
  14166. goto exit;
  14167. }
  14168. outIdx += w;
  14169. val = 0;
  14170. }
  14171. inIdx++;
  14172. }
  14173. if (outIdx == outSz)
  14174. outIdx--;
  14175. out[outIdx] = 0;
  14176. w = (int)outIdx;
  14177. exit:
  14178. return w;
  14179. }
  14180. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  14181. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  14182. #ifdef WOLFSSL_ASN_TEMPLATE
  14183. /* ASN.1 template for PolicyInformation.
  14184. * X.509: RFC 5280, 4.2.1.4 - Certificate Policies.
  14185. */
  14186. static const ASNItem policyInfoASN[] = {
  14187. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14188. /* policyIdentifier */
  14189. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  14190. /* policyQualifiers */
  14191. /* 2 */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  14192. };
  14193. /* Number of items in ASN.1 template for PolicyInformation. */
  14194. #define policyInfoASN_Length (sizeof(policyInfoASN) / sizeof(ASNItem))
  14195. #endif
  14196. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  14197. static int DecodeCertPolicy(const byte* input, int sz, DecodedCert* cert)
  14198. {
  14199. #ifndef WOLFSSL_ASN_TEMPLATE
  14200. word32 idx = 0;
  14201. word32 oldIdx;
  14202. int policy_length = 0;
  14203. int ret;
  14204. int total_length = 0;
  14205. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  14206. !defined(WOLFSSL_DUP_CERTPOL)
  14207. int i;
  14208. #endif
  14209. WOLFSSL_ENTER("DecodeCertPolicy");
  14210. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  14211. /* Check if cert is null before dereferencing below */
  14212. if (cert == NULL)
  14213. return BAD_FUNC_ARG;
  14214. #else
  14215. (void)cert;
  14216. #endif
  14217. #if defined(WOLFSSL_CERT_EXT)
  14218. cert->extCertPoliciesNb = 0;
  14219. #endif
  14220. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  14221. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  14222. return ASN_PARSE_E;
  14223. }
  14224. /* Validate total length */
  14225. if (total_length > (sz - (int)idx)) {
  14226. WOLFSSL_MSG("\tCertPolicy length mismatch");
  14227. return ASN_PARSE_E;
  14228. }
  14229. /* Unwrap certificatePolicies */
  14230. do {
  14231. int length = 0;
  14232. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  14233. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  14234. return ASN_PARSE_E;
  14235. }
  14236. oldIdx = idx;
  14237. ret = GetASNObjectId(input, &idx, &length, sz);
  14238. if (ret != 0)
  14239. return ret;
  14240. policy_length -= idx - oldIdx;
  14241. if (length > 0) {
  14242. /* Verify length won't overrun buffer */
  14243. if (length > (sz - (int)idx)) {
  14244. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  14245. return ASN_PARSE_E;
  14246. }
  14247. #if defined(WOLFSSL_SEP)
  14248. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  14249. DYNAMIC_TYPE_X509_EXT);
  14250. if (cert->deviceType == NULL) {
  14251. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  14252. return MEMORY_E;
  14253. }
  14254. cert->deviceTypeSz = length;
  14255. XMEMCPY(cert->deviceType, input + idx, length);
  14256. break;
  14257. #elif defined(WOLFSSL_CERT_EXT)
  14258. /* decode cert policy */
  14259. if (DecodePolicyOID(cert->extCertPolicies[
  14260. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  14261. input + idx, length) <= 0) {
  14262. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  14263. return ASN_PARSE_E;
  14264. }
  14265. #ifndef WOLFSSL_DUP_CERTPOL
  14266. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  14267. * NOT appear more than once in a certificate policies
  14268. * extension". This is a sanity check for duplicates.
  14269. * extCertPolicies should only have OID values, additional
  14270. * qualifiers need to be stored in a separate array. */
  14271. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  14272. if (XMEMCMP(cert->extCertPolicies[i],
  14273. cert->extCertPolicies[cert->extCertPoliciesNb],
  14274. MAX_CERTPOL_SZ) == 0) {
  14275. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  14276. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  14277. return CERTPOLICIES_E;
  14278. }
  14279. }
  14280. #endif /* !WOLFSSL_DUP_CERTPOL */
  14281. cert->extCertPoliciesNb++;
  14282. #else
  14283. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  14284. return 0;
  14285. #endif
  14286. }
  14287. idx += policy_length;
  14288. } while((int)idx < total_length
  14289. #if defined(WOLFSSL_CERT_EXT)
  14290. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  14291. #endif
  14292. );
  14293. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  14294. return 0;
  14295. #else /* WOLFSSL_ASN_TEMPLATE */
  14296. word32 idx = 0;
  14297. int ret = 0;
  14298. int total_length = 0;
  14299. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  14300. !defined(WOLFSSL_DUP_CERTPOL)
  14301. int i;
  14302. #endif
  14303. WOLFSSL_ENTER("DecodeCertPolicy");
  14304. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  14305. /* Check if cert is null before dereferencing below */
  14306. if (cert == NULL)
  14307. ret = BAD_FUNC_ARG;
  14308. #endif
  14309. if (ret == 0) {
  14310. #if defined(WOLFSSL_CERT_EXT)
  14311. cert->extCertPoliciesNb = 0;
  14312. #endif
  14313. /* Strip SEQUENCE OF and check using all data. */
  14314. if (GetASN_Sequence(input, &idx, &total_length, sz, 1) < 0) {
  14315. ret = ASN_PARSE_E;
  14316. }
  14317. }
  14318. /* Unwrap certificatePolicies */
  14319. while ((ret == 0) && ((int)idx < total_length)
  14320. #if defined(WOLFSSL_CERT_EXT)
  14321. && (cert->extCertPoliciesNb < MAX_CERTPOL_NB)
  14322. #endif
  14323. ) {
  14324. ASNGetData dataASN[policyInfoASN_Length];
  14325. byte* data;
  14326. word32 length = 0;
  14327. /* Clear dynamic data and check OID is a cert policy type. */
  14328. XMEMSET(dataASN, 0, sizeof(dataASN));
  14329. GetASN_OID(&dataASN[1], oidCertPolicyType);
  14330. ret = GetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length, 1,
  14331. input, &idx, sz);
  14332. if (ret == 0) {
  14333. /* Get the OID. */
  14334. GetASN_OIDData(&dataASN[1], &data, &length);
  14335. if (length == 0) {
  14336. ret = ASN_PARSE_E;
  14337. }
  14338. }
  14339. #if defined(WOLFSSL_SEP)
  14340. /* Store OID in device type. */
  14341. if (ret == 0) {
  14342. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  14343. DYNAMIC_TYPE_X509_EXT);
  14344. if (cert->deviceType == NULL) {
  14345. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  14346. ret = MEMORY_E;
  14347. }
  14348. }
  14349. if (ret == 0) {
  14350. /* Store device type data and length. */
  14351. cert->deviceTypeSz = length;
  14352. XMEMCPY(cert->deviceType, data, length);
  14353. break;
  14354. }
  14355. #elif defined(WOLFSSL_CERT_EXT)
  14356. if (ret == 0) {
  14357. /* Decode cert policy. */
  14358. if (DecodePolicyOID(
  14359. cert->extCertPolicies[cert->extCertPoliciesNb],
  14360. MAX_CERTPOL_SZ, data, length) <= 0) {
  14361. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  14362. ret = ASN_PARSE_E;
  14363. }
  14364. }
  14365. #ifndef WOLFSSL_DUP_CERTPOL
  14366. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  14367. * NOT appear more than once in a certificate policies
  14368. * extension". This is a sanity check for duplicates.
  14369. * extCertPolicies should only have OID values, additional
  14370. * qualifiers need to be stored in a seperate array. */
  14371. for (i = 0; (ret == 0) && (i < cert->extCertPoliciesNb); i++) {
  14372. if (XMEMCMP(cert->extCertPolicies[i],
  14373. cert->extCertPolicies[cert->extCertPoliciesNb],
  14374. MAX_CERTPOL_SZ) == 0) {
  14375. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  14376. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  14377. ret = CERTPOLICIES_E;
  14378. }
  14379. }
  14380. #endif /* !defined(WOLFSSL_DUP_CERTPOL) */
  14381. if (ret == 0) {
  14382. /* Keep count of policies seen. */
  14383. cert->extCertPoliciesNb++;
  14384. }
  14385. #else
  14386. (void)data;
  14387. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  14388. break;
  14389. #endif
  14390. }
  14391. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  14392. return ret;
  14393. #endif /* WOLFSSL_ASN_TEMPLATE */
  14394. }
  14395. #endif /* WOLFSSL_SEP */
  14396. /* Macro to check if bit is set, if not sets and return success.
  14397. Otherwise returns failure */
  14398. /* Macro required here because bit-field operation */
  14399. #ifndef WOLFSSL_NO_ASN_STRICT
  14400. #define VERIFY_AND_SET_OID(bit) \
  14401. if (bit == 0) \
  14402. bit = 1; \
  14403. else \
  14404. return ASN_OBJECT_ID_E;
  14405. #else
  14406. /* With no strict defined, the verify is skipped */
  14407. #define VERIFY_AND_SET_OID(bit) bit = 1;
  14408. #endif
  14409. /* Parse extension type specific data based on OID sum.
  14410. *
  14411. * Supported extensions:
  14412. * Basic Constraints - BASIC_CA_OID
  14413. * CRL Distribution Points - CRL_DIST_OID
  14414. * Authority Information Access - AUTH_INFO_OID
  14415. * Subject Alternative Name - ALT_NAMES_OID
  14416. * Authority Key Identifier - AUTH_KEY_OID
  14417. * Subject Key Identifier - SUBJ_KEY_OID
  14418. * Certificate Policies - CERT_POLICY_OID (conditional parsing)
  14419. * Key Usage - KEY_USAGE_OID
  14420. * Extended Key Usage - EXT_KEY_USAGE_OID
  14421. * Name Constraints - NAME_CONS_OID
  14422. * Inhibit anyPolicy - INHIBIT_ANY_OID
  14423. * Netscape Certificate Type - NETSCAPE_CT_OID (able to be excluded)
  14424. * OCSP no check - OCSP_NOCHECK_OID (when compiling OCSP)
  14425. * Unsupported extensions from RFC 580:
  14426. * 4.2.1.5 - Policy mappings
  14427. * 4.2.1.7 - Issuer Alternative Name
  14428. * 4.2.1.8 - Subject Directory Attributes
  14429. * 4.2.1.11 - Policy Constraints
  14430. * 4.2.1.15 - Freshest CRL
  14431. * 4.2.2.2 - Subject Information Access
  14432. *
  14433. * @param [in] input Buffer containing extension type specific data.
  14434. * @param [in] length Length of data.
  14435. * @param [in] oid OID sum for extension.
  14436. * @param [in] critical Whether extension is critical.
  14437. * @param [in, out] cert Certificate object.
  14438. * @return 0 on success.
  14439. * @return ASN_PARSE_E when BER encoding is invalid.
  14440. * @return MEMORY_E on dynamic memory allocation failure.
  14441. * @return Other -ve value on error.
  14442. */
  14443. static int DecodeExtensionType(const byte* input, int length, word32 oid,
  14444. byte critical, DecodedCert* cert)
  14445. {
  14446. int ret = 0;
  14447. word32 idx = 0;
  14448. switch (oid) {
  14449. /* Basic Constraints. */
  14450. case BASIC_CA_OID:
  14451. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  14452. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14453. cert->extBasicConstCrit = critical;
  14454. #endif
  14455. if (DecodeBasicCaConstraint(input, length, cert) < 0) {
  14456. ret = ASN_PARSE_E;
  14457. }
  14458. break;
  14459. /* CRL Distribution point. */
  14460. case CRL_DIST_OID:
  14461. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  14462. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14463. cert->extCRLdistCrit = critical;
  14464. #endif
  14465. if (DecodeCrlDist(input, length, cert) < 0) {
  14466. ret = ASN_PARSE_E;
  14467. }
  14468. break;
  14469. /* Authority information access. */
  14470. case AUTH_INFO_OID:
  14471. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  14472. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14473. cert->extAuthInfoCrit = critical;
  14474. #endif
  14475. if (DecodeAuthInfo(input, length, cert) < 0) {
  14476. ret = ASN_PARSE_E;
  14477. }
  14478. break;
  14479. /* Subject alternative name. */
  14480. case ALT_NAMES_OID:
  14481. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  14482. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14483. cert->extSubjAltNameCrit = critical;
  14484. #endif
  14485. ret = DecodeAltNames(input, length, cert);
  14486. break;
  14487. /* Authority Key Identifier. */
  14488. case AUTH_KEY_OID:
  14489. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  14490. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14491. cert->extAuthKeyIdCrit = critical;
  14492. #endif
  14493. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  14494. /* This check is added due to RFC 5280 section 4.2.1.1
  14495. * stating that conforming CA's must mark this extension
  14496. * as non-critical. When parsing extensions check that
  14497. * certificate was made in compliance with this. */
  14498. if (critical) {
  14499. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  14500. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  14501. ret = ASN_CRIT_EXT_E;
  14502. }
  14503. #endif
  14504. if ((ret == 0) && (DecodeAuthKeyId(input, length, cert) < 0)) {
  14505. ret = ASN_PARSE_E;
  14506. }
  14507. break;
  14508. /* Subject Key Identifier. */
  14509. case SUBJ_KEY_OID:
  14510. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  14511. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14512. cert->extSubjKeyIdCrit = critical;
  14513. #endif
  14514. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  14515. /* This check is added due to RFC 5280 section 4.2.1.2
  14516. * stating that conforming CA's must mark this extension
  14517. * as non-critical. When parsing extensions check that
  14518. * certificate was made in compliance with this. */
  14519. if (critical) {
  14520. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  14521. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  14522. ret = ASN_CRIT_EXT_E;
  14523. }
  14524. #endif
  14525. if ((ret == 0) && (DecodeSubjKeyId(input, length, cert) < 0)) {
  14526. ret = ASN_PARSE_E;
  14527. }
  14528. break;
  14529. /* Certificate policies. */
  14530. case CERT_POLICY_OID:
  14531. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  14532. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  14533. #if defined(OPENSSL_EXTRA) || \
  14534. defined(OPENSSL_EXTRA_X509_SMALL)
  14535. cert->extCertPolicyCrit = critical;
  14536. #endif
  14537. #endif
  14538. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  14539. defined(WOLFSSL_QT)
  14540. if (DecodeCertPolicy(input, length, cert) < 0) {
  14541. ret = ASN_PARSE_E;
  14542. }
  14543. #else
  14544. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  14545. #endif
  14546. break;
  14547. /* Key usage. */
  14548. case KEY_USAGE_OID:
  14549. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  14550. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14551. cert->extKeyUsageCrit = critical;
  14552. #endif
  14553. if (DecodeKeyUsage(input, length, cert) < 0) {
  14554. ret = ASN_PARSE_E;
  14555. }
  14556. break;
  14557. /* Extended key usage. */
  14558. case EXT_KEY_USAGE_OID:
  14559. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  14560. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14561. cert->extExtKeyUsageCrit = critical;
  14562. #endif
  14563. if (DecodeExtKeyUsage(input, length, cert) < 0) {
  14564. ret = ASN_PARSE_E;
  14565. }
  14566. break;
  14567. #ifndef IGNORE_NAME_CONSTRAINTS
  14568. /* Name constraints. */
  14569. case NAME_CONS_OID:
  14570. #ifndef WOLFSSL_NO_ASN_STRICT
  14571. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  14572. "The name constraints extension,
  14573. which MUST be used only in a CA certificate" */
  14574. if (!cert->isCA) {
  14575. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  14576. ret = ASN_NAME_INVALID_E;
  14577. }
  14578. #endif
  14579. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  14580. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14581. cert->extNameConstraintCrit = critical;
  14582. #endif
  14583. if (DecodeNameConstraints(input, length, cert) < 0) {
  14584. ret = ASN_PARSE_E;
  14585. }
  14586. break;
  14587. #endif /* IGNORE_NAME_CONSTRAINTS */
  14588. /* Inhibit anyPolicy. */
  14589. case INHIBIT_ANY_OID:
  14590. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  14591. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  14592. break;
  14593. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  14594. /* Netscape's certificate type. */
  14595. case NETSCAPE_CT_OID:
  14596. if (DecodeNsCertType(input, length, cert) < 0)
  14597. ret = ASN_PARSE_E;
  14598. break;
  14599. #endif
  14600. #ifdef HAVE_OCSP
  14601. /* OCSP no check. */
  14602. case OCSP_NOCHECK_OID:
  14603. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  14604. ret = GetASNNull(input, &idx, length);
  14605. if (ret != 0) {
  14606. ret = ASN_PARSE_E;
  14607. }
  14608. break;
  14609. #endif
  14610. case POLICY_CONST_OID:
  14611. VERIFY_AND_SET_OID(cert->extPolicyConstSet);
  14612. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  14613. cert->extPolicyConstCrit = critical;
  14614. #endif
  14615. if (DecodePolicyConstraints(&input[idx], length, cert) < 0)
  14616. return ASN_PARSE_E;
  14617. break;
  14618. default:
  14619. #ifndef WOLFSSL_NO_ASN_STRICT
  14620. /* While it is a failure to not support critical extensions,
  14621. * still parse the certificate ignoring the unsupported
  14622. * extension to allow caller to accept it with the verify
  14623. * callback. */
  14624. if (critical)
  14625. ret = ASN_CRIT_EXT_E;
  14626. #endif
  14627. break;
  14628. }
  14629. return ret;
  14630. }
  14631. #ifdef WOLFSSL_ASN_TEMPLATE
  14632. /* ASN.1 template for extensions.
  14633. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  14634. */
  14635. static const ASNItem certExtHdrASN[] = {
  14636. /* 0 */ { 0, ASN_CONTEXT_SPECIFIC | 3, 1, 1, 0 },
  14637. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14638. };
  14639. /* Number of itesm in ASN.1 template for extensions. */
  14640. #define certExtHdrASN_Length (sizeof(certExtHdrASN) / sizeof(ASNItem))
  14641. /* ASN.1 template for Extension.
  14642. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  14643. */
  14644. static const ASNItem certExtASN[] = {
  14645. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14646. /* Extension object id */
  14647. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  14648. /* critical - when true, must be parseable. */
  14649. /* 2 */ { 1, ASN_BOOLEAN, 0, 0, 1 },
  14650. /* Data for extension - leave index at start of data. */
  14651. /* 3 */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  14652. };
  14653. /* Number of items in ASN.1 template for Extension. */
  14654. #define certExtASN_Length (sizeof(certExtASN) / sizeof(ASNItem))
  14655. #endif
  14656. /*
  14657. * Processing the Certificate Extensions. This does not modify the current
  14658. * index. It is works starting with the recorded extensions pointer.
  14659. */
  14660. static int DecodeCertExtensions(DecodedCert* cert)
  14661. {
  14662. #ifndef WOLFSSL_ASN_TEMPLATE
  14663. int ret = 0;
  14664. word32 idx = 0;
  14665. int sz = cert->extensionsSz;
  14666. const byte* input = cert->extensions;
  14667. int length;
  14668. word32 oid;
  14669. byte critical = 0;
  14670. byte criticalFail = 0;
  14671. byte tag = 0;
  14672. WOLFSSL_ENTER("DecodeCertExtensions");
  14673. if (input == NULL || sz == 0)
  14674. return BAD_FUNC_ARG;
  14675. #ifdef WOLFSSL_CERT_REQ
  14676. if (!cert->isCSR)
  14677. #endif
  14678. { /* Not included in CSR */
  14679. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  14680. return ASN_PARSE_E;
  14681. }
  14682. if (tag != ASN_EXTENSIONS) {
  14683. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  14684. return ASN_PARSE_E;
  14685. }
  14686. if (GetLength(input, &idx, &length, sz) < 0) {
  14687. WOLFSSL_MSG("\tfail: invalid length");
  14688. return ASN_PARSE_E;
  14689. }
  14690. }
  14691. if (GetSequence(input, &idx, &length, sz) < 0) {
  14692. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  14693. return ASN_PARSE_E;
  14694. }
  14695. while (idx < (word32)sz) {
  14696. word32 localIdx;
  14697. if (GetSequence(input, &idx, &length, sz) < 0) {
  14698. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  14699. return ASN_PARSE_E;
  14700. }
  14701. oid = 0;
  14702. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  14703. WOLFSSL_MSG("\tfail: OBJECT ID");
  14704. return ret;
  14705. }
  14706. /* check for critical flag */
  14707. critical = 0;
  14708. if ((idx + 1) > (word32)sz) {
  14709. WOLFSSL_MSG("\tfail: malformed buffer");
  14710. return BUFFER_E;
  14711. }
  14712. localIdx = idx;
  14713. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  14714. if (tag == ASN_BOOLEAN) {
  14715. ret = GetBoolean(input, &idx, sz);
  14716. if (ret < 0) {
  14717. WOLFSSL_MSG("\tfail: critical boolean");
  14718. return ret;
  14719. }
  14720. critical = (byte)ret;
  14721. }
  14722. }
  14723. /* process the extension based on the OID */
  14724. ret = GetOctetString(input, &idx, &length, sz);
  14725. if (ret < 0) {
  14726. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  14727. return ret;
  14728. }
  14729. ret = DecodeExtensionType(input + idx, length, oid, critical, cert);
  14730. if (ret == ASN_CRIT_EXT_E) {
  14731. ret = 0;
  14732. criticalFail = 1;
  14733. }
  14734. if (ret < 0)
  14735. goto end;
  14736. idx += length;
  14737. }
  14738. ret = criticalFail ? ASN_CRIT_EXT_E : 0;
  14739. end:
  14740. return ret;
  14741. #else
  14742. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  14743. ASNGetData dataExtsASN[certExtHdrASN_Length];
  14744. int ret = 0;
  14745. const byte* input = cert->extensions;
  14746. int sz = cert->extensionsSz;
  14747. word32 idx = 0;
  14748. int criticalRet = 0;
  14749. int offset = 0;
  14750. WOLFSSL_ENTER("DecodeCertExtensions");
  14751. if (input == NULL || sz == 0)
  14752. ret = BAD_FUNC_ARG;
  14753. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, cert->heap);
  14754. #ifdef WOLFSSL_CERT_REQ
  14755. if (cert->isCSR) {
  14756. offset = 1;
  14757. }
  14758. #endif
  14759. if (ret == 0) {
  14760. /* Clear dynamic data. */
  14761. XMEMSET(dataExtsASN, 0, sizeof(dataExtsASN));
  14762. /* Parse extensions header. */
  14763. ret = GetASN_Items(certExtHdrASN + offset, dataExtsASN + offset,
  14764. certExtHdrASN_Length - offset, 0, input, &idx, sz);
  14765. }
  14766. /* Parse each extension. */
  14767. while ((ret == 0) && (idx < (word32)sz)) {
  14768. byte critical = 0;
  14769. /* Clear dynamic data. */
  14770. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  14771. /* Ensure OID is an extention type. */
  14772. GetASN_OID(&dataASN[1], oidCertExtType);
  14773. /* Set criticality variable. */
  14774. GetASN_Int8Bit(&dataASN[2], &critical);
  14775. /* Parse extension wrapper. */
  14776. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  14777. &idx, sz);
  14778. if (ret == 0) {
  14779. word32 oid = dataASN[1].data.oid.sum;
  14780. int length = dataASN[3].length;
  14781. /* Decode the extension by type. */
  14782. ret = DecodeExtensionType(input + idx, length, oid, critical, cert);
  14783. /* Move index on to next extension. */
  14784. idx += length;
  14785. }
  14786. /* Don't fail criticality until all other extensions have been checked.
  14787. */
  14788. if (ret == ASN_CRIT_EXT_E) {
  14789. criticalRet = ASN_CRIT_EXT_E;
  14790. ret = 0;
  14791. }
  14792. }
  14793. if (ret == 0) {
  14794. /* Use criticality return. */
  14795. ret = criticalRet;
  14796. }
  14797. FREE_ASNGETDATA(dataASN, cert->heap);
  14798. return ret;
  14799. #endif
  14800. }
  14801. #ifdef WOLFSSL_ASN_TEMPLATE
  14802. /* ASN template for an X509 certificate.
  14803. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  14804. */
  14805. static const ASNItem x509CertASN[] = {
  14806. /* Certificate ::= SEQUENCE */
  14807. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  14808. /* tbsCertificate TBSCertificate */
  14809. /* TBSCertificate ::= SEQUENCE */
  14810. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14811. /* version [0] EXPLICT Version DEFAULT v1 */
  14812. /* 2 */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  14813. /* Version ::= INTEGER { v1(0), v2(1), v3(2) */
  14814. /* 3 */ { 3, ASN_INTEGER, 0, 0, 0 },
  14815. /* serialNumber CertificateSerialNumber */
  14816. /* CetificateSerialNumber ::= INTEGER */
  14817. /* 4 */ { 2, ASN_INTEGER, 0, 0, 0 },
  14818. /* signature AlgorithmIdentifier */
  14819. /* AlgorithmIdentifier ::= SEQUENCE */
  14820. /* 5 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  14821. /* Algorithm OBJECT IDENTIFIER */
  14822. /* 6 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  14823. /* parameters ANY defined by algorithm OPTIONAL */
  14824. /* 7 */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  14825. /* issuer Name */
  14826. /* 8 */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  14827. /* validity Validity */
  14828. /* Validity ::= SEQUENCE */
  14829. /* 9 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  14830. /* notBefore Time */
  14831. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  14832. /* 10 */ { 3, ASN_UTC_TIME, 0, 0, 2 },
  14833. /* 11 */ { 3, ASN_GENERALIZED_TIME, 0, 0, 2 },
  14834. /* notAfter Time */
  14835. /* Time :: CHOICE { UTCTime, GeneralizedTime } */
  14836. /* 12 */ { 3, ASN_UTC_TIME, 0, 0, 3 },
  14837. /* 13 */ { 3, ASN_GENERALIZED_TIME, 0, 0, 3 },
  14838. /* subject Name */
  14839. /* 14 */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  14840. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  14841. /* 15 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  14842. /* algorithm AlgorithmIdentifier */
  14843. /* AlgorithmIdentifier ::= SEQUENCE */
  14844. /* 16 */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  14845. /* Algorithm OBJECT IDENTIFIER */
  14846. /* 17 */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  14847. /* parameters ANY defined by algorithm OPTIONAL */
  14848. /* 18 */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  14849. /* 19 */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  14850. /* subjectPublicKey BIT STRING */
  14851. /* 20 */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  14852. /* issuerUniqueID UniqueIdentfier OPTIONAL */
  14853. /* 21 */ { 2, ASN_CONTEXT_SPECIFIC | 1, 0, 0, 1 },
  14854. /* subjectUniqueID UniqueIdentfier OPTIONAL */
  14855. /* 22 */ { 2, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 1 },
  14856. /* extensions Extensions OPTIONAL */
  14857. /* 23 */ { 2, ASN_CONTEXT_SPECIFIC | 3, 1, 0, 1 },
  14858. /* signatureAlgorithm AlgorithmIdentifier */
  14859. /* AlgorithmIdentifier ::= SEQUENCE */
  14860. /* 24 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  14861. /* Algorithm OBJECT IDENTIFIER */
  14862. /* 25 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  14863. /* parameters ANY defined by algorithm OPTIONAL */
  14864. /* 26 */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  14865. /* signature BIT STRING */
  14866. /* 27 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  14867. };
  14868. /* Number of items in ASN template for an X509 certificate. */
  14869. #define x509CertASN_Length (sizeof(x509CertASN) / sizeof(ASNItem))
  14870. /* Check the data data.
  14871. *
  14872. * @param [in] dataASN ASN template dynamic data item.
  14873. * @param [in] dataType BEFORE or AFTER date.
  14874. * @return 0 on success.
  14875. * @return ASN_TIME_E when BER tag is nor UTC or GENERALIZED time.
  14876. * @return ASN_DATE_SZ_E when time data is not supported.
  14877. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  14878. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  14879. */
  14880. static int CheckDate(ASNGetData *dataASN, int dateType)
  14881. {
  14882. int ret = 0;
  14883. /* Check BER tag is valid. */
  14884. if ((dataASN->tag != ASN_UTC_TIME) &&
  14885. (dataASN->tag != ASN_GENERALIZED_TIME)) {
  14886. ret = ASN_TIME_E;
  14887. }
  14888. /* Check date length is valid. */
  14889. if ((ret == 0) && ((dataASN->length > MAX_DATE_SIZE) ||
  14890. (dataASN->length < MIN_DATE_SIZE))) {
  14891. ret = ASN_DATE_SZ_E;
  14892. }
  14893. #ifndef NO_ASN_TIME
  14894. /* Check date is a valid string and BEFORE or AFTER now. */
  14895. if ((ret == 0) &&
  14896. (!XVALIDATE_DATE(dataASN->data.ref.data, dataASN->tag, dateType))) {
  14897. if (dateType == BEFORE) {
  14898. ret = ASN_BEFORE_DATE_E;
  14899. }
  14900. else {
  14901. ret = ASN_AFTER_DATE_E;
  14902. }
  14903. }
  14904. #endif
  14905. (void)dateType;
  14906. return ret;
  14907. }
  14908. /* Decode a certificate. Internal/non-public API.
  14909. *
  14910. * @param [in] cert Certificate object.
  14911. * @param [in] verify Whether to verify dates before and after now.
  14912. * @param [out] criticalExt Critical extension return code.
  14913. * @param [out] badDateRet Bad date return code.
  14914. * @param [in] stopAtPubKey Stop parsing before subkectPublicKeyInfo.
  14915. * @param [in] stopAfterPubKey Stop parsing after subkectPublicKeyInfo.
  14916. * @return 0 on success.
  14917. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  14918. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  14919. * @return ASN_DATE_SZ_E when time data is not supported.
  14920. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  14921. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  14922. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  14923. * is invalid.
  14924. * @return BUFFER_E when data in buffer is too small.
  14925. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  14926. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  14927. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  14928. * non-zero length.
  14929. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  14930. */
  14931. static int DecodeCertInternal(DecodedCert* cert, int verify, int* criticalExt,
  14932. int* badDateRet, int stopAtPubKey,
  14933. int stopAfterPubKey)
  14934. {
  14935. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  14936. int ret = 0;
  14937. int badDate = 0;
  14938. int i;
  14939. byte version;
  14940. word32 idx;
  14941. word32 serialSz;
  14942. int done = 0;
  14943. CALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  14944. if (ret == 0) {
  14945. version = 0;
  14946. serialSz = EXTERNAL_SERIAL_SIZE;
  14947. /* Get the version and put the serial number into the buffer. */
  14948. GetASN_Int8Bit(&dataASN[3], &version);
  14949. GetASN_Buffer(&dataASN[4], cert->serial, &serialSz);
  14950. /* Check OID types for signature, algorithm, ECC curve and sigAlg. */
  14951. GetASN_OID(&dataASN[6], oidSigType);
  14952. GetASN_OID(&dataASN[17], oidKeyType);
  14953. GetASN_OID(&dataASN[19], oidCurveType);
  14954. GetASN_OID(&dataASN[25], oidSigType);
  14955. /* Parse the X509 certificate. */
  14956. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1,
  14957. cert->source, &cert->srcIdx, cert->maxIdx);
  14958. }
  14959. /* Check version is valid/supported - can't be negative. */
  14960. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  14961. WOLFSSL_MSG("Unexpected certificate version");
  14962. ret = ASN_PARSE_E;
  14963. }
  14964. if (ret == 0) {
  14965. /* Set fields extracted from data. */
  14966. cert->version = version;
  14967. cert->serialSz = serialSz;
  14968. cert->signatureOID = dataASN[6].data.oid.sum;
  14969. cert->keyOID = dataASN[17].data.oid.sum;
  14970. cert->certBegin = dataASN[1].offset;
  14971. /* No bad date error - don't always care. */
  14972. badDate = 0;
  14973. /* Find the item with the BEFORE date and check it. */
  14974. i = (dataASN[10].tag != 0) ? 10 : 11;
  14975. if ((CheckDate(&dataASN[i], BEFORE) < 0) && verify) {
  14976. badDate = ASN_BEFORE_DATE_E;
  14977. }
  14978. /* Store reference to BEFOREdate. */
  14979. cert->beforeDate = GetASNItem_Addr(dataASN[i], cert->source);
  14980. cert->beforeDateLen = GetASNItem_Length(dataASN[i], cert->source);
  14981. /* Find the item with the AFTER date and check it. */
  14982. i = (dataASN[12].tag != 0) ? 12 : 13;
  14983. if ((CheckDate(&dataASN[i], AFTER) < 0) && verify) {
  14984. badDate = ASN_AFTER_DATE_E;
  14985. }
  14986. /* Store reference to AFTER date. */
  14987. cert->afterDate = GetASNItem_Addr(dataASN[i], cert->source);
  14988. cert->afterDateLen = GetASNItem_Length(dataASN[i], cert->source);
  14989. /* Get the issuer name and calculate hash. */
  14990. idx = dataASN[8].offset;
  14991. ret = GetCertName(cert, cert->issuer, cert->issuerHash, ISSUER,
  14992. cert->source, &idx, dataASN[9].offset);
  14993. }
  14994. if (ret == 0) {
  14995. /* Get the subject name and calculate hash. */
  14996. idx = dataASN[14].offset;
  14997. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  14998. cert->source, &idx, dataASN[15].offset);
  14999. }
  15000. if (ret == 0) {
  15001. /* Determine if self signed by comparig issuer and subject hashes. */
  15002. cert->selfSigned = XMEMCMP(cert->issuerHash, cert->subjectHash,
  15003. KEYID_SIZE) == 0 ? 1 : 0;
  15004. if (stopAtPubKey) {
  15005. /* Return any bad date error through badDateRed and return offset of
  15006. * subjectPublicKeyInfo.
  15007. */
  15008. if (badDateRet != NULL) {
  15009. *badDateRet = badDate;
  15010. }
  15011. ret = dataASN[15].offset;
  15012. done = 1;
  15013. }
  15014. }
  15015. if ((ret == 0) && (!done)) {
  15016. /* Parse the public key. */
  15017. idx = dataASN[15].offset;
  15018. ret = GetCertKey(cert, cert->source, &idx, dataASN[21].offset);
  15019. if ((ret == 0) && stopAfterPubKey) {
  15020. /* Return any bad date error through badDateRed and return offset
  15021. * after subjectPublicKeyInfo.
  15022. */
  15023. if (badDateRet != NULL) {
  15024. *badDateRet = badDate;
  15025. }
  15026. done = 1;
  15027. }
  15028. }
  15029. if ((ret == 0) && (!done) && (dataASN[23].data.ref.data != NULL)) {
  15030. #ifndef ALLOW_V1_EXTENSIONS
  15031. /* Certificate extensions were only defined in version 2. */
  15032. if (cert->version < 2) {
  15033. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  15034. ret = ASN_VERSION_E;
  15035. }
  15036. #endif
  15037. if (ret == 0) {
  15038. /* Save references to extension data. */
  15039. cert->extensions = GetASNItem_Addr(dataASN[23], cert->source);
  15040. cert->extensionsSz = GetASNItem_Length(dataASN[23], cert->source);
  15041. cert->extensionsIdx = dataASN[23].offset;
  15042. /* Decode the extension data starting at [3]. */
  15043. ret = DecodeCertExtensions(cert);
  15044. if (criticalExt != NULL) {
  15045. if (ret == ASN_CRIT_EXT_E) {
  15046. /* Return critical extension not recognized. */
  15047. *criticalExt = ret;
  15048. ret = 0;
  15049. }
  15050. else {
  15051. /* No critical extension error. */
  15052. *criticalExt = 0;
  15053. }
  15054. }
  15055. }
  15056. if (ret == 0) {
  15057. /* Advance past extensions. */
  15058. cert->srcIdx = dataASN[24].offset;
  15059. }
  15060. }
  15061. if ((ret == 0) && (!done)) {
  15062. /* Store the signature information. */
  15063. cert->sigIndex = dataASN[24].offset;
  15064. GetASN_GetConstRef(&dataASN[27], &cert->signature, &cert->sigLength);
  15065. /* Make sure 'signature' and 'signatureAlgorithm' are the same. */
  15066. if (dataASN[25].data.oid.sum != cert->signatureOID) {
  15067. ret = ASN_SIG_OID_E;
  15068. }
  15069. /* NULL tagged item not allowed after ECDSA or EdDSA algorithm OID. */
  15070. if (IsSigAlgoECC(cert->signatureOID) && (dataASN[26].tag != 0)) {
  15071. ret = ASN_PARSE_E;
  15072. }
  15073. }
  15074. if ((ret == 0) && (!done) && (badDate != 0)) {
  15075. /* Parsed whole certificate fine but return any date errors. */
  15076. ret = badDate;
  15077. }
  15078. FREE_ASNGETDATA(dataASN, cert->heap);
  15079. return ret;
  15080. }
  15081. /* Decode BER/DER data into certificate object.
  15082. *
  15083. * BER/DER data information held in source, srcIdx and maxIdx fields of
  15084. * certificate object.
  15085. *
  15086. * @param [in] cert Decoded certificate object.
  15087. * @param [in] verify Whether to find CA and verify certificate.
  15088. * @param [in] criticalExt Any error for critical extensions not recognized.
  15089. * @return 0 on success.
  15090. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  15091. * @return ASN_TIME_E when date BER tag is nor UTC or GENERALIZED time.
  15092. * @return ASN_DATE_SZ_E when time data is not supported.
  15093. * @return ASN_BEFORE_DATE_E when BEFORE date is invalid.
  15094. * @return ASN_AFTER_DATE_E when AFTER date is invalid.
  15095. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15096. * is invalid.
  15097. * @return BUFFER_E when data in buffer is too small.
  15098. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  15099. * @return ASN_BITSTR_E when the expected BIT_STRING tag is not found.
  15100. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  15101. * non-zero length.
  15102. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15103. */
  15104. int DecodeCert(DecodedCert* cert, int verify, int* criticalExt)
  15105. {
  15106. return DecodeCertInternal(cert, verify, criticalExt, NULL, 0, 0);
  15107. }
  15108. #ifdef WOLFSSL_CERT_REQ
  15109. /* ASN.1 template for certificate request Attribute.
  15110. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  15111. */
  15112. static const ASNItem reqAttrASN[] = {
  15113. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  15114. /* type */
  15115. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  15116. /* values */
  15117. /* 2 */ { 1, ASN_SET, 1, 0, 0 },
  15118. };
  15119. /* Number of items in ASN.1 template for certificate request Attribute. */
  15120. #define reqAttrASN_Length (sizeof(reqAttrASN) / sizeof(ASNItem))
  15121. /* ASN.1 template for a string choice. */
  15122. static const ASNItem strAttrASN[] = {
  15123. { 0, 0, 0, 0, 0 },
  15124. };
  15125. /* Number of items in ASN.1 template for a string choice. */
  15126. #define strAttrASN_Length (sizeof(strAttrASN) / sizeof(ASNItem))
  15127. /* ASN.1 choices for types for a string in an attribute. */
  15128. static const byte strAttrChoice[] = {
  15129. ASN_PRINTABLE_STRING, ASN_IA5_STRING, ASN_UTF8STRING, 0
  15130. };
  15131. /* Decode a certificate request attribute's value.
  15132. *
  15133. * @param [in] cert Certificate request object.
  15134. * @param [out] criticalExt Critical extension return code.
  15135. * @param [in] oid OID decribing which attribute was found.
  15136. * @param [in] aIdx Index into certificate source to start parsing.
  15137. * @param [in] input Attribute value data.
  15138. * @param [in] maxIdx Maximum index to parse to.
  15139. * @return 0 on success.
  15140. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15141. * is invalid.
  15142. */
  15143. static int DecodeCertReqAttrValue(DecodedCert* cert, int* criticalExt,
  15144. word32 oid, word32 aIdx, const byte* input, word32 maxIdx)
  15145. {
  15146. int ret = 0;
  15147. word32 idx = 0;
  15148. ASNGetData strDataASN[strAttrASN_Length];
  15149. switch (oid) {
  15150. case PKCS9_CONTENT_TYPE_OID:
  15151. /* Clear dynamic data and specify choices acceptable. */
  15152. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  15153. GetASN_Choice(&strDataASN[0], strAttrChoice);
  15154. /* Parse a string. */
  15155. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  15156. 1, input, &idx, maxIdx);
  15157. if (ret == 0) {
  15158. /* Store references to password data. */
  15159. cert->contentType = (char*)strDataASN[0].data.ref.data;
  15160. cert->contentTypeLen = strDataASN[0].data.ref.length;
  15161. }
  15162. break;
  15163. /* A password by which the entity may request certificate revocation.
  15164. * PKCS#9: RFC 2985, 5.4.1 - Challenge password
  15165. */
  15166. case CHALLENGE_PASSWORD_OID:
  15167. /* Clear dynamic data and specify choices acceptable. */
  15168. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  15169. GetASN_Choice(&strDataASN[0], strAttrChoice);
  15170. /* Parse a string. */
  15171. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  15172. 1, input, &idx, maxIdx);
  15173. if (ret == 0) {
  15174. /* Store references to password data. */
  15175. cert->cPwd = (char*)strDataASN[0].data.ref.data;
  15176. cert->cPwdLen = strDataASN[0].data.ref.length;
  15177. }
  15178. break;
  15179. /* Requested serial number to issue with.
  15180. * PKCS#9: RFC 2985, 5.2.10 - Serial Number
  15181. * (References: ISO/IEC 9594-6:1997)
  15182. */
  15183. case SERIAL_NUMBER_OID:
  15184. /* Clear dynamic data and specify choices acceptable. */
  15185. XMEMSET(strDataASN, 0, sizeof(strDataASN));
  15186. GetASN_Choice(&strDataASN[0], strAttrChoice);
  15187. /* Parse a string. */
  15188. ret = GetASN_Items(strAttrASN, strDataASN, strAttrASN_Length,
  15189. 1, input, &idx, maxIdx);
  15190. if (ret == 0) {
  15191. /* Store references to serial number. */
  15192. cert->sNum = (char*)strDataASN[0].data.ref.data;
  15193. cert->sNumLen = strDataASN[0].data.ref.length;
  15194. /* Store serial number if small enough. */
  15195. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  15196. XMEMCPY(cert->serial, cert->sNum, cert->sNumLen);
  15197. cert->serialSz = cert->sNumLen;
  15198. }
  15199. }
  15200. break;
  15201. /* Certificate extensions to be included in generated certificate.
  15202. * PKCS#9: RFC 2985, 5.4.2 - Extension request
  15203. */
  15204. case EXTENSION_REQUEST_OID:
  15205. /* Store references to all extensions. */
  15206. cert->extensions = input;
  15207. cert->extensionsSz = maxIdx;
  15208. cert->extensionsIdx = aIdx;
  15209. /* Decode and validate extensions. */
  15210. ret = DecodeCertExtensions(cert);
  15211. if (ret == ASN_CRIT_EXT_E) {
  15212. /* Return critical extension not recognized. */
  15213. *criticalExt = ret;
  15214. ret = 0;
  15215. }
  15216. else {
  15217. /* No critical extension error. */
  15218. *criticalExt = 0;
  15219. }
  15220. break;
  15221. default:
  15222. ret = ASN_PARSE_E;
  15223. break;
  15224. }
  15225. return ret;
  15226. }
  15227. /* Decode attributes of a BER encoded certificate request.
  15228. *
  15229. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  15230. *
  15231. * Outer sequence has been removed.
  15232. *
  15233. * @param [in] cert Certificate request object.
  15234. * @param [out] criticalExt Critical extension return code.
  15235. * @param [in] idx Index into certificate source to start parsing.
  15236. * @param [in] maxIdx Maximum index to parse to.
  15237. * @return 0 on success.
  15238. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  15239. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15240. * is invalid.
  15241. * @return BUFFER_E when data in buffer is too small.
  15242. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  15243. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  15244. * non-zero length.
  15245. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15246. */
  15247. static int DecodeCertReqAttributes(DecodedCert* cert, int* criticalExt,
  15248. word32 idx, word32 maxIdx)
  15249. {
  15250. DECL_ASNGETDATA(dataASN, reqAttrASN_Length);
  15251. int ret = 0;
  15252. WOLFSSL_ENTER("DecodeCertReqAttributes");
  15253. ALLOC_ASNGETDATA(dataASN, reqAttrASN_Length, ret, cert->heap);
  15254. /* Parse each attribute until all data used up. */
  15255. while ((ret == 0) && (idx < maxIdx)) {
  15256. /* Clear dynamic data. */
  15257. XMEMSET(dataASN, 0, sizeof(ASNGetData) * reqAttrASN_Length);
  15258. GetASN_OID(&dataASN[1], oidIgnoreType);
  15259. /* Parse an attribute. */
  15260. ret = GetASN_Items(reqAttrASN, dataASN, reqAttrASN_Length, 0,
  15261. cert->source, &idx, maxIdx);
  15262. /* idx is now at end of attribute data. */
  15263. if (ret == 0) {
  15264. ret = DecodeCertReqAttrValue(cert, criticalExt,
  15265. dataASN[1].data.oid.sum,
  15266. GetASNItem_DataIdx(dataASN[2], cert->source),
  15267. dataASN[2].data.ref.data, dataASN[2].data.ref.length);
  15268. }
  15269. }
  15270. FREE_ASNGETDATA(dataASN, cert->heap);
  15271. return ret;
  15272. }
  15273. /* ASN.1 template for a certificate request.
  15274. * PKCS#10: RFC 2986, 4.1 - CertificationRequestInfo
  15275. */
  15276. static const ASNItem certReqASN[] = {
  15277. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  15278. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  15279. /* version INTEGER { v1(0), v2(1), v3(2) */
  15280. /* 2 */ { 2, ASN_INTEGER, 0, 0, 0 },
  15281. /* subject Name */
  15282. /* 3 */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  15283. /* subjectPublicKeyInfo SubjectPublicKeyInfo */
  15284. /* 4 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  15285. /* algorithm AlgorithmIdentifier */
  15286. /* 5 */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  15287. /* Algorithm OBJECT IDENTIFIER */
  15288. /* 6 */ { 4, ASN_OBJECT_ID, 0, 0, 0 },
  15289. /* parameters ANY defined by algorithm OPTIONAL */
  15290. /* 7 */ { 4, ASN_TAG_NULL, 0, 0, 1 },
  15291. /* 8 */ { 4, ASN_OBJECT_ID, 0, 0, 1 },
  15292. /* 9 */ { 4, ASN_SEQUENCE, 1, 0, 1 },
  15293. /* subjectPublicKey BIT STRING */
  15294. /* 10 */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  15295. /* attributes [0] Attributes */
  15296. /* 11 */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 0, 1 },
  15297. /* signatureAlgorithm AlgorithmIdentifier */
  15298. /* 12 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  15299. /* Algorithm OBJECT IDENTIFIER */
  15300. /* 13 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  15301. /* parameters ANY defined by algorithm OPTIONAL */
  15302. /* 14 */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  15303. /* signature BIT STRING */
  15304. /* 15 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  15305. };
  15306. /* Number of items in ASN.1 template for a certificate request. */
  15307. #define certReqASN_Length (sizeof(certReqASN) / sizeof(ASNItem))
  15308. /* Parse BER encoded certificate request.
  15309. *
  15310. * RFC 2986 - PKCS #10: Certification Request Syntax Specification Version 1.7
  15311. *
  15312. * @param [in] cert Certificate request object.
  15313. * @param [out] criticalExt Critical extension return code.
  15314. * @return 0 on success.
  15315. * @return ASN_CRIT_EXT_E when a critical extension was not recognized.
  15316. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15317. * is invalid.
  15318. * @return BUFFER_E when data in buffer is too small.
  15319. * @return ASN_OBJECT_ID_E when the expected OBJECT_ID tag is not found.
  15320. * @return ASN_EXPECT_0_E when the INTEGER has the MSB set or NULL has a
  15321. * non-zero length.
  15322. * @return ASN_UNKNOWN_OID_E when the OID cannot be verified.
  15323. * @return MEMORY_E on dynamic memory allocation failure.
  15324. */
  15325. static int DecodeCertReq(DecodedCert* cert, int* criticalExt)
  15326. {
  15327. DECL_ASNGETDATA(dataASN, certReqASN_Length);
  15328. int ret = 0;
  15329. byte version;
  15330. word32 idx;
  15331. CALLOC_ASNGETDATA(dataASN, certReqASN_Length, ret, cert->heap);
  15332. if (ret == 0) {
  15333. /* Default version is 0. */
  15334. version = 0;
  15335. /* Set version var and OID types to expect. */
  15336. GetASN_Int8Bit(&dataASN[2], &version);
  15337. GetASN_OID(&dataASN[6], oidKeyType);
  15338. GetASN_OID(&dataASN[8], oidCurveType);
  15339. GetASN_OID(&dataASN[13], oidSigType);
  15340. /* Parse a certificate request. */
  15341. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1,
  15342. cert->source, &cert->srcIdx, cert->maxIdx);
  15343. }
  15344. /* Check version is valid/supported - can't be negative. */
  15345. if ((ret == 0) && (version > MAX_X509_VERSION)) {
  15346. WOLFSSL_MSG("Unexpected certificate request version");
  15347. ret = ASN_PARSE_E;
  15348. }
  15349. if (ret == 0) {
  15350. /* Set fields of certificate request. */
  15351. cert->version = version;
  15352. cert->signatureOID = dataASN[13].data.oid.sum;
  15353. cert->keyOID = dataASN[6].data.oid.sum;
  15354. cert->certBegin = dataASN[1].offset;
  15355. /* Parse the subject name. */
  15356. idx = dataASN[3].offset;
  15357. ret = GetCertName(cert, cert->subject, cert->subjectHash, SUBJECT,
  15358. cert->source, &idx, dataASN[4].offset);
  15359. }
  15360. if (ret == 0) {
  15361. /* Parse the certificate request Attributes. */
  15362. ret = DecodeCertReqAttributes(cert, criticalExt,
  15363. GetASNItem_DataIdx(dataASN[11], cert->source), dataASN[12].offset);
  15364. }
  15365. if (ret == 0) {
  15366. /* Parse the certificate request's key. */
  15367. idx = dataASN[4].offset;
  15368. ret = GetCertKey(cert, cert->source, &idx, dataASN[11].offset);
  15369. }
  15370. if (ret == 0) {
  15371. /* Store references to signature. */
  15372. cert->sigIndex = dataASN[12].offset;
  15373. GetASN_GetConstRef(&dataASN[15], &cert->signature, &cert->sigLength);
  15374. }
  15375. FREE_ASNGETDATA(dataASN, cert->heap);
  15376. return ret;
  15377. }
  15378. #endif /* WOLFSSL_CERT_REQ */
  15379. #endif
  15380. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  15381. {
  15382. int ret;
  15383. char* ptr;
  15384. ret = ParseCertRelative(cert, type, verify, cm);
  15385. if (ret < 0)
  15386. return ret;
  15387. if (cert->subjectCNLen > 0) {
  15388. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  15389. DYNAMIC_TYPE_SUBJECT_CN);
  15390. if (ptr == NULL)
  15391. return MEMORY_E;
  15392. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  15393. ptr[cert->subjectCNLen] = '\0';
  15394. cert->subjectCN = ptr;
  15395. cert->subjectCNStored = 1;
  15396. }
  15397. if (cert->keyOID == RSAk &&
  15398. cert->publicKey != NULL && cert->pubKeySize > 0) {
  15399. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  15400. DYNAMIC_TYPE_PUBLIC_KEY);
  15401. if (ptr == NULL)
  15402. return MEMORY_E;
  15403. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  15404. cert->publicKey = (byte *)ptr;
  15405. cert->pubKeyStored = 1;
  15406. }
  15407. return ret;
  15408. }
  15409. #if !defined(OPENSSL_EXTRA) && !defined(OPENSSL_EXTRA_X509_SMALL) && \
  15410. !defined(GetCA)
  15411. /* from SSL proper, for locking can't do find here anymore.
  15412. * brought in from internal.h if built with compat layer.
  15413. * if defined(GetCA), it's a predefined macro and these prototypes
  15414. * would conflict.
  15415. */
  15416. #ifdef __cplusplus
  15417. extern "C" {
  15418. #endif
  15419. Signer* GetCA(void* signers, byte* hash);
  15420. #ifndef NO_SKID
  15421. Signer* GetCAByName(void* signers, byte* hash);
  15422. #endif
  15423. #ifdef __cplusplus
  15424. }
  15425. #endif
  15426. #endif /* !OPENSSL_EXTRA && !OPENSSL_EXTRA_X509_SMALL && !GetCA */
  15427. #if defined(WOLFCRYPT_ONLY)
  15428. /* dummy functions, not using wolfSSL so don't need actual ones */
  15429. Signer* GetCA(void* signers, byte* hash)
  15430. {
  15431. (void)hash;
  15432. return (Signer*)signers;
  15433. }
  15434. #ifndef NO_SKID
  15435. Signer* GetCAByName(void* signers, byte* hash)
  15436. {
  15437. (void)hash;
  15438. return (Signer*)signers;
  15439. }
  15440. #endif /* NO_SKID */
  15441. #endif /* WOLFCRYPT_ONLY */
  15442. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  15443. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  15444. {
  15445. Signer* ca = NULL;
  15446. if (cert->extSubjKeyIdSet)
  15447. ca = GetCA(cm, cert->extSubjKeyId);
  15448. if (ca == NULL)
  15449. ca = GetCAByName(cm, cert->subjectHash);
  15450. if (ca) {
  15451. if ((ca->pubKeySize == cert->pubKeySize) &&
  15452. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  15453. return ca;
  15454. }
  15455. }
  15456. return NULL;
  15457. }
  15458. #endif
  15459. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  15460. #ifdef WOLFSSL_ASN_TEMPLATE
  15461. /* Get the Hash of the Authority Key Identifier from the list of extensions.
  15462. *
  15463. * @param [in] input Input data.
  15464. * @param [in] maxIdx Maximum index for data.
  15465. * @param [out] hash Hash of AKI.
  15466. * @param [out] set Whether the hash buffer was set.
  15467. * @param [in] heap Dynamic memory allocation hint.
  15468. * @return 0 on success.
  15469. * @return ASN_PARSE_E when BER encoded data does not match ASN.1 items or
  15470. * is invalid.
  15471. * @return MEMORY_E on dynamic memory allocation failure.
  15472. */
  15473. static int GetAKIHash(const byte* input, word32 maxIdx, byte* hash, int* set,
  15474. void* heap)
  15475. {
  15476. /* AKI and Certificate Extenion ASN.1 templates are the same length. */
  15477. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  15478. int ret = 0;
  15479. word32 idx = 0;
  15480. int extLen = 0;
  15481. word32 extEndIdx;
  15482. byte* extData;
  15483. word32 extDataSz;
  15484. byte critical;
  15485. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, heap);
  15486. (void)heap;
  15487. /* Parse the outer SEQUENCE and calculate end index of extensions. */
  15488. if ((ret == 0) && (GetASN_Sequence(input, &idx, &extLen, maxIdx, 1) < 0)) {
  15489. ret = ASN_PARSE_E;
  15490. }
  15491. extEndIdx = idx + extLen;
  15492. /* Step through each extension looking for AKI. */
  15493. while ((ret == 0) && (idx < extEndIdx)) {
  15494. /* Clear dynamic data and check for certificate extension type OIDs. */
  15495. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  15496. GetASN_OID(&dataASN[1], oidCertExtType);
  15497. /* Set criticality variable. */
  15498. GetASN_Int8Bit(&dataASN[2], &critical);
  15499. /* Parse an extension. */
  15500. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, input,
  15501. &idx, extEndIdx);
  15502. if (ret == 0) {
  15503. /* Get reference to extension data and move index on past this
  15504. * extension. */
  15505. GetASN_GetRef(&dataASN[3], &extData, &extDataSz);
  15506. idx += extDataSz;
  15507. /* Check whether we have the AKI extension. */
  15508. if (dataASN[1].data.oid.sum == AUTH_KEY_OID) {
  15509. /* Clear dynamic data. */
  15510. XMEMSET(dataASN, 0, sizeof(*dataASN) * authKeyIdASN_Length);
  15511. /* Start parsing extension data from the start. */
  15512. idx = 0;
  15513. /* Parse AKI extension data. */
  15514. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length,
  15515. 1, extData, &idx, extDataSz);
  15516. if ((ret == 0) && (dataASN[1].data.ref.data != NULL)) {
  15517. /* We parsed successfully and have data. */
  15518. *set = 1;
  15519. /* Get the hash or hash of the hash if wrong size. */
  15520. ret = GetHashId(dataASN[1].data.ref.data,
  15521. dataASN[1].data.ref.length, hash);
  15522. }
  15523. break;
  15524. }
  15525. }
  15526. }
  15527. FREE_ASNGETDATA(dataASN, heap);
  15528. return ret;
  15529. }
  15530. #endif
  15531. /* Only quick step through the certificate to find fields that are then used
  15532. * in certificate signature verification.
  15533. * Must use the signature OID from the signed part of the certificate.
  15534. * Works also on certificate signing requests.
  15535. *
  15536. * This is only for minimizing dynamic memory usage during TLS certificate
  15537. * chain processing.
  15538. * Doesn't support:
  15539. * OCSP Only: alt lookup using subject and pub key w/o sig check
  15540. */
  15541. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  15542. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  15543. {
  15544. #ifndef WOLFSSL_ASN_TEMPLATE
  15545. #ifndef WOLFSSL_SMALL_STACK
  15546. SignatureCtx sigCtx[1];
  15547. #else
  15548. SignatureCtx* sigCtx;
  15549. #endif
  15550. byte hash[KEYID_SIZE];
  15551. Signer* ca = NULL;
  15552. word32 idx = 0;
  15553. int len;
  15554. word32 tbsCertIdx = 0;
  15555. word32 sigIndex = 0;
  15556. word32 signatureOID = 0;
  15557. word32 oid = 0;
  15558. word32 issuerIdx = 0;
  15559. word32 issuerSz = 0;
  15560. #ifndef NO_SKID
  15561. int extLen = 0;
  15562. word32 extIdx = 0;
  15563. word32 extEndIdx = 0;
  15564. int extAuthKeyIdSet = 0;
  15565. #endif
  15566. int ret = 0;
  15567. word32 localIdx;
  15568. byte tag;
  15569. if (cert == NULL) {
  15570. return BAD_FUNC_ARG;
  15571. }
  15572. #ifdef WOLFSSL_SMALL_STACK
  15573. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  15574. if (sigCtx == NULL)
  15575. return MEMORY_E;
  15576. #endif
  15577. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  15578. /* Certificate SEQUENCE */
  15579. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15580. ret = ASN_PARSE_E;
  15581. if (ret == 0) {
  15582. tbsCertIdx = idx;
  15583. /* TBSCertificate SEQUENCE */
  15584. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15585. ret = ASN_PARSE_E;
  15586. }
  15587. if (ret == 0) {
  15588. sigIndex = len + idx;
  15589. if ((idx + 1) > certSz)
  15590. ret = BUFFER_E;
  15591. }
  15592. if (ret == 0) {
  15593. /* version - optional */
  15594. localIdx = idx;
  15595. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  15596. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  15597. idx++;
  15598. if (GetLength(cert, &idx, &len, certSz) < 0)
  15599. ret = ASN_PARSE_E;
  15600. idx += len;
  15601. }
  15602. }
  15603. }
  15604. if (ret == 0) {
  15605. /* serialNumber */
  15606. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  15607. ret = ASN_PARSE_E;
  15608. }
  15609. if (ret == 0) {
  15610. idx += len;
  15611. /* signature */
  15612. if (!req &&
  15613. GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  15614. ret = ASN_PARSE_E;
  15615. }
  15616. if (ret == 0) {
  15617. issuerIdx = idx;
  15618. /* issuer for cert or subject for csr */
  15619. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15620. ret = ASN_PARSE_E;
  15621. }
  15622. if (ret == 0) {
  15623. issuerSz = len + idx - issuerIdx;
  15624. }
  15625. #ifndef NO_SKID
  15626. if (!req && ret == 0) {
  15627. idx += len;
  15628. /* validity */
  15629. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15630. ret = ASN_PARSE_E;
  15631. }
  15632. if (!req && ret == 0) {
  15633. idx += len;
  15634. /* subject */
  15635. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15636. ret = ASN_PARSE_E;
  15637. }
  15638. if (ret == 0) {
  15639. idx += len;
  15640. /* subjectPublicKeyInfo */
  15641. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15642. ret = ASN_PARSE_E;
  15643. }
  15644. if (req && ret == 0) {
  15645. idx += len;
  15646. /* attributes */
  15647. if (GetASNHeader_ex(cert,
  15648. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  15649. &len, certSz, 1) < 0)
  15650. ret = ASN_PARSE_E;
  15651. }
  15652. if (!req) {
  15653. if (ret == 0) {
  15654. idx += len;
  15655. if ((idx + 1) > certSz)
  15656. ret = BUFFER_E;
  15657. }
  15658. if (ret == 0) {
  15659. /* issuerUniqueID - optional */
  15660. localIdx = idx;
  15661. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  15662. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  15663. idx++;
  15664. if (GetLength(cert, &idx, &len, certSz) < 0)
  15665. ret = ASN_PARSE_E;
  15666. idx += len;
  15667. }
  15668. }
  15669. }
  15670. if (ret == 0) {
  15671. if ((idx + 1) > certSz)
  15672. ret = BUFFER_E;
  15673. }
  15674. if (ret == 0) {
  15675. /* subjectUniqueID - optional */
  15676. localIdx = idx;
  15677. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  15678. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  15679. idx++;
  15680. if (GetLength(cert, &idx, &len, certSz) < 0)
  15681. ret = ASN_PARSE_E;
  15682. idx += len;
  15683. }
  15684. }
  15685. }
  15686. if (ret == 0) {
  15687. if ((idx + 1) > certSz)
  15688. ret = BUFFER_E;
  15689. }
  15690. /* extensions - optional */
  15691. localIdx = idx;
  15692. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  15693. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  15694. idx++;
  15695. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  15696. ret = ASN_PARSE_E;
  15697. if (ret == 0) {
  15698. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  15699. ret = ASN_PARSE_E;
  15700. }
  15701. if (ret == 0) {
  15702. extEndIdx = idx + extLen;
  15703. /* Check each extension for the ones we want. */
  15704. while (ret == 0 && idx < extEndIdx) {
  15705. if (GetSequence(cert, &idx, &len, certSz) < 0)
  15706. ret = ASN_PARSE_E;
  15707. if (ret == 0) {
  15708. extIdx = idx;
  15709. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  15710. certSz) < 0) {
  15711. ret = ASN_PARSE_E;
  15712. }
  15713. if (ret == 0) {
  15714. if ((extIdx + 1) > certSz)
  15715. ret = BUFFER_E;
  15716. }
  15717. }
  15718. if (ret == 0) {
  15719. localIdx = extIdx;
  15720. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  15721. tag == ASN_BOOLEAN) {
  15722. if (GetBoolean(cert, &extIdx, certSz) < 0)
  15723. ret = ASN_PARSE_E;
  15724. }
  15725. }
  15726. if (ret == 0) {
  15727. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  15728. ret = ASN_PARSE_E;
  15729. }
  15730. if (ret == 0) {
  15731. switch (oid) {
  15732. case AUTH_KEY_OID:
  15733. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  15734. ret = ASN_PARSE_E;
  15735. if (ret == 0 && (extIdx + 1) >= certSz)
  15736. ret = BUFFER_E;
  15737. if (ret == 0 &&
  15738. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  15739. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  15740. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  15741. ret = ASN_PARSE_E;
  15742. if (ret == 0) {
  15743. extAuthKeyIdSet = 1;
  15744. /* Get the hash or hash of the hash if wrong
  15745. * size. */
  15746. ret = GetHashId(cert + extIdx, extLen,
  15747. hash);
  15748. }
  15749. }
  15750. break;
  15751. default:
  15752. break;
  15753. }
  15754. }
  15755. idx += len;
  15756. }
  15757. }
  15758. }
  15759. }
  15760. else if (ret == 0) {
  15761. idx += len;
  15762. }
  15763. if (ret == 0 && pubKey == NULL) {
  15764. if (extAuthKeyIdSet)
  15765. ca = GetCA(cm, hash);
  15766. if (ca == NULL) {
  15767. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  15768. if (ret == 0)
  15769. ca = GetCAByName(cm, hash);
  15770. }
  15771. }
  15772. #else
  15773. if (ret == 0 && pubKey == NULL) {
  15774. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  15775. if (ret == 0)
  15776. ca = GetCA(cm, hash);
  15777. }
  15778. #endif /* !NO_SKID */
  15779. if (ca == NULL && pubKey == NULL)
  15780. ret = ASN_NO_SIGNER_E;
  15781. if (ret == 0) {
  15782. idx = sigIndex;
  15783. /* signatureAlgorithm */
  15784. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  15785. ret = ASN_PARSE_E;
  15786. /* In CSR signature data is not present in body */
  15787. if (req)
  15788. signatureOID = oid;
  15789. }
  15790. if (ret == 0) {
  15791. if (oid != signatureOID)
  15792. ret = ASN_SIG_OID_E;
  15793. }
  15794. if (ret == 0) {
  15795. /* signatureValue */
  15796. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  15797. ret = ASN_PARSE_E;
  15798. }
  15799. if (ret == 0) {
  15800. if (pubKey != NULL) {
  15801. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  15802. sigIndex - tbsCertIdx,
  15803. pubKey, pubKeySz, pubKeyOID,
  15804. cert + idx, len, signatureOID, NULL);
  15805. }
  15806. else {
  15807. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  15808. sigIndex - tbsCertIdx,
  15809. ca->publicKey, ca->pubKeySize, ca->keyOID,
  15810. cert + idx, len, signatureOID, NULL);
  15811. }
  15812. if (ret != 0) {
  15813. WOLFSSL_MSG("Confirm signature failed");
  15814. }
  15815. }
  15816. FreeSignatureCtx(sigCtx);
  15817. #ifdef WOLFSSL_SMALL_STACK
  15818. if (sigCtx != NULL)
  15819. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  15820. #endif
  15821. return ret;
  15822. #else /* WOLFSSL_ASN_TEMPLATE */
  15823. /* X509 ASN.1 template longer than Certificate Request template. */
  15824. DECL_ASNGETDATA(dataASN, x509CertASN_Length);
  15825. #ifndef WOLFSSL_SMALL_STACK
  15826. SignatureCtx sigCtx[1];
  15827. #else
  15828. SignatureCtx* sigCtx = NULL;
  15829. #endif
  15830. byte hash[KEYID_SIZE];
  15831. Signer* ca = NULL;
  15832. int ret = 0;
  15833. word32 idx = 0;
  15834. #ifndef NO_SKID
  15835. int extAuthKeyIdSet = 0;
  15836. #endif
  15837. const byte* tbs = NULL;
  15838. word32 tbsSz = 0;
  15839. const byte* sig = NULL;
  15840. word32 sigSz = 0;
  15841. word32 sigOID = 0;
  15842. const byte* caName = NULL;
  15843. word32 caNameLen = 0;
  15844. (void)req;
  15845. (void)heap;
  15846. if (cert == NULL) {
  15847. ret = BAD_FUNC_ARG;
  15848. }
  15849. ALLOC_ASNGETDATA(dataASN, x509CertASN_Length, ret, heap);
  15850. #ifdef WOLFSSL_SMALL_STACK
  15851. if (ret == 0) {
  15852. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap,
  15853. DYNAMIC_TYPE_SIGNATURE);
  15854. if (sigCtx == NULL) {
  15855. ret = MEMORY_E;
  15856. }
  15857. }
  15858. #endif
  15859. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  15860. if ((ret == 0) && (!req)) {
  15861. /* Clear dynamic data for certificate items. */
  15862. XMEMSET(dataASN, 0, sizeof(ASNGetData) * x509CertASN_Length);
  15863. /* Set OID types expected for signature and public key. */
  15864. GetASN_OID(&dataASN[6], oidSigType);
  15865. GetASN_OID(&dataASN[17], oidKeyType);
  15866. GetASN_OID(&dataASN[19], oidCurveType);
  15867. GetASN_OID(&dataASN[25], oidSigType);
  15868. /* Parse certificate. */
  15869. ret = GetASN_Items(x509CertASN, dataASN, x509CertASN_Length, 1, cert,
  15870. &idx, certSz);
  15871. /* Check signature OIDs match. */
  15872. if ((ret == 0) && dataASN[6].data.oid.sum != dataASN[25].data.oid.sum) {
  15873. ret = ASN_SIG_OID_E;
  15874. }
  15875. /* Store the data for verification in the certificate. */
  15876. if (ret == 0) {
  15877. tbs = GetASNItem_Addr(dataASN[1], cert);
  15878. tbsSz = GetASNItem_Length(dataASN[1], cert);
  15879. caName = GetASNItem_Addr(dataASN[8], cert);
  15880. caNameLen = GetASNItem_Length(dataASN[8], cert);
  15881. sigOID = dataASN[25].data.oid.sum;
  15882. GetASN_GetConstRef(&dataASN[27], &sig, &sigSz);
  15883. }
  15884. }
  15885. else if (ret == 0) {
  15886. #ifndef WOLFSSL_CERT_REQ
  15887. ret = NOT_COMPILED_IN;
  15888. #else
  15889. /* Clear dynamic data for certificate request items. */
  15890. XMEMSET(dataASN, 0, sizeof(ASNGetData) * certReqASN_Length);
  15891. /* Set OID types expected for signature and public key. */
  15892. GetASN_OID(&dataASN[6], oidKeyType);
  15893. GetASN_OID(&dataASN[8], oidCurveType);
  15894. GetASN_OID(&dataASN[13], oidSigType);
  15895. /* Parse certificate request. */
  15896. ret = GetASN_Items(certReqASN, dataASN, certReqASN_Length, 1, cert,
  15897. &idx, certSz);
  15898. if (ret == 0) {
  15899. /* Store the data for verification in the certificate. */
  15900. tbs = GetASNItem_Addr(dataASN[1], cert);
  15901. tbsSz = GetASNItem_Length(dataASN[1], cert);
  15902. caName = GetASNItem_Addr(dataASN[3], cert);
  15903. caNameLen = GetASNItem_Length(dataASN[3], cert);
  15904. sigOID = dataASN[13].data.oid.sum;
  15905. GetASN_GetConstRef(&dataASN[15], &sig, &sigSz);
  15906. }
  15907. #endif
  15908. }
  15909. /* If no public passed, then find the CA. */
  15910. if ((ret == 0) && (pubKey == NULL)) {
  15911. #ifndef NO_SKID
  15912. /* Find the AKI extension in list of extensions and get hash. */
  15913. if ((ret == 0) && (!req) && (dataASN[23].data.ref.data != NULL)) {
  15914. /* TODO: test case */
  15915. ret = GetAKIHash(dataASN[23].data.ref.data,
  15916. dataASN[23].data.ref.length, hash,
  15917. &extAuthKeyIdSet, heap);
  15918. }
  15919. /* Get the CA by hash one was found. */
  15920. if (extAuthKeyIdSet) {
  15921. ca = GetCA(cm, hash);
  15922. }
  15923. if (ca == NULL)
  15924. #endif
  15925. {
  15926. /* Try hash of issuer name. */
  15927. ret = CalcHashId(caName, caNameLen, hash);
  15928. if (ret == 0) {
  15929. ca = GetCAByName(cm, hash);
  15930. }
  15931. }
  15932. if (ca != NULL) {
  15933. /* Extract public key information. */
  15934. pubKey = ca->publicKey;
  15935. pubKeySz = ca->pubKeySize;
  15936. pubKeyOID = ca->keyOID;
  15937. }
  15938. else {
  15939. /* No public key to verify with. */
  15940. ret = ASN_NO_SIGNER_E;
  15941. }
  15942. }
  15943. if (ret == 0) {
  15944. /* Check signature. */
  15945. ret = ConfirmSignature(sigCtx, tbs, tbsSz, pubKey, pubKeySz, pubKeyOID,
  15946. sig, sigSz, sigOID, NULL);
  15947. if (ret != 0) {
  15948. WOLFSSL_MSG("Confirm signature failed");
  15949. }
  15950. }
  15951. FreeSignatureCtx(sigCtx);
  15952. #ifdef WOLFSSL_SMALL_STACK
  15953. if (sigCtx != NULL)
  15954. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  15955. #endif
  15956. FREE_ASNGETDATA(dataASN, heap);
  15957. return ret;
  15958. #endif /* WOLFSSL_ASN_TEMPLATE */
  15959. }
  15960. #ifdef OPENSSL_EXTRA
  15961. /* Call CheckCertSignature_ex using a public key buffer for verification
  15962. */
  15963. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  15964. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  15965. {
  15966. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  15967. pubKey, pubKeySz, pubKeyOID, 0);
  15968. }
  15969. #ifdef WOLFSSL_CERT_REQ
  15970. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  15971. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  15972. {
  15973. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  15974. pubKey, pubKeySz, pubKeyOID, 1);
  15975. }
  15976. #endif /* WOLFSSL_CERT_REQ */
  15977. #endif /* OPENSSL_EXTRA */
  15978. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  15979. /* Call CheckCertSignature_ex using a certificate manager (cm)
  15980. */
  15981. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  15982. {
  15983. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  15984. }
  15985. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  15986. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  15987. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  15988. {
  15989. int ret = 0;
  15990. int checkPathLen = 0;
  15991. int decrementMaxPathLen = 0;
  15992. #ifndef WOLFSSL_ASN_TEMPLATE
  15993. word32 confirmOID = 0;
  15994. #ifdef WOLFSSL_CERT_REQ
  15995. int len = 0;
  15996. #endif
  15997. #endif
  15998. #if defined(WOLFSSL_RENESAS_TSIP)
  15999. int idx = 0;
  16000. #endif
  16001. byte* tsip_encRsaKeyIdx;
  16002. if (cert == NULL) {
  16003. return BAD_FUNC_ARG;
  16004. }
  16005. #ifdef WOLFSSL_CERT_REQ
  16006. if (type == CERTREQ_TYPE)
  16007. cert->isCSR = 1;
  16008. #endif
  16009. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  16010. #ifndef WOLFSSL_ASN_TEMPLATE
  16011. cert->badDate = 0;
  16012. cert->criticalExt = 0;
  16013. if ((ret = DecodeToKey(cert, verify)) < 0) {
  16014. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  16015. cert->badDate = ret;
  16016. else
  16017. return ret;
  16018. }
  16019. WOLFSSL_MSG("Parsed Past Key");
  16020. #ifdef WOLFSSL_CERT_REQ
  16021. /* Read attributes */
  16022. if (cert->isCSR) {
  16023. if (GetASNHeader_ex(cert->source,
  16024. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  16025. &len, cert->maxIdx, 1) < 0) {
  16026. WOLFSSL_MSG("GetASNHeader_ex error");
  16027. return ASN_PARSE_E;
  16028. }
  16029. if (len) {
  16030. word32 attrMaxIdx = cert->srcIdx + len;
  16031. word32 oid;
  16032. byte tag;
  16033. if (attrMaxIdx > cert->maxIdx) {
  16034. WOLFSSL_MSG("Attribute length greater than CSR length");
  16035. return ASN_PARSE_E;
  16036. }
  16037. while (cert->srcIdx < attrMaxIdx) {
  16038. /* Attributes have the structure:
  16039. * SEQ -> OID -> SET -> ATTRIBUTE */
  16040. if (GetSequence(cert->source, &cert->srcIdx, &len,
  16041. attrMaxIdx) < 0) {
  16042. WOLFSSL_MSG("attr GetSequence error");
  16043. return ASN_PARSE_E;
  16044. }
  16045. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  16046. oidCsrAttrType, attrMaxIdx) < 0) {
  16047. WOLFSSL_MSG("attr GetObjectId error");
  16048. return ASN_PARSE_E;
  16049. }
  16050. if (GetSet(cert->source, &cert->srcIdx, &len,
  16051. attrMaxIdx) < 0) {
  16052. WOLFSSL_MSG("attr GetSet error");
  16053. return ASN_PARSE_E;
  16054. }
  16055. switch (oid) {
  16056. case PKCS9_CONTENT_TYPE_OID:
  16057. if (GetHeader(cert->source, &tag,
  16058. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  16059. WOLFSSL_MSG("attr GetHeader error");
  16060. return ASN_PARSE_E;
  16061. }
  16062. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16063. tag != ASN_IA5_STRING) {
  16064. WOLFSSL_MSG("Unsupported attribute value format");
  16065. return ASN_PARSE_E;
  16066. }
  16067. cert->contentType = (char*)cert->source + cert->srcIdx;
  16068. cert->contentTypeLen = len;
  16069. cert->srcIdx += len;
  16070. break;
  16071. case CHALLENGE_PASSWORD_OID:
  16072. if (GetHeader(cert->source, &tag,
  16073. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  16074. WOLFSSL_MSG("attr GetHeader error");
  16075. return ASN_PARSE_E;
  16076. }
  16077. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16078. tag != ASN_IA5_STRING) {
  16079. WOLFSSL_MSG("Unsupported attribute value format");
  16080. return ASN_PARSE_E;
  16081. }
  16082. cert->cPwd = (char*)cert->source + cert->srcIdx;
  16083. cert->cPwdLen = len;
  16084. cert->srcIdx += len;
  16085. break;
  16086. case SERIAL_NUMBER_OID:
  16087. if (GetHeader(cert->source, &tag,
  16088. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  16089. WOLFSSL_MSG("attr GetHeader error");
  16090. return ASN_PARSE_E;
  16091. }
  16092. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  16093. tag != ASN_IA5_STRING) {
  16094. WOLFSSL_MSG("Unsupported attribute value format");
  16095. return ASN_PARSE_E;
  16096. }
  16097. cert->sNum = (char*)cert->source + cert->srcIdx;
  16098. cert->sNumLen = len;
  16099. cert->srcIdx += len;
  16100. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  16101. XMEMCPY(cert->serial, cert->sNum, cert->sNumLen);
  16102. cert->serialSz = cert->sNumLen;
  16103. }
  16104. break;
  16105. case EXTENSION_REQUEST_OID:
  16106. /* save extensions */
  16107. cert->extensions = &cert->source[cert->srcIdx];
  16108. cert->extensionsSz = len;
  16109. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  16110. if ((ret = DecodeCertExtensions(cert)) < 0) {
  16111. if (ret == ASN_CRIT_EXT_E)
  16112. cert->criticalExt = ret;
  16113. else
  16114. return ret;
  16115. }
  16116. cert->srcIdx += len;
  16117. break;
  16118. default:
  16119. WOLFSSL_MSG("Unsupported attribute type");
  16120. return ASN_PARSE_E;
  16121. }
  16122. }
  16123. }
  16124. }
  16125. #endif
  16126. if (cert->srcIdx < cert->sigIndex) {
  16127. #ifndef ALLOW_V1_EXTENSIONS
  16128. if (cert->version < 2) {
  16129. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  16130. return ASN_VERSION_E;
  16131. }
  16132. #endif
  16133. /* save extensions */
  16134. cert->extensions = &cert->source[cert->srcIdx];
  16135. cert->extensionsSz = cert->sigIndex - cert->srcIdx;
  16136. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  16137. if ((ret = DecodeCertExtensions(cert)) < 0) {
  16138. if (ret == ASN_CRIT_EXT_E)
  16139. cert->criticalExt = ret;
  16140. else
  16141. return ret;
  16142. }
  16143. #ifdef HAVE_OCSP
  16144. if (verify == VERIFY_OCSP_CERT) {
  16145. /* trust for the lifetime of the responder's cert*/
  16146. if (cert->ocspNoCheckSet)
  16147. verify = VERIFY;
  16148. else
  16149. verify = VERIFY_OCSP;
  16150. }
  16151. #endif
  16152. /* advance past extensions */
  16153. cert->srcIdx = cert->sigIndex;
  16154. }
  16155. if ((ret = GetAlgoId(cert->source, &cert->srcIdx,
  16156. #ifdef WOLFSSL_CERT_REQ
  16157. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  16158. #else
  16159. &confirmOID,
  16160. #endif
  16161. oidSigType, cert->maxIdx)) < 0)
  16162. return ret;
  16163. if ((ret = GetSignature(cert)) < 0)
  16164. return ret;
  16165. if (confirmOID != cert->signatureOID
  16166. #ifdef WOLFSSL_CERT_REQ
  16167. && !cert->isCSR
  16168. #endif
  16169. )
  16170. return ASN_SIG_OID_E;
  16171. #else
  16172. #ifdef WOLFSSL_CERT_REQ
  16173. if (cert->isCSR) {
  16174. ret = DecodeCertReq(cert, &cert->criticalExt);
  16175. if (ret < 0) {
  16176. return ret;
  16177. }
  16178. }
  16179. else
  16180. #endif
  16181. {
  16182. ret = DecodeCert(cert, verify, &cert->criticalExt);
  16183. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  16184. cert->badDate = ret;
  16185. else if (ret < 0)
  16186. return ret;
  16187. }
  16188. #endif
  16189. #ifndef NO_SKID
  16190. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  16191. cert->pubKeySize > 0) {
  16192. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  16193. cert->extSubjKeyId);
  16194. if (ret != 0)
  16195. return ret;
  16196. }
  16197. #endif /* !NO_SKID */
  16198. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  16199. type != TRUSTED_PEER_TYPE)) {
  16200. cert->ca = NULL;
  16201. #ifndef NO_SKID
  16202. if (cert->extAuthKeyIdSet) {
  16203. cert->ca = GetCA(cm, cert->extAuthKeyId);
  16204. }
  16205. if (cert->ca == NULL && cert->extSubjKeyIdSet
  16206. && verify != VERIFY_OCSP) {
  16207. cert->ca = GetCA(cm, cert->extSubjKeyId);
  16208. }
  16209. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  16210. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  16211. cert->ca = NULL;
  16212. }
  16213. if (cert->ca == NULL) {
  16214. cert->ca = GetCAByName(cm, cert->issuerHash);
  16215. /* If AKID is available then this CA doesn't have the public
  16216. * key required */
  16217. if (cert->ca && cert->extAuthKeyIdSet) {
  16218. WOLFSSL_MSG("CA SKID doesn't match AKID");
  16219. cert->ca = NULL;
  16220. }
  16221. }
  16222. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  16223. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  16224. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  16225. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  16226. if (cert->ca) {
  16227. ret = 0; /* success */
  16228. goto exit_pcr;
  16229. }
  16230. }
  16231. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  16232. #else
  16233. cert->ca = GetCA(cm, cert->issuerHash);
  16234. #endif /* !NO_SKID */
  16235. if (cert->ca) {
  16236. WOLFSSL_MSG("CA found");
  16237. }
  16238. }
  16239. if (cert->selfSigned) {
  16240. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  16241. } else {
  16242. /* RFC 5280 Section 4.2.1.9:
  16243. *
  16244. * load/receive check
  16245. *
  16246. * 1) Is CA boolean set?
  16247. * No - SKIP CHECK
  16248. * Yes - Check key usage
  16249. * 2) Is Key usage extension present?
  16250. * No - goto 3
  16251. * Yes - check keyCertSign assertion
  16252. * 2.a) Is keyCertSign asserted?
  16253. * No - goto 4
  16254. * Yes - goto 3
  16255. * 3) Is pathLen set?
  16256. * No - goto 4
  16257. * Yes - check pathLen against maxPathLen.
  16258. * 3.a) Is pathLen less than maxPathLen?
  16259. * No - goto 4
  16260. * Yes - set maxPathLen to pathLen and EXIT
  16261. * 4) Is maxPathLen > 0?
  16262. * Yes - Reduce by 1
  16263. * No - ERROR
  16264. */
  16265. if (cert->ca && cert->pathLengthSet) {
  16266. cert->maxPathLen = cert->pathLength;
  16267. if (cert->isCA) {
  16268. WOLFSSL_MSG("\tCA boolean set");
  16269. if (cert->extKeyUsageSet) {
  16270. WOLFSSL_MSG("\tExtension Key Usage Set");
  16271. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  16272. checkPathLen = 1;
  16273. } else {
  16274. decrementMaxPathLen = 1;
  16275. }
  16276. } else {
  16277. checkPathLen = 1;
  16278. } /* !cert->ca check */
  16279. } /* cert is not a CA (assuming entity cert) */
  16280. if (checkPathLen && cert->pathLengthSet) {
  16281. if (cert->pathLength < cert->ca->maxPathLen) {
  16282. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  16283. cert->maxPathLen = cert->pathLength;
  16284. } else {
  16285. decrementMaxPathLen = 1;
  16286. }
  16287. }
  16288. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  16289. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  16290. cert->maxPathLen = cert->ca->maxPathLen - 1;
  16291. if (verify != NO_VERIFY && type != CA_TYPE &&
  16292. type != TRUSTED_PEER_TYPE) {
  16293. WOLFSSL_MSG("\tmaxPathLen status: OK");
  16294. }
  16295. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  16296. cert->maxPathLen = 0;
  16297. if (verify != NO_VERIFY && type != CA_TYPE &&
  16298. type != TRUSTED_PEER_TYPE) {
  16299. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  16300. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  16301. return ASN_PATHLEN_INV_E;
  16302. }
  16303. }
  16304. } else if (cert->ca && cert->isCA) {
  16305. /* case where cert->pathLength extension is not set */
  16306. if (cert->ca->maxPathLen > 0) {
  16307. cert->maxPathLen = cert->ca->maxPathLen - 1;
  16308. } else {
  16309. cert->maxPathLen = 0;
  16310. if (verify != NO_VERIFY && type != CA_TYPE &&
  16311. type != TRUSTED_PEER_TYPE) {
  16312. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  16313. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  16314. return ASN_PATHLEN_INV_E;
  16315. }
  16316. }
  16317. }
  16318. }
  16319. #ifdef HAVE_OCSP
  16320. if (verify != NO_VERIFY && type != CA_TYPE &&
  16321. type != TRUSTED_PEER_TYPE) {
  16322. if (cert->ca) {
  16323. /* Need the CA's public key hash for OCSP */
  16324. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  16325. KEYID_SIZE);
  16326. }
  16327. }
  16328. #endif /* HAVE_OCSP */
  16329. }
  16330. #if defined(WOLFSSL_RENESAS_TSIP)
  16331. /* prepare for TSIP TLS cert verification API use */
  16332. if (cert->keyOID == RSAk) {
  16333. /* to call TSIP API, it needs keys position info in bytes */
  16334. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  16335. cert->pubKeySize,
  16336. &cert->sigCtx.pubkey_n_start,
  16337. &cert->sigCtx.pubkey_n_len,
  16338. &cert->sigCtx.pubkey_e_start,
  16339. &cert->sigCtx.pubkey_e_len)) != 0) {
  16340. WOLFSSL_MSG("Decoding index from cert failed.");
  16341. return ret;
  16342. }
  16343. cert->sigCtx.certBegin = cert->certBegin;
  16344. }
  16345. /* check if we can use TSIP for cert verification */
  16346. /* if the ca is verified as tsip root ca. */
  16347. /* TSIP can only handle 2048 bits(256 byte) key. */
  16348. if (cert->ca && tsip_checkCA(cert->ca->cm_idx) != 0 &&
  16349. cert->sigCtx.pubkey_n_len == 256) {
  16350. /* assign memory to encrypted tsip Rsa key index */
  16351. if (!cert->tsip_encRsaKeyIdx)
  16352. cert->tsip_encRsaKeyIdx =
  16353. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  16354. cert->heap, DYNAMIC_TYPE_RSA);
  16355. if (cert->tsip_encRsaKeyIdx == NULL)
  16356. return MEMORY_E;
  16357. } else {
  16358. if (cert->ca) {
  16359. /* TSIP isn't usable */
  16360. if (tsip_checkCA(cert->ca->cm_idx) == 0)
  16361. WOLFSSL_MSG("TSIP isn't usable because the ca isn't verified "
  16362. "by TSIP.");
  16363. else if (cert->sigCtx.pubkey_n_len != 256)
  16364. WOLFSSL_MSG("TSIP isn't usable because the ca isn't signed by "
  16365. "RSA 2048.");
  16366. else
  16367. WOLFSSL_MSG("TSIP isn't usable");
  16368. }
  16369. cert->tsip_encRsaKeyIdx = NULL;
  16370. }
  16371. tsip_encRsaKeyIdx = cert->tsip_encRsaKeyIdx;
  16372. #else
  16373. tsip_encRsaKeyIdx = NULL;
  16374. #endif
  16375. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  16376. if (cert->ca) {
  16377. if (verify == VERIFY || verify == VERIFY_OCSP ||
  16378. verify == VERIFY_SKIP_DATE) {
  16379. /* try to confirm/verify signature */
  16380. if ((ret = ConfirmSignature(&cert->sigCtx,
  16381. cert->source + cert->certBegin,
  16382. cert->sigIndex - cert->certBegin,
  16383. cert->ca->publicKey, cert->ca->pubKeySize,
  16384. cert->ca->keyOID, cert->signature,
  16385. cert->sigLength, cert->signatureOID,
  16386. tsip_encRsaKeyIdx)) != 0) {
  16387. if (ret != WC_PENDING_E) {
  16388. WOLFSSL_MSG("Confirm signature failed");
  16389. }
  16390. return ret;
  16391. }
  16392. }
  16393. #ifndef IGNORE_NAME_CONSTRAINTS
  16394. if (verify == VERIFY || verify == VERIFY_OCSP ||
  16395. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  16396. /* check that this cert's name is permitted by the signer's
  16397. * name constraints */
  16398. if (!ConfirmNameConstraints(cert->ca, cert)) {
  16399. WOLFSSL_MSG("Confirm name constraint failed");
  16400. return ASN_NAME_INVALID_E;
  16401. }
  16402. }
  16403. #endif /* IGNORE_NAME_CONSTRAINTS */
  16404. }
  16405. else {
  16406. /* no signer */
  16407. WOLFSSL_MSG("No CA signer to verify with");
  16408. return ASN_NO_SIGNER_E;
  16409. }
  16410. }
  16411. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  16412. exit_pcr:
  16413. #endif
  16414. if (cert->badDate != 0) {
  16415. if (verify != VERIFY_SKIP_DATE) {
  16416. return cert->badDate;
  16417. }
  16418. WOLFSSL_MSG("Date error: Verify option is skipping");
  16419. }
  16420. if (cert->criticalExt != 0)
  16421. return cert->criticalExt;
  16422. return ret;
  16423. }
  16424. /* Create and init an new signer */
  16425. Signer* MakeSigner(void* heap)
  16426. {
  16427. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  16428. DYNAMIC_TYPE_SIGNER);
  16429. if (signer) {
  16430. XMEMSET(signer, 0, sizeof(Signer));
  16431. }
  16432. (void)heap;
  16433. return signer;
  16434. }
  16435. /* Free an individual signer.
  16436. *
  16437. * Used by Certificate Manager.
  16438. *
  16439. * @param [in, out] signer On in, signer object.
  16440. * On out, pointer is no longer valid.
  16441. * @param [in] heap Dynamic memory hint.
  16442. */
  16443. void FreeSigner(Signer* signer, void* heap)
  16444. {
  16445. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  16446. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  16447. #ifndef IGNORE_NAME_CONSTRAINTS
  16448. if (signer->permittedNames)
  16449. FreeNameSubtrees(signer->permittedNames, heap);
  16450. if (signer->excludedNames)
  16451. FreeNameSubtrees(signer->excludedNames, heap);
  16452. #endif
  16453. #ifdef WOLFSSL_SIGNER_DER_CERT
  16454. FreeDer(&signer->derCert);
  16455. #endif
  16456. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  16457. (void)heap;
  16458. }
  16459. /* Free the whole singer table with number of rows.
  16460. *
  16461. * Each table entry is a linked list of signers.
  16462. * Used by Certificate Manager.
  16463. *
  16464. * @param [in, out] table Array of signer objects.
  16465. * @param [in] rows Number of entries in table.
  16466. * @param [in] heap Dynamic memory hint.
  16467. */
  16468. void FreeSignerTable(Signer** table, int rows, void* heap)
  16469. {
  16470. int i;
  16471. for (i = 0; i < rows; i++) {
  16472. Signer* signer = table[i];
  16473. while (signer) {
  16474. Signer* next = signer->next;
  16475. FreeSigner(signer, heap);
  16476. signer = next;
  16477. }
  16478. table[i] = NULL;
  16479. }
  16480. }
  16481. #ifdef WOLFSSL_TRUST_PEER_CERT
  16482. /* Free an individual trusted peer cert.
  16483. *
  16484. * @param [in, out] tp Trusted peer certificate object.
  16485. * @param [in] heap Dynamic memory hint.
  16486. */
  16487. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  16488. {
  16489. if (tp == NULL) {
  16490. return;
  16491. }
  16492. if (tp->name) {
  16493. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  16494. }
  16495. if (tp->sig) {
  16496. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  16497. }
  16498. #ifndef IGNORE_NAME_CONSTRAINTS
  16499. if (tp->permittedNames)
  16500. FreeNameSubtrees(tp->permittedNames, heap);
  16501. if (tp->excludedNames)
  16502. FreeNameSubtrees(tp->excludedNames, heap);
  16503. #endif
  16504. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  16505. (void)heap;
  16506. }
  16507. /* Free the whole Trusted Peer linked list.
  16508. *
  16509. * Each table entry is a linked list of trusted peer certificates.
  16510. * Used by Certificate Manager.
  16511. *
  16512. * @param [in, out] table Array of trusted peer certificate objects.
  16513. * @param [in] rows Number of entries in table.
  16514. * @param [in] heap Dynamic memory hint.
  16515. */
  16516. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  16517. {
  16518. int i;
  16519. for (i = 0; i < rows; i++) {
  16520. TrustedPeerCert* tp = table[i];
  16521. while (tp) {
  16522. TrustedPeerCert* next = tp->next;
  16523. FreeTrustedPeer(tp, heap);
  16524. tp = next;
  16525. }
  16526. table[i] = NULL;
  16527. }
  16528. }
  16529. #endif /* WOLFSSL_TRUST_PEER_CERT */
  16530. int SetMyVersion(word32 version, byte* output, int header)
  16531. {
  16532. int i = 0;
  16533. if (output == NULL)
  16534. return BAD_FUNC_ARG;
  16535. if (header) {
  16536. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  16537. output[i++] = 3;
  16538. }
  16539. output[i++] = ASN_INTEGER;
  16540. output[i++] = 0x01;
  16541. output[i++] = (byte)version;
  16542. return i;
  16543. }
  16544. #if !defined(WOLFSSL_ASN_TEMPLATE) || defined(HAVE_PKCS7)
  16545. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  16546. word32 outputSz, int maxSnSz)
  16547. {
  16548. int i;
  16549. int snSzInt = (int)snSz;
  16550. if (sn == NULL || output == NULL || snSzInt < 0)
  16551. return BAD_FUNC_ARG;
  16552. /* remove leading zeros */
  16553. while (snSzInt > 0 && sn[0] == 0) {
  16554. snSzInt--;
  16555. sn++;
  16556. }
  16557. /* RFC 5280 - 4.1.2.2:
  16558. * Serial numbers must be a positive value (and not zero) */
  16559. if (snSzInt == 0)
  16560. return BAD_FUNC_ARG;
  16561. if (sn[0] & 0x80)
  16562. maxSnSz--;
  16563. /* truncate if input is too long */
  16564. if (snSzInt > maxSnSz)
  16565. snSzInt = maxSnSz;
  16566. i = SetASNInt(snSzInt, sn[0], NULL);
  16567. /* truncate if input is too long */
  16568. if (snSzInt > (int)outputSz - i)
  16569. snSzInt = (int)outputSz - i;
  16570. /* sanity check number of bytes to copy */
  16571. if (snSzInt <= 0) {
  16572. return BUFFER_E;
  16573. }
  16574. /* write out ASN.1 Integer */
  16575. (void)SetASNInt(snSzInt, sn[0], output);
  16576. XMEMCPY(output + i, sn, snSzInt);
  16577. /* compute final length */
  16578. i += snSzInt;
  16579. return i;
  16580. }
  16581. #endif /* !WOLFSSL_ASN_TEMPLATE */
  16582. #endif /* !NO_CERTS */
  16583. #ifndef WOLFSSL_ASN_TEMPLATE
  16584. int GetSerialNumber(const byte* input, word32* inOutIdx,
  16585. byte* serial, int* serialSz, word32 maxIdx)
  16586. {
  16587. int result = 0;
  16588. int ret;
  16589. WOLFSSL_ENTER("GetSerialNumber");
  16590. if (serial == NULL || input == NULL || serialSz == NULL) {
  16591. return BAD_FUNC_ARG;
  16592. }
  16593. /* First byte is ASN type */
  16594. if ((*inOutIdx+1) > maxIdx) {
  16595. WOLFSSL_MSG("Bad idx first");
  16596. return BUFFER_E;
  16597. }
  16598. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  16599. if (ret != 0)
  16600. return ret;
  16601. if (*serialSz > EXTERNAL_SERIAL_SIZE || *serialSz <= 0) {
  16602. WOLFSSL_MSG("Serial size bad");
  16603. return ASN_PARSE_E;
  16604. }
  16605. /* return serial */
  16606. XMEMCPY(serial, &input[*inOutIdx], (size_t)*serialSz);
  16607. *inOutIdx += *serialSz;
  16608. return result;
  16609. }
  16610. #endif
  16611. #ifndef NO_CERTS
  16612. /* TODO: consider moving PEM code out to a different file. */
  16613. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  16614. {
  16615. int ret = BAD_FUNC_ARG;
  16616. if (pDer) {
  16617. int dynType = 0;
  16618. DerBuffer* der;
  16619. /* Determine dynamic type */
  16620. switch (type) {
  16621. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  16622. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  16623. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  16624. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  16625. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  16626. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  16627. default: dynType = DYNAMIC_TYPE_KEY; break;
  16628. }
  16629. /* Setup new buffer */
  16630. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  16631. if (*pDer == NULL) {
  16632. return MEMORY_E;
  16633. }
  16634. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  16635. der = *pDer;
  16636. der->type = type;
  16637. der->dynType = dynType; /* Cache this for FreeDer */
  16638. der->heap = heap;
  16639. der->buffer = (byte*)der + sizeof(DerBuffer);
  16640. der->length = length;
  16641. ret = 0; /* Success */
  16642. }
  16643. return ret;
  16644. }
  16645. void FreeDer(DerBuffer** pDer)
  16646. {
  16647. if (pDer && *pDer)
  16648. {
  16649. DerBuffer* der = (DerBuffer*)*pDer;
  16650. /* ForceZero private keys */
  16651. if (der->type == PRIVATEKEY_TYPE && der->buffer != NULL) {
  16652. ForceZero(der->buffer, der->length);
  16653. }
  16654. der->buffer = NULL;
  16655. der->length = 0;
  16656. XFREE(der, der->heap, der->dynType);
  16657. *pDer = NULL;
  16658. }
  16659. }
  16660. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  16661. {
  16662. return AllocDer(pDer, length, type, heap);
  16663. }
  16664. void wc_FreeDer(DerBuffer** pDer)
  16665. {
  16666. FreeDer(pDer);
  16667. }
  16668. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  16669. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  16670. updated to reflect maximum length and pem_struct_min_sz
  16671. to reflect minimum size */
  16672. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  16673. wcchar END_CERT = "-----END CERTIFICATE-----";
  16674. #ifdef WOLFSSL_CERT_REQ
  16675. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  16676. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  16677. #endif
  16678. #ifndef NO_DH
  16679. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  16680. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  16681. wcchar BEGIN_X942_PARAM = "-----BEGIN X9.42 DH PARAMETERS-----";
  16682. wcchar END_X942_PARAM = "-----END X9.42 DH PARAMETERS-----";
  16683. #endif
  16684. #ifndef NO_DSA
  16685. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  16686. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  16687. #endif
  16688. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  16689. wcchar END_X509_CRL = "-----END X509 CRL-----";
  16690. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  16691. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  16692. wcchar BEGIN_RSA_PUB = "-----BEGIN RSA PUBLIC KEY-----";
  16693. wcchar END_RSA_PUB = "-----END RSA PUBLIC KEY-----";
  16694. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  16695. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  16696. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  16697. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  16698. #ifdef HAVE_ECC
  16699. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  16700. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  16701. #endif
  16702. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  16703. !defined(NO_DSA)
  16704. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  16705. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  16706. #endif
  16707. #ifdef OPENSSL_EXTRA
  16708. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  16709. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  16710. const char END_PRIV_KEY_PREFIX[] = "-----END";
  16711. #endif
  16712. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  16713. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  16714. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  16715. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  16716. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  16717. #endif
  16718. #if defined(HAVE_LIBOQS)
  16719. wcchar BEGIN_FALCON_LEVEL1_PRIV = "-----BEGIN FALCON_LEVEL1 PRIVATE KEY-----";
  16720. wcchar END_FALCON_LEVEL1_PRIV = "-----END FALCON_LEVEL1 PRIVATE KEY-----";
  16721. wcchar BEGIN_FALCON_LEVEL5_PRIV = "-----BEGIN FALCON_LEVEL5 PRIVATE KEY-----";
  16722. wcchar END_FALCON_LEVEL5_PRIV = "-----END FALCON_LEVEL5 PRIVATE KEY-----";
  16723. #endif
  16724. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  16725. "-----END X509 CRL-----");
  16726. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  16727. const char* endOfLine)
  16728. {
  16729. /* eat end of line characters */
  16730. while (line < endOfLine &&
  16731. (line[0] == '\r' || line[0] == '\n')) {
  16732. line++;
  16733. }
  16734. return line;
  16735. }
  16736. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  16737. {
  16738. int ret = BAD_FUNC_ARG;
  16739. switch (type) {
  16740. case CA_TYPE: /* same as below */
  16741. case TRUSTED_PEER_TYPE:
  16742. case CERT_TYPE:
  16743. if (header) *header = BEGIN_CERT;
  16744. if (footer) *footer = END_CERT;
  16745. ret = 0;
  16746. break;
  16747. case CRL_TYPE:
  16748. if (header) *header = BEGIN_X509_CRL;
  16749. if (footer) *footer = END_X509_CRL;
  16750. ret = 0;
  16751. break;
  16752. #ifndef NO_DH
  16753. case DH_PARAM_TYPE:
  16754. if (header) *header = BEGIN_DH_PARAM;
  16755. if (footer) *footer = END_DH_PARAM;
  16756. ret = 0;
  16757. break;
  16758. case X942_PARAM_TYPE:
  16759. if (header) *header = BEGIN_X942_PARAM;
  16760. if (footer) *footer = END_X942_PARAM;
  16761. ret = 0;
  16762. break;
  16763. #endif
  16764. #ifndef NO_DSA
  16765. case DSA_PARAM_TYPE:
  16766. if (header) *header = BEGIN_DSA_PARAM;
  16767. if (footer) *footer = END_DSA_PARAM;
  16768. ret = 0;
  16769. break;
  16770. #endif
  16771. #ifdef WOLFSSL_CERT_REQ
  16772. case CERTREQ_TYPE:
  16773. if (header) *header = BEGIN_CERT_REQ;
  16774. if (footer) *footer = END_CERT_REQ;
  16775. ret = 0;
  16776. break;
  16777. #endif
  16778. #ifndef NO_DSA
  16779. case DSA_TYPE:
  16780. case DSA_PRIVATEKEY_TYPE:
  16781. if (header) *header = BEGIN_DSA_PRIV;
  16782. if (footer) *footer = END_DSA_PRIV;
  16783. ret = 0;
  16784. break;
  16785. #endif
  16786. #ifdef HAVE_ECC
  16787. case ECC_TYPE:
  16788. case ECC_PRIVATEKEY_TYPE:
  16789. if (header) *header = BEGIN_EC_PRIV;
  16790. if (footer) *footer = END_EC_PRIV;
  16791. ret = 0;
  16792. break;
  16793. #endif
  16794. case RSA_TYPE:
  16795. case PRIVATEKEY_TYPE:
  16796. if (header) *header = BEGIN_RSA_PRIV;
  16797. if (footer) *footer = END_RSA_PRIV;
  16798. ret = 0;
  16799. break;
  16800. #ifdef HAVE_ED25519
  16801. case ED25519_TYPE:
  16802. #endif
  16803. #ifdef HAVE_ED448
  16804. case ED448_TYPE:
  16805. #endif
  16806. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  16807. case EDDSA_PRIVATEKEY_TYPE:
  16808. if (header) *header = BEGIN_EDDSA_PRIV;
  16809. if (footer) *footer = END_EDDSA_PRIV;
  16810. ret = 0;
  16811. break;
  16812. #endif
  16813. #ifdef HAVE_LIBOQS
  16814. case FALCON_LEVEL1_TYPE:
  16815. if (header) *header = BEGIN_FALCON_LEVEL1_PRIV;
  16816. if (footer) *footer = END_FALCON_LEVEL1_PRIV;
  16817. ret = 0;
  16818. break;
  16819. case FALCON_LEVEL5_TYPE:
  16820. if (header) *header = BEGIN_FALCON_LEVEL5_PRIV;
  16821. if (footer) *footer = END_FALCON_LEVEL5_PRIV;
  16822. ret = 0;
  16823. break;
  16824. #endif
  16825. case PUBLICKEY_TYPE:
  16826. case ECC_PUBLICKEY_TYPE:
  16827. if (header) *header = BEGIN_PUB_KEY;
  16828. if (footer) *footer = END_PUB_KEY;
  16829. ret = 0;
  16830. break;
  16831. #ifndef NO_DH
  16832. case DH_PRIVATEKEY_TYPE:
  16833. #endif
  16834. case PKCS8_PRIVATEKEY_TYPE:
  16835. if (header) *header = BEGIN_PRIV_KEY;
  16836. if (footer) *footer = END_PRIV_KEY;
  16837. ret = 0;
  16838. break;
  16839. case PKCS8_ENC_PRIVATEKEY_TYPE:
  16840. if (header) *header = BEGIN_ENC_PRIV_KEY;
  16841. if (footer) *footer = END_ENC_PRIV_KEY;
  16842. ret = 0;
  16843. break;
  16844. default:
  16845. break;
  16846. }
  16847. return ret;
  16848. }
  16849. #ifdef WOLFSSL_ENCRYPTED_KEYS
  16850. static wcchar kProcTypeHeader = "Proc-Type";
  16851. static wcchar kDecInfoHeader = "DEK-Info";
  16852. #ifdef WOLFSSL_PEM_TO_DER
  16853. #ifndef NO_DES3
  16854. static wcchar kEncTypeDes = "DES-CBC";
  16855. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  16856. #endif
  16857. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  16858. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  16859. #endif
  16860. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  16861. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  16862. #endif
  16863. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  16864. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  16865. #endif
  16866. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  16867. {
  16868. int ret = 0;
  16869. if (info == NULL || cipherInfo == NULL)
  16870. return BAD_FUNC_ARG;
  16871. /* determine cipher information */
  16872. #ifndef NO_DES3
  16873. if (XSTRNCMP(cipherInfo, kEncTypeDes, XSTRLEN(kEncTypeDes)) == 0) {
  16874. info->cipherType = WC_CIPHER_DES;
  16875. info->keySz = DES_KEY_SIZE;
  16876. /* DES_IV_SIZE is incorrectly 16 in FIPS v2. It should be 8, same as the
  16877. * block size. */
  16878. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  16879. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  16880. #else
  16881. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  16882. #endif
  16883. }
  16884. else if (XSTRNCMP(cipherInfo, kEncTypeDes3, XSTRLEN(kEncTypeDes3)) == 0) {
  16885. info->cipherType = WC_CIPHER_DES3;
  16886. info->keySz = DES3_KEY_SIZE;
  16887. #if defined(HAVE_FIPS) && defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION == 2)
  16888. if (info->ivSz == 0) info->ivSz = DES_BLOCK_SIZE;
  16889. #else
  16890. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  16891. #endif
  16892. }
  16893. else
  16894. #endif /* !NO_DES3 */
  16895. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  16896. if (XSTRNCMP(cipherInfo, kEncTypeAesCbc128, XSTRLEN(kEncTypeAesCbc128)) == 0) {
  16897. info->cipherType = WC_CIPHER_AES_CBC;
  16898. info->keySz = AES_128_KEY_SIZE;
  16899. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  16900. }
  16901. else
  16902. #endif
  16903. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  16904. if (XSTRNCMP(cipherInfo, kEncTypeAesCbc192, XSTRLEN(kEncTypeAesCbc192)) == 0) {
  16905. info->cipherType = WC_CIPHER_AES_CBC;
  16906. info->keySz = AES_192_KEY_SIZE;
  16907. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  16908. }
  16909. else
  16910. #endif
  16911. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  16912. if (XSTRNCMP(cipherInfo, kEncTypeAesCbc256, XSTRLEN(kEncTypeAesCbc256)) == 0) {
  16913. info->cipherType = WC_CIPHER_AES_CBC;
  16914. info->keySz = AES_256_KEY_SIZE;
  16915. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  16916. }
  16917. else
  16918. #endif
  16919. {
  16920. ret = NOT_COMPILED_IN;
  16921. }
  16922. return ret;
  16923. }
  16924. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  16925. size_t bufSz)
  16926. {
  16927. int err = 0;
  16928. const char* bufferStart;
  16929. const char* bufferEnd;
  16930. char* line;
  16931. word32 lineSz;
  16932. char* finish;
  16933. word32 finishSz;
  16934. char* start = NULL;
  16935. word32 startSz;
  16936. const char* newline = NULL;
  16937. if (info == NULL || pBuffer == NULL || bufSz == 0)
  16938. return BAD_FUNC_ARG;
  16939. bufferStart = *pBuffer;
  16940. bufferEnd = bufferStart + bufSz;
  16941. /* find encrypted info marker */
  16942. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  16943. min((word32)bufSz, PEM_LINE_LEN));
  16944. if (line != NULL) {
  16945. if (line >= bufferEnd) {
  16946. return BUFFER_E;
  16947. }
  16948. lineSz = (word32)(bufferEnd - line);
  16949. /* find DEC-Info marker */
  16950. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  16951. if (start == NULL)
  16952. return BUFFER_E;
  16953. /* skip dec-info and ": " */
  16954. start += XSTRLEN(kDecInfoHeader);
  16955. if (start >= bufferEnd)
  16956. return BUFFER_E;
  16957. if (start[0] == ':') {
  16958. start++;
  16959. if (start >= bufferEnd)
  16960. return BUFFER_E;
  16961. }
  16962. if (start[0] == ' ')
  16963. start++;
  16964. startSz = (word32)(bufferEnd - start);
  16965. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  16966. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  16967. if (finish >= bufferEnd) {
  16968. return BUFFER_E;
  16969. }
  16970. finishSz = (word32)(bufferEnd - finish);
  16971. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  16972. /* get cipher name */
  16973. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  16974. return BUFFER_E;
  16975. if (XMEMCPY(info->name, start, finish - start) == NULL)
  16976. return BUFFER_E;
  16977. info->name[finish - start] = '\0'; /* null term */
  16978. /* populate info */
  16979. err = wc_EncryptedInfoGet(info, info->name);
  16980. if (err != 0)
  16981. return err;
  16982. /* get IV */
  16983. if (finishSz < info->ivSz + 1)
  16984. return BUFFER_E;
  16985. if (newline == NULL) {
  16986. newline = XSTRNSTR(finish, "\n", min(finishSz,
  16987. PEM_LINE_LEN));
  16988. }
  16989. if ((newline != NULL) && (newline > finish)) {
  16990. finish++;
  16991. info->ivSz = (word32)(newline - finish);
  16992. if (info->ivSz > IV_SZ)
  16993. return BUFFER_E;
  16994. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  16995. return BUFFER_E;
  16996. info->set = 1;
  16997. }
  16998. else
  16999. return BUFFER_E;
  17000. }
  17001. else
  17002. return BUFFER_E;
  17003. /* eat end of line characters */
  17004. newline = SkipEndOfLineChars(newline, bufferEnd);
  17005. /* return new headerEnd */
  17006. *pBuffer = newline;
  17007. }
  17008. return err;
  17009. }
  17010. #endif /* WOLFSSL_PEM_TO_DER */
  17011. #ifdef WOLFSSL_DER_TO_PEM
  17012. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  17013. {
  17014. if (cipherInfo != NULL) {
  17015. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  17016. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  17017. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  17018. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  17019. /* strncat's src length needs to include the NULL */
  17020. XSTRNCAT(dest, kProcTypeHeader, 10);
  17021. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  17022. XSTRNCAT(dest, kDecInfoHeader, 9);
  17023. XSTRNCAT(dest, ": ", 3);
  17024. XSTRNCAT(dest, cipherInfo, destSz - (int)XSTRLEN(dest) - 1);
  17025. XSTRNCAT(dest, "\n\n", 4);
  17026. }
  17027. }
  17028. return 0;
  17029. }
  17030. #endif /* WOLFSSL_DER_TO_PEM */
  17031. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  17032. #ifdef WOLFSSL_DER_TO_PEM
  17033. /* Used for compatibility API */
  17034. int wc_DerToPem(const byte* der, word32 derSz,
  17035. byte* output, word32 outSz, int type)
  17036. {
  17037. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  17038. }
  17039. /* convert der buffer to pem into output, can't do inplace, der and output
  17040. need to be different */
  17041. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  17042. byte *cipher_info, int type)
  17043. {
  17044. const char* headerStr = NULL;
  17045. const char* footerStr = NULL;
  17046. #ifdef WOLFSSL_SMALL_STACK
  17047. char* header = NULL;
  17048. char* footer = NULL;
  17049. #else
  17050. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  17051. char footer[MAX_X509_HEADER_SZ];
  17052. #endif
  17053. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  17054. int footerLen = MAX_X509_HEADER_SZ;
  17055. int i;
  17056. int err;
  17057. int outLen; /* return length or error */
  17058. (void)cipher_info;
  17059. if (der == output) /* no in place conversion */
  17060. return BAD_FUNC_ARG;
  17061. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  17062. if (err != 0)
  17063. return err;
  17064. #ifdef WOLFSSL_SMALL_STACK
  17065. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17066. if (header == NULL)
  17067. return MEMORY_E;
  17068. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17069. if (footer == NULL) {
  17070. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17071. return MEMORY_E;
  17072. }
  17073. #endif
  17074. /* build header and footer based on type */
  17075. XSTRNCPY(header, headerStr, headerLen - 1);
  17076. header[headerLen - 2] = 0;
  17077. XSTRNCPY(footer, footerStr, footerLen - 1);
  17078. footer[footerLen - 2] = 0;
  17079. /* add new line to end */
  17080. XSTRNCAT(header, "\n", 2);
  17081. XSTRNCAT(footer, "\n", 2);
  17082. #ifdef WOLFSSL_ENCRYPTED_KEYS
  17083. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  17084. if (err != 0) {
  17085. #ifdef WOLFSSL_SMALL_STACK
  17086. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17087. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17088. #endif
  17089. return err;
  17090. }
  17091. #endif
  17092. headerLen = (int)XSTRLEN(header);
  17093. footerLen = (int)XSTRLEN(footer);
  17094. /* if null output and 0 size passed in then return size needed */
  17095. if (!output && outSz == 0) {
  17096. #ifdef WOLFSSL_SMALL_STACK
  17097. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17098. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17099. #endif
  17100. outLen = 0;
  17101. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  17102. != LENGTH_ONLY_E) {
  17103. return err;
  17104. }
  17105. return headerLen + footerLen + outLen;
  17106. }
  17107. if (!der || !output) {
  17108. #ifdef WOLFSSL_SMALL_STACK
  17109. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17110. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17111. #endif
  17112. return BAD_FUNC_ARG;
  17113. }
  17114. /* don't even try if outSz too short */
  17115. if (outSz < headerLen + footerLen + derSz) {
  17116. #ifdef WOLFSSL_SMALL_STACK
  17117. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17118. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17119. #endif
  17120. return BAD_FUNC_ARG;
  17121. }
  17122. /* header */
  17123. XMEMCPY(output, header, headerLen);
  17124. i = headerLen;
  17125. #ifdef WOLFSSL_SMALL_STACK
  17126. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17127. #endif
  17128. /* body */
  17129. outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */
  17130. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  17131. #ifdef WOLFSSL_SMALL_STACK
  17132. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17133. #endif
  17134. return err;
  17135. }
  17136. i += outLen;
  17137. /* footer */
  17138. if ( (i + footerLen) > (int)outSz) {
  17139. #ifdef WOLFSSL_SMALL_STACK
  17140. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17141. #endif
  17142. return BAD_FUNC_ARG;
  17143. }
  17144. XMEMCPY(output + i, footer, footerLen);
  17145. #ifdef WOLFSSL_SMALL_STACK
  17146. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  17147. #endif
  17148. return outLen + headerLen + footerLen;
  17149. }
  17150. #endif /* WOLFSSL_DER_TO_PEM */
  17151. #ifdef WOLFSSL_PEM_TO_DER
  17152. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  17153. info->consumed tracks of PEM bytes consumed in case multiple parts */
  17154. int PemToDer(const unsigned char* buff, long longSz, int type,
  17155. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  17156. {
  17157. const char* header = NULL;
  17158. const char* footer = NULL;
  17159. const char* headerEnd;
  17160. const char* footerEnd;
  17161. const char* consumedEnd;
  17162. const char* bufferEnd = (const char*)(buff + longSz);
  17163. long neededSz;
  17164. int ret = 0;
  17165. int sz = (int)longSz;
  17166. int encrypted_key = 0;
  17167. DerBuffer* der;
  17168. word32 algId = 0;
  17169. word32 idx;
  17170. #if defined(WOLFSSL_ENCRYPTED_KEYS)
  17171. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3) && \
  17172. !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  17173. int padVal = 0;
  17174. #endif
  17175. #endif
  17176. #ifdef OPENSSL_EXTRA
  17177. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  17178. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  17179. #endif
  17180. WOLFSSL_ENTER("PemToDer");
  17181. /* get PEM header and footer based on type */
  17182. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  17183. if (ret != 0)
  17184. return ret;
  17185. /* map header if not found for type */
  17186. for (;;) {
  17187. headerEnd = XSTRNSTR((char*)buff, header, sz);
  17188. if (headerEnd) {
  17189. break;
  17190. }
  17191. if (type == PRIVATEKEY_TYPE) {
  17192. if (header == BEGIN_RSA_PRIV) {
  17193. header = BEGIN_PRIV_KEY;
  17194. footer = END_PRIV_KEY;
  17195. }
  17196. else if (header == BEGIN_PRIV_KEY) {
  17197. header = BEGIN_ENC_PRIV_KEY;
  17198. footer = END_ENC_PRIV_KEY;
  17199. }
  17200. #ifdef HAVE_ECC
  17201. else if (header == BEGIN_ENC_PRIV_KEY) {
  17202. header = BEGIN_EC_PRIV;
  17203. footer = END_EC_PRIV;
  17204. }
  17205. else if (header == BEGIN_EC_PRIV) {
  17206. header = BEGIN_DSA_PRIV;
  17207. footer = END_DSA_PRIV;
  17208. }
  17209. #endif
  17210. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  17211. #ifdef HAVE_ECC
  17212. else if (header == BEGIN_DSA_PRIV) {
  17213. #else
  17214. else if (header == BEGIN_ENC_PRIV_KEY) {
  17215. #endif
  17216. header = BEGIN_EDDSA_PRIV;
  17217. footer = END_EDDSA_PRIV;
  17218. }
  17219. #endif
  17220. else {
  17221. #if defined(WOLF_CRYPTO_CB) || defined(HAVE_PK_CALLBACKS)
  17222. /* allow loading a public key for use with crypto or PK callbacks */
  17223. type = PUBLICKEY_TYPE;
  17224. header = BEGIN_PUB_KEY;
  17225. footer = END_PUB_KEY;
  17226. #else
  17227. break;
  17228. #endif
  17229. }
  17230. }
  17231. else if (type == PUBLICKEY_TYPE) {
  17232. if (header == BEGIN_PUB_KEY) {
  17233. header = BEGIN_RSA_PUB;
  17234. footer = END_RSA_PUB;
  17235. }
  17236. else {
  17237. break;
  17238. }
  17239. }
  17240. #ifdef HAVE_CRL
  17241. else if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  17242. header = BEGIN_X509_CRL;
  17243. footer = END_X509_CRL;
  17244. }
  17245. #endif
  17246. else {
  17247. break;
  17248. }
  17249. }
  17250. if (!headerEnd) {
  17251. #ifdef OPENSSL_EXTRA
  17252. if (type == PRIVATEKEY_TYPE) {
  17253. const char* beginEnd;
  17254. int endLen;
  17255. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  17256. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  17257. if (headerEnd) {
  17258. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  17259. if (beginEnd >= (char*)buff + sz) {
  17260. return BUFFER_E;
  17261. }
  17262. /* back up to BEGIN_PRIV_KEY_PREFIX */
  17263. while (headerEnd > (char*)buff &&
  17264. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  17265. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  17266. *headerEnd != '\n') {
  17267. headerEnd--;
  17268. }
  17269. if (headerEnd <= (char*)buff ||
  17270. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  17271. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  17272. beginEnd - headerEnd > PEM_LINE_LEN) {
  17273. WOLFSSL_MSG("Couldn't find PEM header");
  17274. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  17275. return ASN_NO_PEM_HEADER;
  17276. }
  17277. /* headerEnd now points to beginning of header */
  17278. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  17279. beginBuf[beginEnd - headerEnd] = '\0';
  17280. /* look for matching footer */
  17281. footer = XSTRNSTR(beginEnd,
  17282. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  17283. (unsigned int)((char*)buff + sz - beginEnd));
  17284. if (!footer) {
  17285. WOLFSSL_MSG("Couldn't find PEM footer");
  17286. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  17287. return ASN_NO_PEM_HEADER;
  17288. }
  17289. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  17290. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  17291. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  17292. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  17293. WOLFSSL_MSG("Unexpected footer for PEM");
  17294. return BUFFER_E;
  17295. }
  17296. endLen = (unsigned int)(beginEnd - headerEnd -
  17297. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  17298. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  17299. XMEMCPY(endBuf, footer, endLen);
  17300. endBuf[endLen] = '\0';
  17301. header = beginBuf;
  17302. footer = endBuf;
  17303. headerEnd = beginEnd;
  17304. }
  17305. }
  17306. if (!headerEnd) {
  17307. WOLFSSL_MSG("Couldn't find PEM header");
  17308. WOLFSSL_ERROR(ASN_NO_PEM_HEADER);
  17309. return ASN_NO_PEM_HEADER;
  17310. }
  17311. #else
  17312. WOLFSSL_MSG("Couldn't find PEM header");
  17313. return ASN_NO_PEM_HEADER;
  17314. #endif
  17315. } else {
  17316. headerEnd += XSTRLEN(header);
  17317. }
  17318. /* eat end of line characters */
  17319. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  17320. if (keyFormat) {
  17321. /* keyFormat is Key_Sum enum */
  17322. if (type == PRIVATEKEY_TYPE) {
  17323. #ifndef NO_RSA
  17324. if (header == BEGIN_RSA_PRIV)
  17325. *keyFormat = RSAk;
  17326. #endif
  17327. #ifdef HAVE_ECC
  17328. if (header == BEGIN_EC_PRIV)
  17329. *keyFormat = ECDSAk;
  17330. #endif
  17331. #ifndef NO_DSA
  17332. if (header == BEGIN_DSA_PRIV)
  17333. *keyFormat = DSAk;
  17334. #endif
  17335. }
  17336. #if defined(WOLF_CRYPTO_CB) || defined(HAVE_PK_CALLBACKS)
  17337. else if (type == PUBLICKEY_TYPE) {
  17338. #ifndef NO_RSA
  17339. if (header == BEGIN_RSA_PUB)
  17340. *keyFormat = RSAk;
  17341. #endif
  17342. }
  17343. #endif
  17344. }
  17345. #ifdef WOLFSSL_ENCRYPTED_KEYS
  17346. if (info) {
  17347. ret = wc_EncryptedInfoParse(info, &headerEnd, bufferEnd - headerEnd);
  17348. if (ret < 0)
  17349. return ret;
  17350. if (info->set)
  17351. encrypted_key = 1;
  17352. }
  17353. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  17354. /* find footer */
  17355. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff +
  17356. sz - headerEnd));
  17357. if (!footerEnd) {
  17358. if (info)
  17359. info->consumed = longSz; /* No more certs if no footer */
  17360. return BUFFER_E;
  17361. }
  17362. consumedEnd = footerEnd + XSTRLEN(footer);
  17363. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  17364. /* eat end of line characters */
  17365. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  17366. /* skip possible null term */
  17367. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  17368. consumedEnd++;
  17369. }
  17370. if (info)
  17371. info->consumed = (long)(consumedEnd - (const char*)buff);
  17372. /* set up der buffer */
  17373. neededSz = (long)(footerEnd - headerEnd);
  17374. if (neededSz > sz || neededSz <= 0)
  17375. return BUFFER_E;
  17376. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  17377. if (ret < 0) {
  17378. return ret;
  17379. }
  17380. der = *pDer;
  17381. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  17382. der->buffer, &der->length) < 0) {
  17383. WOLFSSL_ERROR(BUFFER_E);
  17384. return BUFFER_E;
  17385. }
  17386. if ((header == BEGIN_PRIV_KEY
  17387. #ifdef OPENSSL_EXTRA
  17388. || header == beginBuf
  17389. #endif
  17390. #ifdef HAVE_ECC
  17391. || header == BEGIN_EC_PRIV
  17392. #endif
  17393. ) && !encrypted_key)
  17394. {
  17395. /* detect pkcs8 key and get alg type */
  17396. /* keep PKCS8 header */
  17397. idx = 0;
  17398. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length, &algId);
  17399. if (ret > 0) {
  17400. if (keyFormat)
  17401. *keyFormat = algId;
  17402. }
  17403. else {
  17404. /* ignore failure here and assume key is not pkcs8 wrapped */
  17405. }
  17406. return 0;
  17407. }
  17408. #ifdef WOLFSSL_ENCRYPTED_KEYS
  17409. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  17410. int passwordSz = NAME_SZ;
  17411. #ifdef WOLFSSL_SMALL_STACK
  17412. char* password = NULL;
  17413. #else
  17414. char password[NAME_SZ];
  17415. #endif
  17416. if (!info || !info->passwd_cb) {
  17417. WOLFSSL_MSG("No password callback set");
  17418. return NO_PASSWORD;
  17419. }
  17420. #ifdef WOLFSSL_SMALL_STACK
  17421. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  17422. if (password == NULL)
  17423. return MEMORY_E;
  17424. #endif
  17425. /* get password */
  17426. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  17427. info->passwd_userdata);
  17428. if (ret >= 0) {
  17429. passwordSz = ret;
  17430. /* convert and adjust length */
  17431. if (header == BEGIN_ENC_PRIV_KEY) {
  17432. #ifndef NO_PWDBASED
  17433. ret = wc_DecryptPKCS8Key(der->buffer, der->length,
  17434. password, passwordSz);
  17435. if (ret > 0) {
  17436. /* update length by decrypted content */
  17437. der->length = ret;
  17438. idx = 0;
  17439. /* detect pkcs8 key and get alg type */
  17440. /* keep PKCS8 header */
  17441. ret = ToTraditionalInline_ex(der->buffer, &idx, der->length,
  17442. &algId);
  17443. if (ret >= 0) {
  17444. if (keyFormat)
  17445. *keyFormat = algId;
  17446. ret = 0;
  17447. }
  17448. }
  17449. #else
  17450. ret = NOT_COMPILED_IN;
  17451. #endif
  17452. }
  17453. /* decrypt the key */
  17454. else {
  17455. if (passwordSz == 0) {
  17456. /* The key is encrypted but does not have a password */
  17457. WOLFSSL_MSG("No password for encrypted key");
  17458. ret = NO_PASSWORD;
  17459. }
  17460. else {
  17461. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  17462. (byte*)password, passwordSz, WC_MD5);
  17463. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  17464. #ifndef NO_DES3
  17465. if (info->cipherType == WC_CIPHER_DES3) {
  17466. /* Assuming there is padding:
  17467. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  17468. * (der->length % DES_BLOCK_SIZE) != 0)
  17469. * and assuming the last value signifies the number of
  17470. * padded bytes IE if last value is 0x08 then there are
  17471. * 8 bytes of padding:
  17472. * padVal = der->buffer[der->length-1];
  17473. * then strip this padding before proceeding:
  17474. * der->length -= padVal;
  17475. */
  17476. if (der->length > DES_BLOCK_SIZE &&
  17477. (der->length % DES_BLOCK_SIZE) != 0) {
  17478. padVal = der->buffer[der->length-1];
  17479. if (padVal < DES_BLOCK_SIZE) {
  17480. der->length -= padVal;
  17481. }
  17482. }
  17483. }
  17484. #endif /* !NO_DES3 */
  17485. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  17486. }
  17487. }
  17488. #ifdef OPENSSL_EXTRA
  17489. if (ret) {
  17490. PEMerr(0, PEM_R_BAD_DECRYPT);
  17491. }
  17492. #endif
  17493. ForceZero(password, passwordSz);
  17494. }
  17495. #ifdef OPENSSL_EXTRA
  17496. else {
  17497. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  17498. }
  17499. #endif
  17500. #ifdef WOLFSSL_SMALL_STACK
  17501. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  17502. #endif
  17503. }
  17504. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  17505. return ret;
  17506. }
  17507. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  17508. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  17509. {
  17510. int ret = PemToDer(buff, longSz, type, pDer, heap, info, keyFormat);
  17511. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  17512. if (ret == 0 && type == PRIVATEKEY_TYPE) {
  17513. DerBuffer* der = *pDer;
  17514. /* if a PKCS8 key header exists remove it */
  17515. ret = ToTraditional(der->buffer, der->length);
  17516. if (ret > 0) {
  17517. der->length = ret;
  17518. }
  17519. ret = 0; /* ignore error removing PKCS8 header */
  17520. }
  17521. #endif
  17522. return ret;
  17523. }
  17524. /* our KeyPemToDer password callback, password in userData */
  17525. static int KeyPemToDerPassCb(char* passwd, int sz, int rw, void* userdata)
  17526. {
  17527. (void)rw;
  17528. if (userdata == NULL)
  17529. return 0;
  17530. XSTRNCPY(passwd, (char*)userdata, sz);
  17531. return min((word32)sz, (word32)XSTRLEN((char*)userdata));
  17532. }
  17533. /* Return bytes written to buff or < 0 for error */
  17534. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  17535. unsigned char* buff, int buffSz, const char* pass)
  17536. {
  17537. int ret;
  17538. DerBuffer* der = NULL;
  17539. #ifdef WOLFSSL_SMALL_STACK
  17540. EncryptedInfo* info = NULL;
  17541. #else
  17542. EncryptedInfo info[1];
  17543. #endif
  17544. WOLFSSL_ENTER("wc_KeyPemToDer");
  17545. if (pem == NULL || buff == NULL || buffSz <= 0) {
  17546. WOLFSSL_MSG("Bad pem der args");
  17547. return BAD_FUNC_ARG;
  17548. }
  17549. #ifdef WOLFSSL_SMALL_STACK
  17550. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  17551. DYNAMIC_TYPE_ENCRYPTEDINFO);
  17552. if (info == NULL)
  17553. return MEMORY_E;
  17554. #endif
  17555. XMEMSET(info, 0, sizeof(EncryptedInfo));
  17556. info->passwd_cb = KeyPemToDerPassCb;
  17557. info->passwd_userdata = (void*)pass;
  17558. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, NULL);
  17559. #ifdef WOLFSSL_SMALL_STACK
  17560. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  17561. #endif
  17562. if (ret < 0 || der == NULL) {
  17563. WOLFSSL_MSG("Bad Pem To Der");
  17564. }
  17565. else {
  17566. if (der->length <= (word32)buffSz) {
  17567. XMEMCPY(buff, der->buffer, der->length);
  17568. ret = der->length;
  17569. }
  17570. else {
  17571. WOLFSSL_MSG("Bad der length");
  17572. ret = BAD_FUNC_ARG;
  17573. }
  17574. }
  17575. FreeDer(&der);
  17576. return ret;
  17577. }
  17578. /* Return bytes written to buff or < 0 for error */
  17579. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  17580. unsigned char* buff, int buffSz, int type)
  17581. {
  17582. int ret;
  17583. DerBuffer* der = NULL;
  17584. WOLFSSL_ENTER("wc_CertPemToDer");
  17585. if (pem == NULL || buff == NULL || buffSz <= 0) {
  17586. WOLFSSL_MSG("Bad pem der args");
  17587. return BAD_FUNC_ARG;
  17588. }
  17589. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  17590. WOLFSSL_MSG("Bad cert type");
  17591. return BAD_FUNC_ARG;
  17592. }
  17593. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, NULL);
  17594. if (ret < 0 || der == NULL) {
  17595. WOLFSSL_MSG("Bad Pem To Der");
  17596. }
  17597. else {
  17598. if (der->length <= (word32)buffSz) {
  17599. XMEMCPY(buff, der->buffer, der->length);
  17600. ret = der->length;
  17601. }
  17602. else {
  17603. WOLFSSL_MSG("Bad der length");
  17604. ret = BAD_FUNC_ARG;
  17605. }
  17606. }
  17607. FreeDer(&der);
  17608. return ret;
  17609. }
  17610. #endif /* WOLFSSL_PEM_TO_DER */
  17611. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  17612. #ifdef WOLFSSL_PEM_TO_DER
  17613. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  17614. /* Return bytes written to buff or < 0 for error */
  17615. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  17616. unsigned char* buff, int buffSz)
  17617. {
  17618. int ret;
  17619. DerBuffer* der = NULL;
  17620. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  17621. if (pem == NULL || buff == NULL || buffSz <= 0) {
  17622. WOLFSSL_MSG("Bad pem der args");
  17623. return BAD_FUNC_ARG;
  17624. }
  17625. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  17626. if (ret < 0 || der == NULL) {
  17627. WOLFSSL_MSG("Bad Pem To Der");
  17628. }
  17629. else {
  17630. if (der->length <= (word32)buffSz) {
  17631. XMEMCPY(buff, der->buffer, der->length);
  17632. ret = der->length;
  17633. }
  17634. else {
  17635. WOLFSSL_MSG("Bad der length");
  17636. ret = BAD_FUNC_ARG;
  17637. }
  17638. }
  17639. FreeDer(&der);
  17640. return ret;
  17641. }
  17642. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  17643. #endif /* WOLFSSL_PEM_TO_DER */
  17644. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_PEM_TO_DER)
  17645. #ifdef WOLFSSL_CERT_GEN
  17646. int wc_PemCertToDer_ex(const char* fileName, DerBuffer** der)
  17647. {
  17648. #ifdef WOLFSSL_SMALL_STACK
  17649. byte staticBuffer[1]; /* force XMALLOC */
  17650. #else
  17651. byte staticBuffer[FILE_BUFFER_SIZE];
  17652. #endif
  17653. byte* fileBuf = staticBuffer;
  17654. int dynamic = 0;
  17655. int ret = 0;
  17656. long sz = 0;
  17657. XFILE file;
  17658. WOLFSSL_ENTER("wc_PemCertToDer");
  17659. if (fileName == NULL) {
  17660. ret = BAD_FUNC_ARG;
  17661. }
  17662. else {
  17663. file = XFOPEN(fileName, "rb");
  17664. if (file == XBADFILE) {
  17665. ret = BUFFER_E;
  17666. }
  17667. }
  17668. if (ret == 0) {
  17669. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  17670. ret = BUFFER_E;
  17671. }
  17672. sz = XFTELL(file);
  17673. XREWIND(file);
  17674. if (sz <= 0) {
  17675. ret = BUFFER_E;
  17676. }
  17677. else if (sz > (long)sizeof(staticBuffer)) {
  17678. #ifdef WOLFSSL_STATIC_MEMORY
  17679. WOLFSSL_MSG("File was larger then static buffer");
  17680. ret = MEMORY_E;
  17681. #else
  17682. fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
  17683. if (fileBuf == NULL)
  17684. ret = MEMORY_E;
  17685. else
  17686. dynamic = 1;
  17687. #endif
  17688. }
  17689. if (ret == 0) {
  17690. if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
  17691. ret = BUFFER_E;
  17692. }
  17693. else {
  17694. ret = PemToDer(fileBuf, sz, CA_TYPE, der, 0, NULL,NULL);
  17695. }
  17696. }
  17697. XFCLOSE(file);
  17698. if (dynamic)
  17699. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  17700. }
  17701. return ret;
  17702. }
  17703. /* load pem cert from file into der buffer, return der size or error */
  17704. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  17705. {
  17706. int ret;
  17707. DerBuffer* converted = NULL;
  17708. ret = wc_PemCertToDer_ex(fileName, &converted);
  17709. if (ret == 0) {
  17710. if (converted->length < (word32)derSz) {
  17711. XMEMCPY(derBuf, converted->buffer, converted->length);
  17712. ret = converted->length;
  17713. }
  17714. else
  17715. ret = BUFFER_E;
  17716. FreeDer(&converted);
  17717. }
  17718. return ret;
  17719. }
  17720. #endif /* WOLFSSL_CERT_GEN */
  17721. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  17722. /* load pem public key from file into der buffer, return der size or error */
  17723. int wc_PemPubKeyToDer_ex(const char* fileName, DerBuffer** der)
  17724. {
  17725. #ifdef WOLFSSL_SMALL_STACK
  17726. byte staticBuffer[1]; /* force XMALLOC */
  17727. #else
  17728. byte staticBuffer[FILE_BUFFER_SIZE];
  17729. #endif
  17730. byte* fileBuf = staticBuffer;
  17731. int dynamic = 0;
  17732. int ret = 0;
  17733. long sz = 0;
  17734. XFILE file;
  17735. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  17736. if (fileName == NULL) {
  17737. ret = BAD_FUNC_ARG;
  17738. }
  17739. else {
  17740. file = XFOPEN(fileName, "rb");
  17741. if (file == XBADFILE) {
  17742. ret = BUFFER_E;
  17743. }
  17744. }
  17745. if (ret == 0) {
  17746. if (XFSEEK(file, 0, XSEEK_END) != 0) {
  17747. ret = BUFFER_E;
  17748. }
  17749. sz = XFTELL(file);
  17750. XREWIND(file);
  17751. if (sz <= 0) {
  17752. ret = BUFFER_E;
  17753. }
  17754. else if (sz > (long)sizeof(staticBuffer)) {
  17755. #ifdef WOLFSSL_STATIC_MEMORY
  17756. WOLFSSL_MSG("File was larger then static buffer");
  17757. ret = MEMORY_E;
  17758. #else
  17759. fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
  17760. if (fileBuf == NULL)
  17761. ret = MEMORY_E;
  17762. else
  17763. dynamic = 1;
  17764. #endif
  17765. }
  17766. if (ret == 0) {
  17767. if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
  17768. ret = BUFFER_E;
  17769. }
  17770. else {
  17771. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, der,
  17772. 0, NULL, NULL);
  17773. }
  17774. }
  17775. XFCLOSE(file);
  17776. if (dynamic) {
  17777. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  17778. }
  17779. }
  17780. return ret;
  17781. }
  17782. /* load pem public key from file into der buffer, return der size or error */
  17783. int wc_PemPubKeyToDer(const char* fileName,
  17784. unsigned char* derBuf, int derSz)
  17785. {
  17786. int ret;
  17787. DerBuffer* converted = NULL;
  17788. ret = wc_PemPubKeyToDer_ex(fileName, &converted);
  17789. if (ret == 0) {
  17790. if (converted->length < (word32)derSz) {
  17791. XMEMCPY(derBuf, converted->buffer, converted->length);
  17792. ret = converted->length;
  17793. }
  17794. else
  17795. ret = BUFFER_E;
  17796. FreeDer(&converted);
  17797. }
  17798. return ret;
  17799. }
  17800. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  17801. #endif /* !NO_FILESYSTEM && WOLFSSL_PEM_TO_DER */
  17802. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  17803. defined(WOLFSSL_KCAPI_RSA) || \
  17804. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  17805. /* USER RSA ifdef portions used instead of refactor in consideration for
  17806. possible fips build */
  17807. /* Encode a public RSA key to output.
  17808. *
  17809. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  17810. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  17811. *
  17812. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  17813. * (RSAPublicKey).
  17814. *
  17815. * @param [out] output Buffer to put encoded data in.
  17816. * @param [in] key RSA key object.
  17817. * @param [in] outLen Size of the output buffer in bytes.
  17818. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  17819. * @return Size of encoded data in bytes on success.
  17820. * @return BAD_FUNC_ARG when output or key is NULL, or outLen is less than
  17821. * minimum length (5 bytes).
  17822. * @return MEMORY_E when dynamic memory allocation failed.
  17823. */
  17824. static int SetRsaPublicKey(byte* output, RsaKey* key, int outLen,
  17825. int with_header)
  17826. {
  17827. #ifndef WOLFSSL_ASN_TEMPLATE
  17828. int idx, nSz, eSz, seqSz, headSz = 0, bitStringSz = 0, algoSz = 0;
  17829. byte seq[MAX_SEQ_SZ];
  17830. byte headSeq[MAX_SEQ_SZ];
  17831. byte bitString[1 + MAX_LENGTH_SZ + 1];
  17832. byte algo[MAX_ALGO_SZ]; /* 20 bytes */
  17833. if (key == NULL) {
  17834. return BAD_FUNC_ARG;
  17835. }
  17836. #ifdef HAVE_USER_RSA
  17837. nSz = SetASNIntRSA(key->n, NULL);
  17838. #else
  17839. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  17840. #endif
  17841. if (nSz < 0)
  17842. return nSz;
  17843. #ifdef HAVE_USER_RSA
  17844. eSz = SetASNIntRSA(key->e, NULL);
  17845. #else
  17846. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  17847. #endif
  17848. if (eSz < 0)
  17849. return eSz;
  17850. seqSz = SetSequence(nSz + eSz, seq);
  17851. /* headers */
  17852. if (with_header) {
  17853. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  17854. bitStringSz = SetBitString(seqSz + nSz + eSz, 0, bitString);
  17855. headSz = SetSequence(nSz + eSz + seqSz + bitStringSz + algoSz, headSeq);
  17856. }
  17857. /* if getting length only */
  17858. if (output == NULL) {
  17859. return headSz + algoSz + bitStringSz + seqSz + nSz + eSz;
  17860. }
  17861. /* check output size */
  17862. if ((headSz + algoSz + bitStringSz + seqSz + nSz + eSz) > outLen) {
  17863. return BUFFER_E;
  17864. }
  17865. /* write output */
  17866. idx = 0;
  17867. if (with_header) {
  17868. /* header size */
  17869. XMEMCPY(output + idx, headSeq, headSz);
  17870. idx += headSz;
  17871. /* algo */
  17872. XMEMCPY(output + idx, algo, algoSz);
  17873. idx += algoSz;
  17874. /* bit string */
  17875. XMEMCPY(output + idx, bitString, bitStringSz);
  17876. idx += bitStringSz;
  17877. }
  17878. /* seq */
  17879. XMEMCPY(output + idx, seq, seqSz);
  17880. idx += seqSz;
  17881. /* n */
  17882. #ifdef HAVE_USER_RSA
  17883. nSz = SetASNIntRSA(key->n, output + idx);
  17884. #else
  17885. nSz = SetASNIntMP(&key->n, nSz, output + idx);
  17886. #endif
  17887. idx += nSz;
  17888. /* e */
  17889. #ifdef HAVE_USER_RSA
  17890. eSz = SetASNIntRSA(key->e, output + idx);
  17891. #else
  17892. eSz = SetASNIntMP(&key->e, eSz, output + idx);
  17893. #endif
  17894. idx += eSz;
  17895. return idx;
  17896. #else
  17897. DECL_ASNSETDATA(dataASN, rsaPublicKeyASN_Length);
  17898. int sz;
  17899. int ret = 0;
  17900. int o = 0;
  17901. /* Check parameter validity. */
  17902. if ((key == NULL) || ((output != NULL) && (outLen < MAX_SEQ_SZ))) {
  17903. ret = BAD_FUNC_ARG;
  17904. }
  17905. CALLOC_ASNSETDATA(dataASN, rsaPublicKeyASN_Length, ret, key->heap);
  17906. if (ret == 0) {
  17907. if (!with_header) {
  17908. /* Start encoding with items after header. */
  17909. o = 5;
  17910. }
  17911. /* Set OID for RSA key. */
  17912. SetASN_OID(&dataASN[2], RSAk, oidKeyType);
  17913. /* Set public key mp_ints. */
  17914. #ifdef HAVE_USER_RSA
  17915. SetASN_MP(&dataASN[6], key->n);
  17916. SetASN_MP(&dataASN[7], key->e);
  17917. #else
  17918. SetASN_MP(&dataASN[6], &key->n);
  17919. SetASN_MP(&dataASN[7], &key->e);
  17920. #endif
  17921. /* Calculate size of RSA public key. */
  17922. ret = SizeASN_Items(rsaPublicKeyASN + o, dataASN + o,
  17923. rsaPublicKeyASN_Length - o, &sz);
  17924. }
  17925. /* Check output buffer is big enough for encoding. */
  17926. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  17927. ret = BUFFER_E;
  17928. }
  17929. if ((ret == 0) && (output != NULL)) {
  17930. /* Encode RSA public key. */
  17931. SetASN_Items(rsaPublicKeyASN + o, dataASN + o,
  17932. rsaPublicKeyASN_Length - o, output);
  17933. }
  17934. if (ret == 0) {
  17935. /* Return size of encoding. */
  17936. ret = sz;
  17937. }
  17938. FREE_ASNSETDATA(dataASN, key->heap);
  17939. return ret;
  17940. #endif /* WOLFSSL_ASN_TEMPLATE */
  17941. }
  17942. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || (WOLFSSL_KEY_GEN &&
  17943. !HAVE_USER_RSA))) */
  17944. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  17945. /* Calculate size of encoded public RSA key in bytes.
  17946. *
  17947. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  17948. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  17949. *
  17950. * Encoded data can either be SubjectPublicKeyInfo (with header) or just the key
  17951. * (RSAPublicKey).
  17952. *
  17953. * @param [in] key RSA key object.
  17954. * @param [in] with_header Whether to include SubjectPublicKeyInfo around key.
  17955. * @return Size of encoded data in bytes on success.
  17956. * @return BAD_FUNC_ARG when key is NULL.
  17957. * @return MEMORY_E when dynamic memory allocation failed.
  17958. */
  17959. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  17960. {
  17961. return SetRsaPublicKey(NULL, key, 0, with_header);
  17962. }
  17963. #endif /* !NO_RSA && WOLFSSL_CERT_GEN */
  17964. #if ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && \
  17965. !defined(NO_RSA) && !defined(HAVE_USER_RSA)) || defined(WOLFSSL_KCAPI_RSA)
  17966. /* Encode private RSA key in DER format.
  17967. *
  17968. * PKCS #1: RFC 8017, A.1.2 - RSAPrivateKey
  17969. *
  17970. * @param [in] key RSA key object.
  17971. * @param [out] output Buffer to put encoded data in.
  17972. * @param [in] inLen Size of buffer in bytes.
  17973. * @return Size of encoded data in bytes on success.
  17974. * @return BAD_FUNC_ARG when key is NULL or not a private key.
  17975. * @return MEMORY_E when dynamic memory allocation failed.
  17976. */
  17977. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  17978. {
  17979. #ifndef WOLFSSL_ASN_TEMPLATE
  17980. int ret = 0, i, j, outLen = 0, mpSz;
  17981. word32 seqSz = 0, verSz = 0, rawLen, intTotalLen = 0;
  17982. word32 sizes[RSA_INTS];
  17983. byte seq[MAX_SEQ_SZ];
  17984. byte ver[MAX_VERSION_SZ];
  17985. byte* tmps[RSA_INTS];
  17986. if (key == NULL)
  17987. return BAD_FUNC_ARG;
  17988. if (key->type != RSA_PRIVATE)
  17989. return BAD_FUNC_ARG;
  17990. for (i = 0; i < RSA_INTS; i++)
  17991. tmps[i] = NULL;
  17992. /* write all big ints from key to DER tmps */
  17993. for (i = 0; i < RSA_INTS; i++) {
  17994. mp_int* keyInt = GetRsaInt(key, (byte)i);
  17995. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  17996. if (output != NULL) {
  17997. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  17998. DYNAMIC_TYPE_RSA);
  17999. if (tmps[i] == NULL) {
  18000. ret = MEMORY_E;
  18001. break;
  18002. }
  18003. }
  18004. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  18005. if (mpSz < 0) {
  18006. ret = mpSz;
  18007. break;
  18008. }
  18009. intTotalLen += (sizes[i] = mpSz);
  18010. }
  18011. if (ret == 0) {
  18012. /* make headers */
  18013. verSz = SetMyVersion(0, ver, FALSE);
  18014. seqSz = SetSequence(verSz + intTotalLen, seq);
  18015. outLen = seqSz + verSz + intTotalLen;
  18016. if (output != NULL && outLen > (int)inLen)
  18017. ret = BUFFER_E;
  18018. }
  18019. if (ret == 0 && output != NULL) {
  18020. /* write to output */
  18021. XMEMCPY(output, seq, seqSz);
  18022. j = seqSz;
  18023. XMEMCPY(output + j, ver, verSz);
  18024. j += verSz;
  18025. for (i = 0; i < RSA_INTS; i++) {
  18026. XMEMCPY(output + j, tmps[i], sizes[i]);
  18027. j += sizes[i];
  18028. }
  18029. }
  18030. for (i = 0; i < RSA_INTS; i++) {
  18031. if (tmps[i])
  18032. XFREE(tmps[i], key->heap, DYNAMIC_TYPE_RSA);
  18033. }
  18034. if (ret == 0)
  18035. ret = outLen;
  18036. return ret;
  18037. #else
  18038. DECL_ASNSETDATA(dataASN, rsaKeyASN_Length);
  18039. byte i;
  18040. int sz;
  18041. int ret = 0;
  18042. if ((key == NULL) || (key->type != RSA_PRIVATE)) {
  18043. ret = BAD_FUNC_ARG;
  18044. }
  18045. CALLOC_ASNSETDATA(dataASN, rsaKeyASN_Length, ret, key->heap);
  18046. if (ret == 0) {
  18047. /* Set the version. */
  18048. SetASN_Int8Bit(&dataASN[1], 0);
  18049. /* Set all the mp_ints in private key. */
  18050. for (i = 0; i < RSA_INTS; i++) {
  18051. SetASN_MP(&dataASN[2 + i], GetRsaInt(key, i));
  18052. }
  18053. /* Calculate size of RSA private key encoding. */
  18054. ret = SizeASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, &sz);
  18055. }
  18056. /* Check output buffer has enough space for encoding. */
  18057. if ((ret == 0) && (output != NULL) && (sz > (int)inLen)) {
  18058. ret = BAD_FUNC_ARG;
  18059. }
  18060. if ((ret == 0) && (output != NULL)) {
  18061. /* Encode RSA private key. */
  18062. SetASN_Items(rsaKeyASN, dataASN, rsaKeyASN_Length, output);
  18063. }
  18064. if (ret == 0) {
  18065. /* Return size of encoding. */
  18066. ret = sz;
  18067. }
  18068. FREE_ASNSETDATA(dataASN, key->heap);
  18069. return ret;
  18070. #endif
  18071. }
  18072. /* Encode public RSA key in DER format.
  18073. *
  18074. * X.509: RFC 5280, 4.1 - SubjectPublicKeyInfo
  18075. * PKCS #1: RFC 8017, A.1.1 - RSAPublicKey
  18076. *
  18077. * @param [in] key RSA key object.
  18078. * @param [out] output Buffer to put encoded data in.
  18079. * @param [in] inLen Size of buffer in bytes.
  18080. * @return Size of encoded data in bytes on success.
  18081. * @return BAD_FUNC_ARG when key or output is NULL.
  18082. * @return MEMORY_E when dynamic memory allocation failed.
  18083. */
  18084. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  18085. {
  18086. return SetRsaPublicKey(output, key, inLen, 1);
  18087. }
  18088. /* Returns public DER version of the RSA key. If with_header is 0 then only a
  18089. * seq + n + e is returned in ASN.1 DER format */
  18090. int wc_RsaKeyToPublicDer_ex(RsaKey* key, byte* output, word32 inLen,
  18091. int with_header)
  18092. {
  18093. return SetRsaPublicKey(output, key, inLen, with_header);
  18094. }
  18095. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  18096. #ifdef WOLFSSL_CERT_GEN
  18097. /* Initialize and Set Certificate defaults:
  18098. version = 3 (0x2)
  18099. serial = 0
  18100. sigType = SHA_WITH_RSA
  18101. issuer = blank
  18102. daysValid = 500
  18103. selfSigned = 1 (true) use subject as issuer
  18104. subject = blank
  18105. */
  18106. int wc_InitCert_ex(Cert* cert, void* heap, int devId)
  18107. {
  18108. #ifdef WOLFSSL_MULTI_ATTRIB
  18109. int i = 0;
  18110. #endif
  18111. if (cert == NULL) {
  18112. return BAD_FUNC_ARG;
  18113. }
  18114. XMEMSET(cert, 0, sizeof(Cert));
  18115. cert->version = 2; /* version 3 is hex 2 */
  18116. #ifndef NO_SHA
  18117. cert->sigType = CTC_SHAwRSA;
  18118. #elif !defined(NO_SHA256)
  18119. cert->sigType = CTC_SHA256wRSA;
  18120. #else
  18121. cert->sigType = 0;
  18122. #endif
  18123. cert->daysValid = 500;
  18124. cert->selfSigned = 1;
  18125. cert->keyType = RSA_KEY;
  18126. cert->issuer.countryEnc = CTC_PRINTABLE;
  18127. cert->issuer.stateEnc = CTC_UTF8;
  18128. cert->issuer.localityEnc = CTC_UTF8;
  18129. cert->issuer.surEnc = CTC_UTF8;
  18130. cert->issuer.orgEnc = CTC_UTF8;
  18131. cert->issuer.unitEnc = CTC_UTF8;
  18132. cert->issuer.commonNameEnc = CTC_UTF8;
  18133. cert->subject.countryEnc = CTC_PRINTABLE;
  18134. cert->subject.stateEnc = CTC_UTF8;
  18135. cert->subject.localityEnc = CTC_UTF8;
  18136. cert->subject.surEnc = CTC_UTF8;
  18137. cert->subject.orgEnc = CTC_UTF8;
  18138. cert->subject.unitEnc = CTC_UTF8;
  18139. cert->subject.commonNameEnc = CTC_UTF8;
  18140. #ifdef WOLFSSL_MULTI_ATTRIB
  18141. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  18142. cert->issuer.name[i].type = CTC_UTF8;
  18143. cert->subject.name[i].type = CTC_UTF8;
  18144. }
  18145. #endif /* WOLFSSL_MULTI_ATTRIB */
  18146. cert->heap = heap;
  18147. (void)devId; /* future */
  18148. return 0;
  18149. }
  18150. int wc_InitCert(Cert* cert)
  18151. {
  18152. return wc_InitCert_ex(cert, NULL, INVALID_DEVID);
  18153. }
  18154. /* DER encoded x509 Certificate */
  18155. typedef struct DerCert {
  18156. byte size[MAX_LENGTH_SZ]; /* length encoded */
  18157. byte version[MAX_VERSION_SZ]; /* version encoded */
  18158. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  18159. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  18160. byte issuer[ASN_NAME_MAX]; /* issuer encoded */
  18161. byte subject[ASN_NAME_MAX]; /* subject encoded */
  18162. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  18163. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa public key encoded */
  18164. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  18165. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  18166. #ifdef WOLFSSL_CERT_EXT
  18167. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  18168. byte akid[MAX_KID_SZ
  18169. #ifdef WOLFSSL_AKID_NAME
  18170. + sizeof(CertName) + CTC_SERIAL_SIZE
  18171. #endif
  18172. ]; /* Authority Key Identifier extension */
  18173. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  18174. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  18175. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18176. byte nsCertType[MAX_NSCERTTYPE_SZ]; /* Extended Key Usage extension */
  18177. #endif
  18178. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  18179. byte crlInfo[CTC_MAX_CRLINFO_SZ]; /* CRL Distribution Points */
  18180. #endif
  18181. #ifdef WOLFSSL_CERT_REQ
  18182. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  18183. #endif
  18184. #ifdef WOLFSSL_ALT_NAMES
  18185. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  18186. #endif
  18187. int sizeSz; /* encoded size length */
  18188. int versionSz; /* encoded version length */
  18189. int serialSz; /* encoded serial length */
  18190. int sigAlgoSz; /* encoded sig algo length */
  18191. int issuerSz; /* encoded issuer length */
  18192. int subjectSz; /* encoded subject length */
  18193. int validitySz; /* encoded validity length */
  18194. int publicKeySz; /* encoded public key length */
  18195. int caSz; /* encoded CA extension length */
  18196. #ifdef WOLFSSL_CERT_EXT
  18197. int skidSz; /* encoded SKID extension length */
  18198. int akidSz; /* encoded SKID extension length */
  18199. int keyUsageSz; /* encoded KeyUsage extension length */
  18200. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  18201. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  18202. int nsCertTypeSz; /* encoded Netscape Certifcate Type
  18203. * extension length */
  18204. #endif
  18205. int certPoliciesSz; /* encoded CertPolicies extension length*/
  18206. int crlInfoSz; /* encoded CRL Dist Points length */
  18207. #endif
  18208. #ifdef WOLFSSL_ALT_NAMES
  18209. int altNamesSz; /* encoded AltNames extension length */
  18210. #endif
  18211. int extensionsSz; /* encoded extensions total length */
  18212. int total; /* total encoded lengths */
  18213. #ifdef WOLFSSL_CERT_REQ
  18214. int attribSz;
  18215. #endif
  18216. } DerCert;
  18217. #ifdef WOLFSSL_CERT_REQ
  18218. #ifndef WOLFSSL_ASN_TEMPLATE
  18219. /* Write a set header to output */
  18220. static word32 SetPrintableString(word32 len, byte* output)
  18221. {
  18222. output[0] = ASN_PRINTABLE_STRING;
  18223. return SetLength(len, output + 1) + 1;
  18224. }
  18225. static word32 SetUTF8String(word32 len, byte* output)
  18226. {
  18227. output[0] = ASN_UTF8STRING;
  18228. return SetLength(len, output + 1) + 1;
  18229. }
  18230. #endif
  18231. #endif /* WOLFSSL_CERT_REQ */
  18232. #ifndef WOLFSSL_CERT_GEN_CACHE
  18233. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  18234. static
  18235. #endif
  18236. void wc_SetCert_Free(Cert* cert)
  18237. {
  18238. if (cert != NULL) {
  18239. cert->der = NULL;
  18240. if (cert->decodedCert) {
  18241. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  18242. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  18243. cert->decodedCert = NULL;
  18244. }
  18245. }
  18246. }
  18247. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz)
  18248. {
  18249. int ret;
  18250. if (cert == NULL) {
  18251. ret = BAD_FUNC_ARG;
  18252. }
  18253. else {
  18254. /* Allocate DecodedCert struct and Zero */
  18255. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  18256. DYNAMIC_TYPE_DCERT);
  18257. if (cert->decodedCert == NULL) {
  18258. ret = MEMORY_E;
  18259. }
  18260. else {
  18261. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  18262. InitDecodedCert((DecodedCert*)cert->decodedCert, der, derSz,
  18263. cert->heap);
  18264. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  18265. CERT_TYPE, 0, NULL);
  18266. if (ret >= 0) {
  18267. cert->der = (byte*)der;
  18268. }
  18269. else {
  18270. wc_SetCert_Free(cert);
  18271. }
  18272. }
  18273. }
  18274. return ret;
  18275. }
  18276. #endif /* WOLFSSL_CERT_GEN */
  18277. #ifdef HAVE_ECC
  18278. #ifdef WOLFSSL_ASN_TEMPLATE
  18279. /* ASN.1 template for ECC public key (SubjectPublicKeyInfo).
  18280. * RFC 5480, 2 - Subject Public Key Information Fields
  18281. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  18282. * X9.62 ECC point format.
  18283. * See ASN.1 template 'eccSpecifiedASN' for specifiedCurve.
  18284. */
  18285. static const ASNItem eccPublicKeyASN[] = {
  18286. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18287. /* AlgorithmIdentifier */
  18288. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18289. /* algorithm */
  18290. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  18291. /* namedCurve */
  18292. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  18293. /* specifiedCurve - explicit parameters */
  18294. /* 4 */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  18295. /* */
  18296. /* 5 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18297. };
  18298. /* Number of items in ASN.1 template for ECC public key. */
  18299. #define eccPublicKeyASN_Length (sizeof(eccPublicKeyASN) / sizeof(ASNItem))
  18300. #endif /* WOLFSSL_ASN_TEMPLATE */
  18301. #endif /* HAVE_ECC */
  18302. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  18303. /* Encode public ECC key in DER format.
  18304. *
  18305. * RFC 5480, 2 - Subject Public Key Information Fields
  18306. * 2.1.1 - Unrestricted Algorithm Identifier and Parameters
  18307. * X9.62 ECC point format.
  18308. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  18309. *
  18310. * @param [out] output Buffer to put encoded data in.
  18311. * @param [in] key ECC key object.
  18312. * @param [in] outLen Size of buffer in bytes.
  18313. * @param [in] with_header Whether to use SubjectPublicKeyInfo format.
  18314. * @return Size of encoded data in bytes on success.
  18315. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  18316. * @return MEMORY_E when dynamic memory allocation failed.
  18317. */
  18318. static int SetEccPublicKey(byte* output, ecc_key* key, int outLen,
  18319. int with_header)
  18320. {
  18321. #ifndef WOLFSSL_ASN_TEMPLATE
  18322. byte bitString[1 + MAX_LENGTH_SZ + 1];
  18323. int algoSz;
  18324. int curveSz;
  18325. int bitStringSz;
  18326. int idx;
  18327. word32 pubSz = ECC_BUFSIZE;
  18328. #ifdef WOLFSSL_SMALL_STACK
  18329. byte* algo = NULL;
  18330. byte* curve = NULL;
  18331. byte* pub;
  18332. #else
  18333. byte algo[MAX_ALGO_SZ];
  18334. byte curve[MAX_ALGO_SZ];
  18335. byte pub[ECC_BUFSIZE];
  18336. #endif
  18337. int ret;
  18338. (void)outLen;
  18339. #ifdef WOLFSSL_SMALL_STACK
  18340. pub = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18341. if (pub == NULL)
  18342. return MEMORY_E;
  18343. #endif
  18344. #if defined(HAVE_SELFTEST) || defined(HAVE_FIPS)
  18345. /* older version of ecc.c can not handle dp being NULL */
  18346. if (key != NULL && key->dp == NULL) {
  18347. ret = BAD_FUNC_ARG;
  18348. }
  18349. else {
  18350. PRIVATE_KEY_UNLOCK();
  18351. ret = wc_ecc_export_x963(key, pub, &pubSz);
  18352. PRIVATE_KEY_LOCK();
  18353. }
  18354. #else
  18355. ret = wc_ecc_export_x963(key, pub, &pubSz);
  18356. #endif
  18357. if (ret != 0) {
  18358. #ifdef WOLFSSL_SMALL_STACK
  18359. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18360. #endif
  18361. return ret;
  18362. }
  18363. /* headers */
  18364. if (with_header) {
  18365. #ifdef WOLFSSL_SMALL_STACK
  18366. curve = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18367. if (curve == NULL) {
  18368. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18369. return MEMORY_E;
  18370. }
  18371. #endif
  18372. curveSz = SetCurve(key, curve);
  18373. if (curveSz <= 0) {
  18374. #ifdef WOLFSSL_SMALL_STACK
  18375. XFREE(curve, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18376. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18377. #endif
  18378. return curveSz;
  18379. }
  18380. #ifdef WOLFSSL_SMALL_STACK
  18381. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18382. if (algo == NULL) {
  18383. XFREE(curve, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18384. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18385. return MEMORY_E;
  18386. }
  18387. #endif
  18388. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, curveSz);
  18389. bitStringSz = SetBitString(pubSz, 0, bitString);
  18390. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, output);
  18391. /* algo */
  18392. if (output)
  18393. XMEMCPY(output + idx, algo, algoSz);
  18394. idx += algoSz;
  18395. /* curve */
  18396. if (output)
  18397. XMEMCPY(output + idx, curve, curveSz);
  18398. idx += curveSz;
  18399. /* bit string */
  18400. if (output)
  18401. XMEMCPY(output + idx, bitString, bitStringSz);
  18402. idx += bitStringSz;
  18403. }
  18404. else
  18405. idx = 0;
  18406. /* pub */
  18407. if (output)
  18408. XMEMCPY(output + idx, pub, pubSz);
  18409. idx += pubSz;
  18410. #ifdef WOLFSSL_SMALL_STACK
  18411. if (with_header) {
  18412. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18413. XFREE(curve, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18414. }
  18415. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  18416. #endif
  18417. return idx;
  18418. #else
  18419. word32 pubSz = 0;
  18420. int sz = 0;
  18421. int ret = 0;
  18422. /* Check key validity. */
  18423. if ((key == NULL) || (key->dp == NULL)) {
  18424. ret = BAD_FUNC_ARG;
  18425. }
  18426. if (ret == 0) {
  18427. /* Calculate the size of the encoded public point. */
  18428. PRIVATE_KEY_UNLOCK();
  18429. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  18430. PRIVATE_KEY_LOCK();
  18431. /* LENGTH_ONLY_E on success. */
  18432. if (ret == LENGTH_ONLY_E) {
  18433. ret = 0;
  18434. }
  18435. }
  18436. if ((ret == 0) && with_header) {
  18437. /* Including SubjectPublicKeyInfo header. */
  18438. DECL_ASNSETDATA(dataASN, eccPublicKeyASN_Length);
  18439. CALLOC_ASNSETDATA(dataASN, eccPublicKeyASN_Length, ret, key->heap);
  18440. if (ret == 0) {
  18441. /* Set the key type OID. */
  18442. SetASN_OID(&dataASN[2], ECDSAk, oidKeyType);
  18443. /* Set the curve OID. */
  18444. SetASN_Buffer(&dataASN[3], key->dp->oid, key->dp->oidSz);
  18445. /* Don't try to write out explicit parameters. */
  18446. dataASN[4].noOut = 1;
  18447. /* Set size of public point to ensure space is made for it. */
  18448. SetASN_Buffer(&dataASN[5], NULL, pubSz);
  18449. /* Calculate size of ECC public key. */
  18450. ret = SizeASN_Items(eccPublicKeyASN, dataASN,
  18451. eccPublicKeyASN_Length, &sz);
  18452. }
  18453. /* Check buffer, if passed in, is big enough for encoded data. */
  18454. if ((ret == 0) && (output != NULL) && (sz > outLen)) {
  18455. ret = BUFFER_E;
  18456. }
  18457. if ((ret == 0) && (output != NULL)) {
  18458. /* Encode ECC public key. */
  18459. SetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length,
  18460. output);
  18461. /* Skip to where public point is to be encoded. */
  18462. output += sz - pubSz;
  18463. }
  18464. FREE_ASNSETDATA(dataASN, key->heap);
  18465. }
  18466. else if ((ret == 0) && (output != NULL) && (pubSz > (word32)outLen)) {
  18467. ret = BUFFER_E;
  18468. }
  18469. else {
  18470. /* Total size is the public point size. */
  18471. sz = pubSz;
  18472. }
  18473. if ((ret == 0) && (output != NULL)) {
  18474. /* Encode public point. */
  18475. PRIVATE_KEY_UNLOCK();
  18476. ret = wc_ecc_export_x963(key, output, &pubSz);
  18477. PRIVATE_KEY_LOCK();
  18478. }
  18479. if (ret == 0) {
  18480. /* Return the size of the encoding. */
  18481. ret = sz;
  18482. }
  18483. return ret;
  18484. #endif
  18485. }
  18486. /* Encode the public part of an ECC key in a DER.
  18487. *
  18488. * Pass NULL for output to get the size of the encoding.
  18489. *
  18490. * @param [in] key ECC key object.
  18491. * @param [out] output Buffer to hold DER encoding.
  18492. * @param [in] inLen Size of buffer in bytes.
  18493. * @param [in] with_AlgCurve Whether to use SubjectPublicKeyInfo format.
  18494. * @return Size of encoded data in bytes on success.
  18495. * @return BAD_FUNC_ARG when key or key's parameters is NULL.
  18496. * @return MEMORY_E when dynamic memory allocation failed.
  18497. */
  18498. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  18499. int with_AlgCurve)
  18500. {
  18501. #ifndef WOLFSSL_ASN_TEMPLATE
  18502. word32 infoSz = 0;
  18503. word32 keySz = 0;
  18504. int ret;
  18505. if (key == NULL) {
  18506. return BAD_FUNC_ARG;
  18507. }
  18508. if (with_AlgCurve) {
  18509. /* buffer space for algorithm/curve */
  18510. infoSz += MAX_SEQ_SZ;
  18511. infoSz += 2 * MAX_ALGO_SZ;
  18512. /* buffer space for public key sequence */
  18513. infoSz += MAX_SEQ_SZ;
  18514. infoSz += TRAILING_ZERO;
  18515. }
  18516. #if defined(HAVE_SELFTEST) || defined(HAVE_FIPS)
  18517. /* older version of ecc.c can not handle dp being NULL */
  18518. if (key->dp == NULL) {
  18519. keySz = 1 + 2 * MAX_ECC_BYTES;
  18520. ret = LENGTH_ONLY_E;
  18521. }
  18522. else {
  18523. PRIVATE_KEY_UNLOCK();
  18524. ret = wc_ecc_export_x963(key, NULL, &keySz);
  18525. PRIVATE_KEY_LOCK();
  18526. }
  18527. #else
  18528. ret = wc_ecc_export_x963(key, NULL, &keySz);
  18529. #endif
  18530. if (ret != LENGTH_ONLY_E) {
  18531. WOLFSSL_MSG("Error in getting ECC public key size");
  18532. return ret;
  18533. }
  18534. /* if output null then just return size */
  18535. if (output == NULL) {
  18536. return keySz + infoSz;
  18537. }
  18538. if (inLen < keySz + infoSz) {
  18539. return BUFFER_E;
  18540. }
  18541. #endif
  18542. return SetEccPublicKey(output, key, inLen, with_AlgCurve);
  18543. }
  18544. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  18545. {
  18546. #ifndef WOLFSSL_ASN_TEMPLATE
  18547. return wc_EccPublicKeyToDer(key, NULL, 0, with_AlgCurve);
  18548. #else
  18549. return SetEccPublicKey(NULL, key, 0, with_AlgCurve);
  18550. #endif
  18551. }
  18552. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  18553. #ifdef WOLFSSL_ASN_TEMPLATE
  18554. #if defined(WC_ENABLE_ASYM_KEY_EXPORT) || defined(WC_ENABLE_ASYM_KEY_IMPORT)
  18555. /* ASN.1 template for Ed25519 and Ed448 public key (SubkectPublicKeyInfo).
  18556. * RFC 8410, 4 - Subject Public Key Fields
  18557. */
  18558. static const ASNItem edPubKeyASN[] = {
  18559. /* SubjectPublicKeyInfo */
  18560. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  18561. /* AlgorithmIdentifier */
  18562. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  18563. /* Ed25519/Ed448 OID */
  18564. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  18565. /* Public key stream */
  18566. /* 3 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  18567. };
  18568. /* Number of items in ASN.1 template for Ed25519 and Ed448 public key. */
  18569. #define edPubKeyASN_Length (sizeof(edPubKeyASN) / sizeof(ASNItem))
  18570. #endif /* WC_ENABLE_ASYM_KEY_EXPORT || WC_ENABLE_ASYM_KEY_IMPORT */
  18571. #endif /* WOLFSSL_ASN_TEMPLATE */
  18572. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  18573. /* Build ASN.1 formatted public key based on RFC 8410
  18574. *
  18575. * Pass NULL for output to get the size of the encoding.
  18576. *
  18577. * @param [in] pubKey public key buffer
  18578. * @param [in] pubKeyLen public ket buffer length
  18579. * @param [out] output Buffer to put encoded data in (optional)
  18580. * @param [in] outLen Size of buffer in bytes
  18581. * @param [in] keyType is "enum Key_Sum" like ED25519k
  18582. * @param [in] withHeader Whether to include SubjectPublicKeyInfo around key.
  18583. * @return Size of encoded data in bytes on success
  18584. * @return BAD_FUNC_ARG when key is NULL.
  18585. * @return MEMORY_E when dynamic memory allocation failed.
  18586. */
  18587. static int SetAsymKeyDerPublic(const byte* pubKey, word32 pubKeyLen,
  18588. byte* output, word32 outLen, int keyType, int withHeader)
  18589. {
  18590. int ret = 0;
  18591. #ifndef WOLFSSL_ASN_TEMPLATE
  18592. word32 idx = 0;
  18593. word32 seqDataSz = 0;
  18594. word32 sz;
  18595. #else
  18596. int sz = 0;
  18597. DECL_ASNSETDATA(dataASN, edPubKeyASN_Length);
  18598. #endif
  18599. if (pubKey == NULL) {
  18600. return BAD_FUNC_ARG;
  18601. }
  18602. #ifndef WOLFSSL_ASN_TEMPLATE
  18603. /* calculate size */
  18604. if (withHeader) {
  18605. word32 algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  18606. word32 bitStringSz = SetBitString(pubKeyLen, 0, NULL);
  18607. seqDataSz = algoSz + bitStringSz + pubKeyLen;
  18608. sz = SetSequence(seqDataSz, NULL) + seqDataSz;
  18609. }
  18610. else {
  18611. sz = pubKeyLen;
  18612. }
  18613. /* checkout output size */
  18614. if (output != NULL && sz > outLen) {
  18615. ret = BUFFER_E;
  18616. }
  18617. /* headers */
  18618. if (ret == 0 && output != NULL && withHeader) {
  18619. /* sequence */
  18620. idx = SetSequence(seqDataSz, output);
  18621. /* algo */
  18622. idx += SetAlgoID(keyType, output + idx, oidKeyType, 0);
  18623. /* bit string */
  18624. idx += SetBitString(pubKeyLen, 0, output + idx);
  18625. }
  18626. if (ret == 0 && output != NULL) {
  18627. /* pub */
  18628. XMEMCPY(output + idx, pubKey, pubKeyLen);
  18629. idx += pubKeyLen;
  18630. sz = idx;
  18631. }
  18632. if (ret == 0) {
  18633. ret = sz;
  18634. }
  18635. #else
  18636. if (withHeader) {
  18637. CALLOC_ASNSETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  18638. if (ret == 0) {
  18639. /* Set the OID. */
  18640. SetASN_OID(&dataASN[2], keyType, oidKeyType);
  18641. /* Leave space for public point. */
  18642. SetASN_Buffer(&dataASN[3], NULL, pubKeyLen);
  18643. /* Calculate size of public key encoding. */
  18644. ret = SizeASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, &sz);
  18645. }
  18646. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  18647. ret = BUFFER_E;
  18648. }
  18649. if ((ret == 0) && (output != NULL)) {
  18650. /* Encode public key. */
  18651. SetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, output);
  18652. /* Set location to encode public point. */
  18653. output = (byte*)dataASN[3].data.buffer.data;
  18654. }
  18655. FREE_ASNSETDATA(dataASN, NULL);
  18656. }
  18657. else if ((output != NULL) && (pubKeyLen > outLen)) {
  18658. ret = BUFFER_E;
  18659. }
  18660. else if (ret == 0) {
  18661. sz = pubKeyLen;
  18662. }
  18663. if ((ret == 0) && (output != NULL)) {
  18664. /* Put public key into space provided. */
  18665. XMEMCPY(output, pubKey, pubKeyLen);
  18666. }
  18667. if (ret == 0) {
  18668. ret = sz;
  18669. }
  18670. #endif /* WOLFSSL_ASN_TEMPLATE */
  18671. return ret;
  18672. }
  18673. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  18674. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  18675. /* Encode the public part of an Ed25519 key in DER.
  18676. *
  18677. * Pass NULL for output to get the size of the encoding.
  18678. *
  18679. * @param [in] key Ed25519 key object.
  18680. * @param [out] output Buffer to put encoded data in.
  18681. * @param [in] outLen Size of buffer in bytes.
  18682. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  18683. * @return Size of encoded data in bytes on success.
  18684. * @return BAD_FUNC_ARG when key is NULL.
  18685. * @return MEMORY_E when dynamic memory allocation failed.
  18686. */
  18687. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  18688. int withAlg)
  18689. {
  18690. int ret;
  18691. byte pubKey[ED25519_PUB_KEY_SIZE];
  18692. word32 pubKeyLen = (word32)sizeof(pubKey);
  18693. if (key == NULL || output == NULL) {
  18694. return BAD_FUNC_ARG;
  18695. }
  18696. ret = wc_ed25519_export_public(key, pubKey, &pubKeyLen);
  18697. if (ret == 0) {
  18698. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  18699. ED25519k, withAlg);
  18700. }
  18701. return ret;
  18702. }
  18703. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  18704. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  18705. /* Encode the public part of an Ed448 key in DER.
  18706. *
  18707. * Pass NULL for output to get the size of the encoding.
  18708. *
  18709. * @param [in] key Ed448 key object.
  18710. * @param [out] output Buffer to put encoded data in.
  18711. * @param [in] outLen Size of buffer in bytes.
  18712. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  18713. * @return Size of encoded data in bytes on success.
  18714. * @return BAD_FUNC_ARG when key is NULL.
  18715. * @return MEMORY_E when dynamic memory allocation failed.
  18716. */
  18717. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  18718. int withAlg)
  18719. {
  18720. int ret;
  18721. byte pubKey[ED448_PUB_KEY_SIZE];
  18722. word32 pubKeyLen = (word32)sizeof(pubKey);
  18723. if (key == NULL || output == NULL) {
  18724. return BAD_FUNC_ARG;
  18725. }
  18726. ret = wc_ed448_export_public(key, pubKey, &pubKeyLen);
  18727. if (ret == 0) {
  18728. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  18729. ED448k, withAlg);
  18730. }
  18731. return ret;
  18732. }
  18733. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  18734. #if defined(HAVE_LIBOQS)
  18735. /* Encode the public part of an Falcon key in DER.
  18736. *
  18737. * Pass NULL for output to get the size of the encoding.
  18738. *
  18739. * @param [in] key Falcon key object.
  18740. * @param [out] output Buffer to put encoded data in.
  18741. * @param [in] outLen Size of buffer in bytes.
  18742. * @param [in] withAlg Whether to use SubjectPublicKeyInfo format.
  18743. * @return Size of encoded data in bytes on success.
  18744. * @return BAD_FUNC_ARG when key is NULL.
  18745. * @return MEMORY_E when dynamic memory allocation failed.
  18746. */
  18747. int wc_Falcon_PublicKeyToDer(falcon_key* key, byte* output, word32 inLen,
  18748. int withAlg)
  18749. {
  18750. int ret;
  18751. byte pubKey[FALCON_MAX_PUB_KEY_SIZE];
  18752. word32 pubKeyLen = (word32)sizeof(pubKey);
  18753. int keytype = 0;
  18754. if (key == NULL || output == NULL) {
  18755. return BAD_FUNC_ARG;
  18756. }
  18757. if (key->level == 1) {
  18758. keytype = FALCON_LEVEL1k;
  18759. }
  18760. else if (key->level == 5) {
  18761. keytype = FALCON_LEVEL5k;
  18762. }
  18763. else {
  18764. return BAD_FUNC_ARG;
  18765. }
  18766. ret = wc_falcon_export_public(key, pubKey, &pubKeyLen);
  18767. if (ret == 0) {
  18768. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen, keytype,
  18769. withAlg);
  18770. }
  18771. return ret;
  18772. }
  18773. #endif /* HAVE_LIBOQS */
  18774. #ifdef WOLFSSL_CERT_GEN
  18775. #ifndef NO_ASN_TIME
  18776. static WC_INLINE byte itob(int number)
  18777. {
  18778. return (byte)number + 0x30;
  18779. }
  18780. /* write time to output, format */
  18781. static void SetTime(struct tm* date, byte* output)
  18782. {
  18783. int i = 0;
  18784. output[i++] = itob((date->tm_year % 10000) / 1000);
  18785. output[i++] = itob((date->tm_year % 1000) / 100);
  18786. output[i++] = itob((date->tm_year % 100) / 10);
  18787. output[i++] = itob( date->tm_year % 10);
  18788. output[i++] = itob(date->tm_mon / 10);
  18789. output[i++] = itob(date->tm_mon % 10);
  18790. output[i++] = itob(date->tm_mday / 10);
  18791. output[i++] = itob(date->tm_mday % 10);
  18792. output[i++] = itob(date->tm_hour / 10);
  18793. output[i++] = itob(date->tm_hour % 10);
  18794. output[i++] = itob(date->tm_min / 10);
  18795. output[i++] = itob(date->tm_min % 10);
  18796. output[i++] = itob(date->tm_sec / 10);
  18797. output[i++] = itob(date->tm_sec % 10);
  18798. output[i] = 'Z'; /* Zulu profile */
  18799. }
  18800. #endif
  18801. #ifdef WOLFSSL_ALT_NAMES
  18802. #ifndef WOLFSSL_ASN_TEMPLATE
  18803. /* Copy Dates from cert, return bytes written */
  18804. static int CopyValidity(byte* output, Cert* cert)
  18805. {
  18806. int seqSz;
  18807. WOLFSSL_ENTER("CopyValidity");
  18808. /* headers and output */
  18809. seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
  18810. if (output) {
  18811. XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
  18812. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  18813. cert->afterDateSz);
  18814. }
  18815. return seqSz + cert->beforeDateSz + cert->afterDateSz;
  18816. }
  18817. #endif /* !WOLFSSL_ASN_TEMPLATE */
  18818. #endif
  18819. /* Get Which Name from index */
  18820. const char* GetOneCertName(CertName* name, int idx)
  18821. {
  18822. switch (idx) {
  18823. case 0:
  18824. return name->country;
  18825. case 1:
  18826. return name->state;
  18827. case 2:
  18828. return name->street;
  18829. case 3:
  18830. return name->locality;
  18831. case 4:
  18832. return name->sur;
  18833. case 5:
  18834. return name->org;
  18835. case 6:
  18836. return name->unit;
  18837. case 7:
  18838. return name->commonName;
  18839. case 8:
  18840. return name->serialDev;
  18841. case 9:
  18842. return name->postalCode;
  18843. case 10:
  18844. #ifdef WOLFSSL_CERT_EXT
  18845. return name->busCat;
  18846. case 11:
  18847. #endif
  18848. return name->email;
  18849. default:
  18850. return NULL;
  18851. }
  18852. }
  18853. /* Get Which Name Encoding from index */
  18854. static char GetNameType(CertName* name, int idx)
  18855. {
  18856. switch (idx) {
  18857. case 0:
  18858. return name->countryEnc;
  18859. case 1:
  18860. return name->stateEnc;
  18861. case 2:
  18862. return name->postalCodeEnc;
  18863. case 3:
  18864. return name->localityEnc;
  18865. case 4:
  18866. return name->surEnc;
  18867. case 5:
  18868. return name->orgEnc;
  18869. case 6:
  18870. return name->unitEnc;
  18871. case 7:
  18872. return name->commonNameEnc;
  18873. case 8:
  18874. return name->serialDevEnc;
  18875. case 9:
  18876. return name->postalCodeEnc;
  18877. case 10:
  18878. #ifdef WOLFSSL_CERT_EXT
  18879. return name->busCatEnc;
  18880. case 11:
  18881. #endif
  18882. /* FALL THROUGH */
  18883. /* The last index, email name, does not have encoding type.
  18884. The empty case here is to keep track of it for future reference. */
  18885. default:
  18886. return 0;
  18887. }
  18888. }
  18889. /* Get ASN Name from index */
  18890. byte GetCertNameId(int idx)
  18891. {
  18892. switch (idx) {
  18893. case 0:
  18894. return ASN_COUNTRY_NAME;
  18895. case 1:
  18896. return ASN_STATE_NAME;
  18897. case 2:
  18898. return ASN_STREET_ADDR;
  18899. case 3:
  18900. return ASN_LOCALITY_NAME;
  18901. case 4:
  18902. return ASN_SUR_NAME;
  18903. case 5:
  18904. return ASN_ORG_NAME;
  18905. case 6:
  18906. return ASN_ORGUNIT_NAME;
  18907. case 7:
  18908. return ASN_COMMON_NAME;
  18909. case 8:
  18910. return ASN_SERIAL_NUMBER;
  18911. case 9:
  18912. return ASN_POSTAL_CODE;
  18913. case 10:
  18914. #ifdef WOLFSSL_CERT_EXT
  18915. return ASN_BUS_CAT;
  18916. case 11:
  18917. #endif
  18918. return ASN_EMAIL_NAME;
  18919. default:
  18920. return 0;
  18921. }
  18922. }
  18923. #ifndef WOLFSSL_ASN_TEMPLATE
  18924. /*
  18925. Extensions ::= SEQUENCE OF Extension
  18926. Extension ::= SEQUENCE {
  18927. extnId OBJECT IDENTIFIER,
  18928. critical BOOLEAN DEFAULT FALSE,
  18929. extnValue OCTET STRING }
  18930. */
  18931. /* encode all extensions, return total bytes written */
  18932. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  18933. const byte* ext, int extSz)
  18934. {
  18935. if (out == NULL || IdxInOut == NULL || ext == NULL)
  18936. return BAD_FUNC_ARG;
  18937. if (outSz < (word32)(*IdxInOut+extSz))
  18938. return BUFFER_E;
  18939. XMEMCPY(&out[*IdxInOut], ext, extSz); /* extensions */
  18940. *IdxInOut += extSz;
  18941. return *IdxInOut;
  18942. }
  18943. /* encode extensions header, return total bytes written */
  18944. static int SetExtensionsHeader(byte* out, word32 outSz, int extSz)
  18945. {
  18946. byte sequence[MAX_SEQ_SZ];
  18947. byte len[MAX_LENGTH_SZ];
  18948. int seqSz, lenSz, idx = 0;
  18949. if (out == NULL)
  18950. return BAD_FUNC_ARG;
  18951. if (outSz < 3)
  18952. return BUFFER_E;
  18953. seqSz = SetSequence(extSz, sequence);
  18954. /* encode extensions length provided */
  18955. lenSz = SetLength(extSz+seqSz, len);
  18956. if (outSz < (word32)(lenSz+seqSz+1))
  18957. return BUFFER_E;
  18958. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  18959. XMEMCPY(&out[idx], len, lenSz); /* length */
  18960. idx += lenSz;
  18961. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  18962. idx += seqSz;
  18963. return idx;
  18964. }
  18965. /* encode CA basic constraint true, return total bytes written */
  18966. static int SetCa(byte* out, word32 outSz)
  18967. {
  18968. const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  18969. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
  18970. if (out == NULL)
  18971. return BAD_FUNC_ARG;
  18972. if (outSz < sizeof(ca))
  18973. return BUFFER_E;
  18974. XMEMCPY(out, ca, sizeof(ca));
  18975. return (int)sizeof(ca);
  18976. }
  18977. #endif
  18978. #ifdef WOLFSSL_CERT_EXT
  18979. #ifndef WOLFSSL_ASN_TEMPLATE
  18980. /* encode OID and associated value, return total bytes written */
  18981. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  18982. byte *in, word32 inSz)
  18983. {
  18984. int idx = 0;
  18985. if (out == NULL || oid == NULL || in == NULL)
  18986. return BAD_FUNC_ARG;
  18987. if (outSz < 3)
  18988. return BUFFER_E;
  18989. /* sequence, + 1 => byte to put value size */
  18990. idx = SetSequence(inSz + oidSz + 1, out);
  18991. if ((idx + inSz + oidSz + 1) > outSz)
  18992. return BUFFER_E;
  18993. XMEMCPY(out+idx, oid, oidSz);
  18994. idx += oidSz;
  18995. out[idx++] = (byte)inSz;
  18996. XMEMCPY(out+idx, in, inSz);
  18997. return (idx+inSz);
  18998. }
  18999. /* encode Subject Key Identifier, return total bytes written
  19000. * RFC5280 : non-critical */
  19001. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  19002. {
  19003. byte skid_len[1 + MAX_LENGTH_SZ];
  19004. byte skid_enc_len[MAX_LENGTH_SZ];
  19005. int idx = 0, skid_lenSz, skid_enc_lenSz;
  19006. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  19007. if (output == NULL || input == NULL)
  19008. return BAD_FUNC_ARG;
  19009. /* Octet String header */
  19010. skid_lenSz = SetOctetString(length, skid_len);
  19011. /* length of encoded value */
  19012. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  19013. if (outSz < 3)
  19014. return BUFFER_E;
  19015. idx = SetSequence(length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz,
  19016. output);
  19017. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  19018. return BUFFER_E;
  19019. /* put oid */
  19020. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  19021. idx += sizeof(skid_oid);
  19022. /* put encoded len */
  19023. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  19024. idx += skid_enc_lenSz;
  19025. /* put octet header */
  19026. XMEMCPY(output+idx, skid_len, skid_lenSz);
  19027. idx += skid_lenSz;
  19028. /* put value */
  19029. XMEMCPY(output+idx, input, length);
  19030. idx += length;
  19031. return idx;
  19032. }
  19033. /* encode Authority Key Identifier, return total bytes written
  19034. * RFC5280 : non-critical */
  19035. static int SetAKID(byte* output, word32 outSz, byte *input, word32 length,
  19036. byte rawAkid)
  19037. {
  19038. int enc_valSz, inSeqSz;
  19039. byte enc_val_buf[MAX_KID_SZ];
  19040. byte* enc_val;
  19041. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23 };
  19042. const byte akid_cs[] = { 0x80 };
  19043. word32 idx;
  19044. (void)rawAkid;
  19045. if (output == NULL || input == NULL)
  19046. return BAD_FUNC_ARG;
  19047. #ifdef WOLFSSL_AKID_NAME
  19048. if (rawAkid) {
  19049. enc_val = input;
  19050. enc_valSz = length;
  19051. }
  19052. else
  19053. #endif
  19054. {
  19055. enc_val = enc_val_buf;
  19056. enc_valSz = length + 3 + sizeof(akid_cs);
  19057. if (enc_valSz > (int)sizeof(enc_val_buf))
  19058. return BAD_FUNC_ARG;
  19059. /* sequence for ContentSpec & value */
  19060. enc_valSz = SetOidValue(enc_val, enc_valSz, akid_cs, sizeof(akid_cs),
  19061. input, length);
  19062. if (enc_valSz <= 0)
  19063. return enc_valSz;
  19064. }
  19065. /* The size of the extension sequence contents */
  19066. inSeqSz = sizeof(akid_oid) + SetOctetString(enc_valSz, NULL) +
  19067. enc_valSz;
  19068. if (SetSequence(inSeqSz, NULL) + inSeqSz > outSz)
  19069. return BAD_FUNC_ARG;
  19070. /* Write out the sequence header */
  19071. idx = SetSequence(inSeqSz, output);
  19072. /* Write out OID */
  19073. XMEMCPY(output + idx, akid_oid, sizeof(akid_oid));
  19074. idx += sizeof(akid_oid);
  19075. /* Write out AKID */
  19076. idx += SetOctetString(enc_valSz, output + idx);
  19077. XMEMCPY(output + idx, enc_val, enc_valSz);
  19078. return idx + enc_valSz;
  19079. }
  19080. /* encode Key Usage, return total bytes written
  19081. * RFC5280 : critical */
  19082. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  19083. {
  19084. byte ku[5];
  19085. int idx;
  19086. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  19087. 0x01, 0x01, 0xff, 0x04};
  19088. if (output == NULL)
  19089. return BAD_FUNC_ARG;
  19090. idx = SetBitString16Bit(input, ku);
  19091. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  19092. ku, idx);
  19093. }
  19094. static int SetOjectIdValue(byte* output, word32 outSz, int* idx,
  19095. const byte* oid, word32 oidSz)
  19096. {
  19097. /* verify room */
  19098. if (*idx + 2 + oidSz >= outSz)
  19099. return ASN_PARSE_E;
  19100. *idx += SetObjectId(oidSz, &output[*idx]);
  19101. XMEMCPY(&output[*idx], oid, oidSz);
  19102. *idx += oidSz;
  19103. return 0;
  19104. }
  19105. #endif
  19106. #ifdef WOLFSSL_ASN_TEMPLATE
  19107. /* ASN.1 template for extended key usage.
  19108. * X.509: RFC 5280, 4.2.12 - Extended Key Usage
  19109. * Dynamic creation of template for encoding.
  19110. */
  19111. static const ASNItem ekuASN[] = {
  19112. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  19113. /* 1 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  19114. };
  19115. /* OIDs corresponding to extended key usage. */
  19116. struct {
  19117. const byte* oid;
  19118. word32 oidSz;
  19119. } ekuOid[] = {
  19120. { extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid) },
  19121. { extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid) },
  19122. { extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid) },
  19123. { extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid) },
  19124. { extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid) },
  19125. { extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid) },
  19126. };
  19127. #define EKU_OID_LO 1
  19128. #define EKU_OID_HI 6
  19129. #endif /* WOLFSSL_ASN_TEMPLATE */
  19130. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  19131. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  19132. {
  19133. #ifndef WOLFSSL_ASN_TEMPLATE
  19134. int idx = 0, oidListSz = 0, totalSz, ret = 0;
  19135. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  19136. if (output == NULL)
  19137. return BAD_FUNC_ARG;
  19138. /* Skip to OID List */
  19139. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  19140. idx = totalSz;
  19141. /* Build OID List */
  19142. /* If any set, then just use it */
  19143. if (input & EXTKEYUSE_ANY) {
  19144. ret |= SetOjectIdValue(output, outSz, &idx,
  19145. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  19146. }
  19147. else {
  19148. if (input & EXTKEYUSE_SERVER_AUTH)
  19149. ret |= SetOjectIdValue(output, outSz, &idx,
  19150. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  19151. if (input & EXTKEYUSE_CLIENT_AUTH)
  19152. ret |= SetOjectIdValue(output, outSz, &idx,
  19153. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  19154. if (input & EXTKEYUSE_CODESIGN)
  19155. ret |= SetOjectIdValue(output, outSz, &idx,
  19156. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  19157. if (input & EXTKEYUSE_EMAILPROT)
  19158. ret |= SetOjectIdValue(output, outSz, &idx,
  19159. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  19160. if (input & EXTKEYUSE_TIMESTAMP)
  19161. ret |= SetOjectIdValue(output, outSz, &idx,
  19162. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  19163. if (input & EXTKEYUSE_OCSP_SIGN)
  19164. ret |= SetOjectIdValue(output, outSz, &idx,
  19165. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  19166. #ifdef WOLFSSL_EKU_OID
  19167. /* iterate through OID values */
  19168. if (input & EXTKEYUSE_USER) {
  19169. int i, sz;
  19170. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  19171. sz = cert->extKeyUsageOIDSz[i];
  19172. if (sz > 0) {
  19173. ret |= SetOjectIdValue(output, outSz, &idx,
  19174. cert->extKeyUsageOID[i], sz);
  19175. }
  19176. }
  19177. }
  19178. #endif /* WOLFSSL_EKU_OID */
  19179. }
  19180. if (ret != 0)
  19181. return ASN_PARSE_E;
  19182. /* Calculate Sizes */
  19183. oidListSz = idx - totalSz;
  19184. totalSz = idx - 2; /* exclude first seq/len (2) */
  19185. /* 1. Seq + Total Len (2) */
  19186. idx = SetSequence(totalSz, output);
  19187. /* 2. Object ID (2) */
  19188. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  19189. idx += sizeof(extkeyusage_oid);
  19190. /* 3. Octet String (2) */
  19191. idx += SetOctetString(totalSz - idx, &output[idx]);
  19192. /* 4. Seq + OidListLen (2) */
  19193. idx += SetSequence(oidListSz, &output[idx]);
  19194. /* 5. Oid List (already set in-place above) */
  19195. idx += oidListSz;
  19196. (void)cert;
  19197. return idx;
  19198. #else
  19199. /* TODO: consider calculating size of OBJECT_IDs, setting length into
  19200. * SEQUENCE, encode SEQUENCE, encode OBJECT_IDs into buffer. */
  19201. ASNSetData* dataASN;
  19202. ASNItem* extKuASN = NULL;
  19203. int asnIdx = 1;
  19204. int cnt = 1 + EKU_OID_HI;
  19205. int i;
  19206. int ret = 0;
  19207. int sz;
  19208. #ifdef WOLFSSL_EKU_OID
  19209. cnt += CTC_MAX_EKU_NB;
  19210. #endif
  19211. /* Allocate memory for dynamic data items. */
  19212. dataASN = (ASNSetData*)XMALLOC(cnt * sizeof(ASNSetData), cert->heap,
  19213. DYNAMIC_TYPE_TMP_BUFFER);
  19214. if (dataASN == NULL) {
  19215. ret = MEMORY_E;
  19216. }
  19217. if (ret == 0) {
  19218. /* Allocate memory for dynamic ASN.1 template. */
  19219. extKuASN = (ASNItem*)XMALLOC(cnt * sizeof(ASNItem), cert->heap,
  19220. DYNAMIC_TYPE_TMP_BUFFER);
  19221. if (extKuASN == NULL) {
  19222. ret = MEMORY_E;
  19223. }
  19224. }
  19225. if (ret == 0) {
  19226. /* Copy Sequence into dynamic ASN.1 template. */
  19227. XMEMCPY(&extKuASN[0], ekuASN, sizeof(ASNItem));
  19228. /* Clear dynamic data. */
  19229. XMEMSET(dataASN, 0, cnt * sizeof(ASNSetData));
  19230. /* Build up the template and data. */
  19231. /* If 'any' set, then just use it. */
  19232. if ((input & EXTKEYUSE_ANY) == EXTKEYUSE_ANY) {
  19233. /* Set template item. */
  19234. XMEMCPY(&extKuASN[1], &ekuASN[1], sizeof(ASNItem));
  19235. /* Set data item. */
  19236. SetASN_Buffer(&dataASN[asnIdx], extExtKeyUsageAnyOid,
  19237. sizeof(extExtKeyUsageAnyOid));
  19238. asnIdx++;
  19239. }
  19240. else {
  19241. /* Step through the flagged purposes. */
  19242. for (i = EKU_OID_LO; i <= EKU_OID_HI; i++) {
  19243. if ((input & (1 << i)) != 0) {
  19244. /* Set template item. */
  19245. XMEMCPY(&extKuASN[asnIdx], &ekuASN[1], sizeof(ASNItem));
  19246. /* Set data item. */
  19247. SetASN_Buffer(&dataASN[asnIdx], ekuOid[i - 1].oid,
  19248. ekuOid[i - 1].oidSz);
  19249. asnIdx++;
  19250. }
  19251. }
  19252. #ifdef WOLFSSL_EKU_OID
  19253. if (input & EXTKEYUSE_USER) {
  19254. /* Iterate through OID values */
  19255. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  19256. int sz = cert->extKeyUsageOIDSz[i];
  19257. if (sz > 0) {
  19258. /* Set template item. */
  19259. XMEMCPY(&extKuASN[asnIdx], &ekuASN[1], sizeof(ASNItem));
  19260. /* Set data item. */
  19261. SetASN_Buffer(&dataASN[asnIdx], cert->extKeyUsageOID[i],
  19262. sz);
  19263. asnIdx++;
  19264. }
  19265. }
  19266. }
  19267. #endif /* WOLFSSL_EKU_OID */
  19268. (void)cert;
  19269. }
  19270. /* Calculate size of encoding. */
  19271. ret = SizeASN_Items(extKuASN, dataASN, asnIdx, &sz);
  19272. }
  19273. /* When buffer to write to, ensure it's big enough. */
  19274. if ((ret == 0) && (output != NULL) && (sz > (int)outSz)) {
  19275. ret = BUFFER_E;
  19276. }
  19277. if ((ret == 0) && (output != NULL)) {
  19278. /* Encode extended key usage. */
  19279. SetASN_Items(extKuASN, dataASN, asnIdx, output);
  19280. }
  19281. if (ret == 0) {
  19282. /* Return the encoding size. */
  19283. ret = sz;
  19284. }
  19285. /* Dispose of allocated data. */
  19286. if (extKuASN != NULL) {
  19287. XFREE(extKuASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  19288. }
  19289. if (dataASN != NULL) {
  19290. XFREE(dataASN, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  19291. }
  19292. return ret;
  19293. #endif
  19294. }
  19295. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  19296. #ifndef WOLFSSL_ASN_TEMPLATE
  19297. static int SetNsCertType(Cert* cert, byte* output, word32 outSz, byte input)
  19298. {
  19299. word32 idx;
  19300. byte unusedBits = 0;
  19301. byte nsCertType = input;
  19302. word32 totalSz;
  19303. word32 bitStrSz;
  19304. const byte nscerttype_oid[] = { 0x06, 0x09, 0x60, 0x86, 0x48, 0x01,
  19305. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  19306. if (cert == NULL || output == NULL ||
  19307. input == 0)
  19308. return BAD_FUNC_ARG;
  19309. totalSz = sizeof(nscerttype_oid);
  19310. /* Get amount of lsb zero's */
  19311. for (;(input & 1) == 0; input >>= 1)
  19312. unusedBits++;
  19313. /* 1 byte of NS Cert Type extension */
  19314. bitStrSz = SetBitString(1, unusedBits, NULL) + 1;
  19315. totalSz += SetOctetString(bitStrSz, NULL) + bitStrSz;
  19316. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  19317. return BAD_FUNC_ARG;
  19318. /* 1. Seq + Total Len */
  19319. idx = SetSequence(totalSz, output);
  19320. /* 2. Object ID */
  19321. XMEMCPY(&output[idx], nscerttype_oid, sizeof(nscerttype_oid));
  19322. idx += sizeof(nscerttype_oid);
  19323. /* 3. Octet String */
  19324. idx += SetOctetString(bitStrSz, &output[idx]);
  19325. /* 4. Bit String */
  19326. idx += SetBitString(1, unusedBits, &output[idx]);
  19327. output[idx++] = nsCertType;
  19328. return idx;
  19329. }
  19330. #endif
  19331. #endif
  19332. #ifndef WOLFSSL_ASN_TEMPLATE
  19333. static int SetCRLInfo(Cert* cert, byte* output, word32 outSz, byte* input,
  19334. int inSz)
  19335. {
  19336. word32 idx;
  19337. word32 totalSz;
  19338. const byte crlinfo_oid[] = { 0x06, 0x03, 0x55, 0x1D, 0x1F };
  19339. if (cert == NULL || output == NULL ||
  19340. input == 0 || inSz <= 0)
  19341. return BAD_FUNC_ARG;
  19342. totalSz = sizeof(crlinfo_oid) + SetOctetString(inSz, NULL) + inSz;
  19343. if (SetSequence(totalSz, NULL) + totalSz > outSz)
  19344. return BAD_FUNC_ARG;
  19345. /* 1. Seq + Total Len */
  19346. idx = SetSequence(totalSz, output);
  19347. /* 2. Object ID */
  19348. XMEMCPY(&output[idx], crlinfo_oid, sizeof(crlinfo_oid));
  19349. idx += sizeof(crlinfo_oid);
  19350. /* 3. Octet String */
  19351. idx += SetOctetString(inSz, &output[idx]);
  19352. /* 4. CRL Info */
  19353. XMEMCPY(&output[idx], input, inSz);
  19354. idx += inSz;
  19355. return idx;
  19356. }
  19357. #endif
  19358. /* encode Certificate Policies, return total bytes written
  19359. * each input value must be ITU-T X.690 formatted : a.b.c...
  19360. * input must be an array of values with a NULL terminated for the latest
  19361. * RFC5280 : non-critical */
  19362. static int SetCertificatePolicies(byte *output,
  19363. word32 outputSz,
  19364. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  19365. word16 nb_certpol,
  19366. void* heap)
  19367. {
  19368. #ifndef WOLFSSL_ASN_TEMPLATE
  19369. byte oid[MAX_OID_SZ];
  19370. byte der_oid[MAX_CERTPOL_NB][MAX_OID_SZ];
  19371. byte out[MAX_CERTPOL_SZ];
  19372. word32 oidSz;
  19373. word32 outSz;
  19374. word32 i = 0;
  19375. word32 der_oidSz[MAX_CERTPOL_NB];
  19376. int ret;
  19377. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  19378. const byte oid_oid[] = { 0x06 };
  19379. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  19380. return BAD_FUNC_ARG;
  19381. for (i = 0; i < nb_certpol; i++) {
  19382. oidSz = sizeof(oid);
  19383. XMEMSET(oid, 0, oidSz);
  19384. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  19385. if (ret != 0)
  19386. return ret;
  19387. /* compute sequence value for the oid */
  19388. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  19389. sizeof(oid_oid), oid, oidSz);
  19390. if (ret <= 0)
  19391. return ret;
  19392. else
  19393. der_oidSz[i] = (word32)ret;
  19394. }
  19395. /* concatenate oid, keep two byte for sequence/size of the created value */
  19396. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  19397. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  19398. outSz += der_oidSz[i];
  19399. }
  19400. /* add sequence */
  19401. ret = SetSequence(outSz-2, out);
  19402. if (ret <= 0)
  19403. return ret;
  19404. /* add Policy OID to compute final value */
  19405. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  19406. out, outSz);
  19407. #else
  19408. int i;
  19409. int ret = 0;
  19410. byte oid[MAX_OID_SZ];
  19411. word32 oidSz;
  19412. word32 sz = 0;
  19413. int piSz;
  19414. if ((input == NULL) || (nb_certpol > MAX_CERTPOL_NB)) {
  19415. ret = BAD_FUNC_ARG;
  19416. }
  19417. /* Put in policyIdentifier but not policyQualifiers. */
  19418. for (i = 0; (ret == 0) && (i < nb_certpol); i++) {
  19419. ASNSetData dataASN[policyInfoASN_Length];
  19420. oidSz = sizeof(oid);
  19421. XMEMSET(oid, 0, oidSz);
  19422. dataASN[2].noOut = 1;
  19423. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  19424. if (ret == 0) {
  19425. XMEMSET(dataASN, 0, sizeof(dataASN));
  19426. SetASN_Buffer(&dataASN[1], oid, oidSz);
  19427. ret = SizeASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  19428. &piSz);
  19429. }
  19430. if ((ret == 0) && (output != NULL) && (sz + piSz > outputSz)) {
  19431. ret = BUFFER_E;
  19432. }
  19433. if (ret == 0) {
  19434. if (output != NULL) {
  19435. SetASN_Items(policyInfoASN, dataASN, policyInfoASN_Length,
  19436. output);
  19437. output += piSz;
  19438. }
  19439. sz += piSz;
  19440. }
  19441. }
  19442. if (ret == 0) {
  19443. ret = sz;
  19444. }
  19445. return ret;
  19446. #endif
  19447. }
  19448. #endif /* WOLFSSL_CERT_EXT */
  19449. #ifdef WOLFSSL_ALT_NAMES
  19450. #ifndef WOLFSSL_ASN_TEMPLATE
  19451. /* encode Alternative Names, return total bytes written */
  19452. static int SetAltNames(byte *output, word32 outSz,
  19453. const byte *input, word32 length)
  19454. {
  19455. byte san_len[1 + MAX_LENGTH_SZ];
  19456. int idx = 0, san_lenSz;
  19457. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  19458. if (output == NULL || input == NULL)
  19459. return BAD_FUNC_ARG;
  19460. if (outSz < length)
  19461. return BUFFER_E;
  19462. /* Octet String header */
  19463. san_lenSz = SetOctetString(length, san_len);
  19464. if (outSz < MAX_SEQ_SZ)
  19465. return BUFFER_E;
  19466. idx = SetSequence(length + sizeof(san_oid) + san_lenSz, output);
  19467. if ((length + sizeof(san_oid) + san_lenSz) > outSz)
  19468. return BUFFER_E;
  19469. /* put oid */
  19470. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  19471. idx += sizeof(san_oid);
  19472. /* put octet header */
  19473. XMEMCPY(output+idx, san_len, san_lenSz);
  19474. idx += san_lenSz;
  19475. /* put value */
  19476. XMEMCPY(output+idx, input, length);
  19477. idx += length;
  19478. return idx;
  19479. }
  19480. #endif /* WOLFSSL_ASN_TEMPLATE */
  19481. #ifdef WOLFSSL_CERT_GEN
  19482. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  19483. {
  19484. word32 idx;
  19485. const DNS_entry* curName;
  19486. word32 namesSz = 0;
  19487. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  19488. word32 i;
  19489. #endif
  19490. if (output == NULL)
  19491. return BAD_FUNC_ARG;
  19492. if (names == NULL)
  19493. return 0;
  19494. curName = names;
  19495. do {
  19496. namesSz += curName->len + 2 +
  19497. ((curName->len < ASN_LONG_LENGTH) ? 0
  19498. : BytePrecision(curName->len));
  19499. curName = curName->next;
  19500. } while (curName != NULL);
  19501. if (outputSz < MAX_SEQ_SZ + namesSz)
  19502. return BUFFER_E;
  19503. idx = SetSequence(namesSz, output);
  19504. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  19505. namesSz += idx;
  19506. i = namesSz;
  19507. #endif
  19508. curName = names;
  19509. do {
  19510. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  19511. word32 len = SetLength(curName->len, NULL);
  19512. idx = i - curName->len - len - 1;
  19513. i = idx;
  19514. #endif
  19515. output[idx] = ASN_CONTEXT_SPECIFIC | curName->type;
  19516. if (curName->type == ASN_DIR_TYPE) {
  19517. output[idx] |= ASN_CONSTRUCTED;
  19518. }
  19519. idx++;
  19520. idx += SetLength(curName->len, output + idx);
  19521. XMEMCPY(output + idx, curName->name, curName->len);
  19522. #ifndef WOLFSSL_ALT_NAMES_NO_REV
  19523. idx += curName->len;
  19524. #endif
  19525. curName = curName->next;
  19526. } while (curName != NULL);
  19527. #ifdef WOLFSSL_ALT_NAMES_NO_REV
  19528. idx = namesSz;
  19529. #endif
  19530. return idx;
  19531. }
  19532. #endif /* WOLFSSL_CERT_GEN */
  19533. #endif /* WOLFSSL_ALT_NAMES */
  19534. /* Simple domain name OID size. */
  19535. #define DN_OID_SZ 3
  19536. /* Encodes one attribute of the name (issuer/subject)
  19537. *
  19538. * name structure to hold result of encoding
  19539. * nameStr value to be encoded
  19540. * nameTag tag of encoding i.e CTC_UTF8
  19541. * type id of attribute i.e ASN_COMMON_NAME
  19542. * emailTag tag of email i.e CTC_UTF8
  19543. * returns length on success
  19544. */
  19545. static int wc_EncodeName_ex(EncodedName* name, const char* nameStr,
  19546. byte nameTag, byte type, byte emailTag)
  19547. {
  19548. #if !defined(WOLFSSL_ASN_TEMPLATE)
  19549. word32 idx = 0;
  19550. /* bottom up */
  19551. byte firstLen[1 + MAX_LENGTH_SZ];
  19552. byte secondLen[MAX_LENGTH_SZ];
  19553. byte sequence[MAX_SEQ_SZ];
  19554. byte set[MAX_SET_SZ];
  19555. int strLen;
  19556. int thisLen;
  19557. int firstSz, secondSz, seqSz, setSz;
  19558. if (nameStr == NULL) {
  19559. name->used = 0;
  19560. return 0;
  19561. }
  19562. thisLen = strLen = (int)XSTRLEN(nameStr);
  19563. if (strLen == 0) { /* no user data for this item */
  19564. name->used = 0;
  19565. return 0;
  19566. }
  19567. /* Restrict country code size */
  19568. if (ASN_COUNTRY_NAME == type && strLen != CTC_COUNTRY_SIZE) {
  19569. WOLFSSL_MSG("Country code size error");
  19570. return ASN_COUNTRY_SIZE_E;
  19571. }
  19572. secondSz = SetLength(strLen, secondLen);
  19573. thisLen += secondSz;
  19574. switch (type) {
  19575. case ASN_EMAIL_NAME: /* email */
  19576. thisLen += EMAIL_JOINT_LEN;
  19577. firstSz = EMAIL_JOINT_LEN;
  19578. break;
  19579. case ASN_DOMAIN_COMPONENT:
  19580. thisLen += PILOT_JOINT_LEN;
  19581. firstSz = PILOT_JOINT_LEN;
  19582. break;
  19583. default:
  19584. thisLen++; /* str type */
  19585. thisLen += JOINT_LEN;
  19586. firstSz = JOINT_LEN + 1;
  19587. }
  19588. thisLen++; /* id type */
  19589. firstSz = SetObjectId(firstSz, firstLen);
  19590. thisLen += firstSz;
  19591. seqSz = SetSequence(thisLen, sequence);
  19592. thisLen += seqSz;
  19593. setSz = SetSet(thisLen, set);
  19594. thisLen += setSz;
  19595. if (thisLen > (int)sizeof(name->encoded)) {
  19596. return BUFFER_E;
  19597. }
  19598. /* store it */
  19599. idx = 0;
  19600. /* set */
  19601. XMEMCPY(name->encoded, set, setSz);
  19602. idx += setSz;
  19603. /* seq */
  19604. XMEMCPY(name->encoded + idx, sequence, seqSz);
  19605. idx += seqSz;
  19606. /* asn object id */
  19607. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  19608. idx += firstSz;
  19609. switch (type) {
  19610. case ASN_EMAIL_NAME:
  19611. {
  19612. const byte EMAIL_OID[] = {
  19613. 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01
  19614. };
  19615. /* email joint id */
  19616. XMEMCPY(name->encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
  19617. idx += (int)sizeof(EMAIL_OID);
  19618. name->encoded[idx++] = emailTag;
  19619. break;
  19620. }
  19621. case ASN_DOMAIN_COMPONENT:
  19622. {
  19623. const byte PILOT_OID[] = {
  19624. 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01
  19625. };
  19626. XMEMCPY(name->encoded + idx, PILOT_OID, sizeof(PILOT_OID));
  19627. idx += (int)sizeof(PILOT_OID);
  19628. /* id type */
  19629. name->encoded[idx++] = type;
  19630. /* str type */
  19631. name->encoded[idx++] = nameTag;
  19632. break;
  19633. }
  19634. default:
  19635. name->encoded[idx++] = 0x55;
  19636. name->encoded[idx++] = 0x04;
  19637. /* id type */
  19638. name->encoded[idx++] = type;
  19639. /* str type */
  19640. name->encoded[idx++] = nameTag;
  19641. }
  19642. /* second length */
  19643. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  19644. idx += secondSz;
  19645. /* str value */
  19646. XMEMCPY(name->encoded + idx, nameStr, strLen);
  19647. idx += strLen;
  19648. name->type = type;
  19649. name->totalLen = idx;
  19650. name->used = 1;
  19651. return idx;
  19652. #else
  19653. ASNSetData dataASN[rdnASN_Length];
  19654. ASNItem namesASN[rdnASN_Length];
  19655. byte dnOid[DN_OID_SZ] = { 0x55, 0x04, 0x00 };
  19656. int ret = 0;
  19657. int sz;
  19658. const byte* oid;
  19659. int oidSz;
  19660. /* Validate input parameters. */
  19661. if ((name == NULL) || (nameStr == NULL)) {
  19662. ret = BAD_FUNC_ARG;
  19663. }
  19664. if (ret == 0) {
  19665. /* Clear data to use when encoding. */
  19666. XMEMSET(dataASN, 0, rdnASN_Length * sizeof(ASNSetData));
  19667. /* Copy the RDN encoding template. ASN.1 tag for the name string is set
  19668. * based on type. */
  19669. XMEMCPY(namesASN, rdnASN, rdnASN_Length * sizeof(ASNItem));
  19670. /* Set OID and ASN.1 tag for name depending on type. */
  19671. switch (type) {
  19672. case ASN_EMAIL_NAME:
  19673. /* email OID different to standard types. */
  19674. oid = emailOid;
  19675. oidSz = sizeof(emailOid);
  19676. /* Use email specific type/tag. */
  19677. nameTag = emailTag;
  19678. break;
  19679. case ASN_DOMAIN_COMPONENT:
  19680. /* Domain component OID different to standard types. */
  19681. oid = dcOid;
  19682. oidSz = sizeof(dcOid);
  19683. break;
  19684. default:
  19685. /* Construct OID using type. */
  19686. dnOid[2] = type;
  19687. oid = dnOid;
  19688. oidSz = DN_OID_SZ;
  19689. break;
  19690. }
  19691. /* Set OID corresponding to the name type. */
  19692. SetASN_Buffer(&dataASN[2], oid, oidSz);
  19693. /* Set name string. */
  19694. SetASN_Buffer(&dataASN[3], (const byte *)nameStr,
  19695. (word32)XSTRLEN(nameStr));
  19696. /* Set the ASN.1 tag for the name string. */
  19697. namesASN[3].tag = nameTag;
  19698. /* Calculate size of encoded name and indexes of components. */
  19699. ret = SizeASN_Items(namesASN, dataASN, rdnASN_Length, &sz);
  19700. }
  19701. /* Check if name's buffer is big enough. */
  19702. if ((ret == 0) && (sz > (int)sizeof(name->encoded))) {
  19703. ret = BUFFER_E;
  19704. }
  19705. if (ret == 0) {
  19706. /* Encode name into the buffer. */
  19707. SetASN_Items(namesASN, dataASN, rdnASN_Length, name->encoded);
  19708. /* Cache the type and size, and set that it is used. */
  19709. name->type = type;
  19710. name->totalLen = sz;
  19711. name->used = 1;
  19712. /* Return size of encoding. */
  19713. ret = sz;
  19714. }
  19715. return ret;
  19716. #endif /* WOLFSSL_ASN_TEMPLATE */
  19717. }
  19718. /* canonical encoding one attribute of the name (issuer/subject)
  19719. * call wc_EncodeName_ex with CTC_UTF8 for email type
  19720. *
  19721. * name structure to hold result of encoding
  19722. * nameStr value to be encoded
  19723. * nameType type of encoding i.e CTC_UTF8
  19724. * type id of attribute i.e ASN_COMMON_NAME
  19725. *
  19726. * returns length on success
  19727. */
  19728. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr,
  19729. char nameType, byte type)
  19730. {
  19731. return wc_EncodeName_ex(name, nameStr, (byte)nameType, type,
  19732. ASN_UTF8STRING);
  19733. }
  19734. /* Encodes one attribute of the name (issuer/subject)
  19735. * call we_EncodeName_ex with 0x16, IA5String for email type
  19736. * name structure to hold result of encoding
  19737. * nameStr value to be encoded
  19738. * nameType type of encoding i.e CTC_UTF8
  19739. * type id of attribute i.e ASN_COMMON_NAME
  19740. *
  19741. * returns length on success
  19742. */
  19743. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  19744. byte type)
  19745. {
  19746. return wc_EncodeName_ex(name, nameStr, (byte)nameType, type,
  19747. ASN_IA5_STRING);
  19748. }
  19749. #ifdef WOLFSSL_ASN_TEMPLATE
  19750. /* Simple name OID size. */
  19751. #define NAME_OID_SZ 3
  19752. /* Domain name OIDs. */
  19753. static const byte nameOid[NAME_ENTRIES - 1][NAME_OID_SZ] = {
  19754. { 0x55, 0x04, ASN_COUNTRY_NAME },
  19755. { 0x55, 0x04, ASN_STATE_NAME },
  19756. { 0x55, 0x04, ASN_STREET_ADDR },
  19757. { 0x55, 0x04, ASN_LOCALITY_NAME },
  19758. { 0x55, 0x04, ASN_SUR_NAME },
  19759. { 0x55, 0x04, ASN_ORG_NAME },
  19760. { 0x55, 0x04, ASN_ORGUNIT_NAME },
  19761. { 0x55, 0x04, ASN_COMMON_NAME },
  19762. { 0x55, 0x04, ASN_SERIAL_NUMBER },
  19763. #ifdef WOLFSSL_CERT_EXT
  19764. { 0x55, 0x04, ASN_BUS_CAT },
  19765. #endif
  19766. { 0x55, 0x04, ASN_POSTAL_CODE },
  19767. /* Email OID is much longer. */
  19768. };
  19769. static void SetRdnItems(ASNItem* namesASN, ASNSetData* dataASN, const byte* oid,
  19770. int oidSz, byte tag, const byte* data, int sz)
  19771. {
  19772. XMEMCPY(namesASN, rdnASN, sizeof(rdnASN));
  19773. SetASN_Buffer(&dataASN[2], oid, oidSz);
  19774. namesASN[3].tag = tag;
  19775. SetASN_Buffer(&dataASN[3], data, sz);
  19776. }
  19777. #ifdef WOLFSSL_MULTI_ATTRIB
  19778. static int FindMultiAttrib(CertName* name, int id, int* idx)
  19779. {
  19780. int i;
  19781. for (i = *idx + 1; i < CTC_MAX_ATTRIB; i++) {
  19782. if (name->name[i].sz > 0 && name->name[i].id == id) {
  19783. break;
  19784. }
  19785. }
  19786. if (i == CTC_MAX_ATTRIB) {
  19787. i = -1;
  19788. }
  19789. *idx = i;
  19790. return i >= 0;
  19791. }
  19792. #endif
  19793. /* ASN.1 template for the SEQUENCE around the RDNs.
  19794. * X.509: RFC 5280, 4.1.2.4 - RDNSequence
  19795. */
  19796. static const ASNItem nameASN[] = {
  19797. { 0, ASN_SEQUENCE, 1, 1, 0 },
  19798. };
  19799. /* Number of items in ASN.1 template for the SEQUENCE around the RDNs. */
  19800. #define nameASN_Length (sizeof(nameASN) / sizeof(ASNItem))
  19801. #endif
  19802. /* encode CertName into output, return total bytes written */
  19803. int SetNameEx(byte* output, word32 outputSz, CertName* name, void* heap)
  19804. {
  19805. #ifndef WOLFSSL_ASN_TEMPLATE
  19806. int totalBytes = 0, i, idx;
  19807. #ifdef WOLFSSL_SMALL_STACK
  19808. EncodedName* names = NULL;
  19809. #else
  19810. EncodedName names[NAME_ENTRIES];
  19811. #endif
  19812. #ifdef WOLFSSL_MULTI_ATTRIB
  19813. EncodedName addNames[CTC_MAX_ATTRIB];
  19814. int j, type;
  19815. #endif
  19816. if (output == NULL || name == NULL)
  19817. return BAD_FUNC_ARG;
  19818. if (outputSz < 3)
  19819. return BUFFER_E;
  19820. #ifdef WOLFSSL_SMALL_STACK
  19821. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  19822. DYNAMIC_TYPE_TMP_BUFFER);
  19823. if (names == NULL)
  19824. return MEMORY_E;
  19825. #endif
  19826. for (i = 0; i < NAME_ENTRIES; i++) {
  19827. int ret;
  19828. const char* nameStr = GetOneCertName(name, i);
  19829. ret = wc_EncodeName(&names[i], nameStr, GetNameType(name, i),
  19830. GetCertNameId(i));
  19831. if (ret < 0) {
  19832. #ifdef WOLFSSL_SMALL_STACK
  19833. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19834. #endif
  19835. WOLFSSL_MSG("EncodeName failed");
  19836. return BUFFER_E;
  19837. }
  19838. totalBytes += ret;
  19839. }
  19840. #ifdef WOLFSSL_MULTI_ATTRIB
  19841. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  19842. if (name->name[i].sz > 0) {
  19843. int ret;
  19844. ret = wc_EncodeName(&addNames[i], name->name[i].value,
  19845. name->name[i].type, name->name[i].id);
  19846. if (ret < 0) {
  19847. #ifdef WOLFSSL_SMALL_STACK
  19848. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19849. #endif
  19850. WOLFSSL_MSG("EncodeName on multiple attributes failed\n");
  19851. return BUFFER_E;
  19852. }
  19853. totalBytes += ret;
  19854. }
  19855. else {
  19856. addNames[i].used = 0;
  19857. }
  19858. }
  19859. #endif /* WOLFSSL_MULTI_ATTRIB */
  19860. /* header */
  19861. idx = SetSequence(totalBytes, output);
  19862. totalBytes += idx;
  19863. if (totalBytes > ASN_NAME_MAX) {
  19864. #ifdef WOLFSSL_SMALL_STACK
  19865. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19866. #endif
  19867. WOLFSSL_MSG("Total Bytes is greater than ASN_NAME_MAX");
  19868. return BUFFER_E;
  19869. }
  19870. for (i = 0; i < NAME_ENTRIES; i++) {
  19871. #ifdef WOLFSSL_MULTI_ATTRIB
  19872. type = GetCertNameId(i);
  19873. /* list all DC values before OUs */
  19874. if (type == ASN_ORGUNIT_NAME) {
  19875. type = ASN_DOMAIN_COMPONENT;
  19876. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  19877. if (name->name[j].sz > 0 && type == name->name[j].id) {
  19878. if (outputSz < (word32)(idx+addNames[j].totalLen)) {
  19879. #ifdef WOLFSSL_SMALL_STACK
  19880. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19881. #endif
  19882. WOLFSSL_MSG("Not enough space left for DC value");
  19883. return BUFFER_E;
  19884. }
  19885. XMEMCPY(output + idx, addNames[j].encoded,
  19886. addNames[j].totalLen);
  19887. idx += addNames[j].totalLen;
  19888. }
  19889. }
  19890. type = ASN_ORGUNIT_NAME;
  19891. }
  19892. /* write all similar types to the buffer */
  19893. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  19894. if (name->name[j].sz > 0 && type == name->name[j].id) {
  19895. if (outputSz < (word32)(idx+addNames[j].totalLen)) {
  19896. #ifdef WOLFSSL_SMALL_STACK
  19897. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19898. #endif
  19899. return BUFFER_E;
  19900. }
  19901. XMEMCPY(output + idx, addNames[j].encoded,
  19902. addNames[j].totalLen);
  19903. idx += addNames[j].totalLen;
  19904. }
  19905. }
  19906. #endif /* WOLFSSL_MULTI_ATTRIB */
  19907. if (names[i].used) {
  19908. if (outputSz < (word32)(idx+names[i].totalLen)) {
  19909. #ifdef WOLFSSL_SMALL_STACK
  19910. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19911. #endif
  19912. return BUFFER_E;
  19913. }
  19914. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  19915. idx += names[i].totalLen;
  19916. }
  19917. }
  19918. #ifdef WOLFSSL_SMALL_STACK
  19919. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  19920. #endif
  19921. (void)heap;
  19922. return totalBytes;
  19923. #else
  19924. /* TODO: consider calculating size of entries, putting length into
  19925. * SEQUENCE, encode SEQUENCE, encode entries into buffer. */
  19926. ASNSetData* dataASN;
  19927. ASNItem* namesASN;
  19928. int i;
  19929. int idx;
  19930. int ret = 0;
  19931. int sz;
  19932. int nameLen[NAME_ENTRIES];
  19933. #ifdef WOLFSSL_MULTI_ATTRIB
  19934. int j;
  19935. #endif
  19936. /* Calculate length of name entries and size for allocating. */
  19937. idx = nameASN_Length;
  19938. for (i = 0; i < NAME_ENTRIES; i++) {
  19939. /* Keep name length to identify component is to be encoded. */
  19940. nameLen[i] = (int)XSTRLEN(GetOneCertName(name, i));
  19941. if (nameLen[i] > 0) {
  19942. idx += rdnASN_Length;
  19943. }
  19944. }
  19945. #ifdef WOLFSSL_MULTI_ATTRIB
  19946. /* Count the extra attributes too. */
  19947. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  19948. if (name->name[i].sz > 0)
  19949. idx += rdnASN_Length;
  19950. }
  19951. #endif
  19952. /* Allocate dynamic data items. */
  19953. dataASN = (ASNSetData*)XMALLOC(idx * sizeof(ASNSetData), heap,
  19954. DYNAMIC_TYPE_TMP_BUFFER);
  19955. if (dataASN == NULL) {
  19956. ret = MEMORY_E;
  19957. }
  19958. else {
  19959. /* Allocate dynamic ASN.1 template items. */
  19960. namesASN = (ASNItem*)XMALLOC(idx * sizeof(ASNItem), heap,
  19961. DYNAMIC_TYPE_TMP_BUFFER);
  19962. if (namesASN == NULL) {
  19963. ret = MEMORY_E;
  19964. }
  19965. }
  19966. if (ret == 0) {
  19967. /* Clear the dynamic data. */
  19968. XMEMSET(dataASN, 0, idx * sizeof(ASNSetData));
  19969. /* Copy in the outer sequence. */
  19970. XMEMCPY(namesASN, nameASN, sizeof(nameASN));
  19971. idx = nameASN_Length;
  19972. for (i = 0; i < NAME_ENTRIES; i++) {
  19973. int email = (i == (NAME_ENTRIES - 1));
  19974. #ifdef WOLFSSL_MULTI_ATTRIB
  19975. int type = GetCertNameId(i);
  19976. if (type == ASN_ORGUNIT_NAME) {
  19977. j = -1;
  19978. /* Put DomainComponents before OrgUnitName. */
  19979. while (FindMultiAttrib(name, ASN_DOMAIN_COMPONENT, &j)) {
  19980. /* Copy data into dynamic vars. */
  19981. SetRdnItems(namesASN + idx, dataASN + idx, dcOid,
  19982. sizeof(dcOid), name->name[j].type,
  19983. (byte*)name->name[j].value, name->name[j].sz);
  19984. idx += rdnASN_Length;
  19985. }
  19986. }
  19987. #endif
  19988. if (nameLen[i] > 0) {
  19989. /* Write out first instance of attribute type. */
  19990. if (email) {
  19991. /* Copy email data into dynamic vars. */
  19992. SetRdnItems(namesASN + idx, dataASN + idx, emailOid,
  19993. sizeof(emailOid), ASN_IA5_STRING,
  19994. (const byte*)GetOneCertName(name, i), nameLen[i]);
  19995. }
  19996. else {
  19997. /* Copy name data into dynamic vars. */
  19998. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[i],
  19999. NAME_OID_SZ, GetNameType(name, i),
  20000. (const byte*)GetOneCertName(name, i), nameLen[i]);
  20001. }
  20002. idx += rdnASN_Length;
  20003. }
  20004. #ifdef WOLFSSL_MULTI_ATTRIB
  20005. j = -1;
  20006. /* Write all other attributes of this type. */
  20007. while (FindMultiAttrib(name, type, &j)) {
  20008. /* Copy data into dynamic vars. */
  20009. SetRdnItems(namesASN + idx, dataASN + idx, nameOid[type],
  20010. NAME_OID_SZ, name->name[j].type,
  20011. (byte*)name->name[j].value, name->name[j].sz);
  20012. idx += rdnASN_Length;
  20013. }
  20014. #endif
  20015. }
  20016. /* Calculate size of encoding. */
  20017. ret = SizeASN_Items(namesASN, dataASN, idx, &sz);
  20018. }
  20019. /* Check buffer size if passed in. */
  20020. if ((ret == 0) && (output != NULL) && (sz > (int)outputSz)) {
  20021. ret = BUFFER_E;
  20022. }
  20023. if ((ret == 0) && (output != NULL)) {
  20024. /* Encode Name. */
  20025. SetASN_Items(namesASN, dataASN, idx, output);
  20026. }
  20027. if (ret == 0) {
  20028. /* Return the encoding size. */
  20029. ret = sz;
  20030. }
  20031. XFREE(namesASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  20032. XFREE(dataASN, heap, DYNAMIC_TYPE_TMP_BUFFER);
  20033. (void)heap;
  20034. return ret;
  20035. #endif
  20036. }
  20037. int SetName(byte* output, word32 outputSz, CertName* name)
  20038. {
  20039. return SetNameEx(output, outputSz, name, NULL);
  20040. }
  20041. #ifdef WOLFSSL_ASN_TEMPLATE
  20042. static int EncodePublicKey(int keyType, byte* output, int outLen,
  20043. RsaKey* rsaKey, ecc_key* eccKey,
  20044. ed25519_key* ed25519Key, ed448_key* ed448Key,
  20045. DsaKey* dsaKey)
  20046. {
  20047. int ret = 0;
  20048. (void)outLen;
  20049. (void)rsaKey;
  20050. (void)eccKey;
  20051. (void)ed25519Key;
  20052. (void)ed448Key;
  20053. (void)dsaKey;
  20054. switch (keyType) {
  20055. #ifndef NO_RSA
  20056. case RSA_KEY:
  20057. ret = SetRsaPublicKey(output, rsaKey, outLen, 1);
  20058. if (ret <= 0) {
  20059. ret = PUBLIC_KEY_E;
  20060. }
  20061. break;
  20062. #endif
  20063. #ifdef HAVE_ECC
  20064. case ECC_KEY:
  20065. ret = SetEccPublicKey(output, eccKey, outLen, 1);
  20066. if (ret <= 0) {
  20067. ret = PUBLIC_KEY_E;
  20068. }
  20069. break;
  20070. #endif /* HAVE_ECC */
  20071. #ifdef HAVE_ED25519
  20072. case ED25519_KEY:
  20073. ret = wc_Ed25519PublicKeyToDer(ed25519Key, output, outLen, 1);
  20074. if (ret <= 0) {
  20075. ret = PUBLIC_KEY_E;
  20076. }
  20077. break;
  20078. #endif
  20079. #ifdef HAVE_ED448
  20080. case ED448_KEY:
  20081. ret = wc_Ed448PublicKeyToDer(ed448Key, output, outLen, 1);
  20082. if (ret <= 0) {
  20083. ret = PUBLIC_KEY_E;
  20084. }
  20085. break;
  20086. #endif
  20087. default:
  20088. ret = PUBLIC_KEY_E;
  20089. break;
  20090. }
  20091. return ret;
  20092. }
  20093. /* ASN.1 template for certificate extensions.
  20094. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  20095. * All extensions supported for encoding are described.
  20096. */
  20097. static const ASNItem certExtsASN[] = {
  20098. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  20099. /* Basic Constraints Extension - 4.2.1.9 */
  20100. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20101. /* 2 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20102. /* 3 */ { 2, ASN_OCTET_STRING, 0, 1, 0 },
  20103. /* 4 */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  20104. /* cA */
  20105. /* 5 */ { 4, ASN_BOOLEAN, 0, 0, 0 },
  20106. /* pathLenConstraint */
  20107. /* 6 */ { 4, ASN_INTEGER, 0, 0, 1 },
  20108. /* Subject Alternative Name - 4.2.1.6 */
  20109. /* 7 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20110. /* 8 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20111. /* */
  20112. /* 9 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  20113. #ifdef WOLFSSL_CERT_EXT
  20114. /* Subject Key Identifier - 4.2.1.2 */
  20115. /* 10 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20116. /* 11 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20117. /* 12 */ { 2, ASN_OCTET_STRING, 0, 1, 0 },
  20118. /* 13 */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  20119. /* Authority Key Identifier - 4.2.1.1 */
  20120. /* 14 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20121. /* 15 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20122. /* 16 */ { 2, ASN_OCTET_STRING, 0, 1, 0 },
  20123. /* 17 */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  20124. /* 18 */ { 4, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 0 },
  20125. /* Key Usage - 4.2.1.3 */
  20126. /* 19 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20127. /* 20 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20128. /* 21 */ { 2, ASN_BOOLEAN, 0, 0, 0 },
  20129. /* 22 */ { 2, ASN_OCTET_STRING, 0, 1, 0 },
  20130. /* 23 */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  20131. /* Extended Key Usage - 4,2,1,12 */
  20132. /* 24 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20133. /* 25 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20134. /* 26 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  20135. /* Certificate Policies - 4.2.1.4 */
  20136. /* 27 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20137. /* 28 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20138. /* 29 */ { 2, ASN_OCTET_STRING, 0, 1, 0 },
  20139. /* 30 */ { 3, ASN_SEQUENCE, 0, 0, 0 },
  20140. /* Netscape Certificate Type */
  20141. /* 31 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20142. /* 32 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20143. /* 33 */ { 2, ASN_OCTET_STRING, 0, 1, 0 },
  20144. /* 34 */ { 3, ASN_BIT_STRING, 0, 0, 0 },
  20145. /* 35 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  20146. /* 36 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  20147. /* 37 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  20148. #endif
  20149. };
  20150. /* Number of items in ASN.1 template for certificate extensions. */
  20151. #define certExtsASN_Length (sizeof(certExtsASN) / sizeof(ASNItem))
  20152. static int EncodeExtensions(Cert* cert, byte* output, word32 maxSz,
  20153. int forRequest)
  20154. {
  20155. DECL_ASNSETDATA(dataASN, certExtsASN_Length);
  20156. int sz;
  20157. int ret = 0;
  20158. static const byte bcOID[] = { 0x55, 0x1d, 0x13 };
  20159. #ifdef WOLFSSL_ALT_NAMES
  20160. static const byte sanOID[] = { 0x55, 0x1d, 0x11 };
  20161. #endif
  20162. #ifdef WOLFSSL_CERT_EXT
  20163. static const byte skidOID[] = { 0x55, 0x1d, 0x0e };
  20164. static const byte akidOID[] = { 0x55, 0x1d, 0x23 };
  20165. static const byte kuOID[] = { 0x55, 0x1d, 0x0f };
  20166. static const byte ekuOID[] = { 0x55, 0x1d, 0x25 };
  20167. static const byte cpOID[] = { 0x55, 0x1d, 0x20 };
  20168. static const byte nsCertOID[] = { 0x60, 0x86, 0x48, 0x01,
  20169. 0x86, 0xF8, 0x42, 0x01, 0x01 };
  20170. static const byte crlInfoOID[] = { 0x55, 0x1D, 0x1F };
  20171. #endif
  20172. (void)forRequest;
  20173. CALLOC_ASNSETDATA(dataASN, certExtsASN_Length, ret, cert->heap);
  20174. if (ret == 0) {
  20175. if (cert->isCA) {
  20176. /* Set Basic Constraints to be a Certificate Authority. */
  20177. SetASN_Boolean(&dataASN[5], 1);
  20178. SetASN_Buffer(&dataASN[2], bcOID, sizeof(bcOID));
  20179. /* TODO: consider adding path length field in Cert. */
  20180. dataASN[6].noOut = 1;
  20181. }
  20182. else {
  20183. /* Don't write out Basic Constraints extension items. */
  20184. SetASNItem_NoOut(dataASN, 1, 6);
  20185. }
  20186. #ifdef WOLFSSL_ALT_NAMES
  20187. if (!forRequest && cert->altNamesSz > 0) {
  20188. /* Set Subject Alternative Name OID and data. */
  20189. SetASN_Buffer(&dataASN[8], sanOID, sizeof(sanOID));
  20190. SetASN_Buffer(&dataASN[9], cert->altNames, cert->altNamesSz);
  20191. }
  20192. else
  20193. #endif
  20194. {
  20195. /* Don't write out Subject Alternative Name extension items. */
  20196. SetASNItem_NoOut(dataASN, 7, 9);
  20197. }
  20198. #ifdef WOLFSSL_CERT_EXT
  20199. if (cert->skidSz > 0) {
  20200. /* Set Subject Key Identifier OID and data. */
  20201. SetASN_Buffer(&dataASN[11], skidOID, sizeof(skidOID));
  20202. SetASN_Buffer(&dataASN[13], cert->skid, cert->skidSz);
  20203. }
  20204. else {
  20205. /* Don't write out Subject Key Identifier extension items. */
  20206. SetASNItem_NoOut(dataASN, 10, 13);
  20207. }
  20208. if (cert->akidSz > 0) {
  20209. /* Set Authority Key Identifier OID and data. */
  20210. SetASN_Buffer(&dataASN[15], akidOID, sizeof(akidOID));
  20211. if (cert->rawAkid) {
  20212. SetASN_Buffer(&dataASN[16], cert->akid, cert->akidSz);
  20213. /* cert->akid contains the internal ext structure */
  20214. SetASNItem_NoOutBelow(dataASN, certExtsASN, 16,
  20215. certExtsASN_Length);
  20216. }
  20217. else {
  20218. SetASN_Buffer(&dataASN[18], cert->akid, cert->akidSz);
  20219. }
  20220. }
  20221. else {
  20222. /* Don't write out Authority Key Identifier extension items. */
  20223. SetASNItem_NoOut(dataASN, 14, 18);
  20224. }
  20225. if (cert->keyUsage != 0) {
  20226. /* Set Key Usage OID, critical and value. */
  20227. SetASN_Buffer(&dataASN[20], kuOID, sizeof(kuOID));
  20228. SetASN_Boolean(&dataASN[21], 1);
  20229. SetASN_Int16Bit(&dataASN[23], cert->keyUsage);
  20230. }
  20231. else {
  20232. /* Don't write out Key Usage extension items. */
  20233. SetASNItem_NoOut(dataASN, 19, 23);
  20234. }
  20235. if (cert->extKeyUsage != 0) {
  20236. /* Calculate size of Extended Key Usage data. */
  20237. sz = SetExtKeyUsage(cert, NULL, 0, cert->extKeyUsage);
  20238. if (sz <= 0) {
  20239. ret = KEYUSAGE_E;
  20240. }
  20241. /* Set Extended Key Usage OID and data. */
  20242. SetASN_Buffer(&dataASN[25], ekuOID, sizeof(ekuOID));
  20243. SetASN_Buffer(&dataASN[26], NULL, sz);
  20244. }
  20245. else {
  20246. /* Don't write out Extended Key Usage extension items. */
  20247. SetASNItem_NoOut(dataASN, 24, 26);
  20248. }
  20249. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  20250. /* Calculate size of certificate policies. */
  20251. sz = SetCertificatePolicies(NULL, 0, cert->certPolicies,
  20252. cert->certPoliciesNb, cert->heap);
  20253. if (sz > 0) {
  20254. /* Set Certificate Policies OID. */
  20255. SetASN_Buffer(&dataASN[28], cpOID, sizeof(cpOID));
  20256. /* Make space for data. */
  20257. SetASN_Buffer(&dataASN[30], NULL, sz);
  20258. }
  20259. else {
  20260. ret = CERTPOLICIES_E;
  20261. }
  20262. }
  20263. else {
  20264. /* Don't write out Certificate Policies extension items. */
  20265. SetASNItem_NoOut(dataASN, 27, 30);
  20266. }
  20267. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  20268. /* Netscape Certificate Type */
  20269. if (cert->nsCertType != 0) {
  20270. /* Set Netscape Certificate Type OID and data. */
  20271. SetASN_Buffer(&dataASN[32], nsCertOID, sizeof(nsCertOID));
  20272. SetASN_Buffer(&dataASN[34], &cert->nsCertType, 1);
  20273. }
  20274. else
  20275. #endif
  20276. {
  20277. /* Don't write out Netscape Certificate Type. */
  20278. SetASNItem_NoOut(dataASN, 31, 34);
  20279. }
  20280. if (cert->crlInfoSz > 0) {
  20281. /* Set CRL Distribution Points OID and data. */
  20282. SetASN_Buffer(&dataASN[36], crlInfoOID, sizeof(crlInfoOID));
  20283. SetASN_Buffer(&dataASN[37], cert->crlInfo, cert->crlInfoSz);
  20284. }
  20285. else {
  20286. /* Don't write out CRL Distribution Points. */
  20287. SetASNItem_NoOut(dataASN, 35, 37);
  20288. }
  20289. #endif
  20290. }
  20291. if (ret == 0) {
  20292. /* Calculate size of encoded extensions. */
  20293. ret = SizeASN_Items(certExtsASN, dataASN, certExtsASN_Length, &sz);
  20294. }
  20295. if (ret == 0) {
  20296. /* Only SEQUENCE - don't encode extensions. */
  20297. if (sz == 2) {
  20298. sz = 0;
  20299. }
  20300. /* Check buffer is big enough. */
  20301. else if ((output != NULL) && (sz > (int)maxSz)) {
  20302. ret = BUFFER_E;
  20303. }
  20304. }
  20305. if ((ret == 0) && (output != NULL) && (sz > 0)) {
  20306. /* Encode certificate extensions into buffer. */
  20307. SetASN_Items(certExtsASN, dataASN, certExtsASN_Length, output);
  20308. #ifdef WOLFSSL_CERT_EXT
  20309. if (cert->extKeyUsage != 0){
  20310. /* Encode Extended Key Usage into space provided. */
  20311. if (SetExtKeyUsage(cert, (byte*)dataASN[26].data.buffer.data,
  20312. dataASN[26].data.buffer.length, cert->extKeyUsage) <= 0) {
  20313. ret = KEYUSAGE_E;
  20314. }
  20315. }
  20316. if ((!forRequest) && (cert->certPoliciesNb > 0)) {
  20317. /* Encode Certificate Policies into space provided. */
  20318. if (SetCertificatePolicies((byte*)dataASN[30].data.buffer.data,
  20319. dataASN[30].data.buffer.length, cert->certPolicies,
  20320. cert->certPoliciesNb, cert->heap) <= 0) {
  20321. ret = CERTPOLICIES_E;
  20322. }
  20323. }
  20324. #endif
  20325. }
  20326. if (ret == 0) {
  20327. /* Return the encoding size. */
  20328. ret = sz;
  20329. }
  20330. FREE_ASNSETDATA(dataASN, cert->heap);
  20331. return ret;
  20332. }
  20333. #endif /* WOLFSSL_ASN_TEMPLATE */
  20334. #ifndef WOLFSSL_ASN_TEMPLATE
  20335. /* Set Date validity from now until now + daysValid
  20336. * return size in bytes written to output, 0 on error */
  20337. /* TODO https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.2.5
  20338. * "MUST always encode certificate validity dates through the year 2049 as
  20339. * UTCTime; certificate validity dates in 2050 or later MUST be encoded as
  20340. * GeneralizedTime." */
  20341. static int SetValidity(byte* output, int daysValid)
  20342. {
  20343. #ifndef NO_ASN_TIME
  20344. byte before[MAX_DATE_SIZE];
  20345. byte after[MAX_DATE_SIZE];
  20346. int beforeSz;
  20347. int afterSz;
  20348. int seqSz;
  20349. time_t now;
  20350. time_t then;
  20351. struct tm* tmpTime;
  20352. struct tm* expandedTime;
  20353. struct tm localTime;
  20354. #if defined(NEED_TMP_TIME)
  20355. /* for use with gmtime_r */
  20356. struct tm tmpTimeStorage;
  20357. tmpTime = &tmpTimeStorage;
  20358. #else
  20359. tmpTime = NULL;
  20360. #endif
  20361. (void)tmpTime;
  20362. now = XTIME(0);
  20363. /* before now */
  20364. before[0] = ASN_GENERALIZED_TIME;
  20365. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  20366. /* subtract 1 day of seconds for more compliance */
  20367. then = now - 86400;
  20368. expandedTime = XGMTIME(&then, tmpTime);
  20369. if (expandedTime == NULL) {
  20370. WOLFSSL_MSG("XGMTIME failed");
  20371. return 0; /* error */
  20372. }
  20373. localTime = *expandedTime;
  20374. /* adjust */
  20375. localTime.tm_year += 1900;
  20376. localTime.tm_mon += 1;
  20377. SetTime(&localTime, before + beforeSz);
  20378. beforeSz += ASN_GEN_TIME_SZ;
  20379. after[0] = ASN_GENERALIZED_TIME;
  20380. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  20381. /* add daysValid of seconds */
  20382. then = now + (daysValid * (time_t)86400);
  20383. expandedTime = XGMTIME(&then, tmpTime);
  20384. if (expandedTime == NULL) {
  20385. WOLFSSL_MSG("XGMTIME failed");
  20386. return 0; /* error */
  20387. }
  20388. localTime = *expandedTime;
  20389. /* adjust */
  20390. localTime.tm_year += 1900;
  20391. localTime.tm_mon += 1;
  20392. SetTime(&localTime, after + afterSz);
  20393. afterSz += ASN_GEN_TIME_SZ;
  20394. /* headers and output */
  20395. seqSz = SetSequence(beforeSz + afterSz, output);
  20396. XMEMCPY(output + seqSz, before, beforeSz);
  20397. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  20398. return seqSz + beforeSz + afterSz;
  20399. #else
  20400. (void)output;
  20401. (void)daysValid;
  20402. return NOT_COMPILED_IN;
  20403. #endif
  20404. }
  20405. #else
  20406. static int SetValidity(byte* before, byte* after, int daysValid)
  20407. {
  20408. int ret = 0;
  20409. time_t now;
  20410. time_t then;
  20411. struct tm* tmpTime;
  20412. struct tm* expandedTime;
  20413. struct tm localTime;
  20414. #if defined(NEED_TMP_TIME)
  20415. /* for use with gmtime_r */
  20416. struct tm tmpTimeStorage;
  20417. tmpTime = &tmpTimeStorage;
  20418. #else
  20419. tmpTime = NULL;
  20420. #endif
  20421. (void)tmpTime;
  20422. now = XTIME(0);
  20423. /* subtract 1 day of seconds for more compliance */
  20424. then = now - 86400;
  20425. expandedTime = XGMTIME(&then, tmpTime);
  20426. if (expandedTime == NULL) {
  20427. WOLFSSL_MSG("XGMTIME failed");
  20428. ret = DATE_E;
  20429. }
  20430. if (ret == 0) {
  20431. localTime = *expandedTime;
  20432. /* adjust */
  20433. localTime.tm_year += 1900;
  20434. localTime.tm_mon += 1;
  20435. SetTime(&localTime, before);
  20436. /* add daysValid of seconds */
  20437. then = now + (daysValid * (time_t)86400);
  20438. expandedTime = XGMTIME(&then, tmpTime);
  20439. if (expandedTime == NULL) {
  20440. WOLFSSL_MSG("XGMTIME failed");
  20441. ret = DATE_E;
  20442. }
  20443. }
  20444. if (ret == 0) {
  20445. localTime = *expandedTime;
  20446. /* adjust */
  20447. localTime.tm_year += 1900;
  20448. localTime.tm_mon += 1;
  20449. SetTime(&localTime, after);
  20450. }
  20451. return ret;
  20452. }
  20453. #endif /* WOLFSSL_ASN_TEMPLATE */
  20454. #ifndef WOLFSSL_ASN_TEMPLATE
  20455. /* encode info from cert into DER encoded format */
  20456. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  20457. WC_RNG* rng, DsaKey* dsaKey, ed25519_key* ed25519Key,
  20458. ed448_key* ed448Key, falcon_key* falconKey)
  20459. {
  20460. int ret;
  20461. if (cert == NULL || der == NULL || rng == NULL)
  20462. return BAD_FUNC_ARG;
  20463. /* make sure at least one key type is provided */
  20464. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  20465. dsaKey == NULL && ed448Key == NULL && falconKey == NULL) {
  20466. return PUBLIC_KEY_E;
  20467. }
  20468. /* init */
  20469. XMEMSET(der, 0, sizeof(DerCert));
  20470. /* version */
  20471. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  20472. /* serial number (must be positive) */
  20473. if (cert->serialSz == 0) {
  20474. /* generate random serial */
  20475. cert->serialSz = CTC_GEN_SERIAL_SZ;
  20476. ret = wc_RNG_GenerateBlock(rng, cert->serial, cert->serialSz);
  20477. if (ret != 0)
  20478. return ret;
  20479. /* Clear the top bit to avoid a negative value */
  20480. cert->serial[0] &= 0x7f;
  20481. }
  20482. der->serialSz = SetSerialNumber(cert->serial, cert->serialSz, der->serial,
  20483. sizeof(der->serial), CTC_SERIAL_SIZE);
  20484. if (der->serialSz < 0)
  20485. return der->serialSz;
  20486. /* signature algo */
  20487. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  20488. if (der->sigAlgoSz <= 0)
  20489. return ALGO_ID_E;
  20490. /* public key */
  20491. #ifndef NO_RSA
  20492. if (cert->keyType == RSA_KEY) {
  20493. if (rsaKey == NULL)
  20494. return PUBLIC_KEY_E;
  20495. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  20496. sizeof(der->publicKey), 1);
  20497. }
  20498. #endif
  20499. #ifdef HAVE_ECC
  20500. if (cert->keyType == ECC_KEY) {
  20501. if (eccKey == NULL)
  20502. return PUBLIC_KEY_E;
  20503. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  20504. sizeof(der->publicKey), 1);
  20505. }
  20506. #endif
  20507. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  20508. if (cert->keyType == DSA_KEY) {
  20509. if (dsaKey == NULL)
  20510. return PUBLIC_KEY_E;
  20511. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  20512. sizeof(der->publicKey), 1);
  20513. }
  20514. #endif
  20515. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  20516. if (cert->keyType == ED25519_KEY) {
  20517. if (ed25519Key == NULL)
  20518. return PUBLIC_KEY_E;
  20519. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  20520. (word32)sizeof(der->publicKey), 1);
  20521. }
  20522. #endif
  20523. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  20524. if (cert->keyType == ED448_KEY) {
  20525. if (ed448Key == NULL)
  20526. return PUBLIC_KEY_E;
  20527. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  20528. (word32)sizeof(der->publicKey), 1);
  20529. }
  20530. #endif
  20531. #if defined(HAVE_LIBOQS)
  20532. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  20533. (cert->keyType == FALCON_LEVEL5_KEY)) {
  20534. if (falconKey == NULL)
  20535. return PUBLIC_KEY_E;
  20536. der->publicKeySz =
  20537. wc_Falcon_PublicKeyToDer(falconKey, der->publicKey,
  20538. (word32)sizeof(der->publicKey), 1);
  20539. }
  20540. #endif
  20541. if (der->publicKeySz <= 0)
  20542. return PUBLIC_KEY_E;
  20543. der->validitySz = 0;
  20544. #ifdef WOLFSSL_ALT_NAMES
  20545. /* date validity copy ? */
  20546. if (cert->beforeDateSz && cert->afterDateSz) {
  20547. der->validitySz = CopyValidity(der->validity, cert);
  20548. if (der->validitySz <= 0)
  20549. return DATE_E;
  20550. }
  20551. #endif
  20552. /* date validity */
  20553. if (der->validitySz == 0) {
  20554. der->validitySz = SetValidity(der->validity, cert->daysValid);
  20555. if (der->validitySz <= 0)
  20556. return DATE_E;
  20557. }
  20558. /* subject name */
  20559. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  20560. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  20561. /* Use the raw subject */
  20562. int idx;
  20563. der->subjectSz = min(sizeof(der->subject),
  20564. (word32)XSTRLEN((const char*)cert->sbjRaw));
  20565. /* header */
  20566. idx = SetSequence(der->subjectSz, der->subject);
  20567. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  20568. return SUBJECT_E;
  20569. }
  20570. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  20571. der->subjectSz);
  20572. der->subjectSz += idx;
  20573. }
  20574. else
  20575. #endif
  20576. {
  20577. /* Use the name structure */
  20578. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  20579. &cert->subject, cert->heap);
  20580. }
  20581. if (der->subjectSz <= 0)
  20582. return SUBJECT_E;
  20583. /* issuer name */
  20584. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  20585. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  20586. /* Use the raw issuer */
  20587. int idx;
  20588. der->issuerSz = min(sizeof(der->issuer),
  20589. (word32)XSTRLEN((const char*)cert->issRaw));
  20590. /* header */
  20591. idx = SetSequence(der->issuerSz, der->issuer);
  20592. if (der->issuerSz + idx > (int)sizeof(der->issuer)) {
  20593. return ISSUER_E;
  20594. }
  20595. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  20596. der->issuerSz);
  20597. der->issuerSz += idx;
  20598. }
  20599. else
  20600. #endif
  20601. {
  20602. /* Use the name structure */
  20603. der->issuerSz = SetNameEx(der->issuer, sizeof(der->issuer),
  20604. cert->selfSigned ? &cert->subject : &cert->issuer, cert->heap);
  20605. }
  20606. if (der->issuerSz <= 0)
  20607. return ISSUER_E;
  20608. /* set the extensions */
  20609. der->extensionsSz = 0;
  20610. /* CA */
  20611. if (cert->isCA) {
  20612. der->caSz = SetCa(der->ca, sizeof(der->ca));
  20613. if (der->caSz <= 0)
  20614. return CA_TRUE_E;
  20615. der->extensionsSz += der->caSz;
  20616. }
  20617. else
  20618. der->caSz = 0;
  20619. #ifdef WOLFSSL_ALT_NAMES
  20620. /* Alternative Name */
  20621. if (cert->altNamesSz) {
  20622. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  20623. cert->altNames, cert->altNamesSz);
  20624. if (der->altNamesSz <= 0)
  20625. return ALT_NAME_E;
  20626. der->extensionsSz += der->altNamesSz;
  20627. }
  20628. else
  20629. der->altNamesSz = 0;
  20630. #endif
  20631. #ifdef WOLFSSL_CERT_EXT
  20632. /* SKID */
  20633. if (cert->skidSz) {
  20634. /* check the provided SKID size */
  20635. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  20636. return SKID_E;
  20637. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  20638. cert (CTC_MAX_SKID_SIZE). */
  20639. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  20640. cert->skid, cert->skidSz);
  20641. if (der->skidSz <= 0)
  20642. return SKID_E;
  20643. der->extensionsSz += der->skidSz;
  20644. }
  20645. else
  20646. der->skidSz = 0;
  20647. /* AKID */
  20648. if (cert->akidSz) {
  20649. /* check the provided AKID size */
  20650. if ((
  20651. #ifdef WOLFSSL_AKID_NAME
  20652. !cert->rawAkid &&
  20653. #endif
  20654. cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  20655. #ifdef WOLFSSL_AKID_NAME
  20656. || (cert->rawAkid && cert->akidSz > (int)sizeof(der->akid))
  20657. #endif
  20658. )
  20659. return AKID_E;
  20660. der->akidSz = SetAKID(der->akid, sizeof(der->akid), cert->akid,
  20661. cert->akidSz,
  20662. #ifdef WOLFSSL_AKID_NAME
  20663. cert->rawAkid
  20664. #else
  20665. 0
  20666. #endif
  20667. );
  20668. if (der->akidSz <= 0)
  20669. return AKID_E;
  20670. der->extensionsSz += der->akidSz;
  20671. }
  20672. else
  20673. der->akidSz = 0;
  20674. /* Key Usage */
  20675. if (cert->keyUsage != 0){
  20676. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  20677. cert->keyUsage);
  20678. if (der->keyUsageSz <= 0)
  20679. return KEYUSAGE_E;
  20680. der->extensionsSz += der->keyUsageSz;
  20681. }
  20682. else
  20683. der->keyUsageSz = 0;
  20684. /* Extended Key Usage */
  20685. if (cert->extKeyUsage != 0){
  20686. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  20687. sizeof(der->extKeyUsage), cert->extKeyUsage);
  20688. if (der->extKeyUsageSz <= 0)
  20689. return EXTKEYUSAGE_E;
  20690. der->extensionsSz += der->extKeyUsageSz;
  20691. }
  20692. else
  20693. der->extKeyUsageSz = 0;
  20694. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  20695. /* Netscape Certificate Type */
  20696. if (cert->nsCertType != 0) {
  20697. der->nsCertTypeSz = SetNsCertType(cert, der->nsCertType,
  20698. sizeof(der->nsCertType), cert->nsCertType);
  20699. if (der->nsCertTypeSz <= 0)
  20700. return EXTENSIONS_E;
  20701. der->extensionsSz += der->nsCertTypeSz;
  20702. }
  20703. else
  20704. der->nsCertTypeSz = 0;
  20705. #endif
  20706. if (cert->crlInfoSz > 0) {
  20707. der->crlInfoSz = SetCRLInfo(cert, der->crlInfo, sizeof(der->crlInfo),
  20708. cert->crlInfo, cert->crlInfoSz);
  20709. if (der->crlInfoSz <= 0)
  20710. return EXTENSIONS_E;
  20711. der->extensionsSz += der->crlInfoSz;
  20712. }
  20713. else
  20714. der->crlInfoSz = 0;
  20715. /* Certificate Policies */
  20716. if (cert->certPoliciesNb != 0) {
  20717. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  20718. sizeof(der->certPolicies),
  20719. cert->certPolicies,
  20720. cert->certPoliciesNb,
  20721. cert->heap);
  20722. if (der->certPoliciesSz <= 0)
  20723. return CERTPOLICIES_E;
  20724. der->extensionsSz += der->certPoliciesSz;
  20725. }
  20726. else
  20727. der->certPoliciesSz = 0;
  20728. #endif /* WOLFSSL_CERT_EXT */
  20729. /* put extensions */
  20730. if (der->extensionsSz > 0) {
  20731. /* put the start of extensions sequence (ID, Size) */
  20732. der->extensionsSz = SetExtensionsHeader(der->extensions,
  20733. sizeof(der->extensions),
  20734. der->extensionsSz);
  20735. if (der->extensionsSz <= 0)
  20736. return EXTENSIONS_E;
  20737. /* put CA */
  20738. if (der->caSz) {
  20739. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20740. &der->extensionsSz,
  20741. der->ca, der->caSz);
  20742. if (ret == 0)
  20743. return EXTENSIONS_E;
  20744. }
  20745. #ifdef WOLFSSL_ALT_NAMES
  20746. /* put Alternative Names */
  20747. if (der->altNamesSz) {
  20748. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20749. &der->extensionsSz,
  20750. der->altNames, der->altNamesSz);
  20751. if (ret <= 0)
  20752. return EXTENSIONS_E;
  20753. }
  20754. #endif
  20755. #ifdef WOLFSSL_CERT_EXT
  20756. /* put SKID */
  20757. if (der->skidSz) {
  20758. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20759. &der->extensionsSz,
  20760. der->skid, der->skidSz);
  20761. if (ret <= 0)
  20762. return EXTENSIONS_E;
  20763. }
  20764. /* put AKID */
  20765. if (der->akidSz) {
  20766. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20767. &der->extensionsSz,
  20768. der->akid, der->akidSz);
  20769. if (ret <= 0)
  20770. return EXTENSIONS_E;
  20771. }
  20772. /* put CRL Distribution Points */
  20773. if (der->crlInfoSz) {
  20774. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20775. &der->extensionsSz,
  20776. der->crlInfo, der->crlInfoSz);
  20777. if (ret <= 0)
  20778. return EXTENSIONS_E;
  20779. }
  20780. /* put KeyUsage */
  20781. if (der->keyUsageSz) {
  20782. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20783. &der->extensionsSz,
  20784. der->keyUsage, der->keyUsageSz);
  20785. if (ret <= 0)
  20786. return EXTENSIONS_E;
  20787. }
  20788. /* put ExtendedKeyUsage */
  20789. if (der->extKeyUsageSz) {
  20790. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20791. &der->extensionsSz,
  20792. der->extKeyUsage, der->extKeyUsageSz);
  20793. if (ret <= 0)
  20794. return EXTENSIONS_E;
  20795. }
  20796. /* put Netscape Cert Type */
  20797. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  20798. if (der->nsCertTypeSz) {
  20799. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20800. &der->extensionsSz,
  20801. der->nsCertType, der->nsCertTypeSz);
  20802. if (ret <= 0)
  20803. return EXTENSIONS_E;
  20804. }
  20805. #endif
  20806. /* put Certificate Policies */
  20807. if (der->certPoliciesSz) {
  20808. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  20809. &der->extensionsSz,
  20810. der->certPolicies, der->certPoliciesSz);
  20811. if (ret <= 0)
  20812. return EXTENSIONS_E;
  20813. }
  20814. #endif /* WOLFSSL_CERT_EXT */
  20815. }
  20816. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  20817. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  20818. der->extensionsSz;
  20819. return 0;
  20820. }
  20821. /* write DER encoded cert to buffer, size already checked */
  20822. static int WriteCertBody(DerCert* der, byte* buf)
  20823. {
  20824. int idx;
  20825. /* signed part header */
  20826. idx = SetSequence(der->total, buf);
  20827. /* version */
  20828. XMEMCPY(buf + idx, der->version, der->versionSz);
  20829. idx += der->versionSz;
  20830. /* serial */
  20831. XMEMCPY(buf + idx, der->serial, der->serialSz);
  20832. idx += der->serialSz;
  20833. /* sig algo */
  20834. XMEMCPY(buf + idx, der->sigAlgo, der->sigAlgoSz);
  20835. idx += der->sigAlgoSz;
  20836. /* issuer */
  20837. XMEMCPY(buf + idx, der->issuer, der->issuerSz);
  20838. idx += der->issuerSz;
  20839. /* validity */
  20840. XMEMCPY(buf + idx, der->validity, der->validitySz);
  20841. idx += der->validitySz;
  20842. /* subject */
  20843. XMEMCPY(buf + idx, der->subject, der->subjectSz);
  20844. idx += der->subjectSz;
  20845. /* public key */
  20846. XMEMCPY(buf + idx, der->publicKey, der->publicKeySz);
  20847. idx += der->publicKeySz;
  20848. if (der->extensionsSz) {
  20849. /* extensions */
  20850. XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz,
  20851. (int)sizeof(der->extensions)));
  20852. idx += der->extensionsSz;
  20853. }
  20854. return idx;
  20855. }
  20856. #endif /* !WOLFSSL_ASN_TEMPLATE */
  20857. /* Make RSA signature from buffer (sz), write to sig (sigSz) */
  20858. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz,
  20859. byte* sig, int sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  20860. ed25519_key* ed25519Key, ed448_key* ed448Key, falcon_key* falconKey,
  20861. WC_RNG* rng, int sigAlgoType, void* heap)
  20862. {
  20863. int digestSz = 0, typeH = 0, ret = 0;
  20864. (void)digestSz;
  20865. (void)typeH;
  20866. (void)buf;
  20867. (void)sz;
  20868. (void)sig;
  20869. (void)sigSz;
  20870. (void)rsaKey;
  20871. (void)eccKey;
  20872. (void)ed25519Key;
  20873. (void)ed448Key;
  20874. (void)falconKey;
  20875. (void)rng;
  20876. (void)heap;
  20877. switch (certSignCtx->state) {
  20878. case CERTSIGN_STATE_BEGIN:
  20879. case CERTSIGN_STATE_DIGEST:
  20880. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  20881. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  20882. DYNAMIC_TYPE_TMP_BUFFER);
  20883. if (certSignCtx->digest == NULL) {
  20884. ret = MEMORY_E; goto exit_ms;
  20885. }
  20886. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  20887. &typeH, &digestSz, 0);
  20888. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  20889. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  20890. if (ret != 0) {
  20891. goto exit_ms;
  20892. }
  20893. FALL_THROUGH;
  20894. case CERTSIGN_STATE_ENCODE:
  20895. #ifndef NO_RSA
  20896. if (rsaKey) {
  20897. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  20898. DYNAMIC_TYPE_TMP_BUFFER);
  20899. if (certSignCtx->encSig == NULL) {
  20900. ret = MEMORY_E; goto exit_ms;
  20901. }
  20902. /* signature */
  20903. certSignCtx->encSigSz = wc_EncodeSignature(certSignCtx->encSig,
  20904. certSignCtx->digest, digestSz, typeH);
  20905. }
  20906. #endif /* !NO_RSA */
  20907. FALL_THROUGH;
  20908. case CERTSIGN_STATE_DO:
  20909. certSignCtx->state = CERTSIGN_STATE_DO;
  20910. ret = ALGO_ID_E; /* default to error */
  20911. #ifndef NO_RSA
  20912. if (rsaKey) {
  20913. /* signature */
  20914. ret = wc_RsaSSL_Sign(certSignCtx->encSig, certSignCtx->encSigSz,
  20915. sig, sigSz, rsaKey, rng);
  20916. }
  20917. #endif /* !NO_RSA */
  20918. #ifdef HAVE_ECC
  20919. if (!rsaKey && eccKey) {
  20920. word32 outSz = sigSz;
  20921. ret = wc_ecc_sign_hash(certSignCtx->digest, digestSz,
  20922. sig, &outSz, rng, eccKey);
  20923. if (ret == 0)
  20924. ret = outSz;
  20925. }
  20926. #endif /* HAVE_ECC */
  20927. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_SIGN)
  20928. if (!rsaKey && !eccKey && ed25519Key) {
  20929. word32 outSz = sigSz;
  20930. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  20931. if (ret == 0)
  20932. ret = outSz;
  20933. }
  20934. #endif /* HAVE_ED25519 && HAVE_ED25519_SIGN */
  20935. #if defined(HAVE_ED448) && defined(HAVE_ED448_SIGN)
  20936. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  20937. word32 outSz = sigSz;
  20938. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  20939. if (ret == 0)
  20940. ret = outSz;
  20941. }
  20942. #endif /* HAVE_ED448 && HAVE_ED448_SIGN */
  20943. #if defined(HAVE_LIBOQS)
  20944. if (!rsaKey && !eccKey && !ed25519Key && !ed448Key && falconKey) {
  20945. word32 outSz = sigSz;
  20946. ret = wc_falcon_sign_msg(buf, sz, sig, &outSz, falconKey);
  20947. if (ret == 0)
  20948. ret = outSz;
  20949. }
  20950. #endif /* HAVE_LIBOQS */
  20951. break;
  20952. }
  20953. exit_ms:
  20954. #ifdef WOLFSSL_ASYNC_CRYPT
  20955. if (ret == WC_PENDING_E) {
  20956. return ret;
  20957. }
  20958. #endif
  20959. #ifndef NO_RSA
  20960. if (rsaKey) {
  20961. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  20962. }
  20963. #endif /* !NO_RSA */
  20964. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  20965. certSignCtx->digest = NULL;
  20966. /* reset state */
  20967. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  20968. return ret;
  20969. }
  20970. #ifdef WOLFSSL_ASN_TEMPLATE
  20971. /* Generate a random integer value of at most len bytes.
  20972. *
  20973. * Most-significant bit will not be set when maximum size.
  20974. * Random value may be smaller than maximum size in bytes.
  20975. *
  20976. * @param [in] rng Random number generator.
  20977. * @param [out] out Buffer to hold integer value.
  20978. * @param [in] len Maximum number of bytes of integer.
  20979. * @return 0 on success.
  20980. * @return -ve when random number generation failed.
  20981. */
  20982. static int GenerateInteger(WC_RNG* rng, byte* out, int len)
  20983. {
  20984. int ret;
  20985. /* Generate random number. */
  20986. ret = wc_RNG_GenerateBlock(rng, out, len);
  20987. if (ret == 0) {
  20988. int i;
  20989. /* Clear the top bit to make positive. */
  20990. out[0] &= 0x7f;
  20991. /* Find first non-zero byte. One zero byte is valid though. */
  20992. for (i = 0; i < len - 1; i++) {
  20993. if (out[i] != 0) {
  20994. break;
  20995. }
  20996. }
  20997. if (i != 0) {
  20998. /* Remove leading zeros. */
  20999. XMEMMOVE(out, out + i, len - i);
  21000. }
  21001. }
  21002. return ret;
  21003. }
  21004. /* ASN.1 template for a Certificate.
  21005. * X.509: RFC 5280, 4.1 - Basic Certificate Fields.
  21006. */
  21007. static const ASNItem sigASN[] = {
  21008. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  21009. /* tbsCertificate */
  21010. /* 1 */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  21011. /* signatureAlgorithm */
  21012. /* 2 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  21013. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  21014. /* 4 */ { 2, ASN_TAG_NULL, 0, 0, 0 },
  21015. /* signatureValue */
  21016. /* 5 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  21017. };
  21018. /* Number of items in ASN.1 template for a Certificate. */
  21019. #define sigASN_Length (sizeof(sigASN) / sizeof(ASNItem))
  21020. #endif
  21021. /* add signature to end of buffer, size of buffer assumed checked, return
  21022. new length */
  21023. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  21024. int sigAlgoType)
  21025. {
  21026. #ifndef WOLFSSL_ASN_TEMPLATE
  21027. byte seq[MAX_SEQ_SZ];
  21028. int idx = bodySz, seqSz;
  21029. /* algo */
  21030. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  21031. /* bit string */
  21032. idx += SetBitString(sigSz, 0, buf ? buf + idx : NULL);
  21033. /* signature */
  21034. if (buf)
  21035. XMEMCPY(buf + idx, sig, sigSz);
  21036. idx += sigSz;
  21037. /* make room for overall header */
  21038. seqSz = SetSequence(idx, seq);
  21039. if (buf) {
  21040. XMEMMOVE(buf + seqSz, buf, idx);
  21041. XMEMCPY(buf, seq, seqSz);
  21042. }
  21043. return idx + seqSz;
  21044. #else
  21045. DECL_ASNSETDATA(dataASN, sigASN_Length);
  21046. word32 seqSz;
  21047. int sz;
  21048. int ret = 0;
  21049. CALLOC_ASNSETDATA(dataASN, sigASN_Length, ret, NULL);
  21050. /* In place, put body between SEQUENCE and signature. */
  21051. if (ret == 0) {
  21052. /* Set sigature OID and signature data. */
  21053. SetASN_OID(&dataASN[3], sigAlgoType, oidSigType);
  21054. if (IsSigAlgoECC(sigAlgoType)) {
  21055. /* ECDSA and EdDSA doesn't have NULL tagged item. */
  21056. dataASN[4].noOut = 1;
  21057. }
  21058. SetASN_Buffer(&dataASN[5], sig, sigSz);
  21059. /* Calcuate size of signature data. */
  21060. ret = SizeASN_Items(&sigASN[2], &dataASN[2], sigASN_Length - 2, &sz);
  21061. }
  21062. if (ret == 0) {
  21063. /* Calculate size of outer sequence by calculating size of the encoded
  21064. * length and adding 1 for tag. */
  21065. seqSz = SizeASNHeader(bodySz + sz);
  21066. if (buf != NULL) {
  21067. /* Move body to after sequence. */
  21068. XMEMMOVE(buf + seqSz, buf, bodySz);
  21069. }
  21070. /* Leave space for body in encoding. */
  21071. SetASN_ReplaceBuffer(&dataASN[1], NULL, bodySz);
  21072. /* Calculate overall size and put in offsets and lengths. */
  21073. ret = SizeASN_Items(sigASN, dataASN, sigASN_Length, &sz);
  21074. }
  21075. if ((ret == 0) && (buf != NULL)) {
  21076. /* Write SEQUENCE and signature around body. */
  21077. SetASN_Items(sigASN, dataASN, sigASN_Length, buf);
  21078. }
  21079. if (ret == 0) {
  21080. /* Return the encoding size. */
  21081. ret = sz;
  21082. }
  21083. FREE_ASNSETDATA(dataASN, NULL);
  21084. return ret;
  21085. #endif /* WOLFSSL_ASN_TEMPLATE */
  21086. }
  21087. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  21088. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  21089. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  21090. DsaKey* dsaKey, ed25519_key* ed25519Key,
  21091. ed448_key* ed448Key, falcon_key* falconKey)
  21092. {
  21093. #ifndef WOLFSSL_ASN_TEMPLATE
  21094. int ret;
  21095. #ifdef WOLFSSL_SMALL_STACK
  21096. DerCert* der;
  21097. #else
  21098. DerCert der[1];
  21099. #endif
  21100. if (derBuffer == NULL)
  21101. return BAD_FUNC_ARG;
  21102. if (eccKey)
  21103. cert->keyType = ECC_KEY;
  21104. else if (rsaKey)
  21105. cert->keyType = RSA_KEY;
  21106. else if (dsaKey)
  21107. cert->keyType = DSA_KEY;
  21108. else if (ed25519Key)
  21109. cert->keyType = ED25519_KEY;
  21110. else if (ed448Key)
  21111. cert->keyType = ED448_KEY;
  21112. #ifdef HAVE_LIBOQS
  21113. else if ((falconKey != NULL) && (falconKey->level == 1))
  21114. cert->keyType = FALCON_LEVEL1_KEY;
  21115. else if ((falconKey != NULL) && (falconKey->level == 5))
  21116. cert->keyType = FALCON_LEVEL5_KEY;
  21117. #endif
  21118. else
  21119. return BAD_FUNC_ARG;
  21120. #ifdef WOLFSSL_SMALL_STACK
  21121. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  21122. if (der == NULL)
  21123. return MEMORY_E;
  21124. #endif
  21125. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, dsaKey, ed25519Key,
  21126. ed448Key, falconKey);
  21127. if (ret == 0) {
  21128. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  21129. ret = BUFFER_E;
  21130. else
  21131. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  21132. }
  21133. #ifdef WOLFSSL_SMALL_STACK
  21134. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  21135. #endif
  21136. return ret;
  21137. #else
  21138. /* TODO: issRaw and sbjRaw should be NUL terminated. */
  21139. DECL_ASNSETDATA(dataASN, x509CertASN_Length);
  21140. word32 publicKeySz = 0;
  21141. word32 issuerSz = 0;
  21142. word32 subjectSz = 0;
  21143. word32 extSz = 0;
  21144. int sz;
  21145. int ret = 0;
  21146. word32 issRawLen = 0;
  21147. word32 sbjRawLen = 0;
  21148. CALLOC_ASNSETDATA(dataASN, x509CertASN_Length, ret, cert->heap);
  21149. if (ret == 0) {
  21150. /* Set key type into certificate object based on key passed in. */
  21151. if (rsaKey) {
  21152. cert->keyType = RSA_KEY;
  21153. }
  21154. else if (eccKey) {
  21155. cert->keyType = ECC_KEY;
  21156. }
  21157. else if (dsaKey) {
  21158. cert->keyType = DSA_KEY;
  21159. }
  21160. else if (ed25519Key) {
  21161. cert->keyType = ED25519_KEY;
  21162. }
  21163. else if (ed448Key) {
  21164. cert->keyType = ED448_KEY;
  21165. }
  21166. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  21167. cert->keyType = FALCON_LEVEL1_KEY;
  21168. }
  21169. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  21170. cert->keyType = FALCON_LEVEL5_KEY;
  21171. }
  21172. else {
  21173. ret = BAD_FUNC_ARG;
  21174. }
  21175. }
  21176. if ((ret == 0) && (cert->serialSz == 0)) {
  21177. /* Generate random serial number. */
  21178. cert->serialSz = CTC_GEN_SERIAL_SZ;
  21179. ret = GenerateInteger(rng, cert->serial, CTC_GEN_SERIAL_SZ);
  21180. }
  21181. if (ret == 0) {
  21182. /* Determine issuer name size. */
  21183. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  21184. defined(WOLFSSL_CERT_REQ)
  21185. issRawLen = (word32)XSTRLEN((const char*)cert->issRaw);
  21186. if (issRawLen > 0) {
  21187. issuerSz = min(sizeof(cert->issRaw), issRawLen);
  21188. }
  21189. else
  21190. #endif
  21191. {
  21192. /* Calcuate issuer name encoding size. */
  21193. issuerSz = SetNameEx(NULL, ASN_NAME_MAX, &cert->issuer, cert->heap);
  21194. ret = issuerSz;
  21195. }
  21196. }
  21197. if (ret >= 0) {
  21198. /* Determine subject name size. */
  21199. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  21200. defined(WOLFSSL_CERT_REQ)
  21201. sbjRawLen = (word32)XSTRLEN((const char*)cert->sbjRaw);
  21202. if (sbjRawLen > 0) {
  21203. subjectSz = min(sizeof(cert->sbjRaw), sbjRawLen);
  21204. }
  21205. else
  21206. #endif
  21207. {
  21208. /* Calcuate subject name encoding size. */
  21209. subjectSz = SetNameEx(NULL, ASN_NAME_MAX, &cert->subject, cert->heap);
  21210. ret = subjectSz;
  21211. }
  21212. }
  21213. if (ret >= 0) {
  21214. /* Calcuate public key encoding size. */
  21215. ret = publicKeySz = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  21216. eccKey, ed25519Key, ed448Key, dsaKey);
  21217. }
  21218. if (ret >= 0) {
  21219. /* Calcuate extensions encoding size - may be 0. */
  21220. ret = extSz = EncodeExtensions(cert, NULL, 0, 0);
  21221. }
  21222. if (ret >= 0) {
  21223. /* Don't write out outer sequence - only doing body. */
  21224. dataASN[0].noOut = 1;
  21225. /* Set version, serial number and signature OID */
  21226. SetASN_Int8Bit(&dataASN[3], cert->version);
  21227. SetASN_Buffer(&dataASN[4], cert->serial, cert->serialSz);
  21228. SetASN_OID(&dataASN[6], cert->sigType, oidSigType);
  21229. if (IsSigAlgoECC(cert->sigType)) {
  21230. /* No NULL tagged item with ECDSA and EdDSA signature OIDs. */
  21231. dataASN[7].noOut = 1;
  21232. }
  21233. if (issRawLen > 0) {
  21234. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  21235. defined(WOLFSSL_CERT_REQ)
  21236. /* Put in encoded issuer name. */
  21237. SetASN_Buffer(&dataASN[8], cert->issRaw, issuerSz);
  21238. #endif
  21239. }
  21240. else {
  21241. /* Leave space for issuer name. */
  21242. SetASN_ReplaceBuffer(&dataASN[8], NULL, issuerSz);
  21243. }
  21244. #ifdef WOLFSSL_ALT_NAMES
  21245. if (cert->beforeDateSz && cert->afterDateSz) {
  21246. if (cert->beforeDate[0] == ASN_UTC_TIME) {
  21247. /* Make space for before date data. */
  21248. SetASN_Buffer(&dataASN[10], cert->beforeDate + 2,
  21249. ASN_UTC_TIME_SIZE - 1);
  21250. /* Don't put out Generalized Time before data. */
  21251. dataASN[11].noOut = 1;
  21252. }
  21253. else {
  21254. /* Don't put out UTC before data. */
  21255. dataASN[10].noOut = 1;
  21256. /* Make space for before date data. */
  21257. SetASN_Buffer(&dataASN[11], cert->beforeDate + 2,
  21258. ASN_GEN_TIME_SZ);
  21259. }
  21260. if (cert->afterDate[0] == ASN_UTC_TIME) {
  21261. /* Make space for after date data. */
  21262. SetASN_Buffer(&dataASN[12], cert->afterDate + 2,
  21263. ASN_UTC_TIME_SIZE - 1);
  21264. /* Don't put out UTC Generalized Time after data. */
  21265. dataASN[13].noOut = 1;
  21266. }
  21267. else {
  21268. /* Don't put out UTC after data. */
  21269. dataASN[12].noOut = 1;
  21270. /* Make space for after date data. */
  21271. SetASN_Buffer(&dataASN[13], cert->afterDate + 2,
  21272. ASN_GEN_TIME_SZ);
  21273. }
  21274. }
  21275. else
  21276. #endif
  21277. {
  21278. /* Don't put out UTC before data. */
  21279. dataASN[10].noOut = 1;
  21280. /* Make space for before date data. */
  21281. SetASN_Buffer(&dataASN[11], NULL, ASN_GEN_TIME_SZ);
  21282. /* Don't put out UTC after data. */
  21283. dataASN[12].noOut = 1;
  21284. /* Make space for after date data. */
  21285. SetASN_Buffer(&dataASN[13], NULL, ASN_GEN_TIME_SZ);
  21286. }
  21287. if (sbjRawLen > 0) {
  21288. /* Put in encoded subject name. */
  21289. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA) || \
  21290. defined(WOLFSSL_CERT_REQ)
  21291. SetASN_Buffer(&dataASN[14], cert->sbjRaw, subjectSz);
  21292. #endif
  21293. }
  21294. else {
  21295. /* Leave space for subject name. */
  21296. SetASN_ReplaceBuffer(&dataASN[14], NULL, subjectSz);
  21297. }
  21298. /* Leave space for public key. */
  21299. SetASN_ReplaceBuffer(&dataASN[15], NULL, publicKeySz);
  21300. /* Replacement buffer instead of algorithm identifier items. */
  21301. SetASNItem_NoOut(dataASN, 16, 20);
  21302. /* issuerUniqueID and subjectUniqueID not supported. */
  21303. dataASN[21].noOut = dataASN[22].noOut = 1;
  21304. /* Leave space for extensions if any set into certificate object. */
  21305. if (extSz > 0) {
  21306. SetASN_Buffer(&dataASN[23], NULL, extSz);
  21307. }
  21308. else {
  21309. dataASN[23].noOut = 1;
  21310. }
  21311. /* No signature - added later. */
  21312. SetASNItem_NoOut(dataASN, 24, 27);
  21313. /* Calculate encoded certificate body size. */
  21314. ret = SizeASN_Items(x509CertASN, dataASN, x509CertASN_Length, &sz);
  21315. }
  21316. /* Check buffer is big enough for encoded data. */
  21317. if ((ret == 0) && (sz > (int)derSz)) {
  21318. ret = BUFFER_E;
  21319. }
  21320. if (ret == 0) {
  21321. /* Encode certificate body into buffer. */
  21322. SetASN_Items(x509CertASN, dataASN, x509CertASN_Length, derBuffer);
  21323. if (issRawLen == 0) {
  21324. /* Encode issuer name into buffer. */
  21325. ret = SetNameEx((byte*)dataASN[8].data.buffer.data,
  21326. dataASN[8].data.buffer.length, &cert->issuer, cert->heap);
  21327. }
  21328. }
  21329. if ((ret >= 0) && (sbjRawLen == 0)) {
  21330. /* Encode subject name into buffer. */
  21331. ret = SetNameEx((byte*)dataASN[14].data.buffer.data,
  21332. dataASN[14].data.buffer.length, &cert->subject, cert->heap);
  21333. }
  21334. if (ret >= 0) {
  21335. #ifdef WOLFSSL_ALT_NAMES
  21336. if (cert->beforeDateSz == 0 || cert->afterDateSz == 0)
  21337. #endif
  21338. {
  21339. /* Encode validity into buffer. */
  21340. ret = SetValidity((byte*)dataASN[11].data.buffer.data,
  21341. (byte*)dataASN[13].data.buffer.data, cert->daysValid);
  21342. }
  21343. }
  21344. if (ret >= 0) {
  21345. /* Encode public key into buffer. */
  21346. ret = EncodePublicKey(cert->keyType,
  21347. (byte*)dataASN[15].data.buffer.data, dataASN[15].data.buffer.length,
  21348. rsaKey, eccKey, ed25519Key, ed448Key, dsaKey);
  21349. }
  21350. if ((ret >= 0) && (!dataASN[23].noOut)) {
  21351. /* Encode extensions into buffer. */
  21352. ret = EncodeExtensions(cert, (byte*)dataASN[23].data.buffer.data,
  21353. dataASN[23].data.buffer.length, 0);
  21354. }
  21355. if (ret >= 0) {
  21356. /* Store encoded certifcate body size. */
  21357. cert->bodySz = sz;
  21358. /* Return the encoding size. */
  21359. ret = sz;
  21360. }
  21361. FREE_ASNSETDATA(dataASN, cert->heap);
  21362. return ret;
  21363. #endif
  21364. }
  21365. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  21366. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  21367. void* key, WC_RNG* rng)
  21368. {
  21369. RsaKey* rsaKey = NULL;
  21370. DsaKey* dsaKey = NULL;
  21371. ecc_key* eccKey = NULL;
  21372. ed25519_key* ed25519Key = NULL;
  21373. ed448_key* ed448Key = NULL;
  21374. falcon_key* falconKey = NULL;
  21375. if (keyType == RSA_TYPE)
  21376. rsaKey = (RsaKey*)key;
  21377. else if (keyType == DSA_TYPE)
  21378. dsaKey = (DsaKey*)key;
  21379. else if (keyType == ECC_TYPE)
  21380. eccKey = (ecc_key*)key;
  21381. else if (keyType == ED25519_TYPE)
  21382. ed25519Key = (ed25519_key*)key;
  21383. else if (keyType == ED448_TYPE)
  21384. ed448Key = (ed448_key*)key;
  21385. else if (keyType == FALCON_LEVEL1_TYPE)
  21386. falconKey = (falcon_key*)key;
  21387. else if (keyType == FALCON_LEVEL5_TYPE)
  21388. falconKey = (falcon_key*)key;
  21389. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  21390. ed25519Key, ed448Key, falconKey);
  21391. }
  21392. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  21393. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  21394. ecc_key* eccKey, WC_RNG* rng)
  21395. {
  21396. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL,
  21397. NULL, NULL);
  21398. }
  21399. #ifdef WOLFSSL_CERT_REQ
  21400. #ifndef WOLFSSL_ASN_TEMPLATE
  21401. static int SetReqAttrib(byte* output, char* pw, int pwPrintableString,
  21402. int extSz)
  21403. {
  21404. const byte erOid[] =
  21405. { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
  21406. 0x09, 0x0e };
  21407. int sz = 0; /* overall size */
  21408. int cpSz = 0; /* Challenge Password section size */
  21409. int cpSeqSz = 0;
  21410. int cpSetSz = 0;
  21411. int cpStrSz = 0;
  21412. int pwSz = 0;
  21413. int erSz = 0; /* Extension Request section size */
  21414. int erSeqSz = 0;
  21415. int erSetSz = 0;
  21416. byte cpSeq[MAX_SEQ_SZ];
  21417. byte cpSet[MAX_SET_SZ];
  21418. byte cpStr[MAX_PRSTR_SZ];
  21419. byte erSeq[MAX_SEQ_SZ];
  21420. byte erSet[MAX_SET_SZ];
  21421. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  21422. sz++;
  21423. if (pw && pw[0]) {
  21424. pwSz = (int)XSTRLEN(pw);
  21425. if (pwPrintableString) {
  21426. cpStrSz = SetPrintableString(pwSz, cpStr);
  21427. } else {
  21428. cpStrSz = SetUTF8String(pwSz, cpStr);
  21429. }
  21430. cpSetSz = SetSet(cpStrSz + pwSz, cpSet);
  21431. /* +2 for tag and length parts of the TLV triplet */
  21432. cpSeqSz = SetSequence(2 + sizeof(attrChallengePasswordOid) + cpSetSz +
  21433. cpStrSz + pwSz, cpSeq);
  21434. cpSz = cpSeqSz + 2 + sizeof(attrChallengePasswordOid) + cpSetSz +
  21435. cpStrSz + pwSz;
  21436. }
  21437. if (extSz) {
  21438. erSetSz = SetSet(extSz, erSet);
  21439. erSeqSz = SetSequence(erSetSz + sizeof(erOid) + extSz, erSeq);
  21440. erSz = extSz + erSetSz + erSeqSz + sizeof(erOid);
  21441. }
  21442. /* Put the pieces together. */
  21443. sz += SetLength(cpSz + erSz, &output[sz]);
  21444. if (cpSz) {
  21445. XMEMCPY(&output[sz], cpSeq, cpSeqSz);
  21446. sz += cpSeqSz;
  21447. sz += SetObjectId(sizeof(attrChallengePasswordOid), output + sz);
  21448. XMEMCPY(&output[sz], attrChallengePasswordOid,
  21449. sizeof(attrChallengePasswordOid));
  21450. sz += sizeof(attrChallengePasswordOid);
  21451. XMEMCPY(&output[sz], cpSet, cpSetSz);
  21452. sz += cpSetSz;
  21453. XMEMCPY(&output[sz], cpStr, cpStrSz);
  21454. sz += cpStrSz;
  21455. XMEMCPY(&output[sz], pw, pwSz);
  21456. sz += pwSz;
  21457. }
  21458. if (erSz) {
  21459. XMEMCPY(&output[sz], erSeq, erSeqSz);
  21460. sz += erSeqSz;
  21461. XMEMCPY(&output[sz], erOid, sizeof(erOid));
  21462. sz += sizeof(erOid);
  21463. XMEMCPY(&output[sz], erSet, erSetSz);
  21464. sz += erSetSz;
  21465. /* The actual extension data will be tacked onto the output later. */
  21466. }
  21467. return sz;
  21468. }
  21469. /* encode info from cert into DER encoded format */
  21470. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  21471. DsaKey* dsaKey, ecc_key* eccKey,
  21472. ed25519_key* ed25519Key, ed448_key* ed448Key,
  21473. falcon_key* falconKey)
  21474. {
  21475. (void)eccKey;
  21476. (void)ed25519Key;
  21477. (void)ed448Key;
  21478. (void)falconKey;
  21479. if (cert == NULL || der == NULL)
  21480. return BAD_FUNC_ARG;
  21481. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  21482. dsaKey == NULL && ed448Key == NULL && falconKey == NULL) {
  21483. return PUBLIC_KEY_E;
  21484. }
  21485. /* init */
  21486. XMEMSET(der, 0, sizeof(DerCert));
  21487. /* version */
  21488. der->versionSz = SetMyVersion(cert->version, der->version, FALSE);
  21489. /* subject name */
  21490. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  21491. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  21492. /* Use the raw subject */
  21493. int idx;
  21494. der->subjectSz = min(sizeof(der->subject),
  21495. (word32)XSTRLEN((const char*)cert->sbjRaw));
  21496. /* header */
  21497. idx = SetSequence(der->subjectSz, der->subject);
  21498. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  21499. return SUBJECT_E;
  21500. }
  21501. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  21502. der->subjectSz);
  21503. der->subjectSz += idx;
  21504. }
  21505. else
  21506. #endif
  21507. {
  21508. der->subjectSz = SetNameEx(der->subject, sizeof(der->subject),
  21509. &cert->subject, cert->heap);
  21510. }
  21511. if (der->subjectSz <= 0)
  21512. return SUBJECT_E;
  21513. /* public key */
  21514. #ifndef NO_RSA
  21515. if (cert->keyType == RSA_KEY) {
  21516. if (rsaKey == NULL)
  21517. return PUBLIC_KEY_E;
  21518. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  21519. sizeof(der->publicKey), 1);
  21520. }
  21521. #endif
  21522. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  21523. if (cert->keyType == DSA_KEY) {
  21524. if (dsaKey == NULL)
  21525. return PUBLIC_KEY_E;
  21526. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  21527. sizeof(der->publicKey), 1);
  21528. }
  21529. #endif
  21530. #ifdef HAVE_ECC
  21531. if (cert->keyType == ECC_KEY) {
  21532. if (eccKey == NULL)
  21533. return PUBLIC_KEY_E;
  21534. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey,
  21535. sizeof(der->publicKey), 1);
  21536. }
  21537. #endif
  21538. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  21539. if (cert->keyType == ED25519_KEY) {
  21540. if (ed25519Key == NULL)
  21541. return PUBLIC_KEY_E;
  21542. der->publicKeySz = wc_Ed25519PublicKeyToDer(ed25519Key, der->publicKey,
  21543. (word32)sizeof(der->publicKey), 1);
  21544. }
  21545. #endif
  21546. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  21547. if (cert->keyType == ED448_KEY) {
  21548. if (ed448Key == NULL)
  21549. return PUBLIC_KEY_E;
  21550. der->publicKeySz = wc_Ed448PublicKeyToDer(ed448Key, der->publicKey,
  21551. (word32)sizeof(der->publicKey), 1);
  21552. }
  21553. #endif
  21554. #if defined(HAVE_LIBOQS)
  21555. if ((cert->keyType == FALCON_LEVEL1_KEY) ||
  21556. (cert->keyType == FALCON_LEVEL5_KEY)) {
  21557. if (falconKey == NULL)
  21558. return PUBLIC_KEY_E;
  21559. der->publicKeySz = wc_Falcon_PublicKeyToDer(falconKey,
  21560. der->publicKey, (word32)sizeof(der->publicKey), 1);
  21561. }
  21562. #endif
  21563. if (der->publicKeySz <= 0)
  21564. return PUBLIC_KEY_E;
  21565. /* set the extensions */
  21566. der->extensionsSz = 0;
  21567. /* CA */
  21568. if (cert->isCA) {
  21569. der->caSz = SetCa(der->ca, sizeof(der->ca));
  21570. if (der->caSz <= 0)
  21571. return CA_TRUE_E;
  21572. der->extensionsSz += der->caSz;
  21573. }
  21574. else
  21575. der->caSz = 0;
  21576. #ifdef WOLFSSL_ALT_NAMES
  21577. /* Alternative Name */
  21578. if (cert->altNamesSz) {
  21579. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  21580. cert->altNames, cert->altNamesSz);
  21581. if (der->altNamesSz <= 0)
  21582. return ALT_NAME_E;
  21583. der->extensionsSz += der->altNamesSz;
  21584. }
  21585. else
  21586. der->altNamesSz = 0;
  21587. #endif
  21588. #ifdef WOLFSSL_CERT_EXT
  21589. /* SKID */
  21590. if (cert->skidSz) {
  21591. /* check the provided SKID size */
  21592. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  21593. return SKID_E;
  21594. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  21595. cert->skid, cert->skidSz);
  21596. if (der->skidSz <= 0)
  21597. return SKID_E;
  21598. der->extensionsSz += der->skidSz;
  21599. }
  21600. else
  21601. der->skidSz = 0;
  21602. /* Key Usage */
  21603. if (cert->keyUsage != 0){
  21604. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  21605. cert->keyUsage);
  21606. if (der->keyUsageSz <= 0)
  21607. return KEYUSAGE_E;
  21608. der->extensionsSz += der->keyUsageSz;
  21609. }
  21610. else
  21611. der->keyUsageSz = 0;
  21612. /* Extended Key Usage */
  21613. if (cert->extKeyUsage != 0){
  21614. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  21615. sizeof(der->extKeyUsage), cert->extKeyUsage);
  21616. if (der->extKeyUsageSz <= 0)
  21617. return EXTKEYUSAGE_E;
  21618. der->extensionsSz += der->extKeyUsageSz;
  21619. }
  21620. else
  21621. der->extKeyUsageSz = 0;
  21622. #endif /* WOLFSSL_CERT_EXT */
  21623. /* put extensions */
  21624. if (der->extensionsSz > 0) {
  21625. int ret;
  21626. /* put the start of sequence (ID, Size) */
  21627. der->extensionsSz = SetSequence(der->extensionsSz, der->extensions);
  21628. if (der->extensionsSz <= 0)
  21629. return EXTENSIONS_E;
  21630. /* put CA */
  21631. if (der->caSz) {
  21632. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  21633. &der->extensionsSz,
  21634. der->ca, der->caSz);
  21635. if (ret <= 0)
  21636. return EXTENSIONS_E;
  21637. }
  21638. #ifdef WOLFSSL_ALT_NAMES
  21639. /* put Alternative Names */
  21640. if (der->altNamesSz) {
  21641. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  21642. &der->extensionsSz,
  21643. der->altNames, der->altNamesSz);
  21644. if (ret <= 0)
  21645. return EXTENSIONS_E;
  21646. }
  21647. #endif
  21648. #ifdef WOLFSSL_CERT_EXT
  21649. /* put SKID */
  21650. if (der->skidSz) {
  21651. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  21652. &der->extensionsSz,
  21653. der->skid, der->skidSz);
  21654. if (ret <= 0)
  21655. return EXTENSIONS_E;
  21656. }
  21657. /* put AKID */
  21658. if (der->akidSz) {
  21659. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  21660. &der->extensionsSz,
  21661. der->akid, der->akidSz);
  21662. if (ret <= 0)
  21663. return EXTENSIONS_E;
  21664. }
  21665. /* put KeyUsage */
  21666. if (der->keyUsageSz) {
  21667. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  21668. &der->extensionsSz,
  21669. der->keyUsage, der->keyUsageSz);
  21670. if (ret <= 0)
  21671. return EXTENSIONS_E;
  21672. }
  21673. /* put ExtendedKeyUsage */
  21674. if (der->extKeyUsageSz) {
  21675. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  21676. &der->extensionsSz,
  21677. der->extKeyUsage, der->extKeyUsageSz);
  21678. if (ret <= 0)
  21679. return EXTENSIONS_E;
  21680. }
  21681. #endif /* WOLFSSL_CERT_EXT */
  21682. }
  21683. der->attribSz = SetReqAttrib(der->attrib, cert->challengePw,
  21684. cert->challengePwPrintableString,
  21685. der->extensionsSz);
  21686. if (der->attribSz <= 0)
  21687. return REQ_ATTRIBUTE_E;
  21688. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  21689. der->extensionsSz + der->attribSz;
  21690. return 0;
  21691. }
  21692. /* write DER encoded cert req to buffer, size already checked */
  21693. static int WriteCertReqBody(DerCert* der, byte* buf)
  21694. {
  21695. int idx;
  21696. /* signed part header */
  21697. idx = SetSequence(der->total, buf);
  21698. /* version */
  21699. if (buf)
  21700. XMEMCPY(buf + idx, der->version, der->versionSz);
  21701. idx += der->versionSz;
  21702. /* subject */
  21703. if (buf)
  21704. XMEMCPY(buf + idx, der->subject, der->subjectSz);
  21705. idx += der->subjectSz;
  21706. /* public key */
  21707. if (buf)
  21708. XMEMCPY(buf + idx, der->publicKey, der->publicKeySz);
  21709. idx += der->publicKeySz;
  21710. /* attributes */
  21711. if (buf)
  21712. XMEMCPY(buf + idx, der->attrib, der->attribSz);
  21713. idx += der->attribSz;
  21714. /* extensions */
  21715. if (der->extensionsSz) {
  21716. if (buf)
  21717. XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz,
  21718. (int)sizeof(der->extensions)));
  21719. idx += der->extensionsSz;
  21720. }
  21721. return idx;
  21722. }
  21723. #endif
  21724. #ifdef WOLFSSL_ASN_TEMPLATE
  21725. /* ASN.1 template for Certificate Request body.
  21726. * PKCS #10: RFC 2986, 4.1 - CertificationRequestInfo
  21727. */
  21728. static const ASNItem certReqBodyASN[] = {
  21729. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  21730. /* version */
  21731. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  21732. /* subject */
  21733. /* 2 */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  21734. /* subjectPKInfo */
  21735. /* 3 */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  21736. /* attributes*/
  21737. /* 4 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  21738. /* Challenge Password Attribute */
  21739. /* 5 */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  21740. /* 6 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  21741. /* 7 */ { 3, ASN_SET, 1, 1, 0 },
  21742. /* 8 */ { 4, ASN_PRINTABLE_STRING, 0, 0, 0 },
  21743. /* 9 */ { 4, ASN_UTF8STRING, 0, 0, 0 },
  21744. /* Extensions Attribute */
  21745. /* 10 */ { 2, ASN_SEQUENCE, 1, 1, 1 },
  21746. /* 11 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  21747. /* 12 */ { 3, ASN_SET, 1, 1, 0 },
  21748. /* 13 */ { 4, ASN_SEQUENCE, 1, 0, 0 },
  21749. };
  21750. /* Number of items in ASN.1 template for Certificate Request body. */
  21751. #define certReqBodyASN_Length (sizeof(certReqBodyASN) / sizeof(ASNItem))
  21752. #endif
  21753. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  21754. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  21755. ed25519_key* ed25519Key, ed448_key* ed448Key,
  21756. falcon_key* falconKey)
  21757. {
  21758. #ifndef WOLFSSL_ASN_TEMPLATE
  21759. int ret;
  21760. #ifdef WOLFSSL_SMALL_STACK
  21761. DerCert* der;
  21762. #else
  21763. DerCert der[1];
  21764. #endif
  21765. if (eccKey)
  21766. cert->keyType = ECC_KEY;
  21767. else if (rsaKey)
  21768. cert->keyType = RSA_KEY;
  21769. else if (dsaKey)
  21770. cert->keyType = DSA_KEY;
  21771. else if (ed25519Key)
  21772. cert->keyType = ED25519_KEY;
  21773. else if (ed448Key)
  21774. cert->keyType = ED448_KEY;
  21775. #ifdef HAVE_LIBOQS
  21776. else if ((falconKey != NULL) && (falconKey->level == 1))
  21777. cert->keyType = FALCON_LEVEL1_KEY;
  21778. else if ((falconKey != NULL) && (falconKey->level == 5))
  21779. cert->keyType = FALCON_LEVEL5_KEY;
  21780. #endif
  21781. else
  21782. return BAD_FUNC_ARG;
  21783. #ifdef WOLFSSL_SMALL_STACK
  21784. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  21785. DYNAMIC_TYPE_TMP_BUFFER);
  21786. if (der == NULL)
  21787. return MEMORY_E;
  21788. #endif
  21789. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key,
  21790. falconKey);
  21791. if (ret == 0) {
  21792. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  21793. ret = BUFFER_E;
  21794. else
  21795. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  21796. }
  21797. #ifdef WOLFSSL_SMALL_STACK
  21798. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  21799. #endif
  21800. return ret;
  21801. #else
  21802. DECL_ASNSETDATA(dataASN, certReqBodyASN_Length);
  21803. word32 publicKeySz, subjectSz, extSz;
  21804. int sz;
  21805. int ret = 0;
  21806. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  21807. word32 sbjRawSz;
  21808. #endif
  21809. /* Challenge Password OID. */
  21810. static const byte cpOid[] =
  21811. { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x07 };
  21812. /* Extension Requested OID. */
  21813. static const byte erOid[] =
  21814. { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x0e };
  21815. CALLOC_ASNSETDATA(dataASN, certReqBodyASN_Length, ret, cert->heap);
  21816. if (ret == 0) {
  21817. /* Set key type into certificate object based on key passed in. */
  21818. if (rsaKey != NULL) {
  21819. cert->keyType = RSA_KEY;
  21820. }
  21821. else if (eccKey != NULL) {
  21822. cert->keyType = ECC_KEY;
  21823. }
  21824. else if (dsaKey != NULL) {
  21825. cert->keyType = DSA_KEY;
  21826. }
  21827. else if (ed25519Key != NULL) {
  21828. cert->keyType = ED25519_KEY;
  21829. }
  21830. else if (ed448Key != NULL) {
  21831. cert->keyType = ED448_KEY;
  21832. }
  21833. else if ((falconKey != NULL) && (falconKey->level == 1)) {
  21834. cert->keyType = FALCON_LEVEL1_KEY;
  21835. }
  21836. else if ((falconKey != NULL) && (falconKey->level == 5)) {
  21837. cert->keyType = FALCON_LEVEL5_KEY;
  21838. }
  21839. else {
  21840. ret = BAD_FUNC_ARG;
  21841. }
  21842. }
  21843. if (ret == 0) {
  21844. /* Determine subject name size. */
  21845. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  21846. sbjRawSz = (word32)XSTRLEN((const char*)cert->sbjRaw);
  21847. if (sbjRawSz > 0) {
  21848. subjectSz = min(sizeof(cert->sbjRaw), sbjRawSz);
  21849. }
  21850. else
  21851. #endif
  21852. {
  21853. subjectSz = SetNameEx(NULL, ASN_NAME_MAX, &cert->subject, cert->heap);
  21854. ret = subjectSz;
  21855. }
  21856. }
  21857. if (ret >= 0) {
  21858. /* Determine encode public key size. */
  21859. ret = publicKeySz = EncodePublicKey(cert->keyType, NULL, 0, rsaKey,
  21860. eccKey, ed25519Key, ed448Key, dsaKey);
  21861. }
  21862. if (ret >= 0) {
  21863. /* Determine encode extensions size. */
  21864. ret = extSz = EncodeExtensions(cert, NULL, 0, 1);
  21865. }
  21866. if (ret >= 0) {
  21867. /* Set version. */
  21868. SetASN_Int8Bit(&dataASN[1], cert->version);
  21869. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  21870. if (sbjRawSz > 0) {
  21871. /* Put in encoded subject name. */
  21872. SetASN_Buffer(&dataASN[2], cert->sbjRaw, subjectSz);
  21873. }
  21874. else
  21875. #endif
  21876. {
  21877. /* Leave space for subject name. */
  21878. SetASN_ReplaceBuffer(&dataASN[2], NULL, subjectSz);
  21879. }
  21880. /* Leave space for public key. */
  21881. SetASN_ReplaceBuffer(&dataASN[3], NULL, publicKeySz);
  21882. if (cert->challengePw[0] != '\0') {
  21883. /* Add challenge password attribute. */
  21884. /* Set challenge password OID. */
  21885. SetASN_Buffer(&dataASN[6], cpOid, sizeof(cpOid));
  21886. /* Enable the ASN template item with the appropriate tag. */
  21887. if (cert->challengePwPrintableString) {
  21888. /* PRINTABLE_STRING - set buffer */
  21889. SetASN_Buffer(&dataASN[8], (byte*)cert->challengePw,
  21890. (word32)XSTRLEN(cert->challengePw));
  21891. /* UTF8STRING - don't encode */
  21892. dataASN[9].noOut = 1;
  21893. }
  21894. else {
  21895. /* PRINTABLE_STRING - don't encode */
  21896. dataASN[8].noOut = 1;
  21897. /* UTF8STRING - set buffer */
  21898. SetASN_Buffer(&dataASN[9], (byte*)cert->challengePw,
  21899. (word32)XSTRLEN(cert->challengePw));
  21900. }
  21901. }
  21902. else {
  21903. /* Leave out challenge password attribute items. */
  21904. SetASNItem_NoOut(dataASN, 5, 9);
  21905. }
  21906. if (extSz > 0) {
  21907. /* Set extension attribute OID. */
  21908. SetASN_Buffer(&dataASN[11], erOid, sizeof(erOid));
  21909. /* Leave space for data. */
  21910. SetASN_Buffer(&dataASN[13], NULL, extSz);
  21911. }
  21912. else {
  21913. /* Leave out extension attribute items. */
  21914. SetASNItem_NoOut(dataASN, 10, 13);
  21915. }
  21916. /* Calculate size of encoded certificate request body. */
  21917. ret = SizeASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length,
  21918. &sz);
  21919. }
  21920. /* Check buffer is big enough for encoded data. */
  21921. if ((ret == 0) && (sz > (int)derSz)) {
  21922. ret = BUFFER_E;
  21923. }
  21924. if (ret == 0) {
  21925. /* Encode certificate request body into buffer. */
  21926. SetASN_Items(certReqBodyASN, dataASN, certReqBodyASN_Length, derBuffer);
  21927. /* Put in generated data */
  21928. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  21929. if (sbjRawSz == 0)
  21930. #endif
  21931. {
  21932. /* Encode subject name into space in buffer. */
  21933. ret = SetNameEx((byte*)dataASN[2].data.buffer.data,
  21934. dataASN[3].data.buffer.length, &cert->subject, cert->heap);
  21935. }
  21936. }
  21937. if (ret >= 0) {
  21938. /* Encode public key into space in buffer. */
  21939. ret = EncodePublicKey(cert->keyType, (byte*)dataASN[3].data.buffer.data,
  21940. dataASN[3].data.buffer.length, rsaKey, eccKey, ed25519Key, ed448Key,
  21941. dsaKey);
  21942. }
  21943. if ((ret >= 0) && (!dataASN[13].noOut)) {
  21944. /* Encode extensions into space in buffer. */
  21945. ret = EncodeExtensions(cert, (byte*)dataASN[13].data.buffer.data,
  21946. dataASN[13].data.buffer.length, 1);
  21947. }
  21948. if (ret >= 0) {
  21949. /* Store encoded certifcate request body size. */
  21950. cert->bodySz = sz;
  21951. /* Return the encoding size. */
  21952. ret = sz;
  21953. }
  21954. FREE_ASNSETDATA(dataASN, cert->heap);
  21955. return ret;
  21956. #endif /* WOLFSSL_ASN_TEMPLATE */
  21957. }
  21958. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  21959. void* key)
  21960. {
  21961. RsaKey* rsaKey = NULL;
  21962. DsaKey* dsaKey = NULL;
  21963. ecc_key* eccKey = NULL;
  21964. ed25519_key* ed25519Key = NULL;
  21965. ed448_key* ed448Key = NULL;
  21966. falcon_key* falconKey = NULL;
  21967. if (keyType == RSA_TYPE)
  21968. rsaKey = (RsaKey*)key;
  21969. else if (keyType == DSA_TYPE)
  21970. dsaKey = (DsaKey*)key;
  21971. else if (keyType == ECC_TYPE)
  21972. eccKey = (ecc_key*)key;
  21973. else if (keyType == ED25519_TYPE)
  21974. ed25519Key = (ed25519_key*)key;
  21975. else if (keyType == ED448_TYPE)
  21976. ed448Key = (ed448_key*)key;
  21977. else if (keyType == FALCON_LEVEL1_TYPE)
  21978. falconKey = (falcon_key*)key;
  21979. else if (keyType == FALCON_LEVEL5_TYPE)
  21980. falconKey = (falcon_key*)key;
  21981. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey,
  21982. ed25519Key, ed448Key, falconKey);
  21983. }
  21984. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  21985. RsaKey* rsaKey, ecc_key* eccKey)
  21986. {
  21987. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL,
  21988. NULL, NULL);
  21989. }
  21990. #endif /* WOLFSSL_CERT_REQ */
  21991. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  21992. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  21993. ed448_key* ed448Key, falcon_key* falconKey, WC_RNG* rng)
  21994. {
  21995. int sigSz = 0;
  21996. void* heap = NULL;
  21997. CertSignCtx* certSignCtx;
  21998. #ifndef WOLFSSL_ASYNC_CRYPT
  21999. CertSignCtx certSignCtx_lcl;
  22000. certSignCtx = &certSignCtx_lcl;
  22001. XMEMSET(certSignCtx, 0, sizeof(CertSignCtx));
  22002. #else
  22003. certSignCtx = NULL;
  22004. #endif
  22005. if (requestSz < 0)
  22006. return requestSz;
  22007. /* locate ctx */
  22008. if (rsaKey) {
  22009. #ifndef NO_RSA
  22010. #ifdef WOLFSSL_ASYNC_CRYPT
  22011. certSignCtx = &rsaKey->certSignCtx;
  22012. #endif
  22013. heap = rsaKey->heap;
  22014. #else
  22015. return NOT_COMPILED_IN;
  22016. #endif /* NO_RSA */
  22017. }
  22018. else if (eccKey) {
  22019. #ifdef HAVE_ECC
  22020. #ifdef WOLFSSL_ASYNC_CRYPT
  22021. certSignCtx = &eccKey->certSignCtx;
  22022. #endif
  22023. heap = eccKey->heap;
  22024. #else
  22025. return NOT_COMPILED_IN;
  22026. #endif /* HAVE_ECC */
  22027. }
  22028. #ifdef WOLFSSL_ASYNC_CRYPT
  22029. if (certSignCtx == NULL) {
  22030. return BAD_FUNC_ARG;
  22031. }
  22032. #endif
  22033. if (certSignCtx->sig == NULL) {
  22034. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  22035. DYNAMIC_TYPE_TMP_BUFFER);
  22036. if (certSignCtx->sig == NULL)
  22037. return MEMORY_E;
  22038. }
  22039. sigSz = MakeSignature(certSignCtx, buf, requestSz, certSignCtx->sig,
  22040. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key,
  22041. falconKey, rng, sType, heap);
  22042. #ifdef WOLFSSL_ASYNC_CRYPT
  22043. if (sigSz == WC_PENDING_E) {
  22044. /* Not free'ing certSignCtx->sig here because it could still be in use
  22045. * with async operations. */
  22046. return sigSz;
  22047. }
  22048. #endif
  22049. if (sigSz >= 0) {
  22050. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  22051. sigSz = BUFFER_E;
  22052. else
  22053. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  22054. sType);
  22055. }
  22056. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22057. certSignCtx->sig = NULL;
  22058. return sigSz;
  22059. }
  22060. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  22061. int keyType, void* key, WC_RNG* rng)
  22062. {
  22063. RsaKey* rsaKey = NULL;
  22064. ecc_key* eccKey = NULL;
  22065. ed25519_key* ed25519Key = NULL;
  22066. ed448_key* ed448Key = NULL;
  22067. falcon_key* falconKey = NULL;
  22068. if (keyType == RSA_TYPE)
  22069. rsaKey = (RsaKey*)key;
  22070. else if (keyType == ECC_TYPE)
  22071. eccKey = (ecc_key*)key;
  22072. else if (keyType == ED25519_TYPE)
  22073. ed25519Key = (ed25519_key*)key;
  22074. else if (keyType == ED448_TYPE)
  22075. ed448Key = (ed448_key*)key;
  22076. else if (keyType == FALCON_LEVEL1_TYPE)
  22077. falconKey = (falcon_key*)key;
  22078. else if (keyType == FALCON_LEVEL5_TYPE)
  22079. falconKey = (falcon_key*)key;
  22080. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  22081. ed448Key, falconKey, rng);
  22082. }
  22083. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  22084. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  22085. {
  22086. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  22087. NULL, rng);
  22088. }
  22089. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  22090. RsaKey* key, WC_RNG* rng)
  22091. {
  22092. int ret;
  22093. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  22094. if (ret < 0)
  22095. return ret;
  22096. return wc_SignCert(cert->bodySz, cert->sigType,
  22097. buf, buffSz, key, NULL, rng);
  22098. }
  22099. #ifdef WOLFSSL_CERT_EXT
  22100. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  22101. The raw subject pointer will only be valid while "cert" is valid. */
  22102. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  22103. {
  22104. int rc = BAD_FUNC_ARG;
  22105. if ((subjectRaw != NULL) && (cert != NULL)) {
  22106. *subjectRaw = cert->sbjRaw;
  22107. rc = 0;
  22108. }
  22109. return rc;
  22110. }
  22111. /* Set KID from public key */
  22112. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  22113. ed25519_key* ed25519Key, ed448_key* ed448Key,
  22114. falcon_key* falconKey, int kid_type)
  22115. {
  22116. byte *buf;
  22117. int bufferSz, ret;
  22118. if (cert == NULL ||
  22119. (rsakey == NULL && eckey == NULL && ed25519Key == NULL &&
  22120. ed448Key == NULL && falconKey == NULL) ||
  22121. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  22122. return BAD_FUNC_ARG;
  22123. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  22124. DYNAMIC_TYPE_TMP_BUFFER);
  22125. if (buf == NULL)
  22126. return MEMORY_E;
  22127. /* Public Key */
  22128. bufferSz = -1;
  22129. #ifndef NO_RSA
  22130. /* RSA public key */
  22131. if (rsakey != NULL)
  22132. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  22133. #endif
  22134. #ifdef HAVE_ECC
  22135. /* ECC public key */
  22136. if (eckey != NULL)
  22137. bufferSz = SetEccPublicKey(buf, eckey, MAX_PUBLIC_KEY_SZ, 0);
  22138. #endif
  22139. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  22140. /* ED25519 public key */
  22141. if (ed25519Key != NULL) {
  22142. bufferSz = wc_Ed25519PublicKeyToDer(ed25519Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  22143. }
  22144. #endif
  22145. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  22146. /* ED448 public key */
  22147. if (ed448Key != NULL) {
  22148. bufferSz = wc_Ed448PublicKeyToDer(ed448Key, buf, MAX_PUBLIC_KEY_SZ, 0);
  22149. }
  22150. #endif
  22151. #if defined(HAVE_LIBOQS)
  22152. if (falconKey != NULL) {
  22153. bufferSz = wc_Falcon_PublicKeyToDer(falconKey, buf, MAX_PUBLIC_KEY_SZ,
  22154. 0);
  22155. }
  22156. #endif
  22157. if (bufferSz <= 0) {
  22158. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22159. return PUBLIC_KEY_E;
  22160. }
  22161. /* Compute SKID by hashing public key */
  22162. if (kid_type == SKID_TYPE) {
  22163. ret = CalcHashId(buf, bufferSz, cert->skid);
  22164. cert->skidSz = KEYID_SIZE;
  22165. }
  22166. else if (kid_type == AKID_TYPE) {
  22167. ret = CalcHashId(buf, bufferSz, cert->akid);
  22168. cert->akidSz = KEYID_SIZE;
  22169. }
  22170. else
  22171. ret = BAD_FUNC_ARG;
  22172. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22173. return ret;
  22174. }
  22175. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  22176. {
  22177. RsaKey* rsaKey = NULL;
  22178. ecc_key* eccKey = NULL;
  22179. ed25519_key* ed25519Key = NULL;
  22180. ed448_key* ed448Key = NULL;
  22181. falcon_key* falconKey = NULL;
  22182. if (keyType == RSA_TYPE)
  22183. rsaKey = (RsaKey*)key;
  22184. else if (keyType == ECC_TYPE)
  22185. eccKey = (ecc_key*)key;
  22186. else if (keyType == ED25519_TYPE)
  22187. ed25519Key = (ed25519_key*)key;
  22188. else if (keyType == ED448_TYPE)
  22189. ed448Key = (ed448_key*)key;
  22190. else if (keyType == FALCON_LEVEL1_TYPE)
  22191. falconKey = (falcon_key*)key;
  22192. else if (keyType == FALCON_LEVEL5_TYPE)
  22193. falconKey = (falcon_key*)key;
  22194. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  22195. falconKey, SKID_TYPE);
  22196. }
  22197. /* Set SKID from RSA or ECC public key */
  22198. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  22199. {
  22200. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL,
  22201. SKID_TYPE);
  22202. }
  22203. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  22204. {
  22205. RsaKey* rsaKey = NULL;
  22206. ecc_key* eccKey = NULL;
  22207. ed25519_key* ed25519Key = NULL;
  22208. ed448_key* ed448Key = NULL;
  22209. falcon_key* falconKey = NULL;
  22210. if (keyType == RSA_TYPE)
  22211. rsaKey = (RsaKey*)key;
  22212. else if (keyType == ECC_TYPE)
  22213. eccKey = (ecc_key*)key;
  22214. else if (keyType == ED25519_TYPE)
  22215. ed25519Key = (ed25519_key*)key;
  22216. else if (keyType == ED448_TYPE)
  22217. ed448Key = (ed448_key*)key;
  22218. else if (keyType == FALCON_LEVEL1_TYPE)
  22219. falconKey = (falcon_key*)key;
  22220. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, ed25519Key, ed448Key,
  22221. falconKey, AKID_TYPE);
  22222. }
  22223. /* Set SKID from RSA or ECC public key */
  22224. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  22225. {
  22226. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, NULL, NULL,
  22227. AKID_TYPE);
  22228. }
  22229. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  22230. /* Set SKID from public key file in PEM */
  22231. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  22232. {
  22233. int ret, derSz;
  22234. byte* der;
  22235. word32 idx;
  22236. RsaKey *rsakey = NULL;
  22237. ecc_key *eckey = NULL;
  22238. if (cert == NULL || file == NULL)
  22239. return BAD_FUNC_ARG;
  22240. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  22241. if (der == NULL) {
  22242. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  22243. return MEMORY_E;
  22244. }
  22245. derSz = MAX_PUBLIC_KEY_SZ;
  22246. XMEMSET(der, 0, derSz);
  22247. derSz = wc_PemPubKeyToDer(file, der, derSz);
  22248. if (derSz <= 0) {
  22249. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22250. return derSz;
  22251. }
  22252. /* Load PubKey in internal structure */
  22253. #ifndef NO_RSA
  22254. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  22255. if (rsakey == NULL) {
  22256. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22257. return MEMORY_E;
  22258. }
  22259. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  22260. WOLFSSL_MSG("wc_InitRsaKey failure");
  22261. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  22262. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22263. return MEMORY_E;
  22264. }
  22265. idx = 0;
  22266. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, derSz);
  22267. if (ret != 0)
  22268. #endif
  22269. {
  22270. #ifndef NO_RSA
  22271. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  22272. wc_FreeRsaKey(rsakey);
  22273. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  22274. rsakey = NULL;
  22275. #endif
  22276. #ifdef HAVE_ECC
  22277. /* Check to load ecc public key */
  22278. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  22279. DYNAMIC_TYPE_ECC);
  22280. if (eckey == NULL) {
  22281. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22282. return MEMORY_E;
  22283. }
  22284. if (wc_ecc_init(eckey) != 0) {
  22285. WOLFSSL_MSG("wc_ecc_init failure");
  22286. wc_ecc_free(eckey);
  22287. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  22288. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22289. return MEMORY_E;
  22290. }
  22291. idx = 0;
  22292. ret = wc_EccPublicKeyDecode(der, &idx, eckey, derSz);
  22293. if (ret != 0) {
  22294. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  22295. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22296. wc_ecc_free(eckey);
  22297. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  22298. return PUBLIC_KEY_E;
  22299. }
  22300. #else
  22301. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22302. return PUBLIC_KEY_E;
  22303. #endif /* HAVE_ECC */
  22304. }
  22305. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  22306. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  22307. #ifndef NO_RSA
  22308. wc_FreeRsaKey(rsakey);
  22309. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  22310. #endif
  22311. #ifdef HAVE_ECC
  22312. wc_ecc_free(eckey);
  22313. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  22314. #endif
  22315. return ret;
  22316. }
  22317. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  22318. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  22319. {
  22320. int ret = 0;
  22321. /* Subject Key Id not found !! */
  22322. if (decoded->extSubjKeyIdSet == 0) {
  22323. ret = ASN_NO_SKID;
  22324. }
  22325. /* SKID invalid size */
  22326. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  22327. ret = MEMORY_E;
  22328. }
  22329. else {
  22330. /* Put the SKID of CA to AKID of certificate */
  22331. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  22332. cert->akidSz = KEYID_SIZE;
  22333. }
  22334. return ret;
  22335. }
  22336. /* Set AKID from certificate contains in buffer (DER encoded) */
  22337. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  22338. {
  22339. int ret = 0;
  22340. if (cert == NULL) {
  22341. ret = BAD_FUNC_ARG;
  22342. }
  22343. else {
  22344. /* Check if decodedCert is cached */
  22345. if (cert->der != der) {
  22346. /* Allocate cache for the decoded cert */
  22347. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22348. }
  22349. if (ret >= 0) {
  22350. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  22351. #ifndef WOLFSSL_CERT_GEN_CACHE
  22352. wc_SetCert_Free(cert);
  22353. #endif
  22354. }
  22355. }
  22356. return ret;
  22357. }
  22358. #ifndef NO_FILESYSTEM
  22359. /* Set AKID from certificate file in PEM */
  22360. int wc_SetAuthKeyId(Cert *cert, const char* file)
  22361. {
  22362. int ret;
  22363. DerBuffer* der = NULL;
  22364. if (cert == NULL || file == NULL)
  22365. return BAD_FUNC_ARG;
  22366. ret = wc_PemCertToDer_ex(file, &der);
  22367. if (ret == 0)
  22368. {
  22369. ret = wc_SetAuthKeyIdFromCert(cert, der->buffer, der->length);
  22370. FreeDer(&der);
  22371. }
  22372. return ret;
  22373. }
  22374. #endif /* !NO_FILESYSTEM */
  22375. /* Set KeyUsage from human readable string */
  22376. int wc_SetKeyUsage(Cert *cert, const char *value)
  22377. {
  22378. int ret = 0;
  22379. char *token, *str, *ptr;
  22380. word32 len;
  22381. if (cert == NULL || value == NULL)
  22382. return BAD_FUNC_ARG;
  22383. cert->keyUsage = 0;
  22384. /* duplicate string (including terminator) */
  22385. len = (word32)XSTRLEN(value);
  22386. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22387. if (str == NULL)
  22388. return MEMORY_E;
  22389. XMEMCPY(str, value, len+1);
  22390. /* parse value, and set corresponding Key Usage value */
  22391. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  22392. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22393. return KEYUSAGE_E;
  22394. }
  22395. while (token != NULL)
  22396. {
  22397. len = (word32)XSTRLEN(token);
  22398. if (!XSTRNCASECMP(token, "digitalSignature", len))
  22399. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  22400. else if (!XSTRNCASECMP(token, "nonRepudiation", len) ||
  22401. !XSTRNCASECMP(token, "contentCommitment", len))
  22402. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  22403. else if (!XSTRNCASECMP(token, "keyEncipherment", len))
  22404. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  22405. else if (!XSTRNCASECMP(token, "dataEncipherment", len))
  22406. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  22407. else if (!XSTRNCASECMP(token, "keyAgreement", len))
  22408. cert->keyUsage |= KEYUSE_KEY_AGREE;
  22409. else if (!XSTRNCASECMP(token, "keyCertSign", len))
  22410. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  22411. else if (!XSTRNCASECMP(token, "cRLSign", len))
  22412. cert->keyUsage |= KEYUSE_CRL_SIGN;
  22413. else if (!XSTRNCASECMP(token, "encipherOnly", len))
  22414. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  22415. else if (!XSTRNCASECMP(token, "decipherOnly", len))
  22416. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  22417. else {
  22418. ret = KEYUSAGE_E;
  22419. break;
  22420. }
  22421. token = XSTRTOK(NULL, ",", &ptr);
  22422. }
  22423. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22424. return ret;
  22425. }
  22426. /* Set ExtendedKeyUsage from human readable string */
  22427. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  22428. {
  22429. int ret = 0;
  22430. char *token, *str, *ptr;
  22431. word32 len;
  22432. if (cert == NULL || value == NULL)
  22433. return BAD_FUNC_ARG;
  22434. cert->extKeyUsage = 0;
  22435. /* duplicate string (including terminator) */
  22436. len = (word32)XSTRLEN(value);
  22437. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22438. if (str == NULL)
  22439. return MEMORY_E;
  22440. XMEMCPY(str, value, len+1);
  22441. /* parse value, and set corresponding Key Usage value */
  22442. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  22443. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22444. return EXTKEYUSAGE_E;
  22445. }
  22446. while (token != NULL)
  22447. {
  22448. len = (word32)XSTRLEN(token);
  22449. if (!XSTRNCASECMP(token, "any", len))
  22450. cert->extKeyUsage |= EXTKEYUSE_ANY;
  22451. else if (!XSTRNCASECMP(token, "serverAuth", len))
  22452. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  22453. else if (!XSTRNCASECMP(token, "clientAuth", len))
  22454. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  22455. else if (!XSTRNCASECMP(token, "codeSigning", len))
  22456. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  22457. else if (!XSTRNCASECMP(token, "emailProtection", len))
  22458. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  22459. else if (!XSTRNCASECMP(token, "timeStamping", len))
  22460. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  22461. else if (!XSTRNCASECMP(token, "OCSPSigning", len))
  22462. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  22463. else {
  22464. ret = EXTKEYUSAGE_E;
  22465. break;
  22466. }
  22467. token = XSTRTOK(NULL, ",", &ptr);
  22468. }
  22469. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22470. return ret;
  22471. }
  22472. #ifdef WOLFSSL_EKU_OID
  22473. /*
  22474. * cert structure to set EKU oid in
  22475. * oid the oid in byte representation
  22476. * sz size of oid buffer
  22477. * idx index of array to place oid
  22478. *
  22479. * returns 0 on success
  22480. */
  22481. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  22482. void* heap)
  22483. {
  22484. byte oid[MAX_OID_SZ];
  22485. word32 oidSz = MAX_OID_SZ;
  22486. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  22487. WOLFSSL_MSG("Either idx or sz was too large");
  22488. return BAD_FUNC_ARG;
  22489. }
  22490. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  22491. return BUFFER_E;
  22492. }
  22493. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  22494. cert->extKeyUsageOIDSz[idx] = oidSz;
  22495. cert->extKeyUsage |= EXTKEYUSE_USER;
  22496. return 0;
  22497. }
  22498. #endif /* WOLFSSL_EKU_OID */
  22499. #endif /* WOLFSSL_CERT_EXT */
  22500. #ifdef WOLFSSL_ALT_NAMES
  22501. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  22502. {
  22503. int ret = 0;
  22504. cert->altNamesSz = 0;
  22505. if (decoded->altNames) {
  22506. ret = FlattenAltNames(cert->altNames,
  22507. sizeof(cert->altNames), decoded->altNames);
  22508. if (ret >= 0) {
  22509. cert->altNamesSz = ret;
  22510. ret = 0;
  22511. }
  22512. }
  22513. return ret;
  22514. }
  22515. #ifndef NO_FILESYSTEM
  22516. /* Set Alt Names from der cert, return 0 on success */
  22517. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
  22518. {
  22519. int ret;
  22520. #ifdef WOLFSSL_SMALL_STACK
  22521. DecodedCert* decoded;
  22522. #else
  22523. DecodedCert decoded[1];
  22524. #endif
  22525. if (derSz < 0)
  22526. return derSz;
  22527. #ifdef WOLFSSL_SMALL_STACK
  22528. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  22529. DYNAMIC_TYPE_TMP_BUFFER);
  22530. if (decoded == NULL)
  22531. return MEMORY_E;
  22532. #endif
  22533. InitDecodedCert(decoded, der, derSz, NULL);
  22534. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  22535. if (ret < 0) {
  22536. WOLFSSL_MSG("ParseCertRelative error");
  22537. }
  22538. else {
  22539. ret = SetAltNamesFromDcert(cert, decoded);
  22540. }
  22541. FreeDecodedCert(decoded);
  22542. #ifdef WOLFSSL_SMALL_STACK
  22543. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  22544. #endif
  22545. return ret < 0 ? ret : 0;
  22546. }
  22547. #endif
  22548. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  22549. {
  22550. int ret = 0;
  22551. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  22552. WOLFSSL_MSG("Couldn't extract dates");
  22553. ret = -1;
  22554. }
  22555. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  22556. decoded->afterDateLen > MAX_DATE_SIZE) {
  22557. WOLFSSL_MSG("Bad date size");
  22558. ret = -1;
  22559. }
  22560. else {
  22561. XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen);
  22562. XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen);
  22563. cert->beforeDateSz = decoded->beforeDateLen;
  22564. cert->afterDateSz = decoded->afterDateLen;
  22565. }
  22566. return ret;
  22567. }
  22568. #endif /* WOLFSSL_ALT_NAMES */
  22569. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  22570. {
  22571. int sz;
  22572. if (decoded->subjectCN) {
  22573. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  22574. : CTC_NAME_SIZE - 1;
  22575. XSTRNCPY(cn->commonName, decoded->subjectCN, sz);
  22576. cn->commonName[sz] = '\0';
  22577. cn->commonNameEnc = decoded->subjectCNEnc;
  22578. }
  22579. if (decoded->subjectC) {
  22580. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  22581. : CTC_NAME_SIZE - 1;
  22582. XSTRNCPY(cn->country, decoded->subjectC, sz);
  22583. cn->country[sz] = '\0';
  22584. cn->countryEnc = decoded->subjectCEnc;
  22585. }
  22586. if (decoded->subjectST) {
  22587. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  22588. : CTC_NAME_SIZE - 1;
  22589. XSTRNCPY(cn->state, decoded->subjectST, sz);
  22590. cn->state[sz] = '\0';
  22591. cn->stateEnc = decoded->subjectSTEnc;
  22592. }
  22593. if (decoded->subjectL) {
  22594. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  22595. : CTC_NAME_SIZE - 1;
  22596. XSTRNCPY(cn->locality, decoded->subjectL, sz);
  22597. cn->locality[sz] = '\0';
  22598. cn->localityEnc = decoded->subjectLEnc;
  22599. }
  22600. if (decoded->subjectO) {
  22601. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  22602. : CTC_NAME_SIZE - 1;
  22603. XSTRNCPY(cn->org, decoded->subjectO, sz);
  22604. cn->org[sz] = '\0';
  22605. cn->orgEnc = decoded->subjectOEnc;
  22606. }
  22607. if (decoded->subjectOU) {
  22608. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  22609. : CTC_NAME_SIZE - 1;
  22610. XSTRNCPY(cn->unit, decoded->subjectOU, sz);
  22611. cn->unit[sz] = '\0';
  22612. cn->unitEnc = decoded->subjectOUEnc;
  22613. }
  22614. if (decoded->subjectSN) {
  22615. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  22616. : CTC_NAME_SIZE - 1;
  22617. XSTRNCPY(cn->sur, decoded->subjectSN, sz);
  22618. cn->sur[sz] = '\0';
  22619. cn->surEnc = decoded->subjectSNEnc;
  22620. }
  22621. if (decoded->subjectSND) {
  22622. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  22623. : CTC_NAME_SIZE - 1;
  22624. XSTRNCPY(cn->serialDev, decoded->subjectSND, sz);
  22625. cn->serialDev[sz] = '\0';
  22626. cn->serialDevEnc = decoded->subjectSNDEnc;
  22627. }
  22628. #ifdef WOLFSSL_CERT_EXT
  22629. if (decoded->subjectBC) {
  22630. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  22631. : CTC_NAME_SIZE - 1;
  22632. XSTRNCPY(cn->busCat, decoded->subjectBC, sz);
  22633. cn->busCat[sz] = '\0';
  22634. cn->busCatEnc = decoded->subjectBCEnc;
  22635. }
  22636. if (decoded->subjectJC) {
  22637. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  22638. : CTC_NAME_SIZE - 1;
  22639. XSTRNCPY(cn->joiC, decoded->subjectJC, sz);
  22640. cn->joiC[sz] = '\0';
  22641. cn->joiCEnc = decoded->subjectJCEnc;
  22642. }
  22643. if (decoded->subjectJS) {
  22644. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  22645. : CTC_NAME_SIZE - 1;
  22646. XSTRNCPY(cn->joiSt, decoded->subjectJS, sz);
  22647. cn->joiSt[sz] = '\0';
  22648. cn->joiStEnc = decoded->subjectJSEnc;
  22649. }
  22650. #endif
  22651. if (decoded->subjectEmail) {
  22652. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  22653. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  22654. XSTRNCPY(cn->email, decoded->subjectEmail, sz);
  22655. cn->email[sz] = '\0';
  22656. }
  22657. }
  22658. #ifndef NO_FILESYSTEM
  22659. /* Set cn name from der buffer, return 0 on success */
  22660. static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
  22661. {
  22662. int ret;
  22663. #ifdef WOLFSSL_SMALL_STACK
  22664. DecodedCert* decoded;
  22665. #else
  22666. DecodedCert decoded[1];
  22667. #endif
  22668. if (derSz < 0)
  22669. return derSz;
  22670. #ifdef WOLFSSL_SMALL_STACK
  22671. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  22672. DYNAMIC_TYPE_TMP_BUFFER);
  22673. if (decoded == NULL)
  22674. return MEMORY_E;
  22675. #endif
  22676. InitDecodedCert(decoded, der, derSz, NULL);
  22677. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  22678. if (ret < 0) {
  22679. WOLFSSL_MSG("ParseCertRelative error");
  22680. }
  22681. else {
  22682. SetNameFromDcert(cn, decoded);
  22683. }
  22684. FreeDecodedCert(decoded);
  22685. #ifdef WOLFSSL_SMALL_STACK
  22686. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  22687. #endif
  22688. return ret < 0 ? ret : 0;
  22689. }
  22690. /* Set cert issuer from issuerFile in PEM */
  22691. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  22692. {
  22693. int ret;
  22694. DerBuffer* der = NULL;
  22695. if (cert == NULL || issuerFile == NULL)
  22696. return BAD_FUNC_ARG;
  22697. ret = wc_PemCertToDer_ex(issuerFile, &der);
  22698. if (ret == 0) {
  22699. cert->selfSigned = 0;
  22700. ret = SetNameFromCert(&cert->issuer, der->buffer, der->length);
  22701. FreeDer(&der);
  22702. }
  22703. return ret;
  22704. }
  22705. /* Set cert subject from subjectFile in PEM */
  22706. int wc_SetSubject(Cert* cert, const char* subjectFile)
  22707. {
  22708. int ret;
  22709. DerBuffer* der = NULL;
  22710. if (cert == NULL || subjectFile == NULL)
  22711. return BAD_FUNC_ARG;
  22712. ret = wc_PemCertToDer_ex(subjectFile, &der);
  22713. if (ret == 0) {
  22714. ret = SetNameFromCert(&cert->subject, der->buffer, der->length);
  22715. FreeDer(&der);
  22716. }
  22717. return ret;
  22718. }
  22719. #ifdef WOLFSSL_ALT_NAMES
  22720. /* Set alt names from file in PEM */
  22721. int wc_SetAltNames(Cert* cert, const char* file)
  22722. {
  22723. int ret;
  22724. DerBuffer* der = NULL;
  22725. if (cert == NULL) {
  22726. return BAD_FUNC_ARG;
  22727. }
  22728. ret = wc_PemCertToDer_ex(file, &der);
  22729. if (ret == 0) {
  22730. ret = SetAltNamesFromCert(cert, der->buffer, der->length);
  22731. FreeDer(&der);
  22732. }
  22733. return ret;
  22734. }
  22735. #endif /* WOLFSSL_ALT_NAMES */
  22736. #endif /* !NO_FILESYSTEM */
  22737. /* Set cert issuer from DER buffer */
  22738. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  22739. {
  22740. int ret = 0;
  22741. if (cert == NULL) {
  22742. ret = BAD_FUNC_ARG;
  22743. }
  22744. else {
  22745. cert->selfSigned = 0;
  22746. /* Check if decodedCert is cached */
  22747. if (cert->der != der) {
  22748. /* Allocate cache for the decoded cert */
  22749. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22750. }
  22751. if (ret >= 0) {
  22752. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  22753. #ifndef WOLFSSL_CERT_GEN_CACHE
  22754. wc_SetCert_Free(cert);
  22755. #endif
  22756. }
  22757. }
  22758. return ret;
  22759. }
  22760. /* Set cert subject from DER buffer */
  22761. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  22762. {
  22763. int ret = 0;
  22764. if (cert == NULL) {
  22765. ret = BAD_FUNC_ARG;
  22766. }
  22767. else {
  22768. /* Check if decodedCert is cached */
  22769. if (cert->der != der) {
  22770. /* Allocate cache for the decoded cert */
  22771. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22772. }
  22773. if (ret >= 0) {
  22774. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  22775. #ifndef WOLFSSL_CERT_GEN_CACHE
  22776. wc_SetCert_Free(cert);
  22777. #endif
  22778. }
  22779. }
  22780. return ret;
  22781. }
  22782. #ifdef WOLFSSL_CERT_EXT
  22783. /* Set cert raw subject from DER buffer */
  22784. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  22785. {
  22786. int ret = 0;
  22787. if (cert == NULL) {
  22788. ret = BAD_FUNC_ARG;
  22789. }
  22790. else {
  22791. /* Check if decodedCert is cached */
  22792. if (cert->der != der) {
  22793. /* Allocate cache for the decoded cert */
  22794. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22795. }
  22796. if (ret >= 0) {
  22797. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  22798. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  22799. (int)sizeof(CertName))) {
  22800. XMEMCPY(cert->sbjRaw,
  22801. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  22802. ((DecodedCert*)cert->decodedCert)->subjectRawLen);
  22803. }
  22804. #ifndef WOLFSSL_CERT_GEN_CACHE
  22805. wc_SetCert_Free(cert);
  22806. #endif
  22807. }
  22808. }
  22809. return ret;
  22810. }
  22811. /* Set cert raw issuer from DER buffer */
  22812. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  22813. {
  22814. int ret = 0;
  22815. if (cert == NULL) {
  22816. ret = BAD_FUNC_ARG;
  22817. }
  22818. else {
  22819. /* Check if decodedCert is cached */
  22820. if (cert->der != der) {
  22821. /* Allocate cache for the decoded cert */
  22822. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22823. }
  22824. if (ret >= 0) {
  22825. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  22826. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  22827. (int)sizeof(CertName))) {
  22828. /* Copy the subject to the issuer field */
  22829. XMEMCPY(cert->issRaw,
  22830. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  22831. ((DecodedCert*)cert->decodedCert)->subjectRawLen);
  22832. }
  22833. #ifndef WOLFSSL_CERT_GEN_CACHE
  22834. wc_SetCert_Free(cert);
  22835. #endif
  22836. }
  22837. }
  22838. return ret;
  22839. }
  22840. #endif
  22841. #ifdef WOLFSSL_ALT_NAMES
  22842. /* Set cert alt names from DER buffer */
  22843. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  22844. {
  22845. int ret = 0;
  22846. if (cert == NULL) {
  22847. ret = BAD_FUNC_ARG;
  22848. }
  22849. else {
  22850. /* Check if decodedCert is cached */
  22851. if (cert->der != der) {
  22852. /* Allocate cache for the decoded cert */
  22853. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22854. }
  22855. if (ret >= 0) {
  22856. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  22857. #ifndef WOLFSSL_CERT_GEN_CACHE
  22858. wc_SetCert_Free(cert);
  22859. #endif
  22860. }
  22861. }
  22862. return(ret);
  22863. }
  22864. /* Set cert dates from DER buffer */
  22865. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  22866. {
  22867. int ret = 0;
  22868. if (cert == NULL) {
  22869. ret = BAD_FUNC_ARG;
  22870. }
  22871. else {
  22872. /* Check if decodedCert is cached */
  22873. if (cert->der != der) {
  22874. /* Allocate cache for the decoded cert */
  22875. ret = wc_SetCert_LoadDer(cert, der, derSz);
  22876. }
  22877. if (ret >= 0) {
  22878. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  22879. #ifndef WOLFSSL_CERT_GEN_CACHE
  22880. wc_SetCert_Free(cert);
  22881. #endif
  22882. }
  22883. }
  22884. return(ret);
  22885. }
  22886. #endif /* WOLFSSL_ALT_NAMES */
  22887. #endif /* WOLFSSL_CERT_GEN */
  22888. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  22889. || defined(OPENSSL_EXTRA)
  22890. /* Encode OID string representation to ITU-T X.690 format */
  22891. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  22892. {
  22893. word32 val, idx = 0, nb_val;
  22894. char *token, *str, *ptr;
  22895. word32 len;
  22896. (void)heap;
  22897. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  22898. return BAD_FUNC_ARG;
  22899. /* duplicate string (including terminator) */
  22900. len = (word32)XSTRLEN(in);
  22901. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22902. if (str == NULL)
  22903. return MEMORY_E;
  22904. XMEMCPY(str, in, len+1);
  22905. nb_val = 0;
  22906. /* parse value, and set corresponding Policy OID value */
  22907. token = XSTRTOK(str, ".", &ptr);
  22908. while (token != NULL)
  22909. {
  22910. val = (word32)XATOI(token);
  22911. if (nb_val == 0) {
  22912. if (val > 2) {
  22913. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22914. return ASN_OBJECT_ID_E;
  22915. }
  22916. out[idx] = (byte)(40 * val);
  22917. }
  22918. else if (nb_val == 1) {
  22919. if (val > 127) {
  22920. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22921. return ASN_OBJECT_ID_E;
  22922. }
  22923. if (idx > *outSz) {
  22924. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22925. return BUFFER_E;
  22926. }
  22927. out[idx++] += (byte)val;
  22928. }
  22929. else {
  22930. word32 tb = 0, x;
  22931. int i = 0;
  22932. byte oid[MAX_OID_SZ];
  22933. while (val >= 128) {
  22934. x = val % 128;
  22935. val /= 128;
  22936. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  22937. }
  22938. if ((idx+(word32)i) >= *outSz) {
  22939. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22940. return BUFFER_E;
  22941. }
  22942. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  22943. /* push value in the right order */
  22944. while (i >= 0)
  22945. out[idx++] = oid[i--];
  22946. }
  22947. token = XSTRTOK(NULL, ".", &ptr);
  22948. nb_val++;
  22949. }
  22950. *outSz = idx;
  22951. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  22952. return 0;
  22953. }
  22954. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  22955. #endif /* !NO_CERTS */
  22956. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  22957. /* Helper function for wolfSSL_i2d_DHparams */
  22958. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  22959. {
  22960. #ifndef WOLFSSL_ASN_TEMPLATE
  22961. word32 idx = 0;
  22962. word32 total;
  22963. WOLFSSL_ENTER("StoreDHparams");
  22964. if (out == NULL) {
  22965. WOLFSSL_MSG("Null buffer error");
  22966. return BUFFER_E;
  22967. }
  22968. /* determine size */
  22969. /* integer - g */
  22970. idx = SetASNIntMP(g, -1, NULL);
  22971. /* integer - p */
  22972. idx += SetASNIntMP(p, -1, NULL);
  22973. total = idx;
  22974. /* sequence */
  22975. idx += SetSequence(idx, NULL);
  22976. /* make sure output fits in buffer */
  22977. if (idx > *outLen) {
  22978. return BUFFER_E;
  22979. }
  22980. /* write DH parameters */
  22981. /* sequence - for P and G only */
  22982. idx = SetSequence(total, out);
  22983. /* integer - p */
  22984. idx += SetASNIntMP(p, -1, out + idx);
  22985. /* integer - g */
  22986. idx += SetASNIntMP(g, -1, out + idx);
  22987. *outLen = idx;
  22988. return 0;
  22989. #else
  22990. ASNSetData dataASN[dhParamASN_Length];
  22991. int ret = 0;
  22992. int sz;
  22993. WOLFSSL_ENTER("StoreDHparams");
  22994. if (out == NULL) {
  22995. ret = BUFFER_E;
  22996. }
  22997. if (ret == 0) {
  22998. XMEMSET(dataASN, 0, sizeof(dataASN));
  22999. /* Set mp_int containing p and g. */
  23000. SetASN_MP(&dataASN[1], p);
  23001. SetASN_MP(&dataASN[2], g);
  23002. /* privateValueLength not encoded. */
  23003. dataASN[3].noOut = 1;
  23004. /* Calculate the size of the DH parameters. */
  23005. ret = SizeASN_Items(dhParamASN, dataASN, dhParamASN_Length, &sz);
  23006. }
  23007. /* Check buffer is big enough for encoding. */
  23008. if ((ret == 0) && ((int)*outLen < sz)) {
  23009. ret = BUFFER_E;
  23010. }
  23011. if (ret == 0) {
  23012. /* Encode the DH parameters into buffer. */
  23013. SetASN_Items(dhParamASN, dataASN, dhParamASN_Length, out);
  23014. /* Set the actual encoding size. */
  23015. *outLen = sz;
  23016. }
  23017. return ret;
  23018. #endif /* WOLFSSL_ASN_TEMPLATE */
  23019. }
  23020. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  23021. #if defined(HAVE_ECC) || !defined(NO_DSA)
  23022. #ifdef WOLFSSL_ASN_TEMPLATE
  23023. /* ASN.1 template for DSA signature.
  23024. * RFC 5912, 6 - DSA-Sig-Value
  23025. */
  23026. static const ASNItem dsaSigASN[] = {
  23027. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23028. /* r */
  23029. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  23030. /* s */
  23031. /* 2 */ { 1, ASN_INTEGER, 0, 0, 0 },
  23032. };
  23033. #define dsaSigASN_Length (sizeof(dsaSigASN) / sizeof(ASNItem))
  23034. #endif
  23035. /* Der Encode r & s ints into out, outLen is (in/out) size */
  23036. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  23037. {
  23038. #ifndef WOLFSSL_ASN_TEMPLATE
  23039. word32 idx = 0;
  23040. int rSz; /* encoding size */
  23041. int sSz;
  23042. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  23043. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  23044. int rLeadingZero = mp_leading_bit(r);
  23045. int sLeadingZero = mp_leading_bit(s);
  23046. int rLen = mp_unsigned_bin_size(r); /* big int size */
  23047. int sLen = mp_unsigned_bin_size(s);
  23048. if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero +
  23049. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  23050. return BUFFER_E;
  23051. idx = SetSequence(rLen + rLeadingZero + sLen+sLeadingZero + headerSz, out);
  23052. /* store r */
  23053. rSz = SetASNIntMP(r, *outLen - idx, &out[idx]);
  23054. if (rSz < 0)
  23055. return rSz;
  23056. idx += rSz;
  23057. /* store s */
  23058. sSz = SetASNIntMP(s, *outLen - idx, &out[idx]);
  23059. if (sSz < 0)
  23060. return sSz;
  23061. idx += sSz;
  23062. *outLen = idx;
  23063. return 0;
  23064. #else
  23065. ASNSetData dataASN[dsaSigASN_Length];
  23066. int ret;
  23067. int sz;
  23068. /* Clear dynamic data and set mp_ints r and s */
  23069. XMEMSET(dataASN, 0, sizeof(dataASN));
  23070. SetASN_MP(&dataASN[1], r);
  23071. SetASN_MP(&dataASN[2], s);
  23072. /* Calculate size of encoding. */
  23073. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  23074. /* Check buffer is big enough for encoding. */
  23075. if ((ret == 0) && ((int)*outLen < sz)) {
  23076. ret = BUFFER_E;
  23077. }
  23078. if (ret == 0) {
  23079. /* Encode DSA signature into buffer. */
  23080. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  23081. /* Set the actual encoding size. */
  23082. *outLen = sz;
  23083. }
  23084. return ret;
  23085. #endif /* WOLFSSL_ASN_TEMPLATE */
  23086. }
  23087. #ifndef WOLFSSL_ASN_TEMPLATE
  23088. /* determine if leading bit is set */
  23089. static int is_leading_bit_set(const byte* input, word32 sz)
  23090. {
  23091. byte c = 0;
  23092. if (sz > 0)
  23093. c = input[0];
  23094. return (c & 0x80) != 0;
  23095. }
  23096. static int trim_leading_zeros(const byte** input, word32 sz)
  23097. {
  23098. int i, leadingZeroCount = 0;
  23099. const byte* tmp = *input;
  23100. for (i=0; i<(int)sz; i++) {
  23101. if (tmp[i] != 0)
  23102. break;
  23103. leadingZeroCount++;
  23104. }
  23105. /* catch all zero case */
  23106. if (sz > 0 && leadingZeroCount == (int)sz) {
  23107. leadingZeroCount--;
  23108. }
  23109. *input += leadingZeroCount;
  23110. sz -= leadingZeroCount;
  23111. return sz;
  23112. }
  23113. #endif
  23114. /* Der Encode r & s ints into out, outLen is (in/out) size */
  23115. /* All input/outputs are assumed to be big-endian */
  23116. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  23117. const byte* s, word32 sLen)
  23118. {
  23119. #ifndef WOLFSSL_ASN_TEMPLATE
  23120. int ret;
  23121. word32 idx;
  23122. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  23123. int rAddLeadZero, sAddLeadZero;
  23124. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  23125. return BAD_FUNC_ARG;
  23126. /* Trim leading zeros */
  23127. rLen = trim_leading_zeros(&r, rLen);
  23128. sLen = trim_leading_zeros(&s, sLen);
  23129. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  23130. /* Add leading zero if MSB is set */
  23131. rAddLeadZero = is_leading_bit_set(r, rLen);
  23132. sAddLeadZero = is_leading_bit_set(s, sLen);
  23133. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  23134. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  23135. return BUFFER_E;
  23136. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  23137. /* store r */
  23138. ret = SetASNInt(rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]);
  23139. if (ret < 0)
  23140. return ret;
  23141. idx += ret;
  23142. XMEMCPY(&out[idx], r, rLen);
  23143. idx += rLen;
  23144. /* store s */
  23145. ret = SetASNInt(sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]);
  23146. if (ret < 0)
  23147. return ret;
  23148. idx += ret;
  23149. XMEMCPY(&out[idx], s, sLen);
  23150. idx += sLen;
  23151. *outLen = idx;
  23152. return 0;
  23153. #else
  23154. ASNSetData dataASN[dsaSigASN_Length];
  23155. int ret;
  23156. int sz;
  23157. /* Clear dynamic data and set buffers for r and s */
  23158. XMEMSET(dataASN, 0, sizeof(dataASN));
  23159. SetASN_Buffer(&dataASN[1], r, rLen);
  23160. SetASN_Buffer(&dataASN[2], s, sLen);
  23161. /* Calculate size of encoding. */
  23162. ret = SizeASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, &sz);
  23163. /* Check buffer is big enough for encoding. */
  23164. if ((ret == 0) && ((int)*outLen < sz)) {
  23165. ret = BUFFER_E;
  23166. }
  23167. if (ret == 0) {
  23168. /* Encode DSA signature into buffer. */
  23169. SetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, out);
  23170. /* Set the actual encoding size. */
  23171. *outLen = sz;
  23172. }
  23173. return ret;
  23174. #endif /* WOLFSSL_ASN_TEMPLATE */
  23175. }
  23176. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  23177. /* All input/outputs are assumed to be big-endian */
  23178. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  23179. byte* s, word32* sLen)
  23180. {
  23181. #ifndef WOLFSSL_ASN_TEMPLATE
  23182. int ret;
  23183. word32 idx = 0;
  23184. int len = 0;
  23185. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  23186. return ASN_ECC_KEY_E;
  23187. }
  23188. #ifndef NO_STRICT_ECDSA_LEN
  23189. /* enable strict length checking for signature */
  23190. if (sigLen != idx + (word32)len) {
  23191. return ASN_ECC_KEY_E;
  23192. }
  23193. #else
  23194. /* allow extra signature bytes at end */
  23195. if ((word32)len > (sigLen - idx)) {
  23196. return ASN_ECC_KEY_E;
  23197. }
  23198. #endif
  23199. ret = GetASNInt(sig, &idx, &len, sigLen);
  23200. if (ret != 0)
  23201. return ret;
  23202. if (rLen)
  23203. *rLen = len;
  23204. if (r)
  23205. XMEMCPY(r, (byte*)sig + idx, len);
  23206. idx += len;
  23207. ret = GetASNInt(sig, &idx, &len, sigLen);
  23208. if (ret != 0)
  23209. return ret;
  23210. if (sLen)
  23211. *sLen = len;
  23212. if (s)
  23213. XMEMCPY(s, (byte*)sig + idx, len);
  23214. #ifndef NO_STRICT_ECDSA_LEN
  23215. /* sanity check that the index has been advanced all the way to the end of
  23216. * the buffer */
  23217. if (idx + len != sigLen) {
  23218. ret = ASN_ECC_KEY_E;
  23219. }
  23220. #endif
  23221. return ret;
  23222. #else
  23223. ASNGetData dataASN[dsaSigASN_Length];
  23224. word32 idx = 0;
  23225. /* Clear dynamic data and set buffers to put r and s into. */
  23226. XMEMSET(dataASN, 0, sizeof(dataASN));
  23227. GetASN_Buffer(&dataASN[1], r, rLen);
  23228. GetASN_Buffer(&dataASN[2], s, sLen);
  23229. /* Decode the DSA signature. */
  23230. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  23231. sigLen);
  23232. #endif /* WOLFSSL_ASN_TEMPLATE */
  23233. }
  23234. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  23235. {
  23236. #ifndef WOLFSSL_ASN_TEMPLATE
  23237. word32 idx = 0;
  23238. int len = 0;
  23239. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  23240. return ASN_ECC_KEY_E;
  23241. }
  23242. #ifndef NO_STRICT_ECDSA_LEN
  23243. /* enable strict length checking for signature */
  23244. if (sigLen != idx + (word32)len) {
  23245. return ASN_ECC_KEY_E;
  23246. }
  23247. #else
  23248. /* allow extra signature bytes at end */
  23249. if ((word32)len > (sigLen - idx)) {
  23250. return ASN_ECC_KEY_E;
  23251. }
  23252. #endif
  23253. if (GetInt(r, sig, &idx, sigLen) < 0) {
  23254. return ASN_ECC_KEY_E;
  23255. }
  23256. if (GetInt(s, sig, &idx, sigLen) < 0) {
  23257. mp_clear(r);
  23258. return ASN_ECC_KEY_E;
  23259. }
  23260. #ifndef NO_STRICT_ECDSA_LEN
  23261. /* sanity check that the index has been advanced all the way to the end of
  23262. * the buffer */
  23263. if (idx != sigLen) {
  23264. mp_clear(r);
  23265. mp_clear(s);
  23266. return ASN_ECC_KEY_E;
  23267. }
  23268. #endif
  23269. return 0;
  23270. #else
  23271. ASNGetData dataASN[dsaSigASN_Length];
  23272. word32 idx = 0;
  23273. /* Clear dynamic data and set mp_ints to put r and s into. */
  23274. XMEMSET(dataASN, 0, sizeof(dataASN));
  23275. GetASN_MP(&dataASN[1], r);
  23276. GetASN_MP(&dataASN[2], s);
  23277. /* Decode the DSA signature. */
  23278. return GetASN_Items(dsaSigASN, dataASN, dsaSigASN_Length, 1, sig, &idx,
  23279. sigLen);
  23280. #endif /* WOLFSSL_ASN_TEMPLATE */
  23281. }
  23282. #endif
  23283. #ifdef WOLFSSL_ASN_TEMPLATE
  23284. #ifdef WOLFSSL_CUSTOM_CURVES
  23285. /* Convert data to hex string.
  23286. *
  23287. * Big-endian byte array is converted to big-endian hexadecimal string.
  23288. *
  23289. * @param [in] input Buffer containing data.
  23290. * @param [in] inSz Size of data in buffer.
  23291. * @param [out] out Buffer to hold hex string.
  23292. */
  23293. static void DataToHexString(const byte* input, word32 inSz, char* out)
  23294. {
  23295. static const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  23296. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  23297. word32 i;
  23298. /* Converting a byte of data at a time to two hex characters. */
  23299. for (i = 0; i < inSz; i++) {
  23300. out[i*2 + 0] = hexChar[input[i] >> 4];
  23301. out[i*2 + 1] = hexChar[input[i] & 0xf];
  23302. }
  23303. /* NUL terminate string. */
  23304. out[i * 2] = '\0';
  23305. }
  23306. /* Convert data to hex string and place in allocated buffer.
  23307. *
  23308. * Big-endian byte array is converted to big-endian hexadecimal string.
  23309. *
  23310. * @param [in] input Buffer containing data.
  23311. * @param [in] inSz Size of data in buffer.
  23312. * @param [out] out Allocated buffer holding hex string.
  23313. * @param [in] heap Dynamic memory allocation hint.
  23314. * @param [in] heapType Type of heap to use.
  23315. * @return 0 on succcess.
  23316. * @return MEMORY_E when dynamic memory allocation fails.
  23317. */
  23318. static int DataToHexStringAlloc(const byte* input, word32 inSz, char** out,
  23319. void* heap, int heapType)
  23320. {
  23321. int ret = 0;
  23322. char* str;
  23323. /* Allocate for 2 string characters ber byte plus NUL. */
  23324. str = (char*)XMALLOC(inSz * 2 + 1, heap, heapType);
  23325. if (str == NULL) {
  23326. ret = MEMORY_E;
  23327. }
  23328. else {
  23329. /* Convert to hex string. */
  23330. DataToHexString(input, inSz, str);
  23331. *out = str;
  23332. }
  23333. (void)heap;
  23334. (void)heapType;
  23335. return ret;
  23336. }
  23337. /* ASN.1 template for SpecifiedECDomain.
  23338. * SEC 1 Ver. 2.0, C.2 - Syntax for Elliptic Curve Domain Parameters
  23339. * NOTE: characteristic-two-field not supported. */
  23340. static const ASNItem eccSpecifiedASN[] = {
  23341. /* version */
  23342. /* 0 */ { 0, ASN_INTEGER, 0, 0, 0 },
  23343. /* fieldID */
  23344. /* 1 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23345. /* prime-field or characteristic-two-field */
  23346. /* 2 */ { 1, ASN_OBJECT_ID, 0, 0, 0 },
  23347. /* Prime-p */
  23348. /* 3 */ { 1, ASN_INTEGER, 0, 0, 0 },
  23349. /* fieldID */
  23350. /* 4 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23351. /* a */
  23352. /* 5 */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  23353. /* b */
  23354. /* 6 */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  23355. /* seed */
  23356. /* 7 */ { 1, ASN_BIT_STRING, 0, 0, 1 },
  23357. /* base */
  23358. /* 8 */ { 0, ASN_OCTET_STRING, 0, 0, 0 },
  23359. /* order */
  23360. /* 9 */ { 0, ASN_INTEGER, 0, 0, 0 },
  23361. /* cofactor */
  23362. /* 10 */ { 0, ASN_INTEGER, 0, 0, 1 },
  23363. /* hash */
  23364. /* 11 */ { 0, ASN_SEQUENCE, 0, 0, 1 },
  23365. };
  23366. /* Number of items in ASN.1 template for SpecifiedECDomain. */
  23367. #define eccSpecifiedASN_Length (sizeof(eccSpecifiedASN) / sizeof(ASNItem))
  23368. /* OID indicating the prime field is explicity defined. */
  23369. static const byte primeFieldOID[] = {
  23370. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x01, 0x01
  23371. };
  23372. static const char ecSetCustomName[] = "Custom";
  23373. /* Explicit EC parameter values. */
  23374. static int EccSpecifiedECDomainDecode(const byte* input, word32 inSz,
  23375. ecc_key* key)
  23376. {
  23377. DECL_ASNGETDATA(dataASN, eccSpecifiedASN_Length);
  23378. int ret = 0;
  23379. ecc_set_type* curve;
  23380. word32 idx = 0;
  23381. byte version;
  23382. byte cofactor;
  23383. const byte *base;
  23384. word32 baseLen;
  23385. /* Allocate a new parameter set. */
  23386. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  23387. DYNAMIC_TYPE_ECC_BUFFER);
  23388. if (curve == NULL)
  23389. ret = MEMORY_E;
  23390. CALLOC_ASNGETDATA(dataASN, eccSpecifiedASN_Length, ret, key->heap);
  23391. if (ret == 0) {
  23392. /* Clear out parameters and set fields to indicate it is custom. */
  23393. XMEMSET(curve, 0, sizeof(*curve));
  23394. /* Set name to be: "Custom" */
  23395. #ifndef WOLFSSL_ECC_CURVE_STATIC
  23396. curve->name = ecSetCustomName;
  23397. #else
  23398. XMEMCPY((void*)curve->name, ecSetCustomName, sizeof(ecSetCustomName));
  23399. #endif
  23400. curve->id = ECC_CURVE_CUSTOM;
  23401. /* Get version, must have prime field OID and get co-factor. */
  23402. GetASN_Int8Bit(&dataASN[0], &version);
  23403. GetASN_ExpBuffer(&dataASN[2], primeFieldOID, sizeof(primeFieldOID));
  23404. GetASN_Int8Bit(&dataASN[10], &cofactor);
  23405. /* Decode the explicit parameters. */
  23406. ret = GetASN_Items(eccSpecifiedASN, dataASN, eccSpecifiedASN_Length, 1,
  23407. input, &idx, inSz);
  23408. }
  23409. /* Version must be 1 or 2 for supporting explicit parameters. */
  23410. if ((ret == 0) && (version < 1 || version > 3)) {
  23411. ret = ASN_PARSE_E;
  23412. }
  23413. /* Only version 2 and above can have a seed. */
  23414. if ((ret == 0) && (dataASN[7].tag != 0) && (version < 2)) {
  23415. ret = ASN_PARSE_E;
  23416. }
  23417. /* Only version 2 and above can have a hash algorithm. */
  23418. if ((ret == 0) && (dataASN[11].tag != 0) && (version < 2)) {
  23419. ret = ASN_PARSE_E;
  23420. }
  23421. if ((ret == 0) && (dataASN[10].tag != 0)) {
  23422. /* Store optional co-factor. */
  23423. curve->cofactor = cofactor;
  23424. }
  23425. if (ret == 0) {
  23426. /* Length of the prime in bytes is the curve size. */
  23427. curve->size = (int)dataASN[3].data.ref.length;
  23428. /* Base point: 0x04 <x> <y> (must be uncompressed). */
  23429. GetASN_GetConstRef(&dataASN[8], &base, &baseLen);
  23430. if ((baseLen < (word32)curve->size * 2 + 1) || (base[0] != 0x4)) {
  23431. ret = ASN_PARSE_E;
  23432. }
  23433. }
  23434. /* Put the curve parameters into the set.
  23435. * Convert the big-endian number byte array to a big-endian string.
  23436. */
  23437. #ifndef WOLFSSL_ECC_CURVE_STATIC
  23438. /* Allocate buffer to put hex strings into. */
  23439. if (ret == 0) {
  23440. /* Base X-ordinate */
  23441. ret = DataToHexStringAlloc(base + 1, curve->size,
  23442. (char**)&curve->Gx, key->heap,
  23443. DYNAMIC_TYPE_ECC_BUFFER);
  23444. }
  23445. if (ret == 0) {
  23446. /* Base Y-ordinate */
  23447. ret = DataToHexStringAlloc(base + 1 + curve->size, curve->size,
  23448. (char**)&curve->Gy, key->heap,
  23449. DYNAMIC_TYPE_ECC_BUFFER);
  23450. }
  23451. if (ret == 0) {
  23452. /* Prime */
  23453. ret = DataToHexStringAlloc(dataASN[3].data.ref.data,
  23454. dataASN[3].data.ref.length,
  23455. (char**)&curve->prime, key->heap,
  23456. DYNAMIC_TYPE_ECC_BUFFER);
  23457. }
  23458. if (ret == 0) {
  23459. /* Parameter A */
  23460. ret = DataToHexStringAlloc(dataASN[5].data.ref.data,
  23461. dataASN[5].data.ref.length,
  23462. (char**)&curve->Af, key->heap,
  23463. DYNAMIC_TYPE_ECC_BUFFER);
  23464. }
  23465. if (ret == 0) {
  23466. /* Parameter B */
  23467. ret = DataToHexStringAlloc(dataASN[6].data.ref.data,
  23468. dataASN[6].data.ref.length,
  23469. (char**)&curve->Bf, key->heap,
  23470. DYNAMIC_TYPE_ECC_BUFFER);
  23471. }
  23472. if (ret == 0) {
  23473. /* Order of curve */
  23474. ret = DataToHexStringAlloc(dataASN[9].data.ref.data,
  23475. dataASN[9].data.ref.length,
  23476. (char**)&curve->order, key->heap,
  23477. DYNAMIC_TYPE_ECC_BUFFER);
  23478. }
  23479. #else
  23480. if (ret == 0) {
  23481. /* Base X-ordinate */
  23482. DataToHexString(base + 1, curve->size, curve->Gx);
  23483. /* Base Y-ordinate */
  23484. DataToHexString(base + 1 + curve->size, curve->size, curve->Gy);
  23485. /* Prime */
  23486. DataToHexString(dataASN[3].data.ref.data, dataASN[3].data.ref.length,
  23487. curve->prime);
  23488. /* Parameter A */
  23489. DataToHexString(dataASN[5].data.ref.data, dataASN[5].data.ref.length,
  23490. curve->Af);
  23491. /* Parameter B */
  23492. DataToHexString(dataASN[6].data.ref.data, dataASN[6].data.ref.length,
  23493. curve->Bf);
  23494. /* Order of curve */
  23495. DataToHexString(dataASN[9].data.ref.data, dataASN[9].data.ref.length,
  23496. curve->order);
  23497. }
  23498. #endif /* WOLFSSL_ECC_CURVE_STATIC */
  23499. /* Store parameter set in key. */
  23500. if ((ret == 0) && (wc_ecc_set_custom_curve(key, curve) < 0)) {
  23501. ret = ASN_PARSE_E;
  23502. }
  23503. if (ret == 0) {
  23504. /* The parameter set was allocated.. */
  23505. key->deallocSet = 1;
  23506. }
  23507. if ((ret != 0) && (curve != NULL)) {
  23508. /* Failed to set parameters so free paramter set. */
  23509. wc_ecc_free_curve(curve, key->heap);
  23510. }
  23511. FREE_ASNGETDATA(dataASN, key->heap);
  23512. return ret;
  23513. }
  23514. #endif /* WOLFSSL_CUSTOM_CURVES */
  23515. #endif /* WOLFSSL_ASN_TEMPLATE */
  23516. #ifdef HAVE_ECC
  23517. #ifdef WOLFSSL_ASN_TEMPLATE
  23518. /* ASN.1 template for ECC private key.
  23519. * SEC.1 Ver 2.0, C.4 - Syntax for Elliptic Curve Private Keys
  23520. */
  23521. static const ASNItem eccKeyASN[] = {
  23522. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  23523. /* version */
  23524. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  23525. /* privateKey */
  23526. /* 2 */ { 1, ASN_OCTET_STRING, 0, 0, 0 },
  23527. /* parameters */
  23528. /* 3 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  23529. /* named */
  23530. /* 4 */ { 2, ASN_OBJECT_ID, 0, 0, 2 },
  23531. /* specified */
  23532. /* 5 */ { 2, ASN_SEQUENCE, 1, 0, 2 },
  23533. /* publicKey */
  23534. /* 6 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 1 },
  23535. /* Uncompressed point - X9.62. */
  23536. /* 7 */ { 2, ASN_BIT_STRING, 0, 0, 0 },
  23537. };
  23538. /* Number of items in ASN.1 template for ECC private key. */
  23539. #define eccKeyASN_Length (sizeof(eccKeyASN) / sizeof(ASNItem))
  23540. #endif
  23541. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  23542. word32 inSz)
  23543. {
  23544. #ifndef WOLFSSL_ASN_TEMPLATE
  23545. word32 oidSum;
  23546. int version, length;
  23547. int privSz, pubSz = 0;
  23548. byte b;
  23549. int ret = 0;
  23550. int curve_id = ECC_CURVE_DEF;
  23551. #ifdef WOLFSSL_SMALL_STACK
  23552. byte* priv;
  23553. byte* pub = NULL;
  23554. #else
  23555. byte priv[ECC_MAXSIZE+1];
  23556. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  23557. #endif
  23558. word32 algId = 0;
  23559. byte* pubData = NULL;
  23560. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  23561. return BAD_FUNC_ARG;
  23562. /* if has pkcs8 header skip it */
  23563. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  23564. /* ignore error, did not have pkcs8 header */
  23565. }
  23566. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  23567. return ASN_PARSE_E;
  23568. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  23569. return ASN_PARSE_E;
  23570. if (*inOutIdx >= inSz)
  23571. return ASN_PARSE_E;
  23572. b = input[*inOutIdx];
  23573. *inOutIdx += 1;
  23574. /* priv type */
  23575. if (b != 4 && b != 6 && b != 7)
  23576. return ASN_PARSE_E;
  23577. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  23578. return ASN_PARSE_E;
  23579. privSz = length;
  23580. if (privSz > ECC_MAXSIZE)
  23581. return BUFFER_E;
  23582. #ifdef WOLFSSL_SMALL_STACK
  23583. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23584. if (priv == NULL)
  23585. return MEMORY_E;
  23586. #endif
  23587. /* priv key */
  23588. XMEMCPY(priv, &input[*inOutIdx], privSz);
  23589. *inOutIdx += length;
  23590. if ((*inOutIdx + 1) < inSz) {
  23591. /* prefix 0, may have */
  23592. b = input[*inOutIdx];
  23593. if (b == ECC_PREFIX_0) {
  23594. *inOutIdx += 1;
  23595. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  23596. ret = ASN_PARSE_E;
  23597. else {
  23598. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  23599. inSz);
  23600. if (ret == 0) {
  23601. if ((ret = CheckCurve(oidSum)) < 0)
  23602. ret = ECC_CURVE_OID_E;
  23603. else {
  23604. curve_id = ret;
  23605. ret = 0;
  23606. }
  23607. }
  23608. }
  23609. }
  23610. }
  23611. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  23612. /* prefix 1 */
  23613. b = input[*inOutIdx];
  23614. *inOutIdx += 1;
  23615. if (b != ECC_PREFIX_1) {
  23616. ret = ASN_ECC_KEY_E;
  23617. }
  23618. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  23619. ret = ASN_PARSE_E;
  23620. }
  23621. else {
  23622. /* key header */
  23623. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  23624. if (ret == 0) {
  23625. /* pub key */
  23626. pubSz = length;
  23627. if (pubSz > 2*(ECC_MAXSIZE+1))
  23628. ret = BUFFER_E;
  23629. else {
  23630. #ifdef WOLFSSL_SMALL_STACK
  23631. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23632. if (pub == NULL)
  23633. ret = MEMORY_E;
  23634. else
  23635. #endif
  23636. {
  23637. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  23638. *inOutIdx += length;
  23639. pubData = pub;
  23640. }
  23641. }
  23642. }
  23643. }
  23644. }
  23645. if (ret == 0) {
  23646. ret = wc_ecc_import_private_key_ex(priv, privSz, pubData, pubSz, key,
  23647. curve_id);
  23648. }
  23649. #ifdef WOLFSSL_SMALL_STACK
  23650. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23651. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  23652. #endif
  23653. return ret;
  23654. #else
  23655. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  23656. byte version;
  23657. int ret = 0;
  23658. int curve_id = ECC_CURVE_DEF;
  23659. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  23660. word32 algId = 0;
  23661. #endif
  23662. /* Validate parameters. */
  23663. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  23664. ret = BAD_FUNC_ARG;
  23665. }
  23666. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  23667. /* if has pkcs8 header skip it */
  23668. if (ToTraditionalInline_ex(input, inOutIdx, inSz, &algId) < 0) {
  23669. /* ignore error, did not have pkcs8 header */
  23670. }
  23671. #endif
  23672. CALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  23673. if (ret == 0) {
  23674. /* Get the version and set the expected OID type. */
  23675. GetASN_Int8Bit(&dataASN[1], &version);
  23676. GetASN_OID(&dataASN[4], oidCurveType);
  23677. /* Decode the private ECC key. */
  23678. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  23679. inOutIdx, inSz);
  23680. }
  23681. /* Only version 1 supported. */
  23682. if ((ret == 0) && (version != 1)) {
  23683. ret = ASN_PARSE_E;
  23684. }
  23685. /* Curve Parameters are optional. */
  23686. if ((ret == 0) && (dataASN[3].tag != 0)) {
  23687. if (dataASN[4].tag != 0) {
  23688. /* Named curve - check and get id. */
  23689. curve_id = CheckCurve(dataASN[4].data.oid.sum);
  23690. if (curve_id < 0) {
  23691. ret = ECC_CURVE_OID_E;
  23692. }
  23693. }
  23694. else {
  23695. #ifdef WOLFSSL_CUSTOM_CURVES
  23696. /* Parse explicit parameters. */
  23697. ret = EccSpecifiedECDomainDecode(dataASN[5].data.ref.data,
  23698. dataASN[5].data.ref.length, key);
  23699. #else
  23700. /* Explicit parameters not supported in build configuration. */
  23701. ret = ASN_PARSE_E;
  23702. #endif
  23703. }
  23704. }
  23705. if (ret == 0) {
  23706. /* Import private key value and public point (may be NULL). */
  23707. ret = wc_ecc_import_private_key_ex(dataASN[2].data.ref.data,
  23708. dataASN[2].data.ref.length, dataASN[7].data.ref.data,
  23709. dataASN[7].data.ref.length, key, curve_id);
  23710. }
  23711. FREE_ASNGETDATA(dataASN, key->heap);
  23712. return ret;
  23713. #endif
  23714. }
  23715. #ifdef WOLFSSL_CUSTOM_CURVES
  23716. #ifndef WOLFSSL_ASN_TEMPLATE
  23717. /* returns 0 on success */
  23718. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  23719. word32 inSz, void* heap, int heapType)
  23720. {
  23721. int len;
  23722. int i;
  23723. char* str;
  23724. word32 localIdx;
  23725. byte tag;
  23726. if (*inOutIdx >= inSz) {
  23727. return BUFFER_E;
  23728. }
  23729. localIdx = *inOutIdx;
  23730. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  23731. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  23732. return ASN_PARSE_E;
  23733. }
  23734. else {
  23735. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  23736. return ASN_PARSE_E;
  23737. }
  23738. str = (char*)XMALLOC(len * 2 + 1, heap, heapType);
  23739. if (str == NULL) {
  23740. return MEMORY_E;
  23741. }
  23742. for (i=0; i<len; i++)
  23743. ByteToHexStr(input[*inOutIdx + i], str + i*2);
  23744. str[len*2] = '\0';
  23745. *inOutIdx += len;
  23746. *out = str;
  23747. (void)heap;
  23748. (void)heapType;
  23749. return 0;
  23750. }
  23751. static int EccKeyParamCopy(char** dst, char* src)
  23752. {
  23753. int ret = 0;
  23754. #ifdef WOLFSSL_ECC_CURVE_STATIC
  23755. word32 length;
  23756. #endif
  23757. if (dst == NULL || src == NULL)
  23758. return BAD_FUNC_ARG;
  23759. #ifndef WOLFSSL_ECC_CURVE_STATIC
  23760. *dst = src;
  23761. #else
  23762. length = (int)XSTRLEN(src) + 1;
  23763. if (length > MAX_ECC_STRING) {
  23764. WOLFSSL_MSG("ECC Param too large for buffer");
  23765. ret = BUFFER_E;
  23766. }
  23767. else {
  23768. XSTRNCPY(*dst, src, MAX_ECC_STRING);
  23769. }
  23770. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23771. #endif
  23772. return ret;
  23773. }
  23774. #endif /* !WOLFSSL_ASN_TEMPLATE */
  23775. #endif /* WOLFSSL_CUSTOM_CURVES */
  23776. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  23777. ecc_key* key, word32 inSz)
  23778. {
  23779. #ifndef WOLFSSL_ASN_TEMPLATE
  23780. int ret;
  23781. int version, length;
  23782. int curve_id = ECC_CURVE_DEF;
  23783. word32 oidSum, localIdx;
  23784. byte tag, isPrivFormat = 0;
  23785. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  23786. return BAD_FUNC_ARG;
  23787. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  23788. return ASN_PARSE_E;
  23789. /* Check if ECC private key is being used and skip private portion */
  23790. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  23791. isPrivFormat = 1;
  23792. /* Type private key */
  23793. if (*inOutIdx >= inSz)
  23794. return ASN_PARSE_E;
  23795. tag = input[*inOutIdx];
  23796. *inOutIdx += 1;
  23797. if (tag != 4 && tag != 6 && tag != 7)
  23798. return ASN_PARSE_E;
  23799. /* Skip Private Key */
  23800. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  23801. return ASN_PARSE_E;
  23802. if (length > ECC_MAXSIZE)
  23803. return BUFFER_E;
  23804. *inOutIdx += length;
  23805. /* Private Curve Header */
  23806. if (*inOutIdx >= inSz)
  23807. return ASN_PARSE_E;
  23808. tag = input[*inOutIdx];
  23809. *inOutIdx += 1;
  23810. if (tag != ECC_PREFIX_0)
  23811. return ASN_ECC_KEY_E;
  23812. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  23813. return ASN_PARSE_E;
  23814. }
  23815. /* Standard ECC public key */
  23816. else {
  23817. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  23818. return ASN_PARSE_E;
  23819. ret = SkipObjectId(input, inOutIdx, inSz);
  23820. if (ret != 0)
  23821. return ret;
  23822. }
  23823. if (*inOutIdx >= inSz) {
  23824. return BUFFER_E;
  23825. }
  23826. localIdx = *inOutIdx;
  23827. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  23828. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  23829. #ifdef WOLFSSL_CUSTOM_CURVES
  23830. ecc_set_type* curve;
  23831. int len;
  23832. char* point = NULL;
  23833. ret = 0;
  23834. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  23835. DYNAMIC_TYPE_ECC_BUFFER);
  23836. if (curve == NULL)
  23837. ret = MEMORY_E;
  23838. if (ret == 0) {
  23839. static const char customName[] = "Custom";
  23840. XMEMSET(curve, 0, sizeof(*curve));
  23841. #ifndef WOLFSSL_ECC_CURVE_STATIC
  23842. curve->name = customName;
  23843. #else
  23844. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  23845. #endif
  23846. curve->id = ECC_CURVE_CUSTOM;
  23847. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  23848. ret = ASN_PARSE_E;
  23849. }
  23850. if (ret == 0) {
  23851. GetInteger7Bit(input, inOutIdx, inSz);
  23852. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  23853. ret = ASN_PARSE_E;
  23854. }
  23855. if (ret == 0) {
  23856. char* p = NULL;
  23857. SkipObjectId(input, inOutIdx, inSz);
  23858. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  23859. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23860. if (ret == 0)
  23861. ret = EccKeyParamCopy((char**)&curve->prime, p);
  23862. }
  23863. if (ret == 0) {
  23864. curve->size = (int)XSTRLEN(curve->prime) / 2;
  23865. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  23866. ret = ASN_PARSE_E;
  23867. }
  23868. if (ret == 0) {
  23869. char* af = NULL;
  23870. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  23871. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23872. if (ret == 0)
  23873. ret = EccKeyParamCopy((char**)&curve->Af, af);
  23874. }
  23875. if (ret == 0) {
  23876. char* bf = NULL;
  23877. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  23878. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23879. if (ret == 0)
  23880. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  23881. }
  23882. if (ret == 0) {
  23883. localIdx = *inOutIdx;
  23884. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  23885. == 0 && tag == ASN_BIT_STRING) {
  23886. len = 0;
  23887. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  23888. if (ret > 0)
  23889. ret = 0; /* reset on success */
  23890. *inOutIdx += len;
  23891. }
  23892. }
  23893. if (ret == 0) {
  23894. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  23895. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23896. /* sanity check that point buffer is not smaller than the expected
  23897. * size to hold ( 0 4 || Gx || Gy )
  23898. * where Gx and Gy are each the size of curve->size * 2 */
  23899. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  23900. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23901. ret = BUFFER_E;
  23902. }
  23903. }
  23904. if (ret == 0) {
  23905. #ifndef WOLFSSL_ECC_CURVE_STATIC
  23906. curve->Gx = (const char*)XMALLOC(curve->size * 2 + 2, key->heap,
  23907. DYNAMIC_TYPE_ECC_BUFFER);
  23908. curve->Gy = (const char*)XMALLOC(curve->size * 2 + 2, key->heap,
  23909. DYNAMIC_TYPE_ECC_BUFFER);
  23910. if (curve->Gx == NULL || curve->Gy == NULL) {
  23911. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23912. ret = MEMORY_E;
  23913. }
  23914. #else
  23915. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  23916. WOLFSSL_MSG("curve size is too large to fit in buffer");
  23917. ret = BUFFER_E;
  23918. }
  23919. #endif
  23920. }
  23921. if (ret == 0) {
  23922. char* o = NULL;
  23923. XMEMCPY((char*)curve->Gx, point + 2, curve->size * 2);
  23924. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  23925. curve->size * 2);
  23926. ((char*)curve->Gx)[curve->size * 2] = '\0';
  23927. ((char*)curve->Gy)[curve->size * 2] = '\0';
  23928. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23929. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  23930. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  23931. if (ret == 0)
  23932. ret = EccKeyParamCopy((char**)&curve->order, o);
  23933. }
  23934. if (ret == 0) {
  23935. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  23936. #ifndef WOLFSSL_ECC_CURVE_STATIC
  23937. curve->oid = NULL;
  23938. #else
  23939. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  23940. #endif
  23941. curve->oidSz = 0;
  23942. curve->oidSum = 0;
  23943. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  23944. ret = ASN_PARSE_E;
  23945. }
  23946. #ifdef WOLFSSL_CUSTOM_CURVES
  23947. key->deallocSet = 1;
  23948. #endif
  23949. curve = NULL;
  23950. }
  23951. if (curve != NULL)
  23952. wc_ecc_free_curve(curve, key->heap);
  23953. if (ret < 0)
  23954. return ret;
  23955. #else
  23956. return ASN_PARSE_E;
  23957. #endif /* WOLFSSL_CUSTOM_CURVES */
  23958. }
  23959. else {
  23960. /* ecc params information */
  23961. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  23962. if (ret != 0)
  23963. return ret;
  23964. /* get curve id */
  23965. if ((ret = CheckCurve(oidSum)) < 0)
  23966. return ECC_CURVE_OID_E;
  23967. else {
  23968. curve_id = ret;
  23969. }
  23970. }
  23971. if (isPrivFormat) {
  23972. /* Public Curve Header - skip */
  23973. if (*inOutIdx >= inSz)
  23974. return ASN_PARSE_E;
  23975. tag = input[*inOutIdx];
  23976. *inOutIdx += 1;
  23977. if (tag != ECC_PREFIX_1)
  23978. return ASN_ECC_KEY_E;
  23979. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  23980. return ASN_PARSE_E;
  23981. }
  23982. /* key header */
  23983. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  23984. if (ret != 0)
  23985. return ret;
  23986. /* This is the raw point data compressed or uncompressed. */
  23987. if (wc_ecc_import_x963_ex(input + *inOutIdx, length, key,
  23988. curve_id) != 0) {
  23989. return ASN_ECC_KEY_E;
  23990. }
  23991. *inOutIdx += length;
  23992. return 0;
  23993. #else
  23994. /* eccKeyASN is longer than eccPublicKeyASN. */
  23995. DECL_ASNGETDATA(dataASN, eccKeyASN_Length);
  23996. int ret = 0;
  23997. int curve_id = ECC_CURVE_DEF;
  23998. int oidIdx = 3;
  23999. #ifdef WOLFSSL_CUSTOM_CURVES
  24000. int specIdx = 4;
  24001. #endif
  24002. int pubIdx = 5;
  24003. if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
  24004. ret = BAD_FUNC_ARG;
  24005. }
  24006. ALLOC_ASNGETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  24007. if (ret == 0) {
  24008. /* Clear dynamic data for ECC public key. */
  24009. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccPublicKeyASN_Length);
  24010. /* Set required ECDSA OID and ignore the curve OID type. */
  24011. GetASN_ExpBuffer(&dataASN[2], keyEcdsaOid, sizeof(keyEcdsaOid));
  24012. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  24013. /* Decode the public ECC key. */
  24014. ret = GetASN_Items(eccPublicKeyASN, dataASN, eccPublicKeyASN_Length, 1,
  24015. input, inOutIdx, inSz);
  24016. if (ret != 0) {
  24017. oidIdx = 4;
  24018. #ifdef WOLFSSL_CUSTOM_CURVES
  24019. specIdx = 5;
  24020. #endif
  24021. pubIdx = 7;
  24022. /* Clear dynamic data for ECC private key. */
  24023. XMEMSET(dataASN, 0, sizeof(*dataASN) * eccKeyASN_Length);
  24024. /* Check named curve OID type. */
  24025. GetASN_OID(&dataASN[oidIdx], oidIgnoreType);
  24026. /* Try private key format .*/
  24027. ret = GetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, 1, input,
  24028. inOutIdx, inSz);
  24029. if (ret != 0) {
  24030. ret = ASN_PARSE_E;
  24031. }
  24032. }
  24033. }
  24034. if (ret == 0) {
  24035. if (dataASN[oidIdx].tag != 0) {
  24036. /* Named curve - check and get id. */
  24037. curve_id = CheckCurve(dataASN[oidIdx].data.oid.sum);
  24038. if (curve_id < 0) {
  24039. ret = ASN_OBJECT_ID_E;
  24040. }
  24041. }
  24042. else {
  24043. #ifdef WOLFSSL_CUSTOM_CURVES
  24044. /* Parse explicit parameters. */
  24045. ret = EccSpecifiedECDomainDecode(dataASN[specIdx].data.ref.data,
  24046. dataASN[specIdx].data.ref.length, key);
  24047. #else
  24048. /* Explicit parameters not supported in build configuration. */
  24049. ret = ASN_PARSE_E;
  24050. #endif
  24051. }
  24052. }
  24053. if (ret == 0) {
  24054. /* Import public point. */
  24055. ret = wc_ecc_import_x963_ex(dataASN[pubIdx].data.ref.data,
  24056. dataASN[pubIdx].data.ref.length, key, curve_id);
  24057. if (ret != 0) {
  24058. ret = ASN_ECC_KEY_E;
  24059. }
  24060. }
  24061. FREE_ASNGETDATA(dataASN, key->heap);
  24062. return ret;
  24063. #endif /* WOLFSSL_ASN_TEMPLATE */
  24064. }
  24065. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  24066. /* build DER formatted ECC key, include optional public key if requested,
  24067. * return length on success, negative on error */
  24068. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  24069. int pubIn, int curveIn)
  24070. {
  24071. #ifndef WOLFSSL_ASN_TEMPLATE
  24072. byte curve[MAX_ALGO_SZ+2];
  24073. byte ver[MAX_VERSION_SZ];
  24074. byte seq[MAX_SEQ_SZ];
  24075. int ret, totalSz, curveSz, verSz;
  24076. int privHdrSz = ASN_ECC_HEADER_SZ;
  24077. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  24078. #ifdef WOLFSSL_NO_MALLOC
  24079. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  24080. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  24081. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  24082. #else
  24083. byte *prv = NULL, *pub = NULL;
  24084. #endif
  24085. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  24086. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  24087. if (key == NULL || (output == NULL && inLen == NULL))
  24088. return BAD_FUNC_ARG;
  24089. if (curveIn) {
  24090. /* curve */
  24091. curve[curveidx++] = ECC_PREFIX_0;
  24092. curveidx++ /* to put the size after computation */;
  24093. curveSz = SetCurve(key, curve+curveidx);
  24094. if (curveSz < 0)
  24095. return curveSz;
  24096. /* set computed size */
  24097. curve[1] = (byte)curveSz;
  24098. curveidx += curveSz;
  24099. }
  24100. /* private */
  24101. privSz = key->dp->size;
  24102. #ifdef WOLFSSL_QNX_CAAM
  24103. /* check if is a black key, and add MAC size if so */
  24104. if (key->blackKey > 0) {
  24105. privSz = privSz + WC_CAAM_MAC_SZ;
  24106. }
  24107. #endif
  24108. #ifndef WOLFSSL_NO_MALLOC
  24109. prv = (byte*)XMALLOC(privSz + privHdrSz + MAX_SEQ_SZ,
  24110. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24111. if (prv == NULL) {
  24112. return MEMORY_E;
  24113. }
  24114. #else
  24115. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  24116. return BUFFER_E;
  24117. }
  24118. #endif
  24119. if (privSz < ASN_LONG_LENGTH) {
  24120. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  24121. }
  24122. else {
  24123. prvidx += SetOctetString(privSz, &prv[prvidx]);
  24124. }
  24125. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  24126. if (ret < 0) {
  24127. #ifndef WOLFSSL_NO_MALLOC
  24128. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24129. #endif
  24130. return ret;
  24131. }
  24132. prvidx += privSz;
  24133. /* pubIn */
  24134. if (pubIn) {
  24135. PRIVATE_KEY_UNLOCK();
  24136. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  24137. PRIVATE_KEY_LOCK();
  24138. if (ret != LENGTH_ONLY_E) {
  24139. #ifndef WOLFSSL_NO_MALLOC
  24140. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24141. #endif
  24142. return ret;
  24143. }
  24144. #ifndef WOLFSSL_NO_MALLOC
  24145. pub = (byte*)XMALLOC(pubSz + pubHdrSz + MAX_SEQ_SZ,
  24146. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24147. if (pub == NULL) {
  24148. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24149. return MEMORY_E;
  24150. }
  24151. #else
  24152. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  24153. return BUFFER_E;
  24154. }
  24155. #endif
  24156. pub[pubidx++] = ECC_PREFIX_1;
  24157. if (pubSz > 128) /* leading zero + extra size byte */
  24158. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  24159. else /* leading zero */
  24160. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  24161. /* SetBitString adds leading zero */
  24162. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  24163. PRIVATE_KEY_UNLOCK();
  24164. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  24165. PRIVATE_KEY_LOCK();
  24166. if (ret != 0) {
  24167. #ifndef WOLFSSL_NO_MALLOC
  24168. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24169. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24170. #endif
  24171. return ret;
  24172. }
  24173. pubidx += pubSz;
  24174. }
  24175. /* make headers */
  24176. verSz = SetMyVersion(1, ver, FALSE);
  24177. seqSz = SetSequence(verSz + prvidx + pubidx + curveidx, seq);
  24178. totalSz = prvidx + pubidx + curveidx + verSz + seqSz;
  24179. if (output == NULL) {
  24180. *inLen = totalSz;
  24181. #ifndef WOLFSSL_NO_MALLOC
  24182. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24183. if (pub) {
  24184. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24185. }
  24186. #endif
  24187. return LENGTH_ONLY_E;
  24188. }
  24189. if (inLen != NULL && totalSz > (int)*inLen) {
  24190. #ifndef WOLFSSL_NO_MALLOC
  24191. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24192. if (pubIn) {
  24193. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24194. }
  24195. #endif
  24196. return BAD_FUNC_ARG;
  24197. }
  24198. /* write out */
  24199. /* seq */
  24200. XMEMCPY(output + idx, seq, seqSz);
  24201. idx = seqSz;
  24202. /* ver */
  24203. XMEMCPY(output + idx, ver, verSz);
  24204. idx += verSz;
  24205. /* private */
  24206. XMEMCPY(output + idx, prv, prvidx);
  24207. idx += prvidx;
  24208. #ifndef WOLFSSL_NO_MALLOC
  24209. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24210. #endif
  24211. /* curve */
  24212. XMEMCPY(output + idx, curve, curveidx);
  24213. idx += curveidx;
  24214. /* pubIn */
  24215. if (pubIn) {
  24216. XMEMCPY(output + idx, pub, pubidx);
  24217. /* idx += pubidx; not used after write, if more data remove comment */
  24218. #ifndef WOLFSSL_NO_MALLOC
  24219. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24220. #endif
  24221. }
  24222. return totalSz;
  24223. #else
  24224. DECL_ASNSETDATA(dataASN, eccKeyASN_Length);
  24225. word32 privSz, pubSz;
  24226. int sz = 0;
  24227. int ret = 0;
  24228. /* Check validity of parameters. */
  24229. if ((key == NULL) || ((output == NULL) && (inLen == NULL))) {
  24230. ret = BAD_FUNC_ARG;
  24231. }
  24232. /* Check key has parameters when encoding curve. */
  24233. if ((ret == 0) && curveIn && (key->dp == NULL)) {
  24234. ret = BAD_FUNC_ARG;
  24235. }
  24236. CALLOC_ASNSETDATA(dataASN, eccKeyASN_Length, ret, key->heap);
  24237. if (ret == 0) {
  24238. /* Private key size is the curve size. */
  24239. privSz = key->dp->size;
  24240. if (pubIn) {
  24241. /* Get the length of the public key. */
  24242. PRIVATE_KEY_UNLOCK();
  24243. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  24244. PRIVATE_KEY_LOCK();
  24245. if (ret == LENGTH_ONLY_E)
  24246. ret = 0;
  24247. }
  24248. }
  24249. if (ret == 0) {
  24250. /* Version: 1 */
  24251. SetASN_Int8Bit(&dataASN[1], 1);
  24252. /* Leave space for private key. */
  24253. SetASN_Buffer(&dataASN[2], NULL, privSz);
  24254. if (curveIn) {
  24255. /* Curve OID */
  24256. SetASN_Buffer(&dataASN[4], key->dp->oid, key->dp->oidSz);
  24257. }
  24258. else {
  24259. dataASN[3].noOut = 1;
  24260. dataASN[4].noOut = 1;
  24261. }
  24262. /* TODO: add support for SpecifiedECDomain curve. */
  24263. dataASN[5].noOut = 1;
  24264. if (pubIn) {
  24265. /* Leave space for public key. */
  24266. SetASN_Buffer(&dataASN[7], NULL, pubSz);
  24267. }
  24268. else {
  24269. /* Don't write out public key. */
  24270. dataASN[6].noOut = dataASN[7].noOut = 1;
  24271. }
  24272. /* Calculate size of the private key encoding. */
  24273. ret = SizeASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, &sz);
  24274. }
  24275. /* Return the size if no buffer. */
  24276. if ((ret == 0) && (output == NULL)) {
  24277. *inLen = sz;
  24278. ret = LENGTH_ONLY_E;
  24279. }
  24280. /* Check the buffer is big enough. */
  24281. if ((ret == 0) && (inLen != NULL) && (sz > (int)*inLen)) {
  24282. ret = BAD_FUNC_ARG;
  24283. }
  24284. if ((ret == 0) && (output != NULL)) {
  24285. /* Encode the private key. */
  24286. SetASN_Items(eccKeyASN, dataASN, eccKeyASN_Length, output);
  24287. /* Export the private value into the buffer. */
  24288. ret = wc_ecc_export_private_only(key,
  24289. (byte*)dataASN[2].data.buffer.data, &privSz);
  24290. if ((ret == 0) && pubIn) {
  24291. /* Export the public point into the buffer. */
  24292. PRIVATE_KEY_UNLOCK();
  24293. ret = wc_ecc_export_x963(key, (byte*)dataASN[7].data.buffer.data,
  24294. &pubSz);
  24295. PRIVATE_KEY_LOCK();
  24296. }
  24297. }
  24298. if (ret == 0) {
  24299. /* Return the encoding size. */
  24300. ret = sz;
  24301. }
  24302. FREE_ASNSETDATA(dataASN, key->heap);
  24303. return ret;
  24304. #endif
  24305. }
  24306. /* Write a Private ecc key, including public to DER format,
  24307. * length on success else < 0 */
  24308. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  24309. {
  24310. return wc_BuildEccKeyDer(key, output, &inLen, 1, 1);
  24311. }
  24312. /* Write only private ecc key to DER format,
  24313. * length on success else < 0 */
  24314. int wc_EccKeyDerSize(ecc_key* key, int pub)
  24315. {
  24316. word32 sz = 0;
  24317. int ret;
  24318. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub, 1);
  24319. if (ret != LENGTH_ONLY_E) {
  24320. return ret;
  24321. }
  24322. return sz;
  24323. }
  24324. /* Write only private ecc key to DER format,
  24325. * length on success else < 0 */
  24326. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  24327. {
  24328. return wc_BuildEccKeyDer(key, output, &inLen, 0, 1);
  24329. }
  24330. #ifdef HAVE_PKCS8
  24331. /* Write only private ecc key or both private and public parts to unencrypted
  24332. * PKCS#8 format.
  24333. *
  24334. * If output is NULL, places required PKCS#8 buffer size in outLen and
  24335. * returns LENGTH_ONLY_E.
  24336. *
  24337. * return length on success else < 0 */
  24338. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  24339. int includePublic)
  24340. {
  24341. int ret, tmpDerSz;
  24342. int algoID = 0;
  24343. word32 oidSz = 0;
  24344. word32 pkcs8Sz = 0;
  24345. const byte* curveOID = NULL;
  24346. #ifdef WOLFSSL_NO_MALLOC
  24347. byte tmpDer[ECC_BUFSIZE];
  24348. #else
  24349. byte* tmpDer = NULL;
  24350. #endif
  24351. word32 sz = ECC_BUFSIZE;
  24352. if (key == NULL || key->dp == NULL || outLen == NULL)
  24353. return BAD_FUNC_ARG;
  24354. /* set algoID, get curve OID */
  24355. algoID = ECDSAk;
  24356. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  24357. if (ret < 0)
  24358. return ret;
  24359. #ifndef WOLFSSL_NO_MALLOC
  24360. /* temp buffer for plain DER key */
  24361. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24362. if (tmpDer == NULL)
  24363. return MEMORY_E;
  24364. #endif
  24365. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  24366. ret = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic, 0);
  24367. if (ret < 0) {
  24368. #ifndef WOLFSSL_NO_MALLOC
  24369. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24370. #endif
  24371. return ret;
  24372. }
  24373. tmpDerSz = ret;
  24374. /* get pkcs8 expected output size */
  24375. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  24376. curveOID, oidSz);
  24377. if (ret != LENGTH_ONLY_E) {
  24378. #ifndef WOLFSSL_NO_MALLOC
  24379. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24380. #endif
  24381. return ret;
  24382. }
  24383. if (output == NULL) {
  24384. #ifndef WOLFSSL_NO_MALLOC
  24385. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24386. #endif
  24387. *outLen = pkcs8Sz;
  24388. return LENGTH_ONLY_E;
  24389. }
  24390. else if (*outLen < pkcs8Sz) {
  24391. #ifndef WOLFSSL_NO_MALLOC
  24392. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24393. #endif
  24394. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  24395. return BUFFER_E;
  24396. }
  24397. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  24398. algoID, curveOID, oidSz);
  24399. if (ret < 0) {
  24400. #ifndef WOLFSSL_NO_MALLOC
  24401. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24402. #endif
  24403. return ret;
  24404. }
  24405. #ifndef WOLFSSL_NO_MALLOC
  24406. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  24407. #endif
  24408. *outLen = ret;
  24409. return ret;
  24410. }
  24411. /* Write only private ecc key to unencrypted PKCS#8 format.
  24412. *
  24413. * return length on success else < 0 */
  24414. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  24415. {
  24416. return eccToPKCS8(key, output, outLen, 0);
  24417. }
  24418. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  24419. *
  24420. * return length on success else < 0 */
  24421. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  24422. word32* outLen)
  24423. {
  24424. return eccToPKCS8(key, output, outLen, 1);
  24425. }
  24426. #endif /* HAVE_PKCS8 */
  24427. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  24428. #endif /* HAVE_ECC */
  24429. #ifdef WC_ENABLE_ASYM_KEY_IMPORT
  24430. #ifdef WOLFSSL_ASN_TEMPLATE
  24431. /* ASN.1 template for Ed25519 and Ed448 private key.
  24432. * RFC 8410, 7 - Private Key Format (but public value is EXPLICIT OCTET_STRING)
  24433. */
  24434. static const ASNItem edKeyASN[] = {
  24435. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  24436. /* Version */
  24437. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  24438. /* privateKeyAlgorithm */
  24439. /* 2 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  24440. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 1 },
  24441. /* privateKey */
  24442. /* 4 */ { 1, ASN_OCTET_STRING, 0, 1, 0 },
  24443. /* CurvePrivateKey */
  24444. /* 5 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  24445. /* attributes */
  24446. /* 6 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  24447. /* publicKey */
  24448. /* 7 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 1 },
  24449. /* Public value */
  24450. /* 8 */ { 2, ASN_OCTET_STRING, 0, 0, 0 }
  24451. };
  24452. /* Number of items in ASN.1 template for Ed25519 and Ed448 private key. */
  24453. #define edKeyASN_Length (sizeof(edKeyASN) / sizeof(ASNItem))
  24454. #endif
  24455. static int DecodeAsymKey(const byte* input, word32* inOutIdx, word32 inSz,
  24456. byte* privKey, word32* privKeyLen,
  24457. byte* pubKey, word32* pubKeyLen, int keyType)
  24458. {
  24459. #ifndef WOLFSSL_ASN_TEMPLATE
  24460. word32 oid;
  24461. int version, length, endKeyIdx, privSz, pubSz;
  24462. const byte* priv;
  24463. const byte* pub;
  24464. #else
  24465. DECL_ASNGETDATA(dataASN, edKeyASN_Length);
  24466. #endif
  24467. if (input == NULL || inOutIdx == NULL || inSz == 0 ||
  24468. privKey == NULL || privKeyLen == NULL) {
  24469. return BAD_FUNC_ARG;
  24470. }
  24471. #ifndef WOLFSSL_ASN_TEMPLATE
  24472. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  24473. endKeyIdx = *inOutIdx + length;
  24474. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  24475. return ASN_PARSE_E;
  24476. if (version != 0) {
  24477. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  24478. return ASN_PARSE_E;
  24479. }
  24480. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  24481. return ASN_PARSE_E;
  24482. if (oid != (word32)keyType)
  24483. return ASN_PARSE_E;
  24484. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  24485. return ASN_PARSE_E;
  24486. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  24487. return ASN_PARSE_E;
  24488. priv = input + *inOutIdx;
  24489. *inOutIdx += privSz;
  24490. }
  24491. else {
  24492. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  24493. return ASN_PARSE_E;
  24494. priv = input + *inOutIdx;
  24495. *inOutIdx += privSz;
  24496. endKeyIdx = *inOutIdx;
  24497. }
  24498. if ((word32)privSz > *privKeyLen)
  24499. return BUFFER_E;
  24500. if (endKeyIdx == (int)*inOutIdx) {
  24501. *privKeyLen = privSz;
  24502. XMEMCPY(privKey, priv, *privKeyLen);
  24503. if (pubKeyLen != NULL)
  24504. *pubKeyLen = 0;
  24505. }
  24506. else {
  24507. if (pubKeyLen == NULL) {
  24508. return BAD_FUNC_ARG;
  24509. }
  24510. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1,
  24511. inOutIdx, &length, inSz) < 0) {
  24512. return ASN_PARSE_E;
  24513. }
  24514. if (GetOctetString(input, inOutIdx, &pubSz, inSz) < 0) {
  24515. return ASN_PARSE_E;
  24516. }
  24517. if ((word32)pubSz > *pubKeyLen)
  24518. return BUFFER_E;
  24519. pub = input + *inOutIdx;
  24520. *inOutIdx += pubSz;
  24521. *privKeyLen = privSz;
  24522. XMEMCPY(privKey, priv, *privKeyLen);
  24523. if (pubKeyLen != NULL)
  24524. *pubKeyLen = pubSz;
  24525. if (pubKey != NULL && pubKeyLen != NULL)
  24526. XMEMCPY(pubKey, pub, *pubKeyLen);
  24527. }
  24528. if (endKeyIdx != (int)*inOutIdx)
  24529. return ASN_PARSE_E;
  24530. return 0;
  24531. #else
  24532. int ret = 0;
  24533. CALLOC_ASNGETDATA(dataASN, edKeyASN_Length, ret, NULL);
  24534. if (ret == 0) {
  24535. /* Require OID. */
  24536. word32 oidSz;
  24537. const byte* oid = OidFromId(keyType, oidKeyType, &oidSz);
  24538. GetASN_ExpBuffer(&dataASN[3], oid, oidSz);
  24539. /* Parse full private key. */
  24540. ret = GetASN_Items(edKeyASN, dataASN, edKeyASN_Length, 1, input,
  24541. inOutIdx, inSz);
  24542. if (ret != 0) {
  24543. /* Parse just the OCTET_STRING. */
  24544. ret = GetASN_Items(&edKeyASN[5], &dataASN[5], 1, 0, input, inOutIdx,
  24545. inSz);
  24546. if (ret != 0) {
  24547. ret = ASN_PARSE_E;
  24548. }
  24549. }
  24550. }
  24551. /* Check the private value length is correct. */
  24552. if ((ret == 0) && dataASN[5].data.ref.length > *privKeyLen) {
  24553. ret = ASN_PARSE_E;
  24554. }
  24555. if ((ret == 0) && dataASN[7].tag == 0) {
  24556. *privKeyLen = dataASN[5].data.ref.length;
  24557. XMEMCPY(privKey, dataASN[5].data.ref.data, *privKeyLen);
  24558. if (pubKeyLen != NULL)
  24559. *pubKeyLen = 0;
  24560. }
  24561. else if ((ret == 0) &&
  24562. (dataASN[8].data.ref.length > *pubKeyLen)) {
  24563. ret = ASN_PARSE_E;
  24564. }
  24565. else if (ret == 0) {
  24566. /* Import private and public value. */
  24567. *privKeyLen = dataASN[5].data.ref.length;
  24568. XMEMCPY(privKey, dataASN[5].data.ref.data, *privKeyLen);
  24569. if (pubKeyLen != NULL)
  24570. *pubKeyLen = dataASN[8].data.ref.length;
  24571. if (pubKey != NULL && pubKeyLen != NULL)
  24572. XMEMCPY(pubKey, dataASN[8].data.ref.data, *pubKeyLen);
  24573. }
  24574. FREE_ASNGETDATA(dataASN, NULL);
  24575. return ret;
  24576. #endif /* WOLFSSL_ASN_TEMPLATE */
  24577. }
  24578. static int DecodeAsymKeyPublic(const byte* input, word32* inOutIdx, word32 inSz,
  24579. byte* pubKey, word32* pubKeyLen, int keyType)
  24580. {
  24581. int ret = 0;
  24582. #ifndef WOLFSSL_ASN_TEMPLATE
  24583. int length;
  24584. word32 oid;
  24585. #else
  24586. word32 len;
  24587. DECL_ASNGETDATA(dataASN, edPubKeyASN_Length);
  24588. #endif
  24589. if (input == NULL || inSz == 0 || inOutIdx == NULL ||
  24590. pubKey == NULL || pubKeyLen == NULL) {
  24591. return BAD_FUNC_ARG;
  24592. }
  24593. #ifndef WOLFSSL_ASN_TEMPLATE
  24594. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  24595. return ASN_PARSE_E;
  24596. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  24597. return ASN_PARSE_E;
  24598. if (GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  24599. return ASN_PARSE_E;
  24600. if (oid != (word32)keyType)
  24601. return ASN_PARSE_E;
  24602. /* key header */
  24603. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  24604. if (ret != 0)
  24605. return ret;
  24606. /* check that the value found is not too large for pubKey buffer */
  24607. if ((word32)length > *pubKeyLen)
  24608. return ASN_PARSE_E;
  24609. /* check that input buffer is exhausted */
  24610. if (*inOutIdx + (word32)length != inSz)
  24611. return ASN_PARSE_E;
  24612. /* This is the raw point data compressed or uncompressed. */
  24613. *pubKeyLen = length;
  24614. XMEMCPY(pubKey, input + *inOutIdx, *pubKeyLen);
  24615. #else
  24616. len = inSz - *inOutIdx;
  24617. CALLOC_ASNGETDATA(dataASN, edPubKeyASN_Length, ret, NULL);
  24618. if (ret == 0) {
  24619. /* Require OID. */
  24620. word32 oidSz;
  24621. const byte* oid = OidFromId(keyType, oidKeyType, &oidSz);
  24622. GetASN_ExpBuffer(&dataASN[2], oid, oidSz);
  24623. /* Decode Ed25519 private key. */
  24624. ret = GetASN_Items(edPubKeyASN, dataASN, edPubKeyASN_Length, 1, input,
  24625. inOutIdx, inSz);
  24626. if (ret != 0)
  24627. ret = ASN_PARSE_E;
  24628. /* check that input buffer is exhausted */
  24629. if (*inOutIdx != inSz)
  24630. ret = ASN_PARSE_E;
  24631. }
  24632. /* Check the public value length is correct. */
  24633. if ((ret == 0) && (dataASN[3].data.ref.length > *pubKeyLen)) {
  24634. ret = ASN_PARSE_E;
  24635. }
  24636. /* Check that the all the buffer was used. */
  24637. if ((ret == 0) && (GetASNItem_Length(dataASN[0], input) != len)) {
  24638. ret = ASN_PARSE_E;
  24639. }
  24640. if (ret == 0) {
  24641. *pubKeyLen = dataASN[3].data.ref.length;
  24642. XMEMCPY(pubKey, dataASN[3].data.ref.data, *pubKeyLen);
  24643. }
  24644. FREE_ASNGETDATA(dataASN, NULL);
  24645. #endif /* WOLFSSL_ASN_TEMPLATE */
  24646. return ret;
  24647. }
  24648. #endif /* WC_ENABLE_ASYM_KEY_IMPORT */
  24649. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_IMPORT)
  24650. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  24651. ed25519_key* key, word32 inSz)
  24652. {
  24653. int ret;
  24654. byte privKey[ED25519_KEY_SIZE], pubKey[ED25519_PUB_KEY_SIZE];
  24655. word32 privKeyLen = (word32)sizeof(privKey);
  24656. word32 pubKeyLen = (word32)sizeof(pubKey);
  24657. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24658. return BAD_FUNC_ARG;
  24659. }
  24660. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  24661. pubKey, &pubKeyLen, ED25519k);
  24662. if (ret == 0) {
  24663. if (pubKeyLen == 0) {
  24664. ret = wc_ed25519_import_private_only(privKey, privKeyLen, key);
  24665. }
  24666. else {
  24667. ret = wc_ed25519_import_private_key(privKey, privKeyLen,
  24668. pubKey, pubKeyLen, key);
  24669. }
  24670. }
  24671. return ret;
  24672. }
  24673. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  24674. ed25519_key* key, word32 inSz)
  24675. {
  24676. int ret;
  24677. byte pubKey[ED25519_PUB_KEY_SIZE];
  24678. word32 pubKeyLen = (word32)sizeof(pubKey);
  24679. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24680. return BAD_FUNC_ARG;
  24681. }
  24682. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  24683. pubKey, &pubKeyLen, ED25519k);
  24684. if (ret == 0) {
  24685. ret = wc_ed25519_import_public(pubKey, pubKeyLen, key);
  24686. }
  24687. return ret;
  24688. }
  24689. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_IMPORT */
  24690. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_IMPORT)
  24691. int wc_Curve25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  24692. curve25519_key* key, word32 inSz)
  24693. {
  24694. int ret;
  24695. byte privKey[CURVE25519_KEYSIZE];
  24696. word32 privKeyLen = CURVE25519_KEYSIZE;
  24697. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24698. return BAD_FUNC_ARG;
  24699. }
  24700. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  24701. NULL, NULL, X25519k);
  24702. if (ret == 0) {
  24703. ret = wc_curve25519_import_private(privKey, privKeyLen, key);
  24704. }
  24705. return ret;
  24706. }
  24707. int wc_Curve25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  24708. curve25519_key* key, word32 inSz)
  24709. {
  24710. int ret;
  24711. byte pubKey[CURVE25519_KEYSIZE];
  24712. word32 pubKeyLen = (word32)sizeof(pubKey);
  24713. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24714. return BAD_FUNC_ARG;
  24715. }
  24716. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  24717. pubKey, &pubKeyLen, X25519k);
  24718. if (ret == 0) {
  24719. ret = wc_curve25519_import_public(pubKey, pubKeyLen, key);
  24720. }
  24721. return ret;
  24722. }
  24723. #endif /* HAVE_CURVE25519 && HAVE_ED25519_KEY_IMPORT */
  24724. #ifdef WC_ENABLE_ASYM_KEY_EXPORT
  24725. /* Build ASN.1 formatted key based on RFC 5958 (Asymmetric Key Packages)
  24726. *
  24727. * Pass NULL for output to get the size of the encoding.
  24728. *
  24729. * @param [in] privKey private key buffer
  24730. * @param [in] privKeyLen private ket buffer length
  24731. * @param [in] pubKey public key buffer (optional)
  24732. * @param [in] pubKeyLen public ket buffer length
  24733. * @param [out] output Buffer to put encoded data in (optional)
  24734. * @param [in] outLen Size of buffer in bytes
  24735. * @param [in] keyType is "enum Key_Sum" like ED25519k
  24736. * @return Size of encoded data in bytes on success
  24737. * @return BAD_FUNC_ARG when key is NULL.
  24738. * @return MEMORY_E when dynamic memory allocation failed.
  24739. * @return LENGTH_ONLY_E return length only.
  24740. */
  24741. static int SetAsymKeyDer(const byte* privKey, word32 privKeyLen,
  24742. const byte* pubKey, word32 pubKeyLen,
  24743. byte* output, word32 outLen, int keyType)
  24744. {
  24745. int ret = 0;
  24746. #ifndef WOLFSSL_ASN_TEMPLATE
  24747. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0, sz;
  24748. #else
  24749. DECL_ASNSETDATA(dataASN, edKeyASN_Length);
  24750. int sz;
  24751. #endif
  24752. /* Validate parameters. */
  24753. if (privKey == NULL || outLen == 0) {
  24754. return BAD_FUNC_ARG;
  24755. }
  24756. #ifndef WOLFSSL_ASN_TEMPLATE
  24757. /* calculate size */
  24758. if (pubKey) {
  24759. pubSz = 2 + 2 + pubKeyLen;
  24760. }
  24761. privSz = 2 + 2 + privKeyLen;
  24762. algoSz = SetAlgoID(keyType, NULL, oidKeyType, 0);
  24763. verSz = 3; /* version is 3 bytes (enum + id + version(byte)) */
  24764. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, NULL);
  24765. sz = seqSz + verSz + algoSz + privSz + pubSz;
  24766. /* checkout output size */
  24767. if (output != NULL && sz > outLen) {
  24768. ret = BAD_FUNC_ARG;
  24769. }
  24770. if (ret == 0 && output != NULL) {
  24771. /* write out */
  24772. /* seq */
  24773. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, output);
  24774. idx = seqSz;
  24775. /* ver */
  24776. SetMyVersion(0, output + idx, FALSE);
  24777. idx += verSz;
  24778. /* algo */
  24779. algoSz = SetAlgoID(keyType, output + idx, oidKeyType, 0);
  24780. idx += algoSz;
  24781. /* privKey */
  24782. idx += SetOctetString(2 + privKeyLen, output + idx);
  24783. idx += SetOctetString(privKeyLen, output + idx);
  24784. XMEMCPY(output + idx, privKey, privKeyLen);
  24785. idx += privKeyLen;
  24786. /* pubKey */
  24787. if (pubKey) {
  24788. idx += SetExplicit(1, 2 + pubKeyLen, output + idx);
  24789. idx += SetOctetString(pubKeyLen, output + idx);
  24790. XMEMCPY(output + idx, pubKey, pubKeyLen);
  24791. idx += pubKeyLen;
  24792. }
  24793. ret = idx;
  24794. }
  24795. #else
  24796. CALLOC_ASNSETDATA(dataASN, edKeyASN_Length, ret, NULL);
  24797. if (ret == 0) {
  24798. /* Set version = 0 */
  24799. SetASN_Int8Bit(&dataASN[1], 0);
  24800. /* Set OID. */
  24801. SetASN_OID(&dataASN[3], keyType, oidKeyType);
  24802. /* Leave space for private key. */
  24803. SetASN_Buffer(&dataASN[5], NULL, privKeyLen);
  24804. /* Don't write out attributes. */
  24805. dataASN[6].noOut = 1;
  24806. if (pubKey) {
  24807. /* Leave space for public key. */
  24808. SetASN_Buffer(&dataASN[8], NULL, pubKeyLen);
  24809. }
  24810. else {
  24811. /* Don't put out public part. */
  24812. dataASN[7].noOut = dataASN[8].noOut = 1;
  24813. }
  24814. /* Calculate the size of encoding. */
  24815. ret = SizeASN_Items(edKeyASN, dataASN, edKeyASN_Length, &sz);
  24816. }
  24817. /* Check buffer is big enough. */
  24818. if ((ret == 0) && (output != NULL) && (sz > (int)outLen)) {
  24819. ret = BAD_FUNC_ARG;
  24820. }
  24821. if ((ret == 0) && (output != NULL)) {
  24822. /* Encode private key. */
  24823. SetASN_Items(edKeyASN, dataASN, edKeyASN_Length, output);
  24824. /* Put private value into space provided. */
  24825. XMEMCPY((byte*)dataASN[5].data.buffer.data, privKey, privKeyLen);
  24826. if (pubKey != NULL) {
  24827. /* Put public value into space provided. */
  24828. XMEMCPY((byte*)dataASN[8].data.buffer.data, pubKey, pubKeyLen);
  24829. }
  24830. /* Return size of encoding. */
  24831. ret = sz;
  24832. }
  24833. FREE_ASNSETDATA(dataASN, NULL);
  24834. #endif
  24835. return ret;
  24836. }
  24837. #endif /* WC_ENABLE_ASYM_KEY_EXPORT */
  24838. #if defined(HAVE_ED25519) && defined(HAVE_ED25519_KEY_EXPORT)
  24839. /* Write a Private ED25519 key, including public to DER format,
  24840. * length on success else < 0 */
  24841. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  24842. {
  24843. if (key == NULL) {
  24844. return BAD_FUNC_ARG;
  24845. }
  24846. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  24847. key->p, ED25519_PUB_KEY_SIZE, output, inLen, ED25519k);
  24848. }
  24849. /* Write only private ED25519 key to DER format,
  24850. * length on success else < 0 */
  24851. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  24852. {
  24853. if (key == NULL) {
  24854. return BAD_FUNC_ARG;
  24855. }
  24856. return SetAsymKeyDer(key->k, ED25519_KEY_SIZE,
  24857. NULL, 0, output, inLen, ED25519k);
  24858. }
  24859. #endif /* HAVE_ED25519 && HAVE_ED25519_KEY_EXPORT */
  24860. #if defined(HAVE_CURVE25519) && defined(HAVE_CURVE25519_KEY_EXPORT)
  24861. /* Write only private Curve25519 key to DER format,
  24862. * length on success else < 0 */
  24863. int wc_Curve25519PrivateKeyToDer(curve25519_key* key, byte* output, word32 inLen)
  24864. {
  24865. int ret;
  24866. byte privKey[CURVE25519_KEYSIZE];
  24867. word32 privKeyLen = CURVE25519_KEYSIZE;
  24868. if (key == NULL) {
  24869. return BAD_FUNC_ARG;
  24870. }
  24871. ret = wc_curve25519_export_private_raw(key, privKey, &privKeyLen);
  24872. if (ret == 0) {
  24873. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  24874. X25519k);
  24875. }
  24876. return ret;
  24877. }
  24878. /* Write a public Curve25519 key to DER format,
  24879. * length on success else < 0 */
  24880. int wc_Curve25519PublicKeyToDer(curve25519_key* key, byte* output, word32 inLen,
  24881. int withAlg)
  24882. {
  24883. int ret;
  24884. byte pubKey[CURVE25519_KEYSIZE];
  24885. word32 pubKeyLen = (word32)sizeof(pubKey);
  24886. if (key == NULL || output == NULL) {
  24887. return BAD_FUNC_ARG;
  24888. }
  24889. ret = wc_curve25519_export_public(key, pubKey, &pubKeyLen);
  24890. if (ret == 0) {
  24891. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  24892. X25519k, withAlg);
  24893. }
  24894. return ret;
  24895. }
  24896. #endif /* HAVE_CURVE25519 && HAVE_CURVE25519_KEY_EXPORT */
  24897. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_IMPORT)
  24898. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  24899. ed448_key* key, word32 inSz)
  24900. {
  24901. int ret;
  24902. byte privKey[ED448_KEY_SIZE], pubKey[ED448_PUB_KEY_SIZE];
  24903. word32 privKeyLen = (word32)sizeof(privKey);
  24904. word32 pubKeyLen = (word32)sizeof(pubKey);
  24905. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24906. return BAD_FUNC_ARG;
  24907. }
  24908. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  24909. pubKey, &pubKeyLen, ED448k);
  24910. if (ret == 0) {
  24911. if (pubKeyLen == 0) {
  24912. ret = wc_ed448_import_private_only(privKey, privKeyLen, key);
  24913. }
  24914. else {
  24915. ret = wc_ed448_import_private_key(privKey, privKeyLen,
  24916. pubKey, pubKeyLen, key);
  24917. }
  24918. }
  24919. return ret;
  24920. }
  24921. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  24922. ed448_key* key, word32 inSz)
  24923. {
  24924. int ret;
  24925. byte pubKey[ED448_PUB_KEY_SIZE];
  24926. word32 pubKeyLen = (word32)sizeof(pubKey);
  24927. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24928. return BAD_FUNC_ARG;
  24929. }
  24930. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  24931. pubKey, &pubKeyLen, ED448k);
  24932. if (ret == 0) {
  24933. ret = wc_ed448_import_public(pubKey, pubKeyLen, key);
  24934. }
  24935. return ret;
  24936. }
  24937. #endif /* HAVE_ED448 && HAVE_ED448_KEY_IMPORT */
  24938. #if defined(HAVE_LIBOQS)
  24939. int wc_Falcon_PrivateKeyDecode(const byte* input, word32* inOutIdx,
  24940. falcon_key* key, word32 inSz)
  24941. {
  24942. int ret = 0;
  24943. byte privKey[FALCON_MAX_KEY_SIZE], pubKey[FALCON_MAX_PUB_KEY_SIZE];
  24944. word32 privKeyLen = (word32)sizeof(privKey);
  24945. word32 pubKeyLen = (word32)sizeof(pubKey);
  24946. int keytype = 0;
  24947. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24948. return BAD_FUNC_ARG;
  24949. }
  24950. if (key->level == 1) {
  24951. keytype = FALCON_LEVEL1k;
  24952. }
  24953. else if (key->level == 5) {
  24954. keytype = FALCON_LEVEL5k;
  24955. }
  24956. else {
  24957. return BAD_FUNC_ARG;
  24958. }
  24959. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  24960. pubKey, &pubKeyLen, keytype);
  24961. if (ret == 0) {
  24962. if (pubKeyLen == 0) {
  24963. ret = wc_falcon_import_private_only(privKey, privKeyLen,
  24964. key);
  24965. }
  24966. else {
  24967. ret = wc_falcon_import_private_key(privKey, privKeyLen,
  24968. pubKey, pubKeyLen, key);
  24969. }
  24970. }
  24971. return ret;
  24972. }
  24973. int wc_Falcon_PublicKeyDecode(const byte* input, word32* inOutIdx,
  24974. falcon_key* key, word32 inSz)
  24975. {
  24976. int ret = 0;
  24977. byte pubKey[FALCON_MAX_PUB_KEY_SIZE];
  24978. word32 pubKeyLen = (word32)sizeof(pubKey);
  24979. int keytype = 0;
  24980. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  24981. return BAD_FUNC_ARG;
  24982. }
  24983. if (key->level == 1) {
  24984. keytype = FALCON_LEVEL1k;
  24985. }
  24986. else if (key->level == 5) {
  24987. keytype = FALCON_LEVEL5k;
  24988. }
  24989. else {
  24990. return BAD_FUNC_ARG;
  24991. }
  24992. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz, pubKey, &pubKeyLen,
  24993. keytype);
  24994. if (ret == 0) {
  24995. ret = wc_falcon_import_public(pubKey, pubKeyLen, key);
  24996. }
  24997. return ret;
  24998. }
  24999. #endif /* HAVE_LIBOQS */
  25000. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_IMPORT)
  25001. int wc_Curve448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  25002. curve448_key* key, word32 inSz)
  25003. {
  25004. int ret;
  25005. byte privKey[CURVE448_KEY_SIZE];
  25006. word32 privKeyLen = CURVE448_KEY_SIZE;
  25007. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  25008. return BAD_FUNC_ARG;
  25009. }
  25010. ret = DecodeAsymKey(input, inOutIdx, inSz, privKey, &privKeyLen,
  25011. NULL, NULL, X448k);
  25012. if (ret == 0) {
  25013. ret = wc_curve448_import_private(privKey, privKeyLen, key);
  25014. }
  25015. return ret;
  25016. }
  25017. int wc_Curve448PublicKeyDecode(const byte* input, word32* inOutIdx,
  25018. curve448_key* key, word32 inSz)
  25019. {
  25020. int ret;
  25021. byte pubKey[CURVE448_PUB_KEY_SIZE];
  25022. word32 pubKeyLen = (word32)sizeof(pubKey);
  25023. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0) {
  25024. return BAD_FUNC_ARG;
  25025. }
  25026. ret = DecodeAsymKeyPublic(input, inOutIdx, inSz,
  25027. pubKey, &pubKeyLen, X448k);
  25028. if (ret == 0) {
  25029. ret = wc_curve448_import_public(pubKey, pubKeyLen, key);
  25030. }
  25031. return ret;
  25032. }
  25033. #endif /* HAVE_CURVE448 && HAVE_ED448_KEY_IMPORT */
  25034. #if defined(HAVE_ED448) && defined(HAVE_ED448_KEY_EXPORT)
  25035. /* Write a Private ecc key, including public to DER format,
  25036. * length on success else < 0 */
  25037. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  25038. {
  25039. if (key == NULL) {
  25040. return BAD_FUNC_ARG;
  25041. }
  25042. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  25043. key->p, ED448_KEY_SIZE, output, inLen, ED448k);
  25044. }
  25045. /* Write only private ecc key to DER format,
  25046. * length on success else < 0 */
  25047. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  25048. {
  25049. if (key == NULL) {
  25050. return BAD_FUNC_ARG;
  25051. }
  25052. return SetAsymKeyDer(key->k, ED448_KEY_SIZE,
  25053. NULL, 0, output, inLen, ED448k);
  25054. }
  25055. #endif /* HAVE_ED448 && HAVE_ED448_KEY_EXPORT */
  25056. #if defined(HAVE_LIBOQS)
  25057. int wc_Falcon_KeyToDer(falcon_key* key, byte* output, word32 inLen)
  25058. {
  25059. if (key == NULL) {
  25060. return BAD_FUNC_ARG;
  25061. }
  25062. if (key->level == 1) {
  25063. return SetAsymKeyDer(key->k, FALCON_LEVEL1_KEY_SIZE, key->p,
  25064. FALCON_LEVEL1_KEY_SIZE, output, inLen,
  25065. FALCON_LEVEL1k);
  25066. }
  25067. else if (key->level == 5) {
  25068. return SetAsymKeyDer(key->k, FALCON_LEVEL5_KEY_SIZE, key->p,
  25069. FALCON_LEVEL5_KEY_SIZE, output, inLen,
  25070. FALCON_LEVEL5k);
  25071. }
  25072. return BAD_FUNC_ARG;
  25073. }
  25074. int wc_Falcon_PrivateKeyToDer(falcon_key* key, byte* output, word32 inLen)
  25075. {
  25076. if (key == NULL) {
  25077. return BAD_FUNC_ARG;
  25078. }
  25079. if (key->level == 1) {
  25080. return SetAsymKeyDer(key->k, FALCON_LEVEL1_KEY_SIZE, NULL, 0, output,
  25081. inLen, FALCON_LEVEL1k);
  25082. }
  25083. else if (key->level == 5) {
  25084. return SetAsymKeyDer(key->k, FALCON_LEVEL5_KEY_SIZE, NULL, 0, output,
  25085. inLen, FALCON_LEVEL5k);
  25086. }
  25087. return BAD_FUNC_ARG;
  25088. }
  25089. #endif /* HAVE_LIBOQS */
  25090. #if defined(HAVE_CURVE448) && defined(HAVE_CURVE448_KEY_EXPORT)
  25091. /* Write private Curve448 key to DER format,
  25092. * length on success else < 0 */
  25093. int wc_Curve448PrivateKeyToDer(curve448_key* key, byte* output, word32 inLen)
  25094. {
  25095. int ret;
  25096. byte privKey[CURVE448_KEY_SIZE];
  25097. word32 privKeyLen = CURVE448_KEY_SIZE;
  25098. if (key == NULL) {
  25099. return BAD_FUNC_ARG;
  25100. }
  25101. ret = wc_curve448_export_private_raw(key, privKey, &privKeyLen);
  25102. if (ret == 0) {
  25103. ret = SetAsymKeyDer(privKey, privKeyLen, NULL, 0, output, inLen,
  25104. X448k);
  25105. }
  25106. return ret;
  25107. }
  25108. /* Write a public Curve448 key to DER format,
  25109. * length on success else < 0 */
  25110. int wc_Curve448PublicKeyToDer(curve448_key* key, byte* output, word32 inLen,
  25111. int withAlg)
  25112. {
  25113. int ret;
  25114. byte pubKey[CURVE448_PUB_KEY_SIZE];
  25115. word32 pubKeyLen = (word32)sizeof(pubKey);
  25116. if (key == NULL || output == NULL) {
  25117. return BAD_FUNC_ARG;
  25118. }
  25119. ret = wc_curve448_export_public(key, pubKey, &pubKeyLen);
  25120. if (ret == 0) {
  25121. ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen,
  25122. X448k, withAlg);
  25123. }
  25124. return ret;
  25125. }
  25126. #endif /* HAVE_CURVE448 && HAVE_CURVE448_KEY_EXPORT */
  25127. #ifndef WOLFSSL_ASN_TEMPLATE
  25128. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  25129. /* Get raw Date only, no processing, 0 on success */
  25130. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  25131. byte* format, int maxIdx)
  25132. {
  25133. int ret, length;
  25134. const byte *datePtr = NULL;
  25135. WOLFSSL_ENTER("GetBasicDate");
  25136. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  25137. if (ret < 0)
  25138. return ret;
  25139. XMEMCPY(date, datePtr, length);
  25140. return 0;
  25141. }
  25142. #endif /* HAVE_OCSP || HAVE_CRL */
  25143. #endif /* WOLFSSL_ASN_TEMPLATE */
  25144. #ifdef HAVE_OCSP
  25145. #ifndef WOLFSSL_ASN_TEMPLATE
  25146. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  25147. int sz)
  25148. {
  25149. word32 idx = *inOutIdx;
  25150. word32 len;
  25151. byte tag;
  25152. WOLFSSL_ENTER("GetEnumerated");
  25153. *value = 0;
  25154. if (GetASNTag(input, &idx, &tag, sz) < 0)
  25155. return ASN_PARSE_E;
  25156. if (tag != ASN_ENUMERATED)
  25157. return ASN_PARSE_E;
  25158. if ((int)idx >= sz)
  25159. return BUFFER_E;
  25160. len = input[idx++];
  25161. if (len > 4 || (int)(len + idx) > sz)
  25162. return ASN_PARSE_E;
  25163. while (len--) {
  25164. *value = *value << 8 | input[idx++];
  25165. }
  25166. *inOutIdx = idx;
  25167. return *value;
  25168. }
  25169. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25170. #ifdef WOLFSSL_ASN_TEMPLATE
  25171. /* ASN.1 template for OCSP single response.
  25172. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  25173. */
  25174. static const ASNItem singleResponseASN[] = {
  25175. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25176. /* certId */
  25177. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25178. /* hashAlgorithm */
  25179. /* 2 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  25180. /* 3 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  25181. /* 4 */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  25182. /* issuerNameHash */
  25183. /* 5 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  25184. /* issuerKeyHash */
  25185. /* 6 */ { 2, ASN_OCTET_STRING, 0, 0, 0 },
  25186. /* serialNumber */
  25187. /* 7 */ { 2, ASN_INTEGER, 0, 0, 0 },
  25188. /* certStatus - CHOICE */
  25189. /* good [0] IMPLICIT NULL */
  25190. /* 8 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 0, 0, 2 },
  25191. /* revoked [1] IMPLICIT RevokedInfo */
  25192. /* 9 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 2 },
  25193. /* revocationTime */
  25194. /* 10 */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  25195. /* revocationReason [0] EXPLICIT CRLReason OPTIONAL */
  25196. /* 11 */ { 2, ASN_CONTEXT_SPECIFIC | 0, 0, 1, 1 },
  25197. /* crlReason */
  25198. /* 12 */ { 3, ASN_ENUMERATED, 0, 0, 0 },
  25199. /* unknown [2] IMPLICIT UnknownInfo ::= NULL */
  25200. /* 13 */ { 1, ASN_CONTEXT_SPECIFIC | 2, 0, 0, 2 },
  25201. /* thisUpdate */
  25202. /* 14 */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0 },
  25203. /* nextUpdate */
  25204. /* 15 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  25205. /* 16 */ { 2, ASN_GENERALIZED_TIME, 0, 0, 0 },
  25206. /* singleExtensions */
  25207. /* 17 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 },
  25208. };
  25209. /* Number of items in ASN.1 template for OCSP single response. */
  25210. #define singleResponseASN_Length (sizeof(singleResponseASN) / sizeof(ASNItem))
  25211. #endif
  25212. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  25213. int wrapperSz, OcspEntry* single)
  25214. {
  25215. #ifndef WOLFSSL_ASN_TEMPLATE
  25216. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  25217. int length;
  25218. int ret;
  25219. byte tag;
  25220. WOLFSSL_ENTER("DecodeSingleResponse");
  25221. prevIndex = idx;
  25222. /* Wrapper around the Single Response */
  25223. if (GetSequence(source, &idx, &length, size) < 0)
  25224. return ASN_PARSE_E;
  25225. /* Wrapper around the CertID */
  25226. certIdIdx = idx;
  25227. if (GetSequence(source, &idx, &length, size) < 0)
  25228. return ASN_PARSE_E;
  25229. single->rawCertId = source + certIdIdx;
  25230. /* Hash algorithm */
  25231. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  25232. if (ret < 0)
  25233. return ret;
  25234. single->hashAlgoOID = oid;
  25235. /* Save reference to the hash of CN */
  25236. ret = GetOctetString(source, &idx, &length, size);
  25237. if (ret < 0)
  25238. return ret;
  25239. if (length > (int)sizeof(single->issuerHash))
  25240. return BUFFER_E;
  25241. XMEMCPY(single->issuerHash, source + idx, length);
  25242. idx += length;
  25243. /* Save reference to the hash of the issuer public key */
  25244. ret = GetOctetString(source, &idx, &length, size);
  25245. if (ret < 0)
  25246. return ret;
  25247. if (length > (int)sizeof(single->issuerKeyHash))
  25248. return BUFFER_E;
  25249. XMEMCPY(single->issuerKeyHash, source + idx, length);
  25250. idx += length;
  25251. /* Get serial number */
  25252. if (GetSerialNumber(source, &idx, single->status->serial, &single->status->serialSz, size) < 0)
  25253. return ASN_PARSE_E;
  25254. single->rawCertIdSize = idx - certIdIdx;
  25255. if (idx >= size)
  25256. return BUFFER_E;
  25257. /* CertStatus */
  25258. switch (source[idx++])
  25259. {
  25260. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  25261. single->status->status = CERT_GOOD;
  25262. idx++;
  25263. break;
  25264. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  25265. single->status->status = CERT_REVOKED;
  25266. if (GetLength(source, &idx, &length, size) < 0)
  25267. return ASN_PARSE_E;
  25268. idx += length;
  25269. break;
  25270. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  25271. single->status->status = CERT_UNKNOWN;
  25272. idx++;
  25273. break;
  25274. default:
  25275. return ASN_PARSE_E;
  25276. }
  25277. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  25278. single->status->thisDateAsn = source + idx;
  25279. localIdx = 0;
  25280. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  25281. (byte*)&single->status->thisDateParsed.type,
  25282. &single->status->thisDateParsed.length, size) < 0)
  25283. return ASN_PARSE_E;
  25284. XMEMCPY(single->status->thisDateParsed.data,
  25285. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  25286. single->status->thisDateParsed.length);
  25287. #endif
  25288. if (GetBasicDate(source, &idx, single->status->thisDate,
  25289. &single->status->thisDateFormat, size) < 0)
  25290. return ASN_PARSE_E;
  25291. #ifndef NO_ASN_TIME
  25292. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  25293. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  25294. return ASN_BEFORE_DATE_E;
  25295. #endif
  25296. #endif
  25297. /* The following items are optional. Only check for them if there is more
  25298. * unprocessed data in the singleResponse wrapper. */
  25299. localIdx = idx;
  25300. if (((int)(idx - prevIndex) < wrapperSz) &&
  25301. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  25302. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  25303. {
  25304. idx++;
  25305. if (GetLength(source, &idx, &length, size) < 0)
  25306. return ASN_PARSE_E;
  25307. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  25308. single->status->nextDateAsn = source + idx;
  25309. localIdx = 0;
  25310. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  25311. (byte*)&single->status->nextDateParsed.type,
  25312. &single->status->nextDateParsed.length, size) < 0)
  25313. return ASN_PARSE_E;
  25314. XMEMCPY(single->status->nextDateParsed.data,
  25315. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  25316. single->status->nextDateParsed.length);
  25317. #endif
  25318. if (GetBasicDate(source, &idx, single->status->nextDate,
  25319. &single->status->nextDateFormat, size) < 0)
  25320. return ASN_PARSE_E;
  25321. #ifndef NO_ASN_TIME
  25322. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  25323. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  25324. return ASN_AFTER_DATE_E;
  25325. #endif
  25326. #endif
  25327. }
  25328. /* Skip the optional extensions in singleResponse. */
  25329. localIdx = idx;
  25330. if (((int)(idx - prevIndex) < wrapperSz) &&
  25331. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  25332. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  25333. {
  25334. idx++;
  25335. if (GetLength(source, &idx, &length, size) < 0)
  25336. return ASN_PARSE_E;
  25337. idx += length;
  25338. }
  25339. *ioIndex = idx;
  25340. return 0;
  25341. #else
  25342. DECL_ASNGETDATA(dataASN, singleResponseASN_Length);
  25343. int ret = 0;
  25344. CertStatus* cs = NULL;
  25345. word32 serialSz;
  25346. word32 issuerHashLen;
  25347. word32 issuerKeyHashLen;
  25348. word32 thisDateLen;
  25349. word32 nextDateLen;
  25350. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  25351. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  25352. WOLFSSL_ASN1_TIME *at;
  25353. #endif
  25354. (void)wrapperSz;
  25355. WOLFSSL_ENTER("DecodeSingleResponse");
  25356. CALLOC_ASNGETDATA(dataASN, singleResponseASN_Length, ret, NULL);
  25357. if (ret == 0) {
  25358. /* Certificate Status field. */
  25359. cs = single->status;
  25360. /* Set maximum lengths for data. */
  25361. issuerHashLen = OCSP_DIGEST_SIZE;
  25362. issuerKeyHashLen = OCSP_DIGEST_SIZE;
  25363. serialSz = EXTERNAL_SERIAL_SIZE;
  25364. thisDateLen = MAX_DATE_SIZE;
  25365. nextDateLen = MAX_DATE_SIZE;
  25366. /* Set OID type, buffers to hold data and variables to hold size. */
  25367. GetASN_OID(&dataASN[3], oidHashType);
  25368. GetASN_Buffer(&dataASN[5], single->issuerHash, &issuerHashLen);
  25369. GetASN_Buffer(&dataASN[6], single->issuerKeyHash, &issuerKeyHashLen);
  25370. GetASN_Buffer(&dataASN[7], cs->serial, &serialSz);
  25371. GetASN_Buffer(&dataASN[14], cs->thisDate, &thisDateLen);
  25372. GetASN_Buffer(&dataASN[16], cs->nextDate, &nextDateLen);
  25373. /* TODO: decode revoked time and reason. */
  25374. /* Decode OCSP single response. */
  25375. ret = GetASN_Items(singleResponseASN, dataASN, singleResponseASN_Length,
  25376. 1, source, ioIndex, size);
  25377. }
  25378. /* Validate the issuer hash length is the size required. */
  25379. if ((ret == 0) && (issuerHashLen != OCSP_DIGEST_SIZE)) {
  25380. ret = ASN_PARSE_E;
  25381. }
  25382. /* Validate the issuer key hash length is the size required. */
  25383. if ((ret == 0) && (issuerKeyHashLen != OCSP_DIGEST_SIZE)) {
  25384. ret = ASN_PARSE_E;
  25385. }
  25386. if (ret == 0) {
  25387. /* Store serial size. */
  25388. cs->serialSz = serialSz;
  25389. /* Determine status by which item was found. */
  25390. if (dataASN[8].tag != 0) {
  25391. cs->status = CERT_GOOD;
  25392. }
  25393. if (dataASN[9].tag != 0) {
  25394. cs->status = CERT_REVOKED;
  25395. }
  25396. if (dataASN[13].tag != 0) {
  25397. cs->status = CERT_UNKNOWN;
  25398. }
  25399. /* Store the thisDate format - only one possible. */
  25400. cs->thisDateFormat = ASN_GENERALIZED_TIME;
  25401. #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  25402. /* Check date is a valid string and BEFORE now. */
  25403. if (!XVALIDATE_DATE(cs->thisDate, ASN_GENERALIZED_TIME, BEFORE)) {
  25404. ret = ASN_BEFORE_DATE_E;
  25405. }
  25406. }
  25407. if (ret == 0) {
  25408. #endif
  25409. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  25410. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  25411. /* Store ASN.1 version of thisDate. */
  25412. cs->thisDateAsn = GetASNItem_Addr(dataASN[14], source);
  25413. at = &cs->thisDateParsed;
  25414. at->type = ASN_GENERALIZED_TIME;
  25415. XMEMCPY(at->data, cs->thisDate, thisDateLen);
  25416. at->length = thisDateLen;
  25417. #endif
  25418. }
  25419. if ((ret == 0) && (dataASN[16].tag != 0)) {
  25420. /* Store the nextDate format - only one possible. */
  25421. cs->nextDateFormat = ASN_GENERALIZED_TIME;
  25422. #if !defined(NO_ASN_TIME) && !defined(WOLFSSL_NO_OCSP_DATE_CHECK)
  25423. /* Check date is a valid string and AFTER now. */
  25424. if (!XVALIDATE_DATE(cs->nextDate, ASN_GENERALIZED_TIME, AFTER)) {
  25425. ret = ASN_AFTER_DATE_E;
  25426. }
  25427. }
  25428. if ((ret == 0) && (dataASN[16].tag != 0)) {
  25429. #endif
  25430. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || \
  25431. defined(WOLFSSL_HAPROXY) || defined(HAVE_LIGHTY)
  25432. /* Store ASN.1 version of thisDate. */
  25433. cs->nextDateAsn = GetASNItem_Addr(dataASN[16], source);
  25434. at = &cs->nextDateParsed;
  25435. at->type = ASN_GENERALIZED_TIME;
  25436. XMEMCPY(at->data, cs->nextDate, nextDateLen);
  25437. at->length = nextDateLen;
  25438. #endif
  25439. }
  25440. if (ret == 0) {
  25441. /* OcspEntry now used. */
  25442. single->used = 1;
  25443. }
  25444. FREE_ASNGETDATA(dataASN, NULL);
  25445. return ret;
  25446. #endif
  25447. }
  25448. #ifdef WOLFSSL_ASN_TEMPLATE
  25449. /* ASN.1 template for OCSP response extension header.
  25450. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  25451. */
  25452. static const ASNItem respExtHdrASN[] = {
  25453. /* responseExtensions */
  25454. /* 0 */ { 0, ASN_CONTEXT_SPECIFIC | 1, 1, 1, 0 },
  25455. /* extensions */
  25456. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  25457. };
  25458. /* Number of items in ASN.1 template for OCSP response extension header. */
  25459. #define respExtHdrASN_Length (sizeof(respExtHdrASN) / sizeof(ASNItem))
  25460. #endif
  25461. static int DecodeOcspRespExtensions(byte* source, word32* ioIndex,
  25462. OcspResponse* resp, word32 sz)
  25463. {
  25464. #ifndef WOLFSSL_ASN_TEMPLATE
  25465. word32 idx = *ioIndex;
  25466. int length;
  25467. int ext_bound; /* boundary index for the sequence of extensions */
  25468. word32 oid;
  25469. int ret;
  25470. byte tag;
  25471. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  25472. if ((idx + 1) > sz)
  25473. return BUFFER_E;
  25474. if (GetASNTag(source, &idx, &tag, sz) < 0)
  25475. return ASN_PARSE_E;
  25476. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  25477. return ASN_PARSE_E;
  25478. if (GetLength(source, &idx, &length, sz) < 0)
  25479. return ASN_PARSE_E;
  25480. if (GetSequence(source, &idx, &length, sz) < 0)
  25481. return ASN_PARSE_E;
  25482. ext_bound = idx + length;
  25483. while (idx < (word32)ext_bound) {
  25484. word32 localIdx;
  25485. if (GetSequence(source, &idx, &length, sz) < 0) {
  25486. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  25487. return ASN_PARSE_E;
  25488. }
  25489. oid = 0;
  25490. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  25491. WOLFSSL_MSG("\tfail: OBJECT ID");
  25492. return ASN_PARSE_E;
  25493. }
  25494. /* check for critical flag */
  25495. if ((idx + 1) > (word32)sz) {
  25496. WOLFSSL_MSG("\tfail: malformed buffer");
  25497. return BUFFER_E;
  25498. }
  25499. localIdx = idx;
  25500. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  25501. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  25502. ret = GetBoolean(source, &idx, sz);
  25503. if (ret < 0)
  25504. return ret;
  25505. }
  25506. ret = GetOctetString(source, &idx, &length, sz);
  25507. if (ret < 0)
  25508. return ret;
  25509. if (oid == OCSP_NONCE_OID) {
  25510. /* get data inside extra OCTET_STRING */
  25511. ret = GetOctetString(source, &idx, &length, sz);
  25512. if (ret < 0)
  25513. return ret;
  25514. resp->nonce = source + idx;
  25515. resp->nonceSz = length;
  25516. }
  25517. idx += length;
  25518. }
  25519. *ioIndex = idx;
  25520. return 0;
  25521. #else
  25522. /* certExtASN_Length is greater than respExtHdrASN_Length */
  25523. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  25524. int ret = 0;
  25525. word32 idx = *ioIndex;
  25526. word32 maxIdx = 0;
  25527. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  25528. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, resp->heap);
  25529. /* Check for header and move past. */
  25530. XMEMSET(dataASN, 0, sizeof(*dataASN) * respExtHdrASN_Length);
  25531. ret = GetASN_Items(respExtHdrASN, dataASN, respExtHdrASN_Length, 0,
  25532. source, &idx, sz);
  25533. if (ret == 0) {
  25534. /* Keep end extensions index for total length check. */
  25535. maxIdx = idx + dataASN[1].length;
  25536. }
  25537. /* Step through all extensions. */
  25538. while ((ret == 0) && (idx < maxIdx)) {
  25539. /* Clear dynamic data, set OID type to expect. */
  25540. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  25541. GetASN_OID(&dataASN[1], oidOcspType);
  25542. /* TODO: check criticality. */
  25543. /* Decode OCSP response extension. */
  25544. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0,
  25545. source, &idx, sz);
  25546. if (ret == 0) {
  25547. word32 oid = dataASN[1].data.oid.sum;
  25548. int length = dataASN[3].length;
  25549. if (oid == OCSP_NONCE_OID) {
  25550. /* Extract nonce data. */
  25551. ret = GetOctetString(source, &idx, &length, sz);
  25552. if (ret >= 0) {
  25553. ret = 0;
  25554. /* get data inside extra OCTET_STRING */
  25555. resp->nonce = source + idx;
  25556. resp->nonceSz = length;
  25557. }
  25558. }
  25559. /* Ignore all other extension types. */
  25560. /* Skip over rest of extension. */
  25561. idx += length;
  25562. }
  25563. }
  25564. /* Return index after extensions. */
  25565. *ioIndex = idx;
  25566. FREE_ASNGETDATA(dataASN, resp->heap);
  25567. return ret;
  25568. #endif
  25569. }
  25570. #ifdef WOLFSSL_ASN_TEMPLATE
  25571. /* ASN.1 template for OCSP ResponseData.
  25572. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  25573. */
  25574. static const ASNItem ocspRespDataASN[] = {
  25575. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25576. /* version DEFAULT v1 */
  25577. /* 1 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  25578. /* 2 */ { 2, ASN_INTEGER, 1, 0, 0 },
  25579. /* byName */
  25580. /* 3 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 2 },
  25581. /* byKey */
  25582. /* 4 */ { 1, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 2 },
  25583. /* producedAt */
  25584. /* 5 */ { 1, ASN_GENERALIZED_TIME, 0, 0, 0, },
  25585. /* responses */
  25586. /* 6 */ { 1, ASN_SEQUENCE, 1, 0, 0 },
  25587. /* responseExtensions */
  25588. /* 7 */ { 1, ASN_CONTEXT_SPECIFIC | 1, 1, 0, 1 }
  25589. };
  25590. /* Number of items in ASN.1 template for OCSP ResponseData. */
  25591. #define ocspRespDataASN_Length (sizeof(ocspRespDataASN) / sizeof(ASNItem))
  25592. #endif
  25593. static int DecodeResponseData(byte* source, word32* ioIndex,
  25594. OcspResponse* resp, word32 size)
  25595. {
  25596. #ifndef WOLFSSL_ASN_TEMPLATE
  25597. word32 idx = *ioIndex, prev_idx, localIdx;
  25598. int length;
  25599. int version;
  25600. int ret;
  25601. byte tag;
  25602. int wrapperSz;
  25603. OcspEntry* single;
  25604. WOLFSSL_ENTER("DecodeResponseData");
  25605. resp->response = source + idx;
  25606. prev_idx = idx;
  25607. if (GetSequence(source, &idx, &length, size) < 0)
  25608. return ASN_PARSE_E;
  25609. resp->responseSz = length + idx - prev_idx;
  25610. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  25611. * item isn't an EXPLICIT[0], then set version to zero and move
  25612. * onto the next item.
  25613. */
  25614. localIdx = idx;
  25615. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  25616. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  25617. {
  25618. idx += 2; /* Eat the value and length */
  25619. if (GetMyVersion(source, &idx, &version, size) < 0)
  25620. return ASN_PARSE_E;
  25621. } else
  25622. version = 0;
  25623. localIdx = idx;
  25624. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  25625. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  25626. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  25627. {
  25628. idx++; /* advance past ASN tag */
  25629. if (GetLength(source, &idx, &length, size) < 0)
  25630. return ASN_PARSE_E;
  25631. idx += length;
  25632. }
  25633. else
  25634. return ASN_PARSE_E;
  25635. /* save pointer to the producedAt time */
  25636. if (GetBasicDate(source, &idx, resp->producedDate,
  25637. &resp->producedDateFormat, size) < 0)
  25638. return ASN_PARSE_E;
  25639. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  25640. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  25641. return ASN_PARSE_E;
  25642. localIdx = idx;
  25643. single = resp->single;
  25644. while (idx - localIdx < (word32)wrapperSz) {
  25645. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  25646. if (ret < 0)
  25647. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  25648. if (idx - localIdx < (word32)wrapperSz) {
  25649. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  25650. DYNAMIC_TYPE_OCSP_ENTRY);
  25651. if (single->next == NULL) {
  25652. return MEMORY_E;
  25653. }
  25654. XMEMSET(single->next, 0, sizeof(OcspEntry));
  25655. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  25656. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  25657. if (single->next->status == NULL) {
  25658. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  25659. single->next = NULL;
  25660. return MEMORY_E;
  25661. }
  25662. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  25663. single->next->isDynamic = 1;
  25664. single = single->next;
  25665. }
  25666. }
  25667. /*
  25668. * Check the length of the ResponseData against the current index to
  25669. * see if there are extensions, they are optional.
  25670. */
  25671. if (idx - prev_idx < resp->responseSz)
  25672. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  25673. return ASN_PARSE_E;
  25674. *ioIndex = idx;
  25675. return 0;
  25676. #else
  25677. DECL_ASNGETDATA(dataASN, ocspRespDataASN_Length);
  25678. int ret = 0;
  25679. byte version;
  25680. word32 dateSz, idx = *ioIndex;
  25681. OcspEntry* single;
  25682. WOLFSSL_ENTER("DecodeResponseData");
  25683. CALLOC_ASNGETDATA(dataASN, ocspRespDataASN_Length, ret, resp->heap);
  25684. if (ret == 0) {
  25685. resp->response = source + idx;
  25686. /* Default, not present, is v1 = 0. */
  25687. version = 0;
  25688. /* Max size of date supported. */
  25689. dateSz = MAX_DATE_SIZE;
  25690. /* Set the where to put version an produced date. */
  25691. GetASN_Int8Bit(&dataASN[2], &version);
  25692. GetASN_Buffer(&dataASN[5], resp->producedDate, &dateSz);
  25693. /* Decode the ResponseData. */
  25694. ret = GetASN_Items(ocspRespDataASN, dataASN, ocspRespDataASN_Length,
  25695. 1, source, ioIndex, size);
  25696. }
  25697. /* Only support v1 == 0 */
  25698. if ((ret == 0) && (version != 0)) {
  25699. ret = ASN_PARSE_E;
  25700. }
  25701. /* Ensure date is a minimal size. */
  25702. if ((ret == 0) && (dateSz < MIN_DATE_SIZE)) {
  25703. ret = ASN_PARSE_E;
  25704. }
  25705. if (ret == 0) {
  25706. /* TODO: use byName/byKey fields. */
  25707. /* Store size of response. */
  25708. resp->responseSz = *ioIndex - idx;
  25709. /* Store date format/tag. */
  25710. resp->producedDateFormat = dataASN[5].tag;
  25711. /* Get the index of the responses SEQUENCE. */
  25712. idx = GetASNItem_DataIdx(dataASN[6], source);
  25713. /* Start with the pre-existing OcspEntry. */
  25714. single = resp->single;
  25715. }
  25716. while ((ret == 0) && (idx < dataASN[7].offset)) {
  25717. /* Allocate and use a new OCSP entry if this is used. */
  25718. if (single->used) {
  25719. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  25720. DYNAMIC_TYPE_OCSP_ENTRY);
  25721. if (single->next == NULL) {
  25722. ret = MEMORY_E;
  25723. }
  25724. else {
  25725. XMEMSET(single->next, 0, sizeof(OcspEntry));
  25726. single->next->status = (CertStatus*)XMALLOC(sizeof(CertStatus),
  25727. resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  25728. if (single->next->status == NULL) {
  25729. XFREE(single->next, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  25730. single->next = NULL;
  25731. ret = MEMORY_E;
  25732. }
  25733. else {
  25734. XMEMSET(single->next->status, 0, sizeof(CertStatus));
  25735. /* Entry to be freed. */
  25736. single->isDynamic = 1;
  25737. /* used will be 0 (false) */
  25738. single = single->next;
  25739. }
  25740. }
  25741. }
  25742. if (ret == 0) {
  25743. /* Decode SingleResponse into OcspEntry. */
  25744. ret = DecodeSingleResponse(source, &idx, dataASN[7].offset,
  25745. dataASN[6].length, single);
  25746. /* single->used set on successful decode. */
  25747. }
  25748. }
  25749. /* Check if there were extensions. */
  25750. if ((ret == 0) && (dataASN[7].data.buffer.data != NULL)) {
  25751. /* Get index of [1] */
  25752. idx = dataASN[7].offset;
  25753. /* Decode the response extensions. */
  25754. if (DecodeOcspRespExtensions(source, &idx, resp, *ioIndex) < 0) {
  25755. ret = ASN_PARSE_E;
  25756. }
  25757. }
  25758. FREE_ASNGETDATA(dataASN, resp->heap);
  25759. return ret;
  25760. #endif
  25761. }
  25762. #ifndef WOLFSSL_ASN_TEMPLATE
  25763. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  25764. static int DecodeCerts(byte* source,
  25765. word32* ioIndex, OcspResponse* resp, word32 size)
  25766. {
  25767. word32 idx = *ioIndex;
  25768. byte tag;
  25769. WOLFSSL_ENTER("DecodeCerts");
  25770. if (GetASNTag(source, &idx, &tag, size) < 0)
  25771. return ASN_PARSE_E;
  25772. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  25773. {
  25774. int length;
  25775. if (GetLength(source, &idx, &length, size) < 0)
  25776. return ASN_PARSE_E;
  25777. if (GetSequence(source, &idx, &length, size) < 0)
  25778. return ASN_PARSE_E;
  25779. resp->cert = source + idx;
  25780. resp->certSz = length;
  25781. idx += length;
  25782. }
  25783. *ioIndex = idx;
  25784. return 0;
  25785. }
  25786. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  25787. #endif /* !WOLFSSL_ASN_TEMPLATE */
  25788. #ifdef WOLFSSL_ASN_TEMPLATE
  25789. /* ASN.1 template for BasicOCSPResponse.
  25790. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  25791. */
  25792. static const ASNItem ocspBasicRespASN[] = {
  25793. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  25794. /* tbsResponseData */
  25795. /* 1 */ { 1, ASN_SEQUENCE, 1, 0, 0, },
  25796. /* signatureAlgorithm */
  25797. /* 2 */ { 1, ASN_SEQUENCE, 1, 1, 0, },
  25798. /* 3 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  25799. /* 4 */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  25800. /* signature */
  25801. /* 5 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  25802. /* certs */
  25803. /* 6 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  25804. /* 7 */ { 2, ASN_SEQUENCE, 1, 0, 0, },
  25805. };
  25806. /* Number of items in ASN.1 template for BasicOCSPResponse. */
  25807. #define ocspBasicRespASN_Length (sizeof(ocspBasicRespASN) / sizeof(ASNItem))
  25808. #endif /* WOLFSSL_ASN_TEMPLATE */
  25809. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  25810. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  25811. {
  25812. #ifndef WOLFSSL_ASN_TEMPLATE
  25813. int length;
  25814. word32 idx = *ioIndex;
  25815. word32 end_index;
  25816. int ret;
  25817. int sigLength;
  25818. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  25819. (void)heap;
  25820. if (GetSequence(source, &idx, &length, size) < 0)
  25821. return ASN_PARSE_E;
  25822. if (idx + length > size)
  25823. return ASN_INPUT_E;
  25824. end_index = idx + length;
  25825. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  25826. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  25827. /* Get the signature algorithm */
  25828. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0)
  25829. return ASN_PARSE_E;
  25830. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  25831. if (ret != 0)
  25832. return ret;
  25833. resp->sigSz = sigLength;
  25834. resp->sig = source + idx;
  25835. idx += sigLength;
  25836. /*
  25837. * Check the length of the BasicOcspResponse against the current index to
  25838. * see if there are certificates, they are optional.
  25839. */
  25840. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  25841. if (idx < end_index)
  25842. {
  25843. DecodedCert cert;
  25844. if (DecodeCerts(source, &idx, resp, size) < 0)
  25845. return ASN_PARSE_E;
  25846. InitDecodedCert(&cert, resp->cert, resp->certSz, heap);
  25847. /* Don't verify if we don't have access to Cert Manager. */
  25848. ret = ParseCertRelative(&cert, CERT_TYPE,
  25849. noVerify ? NO_VERIFY : VERIFY_OCSP_CERT, cm);
  25850. if (ret < 0) {
  25851. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  25852. FreeDecodedCert(&cert);
  25853. return ret;
  25854. }
  25855. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  25856. if ((cert.extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  25857. if (XMEMCMP(cert.subjectHash,
  25858. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  25859. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  25860. }
  25861. else {
  25862. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  25863. #ifdef OPENSSL_EXTRA
  25864. resp->verifyError = OCSP_BAD_ISSUER;
  25865. #else
  25866. FreeDecodedCert(&cert);
  25867. return BAD_OCSP_RESPONDER;
  25868. #endif
  25869. }
  25870. }
  25871. #endif
  25872. /* ConfirmSignature is blocking here */
  25873. ret = ConfirmSignature(&cert.sigCtx,
  25874. resp->response, resp->responseSz,
  25875. cert.publicKey, cert.pubKeySize, cert.keyOID,
  25876. resp->sig, resp->sigSz, resp->sigOID, NULL);
  25877. FreeDecodedCert(&cert);
  25878. if (ret != 0) {
  25879. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  25880. return ASN_OCSP_CONFIRM_E;
  25881. }
  25882. }
  25883. else
  25884. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  25885. {
  25886. Signer* ca;
  25887. int sigValid = -1;
  25888. #ifndef NO_SKID
  25889. ca = GetCA(cm, resp->single->issuerKeyHash);
  25890. #else
  25891. ca = GetCA(cm, resp->single->issuerHash);
  25892. #endif
  25893. if (ca) {
  25894. SignatureCtx sigCtx;
  25895. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  25896. /* ConfirmSignature is blocking here */
  25897. sigValid = ConfirmSignature(&sigCtx, resp->response,
  25898. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  25899. resp->sig, resp->sigSz, resp->sigOID, NULL);
  25900. }
  25901. if (ca == NULL || sigValid != 0) {
  25902. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  25903. return ASN_OCSP_CONFIRM_E;
  25904. }
  25905. (void)noVerify;
  25906. }
  25907. *ioIndex = idx;
  25908. return 0;
  25909. #else
  25910. DECL_ASNGETDATA(dataASN, ocspBasicRespASN_Length);
  25911. int ret = 0;
  25912. word32 idx = *ioIndex;
  25913. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  25914. #ifdef WOLFSSL_SMALL_STACK
  25915. DecodedCert* cert = NULL;
  25916. #else
  25917. DecodedCert cert[1];
  25918. #endif
  25919. int certInit = 0;
  25920. #endif
  25921. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  25922. (void)heap;
  25923. CALLOC_ASNGETDATA(dataASN, ocspBasicRespASN_Length, ret, heap);
  25924. if (ret == 0) {
  25925. /* Set expecting signature OID. */
  25926. GetASN_OID(&dataASN[3], oidSigType);
  25927. /* Decode BasicOCSPResponse. */
  25928. ret = GetASN_Items(ocspBasicRespASN, dataASN, ocspBasicRespASN_Length,
  25929. 1, source, &idx, size);
  25930. }
  25931. if (ret == 0) {
  25932. word32 dataIdx = 0;
  25933. /* Decode the response data. */
  25934. if (DecodeResponseData(GetASNItem_Addr(dataASN[1], source), &dataIdx,
  25935. resp, GetASNItem_Length(dataASN[1], source)) < 0) {
  25936. ret = ASN_PARSE_E;
  25937. }
  25938. }
  25939. if (ret == 0) {
  25940. /* Get the signature OID and signature. */
  25941. resp->sigOID = dataASN[3].data.oid.sum;
  25942. GetASN_GetRef(&dataASN[5], &resp->sig, &resp->sigSz);
  25943. }
  25944. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  25945. if ((ret == 0) && (dataASN[7].data.ref.data != NULL)) {
  25946. /* TODO: support more than one certificate. */
  25947. /* Store reference to certificate BER data. */
  25948. GetASN_GetRef(&dataASN[7], &resp->cert, &resp->certSz);
  25949. /* Allocate a certificate object to decode cert into. */
  25950. #ifdef WOLFSSL_SMALL_STACK
  25951. cert = (DecodedCert*)XMALLOC(sizeof(DecodedCert), heap,
  25952. DYNAMIC_TYPE_TMP_BUFFER);
  25953. if (cert == NULL) {
  25954. ret = MEMORY_E;
  25955. }
  25956. }
  25957. if ((ret == 0) && (dataASN[7].data.ref.data != NULL)) {
  25958. #endif
  25959. /* Initialize the crtificate object. */
  25960. InitDecodedCert(cert, resp->cert, resp->certSz, heap);
  25961. certInit = 1;
  25962. /* Parse the certificate and don't verify if we don't have access to
  25963. * Cert Manager. */
  25964. ret = ParseCertRelative(cert, CERT_TYPE, noVerify ? NO_VERIFY : VERIFY,
  25965. cm);
  25966. if (ret < 0) {
  25967. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  25968. }
  25969. }
  25970. if ((ret == 0) && (dataASN[7].data.ref.data != NULL)) {
  25971. /* TODO: ConfirmSignature is blocking here */
  25972. /* Check the signature of the response. */
  25973. ret = ConfirmSignature(&cert->sigCtx, resp->response, resp->responseSz,
  25974. cert->publicKey, cert->pubKeySize, cert->keyOID, resp->sig,
  25975. resp->sigSz, resp->sigOID, NULL);
  25976. if (ret != 0) {
  25977. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  25978. ret = ASN_OCSP_CONFIRM_E;
  25979. }
  25980. }
  25981. if ((ret == 0) && (dataASN[7].data.ref.data == NULL))
  25982. #else
  25983. if (ret == 0)
  25984. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  25985. {
  25986. Signer* ca;
  25987. int sigValid = -1;
  25988. /* Resonse didn't have a certificate - lookup CA. */
  25989. #ifndef NO_SKID
  25990. ca = GetCA(cm, resp->single->issuerKeyHash);
  25991. #else
  25992. ca = GetCA(cm, resp->single->issuerHash);
  25993. #endif
  25994. if (ca) {
  25995. SignatureCtx sigCtx;
  25996. /* Initialize he signature context. */
  25997. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  25998. /* TODO: ConfirmSignature is blocking here */
  25999. /* Check the signature of the response CA public key. */
  26000. sigValid = ConfirmSignature(&sigCtx, resp->response,
  26001. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  26002. resp->sig, resp->sigSz, resp->sigOID, NULL);
  26003. }
  26004. if ((ca == NULL) || (sigValid != 0)) {
  26005. /* Didn't find certificate or signature verificate failed. */
  26006. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  26007. ret = ASN_OCSP_CONFIRM_E;
  26008. }
  26009. }
  26010. if (ret == 0) {
  26011. /* Update the position to after response data. */
  26012. *ioIndex = idx;
  26013. }
  26014. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  26015. if (certInit) {
  26016. FreeDecodedCert(cert);
  26017. }
  26018. #ifdef WOLFSSL_SMALL_STACK
  26019. if (cert != NULL) {
  26020. /* Dispose of certificate object. */
  26021. XFREE(cert, heap, DYNAMIC_TYPE_TMP_BUFFER);
  26022. }
  26023. #endif
  26024. #endif
  26025. FREE_ASNGETDATA(dataASN, heap);
  26026. return ret;
  26027. #endif /* WOLFSSL_ASN_TEMPLATE */
  26028. }
  26029. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  26030. byte* source, word32 inSz, void* heap)
  26031. {
  26032. WOLFSSL_ENTER("InitOcspResponse");
  26033. XMEMSET(status, 0, sizeof(CertStatus));
  26034. XMEMSET(single, 0, sizeof(OcspEntry));
  26035. XMEMSET(resp, 0, sizeof(OcspResponse));
  26036. single->status = status;
  26037. resp->responseStatus = -1;
  26038. resp->single = single;
  26039. resp->source = source;
  26040. resp->maxIdx = inSz;
  26041. resp->heap = heap;
  26042. }
  26043. void FreeOcspResponse(OcspResponse* resp)
  26044. {
  26045. OcspEntry *single, *next;
  26046. for (single = resp->single; single; single = next) {
  26047. next = single->next;
  26048. if (single->isDynamic) {
  26049. XFREE(single->status, resp->heap, DYNAMIC_TYPE_OCSP_STATUS);
  26050. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  26051. }
  26052. }
  26053. }
  26054. #ifdef WOLFSSL_ASN_TEMPLATE
  26055. /* ASN.1 template for OCSPResponse.
  26056. * RFC 6960, 4.2.1 - ASN.1 Specification of the OCSP Response
  26057. */
  26058. static const ASNItem ocspResponseASN[] = {
  26059. /* OCSPResponse ::= SEQUENCE */
  26060. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26061. /* responseStatus OCSPResponseStatus */
  26062. /* 1 */ { 1, ASN_ENUMERATED, 0, 0, 0, },
  26063. /* responseBytes [0] EXPLICIT ResponseBytes OPTIONAL */
  26064. /* 2 */ { 1, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  26065. /* ResponseBytes ::= SEQUENCE */
  26066. /* 3 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  26067. /* responseType OBJECT IDENTIFIER */
  26068. /* 4 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  26069. /* response OCTET STRING */
  26070. /* 5 */ { 3, ASN_OCTET_STRING, 0, 0, 0 },
  26071. };
  26072. /* Number of items in ASN.1 template for OCSPResponse. */
  26073. #define ocspResponseASN_Length (sizeof(ocspResponseASN) / sizeof(ASNItem))
  26074. #endif /* WOLFSSL_ASN_TEMPLATE */
  26075. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  26076. {
  26077. #ifndef WOLFSSL_ASN_TEMPLATE
  26078. int ret;
  26079. int length = 0;
  26080. word32 idx = 0;
  26081. byte* source = resp->source;
  26082. word32 size = resp->maxIdx;
  26083. word32 oid;
  26084. byte tag;
  26085. WOLFSSL_ENTER("OcspResponseDecode");
  26086. /* peel the outer SEQUENCE wrapper */
  26087. if (GetSequence(source, &idx, &length, size) < 0)
  26088. return ASN_PARSE_E;
  26089. /* First get the responseStatus, an ENUMERATED */
  26090. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0)
  26091. return ASN_PARSE_E;
  26092. if (resp->responseStatus != OCSP_SUCCESSFUL)
  26093. return 0;
  26094. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  26095. if (idx >= size)
  26096. return ASN_INPUT_E;
  26097. if (GetASNTag(source, &idx, &tag, size) < 0)
  26098. return ASN_PARSE_E;
  26099. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  26100. return ASN_PARSE_E;
  26101. if (GetLength(source, &idx, &length, size) < 0)
  26102. return ASN_PARSE_E;
  26103. /* Get the responseBytes SEQUENCE */
  26104. if (GetSequence(source, &idx, &length, size) < 0)
  26105. return ASN_PARSE_E;
  26106. /* Check ObjectID for the resposeBytes */
  26107. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0)
  26108. return ASN_PARSE_E;
  26109. if (oid != OCSP_BASIC_OID)
  26110. return ASN_PARSE_E;
  26111. ret = GetOctetString(source, &idx, &length, size);
  26112. if (ret < 0)
  26113. return ret;
  26114. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  26115. if (ret < 0)
  26116. return ret;
  26117. return 0;
  26118. #else
  26119. DECL_ASNGETDATA(dataASN, ocspResponseASN_Length);
  26120. int ret = 0;
  26121. word32 idx = 0, size = resp->maxIdx;
  26122. byte* source = resp->source;
  26123. byte status;
  26124. byte* basic;
  26125. word32 basicSz;
  26126. WOLFSSL_ENTER("OcspResponseDecode");
  26127. CALLOC_ASNGETDATA(dataASN, ocspResponseASN_Length, ret, resp->heap);
  26128. if (ret == 0) {
  26129. /* Set variable to put status in and expect OCSP OID. */
  26130. GetASN_Int8Bit(&dataASN[1], &status);
  26131. GetASN_OID(&dataASN[4], oidOcspType);
  26132. /* Decode OCSPResponse (and ResponseBytes). */
  26133. ret = GetASN_Items(ocspResponseASN, dataASN, ocspResponseASN_Length, 1,
  26134. source, &idx, size);
  26135. }
  26136. if (ret == 0) {
  26137. /* Get response. */
  26138. resp->responseStatus = status;
  26139. if (dataASN[4].data.oid.sum == OCSP_BASIC_OID) {
  26140. /* Get reference to BasicOCSPResponse. */
  26141. GetASN_GetRef(&dataASN[5], &basic, &basicSz);
  26142. idx = 0;
  26143. /* Decode BasicOCSPResponse. */
  26144. ret = DecodeBasicOcspResponse(basic, &idx, resp, basicSz, cm, heap,
  26145. noVerify);
  26146. }
  26147. /* Only support BasicOCSPResponse. */
  26148. else {
  26149. ret = ASN_PARSE_E;
  26150. }
  26151. }
  26152. FREE_ASNGETDATA(dataASN, resp->heap);
  26153. return ret;
  26154. #endif /* WOLFSSL_ASN_TEMPLATE */
  26155. }
  26156. #ifdef WOLFSSL_ASN_TEMPLATE
  26157. /* ASN.1 template for OCSP nonce extension.
  26158. * RFC 6960, 4.4.1 - Nonce
  26159. * X.509: RFC 5280, 4.1 - Basic Certificate Fields. (Extension)
  26160. */
  26161. static const ASNItem ocspNonceExtASN[] = {
  26162. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26163. /* Extension */
  26164. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  26165. /* extnId */
  26166. /* 2 */ {2, ASN_OBJECT_ID, 0, 0, 0 },
  26167. /* critcal not encoded. */
  26168. /* extnValue */
  26169. /* 3 */ {2, ASN_OCTET_STRING, 0, 1, 0 },
  26170. /* nonce */
  26171. /* 4 */ {3, ASN_OCTET_STRING, 0, 0, 0 },
  26172. };
  26173. /* Number of items in ASN.1 template for OCSP nonce extension. */
  26174. #define ocspNonceExtASN_Length (sizeof(ocspNonceExtASN) / sizeof(ASNItem))
  26175. #endif /* WOLFSSL_ASN_TEMPLATE */
  26176. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  26177. {
  26178. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  26179. 0x30, 0x01, 0x02 };
  26180. #ifndef WOLFSSL_ASN_TEMPLATE
  26181. byte seqArray[5][MAX_SEQ_SZ];
  26182. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  26183. WOLFSSL_ENTER("SetOcspReqExtensions");
  26184. if (!req || !output || !req->nonceSz)
  26185. return 0;
  26186. totalSz += req->nonceSz;
  26187. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  26188. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  26189. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  26190. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  26191. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  26192. if (totalSz > size)
  26193. return 0;
  26194. totalSz = 0;
  26195. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  26196. totalSz += seqSz[4];
  26197. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  26198. totalSz += seqSz[3];
  26199. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  26200. totalSz += seqSz[2];
  26201. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  26202. totalSz += (word32)sizeof(NonceObjId);
  26203. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  26204. totalSz += seqSz[1];
  26205. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  26206. totalSz += seqSz[0];
  26207. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  26208. totalSz += req->nonceSz;
  26209. return totalSz;
  26210. #else
  26211. int ret = 0;
  26212. WOLFSSL_ENTER("SetOcspReqExtensions");
  26213. /* Check request has nonce to write in extension. */
  26214. if (req != NULL && req->nonceSz != 0) {
  26215. DECL_ASNSETDATA(dataASN, ocspNonceExtASN_Length);
  26216. int sz;
  26217. CALLOC_ASNSETDATA(dataASN, ocspNonceExtASN_Length, ret, req->heap);
  26218. /* Set nonce extension OID and nonce. */
  26219. SetASN_Buffer(&dataASN[2], NonceObjId, sizeof(NonceObjId));
  26220. SetASN_Buffer(&dataASN[4], req->nonce, req->nonceSz);
  26221. /* Calculate size of nonce extension. */
  26222. ret = SizeASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  26223. &sz);
  26224. /* Check buffer big enough for encoding if supplied. */
  26225. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  26226. ret = BUFFER_E;
  26227. }
  26228. if ((ret == 0) && (output != NULL)) {
  26229. /* Encode nonce extension. */
  26230. SetASN_Items(ocspNonceExtASN, dataASN, ocspNonceExtASN_Length,
  26231. output);
  26232. }
  26233. if (ret == 0) {
  26234. /* Return size of encoding. */
  26235. ret = sz;
  26236. }
  26237. FREE_ASNSETDATA(dataASN, req->heap);
  26238. }
  26239. return ret;
  26240. #endif /* WOLFSSL_ASN_TEMPLATE */
  26241. }
  26242. #ifdef WOLFSSL_ASN_TEMPLATE
  26243. /* ASN.1 template for OCSPRequest.
  26244. * RFC 6960, 4.1.1 - ASN.1 Specification of the OCSP Request
  26245. */
  26246. static const ASNItem ocspRequestASN[] = {
  26247. /* OCSPRequest */
  26248. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26249. /* tbsRequest */
  26250. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  26251. /* version not written - v1 */
  26252. /* requestorName not written */
  26253. /* requestList */
  26254. /* 2 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  26255. /* Request */
  26256. /* 3 */ { 3, ASN_SEQUENCE, 1, 1, 0 },
  26257. /* reqCert */
  26258. /* 4 */ { 4, ASN_SEQUENCE, 1, 1, 0 },
  26259. /* hashAlgorithm */
  26260. /* 5 */ { 5, ASN_SEQUENCE, 1, 1, 0 },
  26261. /* 6 */ { 6, ASN_OBJECT_ID, 0, 0, 0 },
  26262. /* issuerNameHash */
  26263. /* 7 */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  26264. /* issuerKeyHash */
  26265. /* 8 */ { 5, ASN_OCTET_STRING, 0, 0, 0 },
  26266. /* serialNumber */
  26267. /* 9 */ { 5, ASN_INTEGER, 0, 0, 0 },
  26268. /* requestExtensions */
  26269. /* 10 */ { 2, ASN_CONTEXT_SPECIFIC | 2, 1, 0, 0 },
  26270. /* optionalSignature not written. */
  26271. };
  26272. /* Number of items in ASN.1 template for OCSPRequest. */
  26273. #define ocspRequestASN_Length (sizeof(ocspRequestASN) / sizeof(ASNItem))
  26274. #endif
  26275. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  26276. {
  26277. #ifndef WOLFSSL_ASN_TEMPLATE
  26278. byte seqArray[5][MAX_SEQ_SZ];
  26279. /* The ASN.1 of the OCSP Request is an onion of sequences */
  26280. byte algoArray[MAX_ALGO_SZ];
  26281. byte issuerArray[MAX_ENCODED_DIG_SZ];
  26282. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  26283. byte snArray[MAX_SN_SZ];
  26284. byte extArray[MAX_OCSP_EXT_SZ];
  26285. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  26286. int i, snSz;
  26287. WOLFSSL_ENTER("EncodeOcspRequest");
  26288. #ifdef NO_SHA
  26289. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  26290. #else
  26291. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  26292. #endif
  26293. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  26294. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  26295. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  26296. MAX_SN_SZ, MAX_SN_SZ);
  26297. extSz = 0;
  26298. if (snSz < 0)
  26299. return snSz;
  26300. if (req->nonceSz) {
  26301. /* TLS Extensions use this function too - put extensions after
  26302. * ASN.1: Context Specific [2].
  26303. */
  26304. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  26305. OCSP_NONCE_EXT_SZ);
  26306. extSz += SetExplicit(2, extSz, extArray);
  26307. }
  26308. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  26309. for (i = 4; i >= 0; i--) {
  26310. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  26311. totalSz += seqSz[i];
  26312. if (i == 2) totalSz += extSz;
  26313. }
  26314. if (output == NULL)
  26315. return totalSz;
  26316. if (totalSz > size)
  26317. return BUFFER_E;
  26318. totalSz = 0;
  26319. for (i = 0; i < 5; i++) {
  26320. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  26321. totalSz += seqSz[i];
  26322. }
  26323. XMEMCPY(output + totalSz, algoArray, algoSz);
  26324. totalSz += algoSz;
  26325. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  26326. totalSz += issuerSz;
  26327. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  26328. totalSz += issuerKeySz;
  26329. XMEMCPY(output + totalSz, snArray, snSz);
  26330. totalSz += snSz;
  26331. if (extSz != 0) {
  26332. XMEMCPY(output + totalSz, extArray, extSz);
  26333. totalSz += extSz;
  26334. }
  26335. return totalSz;
  26336. #else
  26337. DECL_ASNSETDATA(dataASN, ocspRequestASN_Length);
  26338. word32 extSz = 0;
  26339. int sz;
  26340. int ret = 0;
  26341. WOLFSSL_ENTER("EncodeOcspRequest");
  26342. CALLOC_ASNSETDATA(dataASN, ocspRequestASN_Length, ret, req->heap);
  26343. if (ret == 0) {
  26344. /* Set OID of hash algorithm use on issuer and key. */
  26345. #ifdef NO_SHA
  26346. SetASN_OID(&dataASN[6], SHA256h, oidHashType);
  26347. #else
  26348. SetASN_OID(&dataASN[6], SHAh, oidHashType);
  26349. #endif
  26350. /* Set issuer, issuer key hash and serial number of certificate being
  26351. * checked. */
  26352. SetASN_Buffer(&dataASN[7], req->issuerHash, KEYID_SIZE);
  26353. SetASN_Buffer(&dataASN[8], req->issuerKeyHash, KEYID_SIZE);
  26354. SetASN_Buffer(&dataASN[9], req->serial, req->serialSz);
  26355. /* Only extension to write is nonce - check if one to encode. */
  26356. if (req->nonceSz) {
  26357. /* Get size of extensions and leave space for them in encoding. */
  26358. ret = extSz = EncodeOcspRequestExtensions(req, NULL, 0);
  26359. SetASN_Buffer(&dataASN[10], NULL, extSz);
  26360. if (ret > 0) {
  26361. ret = 0;
  26362. }
  26363. }
  26364. else {
  26365. /* Don't write out extensions. */
  26366. dataASN[10].noOut = 1;
  26367. }
  26368. }
  26369. if (ret == 0) {
  26370. /* Calculate size of encoding. */
  26371. ret = SizeASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length,
  26372. &sz);
  26373. }
  26374. /* Check buffer big enough for encoding if supplied. */
  26375. if ((ret == 0) && (output != NULL) && (sz > (int)size)) {
  26376. ret = BUFFER_E;
  26377. }
  26378. if ((ret == 0) && (output != NULL)) {
  26379. /* Encode OCSPRequest. */
  26380. SetASN_Items(ocspRequestASN, dataASN, ocspRequestASN_Length, output);
  26381. if (req->nonceSz) {
  26382. /* Encode extensions into space provided. */
  26383. ret = EncodeOcspRequestExtensions(req,
  26384. (byte*)dataASN[10].data.buffer.data, extSz);
  26385. if (ret > 0) {
  26386. ret = 0;
  26387. }
  26388. }
  26389. }
  26390. if (ret == 0) {
  26391. /* Return size of encoding. */
  26392. ret = sz;
  26393. }
  26394. FREE_ASNSETDATA(dataASN, req->heap);
  26395. return ret;
  26396. #endif /* WOLFSSL_ASN_TEMPLATE */
  26397. }
  26398. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  26399. void* heap)
  26400. {
  26401. int ret;
  26402. WOLFSSL_ENTER("InitOcspRequest");
  26403. if (req == NULL)
  26404. return BAD_FUNC_ARG;
  26405. ForceZero(req, sizeof(OcspRequest));
  26406. req->heap = heap;
  26407. if (cert) {
  26408. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  26409. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  26410. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  26411. DYNAMIC_TYPE_OCSP_REQUEST);
  26412. if (req->serial == NULL)
  26413. return MEMORY_E;
  26414. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  26415. req->serialSz = cert->serialSz;
  26416. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  26417. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  26418. DYNAMIC_TYPE_OCSP_REQUEST);
  26419. if (req->url == NULL) {
  26420. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  26421. return MEMORY_E;
  26422. }
  26423. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  26424. req->urlSz = cert->extAuthInfoSz;
  26425. req->url[req->urlSz] = 0;
  26426. }
  26427. }
  26428. if (useNonce) {
  26429. WC_RNG rng;
  26430. #ifndef HAVE_FIPS
  26431. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  26432. #else
  26433. ret = wc_InitRng(&rng);
  26434. #endif
  26435. if (ret != 0) {
  26436. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
  26437. } else {
  26438. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  26439. WOLFSSL_MSG("\tCannot run RNG. Skipping the OSCP Nonce.");
  26440. else
  26441. req->nonceSz = MAX_OCSP_NONCE_SZ;
  26442. wc_FreeRng(&rng);
  26443. }
  26444. }
  26445. return 0;
  26446. }
  26447. void FreeOcspRequest(OcspRequest* req)
  26448. {
  26449. WOLFSSL_ENTER("FreeOcspRequest");
  26450. if (req) {
  26451. if (req->serial)
  26452. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  26453. req->serial = NULL;
  26454. #ifdef OPENSSL_EXTRA
  26455. if (req->serialInt) {
  26456. if (req->serialInt->isDynamic) {
  26457. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  26458. }
  26459. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  26460. }
  26461. req->serialInt = NULL;
  26462. #endif
  26463. if (req->url)
  26464. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  26465. req->url = NULL;
  26466. }
  26467. }
  26468. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  26469. {
  26470. int cmp = -1; /* default as not matching, cmp gets set on each check */
  26471. OcspEntry *single, *next, *prev = NULL, *top;
  26472. WOLFSSL_ENTER("CompareOcspReqResp");
  26473. if (req == NULL) {
  26474. WOLFSSL_MSG("\tReq missing");
  26475. return -1;
  26476. }
  26477. if (resp == NULL || resp->single == NULL) {
  26478. WOLFSSL_MSG("\tResp missing");
  26479. return 1;
  26480. }
  26481. /* Nonces are not critical. The responder may not necessarily add
  26482. * the nonce to the response. */
  26483. if (req->nonceSz && resp->nonce != NULL
  26484. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  26485. && resp->nonceSz != 0
  26486. #endif
  26487. ) {
  26488. cmp = req->nonceSz - resp->nonceSz;
  26489. if (cmp != 0) {
  26490. WOLFSSL_MSG("\tnonceSz mismatch");
  26491. return cmp;
  26492. }
  26493. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  26494. if (cmp != 0) {
  26495. WOLFSSL_MSG("\tnonce mismatch");
  26496. return cmp;
  26497. }
  26498. }
  26499. /* match based on found status and return */
  26500. for (single = resp->single; single; single = next) {
  26501. cmp = req->serialSz - single->status->serialSz;
  26502. if (cmp == 0) {
  26503. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  26504. || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
  26505. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
  26506. if (cmp == 0) {
  26507. /* match found */
  26508. if (resp->single != single && prev) {
  26509. /* move to top of list */
  26510. top = resp->single;
  26511. resp->single = single;
  26512. prev->next = single->next;
  26513. single->next = top;
  26514. }
  26515. break;
  26516. }
  26517. }
  26518. next = single->next;
  26519. prev = single;
  26520. }
  26521. if (cmp != 0) {
  26522. WOLFSSL_MSG("\trequest and response mismatch");
  26523. return cmp;
  26524. }
  26525. return 0;
  26526. }
  26527. #endif /* HAVE_OCSP */
  26528. #ifdef WOLFSSL_ASN_TEMPLATE
  26529. /* ASN.1 template for certificate name hash. */
  26530. static const ASNItem nameHashASN[] = {
  26531. /* 0 */ { 0, ASN_OBJECT_ID, 0, 0, 1 },
  26532. /* 1 */ { 0, ASN_SEQUENCE, 1, 0, 0 },
  26533. };
  26534. /* Number of items in ASN.1 template for certificate name hash. */
  26535. #define nameHashASN_Length (sizeof(nameHashASN) / sizeof(ASNItem))
  26536. #endif /* WOLFSSL_ASN_TEMPLATE */
  26537. /* store WC_SHA hash of NAME */
  26538. int GetNameHash(const byte* source, word32* idx, byte* hash, int maxIdx)
  26539. {
  26540. #ifndef WOLFSSL_ASN_TEMPLATE
  26541. int length; /* length of all distinguished names */
  26542. int ret;
  26543. word32 dummy;
  26544. byte tag;
  26545. WOLFSSL_ENTER("GetNameHash");
  26546. dummy = *idx;
  26547. if (GetASNTag(source, &dummy, &tag, maxIdx) == 0 && tag == ASN_OBJECT_ID) {
  26548. WOLFSSL_MSG("Trying optional prefix...");
  26549. if (GetLength(source, idx, &length, maxIdx) < 0)
  26550. return ASN_PARSE_E;
  26551. *idx += length;
  26552. WOLFSSL_MSG("Got optional prefix");
  26553. }
  26554. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  26555. * calculated over the entire DER encoding of the Name field, including
  26556. * the tag and length. */
  26557. dummy = *idx;
  26558. if (GetSequence(source, idx, &length, maxIdx) < 0)
  26559. return ASN_PARSE_E;
  26560. ret = CalcHashId(source + dummy, length + *idx - dummy, hash);
  26561. *idx += length;
  26562. return ret;
  26563. #else
  26564. ASNGetData dataASN[nameHashASN_Length];
  26565. int ret;
  26566. XMEMSET(dataASN, 0, sizeof(dataASN));
  26567. /* Ignore the OID even when present. */
  26568. GetASN_OID(&dataASN[0], oidIgnoreType);
  26569. /* Decode certificate name. */
  26570. ret = GetASN_Items(nameHashASN, dataASN, nameHashASN_Length, 0, source, idx,
  26571. maxIdx);
  26572. if (ret == 0) {
  26573. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  26574. * calculated over the entire DER encoding of the Name field, including
  26575. * the tag and length. */
  26576. /* Calculate hash of complete name including SEQUENCE. */
  26577. ret = CalcHashId(GetASNItem_Addr(dataASN[1], source),
  26578. GetASNItem_Length(dataASN[1], source), hash);
  26579. }
  26580. return ret;
  26581. #endif /* WOLFSSL_ASN_TEMPLATE */
  26582. }
  26583. #ifdef HAVE_CRL
  26584. /* initialize decoded CRL */
  26585. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  26586. {
  26587. WOLFSSL_MSG("InitDecodedCRL");
  26588. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  26589. dcrl->heap = heap;
  26590. #ifdef WOLFSSL_HEAP_TEST
  26591. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  26592. #endif
  26593. }
  26594. /* free decoded CRL resources */
  26595. void FreeDecodedCRL(DecodedCRL* dcrl)
  26596. {
  26597. RevokedCert* tmp = dcrl->certs;
  26598. WOLFSSL_MSG("FreeDecodedCRL");
  26599. while(tmp) {
  26600. RevokedCert* next = tmp->next;
  26601. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  26602. tmp = next;
  26603. }
  26604. }
  26605. #ifdef WOLFSSL_ASN_TEMPLATE
  26606. /* ASN.1 template for revoked certificates.
  26607. * X.509: RFC 5280, 5.1 - CRL Fields
  26608. */
  26609. static const ASNItem revokedASN[] = {
  26610. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  26611. /* userCertificate CertificateSerialNumber */
  26612. /* 1 */ { 1, ASN_INTEGER, 0, 0, 0 },
  26613. /* revocationDate Time */
  26614. /* 2 */ { 1, ASN_UTC_TIME, 0, 0, 2 },
  26615. /* 3 */ { 1, ASN_GENERALIZED_TIME, 0, 0, 2 },
  26616. /* crlEntryExensions Extensions */
  26617. /* 4 */ { 1, ASN_SEQUENCE, 1, 0, 1 },
  26618. };
  26619. /* Number of items in ASN.1 template for revoked certificates. */
  26620. #define revokedASN_Length (sizeof(revokedASN) / sizeof(ASNItem))
  26621. #endif
  26622. /* Get Revoked Cert list, 0 on success */
  26623. static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
  26624. int maxIdx)
  26625. {
  26626. #ifndef WOLFSSL_ASN_TEMPLATE
  26627. int ret, len;
  26628. word32 end;
  26629. byte b;
  26630. RevokedCert* rc;
  26631. WOLFSSL_ENTER("GetRevoked");
  26632. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  26633. return ASN_PARSE_E;
  26634. end = *idx + len;
  26635. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  26636. DYNAMIC_TYPE_REVOKED);
  26637. if (rc == NULL) {
  26638. WOLFSSL_MSG("Alloc Revoked Cert failed");
  26639. return MEMORY_E;
  26640. }
  26641. if (GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,
  26642. maxIdx) < 0) {
  26643. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  26644. return ASN_PARSE_E;
  26645. }
  26646. /* add to list */
  26647. rc->next = dcrl->certs;
  26648. dcrl->certs = rc;
  26649. dcrl->totalCerts++;
  26650. /* get date */
  26651. ret = GetDateInfo(buff, idx, NULL, &b, NULL, maxIdx);
  26652. if (ret < 0) {
  26653. WOLFSSL_MSG("Expecting Date");
  26654. return ret;
  26655. }
  26656. /* skip extensions */
  26657. *idx = end;
  26658. return 0;
  26659. #else
  26660. DECL_ASNGETDATA(dataASN, revokedASN_Length);
  26661. int ret = 0;
  26662. word32 serialSz = EXTERNAL_SERIAL_SIZE;
  26663. RevokedCert* rc;
  26664. /* Allocate a new revoked certificate object. */
  26665. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  26666. DYNAMIC_TYPE_CRL);
  26667. if (rc == NULL) {
  26668. ret = MEMORY_E;
  26669. }
  26670. CALLOC_ASNGETDATA(dataASN, revokedASN_Length, ret, dcrl->heap);
  26671. if (ret == 0) {
  26672. /* Set buffer to place serial number into. */
  26673. GetASN_Buffer(&dataASN[1], rc->serialNumber, &serialSz);
  26674. /* Decode the Revoked */
  26675. ret = GetASN_Items(revokedASN, dataASN, revokedASN_Length, 1, buff, idx,
  26676. maxIdx);
  26677. }
  26678. if (ret == 0) {
  26679. /* Store size of serial number. */
  26680. rc->serialSz = serialSz;
  26681. /* TODO: use revocation date */
  26682. /* TODO: use extensions, only v2 */
  26683. /* Add revoked certificate to chain. */
  26684. rc->next = dcrl->certs;
  26685. dcrl->certs = rc;
  26686. dcrl->totalCerts++;
  26687. }
  26688. FREE_ASNGETDATA(dataASN, dcrl->heap);
  26689. if ((ret != 0) && (rc != NULL)) {
  26690. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_CRL);
  26691. }
  26692. return ret;
  26693. #endif /* WOLFSSL_ASN_TEMPLATE */
  26694. }
  26695. #ifdef WOLFSSL_ASN_TEMPLATE
  26696. /* Parse the revoked certificates of a CRL.
  26697. *
  26698. * @param [in] dcrl Decoded CRL object.
  26699. * @param [in] buff Buffer holding CRL.
  26700. * @param [in] idx Index into buffer of revoked certificates.
  26701. * @param [in] maxIdx Maximum index of revoked cartificates data.
  26702. * @return 0 on success.
  26703. * @return ASN_PARSE_E on failure.
  26704. */
  26705. static int ParseCRL_RevokedCerts(DecodedCRL* dcrl, const byte* buff, word32 idx,
  26706. word32 maxIdx)
  26707. {
  26708. int ret = 0;
  26709. /* Parse each revoked cerificate. */
  26710. while ((ret == 0) && (idx < maxIdx)) {
  26711. /* Parse a revoked certificate. */
  26712. if (GetRevoked(buff, &idx, dcrl, maxIdx) < 0) {
  26713. ret = ASN_PARSE_E;
  26714. }
  26715. }
  26716. return ret;
  26717. }
  26718. #endif /* WOLFSSL_ASN_TEMPLATE */
  26719. #ifndef WOLFSSL_ASN_TEMPLATE
  26720. /* Get CRL Signature, 0 on success */
  26721. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  26722. int maxIdx)
  26723. {
  26724. int length;
  26725. int ret;
  26726. WOLFSSL_ENTER("GetCRL_Signature");
  26727. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  26728. if (ret != 0)
  26729. return ret;
  26730. dcrl->sigLength = length;
  26731. dcrl->signature = (byte*)&source[*idx];
  26732. *idx += dcrl->sigLength;
  26733. return 0;
  26734. }
  26735. #endif /* !WOLFSSL_ASN_TEMPLATE */
  26736. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  26737. word32 tbsSz, const byte* signature, word32 sigSz,
  26738. word32 signatureOID, Signer *ca, void* heap)
  26739. {
  26740. /* try to confirm/verify signature */
  26741. #ifndef IGNORE_KEY_EXTENSIONS
  26742. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  26743. WOLFSSL_MSG("CA cannot sign CRLs");
  26744. return ASN_CRL_NO_SIGNER_E;
  26745. }
  26746. #endif /* IGNORE_KEY_EXTENSIONS */
  26747. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  26748. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  26749. ca->pubKeySize, ca->keyOID, signature, sigSz,
  26750. signatureOID, NULL) != 0) {
  26751. WOLFSSL_MSG("CRL Confirm signature failed");
  26752. return ASN_CRL_CONFIRM_E;
  26753. }
  26754. return 0;
  26755. }
  26756. #ifdef WOLFSSL_ASN_TEMPLATE
  26757. /* Find the signer for the CRL and verify the signature.
  26758. *
  26759. * @param [in] dcrl Decoded CRL object.
  26760. * @param [in] buff Buffer holding CRL.
  26761. * @param [in] cm Certificate manager object.
  26762. * @return 0 on success.
  26763. * @return ASN_CRL_NO_SIGNER_E when no signer found.
  26764. * @return ASN_CRL_CONFIRM_E when signature did not verify.
  26765. */
  26766. static int PaseCRL_CheckSignature(DecodedCRL* dcrl, const byte* buff, void* cm)
  26767. {
  26768. int ret = 0;
  26769. Signer* ca = NULL;
  26770. SignatureCtx sigCtx;
  26771. /* OpenSSL doesn't add skid by default for CRLs cause firefox chokes.
  26772. * If experiencing issues uncomment NO_SKID define in CRL section of
  26773. * wolfssl/wolfcrypt/settings.h */
  26774. #ifndef NO_SKID
  26775. if (dcrl->extAuthKeyIdSet) {
  26776. /* more unique than issuerHash */
  26777. ca = GetCA(cm, dcrl->extAuthKeyId);
  26778. }
  26779. /* Check issuerHash matched CA's subjectNameHash. */
  26780. if ((ca != NULL) && (XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  26781. KEYID_SIZE) != 0)) {
  26782. ca = NULL;
  26783. }
  26784. if (ca == NULL) {
  26785. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  26786. /* If AKID is available then this CA doesn't have the public
  26787. * key required */
  26788. if (ca && dcrl->extAuthKeyIdSet) {
  26789. WOLFSSL_MSG("CA SKID doesn't match AKID");
  26790. ca = NULL;
  26791. }
  26792. }
  26793. #else
  26794. ca = GetCA(cm, dcrl->issuerHash);
  26795. #endif /* !NO_SKID */
  26796. WOLFSSL_MSG("About to verify CRL signature");
  26797. if (ca == NULL) {
  26798. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  26799. ret = ASN_CRL_NO_SIGNER_E;
  26800. }
  26801. if (ret == 0) {
  26802. WOLFSSL_MSG("Found CRL issuer CA");
  26803. /* Verify CRL signature with CA. */
  26804. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  26805. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  26806. dcrl->signatureOID, ca, dcrl->heap);
  26807. }
  26808. return ret;
  26809. }
  26810. #endif
  26811. #ifndef WOLFSSL_ASN_TEMPLATE
  26812. static int ParseCRL_CertList(DecodedCRL* dcrl, const byte* buf,
  26813. word32* inOutIdx, int sz)
  26814. {
  26815. word32 oid, dateIdx, idx, checkIdx;
  26816. int version;
  26817. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  26818. int doNextDate = 1;
  26819. #endif
  26820. byte tag;
  26821. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  26822. return BAD_FUNC_ARG;
  26823. }
  26824. /* may have version */
  26825. idx = *inOutIdx;
  26826. checkIdx = idx;
  26827. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  26828. if (GetMyVersion(buf, &idx, &version, sz) < 0)
  26829. return ASN_PARSE_E;
  26830. }
  26831. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  26832. return ASN_PARSE_E;
  26833. if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
  26834. return ASN_PARSE_E;
  26835. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  26836. return ASN_PARSE_E;
  26837. dateIdx = idx;
  26838. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  26839. {
  26840. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  26841. (void)dateIdx;
  26842. return ASN_PARSE_E;
  26843. #else
  26844. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  26845. doNextDate = 0;
  26846. idx = dateIdx;
  26847. #endif
  26848. }
  26849. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  26850. if (doNextDate)
  26851. #endif
  26852. {
  26853. #ifndef NO_ASN_TIME
  26854. if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  26855. WOLFSSL_MSG("CRL after date is no longer valid");
  26856. return CRL_CERT_DATE_ERR;
  26857. }
  26858. #endif
  26859. }
  26860. checkIdx = idx;
  26861. if (idx != dcrl->sigIndex &&
  26862. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  26863. int len;
  26864. if (GetSequence(buf, &idx, &len, sz) < 0)
  26865. return ASN_PARSE_E;
  26866. len += idx;
  26867. while (idx < (word32)len) {
  26868. if (GetRevoked(buf, &idx, dcrl, len) < 0)
  26869. return ASN_PARSE_E;
  26870. }
  26871. }
  26872. *inOutIdx = idx;
  26873. return 0;
  26874. }
  26875. #endif /* !WOLFSSL_ASN_TEMPLATE */
  26876. #ifndef NO_SKID
  26877. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  26878. {
  26879. #ifndef WOLFSSL_ASN_TEMPLATE
  26880. word32 idx = 0;
  26881. int length = 0, ret = 0;
  26882. byte tag;
  26883. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  26884. if (GetSequence(input, &idx, &length, sz) < 0) {
  26885. WOLFSSL_MSG("\tfail: should be a SEQUENCE\n");
  26886. return ASN_PARSE_E;
  26887. }
  26888. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  26889. return ASN_PARSE_E;
  26890. }
  26891. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  26892. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
  26893. return 0;
  26894. }
  26895. if (GetLength(input, &idx, &length, sz) <= 0) {
  26896. WOLFSSL_MSG("\tfail: extension data length");
  26897. return ASN_PARSE_E;
  26898. }
  26899. dcrl->extAuthKeyIdSet = 1;
  26900. /* Get the hash or hash of the hash if wrong size. */
  26901. ret = GetHashId(input + idx, length, dcrl->extAuthKeyId);
  26902. return ret;
  26903. #else
  26904. DECL_ASNGETDATA(dataASN, authKeyIdASN_Length);
  26905. int ret = 0;
  26906. word32 idx = 0;
  26907. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  26908. CALLOC_ASNGETDATA(dataASN, authKeyIdASN_Length, ret, dcrl->heap);
  26909. if (ret == 0) {
  26910. /* Parse an authority key identifier. */
  26911. ret = GetASN_Items(authKeyIdASN, dataASN, authKeyIdASN_Length, 1, input,
  26912. &idx, sz);
  26913. }
  26914. if (ret == 0) {
  26915. /* Key id is optional. */
  26916. if (dataASN[1].data.ref.data == NULL) {
  26917. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available");
  26918. }
  26919. else {
  26920. /* Get the hash or hash of the hash if wrong size. */
  26921. ret = GetHashId(dataASN[1].data.ref.data,
  26922. dataASN[1].data.ref.length, dcrl->extAuthKeyId);
  26923. }
  26924. }
  26925. FREE_ASNGETDATA(dataASN, dcrl->heap);
  26926. return ret;
  26927. #endif /* WOLFSSL_ASN_TEMPLATE */
  26928. }
  26929. #endif
  26930. #ifndef WOLFSSL_ASN_TEMPLATE
  26931. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  26932. word32* inOutIdx, word32 sz)
  26933. {
  26934. int length;
  26935. word32 idx;
  26936. word32 ext_bound; /* boundary index for the sequence of extensions */
  26937. word32 oid;
  26938. byte tag;
  26939. WOLFSSL_ENTER("ParseCRL_Extensions");
  26940. (void)dcrl;
  26941. if (inOutIdx == NULL)
  26942. return BAD_FUNC_ARG;
  26943. idx = *inOutIdx;
  26944. /* CRL Extensions are optional */
  26945. if ((idx + 1) > sz)
  26946. return 0;
  26947. /* CRL Extensions are optional */
  26948. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  26949. return 0;
  26950. /* CRL Extensions are optional */
  26951. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  26952. return 0;
  26953. if (GetLength(buf, &idx, &length, sz) < 0)
  26954. return ASN_PARSE_E;
  26955. if (GetSequence(buf, &idx, &length, sz) < 0)
  26956. return ASN_PARSE_E;
  26957. ext_bound = idx + length;
  26958. while (idx < (word32)ext_bound) {
  26959. word32 localIdx;
  26960. int ret;
  26961. if (GetSequence(buf, &idx, &length, sz) < 0) {
  26962. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  26963. return ASN_PARSE_E;
  26964. }
  26965. oid = 0;
  26966. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  26967. WOLFSSL_MSG("\tfail: OBJECT ID");
  26968. return ASN_PARSE_E;
  26969. }
  26970. /* check for critical flag */
  26971. if ((idx + 1) > (word32)sz) {
  26972. WOLFSSL_MSG("\tfail: malformed buffer");
  26973. return BUFFER_E;
  26974. }
  26975. localIdx = idx;
  26976. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  26977. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  26978. ret = GetBoolean(buf, &idx, sz);
  26979. if (ret < 0)
  26980. return ret;
  26981. }
  26982. ret = GetOctetString(buf, &idx, &length, sz);
  26983. if (ret < 0)
  26984. return ret;
  26985. if (oid == AUTH_KEY_OID) {
  26986. #ifndef NO_SKID
  26987. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  26988. if (ret < 0) {
  26989. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  26990. return ret;
  26991. }
  26992. #endif
  26993. }
  26994. idx += length;
  26995. }
  26996. *inOutIdx = idx;
  26997. return 0;
  26998. }
  26999. #else
  27000. /* Parse the extensions of a CRL.
  27001. *
  27002. * @param [in] dcrl Decoded CRL object.
  27003. * @param [in] buff Buffer holding CRL.
  27004. * @param [in] idx Index into buffer of extensions.
  27005. * @param [in] maxIdx Maximum index of extension data.
  27006. * @return 0 on success.
  27007. * @return ASN_PARSE_E on failure.
  27008. */
  27009. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf, word32 idx,
  27010. word32 maxIdx)
  27011. {
  27012. DECL_ASNGETDATA(dataASN, certExtASN_Length);
  27013. int ret = 0;
  27014. ALLOC_ASNGETDATA(dataASN, certExtASN_Length, ret, dcrl->heap);
  27015. while ((ret == 0) && (idx < maxIdx)) {
  27016. byte critical = 0;
  27017. /* Clear dynamic data. */
  27018. XMEMSET(dataASN, 0, sizeof(*dataASN) * certExtASN_Length);
  27019. /* Ensure OID is an extention type. */
  27020. GetASN_OID(&dataASN[1], oidCertExtType);
  27021. /* Set criticality variable. */
  27022. dataASN[2].data.u8 = &critical;
  27023. /* Parse extension wrapper. */
  27024. ret = GetASN_Items(certExtASN, dataASN, certExtASN_Length, 0, buf, &idx,
  27025. maxIdx);
  27026. if (ret == 0) {
  27027. /* OID in extension. */
  27028. word32 oid = dataASN[1].data.oid.sum;
  27029. /* Length of extension data. */
  27030. int length = dataASN[3].length;
  27031. if (oid == AUTH_KEY_OID) {
  27032. #ifndef NO_SKID
  27033. /* Parse Authority Key Id extesion.
  27034. * idx is at start of OCTET_STRING data. */
  27035. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  27036. if (ret != 0) {
  27037. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  27038. }
  27039. #endif
  27040. }
  27041. /* TODO: Parse CRL Number extension */
  27042. /* TODO: check criticality */
  27043. /* Move index on to next extension. */
  27044. idx += length;
  27045. }
  27046. }
  27047. if (ret < 0) {
  27048. ret = ASN_PARSE_E;
  27049. }
  27050. return ret;
  27051. }
  27052. #endif /* !WOLFSSL_ASN_TEMPLATE */
  27053. #ifdef WOLFSSL_ASN_TEMPLATE
  27054. /* ASN.1 template for a CRL- CertificateList.
  27055. * X.509: RFC 5280, 5.1 - CRL Fields
  27056. */
  27057. static const ASNItem crlASN[] = {
  27058. /* CertificateList */
  27059. /* 0 */ { 0, ASN_SEQUENCE, 1, 1, 0 },
  27060. /* tbsCertList */
  27061. /* 1 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  27062. /* version Version OPTIONAL if present must be v2 */
  27063. /* 2 */ { 2, ASN_INTEGER, 0, 0, 1 },
  27064. /* signature */
  27065. /* 3 */ { 2, ASN_SEQUENCE, 1, 1, 0 },
  27066. /* 4 */ { 3, ASN_OBJECT_ID, 0, 0, 0 },
  27067. /* 5 */ { 3, ASN_TAG_NULL, 0, 0, 1 },
  27068. /* issuer */
  27069. /* 6 */ { 2, ASN_SEQUENCE, 1, 0, 0 },
  27070. /* thisUpdate */
  27071. /* 7 */ { 2, ASN_UTC_TIME, 0, 0, 2 },
  27072. /* 8 */ { 2, ASN_GENERALIZED_TIME, 0, 0, 2 },
  27073. /* nextUpdate */
  27074. /* 9 */ { 2, ASN_UTC_TIME, 0, 0, 3 },
  27075. /* 10 */ { 2, ASN_GENERALIZED_TIME, 0, 0, 3 },
  27076. /* revokedCertificates */
  27077. /* 11 */ { 2, ASN_SEQUENCE, 1, 0, 1 },
  27078. /* crlExtensions */
  27079. /* 12 */ { 2, ASN_CONTEXT_SPECIFIC | 0, 1, 1, 1 },
  27080. /* 13 */ { 3, ASN_SEQUENCE, 1, 0, 0 },
  27081. /* signatureAlgorithm */
  27082. /* 14 */ { 1, ASN_SEQUENCE, 1, 1, 0 },
  27083. /* 15 */ { 2, ASN_OBJECT_ID, 0, 0, 0 },
  27084. /* 16 */ { 2, ASN_TAG_NULL, 0, 0, 1 },
  27085. /* signatureValue */
  27086. /* 17 */ { 1, ASN_BIT_STRING, 0, 0, 0 },
  27087. };
  27088. /* Number of items in ASN.1 template for a CRL- CertificateList. */
  27089. #define crlASN_Length (sizeof(crlASN) / sizeof(ASNItem))
  27090. #endif
  27091. /* parse crl buffer into decoded state, 0 on success */
  27092. int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
  27093. {
  27094. #ifndef WOLFSSL_ASN_TEMPLATE
  27095. Signer* ca = NULL;
  27096. SignatureCtx sigCtx;
  27097. int ret = 0;
  27098. int len;
  27099. word32 idx = 0;
  27100. WOLFSSL_MSG("ParseCRL");
  27101. /* raw crl hash */
  27102. /* hash here if needed for optimized comparisons
  27103. * wc_Sha sha;
  27104. * wc_InitSha(&sha);
  27105. * wc_ShaUpdate(&sha, buff, sz);
  27106. * wc_ShaFinal(&sha, dcrl->crlHash); */
  27107. if (GetSequence(buff, &idx, &len, sz) < 0)
  27108. return ASN_PARSE_E;
  27109. dcrl->certBegin = idx;
  27110. /* Normalize sz for the length inside the outer sequence. */
  27111. sz = len + idx;
  27112. if (GetSequence(buff, &idx, &len, sz) < 0)
  27113. return ASN_PARSE_E;
  27114. dcrl->sigIndex = len + idx;
  27115. if (ParseCRL_CertList(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  27116. return ASN_PARSE_E;
  27117. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  27118. return ASN_PARSE_E;
  27119. idx = dcrl->sigIndex;
  27120. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  27121. return ASN_PARSE_E;
  27122. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  27123. return ASN_PARSE_E;
  27124. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  27125. if experiencing issues uncomment NO_SKID define in CRL section of
  27126. wolfssl/wolfcrypt/settings.h */
  27127. #ifndef NO_SKID
  27128. if (dcrl->extAuthKeyIdSet) {
  27129. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  27130. }
  27131. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  27132. KEYID_SIZE) != 0) {
  27133. ca = NULL;
  27134. }
  27135. if (ca == NULL) {
  27136. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  27137. /* If AKID is available then this CA doesn't have the public
  27138. * key required */
  27139. if (ca && dcrl->extAuthKeyIdSet) {
  27140. WOLFSSL_MSG("CA SKID doesn't match AKID");
  27141. ca = NULL;
  27142. }
  27143. }
  27144. #else
  27145. ca = GetCA(cm, dcrl->issuerHash);
  27146. #endif /* !NO_SKID */
  27147. WOLFSSL_MSG("About to verify CRL signature");
  27148. if (ca == NULL) {
  27149. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  27150. ret = ASN_CRL_NO_SIGNER_E;
  27151. goto end;
  27152. }
  27153. WOLFSSL_MSG("Found CRL issuer CA");
  27154. ret = VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  27155. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  27156. dcrl->signatureOID, ca, dcrl->heap);
  27157. end:
  27158. return ret;
  27159. #else
  27160. DECL_ASNGETDATA(dataASN, crlASN_Length);
  27161. int ret = 0;
  27162. /* Default version - v1 = 0 */
  27163. byte version = 0;
  27164. word32 idx = 0;
  27165. /* Size of buffer for date. */
  27166. word32 lastDateSz = MAX_DATE_SIZE;
  27167. word32 nextDateSz = MAX_DATE_SIZE;
  27168. WOLFSSL_MSG("ParseCRL");
  27169. CALLOC_ASNGETDATA(dataASN, crlASN_Length, ret, dcrl->heap);
  27170. if (ret == 0) {
  27171. /* Set variable to store version. */
  27172. GetASN_Int8Bit(&dataASN[2], &version);
  27173. /* Set expecting signature OID. */
  27174. GetASN_OID(&dataASN[4], oidSigType);
  27175. /* Set buffer to put last and next date into. */
  27176. GetASN_Buffer(&dataASN[7], dcrl->lastDate, &lastDateSz);
  27177. GetASN_Buffer(&dataASN[8], dcrl->lastDate, &lastDateSz);
  27178. GetASN_Buffer(&dataASN[9], dcrl->nextDate, &nextDateSz);
  27179. GetASN_Buffer(&dataASN[10], dcrl->nextDate, &nextDateSz);
  27180. /* Set expecting signature OID. */
  27181. GetASN_OID(&dataASN[14], oidSigType);
  27182. /* Decode the CRL. */
  27183. ret = GetASN_Items(crlASN, dataASN, crlASN_Length, 1, buff, &idx, sz);
  27184. }
  27185. /* Version must be v2 = 1 if present. */
  27186. if ((ret == 0) && (dataASN[2].tag != 0) && (version != 1)) {
  27187. ret = ASN_PARSE_E;
  27188. }
  27189. /* Check minimum size of last date. */
  27190. if ((ret == 0) && (lastDateSz < MIN_DATE_SIZE)) {
  27191. ret = ASN_PARSE_E;
  27192. }
  27193. /* Check minimum size of next date. */
  27194. if ((ret == 0) && (nextDateSz < MIN_DATE_SIZE)) {
  27195. ret = ASN_PARSE_E;
  27196. }
  27197. /* 'signatureAlgorithm' OID must be the same as 'signature' OID. */
  27198. if ((ret == 0) && (dataASN[15].data.oid.sum != dataASN[4].data.oid.sum)) {
  27199. ret = ASN_PARSE_E;
  27200. }
  27201. if (ret == 0) {
  27202. /* Store offset of to be signed part. */
  27203. dcrl->certBegin = dataASN[1].offset;
  27204. /* Store index of signature. */
  27205. dcrl->sigIndex = dataASN[14].offset;
  27206. /* Store address and length of signature data. */
  27207. GetASN_GetRef(&dataASN[17], &dcrl->signature, &dcrl->sigLength);
  27208. /* Get the signature OID. */
  27209. dcrl->signatureOID = dataASN[15].data.oid.sum;
  27210. /* Get the format/tag of the last and next date. */
  27211. dcrl->lastDateFormat = (dataASN[7].tag != 0) ? dataASN[7].tag
  27212. : dataASN[8].tag;
  27213. dcrl->nextDateFormat = (dataASN[9].tag != 0) ? dataASN[9].tag
  27214. : dataASN[10].tag;
  27215. #ifndef NO_ASN_TIME
  27216. if (dcrl->nextDateFormat != 0) {
  27217. /* Next date was set, so validate it. */
  27218. if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  27219. WOLFSSL_MSG("CRL after date is no longer valid");
  27220. ret = CRL_CERT_DATE_ERR;
  27221. }
  27222. }
  27223. }
  27224. if (ret == 0) {
  27225. #endif
  27226. /* Calculate the Hash id from the issuer name. */
  27227. ret = CalcHashId(GetASNItem_Addr(dataASN[6], buff),
  27228. GetASNItem_Length(dataASN[6], buff), dcrl->issuerHash);
  27229. if (ret < 0) {
  27230. ret = ASN_PARSE_E;
  27231. }
  27232. }
  27233. if ((ret == 0) && (dataASN[11].tag != 0)) {
  27234. /* Parse revoked cerificates - starting after SEQUENCE OF. */
  27235. ret = ParseCRL_RevokedCerts(dcrl, buff,
  27236. GetASNItem_DataIdx(dataASN[11], buff),
  27237. GetASNItem_EndIdx(dataASN[11], buff));
  27238. }
  27239. if (ret == 0) {
  27240. /* Parse the extensions - starting after SEQUENCE OF. */
  27241. ret = ParseCRL_Extensions(dcrl, buff,
  27242. GetASNItem_DataIdx(dataASN[13], buff),
  27243. GetASNItem_EndIdx(dataASN[13], buff));
  27244. }
  27245. if (ret == 0) {
  27246. /* Find signer and verify signature. */
  27247. ret = PaseCRL_CheckSignature(dcrl, buff, cm);
  27248. }
  27249. FREE_ASNGETDATA(dataASN, dcrl->heap);
  27250. return ret;
  27251. #endif /* WOLFSSL_ASN_TEMPLATE */
  27252. }
  27253. #endif /* HAVE_CRL */
  27254. #ifdef WOLFSSL_CERT_PIV
  27255. #ifdef WOLFSSL_ASN_TEMPLATE
  27256. /* Template for PIV. */
  27257. static const ASNItem pivASN[] = {
  27258. /* 0 */ { 0, ASN_PIV_CERT, 0, 0, 0 },
  27259. /* 1 */ { 0, ASN_PIV_NONCE, 0, 0, 1 },
  27260. /* 2 */ { 0, ASN_PIV_SIGNED_NONCE, 0, 0, 1 },
  27261. };
  27262. #define pivASN_Length (sizeof(pivASN) / sizeof(ASNItem))
  27263. static const ASNItem pivCertASN[] = {
  27264. /* 0x53 = 0x40 | 0x13 */
  27265. /* 0 */ { 1, ASN_APPLICATION | 0x13, 0, 1, 0 },
  27266. /* 0x70 = 0x40 | 0x10 + 0x20 (CONSTRUCTED) */
  27267. /* 1 */ { 2, ASN_APPLICATION | 0x10, 1, 0, 0 },
  27268. /* 0x71 = 0x40 | 0x11 + 0x20 (CONSTRUCTED) */
  27269. /* 2 */ { 2, ASN_APPLICATION | 0x11, 1, 0, 1 },
  27270. /* 0xFE = 0xC0 | 0x1E + 0x20 (CONSTRUCTED) */
  27271. /* 3 */ { 2, ASN_PRIVATE | 0x1e, 1, 0, 1 },
  27272. };
  27273. #define pivCertASN_Length (sizeof(pivCertASN) / sizeof(ASNItem))
  27274. #endif
  27275. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  27276. {
  27277. #ifndef WOLFSSL_ASN_TEMPLATE
  27278. int length = 0;
  27279. word32 idx = 0;
  27280. WOLFSSL_ENTER("wc_ParseCertPIV");
  27281. if (piv == NULL || buf == NULL || totalSz == 0)
  27282. return BAD_FUNC_ARG;
  27283. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  27284. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  27285. /* Certificate (0A 82 05FA) */
  27286. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  27287. /* Identiv Type PIV card */
  27288. piv->isIdentiv = 1;
  27289. piv->cert = &buf[idx];
  27290. piv->certSz = length;
  27291. idx += length;
  27292. /* Nonce (0B 14) */
  27293. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  27294. piv->nonce = &buf[idx];
  27295. piv->nonceSz = length;
  27296. idx += length;
  27297. }
  27298. /* Signed Nonce (0C 82 0100) */
  27299. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  27300. piv->signedNonce = &buf[idx];
  27301. piv->signedNonceSz = length;
  27302. }
  27303. idx = 0;
  27304. buf = piv->cert;
  27305. totalSz = piv->certSz;
  27306. }
  27307. /* Certificate Buffer Total Size (53 82 05F6) */
  27308. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  27309. &length, totalSz) < 0) {
  27310. return ASN_PARSE_E;
  27311. }
  27312. /* PIV Certificate (70 82 05ED) */
  27313. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  27314. totalSz) < 0) {
  27315. return ASN_PARSE_E;
  27316. }
  27317. /* Capture certificate buffer pointer and length */
  27318. piv->cert = &buf[idx];
  27319. piv->certSz = length;
  27320. idx += length;
  27321. /* PIV Certificate Info (71 01 00) */
  27322. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  27323. totalSz) >= 0) {
  27324. if (length >= 1) {
  27325. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  27326. piv->isX509 = ((buf[idx] & ASN_PIV_CERT_INFO_ISX509) != 0);
  27327. }
  27328. idx += length;
  27329. }
  27330. /* PIV Error Detection (FE 00) */
  27331. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  27332. totalSz) >= 0) {
  27333. piv->certErrDet = &buf[idx];
  27334. piv->certErrDetSz = length;
  27335. idx += length;
  27336. }
  27337. return 0;
  27338. #else
  27339. /* pivCertASN_Length is longer than pivASN_Length */
  27340. DECL_ASNGETDATA(dataASN, pivCertASN_Length);
  27341. int ret = 0;
  27342. word32 idx;
  27343. byte info;
  27344. WOLFSSL_ENTER("wc_ParseCertPIV");
  27345. ALLOC_ASNGETDATA(dataASN, pivCertASN_Length, ret, NULL);
  27346. if (ret == 0) {
  27347. /* Clear dynamic data. */
  27348. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivASN_Length);
  27349. /* Start parsing from start of buffer. */
  27350. idx = 0;
  27351. /* Parse Identiv wrapper. */
  27352. ret = GetASN_Items(pivASN, dataASN, pivASN_Length, 1, buf, &idx,
  27353. totalSz);
  27354. if (ret == 0) {
  27355. /* Identiv wrapper found. */
  27356. piv->isIdentiv = 1;
  27357. /* Get nonce reference. */
  27358. if (dataASN[1].tag != 0) {
  27359. GetASN_GetConstRef(&dataASN[1], &piv->nonce, &piv->nonceSz);
  27360. }
  27361. /* Get signedNonce reference. */
  27362. if (dataASN[2].tag != 0) {
  27363. GetASN_GetConstRef(&dataASN[2], &piv->signedNonce,
  27364. &piv->signedNonceSz);
  27365. }
  27366. /* Get the certificate data for parsing. */
  27367. GetASN_GetConstRef(&dataASN[0], &buf, &totalSz);
  27368. }
  27369. ret = 0;
  27370. }
  27371. if (ret == 0) {
  27372. /* Clear dynamic data and set variable to put cert info into. */
  27373. XMEMSET(dataASN, 0, sizeof(*dataASN) * pivCertASN_Length);
  27374. GetASN_Int8Bit(&dataASN[2], &info);
  27375. /* Start parsing from start of buffer. */
  27376. idx = 0;
  27377. /* Parse PIV cetificate data. */
  27378. ret = GetASN_Items(pivCertASN, dataASN, pivCertASN_Length, 1, buf, &idx,
  27379. totalSz);
  27380. if (ret == 0) {
  27381. /* Get X.509 certificate reference. */
  27382. GetASN_GetConstRef(&dataASN[1], &piv->cert, &piv->certSz);
  27383. /* Set the certificate info if available. */
  27384. if (dataASN[2].tag != 0) {
  27385. /* Bits 1 and 2 are compression. */
  27386. piv->compression = info & ASN_PIV_CERT_INFO_COMPRESSED;
  27387. /* Bits 3 is X509 flag. */
  27388. piv->isX509 = ((info & ASN_PIV_CERT_INFO_ISX509) != 0);
  27389. }
  27390. /* Get X.509 certificate error detecton reference. */
  27391. GetASN_GetConstRef(&dataASN[3], &piv->certErrDet,
  27392. &piv->certErrDetSz);
  27393. }
  27394. ret = 0;
  27395. }
  27396. FREE_ASNGETDATA(dataASN, NULL);
  27397. return ret;
  27398. #endif /* WOLFSSL_ASN_TEMPLATE */
  27399. }
  27400. #endif /* WOLFSSL_CERT_PIV */
  27401. #ifdef HAVE_SMIME
  27402. /*****************************************************************************
  27403. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  27404. * and parameters into headers. Will continue until in has no more content.
  27405. *
  27406. * RETURNS:
  27407. * returns zero on success, non-zero on error.
  27408. */
  27409. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  27410. {
  27411. MimeHdr* nextHdr = NULL;
  27412. MimeHdr* curHdr = NULL;
  27413. MimeParam* nextParam = NULL;
  27414. size_t start = 0;
  27415. size_t end = 0;
  27416. char* nameAttr = NULL;
  27417. char* bodyVal = NULL;
  27418. MimeTypes mimeType = MIME_HDR;
  27419. MimeStatus mimeStatus = MIME_NAMEATTR;
  27420. int ret = -1;
  27421. size_t pos = 0;
  27422. size_t lineLen = 0;
  27423. char* curLine = NULL;
  27424. char* ptr = NULL;
  27425. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  27426. ret = BAD_FUNC_ARG;
  27427. goto error;
  27428. }
  27429. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  27430. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  27431. DYNAMIC_TYPE_PKCS7);
  27432. if (nextHdr == NULL || nextParam == NULL) {
  27433. ret = MEMORY_E;
  27434. goto error;
  27435. }
  27436. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  27437. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  27438. curLine = XSTRTOK(in, "\r\n", &ptr);
  27439. if (curLine == NULL) {
  27440. ret = ASN_PARSE_E;
  27441. goto error;
  27442. }
  27443. while (curLine != NULL) {
  27444. /* Leftover from previous line, add params to previous header. */
  27445. if (curLine[0] == ' ' && curHdr) {
  27446. mimeType = MIME_PARAM;
  27447. }
  27448. else {
  27449. mimeType = MIME_HDR;
  27450. }
  27451. start = 0;
  27452. lineLen = XSTRLEN(curLine);
  27453. if (lineLen == 0) {
  27454. ret = BAD_FUNC_ARG;
  27455. goto error;
  27456. }
  27457. for (pos = 0; pos < lineLen; pos++) {
  27458. char cur = curLine[pos];
  27459. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  27460. mimeType == MIME_HDR) || (cur == '=' &&
  27461. mimeType == MIME_PARAM)) && pos >= 1) {
  27462. mimeStatus = MIME_BODYVAL;
  27463. end = pos-1;
  27464. if (nameAttr != NULL)
  27465. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  27466. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  27467. if (ret) {
  27468. goto error;
  27469. }
  27470. start = pos+1;
  27471. }
  27472. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  27473. end = pos-1;
  27474. if (bodyVal != NULL)
  27475. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  27476. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  27477. if (ret) {
  27478. goto error;
  27479. }
  27480. if (mimeType == MIME_HDR) {
  27481. nextHdr->name = nameAttr;
  27482. nameAttr = NULL;
  27483. nextHdr->body = bodyVal;
  27484. bodyVal = NULL;
  27485. nextHdr->next = curHdr;
  27486. curHdr = nextHdr;
  27487. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  27488. DYNAMIC_TYPE_PKCS7);
  27489. if (nextHdr == NULL) {
  27490. ret = MEMORY_E;
  27491. goto error;
  27492. }
  27493. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  27494. }
  27495. else {
  27496. nextParam->attribute = nameAttr;
  27497. nameAttr = NULL;
  27498. nextParam->value = bodyVal;
  27499. bodyVal = NULL;
  27500. nextParam->next = curHdr->params;
  27501. curHdr->params = nextParam;
  27502. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  27503. DYNAMIC_TYPE_PKCS7);
  27504. if (nextParam == NULL) {
  27505. ret = MEMORY_E;
  27506. goto error;
  27507. }
  27508. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  27509. }
  27510. mimeType = MIME_PARAM;
  27511. mimeStatus = MIME_NAMEATTR;
  27512. start = pos+1;
  27513. }
  27514. }
  27515. end = lineLen-1;
  27516. /* Omit newline characters. */
  27517. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  27518. end--;
  27519. }
  27520. if (end >= start && mimeStatus == MIME_BODYVAL) {
  27521. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  27522. if (ret) {
  27523. goto error;
  27524. }
  27525. if (mimeType == MIME_HDR) {
  27526. nextHdr->name = nameAttr;
  27527. nameAttr = NULL;
  27528. nextHdr->body = bodyVal;
  27529. bodyVal = NULL;
  27530. nextHdr->next = curHdr;
  27531. curHdr = nextHdr;
  27532. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  27533. DYNAMIC_TYPE_PKCS7);
  27534. if (nextHdr == NULL) {
  27535. ret = MEMORY_E;
  27536. goto error;
  27537. }
  27538. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  27539. } else {
  27540. nextParam->attribute = nameAttr;
  27541. nameAttr = NULL;
  27542. nextParam->value = bodyVal;
  27543. bodyVal = NULL;
  27544. nextParam->next = curHdr->params;
  27545. curHdr->params = nextParam;
  27546. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  27547. DYNAMIC_TYPE_PKCS7);
  27548. if (nextParam == NULL) {
  27549. ret = MEMORY_E;
  27550. goto error;
  27551. }
  27552. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  27553. }
  27554. }
  27555. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  27556. mimeStatus = MIME_NAMEATTR;
  27557. }
  27558. *headers = curHdr;
  27559. ret = 0; /* success if at this point */
  27560. error:
  27561. if (ret != 0)
  27562. wc_MIME_free_hdrs(curHdr);
  27563. wc_MIME_free_hdrs(nextHdr);
  27564. if (nameAttr != NULL)
  27565. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  27566. if (bodyVal != NULL)
  27567. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  27568. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  27569. return ret;
  27570. }
  27571. /*****************************************************************************
  27572. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  27573. * out disallowed/separator characters and places the rest into *out.
  27574. *
  27575. * RETURNS:
  27576. * returns zero on success, non-zero on error.
  27577. */
  27578. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  27579. {
  27580. size_t inPos = start;
  27581. size_t outPos = 0;
  27582. size_t inLen = 0;
  27583. if (end < start || in == NULL || out == NULL) {
  27584. return BAD_FUNC_ARG;
  27585. }
  27586. inLen = XSTRLEN(in);
  27587. if (start > inLen || end > inLen) {
  27588. return BAD_FUNC_ARG;
  27589. }
  27590. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  27591. DYNAMIC_TYPE_PKCS7);
  27592. if (*out == NULL) {
  27593. return MEMORY_E;
  27594. }
  27595. while (inPos <= end) {
  27596. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  27597. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  27598. (*out)[outPos] = in[inPos];
  27599. outPos++;
  27600. }
  27601. inPos++;
  27602. }
  27603. (*out)[outPos] = '\0';
  27604. return 0;
  27605. }
  27606. /*****************************************************************************
  27607. * wc_MIME_find_header_name - Searches through all given headers until a header with
  27608. * a name matching the provided name is found.
  27609. *
  27610. * RETURNS:
  27611. * returns a pointer to the found header, if no match was found, returns NULL.
  27612. */
  27613. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  27614. {
  27615. size_t len = XSTRLEN(name);
  27616. while (header) {
  27617. if (!XSTRNCMP(name, header->name, len)) {
  27618. return header;
  27619. }
  27620. header = header->next;
  27621. }
  27622. return header;
  27623. }
  27624. /*****************************************************************************
  27625. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  27626. * with a attribute matching the provided attribute is found.
  27627. *
  27628. * RETURNS:
  27629. * returns a pointer to the found parameter, if no match was found,
  27630. * returns NULL.
  27631. */
  27632. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  27633. MimeParam* param)
  27634. {
  27635. size_t len = XSTRLEN(attribute);
  27636. while (param) {
  27637. if (!XSTRNCMP(attribute, param->attribute, len)) {
  27638. return param;
  27639. }
  27640. param = param->next;
  27641. }
  27642. return param;
  27643. }
  27644. /*****************************************************************************
  27645. * wc_MIME_canonicalize - Canonicalize a line by converting all line endings
  27646. * to CRLF.
  27647. *
  27648. * RETURNS:
  27649. * returns a pointer to a canonicalized line on success, NULL on error.
  27650. */
  27651. char* wc_MIME_canonicalize(const char* line)
  27652. {
  27653. size_t end = 0;
  27654. char* canonLine = NULL;
  27655. if (line == NULL || XSTRLEN(line) == 0) {
  27656. return NULL;
  27657. }
  27658. end = XSTRLEN(line);
  27659. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  27660. end--;
  27661. }
  27662. /* Need 2 chars for \r\n and 1 for EOL */
  27663. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  27664. if (canonLine == NULL) {
  27665. return NULL;
  27666. }
  27667. XSTRNCPY(canonLine, line, end);
  27668. canonLine[end] = '\r';
  27669. canonLine[end+1] = '\n';
  27670. canonLine[end+2] = '\0';
  27671. return canonLine;
  27672. }
  27673. /*****************************************************************************
  27674. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  27675. * the provided header pointer.
  27676. *
  27677. * RETURNS:
  27678. * returns zero on success, non-zero on error.
  27679. */
  27680. int wc_MIME_free_hdrs(MimeHdr* head)
  27681. {
  27682. MimeHdr* curHdr = NULL;
  27683. MimeParam* curParam = NULL;
  27684. while (head) {
  27685. while (head->params) {
  27686. curParam = head->params;
  27687. head->params = head->params->next;
  27688. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  27689. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  27690. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  27691. }
  27692. curHdr = head;
  27693. head = head->next;
  27694. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  27695. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  27696. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  27697. }
  27698. return 0;
  27699. }
  27700. #endif /* HAVE_SMIME */
  27701. #undef ERROR_OUT
  27702. #endif /* !NO_ASN */
  27703. #ifdef WOLFSSL_SEP
  27704. #endif /* WOLFSSL_SEP */