asn.c 548 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841
  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) objects.
  24. ASN.1 is a standard interface description language for defining data structures
  25. that can be serialized and deserialized in a cross-platform way.
  26. */
  27. #ifdef HAVE_CONFIG_H
  28. #include <config.h>
  29. #endif
  30. #include <wolfssl/wolfcrypt/settings.h>
  31. /*
  32. ASN Options:
  33. * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
  34. or wishing to save space.
  35. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  36. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  37. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  38. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  39. * WOLFSSL_NO_ASN_STRICT: Disable strict RFC compliance checks to
  40. restore 3.13.0 behavior.
  41. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  42. must still be trusted)
  43. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  44. chain is not loaded. This only matches on subject and public key and
  45. does not perform a PKI validation, so it is not a secure solution.
  46. Only enabled for OCSP.
  47. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  48. disable checking of OCSP subject hash with issuer hash.
  49. * WOLFSSL_SMALL_CERT_VERIFY: Verify the certificate signature without using
  50. DecodedCert. Doubles up on some code but allows smaller dynamic memory
  51. usage.
  52. * WOLFSSL_NO_OCSP_DATE_CHECK: Disable date checks for OCSP responses. This
  53. may be required when the system's real-time clock is not very accurate.
  54. It is recommended to enforce the nonce check instead if possible.
  55. * WOLFSSL_FORCE_OCSP_NONCE_CHECK: Require nonces to be available in OCSP
  56. responses. The nonces are optional and may not be supported by all
  57. responders. If it can be ensured that the used responder sends nonces this
  58. option may improve security.
  59. */
  60. #ifndef NO_ASN
  61. #include <wolfssl/wolfcrypt/asn.h>
  62. #include <wolfssl/wolfcrypt/coding.h>
  63. #include <wolfssl/wolfcrypt/md2.h>
  64. #include <wolfssl/wolfcrypt/hmac.h>
  65. #include <wolfssl/wolfcrypt/error-crypt.h>
  66. #include <wolfssl/wolfcrypt/pwdbased.h>
  67. #include <wolfssl/wolfcrypt/des3.h>
  68. #include <wolfssl/wolfcrypt/aes.h>
  69. #include <wolfssl/wolfcrypt/rc2.h>
  70. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  71. #include <wolfssl/wolfcrypt/logging.h>
  72. #include <wolfssl/wolfcrypt/random.h>
  73. #include <wolfssl/wolfcrypt/hash.h>
  74. #ifdef NO_INLINE
  75. #include <wolfssl/wolfcrypt/misc.h>
  76. #else
  77. #define WOLFSSL_MISC_INCLUDED
  78. #include <wolfcrypt/src/misc.c>
  79. #endif
  80. #ifndef NO_RC4
  81. #include <wolfssl/wolfcrypt/arc4.h>
  82. #endif
  83. #ifdef HAVE_NTRU
  84. #include "libntruencrypt/ntru_crypto.h"
  85. #endif
  86. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  87. #include <wolfssl/wolfcrypt/sha512.h>
  88. #endif
  89. #ifndef NO_SHA256
  90. #include <wolfssl/wolfcrypt/sha256.h>
  91. #endif
  92. #ifdef HAVE_ECC
  93. #include <wolfssl/wolfcrypt/ecc.h>
  94. #endif
  95. #ifdef HAVE_ED25519
  96. #include <wolfssl/wolfcrypt/ed25519.h>
  97. #endif
  98. #ifdef HAVE_ED448
  99. #include <wolfssl/wolfcrypt/ed448.h>
  100. #endif
  101. #ifdef WOLFSSL_QNX_CAAM
  102. #include <wolfssl/wolfcrypt/port/caam/wolfcaam.h>
  103. #endif
  104. #ifndef NO_RSA
  105. #include <wolfssl/wolfcrypt/rsa.h>
  106. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  107. extern int wc_InitRsaHw(RsaKey* key);
  108. #endif
  109. #endif
  110. #ifndef NO_DSA
  111. #include <wolfssl/wolfcrypt/dsa.h>
  112. #else
  113. typedef void* DsaKey;
  114. #endif
  115. #ifdef WOLF_CRYPTO_CB
  116. #include <wolfssl/wolfcrypt/cryptocb.h>
  117. #endif
  118. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  119. #include <wolfssl/openssl/objects.h>
  120. #endif
  121. #ifdef _MSC_VER
  122. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  123. #pragma warning(disable: 4996)
  124. #endif
  125. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  126. #if !defined(NO_SKID) && (!defined(HAVE_FIPS) || !defined(HAVE_FIPS_VERSION))
  127. #if !defined(HAVE_SELFTEST) || (defined(HAVE_SELFTEST) && \
  128. (!defined(HAVE_SELFTEST_VERSION) || \
  129. HAVE_SELFTEST_VERSION < 2))
  130. #ifndef WOLFSSL_AES_KEY_SIZE_ENUM
  131. #define WOLFSSL_AES_KEY_SIZE_ENUM
  132. enum Asn_Misc {
  133. AES_IV_SIZE = 16,
  134. AES_128_KEY_SIZE = 16,
  135. AES_192_KEY_SIZE = 24,
  136. AES_256_KEY_SIZE = 32
  137. };
  138. #endif
  139. #endif /* HAVE_SELFTEST */
  140. #endif
  141. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  142. void tsip_inform_key_position(const word32 key_n_start,
  143. const word32 key_n_len, const word32 key_e_start,
  144. const word32 key_e_len);
  145. int tsip_tls_CertVerify(const byte *cert, word32 certSz,
  146. const byte *signature, word32 sigSz,
  147. word32 key_n_start, word32 key_n_len,
  148. word32 key_e_start, word32 key_e_len,
  149. byte *tsip_encRsaKeyIdx);
  150. #endif
  151. int GetLength(const byte* input, word32* inOutIdx, int* len,
  152. word32 maxIdx)
  153. {
  154. return GetLength_ex(input, inOutIdx, len, maxIdx, 1);
  155. }
  156. /* give option to check length value found against index. 1 to check 0 to not */
  157. int GetLength_ex(const byte* input, word32* inOutIdx, int* len,
  158. word32 maxIdx, int check)
  159. {
  160. int length = 0;
  161. word32 idx = *inOutIdx;
  162. byte b;
  163. *len = 0; /* default length */
  164. if ((idx + 1) > maxIdx) { /* for first read */
  165. WOLFSSL_MSG("GetLength bad index on input");
  166. return BUFFER_E;
  167. }
  168. b = input[idx++];
  169. if (b >= ASN_LONG_LENGTH) {
  170. word32 bytes = b & 0x7F;
  171. if ((idx + bytes) > maxIdx) { /* for reading bytes */
  172. WOLFSSL_MSG("GetLength bad long length");
  173. return BUFFER_E;
  174. }
  175. if (bytes > sizeof(length)) {
  176. return ASN_PARSE_E;
  177. }
  178. while (bytes--) {
  179. b = input[idx++];
  180. length = (length << 8) | b;
  181. }
  182. if (length < 0) {
  183. return ASN_PARSE_E;
  184. }
  185. }
  186. else
  187. length = b;
  188. if (check && (idx + length) > maxIdx) { /* for user of length */
  189. WOLFSSL_MSG("GetLength value exceeds buffer length");
  190. return BUFFER_E;
  191. }
  192. *inOutIdx = idx;
  193. if (length > 0)
  194. *len = length;
  195. return length;
  196. }
  197. /* input : buffer to read from
  198. * inOutIdx : index to start reading from, gets advanced by 1 if successful
  199. * maxIdx : maximum index value
  200. * tag : ASN tag value found
  201. *
  202. * returns 0 on success
  203. */
  204. int GetASNTag(const byte* input, word32* inOutIdx, byte* tag, word32 maxIdx)
  205. {
  206. word32 idx;
  207. if (tag == NULL || inOutIdx == NULL || input == NULL) {
  208. return BAD_FUNC_ARG;
  209. }
  210. idx = *inOutIdx;
  211. if (idx + ASN_TAG_SZ > maxIdx) {
  212. WOLFSSL_MSG("Buffer too small for ASN tag");
  213. return BUFFER_E;
  214. }
  215. *tag = input[idx];
  216. *inOutIdx = idx + ASN_TAG_SZ;
  217. return 0;
  218. }
  219. static int GetASNHeader_ex(const byte* input, byte tag, word32* inOutIdx, int* len,
  220. word32 maxIdx, int check)
  221. {
  222. word32 idx = *inOutIdx;
  223. byte tagFound;
  224. int length;
  225. if (GetASNTag(input, &idx, &tagFound, maxIdx) != 0)
  226. return ASN_PARSE_E;
  227. if (tagFound != tag)
  228. return ASN_PARSE_E;
  229. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  230. return ASN_PARSE_E;
  231. *len = length;
  232. *inOutIdx = idx;
  233. return length;
  234. }
  235. /* Get the DER/BER encoding of an ASN.1 header.
  236. *
  237. * input Buffer holding DER/BER encoded data.
  238. * tag ASN.1 tag value expected in header.
  239. * inOutIdx Current index into buffer to parse.
  240. * len The number of bytes in the ASN.1 data.
  241. * maxIdx Length of data in buffer.
  242. * returns BUFFER_E when there is not enough data to parse.
  243. * ASN_PARSE_E when the expected tag is not found or length is invalid.
  244. * Otherwise, the number of bytes in the ASN.1 data.
  245. */
  246. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  247. word32 maxIdx)
  248. {
  249. return GetASNHeader_ex(input, tag, inOutIdx, len, maxIdx, 1);
  250. }
  251. static int GetHeader(const byte* input, byte* tag, word32* inOutIdx, int* len,
  252. word32 maxIdx, int check)
  253. {
  254. word32 idx = *inOutIdx;
  255. int length;
  256. if ((idx + 1) > maxIdx)
  257. return BUFFER_E;
  258. *tag = input[idx++];
  259. if (GetLength_ex(input, &idx, &length, maxIdx, check) < 0)
  260. return ASN_PARSE_E;
  261. *len = length;
  262. *inOutIdx = idx;
  263. return length;
  264. }
  265. int GetSequence(const byte* input, word32* inOutIdx, int* len,
  266. word32 maxIdx)
  267. {
  268. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  269. maxIdx);
  270. }
  271. int GetSequence_ex(const byte* input, word32* inOutIdx, int* len,
  272. word32 maxIdx, int check)
  273. {
  274. return GetASNHeader_ex(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  275. maxIdx, check);
  276. }
  277. int GetSet(const byte* input, word32* inOutIdx, int* len,
  278. word32 maxIdx)
  279. {
  280. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  281. maxIdx);
  282. }
  283. int GetSet_ex(const byte* input, word32* inOutIdx, int* len,
  284. word32 maxIdx, int check)
  285. {
  286. return GetASNHeader_ex(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  287. maxIdx, check);
  288. }
  289. /* Get the DER/BER encoded ASN.1 NULL element.
  290. * Ensure that the all fields are as expected and move index past the element.
  291. *
  292. * input Buffer holding DER/BER encoded data.
  293. * inOutIdx Current index into buffer to parse.
  294. * maxIdx Length of data in buffer.
  295. * returns BUFFER_E when there is not enough data to parse.
  296. * ASN_TAG_NULL_E when the NULL tag is not found.
  297. * ASN_EXPECT_0_E when the length is not zero.
  298. * Otherwise, 0 to indicate success.
  299. */
  300. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  301. {
  302. word32 idx = *inOutIdx;
  303. byte b;
  304. if ((idx + 2) > maxIdx)
  305. return BUFFER_E;
  306. b = input[idx++];
  307. if (b != ASN_TAG_NULL)
  308. return ASN_TAG_NULL_E;
  309. if (input[idx++] != 0)
  310. return ASN_EXPECT_0_E;
  311. *inOutIdx = idx;
  312. return 0;
  313. }
  314. /* Set the DER/BER encoding of the ASN.1 NULL element.
  315. *
  316. * output Buffer to write into.
  317. * returns the number of bytes added to the buffer.
  318. */
  319. static int SetASNNull(byte* output)
  320. {
  321. output[0] = ASN_TAG_NULL;
  322. output[1] = 0;
  323. return 2;
  324. }
  325. #ifndef NO_CERTS
  326. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  327. *
  328. * input Buffer holding DER/BER encoded data.
  329. * inOutIdx Current index into buffer to parse.
  330. * maxIdx Length of data in buffer.
  331. * returns BUFFER_E when there is not enough data to parse.
  332. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  333. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  334. */
  335. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  336. {
  337. word32 idx = *inOutIdx;
  338. byte b;
  339. if ((idx + 3) > maxIdx)
  340. return BUFFER_E;
  341. b = input[idx++];
  342. if (b != ASN_BOOLEAN)
  343. return ASN_PARSE_E;
  344. if (input[idx++] != 1)
  345. return ASN_PARSE_E;
  346. b = input[idx++] != 0;
  347. *inOutIdx = idx;
  348. return b;
  349. }
  350. #endif /* !NO_CERTS*/
  351. #ifdef ASN1_SET_BOOLEAN
  352. /* Set the DER/BER encoding of the ASN.1 NULL element.
  353. * Note: Function not required as yet.
  354. *
  355. * val Boolean value to encode.
  356. * output Buffer to write into.
  357. * returns the number of bytes added to the buffer.
  358. */
  359. static int SetBoolean(int val, byte* output)
  360. {
  361. output[0] = ASN_BOOLEAN;
  362. output[1] = 1;
  363. output[2] = val ? -1 : 0;
  364. return 3;
  365. }
  366. #endif
  367. /* Get the DER/BER encoding of an ASN.1 OCTET_STRING header.
  368. *
  369. * input Buffer holding DER/BER encoded data.
  370. * inOutIdx Current index into buffer to parse.
  371. * len The number of bytes in the ASN.1 data.
  372. * maxIdx Length of data in buffer.
  373. * returns BUFFER_E when there is not enough data to parse.
  374. * ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  375. * invalid.
  376. * Otherwise, the number of bytes in the ASN.1 data.
  377. */
  378. int GetOctetString(const byte* input, word32* inOutIdx, int* len,
  379. word32 maxIdx)
  380. {
  381. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  382. }
  383. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  384. * Removes the leading zero byte when found.
  385. *
  386. * input Buffer holding DER/BER encoded data.
  387. * inOutIdx Current index into buffer to parse.
  388. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  389. * maxIdx Length of data in buffer.
  390. * returns BUFFER_E when there is not enough data to parse.
  391. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  392. * or invalid use of or missing leading zero.
  393. * Otherwise, 0 to indicate success.
  394. */
  395. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  396. word32 maxIdx)
  397. {
  398. int ret;
  399. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  400. if (ret < 0)
  401. return ret;
  402. if (*len > 0) {
  403. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  404. /* check for invalid padding on negative integer.
  405. * c.f. X.690 (ISO/IEC 8825-2:2003 (E)) 10.4.6; RFC 5280 4.1
  406. */
  407. if (*len > 1) {
  408. if ((input[*inOutIdx] == 0xff) && (input[*inOutIdx + 1] & 0x80))
  409. return ASN_PARSE_E;
  410. }
  411. #endif
  412. /* remove leading zero, unless there is only one 0x00 byte */
  413. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  414. (*inOutIdx)++;
  415. (*len)--;
  416. #ifndef WOLFSSL_ASN_INT_LEAD_0_ANY
  417. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  418. return ASN_PARSE_E;
  419. #endif
  420. }
  421. }
  422. return 0;
  423. }
  424. #ifndef NO_CERTS
  425. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  426. * 7 bits.
  427. *
  428. * input Buffer holding DER/BER encoded data.
  429. * inOutIdx Current index into buffer to parse.
  430. * maxIdx Length of data in buffer.
  431. * returns BUFFER_E when there is not enough data to parse.
  432. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  433. * Otherwise, the 7-bit value.
  434. */
  435. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  436. {
  437. word32 idx = *inOutIdx;
  438. byte b;
  439. if ((idx + 3) > maxIdx)
  440. return BUFFER_E;
  441. if (GetASNTag(input, &idx, &b, maxIdx) != 0)
  442. return ASN_PARSE_E;
  443. if (b != ASN_INTEGER)
  444. return ASN_PARSE_E;
  445. if (input[idx++] != 1)
  446. return ASN_PARSE_E;
  447. b = input[idx++];
  448. *inOutIdx = idx;
  449. return b;
  450. }
  451. #endif /* !NO_CERTS */
  452. #if !defined(NO_DSA) && !defined(NO_SHA)
  453. static const char sigSha1wDsaName[] = "SHAwDSA";
  454. static const char sigSha256wDsaName[] = "SHA256wDSA";
  455. #endif /* NO_DSA */
  456. #ifndef NO_RSA
  457. #ifdef WOLFSSL_MD2
  458. static const char sigMd2wRsaName[] = "md2WithRSAEncryption";
  459. #endif
  460. #ifndef NO_MD5
  461. static const char sigMd5wRsaName[] = "md5WithRSAEncryption";
  462. #endif
  463. #ifndef NO_SHA
  464. static const char sigSha1wRsaName[] = "sha1WithRSAEncryption";
  465. #endif
  466. #ifdef WOLFSSL_SHA224
  467. static const char sigSha224wRsaName[] = "sha224WithRSAEncryption";
  468. #endif
  469. #ifndef NO_SHA256
  470. static const char sigSha256wRsaName[] = "sha256WithRSAEncryption";
  471. #endif
  472. #ifdef WOLFSSL_SHA384
  473. static const char sigSha384wRsaName[] = "sha384WithRSAEncryption";
  474. #endif
  475. #ifdef WOLFSSL_SHA512
  476. static const char sigSha512wRsaName[] = "sha512WithRSAEncryption";
  477. #endif
  478. #endif /* NO_RSA */
  479. #ifdef HAVE_ECC
  480. #ifndef NO_SHA
  481. static const char sigSha1wEcdsaName[] = "SHAwECDSA";
  482. #endif
  483. #ifdef WOLFSSL_SHA224
  484. static const char sigSha224wEcdsaName[] = "SHA224wECDSA";
  485. #endif
  486. #ifndef NO_SHA256
  487. static const char sigSha256wEcdsaName[] = "SHA256wECDSA";
  488. #endif
  489. #ifdef WOLFSSL_SHA384
  490. static const char sigSha384wEcdsaName[] = "SHA384wECDSA";
  491. #endif
  492. #ifdef WOLFSSL_SHA512
  493. static const char sigSha512wEcdsaName[] = "SHA512wECDSA";
  494. #endif
  495. #endif /* HAVE_ECC */
  496. static const char sigUnknownName[] = "Unknown";
  497. /* Get the human readable string for a signature type
  498. *
  499. * oid Oid value for signature
  500. */
  501. const char* GetSigName(int oid) {
  502. switch (oid) {
  503. #if !defined(NO_DSA) && !defined(NO_SHA)
  504. case CTC_SHAwDSA:
  505. return sigSha1wDsaName;
  506. case CTC_SHA256wDSA:
  507. return sigSha256wDsaName;
  508. #endif /* NO_DSA && NO_SHA */
  509. #ifndef NO_RSA
  510. #ifdef WOLFSSL_MD2
  511. case CTC_MD2wRSA:
  512. return sigMd2wRsaName;
  513. #endif
  514. #ifndef NO_MD5
  515. case CTC_MD5wRSA:
  516. return sigMd5wRsaName;
  517. #endif
  518. #ifndef NO_SHA
  519. case CTC_SHAwRSA:
  520. return sigSha1wRsaName;
  521. #endif
  522. #ifdef WOLFSSL_SHA224
  523. case CTC_SHA224wRSA:
  524. return sigSha224wRsaName;
  525. #endif
  526. #ifndef NO_SHA256
  527. case CTC_SHA256wRSA:
  528. return sigSha256wRsaName;
  529. #endif
  530. #ifdef WOLFSSL_SHA384
  531. case CTC_SHA384wRSA:
  532. return sigSha384wRsaName;
  533. #endif
  534. #ifdef WOLFSSL_SHA512
  535. case CTC_SHA512wRSA:
  536. return sigSha512wRsaName;
  537. #endif
  538. #endif /* NO_RSA */
  539. #ifdef HAVE_ECC
  540. #ifndef NO_SHA
  541. case CTC_SHAwECDSA:
  542. return sigSha1wEcdsaName;
  543. #endif
  544. #ifdef WOLFSSL_SHA224
  545. case CTC_SHA224wECDSA:
  546. return sigSha224wEcdsaName;
  547. #endif
  548. #ifndef NO_SHA256
  549. case CTC_SHA256wECDSA:
  550. return sigSha256wEcdsaName;
  551. #endif
  552. #ifdef WOLFSSL_SHA384
  553. case CTC_SHA384wECDSA:
  554. return sigSha384wEcdsaName;
  555. #endif
  556. #ifdef WOLFSSL_SHA512
  557. case CTC_SHA512wECDSA:
  558. return sigSha512wEcdsaName;
  559. #endif
  560. #endif /* HAVE_ECC */
  561. default:
  562. return sigUnknownName;
  563. }
  564. }
  565. #if !defined(NO_DSA) || defined(HAVE_ECC) || !defined(NO_CERTS) || \
  566. (!defined(NO_RSA) && \
  567. (defined(WOLFSSL_CERT_GEN) || \
  568. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA))))
  569. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  570. *
  571. * len Length of data to encode.
  572. * firstByte First byte of data, most significant byte of integer, to encode.
  573. * output Buffer to write into.
  574. * returns the number of bytes added to the buffer.
  575. */
  576. int SetASNInt(int len, byte firstByte, byte* output)
  577. {
  578. word32 idx = 0;
  579. if (output)
  580. output[idx] = ASN_INTEGER;
  581. idx++;
  582. if (firstByte & 0x80)
  583. len++;
  584. idx += SetLength(len, output ? output + idx : NULL);
  585. if (firstByte & 0x80) {
  586. if (output)
  587. output[idx] = 0x00;
  588. idx++;
  589. }
  590. return idx;
  591. }
  592. #endif
  593. #if !defined(NO_DSA) || defined(HAVE_ECC) || (defined(WOLFSSL_CERT_GEN) && \
  594. !defined(NO_RSA)) || ((defined(WOLFSSL_KEY_GEN) || \
  595. defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  596. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  597. * The number is assumed to be positive.
  598. *
  599. * n Multi-precision integer to encode.
  600. * maxSz Maximum size of the encoded integer.
  601. * A negative value indicates no check of length requested.
  602. * output Buffer to write into.
  603. * returns BUFFER_E when the data is too long for the buffer.
  604. * MP_TO_E when encoding the integer fails.
  605. * Otherwise, the number of bytes added to the buffer.
  606. */
  607. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  608. {
  609. int idx = 0;
  610. int leadingBit;
  611. int length;
  612. int err;
  613. leadingBit = mp_leading_bit(n);
  614. length = mp_unsigned_bin_size(n);
  615. if (maxSz >= 0 && (1 + length + (leadingBit ? 1 : 0)) > maxSz)
  616. return BUFFER_E;
  617. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  618. if (maxSz >= 0 && (idx + length) > maxSz)
  619. return BUFFER_E;
  620. if (output) {
  621. err = mp_to_unsigned_bin(n, output + idx);
  622. if (err != MP_OKAY)
  623. return MP_TO_E;
  624. }
  625. idx += length;
  626. return idx;
  627. }
  628. #endif
  629. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && \
  630. (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  631. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  632. * an RSA key.
  633. * The number is assumed to be positive.
  634. *
  635. * n Multi-precision integer to encode.
  636. * output Buffer to write into.
  637. * returns BUFFER_E when the data is too long for the buffer.
  638. * MP_TO_E when encoding the integer fails.
  639. * Otherwise, the number of bytes added to the buffer.
  640. */
  641. static int SetASNIntRSA(void* n, byte* output)
  642. {
  643. int idx = 0;
  644. int leadingBit;
  645. int length;
  646. int err;
  647. leadingBit = wc_Rsa_leading_bit(n);
  648. length = wc_Rsa_unsigned_bin_size(n);
  649. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  650. if ((idx + length) > MAX_RSA_INT_SZ)
  651. return BUFFER_E;
  652. if (output) {
  653. err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  654. if (err != MP_OKAY)
  655. return MP_TO_E;
  656. }
  657. idx += length;
  658. return idx;
  659. }
  660. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  661. /* Windows header clash for WinCE using GetVersion */
  662. int GetMyVersion(const byte* input, word32* inOutIdx,
  663. int* version, word32 maxIdx)
  664. {
  665. word32 idx = *inOutIdx;
  666. byte tag;
  667. if ((idx + MIN_VERSION_SZ) > maxIdx)
  668. return ASN_PARSE_E;
  669. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  670. return ASN_PARSE_E;
  671. if (tag != ASN_INTEGER)
  672. return ASN_PARSE_E;
  673. if (input[idx++] != 0x01)
  674. return ASN_VERSION_E;
  675. *version = input[idx++];
  676. *inOutIdx = idx;
  677. return *version;
  678. }
  679. #ifndef NO_PWDBASED
  680. /* Get small count integer, 32 bits or less */
  681. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  682. {
  683. word32 idx = *inOutIdx;
  684. word32 len;
  685. byte tag;
  686. *number = 0;
  687. /* check for type and length bytes */
  688. if ((idx + 2) > maxIdx)
  689. return BUFFER_E;
  690. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  691. return ASN_PARSE_E;
  692. if (tag != ASN_INTEGER)
  693. return ASN_PARSE_E;
  694. len = input[idx++];
  695. if (len > 4)
  696. return ASN_PARSE_E;
  697. if (len + idx > maxIdx)
  698. return ASN_PARSE_E;
  699. while (len--) {
  700. *number = *number << 8 | input[idx++];
  701. }
  702. *inOutIdx = idx;
  703. return *number;
  704. }
  705. /* Set small integer, 32 bits or less. DER encoding with no leading 0s
  706. * returns total amount written including ASN tag and length byte on success */
  707. int SetShortInt(byte* input, word32* inOutIdx, word32 number, word32 maxIdx)
  708. {
  709. word32 idx = *inOutIdx;
  710. word32 len = 0;
  711. int i;
  712. byte ar[MAX_LENGTH_SZ];
  713. /* check for room for type and length bytes */
  714. if ((idx + 2) > maxIdx)
  715. return BUFFER_E;
  716. input[idx++] = ASN_INTEGER;
  717. idx++; /* place holder for length byte */
  718. if (MAX_LENGTH_SZ + idx > maxIdx)
  719. return ASN_PARSE_E;
  720. /* find first non zero byte */
  721. XMEMSET(ar, 0, MAX_LENGTH_SZ);
  722. c32toa(number, ar);
  723. for (i = 0; i < MAX_LENGTH_SZ; i++) {
  724. if (ar[i] != 0) {
  725. break;
  726. }
  727. }
  728. /* handle case of 0 */
  729. if (i == MAX_LENGTH_SZ) {
  730. input[idx++] = 0; len++;
  731. }
  732. for (; i < MAX_LENGTH_SZ && idx < maxIdx; i++) {
  733. input[idx++] = ar[i]; len++;
  734. }
  735. /* jump back to beginning of input buffer using unaltered inOutIdx value
  736. * and set number of bytes for integer, then update the index value */
  737. input[*inOutIdx + 1] = (byte)len;
  738. *inOutIdx = idx;
  739. return len + 2; /* size of integer bytes plus ASN TAG and length byte */
  740. }
  741. #endif /* !NO_PWDBASED */
  742. /* May not have one, not an error */
  743. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  744. word32 maxIdx)
  745. {
  746. word32 idx = *inOutIdx;
  747. byte tag;
  748. WOLFSSL_ENTER("GetExplicitVersion");
  749. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  750. return ASN_PARSE_E;
  751. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  752. int ret;
  753. *inOutIdx = ++idx; /* skip header */
  754. ret = GetMyVersion(input, inOutIdx, version, maxIdx);
  755. if (ret >= 0) {
  756. /* check if version is expected value rfc 5280 4.1 {0, 1, 2} */
  757. if (*version > MAX_X509_VERSION || *version < MIN_X509_VERSION) {
  758. WOLFSSL_MSG("Unexpected certificate version");
  759. ret = ASN_VERSION_E;
  760. }
  761. }
  762. return ret;
  763. }
  764. /* go back as is */
  765. *version = 0;
  766. return 0;
  767. }
  768. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  769. {
  770. word32 idx = *inOutIdx;
  771. int ret;
  772. int length;
  773. ret = GetASNInt(input, &idx, &length, maxIdx);
  774. if (ret != 0)
  775. return ret;
  776. if (mp_init(mpi) != MP_OKAY)
  777. return MP_INIT_E;
  778. if (mp_read_unsigned_bin(mpi, input + idx, length) != 0) {
  779. mp_clear(mpi);
  780. return ASN_GETINT_E;
  781. }
  782. #ifdef HAVE_WOLF_BIGINT
  783. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  784. mp_clear(mpi);
  785. return ASN_GETINT_E;
  786. }
  787. #endif /* HAVE_WOLF_BIGINT */
  788. *inOutIdx = idx + length;
  789. return 0;
  790. }
  791. #if (!defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)) \
  792. || defined(WOLFSSL_RSA_PUBLIC_ONLY) || (!defined(NO_DSA))
  793. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || !defined(NO_DSA)
  794. static int SkipInt(const byte* input, word32* inOutIdx, word32 maxIdx)
  795. {
  796. word32 idx = *inOutIdx;
  797. int ret;
  798. int length;
  799. ret = GetASNInt(input, &idx, &length, maxIdx);
  800. if (ret != 0)
  801. return ret;
  802. *inOutIdx = idx + length;
  803. return 0;
  804. }
  805. #endif
  806. #endif
  807. int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  808. word32 maxIdx, int zeroBits, byte* unusedBits)
  809. {
  810. word32 idx = *inOutIdx;
  811. int length;
  812. byte b;
  813. if (GetASNTag(input, &idx, &b, maxIdx) != 0) {
  814. return ASN_BITSTR_E;
  815. }
  816. if (b != ASN_BIT_STRING) {
  817. return ASN_BITSTR_E;
  818. }
  819. if (GetLength(input, &idx, &length, maxIdx) < 0)
  820. return ASN_PARSE_E;
  821. /* extra sanity check that length is greater than 0 */
  822. if (length <= 0) {
  823. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  824. return BUFFER_E;
  825. }
  826. if (idx + 1 > maxIdx) {
  827. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  828. return BUFFER_E;
  829. }
  830. b = input[idx];
  831. if (zeroBits && b != 0x00)
  832. return ASN_EXPECT_0_E;
  833. if (b >= 0x08)
  834. return ASN_PARSE_E;
  835. if (b != 0) {
  836. if ((byte)(input[idx + length - 1] << (8 - b)) != 0)
  837. return ASN_PARSE_E;
  838. }
  839. idx++;
  840. length--; /* length has been checked for greater than 0 */
  841. *inOutIdx = idx;
  842. if (len != NULL)
  843. *len = length;
  844. if (unusedBits != NULL)
  845. *unusedBits = b;
  846. return 0;
  847. }
  848. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 OR ED448 (with CertGen or
  849. * KeyGen) */
  850. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  851. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA))) || \
  852. (defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)) || \
  853. ((defined(HAVE_ED25519) || defined(HAVE_ED448)) && \
  854. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA))) || \
  855. (!defined(NO_DSA) && !defined(HAVE_SELFTEST) && defined(WOLFSSL_KEY_GEN))
  856. /* Set the DER/BER encoding of the ASN.1 BIT_STRING header.
  857. *
  858. * len Length of data to encode.
  859. * unusedBits The number of unused bits in the last byte of data.
  860. * That is, the number of least significant zero bits before a one.
  861. * The last byte is the most-significant non-zero byte of a number.
  862. * output Buffer to write into.
  863. * returns the number of bytes added to the buffer.
  864. */
  865. word32 SetBitString(word32 len, byte unusedBits, byte* output)
  866. {
  867. word32 idx = 0;
  868. if (output)
  869. output[idx] = ASN_BIT_STRING;
  870. idx++;
  871. idx += SetLength(len + 1, output ? output + idx : NULL);
  872. if (output)
  873. output[idx] = unusedBits;
  874. idx++;
  875. return idx;
  876. }
  877. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 || HAVE_ED448 */
  878. #ifdef ASN_BER_TO_DER
  879. /* Pull informtation from the ASN.1 BER encoded item header */
  880. static int GetBerHeader(const byte* data, word32* idx, word32 maxIdx,
  881. byte* pTag, word32* pLen, int* indef)
  882. {
  883. int len = 0;
  884. byte tag;
  885. word32 i = *idx;
  886. *indef = 0;
  887. /* Check there is enough data for a minimal header */
  888. if (i + 2 > maxIdx) {
  889. return ASN_PARSE_E;
  890. }
  891. /* Retrieve tag */
  892. tag = data[i++];
  893. /* Indefinite length handled specially */
  894. if (data[i] == 0x80) {
  895. /* Check valid tag for indefinite */
  896. if (((tag & 0xc0) == 0) && ((tag & ASN_CONSTRUCTED) == 0x00)) {
  897. return ASN_PARSE_E;
  898. }
  899. i++;
  900. *indef = 1;
  901. }
  902. else if (GetLength(data, &i, &len, maxIdx) < 0) {
  903. return ASN_PARSE_E;
  904. }
  905. /* Return tag, length and index after BER item header */
  906. *pTag = tag;
  907. *pLen = len;
  908. *idx = i;
  909. return 0;
  910. }
  911. #ifndef INDEF_ITEMS_MAX
  912. #define INDEF_ITEMS_MAX 20
  913. #endif
  914. /* Indef length item data */
  915. typedef struct Indef {
  916. word32 start;
  917. int depth;
  918. int headerLen;
  919. word32 len;
  920. } Indef;
  921. /* Indef length items */
  922. typedef struct IndefItems
  923. {
  924. Indef len[INDEF_ITEMS_MAX];
  925. int cnt;
  926. int idx;
  927. int depth;
  928. } IndefItems;
  929. /* Get header length of current item */
  930. static int IndefItems_HeaderLen(IndefItems* items)
  931. {
  932. return items->len[items->idx].headerLen;
  933. }
  934. /* Get data length of current item */
  935. static word32 IndefItems_Len(IndefItems* items)
  936. {
  937. return items->len[items->idx].len;
  938. }
  939. /* Add a indefinite length item */
  940. static int IndefItems_AddItem(IndefItems* items, word32 start)
  941. {
  942. int ret = 0;
  943. int i;
  944. if (items->cnt == INDEF_ITEMS_MAX) {
  945. ret = MEMORY_E;
  946. }
  947. else {
  948. i = items->cnt++;
  949. items->len[i].start = start;
  950. items->len[i].depth = items->depth++;
  951. items->len[i].headerLen = 1;
  952. items->len[i].len = 0;
  953. items->idx = i;
  954. }
  955. return ret;
  956. }
  957. /* Increase data length of current item */
  958. static void IndefItems_AddData(IndefItems* items, word32 length)
  959. {
  960. items->len[items->idx].len += length;
  961. }
  962. /* Update header length of current item to reflect data length */
  963. static void IndefItems_UpdateHeaderLen(IndefItems* items)
  964. {
  965. items->len[items->idx].headerLen +=
  966. SetLength(items->len[items->idx].len, NULL);
  967. }
  968. /* Go to indefinite parent of current item */
  969. static void IndefItems_Up(IndefItems* items)
  970. {
  971. int i;
  972. int depth = items->len[items->idx].depth - 1;
  973. for (i = items->cnt - 1; i >= 0; i--) {
  974. if (items->len[i].depth == depth) {
  975. break;
  976. }
  977. }
  978. items->idx = i;
  979. items->depth = depth + 1;
  980. }
  981. /* Calculate final length by adding length of indefinite child items */
  982. static void IndefItems_CalcLength(IndefItems* items)
  983. {
  984. int i;
  985. int idx = items->idx;
  986. for (i = idx + 1; i < items->cnt; i++) {
  987. if (items->len[i].depth == items->depth) {
  988. items->len[idx].len += items->len[i].headerLen;
  989. items->len[idx].len += items->len[i].len;
  990. }
  991. }
  992. items->len[idx].headerLen += SetLength(items->len[idx].len, NULL);
  993. }
  994. /* Add more data to indefinite length item */
  995. static void IndefItems_MoreData(IndefItems* items, word32 length)
  996. {
  997. if (items->cnt > 0 && items->idx >= 0) {
  998. items->len[items->idx].len += length;
  999. }
  1000. }
  1001. /* Convert a BER encoding with indefinite length items to DER.
  1002. *
  1003. * ber BER encoded data.
  1004. * berSz Length of BER encoded data.
  1005. * der Buffer to hold DER encoded version of data.
  1006. * NULL indicates only the length is required.
  1007. * derSz The size of the buffer to hold the DER encoded data.
  1008. * Will be set if der is NULL, otherwise the value is checked as der is
  1009. * filled.
  1010. * returns ASN_PARSE_E if the BER data is invalid and BAD_FUNC_ARG if ber or
  1011. * derSz are NULL.
  1012. */
  1013. int wc_BerToDer(const byte* ber, word32 berSz, byte* der, word32* derSz)
  1014. {
  1015. int ret = 0;
  1016. word32 i, j;
  1017. #ifdef WOLFSSL_SMALL_STACK
  1018. IndefItems* indefItems = NULL;
  1019. #else
  1020. IndefItems indefItems[1];
  1021. #endif
  1022. byte tag, basic;
  1023. word32 length;
  1024. int indef;
  1025. if (ber == NULL || derSz == NULL)
  1026. return BAD_FUNC_ARG;
  1027. #ifdef WOLFSSL_SMALL_STACK
  1028. indefItems = (IndefItems *)XMALLOC(sizeof(IndefItems), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1029. if (indefItems == NULL) {
  1030. ret = MEMORY_E;
  1031. goto end;
  1032. }
  1033. #endif
  1034. XMEMSET(indefItems, 0, sizeof(*indefItems));
  1035. /* Calculate indefinite item lengths */
  1036. for (i = 0; i < berSz; ) {
  1037. word32 start = i;
  1038. /* Get next BER item */
  1039. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  1040. if (ret != 0) {
  1041. goto end;
  1042. }
  1043. if (indef) {
  1044. /* Indefinite item - add to list */
  1045. ret = IndefItems_AddItem(indefItems, i);
  1046. if (ret != 0) {
  1047. goto end;
  1048. }
  1049. if ((tag & 0xC0) == 0 &&
  1050. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  1051. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  1052. /* Constructed basic type - get repeating tag */
  1053. basic = tag & (~ASN_CONSTRUCTED);
  1054. /* Add up lengths of each item below */
  1055. for (; i < berSz; ) {
  1056. /* Get next BER_item */
  1057. ret = GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  1058. if (ret != 0) {
  1059. goto end;
  1060. }
  1061. /* End of content closes item */
  1062. if (tag == ASN_EOC) {
  1063. /* Must be zero length */
  1064. if (length != 0) {
  1065. ret = ASN_PARSE_E;
  1066. goto end;
  1067. }
  1068. break;
  1069. }
  1070. /* Must not be indefinite and tag must match parent */
  1071. if (indef || tag != basic) {
  1072. ret = ASN_PARSE_E;
  1073. goto end;
  1074. }
  1075. /* Add to length */
  1076. IndefItems_AddData(indefItems, length);
  1077. /* Skip data */
  1078. i += length;
  1079. }
  1080. /* Ensure we got an EOC and not end of data */
  1081. if (tag != ASN_EOC) {
  1082. ret = ASN_PARSE_E;
  1083. goto end;
  1084. }
  1085. /* Set the header length to include the length field */
  1086. IndefItems_UpdateHeaderLen(indefItems);
  1087. /* Go to indefinte parent item */
  1088. IndefItems_Up(indefItems);
  1089. }
  1090. }
  1091. else if (tag == ASN_EOC) {
  1092. /* End-of-content must be 0 length */
  1093. if (length != 0) {
  1094. ret = ASN_PARSE_E;
  1095. goto end;
  1096. }
  1097. /* Check there is an item to close - missing EOC */
  1098. if (indefItems->depth == 0) {
  1099. ret = ASN_PARSE_E;
  1100. goto end;
  1101. }
  1102. /* Finish calculation of data length for indefinite item */
  1103. IndefItems_CalcLength(indefItems);
  1104. /* Go to indefinte parent item */
  1105. IndefItems_Up(indefItems);
  1106. }
  1107. else {
  1108. /* Known length item to add in - make sure enough data for it */
  1109. if (i + length > berSz) {
  1110. ret = ASN_PARSE_E;
  1111. goto end;
  1112. }
  1113. /* Include all data - can't have indefinite inside definite */
  1114. i += length;
  1115. /* Add entire item to current indefinite item */
  1116. IndefItems_MoreData(indefItems, i - start);
  1117. }
  1118. }
  1119. /* Check we had a EOC for each indefinite item */
  1120. if (indefItems->depth != 0) {
  1121. ret = ASN_PARSE_E;
  1122. goto end;
  1123. }
  1124. /* Write out DER */
  1125. j = 0;
  1126. /* Reset index */
  1127. indefItems->idx = 0;
  1128. for (i = 0; i < berSz; ) {
  1129. word32 start = i;
  1130. /* Get item - checked above */
  1131. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  1132. if (indef) {
  1133. if (der != NULL) {
  1134. /* Check enough space for header */
  1135. if (j + IndefItems_HeaderLen(indefItems) > *derSz) {
  1136. ret = BUFFER_E;
  1137. goto end;
  1138. }
  1139. if ((tag & 0xC0) == 0 &&
  1140. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  1141. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  1142. /* Remove constructed tag for basic types */
  1143. tag &= ~ASN_CONSTRUCTED;
  1144. }
  1145. /* Add tag and length */
  1146. der[j] = tag;
  1147. (void)SetLength(IndefItems_Len(indefItems), der + j + 1);
  1148. }
  1149. /* Add header length of indefinite item */
  1150. j += IndefItems_HeaderLen(indefItems);
  1151. if ((tag & 0xC0) == 0 &&
  1152. tag != (ASN_SEQUENCE | ASN_CONSTRUCTED) &&
  1153. tag != (ASN_SET | ASN_CONSTRUCTED)) {
  1154. /* For basic type - get each child item and add data */
  1155. for (; i < berSz; ) {
  1156. (void)GetBerHeader(ber, &i, berSz, &tag, &length, &indef);
  1157. if (tag == ASN_EOC) {
  1158. break;
  1159. }
  1160. if (der != NULL) {
  1161. if (j + length > *derSz) {
  1162. ret = BUFFER_E;
  1163. goto end;
  1164. }
  1165. XMEMCPY(der + j, ber + i, length);
  1166. }
  1167. j += length;
  1168. i += length;
  1169. }
  1170. }
  1171. /* Move to next indef item in list */
  1172. indefItems->idx++;
  1173. }
  1174. else if (tag == ASN_EOC) {
  1175. /* End-Of-Content is not written out in DER */
  1176. }
  1177. else {
  1178. /* Write out definite length item as is. */
  1179. i += length;
  1180. if (der != NULL) {
  1181. /* Ensure space for item */
  1182. if (j + i - start > *derSz) {
  1183. ret = BUFFER_E;
  1184. goto end;
  1185. }
  1186. /* Copy item as is */
  1187. XMEMCPY(der + j, ber + start, i - start);
  1188. }
  1189. j += i - start;
  1190. }
  1191. }
  1192. /* Return the length of the DER encoded ASN.1 */
  1193. *derSz = j;
  1194. if (der == NULL) {
  1195. ret = LENGTH_ONLY_E;
  1196. }
  1197. end:
  1198. #ifdef WOLFSSL_SMALL_STACK
  1199. if (indefItems != NULL) {
  1200. XFREE(indefItems, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1201. }
  1202. #endif
  1203. return ret;
  1204. }
  1205. #endif
  1206. #if defined(WOLFSSL_CERT_EXT) && defined(WOLFSSL_CERT_GEN)
  1207. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  1208. *
  1209. * val 16-bit value to encode.
  1210. * output Buffer to write into.
  1211. * returns the number of bytes added to the buffer.
  1212. */
  1213. static word32 SetBitString16Bit(word16 val, byte* output)
  1214. {
  1215. word32 idx;
  1216. int len;
  1217. byte lastByte;
  1218. byte unusedBits = 0;
  1219. if ((val >> 8) != 0) {
  1220. len = 2;
  1221. lastByte = (byte)(val >> 8);
  1222. }
  1223. else {
  1224. len = 1;
  1225. lastByte = (byte)val;
  1226. }
  1227. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  1228. unusedBits++;
  1229. idx = SetBitString(len, unusedBits, output);
  1230. output[idx++] = (byte)val;
  1231. if (len > 1)
  1232. output[idx++] = (byte)(val >> 8);
  1233. return idx;
  1234. }
  1235. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_CERT_GEN */
  1236. /* hashType */
  1237. #ifdef WOLFSSL_MD2
  1238. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  1239. #endif
  1240. #ifndef NO_MD5
  1241. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  1242. #endif
  1243. #ifndef NO_SHA
  1244. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  1245. #endif
  1246. #ifdef WOLFSSL_SHA224
  1247. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  1248. #endif
  1249. #ifndef NO_SHA256
  1250. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  1251. #endif
  1252. #ifdef WOLFSSL_SHA384
  1253. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  1254. #endif
  1255. #ifdef WOLFSSL_SHA512
  1256. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  1257. #endif
  1258. /* hmacType */
  1259. #ifndef NO_HMAC
  1260. #ifdef WOLFSSL_SHA224
  1261. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  1262. #endif
  1263. #ifndef NO_SHA256
  1264. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  1265. #endif
  1266. #ifdef WOLFSSL_SHA384
  1267. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  1268. #endif
  1269. #ifdef WOLFSSL_SHA512
  1270. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  1271. #endif
  1272. #endif
  1273. /* sigType */
  1274. #if !defined(NO_DSA) && !defined(NO_SHA)
  1275. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  1276. static const byte sigSha256wDsaOid[] = {96, 134, 72, 1, 101, 3, 4, 3, 2};
  1277. #endif /* NO_DSA */
  1278. #ifndef NO_RSA
  1279. #ifdef WOLFSSL_MD2
  1280. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  1281. #endif
  1282. #ifndef NO_MD5
  1283. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  1284. #endif
  1285. #ifndef NO_SHA
  1286. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  1287. #endif
  1288. #ifdef WOLFSSL_SHA224
  1289. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  1290. #endif
  1291. #ifndef NO_SHA256
  1292. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  1293. #endif
  1294. #ifdef WOLFSSL_SHA384
  1295. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  1296. #endif
  1297. #ifdef WOLFSSL_SHA512
  1298. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  1299. #endif
  1300. #endif /* NO_RSA */
  1301. #ifdef HAVE_ECC
  1302. #ifndef NO_SHA
  1303. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  1304. #endif
  1305. #ifdef WOLFSSL_SHA224
  1306. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  1307. #endif
  1308. #ifndef NO_SHA256
  1309. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  1310. #endif
  1311. #ifdef WOLFSSL_SHA384
  1312. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  1313. #endif
  1314. #ifdef WOLFSSL_SHA512
  1315. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  1316. #endif
  1317. #endif /* HAVE_ECC */
  1318. #ifdef HAVE_ED25519
  1319. static const byte sigEd25519Oid[] = {43, 101, 112};
  1320. #endif /* HAVE_ED25519 */
  1321. #ifdef HAVE_ED448
  1322. static const byte sigEd448Oid[] = {43, 101, 113};
  1323. #endif /* HAVE_ED448 */
  1324. /* keyType */
  1325. #ifndef NO_DSA
  1326. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  1327. #endif /* NO_DSA */
  1328. #ifndef NO_RSA
  1329. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  1330. #endif /* NO_RSA */
  1331. #ifdef HAVE_NTRU
  1332. static const byte keyNtruOid[] = {43, 6, 1, 4, 1, 193, 22, 1, 1, 1, 1};
  1333. #endif /* HAVE_NTRU */
  1334. #ifdef HAVE_ECC
  1335. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  1336. #endif /* HAVE_ECC */
  1337. #ifdef HAVE_ED25519
  1338. static const byte keyEd25519Oid[] = {43, 101, 112};
  1339. #endif /* HAVE_ED25519 */
  1340. #ifdef HAVE_ED448
  1341. static const byte keyEd448Oid[] = {43, 101, 113};
  1342. #endif /* HAVE_ED448 */
  1343. #ifndef NO_DH
  1344. static const byte keyDhOid[] = {42, 134, 72, 134, 247, 13, 1, 3, 1};
  1345. #endif /* !NO_DH */
  1346. /* curveType */
  1347. #ifdef HAVE_ECC
  1348. /* See "ecc_sets" table in ecc.c */
  1349. #endif /* HAVE_ECC */
  1350. #ifdef HAVE_AES_CBC
  1351. /* blkType */
  1352. #ifdef WOLFSSL_AES_128
  1353. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  1354. #endif
  1355. #ifdef WOLFSSL_AES_192
  1356. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  1357. #endif
  1358. #ifdef WOLFSSL_AES_256
  1359. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  1360. #endif
  1361. #endif /* HAVE_AES_CBC */
  1362. #ifdef HAVE_AESGCM
  1363. #ifdef WOLFSSL_AES_128
  1364. static const byte blkAes128GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 6};
  1365. #endif
  1366. #ifdef WOLFSSL_AES_192
  1367. static const byte blkAes192GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 26};
  1368. #endif
  1369. #ifdef WOLFSSL_AES_256
  1370. static const byte blkAes256GcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 46};
  1371. #endif
  1372. #endif /* HAVE_AESGCM */
  1373. #ifdef HAVE_AESCCM
  1374. #ifdef WOLFSSL_AES_128
  1375. static const byte blkAes128CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 7};
  1376. #endif
  1377. #ifdef WOLFSSL_AES_192
  1378. static const byte blkAes192CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 27};
  1379. #endif
  1380. #ifdef WOLFSSL_AES_256
  1381. static const byte blkAes256CcmOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 47};
  1382. #endif
  1383. #endif /* HAVE_AESCCM */
  1384. #ifndef NO_DES3
  1385. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  1386. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  1387. #endif
  1388. /* keyWrapType */
  1389. #ifdef WOLFSSL_AES_128
  1390. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  1391. #endif
  1392. #ifdef WOLFSSL_AES_192
  1393. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  1394. #endif
  1395. #ifdef WOLFSSL_AES_256
  1396. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  1397. #endif
  1398. #ifdef HAVE_PKCS7
  1399. /* From RFC 3211 */
  1400. static const byte wrapPwriKekOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3,9};
  1401. #endif
  1402. /* cmsKeyAgreeType */
  1403. #ifndef NO_SHA
  1404. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  1405. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  1406. #endif
  1407. #ifdef WOLFSSL_SHA224
  1408. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  1409. #endif
  1410. #ifndef NO_SHA256
  1411. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  1412. #endif
  1413. #ifdef WOLFSSL_SHA384
  1414. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  1415. #endif
  1416. #ifdef WOLFSSL_SHA512
  1417. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  1418. #endif
  1419. /* ocspType */
  1420. #ifdef HAVE_OCSP
  1421. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  1422. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  1423. static const byte ocspNoCheckOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 5};
  1424. #endif /* HAVE_OCSP */
  1425. /* certExtType */
  1426. static const byte extBasicCaOid[] = {85, 29, 19};
  1427. static const byte extAltNamesOid[] = {85, 29, 17};
  1428. static const byte extCrlDistOid[] = {85, 29, 31};
  1429. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  1430. static const byte extAuthKeyOid[] = {85, 29, 35};
  1431. static const byte extSubjKeyOid[] = {85, 29, 14};
  1432. static const byte extCertPolicyOid[] = {85, 29, 32};
  1433. static const byte extKeyUsageOid[] = {85, 29, 15};
  1434. static const byte extInhibitAnyOid[] = {85, 29, 54};
  1435. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  1436. #ifndef IGNORE_NAME_CONSTRAINTS
  1437. static const byte extNameConsOid[] = {85, 29, 30};
  1438. #endif
  1439. /* certAuthInfoType */
  1440. #ifdef HAVE_OCSP
  1441. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  1442. #endif
  1443. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  1444. /* certPolicyType */
  1445. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  1446. /* certKeyUseType */
  1447. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  1448. /* certKeyUseType */
  1449. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  1450. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  1451. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  1452. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  1453. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  1454. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  1455. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  1456. #ifdef WOLFSSL_CERT_REQ
  1457. /* csrAttrType */
  1458. static const byte attrChallengePasswordOid[] = {42, 134, 72, 134, 247, 13, 1, 9, 7};
  1459. static const byte attrSerialNumberOid[] = {85, 4, 5};
  1460. #endif
  1461. /* kdfType */
  1462. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  1463. /* PKCS5 */
  1464. #if !defined(NO_DES3) && !defined(NO_SHA)
  1465. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  1466. #endif
  1467. static const byte pbes2[] = {42, 134, 72, 134, 247, 13, 1, 5, 13};
  1468. /* PKCS12 */
  1469. #if !defined(NO_RC4) && !defined(NO_SHA)
  1470. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  1471. #endif
  1472. #if !defined(NO_DES3) && !defined(NO_SHA)
  1473. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  1474. #endif
  1475. #ifdef HAVE_LIBZ
  1476. /* zlib compression */
  1477. static const byte zlibCompress[] = {42, 134, 72, 134, 247, 13, 1, 9, 16, 3, 8};
  1478. #endif
  1479. #ifdef WOLFSSL_APACHE_HTTPD
  1480. /* tlsExtType */
  1481. static const byte tlsFeatureOid[] = {43, 6, 1, 5, 5, 7, 1, 24};
  1482. /* certNameType */
  1483. static const byte dnsSRVOid[] = {43, 6, 1, 5, 5, 7, 8, 7};
  1484. #endif
  1485. /* returns a pointer to the OID string on success and NULL on fail */
  1486. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  1487. {
  1488. const byte* oid = NULL;
  1489. *oidSz = 0;
  1490. switch (type) {
  1491. case oidHashType:
  1492. switch (id) {
  1493. #ifdef WOLFSSL_MD2
  1494. case MD2h:
  1495. oid = hashMd2hOid;
  1496. *oidSz = sizeof(hashMd2hOid);
  1497. break;
  1498. #endif
  1499. #ifndef NO_MD5
  1500. case MD5h:
  1501. oid = hashMd5hOid;
  1502. *oidSz = sizeof(hashMd5hOid);
  1503. break;
  1504. #endif
  1505. #ifndef NO_SHA
  1506. case SHAh:
  1507. oid = hashSha1hOid;
  1508. *oidSz = sizeof(hashSha1hOid);
  1509. break;
  1510. #endif
  1511. #ifdef WOLFSSL_SHA224
  1512. case SHA224h:
  1513. oid = hashSha224hOid;
  1514. *oidSz = sizeof(hashSha224hOid);
  1515. break;
  1516. #endif
  1517. #ifndef NO_SHA256
  1518. case SHA256h:
  1519. oid = hashSha256hOid;
  1520. *oidSz = sizeof(hashSha256hOid);
  1521. break;
  1522. #endif
  1523. #ifdef WOLFSSL_SHA384
  1524. case SHA384h:
  1525. oid = hashSha384hOid;
  1526. *oidSz = sizeof(hashSha384hOid);
  1527. break;
  1528. #endif
  1529. #ifdef WOLFSSL_SHA512
  1530. case SHA512h:
  1531. oid = hashSha512hOid;
  1532. *oidSz = sizeof(hashSha512hOid);
  1533. break;
  1534. #endif
  1535. default:
  1536. break;
  1537. }
  1538. break;
  1539. case oidSigType:
  1540. switch (id) {
  1541. #if !defined(NO_DSA) && !defined(NO_SHA)
  1542. case CTC_SHAwDSA:
  1543. oid = sigSha1wDsaOid;
  1544. *oidSz = sizeof(sigSha1wDsaOid);
  1545. break;
  1546. case CTC_SHA256wDSA:
  1547. oid = sigSha256wDsaOid;
  1548. *oidSz = sizeof(sigSha256wDsaOid);
  1549. break;
  1550. #endif /* NO_DSA */
  1551. #ifndef NO_RSA
  1552. #ifdef WOLFSSL_MD2
  1553. case CTC_MD2wRSA:
  1554. oid = sigMd2wRsaOid;
  1555. *oidSz = sizeof(sigMd2wRsaOid);
  1556. break;
  1557. #endif
  1558. #ifndef NO_MD5
  1559. case CTC_MD5wRSA:
  1560. oid = sigMd5wRsaOid;
  1561. *oidSz = sizeof(sigMd5wRsaOid);
  1562. break;
  1563. #endif
  1564. #ifndef NO_SHA
  1565. case CTC_SHAwRSA:
  1566. oid = sigSha1wRsaOid;
  1567. *oidSz = sizeof(sigSha1wRsaOid);
  1568. break;
  1569. #endif
  1570. #ifdef WOLFSSL_SHA224
  1571. case CTC_SHA224wRSA:
  1572. oid = sigSha224wRsaOid;
  1573. *oidSz = sizeof(sigSha224wRsaOid);
  1574. break;
  1575. #endif
  1576. #ifndef NO_SHA256
  1577. case CTC_SHA256wRSA:
  1578. oid = sigSha256wRsaOid;
  1579. *oidSz = sizeof(sigSha256wRsaOid);
  1580. break;
  1581. #endif
  1582. #ifdef WOLFSSL_SHA384
  1583. case CTC_SHA384wRSA:
  1584. oid = sigSha384wRsaOid;
  1585. *oidSz = sizeof(sigSha384wRsaOid);
  1586. break;
  1587. #endif
  1588. #ifdef WOLFSSL_SHA512
  1589. case CTC_SHA512wRSA:
  1590. oid = sigSha512wRsaOid;
  1591. *oidSz = sizeof(sigSha512wRsaOid);
  1592. break;
  1593. #endif /* WOLFSSL_SHA512 */
  1594. #endif /* NO_RSA */
  1595. #ifdef HAVE_ECC
  1596. #ifndef NO_SHA
  1597. case CTC_SHAwECDSA:
  1598. oid = sigSha1wEcdsaOid;
  1599. *oidSz = sizeof(sigSha1wEcdsaOid);
  1600. break;
  1601. #endif
  1602. #ifdef WOLFSSL_SHA224
  1603. case CTC_SHA224wECDSA:
  1604. oid = sigSha224wEcdsaOid;
  1605. *oidSz = sizeof(sigSha224wEcdsaOid);
  1606. break;
  1607. #endif
  1608. #ifndef NO_SHA256
  1609. case CTC_SHA256wECDSA:
  1610. oid = sigSha256wEcdsaOid;
  1611. *oidSz = sizeof(sigSha256wEcdsaOid);
  1612. break;
  1613. #endif
  1614. #ifdef WOLFSSL_SHA384
  1615. case CTC_SHA384wECDSA:
  1616. oid = sigSha384wEcdsaOid;
  1617. *oidSz = sizeof(sigSha384wEcdsaOid);
  1618. break;
  1619. #endif
  1620. #ifdef WOLFSSL_SHA512
  1621. case CTC_SHA512wECDSA:
  1622. oid = sigSha512wEcdsaOid;
  1623. *oidSz = sizeof(sigSha512wEcdsaOid);
  1624. break;
  1625. #endif
  1626. #endif /* HAVE_ECC */
  1627. #ifdef HAVE_ED25519
  1628. case CTC_ED25519:
  1629. oid = sigEd25519Oid;
  1630. *oidSz = sizeof(sigEd25519Oid);
  1631. break;
  1632. #endif
  1633. #ifdef HAVE_ED448
  1634. case CTC_ED448:
  1635. oid = sigEd448Oid;
  1636. *oidSz = sizeof(sigEd448Oid);
  1637. break;
  1638. #endif
  1639. default:
  1640. break;
  1641. }
  1642. break;
  1643. case oidKeyType:
  1644. switch (id) {
  1645. #ifndef NO_DSA
  1646. case DSAk:
  1647. oid = keyDsaOid;
  1648. *oidSz = sizeof(keyDsaOid);
  1649. break;
  1650. #endif /* NO_DSA */
  1651. #ifndef NO_RSA
  1652. case RSAk:
  1653. oid = keyRsaOid;
  1654. *oidSz = sizeof(keyRsaOid);
  1655. break;
  1656. #endif /* NO_RSA */
  1657. #ifdef HAVE_NTRU
  1658. case NTRUk:
  1659. oid = keyNtruOid;
  1660. *oidSz = sizeof(keyNtruOid);
  1661. break;
  1662. #endif /* HAVE_NTRU */
  1663. #ifdef HAVE_ECC
  1664. case ECDSAk:
  1665. oid = keyEcdsaOid;
  1666. *oidSz = sizeof(keyEcdsaOid);
  1667. break;
  1668. #endif /* HAVE_ECC */
  1669. #ifdef HAVE_ED25519
  1670. case ED25519k:
  1671. oid = keyEd25519Oid;
  1672. *oidSz = sizeof(keyEd25519Oid);
  1673. break;
  1674. #endif /* HAVE_ED25519 */
  1675. #ifdef HAVE_ED448
  1676. case ED448k:
  1677. oid = keyEd448Oid;
  1678. *oidSz = sizeof(keyEd448Oid);
  1679. break;
  1680. #endif /* HAVE_ED448 */
  1681. #ifndef NO_DH
  1682. case DHk:
  1683. oid = keyDhOid;
  1684. *oidSz = sizeof(keyDhOid);
  1685. break;
  1686. #endif /* !NO_DH */
  1687. default:
  1688. break;
  1689. }
  1690. break;
  1691. #ifdef HAVE_ECC
  1692. case oidCurveType:
  1693. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  1694. WOLFSSL_MSG("ECC OID not found");
  1695. }
  1696. break;
  1697. #endif /* HAVE_ECC */
  1698. case oidBlkType:
  1699. switch (id) {
  1700. #ifdef HAVE_AES_CBC
  1701. #ifdef WOLFSSL_AES_128
  1702. case AES128CBCb:
  1703. oid = blkAes128CbcOid;
  1704. *oidSz = sizeof(blkAes128CbcOid);
  1705. break;
  1706. #endif
  1707. #ifdef WOLFSSL_AES_192
  1708. case AES192CBCb:
  1709. oid = blkAes192CbcOid;
  1710. *oidSz = sizeof(blkAes192CbcOid);
  1711. break;
  1712. #endif
  1713. #ifdef WOLFSSL_AES_256
  1714. case AES256CBCb:
  1715. oid = blkAes256CbcOid;
  1716. *oidSz = sizeof(blkAes256CbcOid);
  1717. break;
  1718. #endif
  1719. #endif /* HAVE_AES_CBC */
  1720. #ifdef HAVE_AESGCM
  1721. #ifdef WOLFSSL_AES_128
  1722. case AES128GCMb:
  1723. oid = blkAes128GcmOid;
  1724. *oidSz = sizeof(blkAes128GcmOid);
  1725. break;
  1726. #endif
  1727. #ifdef WOLFSSL_AES_192
  1728. case AES192GCMb:
  1729. oid = blkAes192GcmOid;
  1730. *oidSz = sizeof(blkAes192GcmOid);
  1731. break;
  1732. #endif
  1733. #ifdef WOLFSSL_AES_256
  1734. case AES256GCMb:
  1735. oid = blkAes256GcmOid;
  1736. *oidSz = sizeof(blkAes256GcmOid);
  1737. break;
  1738. #endif
  1739. #endif /* HAVE_AESGCM */
  1740. #ifdef HAVE_AESCCM
  1741. #ifdef WOLFSSL_AES_128
  1742. case AES128CCMb:
  1743. oid = blkAes128CcmOid;
  1744. *oidSz = sizeof(blkAes128CcmOid);
  1745. break;
  1746. #endif
  1747. #ifdef WOLFSSL_AES_192
  1748. case AES192CCMb:
  1749. oid = blkAes192CcmOid;
  1750. *oidSz = sizeof(blkAes192CcmOid);
  1751. break;
  1752. #endif
  1753. #ifdef WOLFSSL_AES_256
  1754. case AES256CCMb:
  1755. oid = blkAes256CcmOid;
  1756. *oidSz = sizeof(blkAes256CcmOid);
  1757. break;
  1758. #endif
  1759. #endif /* HAVE_AESCCM */
  1760. #ifndef NO_DES3
  1761. case DESb:
  1762. oid = blkDesCbcOid;
  1763. *oidSz = sizeof(blkDesCbcOid);
  1764. break;
  1765. case DES3b:
  1766. oid = blkDes3CbcOid;
  1767. *oidSz = sizeof(blkDes3CbcOid);
  1768. break;
  1769. #endif /* !NO_DES3 */
  1770. default:
  1771. break;
  1772. }
  1773. break;
  1774. #ifdef HAVE_OCSP
  1775. case oidOcspType:
  1776. switch (id) {
  1777. case OCSP_BASIC_OID:
  1778. oid = ocspBasicOid;
  1779. *oidSz = sizeof(ocspBasicOid);
  1780. break;
  1781. case OCSP_NONCE_OID:
  1782. oid = ocspNonceOid;
  1783. *oidSz = sizeof(ocspNonceOid);
  1784. break;
  1785. default:
  1786. break;
  1787. }
  1788. break;
  1789. #endif /* HAVE_OCSP */
  1790. case oidCertExtType:
  1791. switch (id) {
  1792. case BASIC_CA_OID:
  1793. oid = extBasicCaOid;
  1794. *oidSz = sizeof(extBasicCaOid);
  1795. break;
  1796. case ALT_NAMES_OID:
  1797. oid = extAltNamesOid;
  1798. *oidSz = sizeof(extAltNamesOid);
  1799. break;
  1800. case CRL_DIST_OID:
  1801. oid = extCrlDistOid;
  1802. *oidSz = sizeof(extCrlDistOid);
  1803. break;
  1804. case AUTH_INFO_OID:
  1805. oid = extAuthInfoOid;
  1806. *oidSz = sizeof(extAuthInfoOid);
  1807. break;
  1808. case AUTH_KEY_OID:
  1809. oid = extAuthKeyOid;
  1810. *oidSz = sizeof(extAuthKeyOid);
  1811. break;
  1812. case SUBJ_KEY_OID:
  1813. oid = extSubjKeyOid;
  1814. *oidSz = sizeof(extSubjKeyOid);
  1815. break;
  1816. case CERT_POLICY_OID:
  1817. oid = extCertPolicyOid;
  1818. *oidSz = sizeof(extCertPolicyOid);
  1819. break;
  1820. case KEY_USAGE_OID:
  1821. oid = extKeyUsageOid;
  1822. *oidSz = sizeof(extKeyUsageOid);
  1823. break;
  1824. case INHIBIT_ANY_OID:
  1825. oid = extInhibitAnyOid;
  1826. *oidSz = sizeof(extInhibitAnyOid);
  1827. break;
  1828. case EXT_KEY_USAGE_OID:
  1829. oid = extExtKeyUsageOid;
  1830. *oidSz = sizeof(extExtKeyUsageOid);
  1831. break;
  1832. #ifndef IGNORE_NAME_CONSTRAINTS
  1833. case NAME_CONS_OID:
  1834. oid = extNameConsOid;
  1835. *oidSz = sizeof(extNameConsOid);
  1836. break;
  1837. #endif
  1838. #ifdef HAVE_OCSP
  1839. case OCSP_NOCHECK_OID:
  1840. oid = ocspNoCheckOid;
  1841. *oidSz = sizeof(ocspNoCheckOid);
  1842. break;
  1843. #endif
  1844. default:
  1845. break;
  1846. }
  1847. break;
  1848. case oidCrlExtType:
  1849. #ifdef HAVE_CRL
  1850. switch (id) {
  1851. case AUTH_KEY_OID:
  1852. oid = extAuthKeyOid;
  1853. *oidSz = sizeof(extAuthKeyOid);
  1854. break;
  1855. default:
  1856. break;
  1857. }
  1858. #endif
  1859. break;
  1860. case oidCertAuthInfoType:
  1861. switch (id) {
  1862. #ifdef HAVE_OCSP
  1863. case AIA_OCSP_OID:
  1864. oid = extAuthInfoOcspOid;
  1865. *oidSz = sizeof(extAuthInfoOcspOid);
  1866. break;
  1867. #endif
  1868. case AIA_CA_ISSUER_OID:
  1869. oid = extAuthInfoCaIssuerOid;
  1870. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  1871. break;
  1872. default:
  1873. break;
  1874. }
  1875. break;
  1876. case oidCertPolicyType:
  1877. switch (id) {
  1878. case CP_ANY_OID:
  1879. oid = extCertPolicyAnyOid;
  1880. *oidSz = sizeof(extCertPolicyAnyOid);
  1881. break;
  1882. default:
  1883. break;
  1884. }
  1885. break;
  1886. case oidCertAltNameType:
  1887. switch (id) {
  1888. case HW_NAME_OID:
  1889. oid = extAltNamesHwNameOid;
  1890. *oidSz = sizeof(extAltNamesHwNameOid);
  1891. break;
  1892. default:
  1893. break;
  1894. }
  1895. break;
  1896. case oidCertKeyUseType:
  1897. switch (id) {
  1898. case EKU_ANY_OID:
  1899. oid = extExtKeyUsageAnyOid;
  1900. *oidSz = sizeof(extExtKeyUsageAnyOid);
  1901. break;
  1902. case EKU_SERVER_AUTH_OID:
  1903. oid = extExtKeyUsageServerAuthOid;
  1904. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  1905. break;
  1906. case EKU_CLIENT_AUTH_OID:
  1907. oid = extExtKeyUsageClientAuthOid;
  1908. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  1909. break;
  1910. case EKU_CODESIGNING_OID:
  1911. oid = extExtKeyUsageCodeSigningOid;
  1912. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  1913. break;
  1914. case EKU_EMAILPROTECT_OID:
  1915. oid = extExtKeyUsageEmailProtectOid;
  1916. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  1917. break;
  1918. case EKU_TIMESTAMP_OID:
  1919. oid = extExtKeyUsageTimestampOid;
  1920. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  1921. break;
  1922. case EKU_OCSP_SIGN_OID:
  1923. oid = extExtKeyUsageOcspSignOid;
  1924. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  1925. break;
  1926. default:
  1927. break;
  1928. }
  1929. break;
  1930. case oidKdfType:
  1931. switch (id) {
  1932. case PBKDF2_OID:
  1933. oid = pbkdf2Oid;
  1934. *oidSz = sizeof(pbkdf2Oid);
  1935. break;
  1936. default:
  1937. break;
  1938. }
  1939. break;
  1940. case oidPBEType:
  1941. switch (id) {
  1942. #if !defined(NO_SHA) && !defined(NO_RC4)
  1943. case PBE_SHA1_RC4_128:
  1944. oid = pbeSha1RC4128;
  1945. *oidSz = sizeof(pbeSha1RC4128);
  1946. break;
  1947. #endif
  1948. #if !defined(NO_SHA) && !defined(NO_DES3)
  1949. case PBE_SHA1_DES:
  1950. oid = pbeSha1Des;
  1951. *oidSz = sizeof(pbeSha1Des);
  1952. break;
  1953. #endif
  1954. #if !defined(NO_SHA) && !defined(NO_DES3)
  1955. case PBE_SHA1_DES3:
  1956. oid = pbeSha1Des3;
  1957. *oidSz = sizeof(pbeSha1Des3);
  1958. break;
  1959. #endif
  1960. case PBES2:
  1961. oid = pbes2;
  1962. *oidSz = sizeof(pbes2);
  1963. break;
  1964. default:
  1965. break;
  1966. }
  1967. break;
  1968. case oidKeyWrapType:
  1969. switch (id) {
  1970. #ifdef WOLFSSL_AES_128
  1971. case AES128_WRAP:
  1972. oid = wrapAes128Oid;
  1973. *oidSz = sizeof(wrapAes128Oid);
  1974. break;
  1975. #endif
  1976. #ifdef WOLFSSL_AES_192
  1977. case AES192_WRAP:
  1978. oid = wrapAes192Oid;
  1979. *oidSz = sizeof(wrapAes192Oid);
  1980. break;
  1981. #endif
  1982. #ifdef WOLFSSL_AES_256
  1983. case AES256_WRAP:
  1984. oid = wrapAes256Oid;
  1985. *oidSz = sizeof(wrapAes256Oid);
  1986. break;
  1987. #endif
  1988. #ifdef HAVE_PKCS7
  1989. case PWRI_KEK_WRAP:
  1990. oid = wrapPwriKekOid;
  1991. *oidSz = sizeof(wrapPwriKekOid);
  1992. break;
  1993. #endif
  1994. default:
  1995. break;
  1996. }
  1997. break;
  1998. case oidCmsKeyAgreeType:
  1999. switch (id) {
  2000. #ifndef NO_SHA
  2001. case dhSinglePass_stdDH_sha1kdf_scheme:
  2002. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  2003. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  2004. break;
  2005. #endif
  2006. #ifdef WOLFSSL_SHA224
  2007. case dhSinglePass_stdDH_sha224kdf_scheme:
  2008. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  2009. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  2010. break;
  2011. #endif
  2012. #ifndef NO_SHA256
  2013. case dhSinglePass_stdDH_sha256kdf_scheme:
  2014. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  2015. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  2016. break;
  2017. #endif
  2018. #ifdef WOLFSSL_SHA384
  2019. case dhSinglePass_stdDH_sha384kdf_scheme:
  2020. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  2021. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  2022. break;
  2023. #endif
  2024. #ifdef WOLFSSL_SHA512
  2025. case dhSinglePass_stdDH_sha512kdf_scheme:
  2026. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  2027. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  2028. break;
  2029. #endif
  2030. default:
  2031. break;
  2032. }
  2033. break;
  2034. #ifndef NO_HMAC
  2035. case oidHmacType:
  2036. switch (id) {
  2037. #ifdef WOLFSSL_SHA224
  2038. case HMAC_SHA224_OID:
  2039. oid = hmacSha224Oid;
  2040. *oidSz = sizeof(hmacSha224Oid);
  2041. break;
  2042. #endif
  2043. #ifndef NO_SHA256
  2044. case HMAC_SHA256_OID:
  2045. oid = hmacSha256Oid;
  2046. *oidSz = sizeof(hmacSha256Oid);
  2047. break;
  2048. #endif
  2049. #ifdef WOLFSSL_SHA384
  2050. case HMAC_SHA384_OID:
  2051. oid = hmacSha384Oid;
  2052. *oidSz = sizeof(hmacSha384Oid);
  2053. break;
  2054. #endif
  2055. #ifdef WOLFSSL_SHA512
  2056. case HMAC_SHA512_OID:
  2057. oid = hmacSha512Oid;
  2058. *oidSz = sizeof(hmacSha512Oid);
  2059. break;
  2060. #endif
  2061. default:
  2062. break;
  2063. }
  2064. break;
  2065. #endif /* !NO_HMAC */
  2066. #ifdef HAVE_LIBZ
  2067. case oidCompressType:
  2068. switch (id) {
  2069. case ZLIBc:
  2070. oid = zlibCompress;
  2071. *oidSz = sizeof(zlibCompress);
  2072. break;
  2073. default:
  2074. break;
  2075. }
  2076. break;
  2077. #endif /* HAVE_LIBZ */
  2078. #ifdef WOLFSSL_APACHE_HTTPD
  2079. case oidCertNameType:
  2080. switch (id) {
  2081. case NID_id_on_dnsSRV:
  2082. oid = dnsSRVOid;
  2083. *oidSz = sizeof(dnsSRVOid);
  2084. break;
  2085. default:
  2086. break;
  2087. }
  2088. break;
  2089. case oidTlsExtType:
  2090. switch (id) {
  2091. case TLS_FEATURE_OID:
  2092. oid = tlsFeatureOid;
  2093. *oidSz = sizeof(tlsFeatureOid);
  2094. break;
  2095. default:
  2096. break;
  2097. }
  2098. break;
  2099. #endif /* WOLFSSL_APACHE_HTTPD */
  2100. #ifdef WOLFSSL_CERT_REQ
  2101. case oidCsrAttrType:
  2102. switch (id) {
  2103. case CHALLENGE_PASSWORD_OID:
  2104. oid = attrChallengePasswordOid;
  2105. *oidSz = sizeof(attrChallengePasswordOid);
  2106. break;
  2107. case SERIAL_NUMBER_OID:
  2108. oid = attrSerialNumberOid;
  2109. *oidSz = sizeof(attrSerialNumberOid);
  2110. break;
  2111. default:
  2112. break;
  2113. }
  2114. break;
  2115. #endif
  2116. case oidIgnoreType:
  2117. default:
  2118. break;
  2119. }
  2120. return oid;
  2121. }
  2122. #ifdef HAVE_OID_ENCODING
  2123. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  2124. {
  2125. int i, x, len;
  2126. word32 d, t;
  2127. /* check args */
  2128. if (in == NULL || outSz == NULL) {
  2129. return BAD_FUNC_ARG;
  2130. }
  2131. /* compute length of encoded OID */
  2132. d = (in[0] * 40) + in[1];
  2133. len = 0;
  2134. for (i = 1; i < (int)inSz; i++) {
  2135. x = 0;
  2136. t = d;
  2137. while (t) {
  2138. x++;
  2139. t >>= 1;
  2140. }
  2141. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  2142. if (i < (int)inSz - 1) {
  2143. d = in[i + 1];
  2144. }
  2145. }
  2146. if (out) {
  2147. /* verify length */
  2148. if ((int)*outSz < len) {
  2149. return BUFFER_E; /* buffer provided is not large enough */
  2150. }
  2151. /* calc first byte */
  2152. d = (in[0] * 40) + in[1];
  2153. /* encode bytes */
  2154. x = 0;
  2155. for (i = 1; i < (int)inSz; i++) {
  2156. if (d) {
  2157. int y = x, z;
  2158. byte mask = 0;
  2159. while (d) {
  2160. out[x++] = (byte)((d & 0x7F) | mask);
  2161. d >>= 7;
  2162. mask |= 0x80; /* upper bit is set on all but the last byte */
  2163. }
  2164. /* now swap bytes y...x-1 */
  2165. z = x - 1;
  2166. while (y < z) {
  2167. mask = out[y];
  2168. out[y] = out[z];
  2169. out[z] = mask;
  2170. ++y;
  2171. --z;
  2172. }
  2173. }
  2174. else {
  2175. out[x++] = 0x00; /* zero value */
  2176. }
  2177. /* next word */
  2178. if (i < (int)inSz - 1) {
  2179. d = in[i + 1];
  2180. }
  2181. }
  2182. }
  2183. /* return length */
  2184. *outSz = len;
  2185. return 0;
  2186. }
  2187. #endif /* HAVE_OID_ENCODING */
  2188. #ifdef HAVE_OID_DECODING
  2189. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  2190. {
  2191. int x = 0, y = 0;
  2192. word32 t = 0;
  2193. /* check args */
  2194. if (in == NULL || outSz == NULL) {
  2195. return BAD_FUNC_ARG;
  2196. }
  2197. /* decode bytes */
  2198. while (inSz--) {
  2199. t = (t << 7) | (in[x] & 0x7F);
  2200. if (!(in[x] & 0x80)) {
  2201. if (y >= (int)*outSz) {
  2202. return BUFFER_E;
  2203. }
  2204. if (y == 0) {
  2205. out[0] = (t / 40);
  2206. out[1] = (t % 40);
  2207. y = 2;
  2208. }
  2209. else {
  2210. out[y++] = t;
  2211. }
  2212. t = 0; /* reset tmp */
  2213. }
  2214. x++;
  2215. }
  2216. /* return length */
  2217. *outSz = y;
  2218. return 0;
  2219. }
  2220. #endif /* HAVE_OID_DECODING */
  2221. /* Get the DER/BER encoding of an ASN.1 OBJECT_ID header.
  2222. *
  2223. * input Buffer holding DER/BER encoded data.
  2224. * inOutIdx Current index into buffer to parse.
  2225. * len The number of bytes in the ASN.1 data.
  2226. * maxIdx Length of data in buffer.
  2227. * returns BUFFER_E when there is not enough data to parse.
  2228. * ASN_OBJECt_ID_E when the OBJECT_ID tag is not found.
  2229. * ASN_PARSE_E when length is invalid.
  2230. * Otherwise, 0 to indicate success.
  2231. */
  2232. int GetASNObjectId(const byte* input, word32* inOutIdx, int* len,
  2233. word32 maxIdx)
  2234. {
  2235. word32 idx = *inOutIdx;
  2236. int length;
  2237. byte tag;
  2238. if ((idx + 1) > maxIdx)
  2239. return BUFFER_E;
  2240. if (GetASNTag(input, &idx, &tag, maxIdx) != 0)
  2241. return ASN_PARSE_E;
  2242. if (tag != ASN_OBJECT_ID)
  2243. return ASN_OBJECT_ID_E;
  2244. if (GetLength(input, &idx, &length, maxIdx) < 0)
  2245. return ASN_PARSE_E;
  2246. *len = length;
  2247. *inOutIdx = idx;
  2248. return 0;
  2249. }
  2250. /* Set the DER/BER encoding of the ASN.1 OBJECT_ID header.
  2251. *
  2252. * len Length of the OBJECT_ID data.
  2253. * output Buffer to write into.
  2254. * returns the number of bytes added to the buffer.
  2255. */
  2256. int SetObjectId(int len, byte* output)
  2257. {
  2258. int idx = 0;
  2259. if (output)
  2260. output[idx++] = ASN_OBJECT_ID;
  2261. else
  2262. idx++;
  2263. idx += SetLength(len, output ? output + idx : NULL);
  2264. return idx;
  2265. }
  2266. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  2267. word32 oidType, word32 maxIdx)
  2268. {
  2269. int ret = 0, length;
  2270. word32 idx = *inOutIdx;
  2271. #ifndef NO_VERIFY_OID
  2272. word32 actualOidSz = 0;
  2273. const byte* actualOid;
  2274. #endif /* NO_VERIFY_OID */
  2275. (void)oidType;
  2276. WOLFSSL_ENTER("GetObjectId()");
  2277. *oid = 0;
  2278. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  2279. if (ret != 0)
  2280. return ret;
  2281. #ifndef NO_VERIFY_OID
  2282. actualOid = &input[idx];
  2283. if (length > 0)
  2284. actualOidSz = (word32)length;
  2285. #endif /* NO_VERIFY_OID */
  2286. while (length--) {
  2287. /* odd HC08 compiler behavior here when input[idx++] */
  2288. *oid += (word32)input[idx];
  2289. idx++;
  2290. }
  2291. /* just sum it up for now */
  2292. *inOutIdx = idx;
  2293. #ifndef NO_VERIFY_OID
  2294. {
  2295. const byte* checkOid = NULL;
  2296. word32 checkOidSz;
  2297. #ifdef ASN_DUMP_OID
  2298. word32 i;
  2299. #endif
  2300. if (oidType != oidIgnoreType) {
  2301. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  2302. #ifdef ASN_DUMP_OID
  2303. /* support for dumping OID information */
  2304. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, actualOidSz, *oid);
  2305. for (i=0; i<actualOidSz; i++) {
  2306. printf("%d, ", actualOid[i]);
  2307. }
  2308. printf("\n");
  2309. #ifdef HAVE_OID_DECODING
  2310. {
  2311. word16 decOid[16];
  2312. word32 decOidSz = sizeof(decOid);
  2313. ret = DecodeObjectId(actualOid, actualOidSz, decOid, &decOidSz);
  2314. if (ret == 0) {
  2315. printf(" Decoded (Sz %d): ", decOidSz);
  2316. for (i=0; i<decOidSz; i++) {
  2317. printf("%d.", decOid[i]);
  2318. }
  2319. printf("\n");
  2320. }
  2321. else {
  2322. printf("DecodeObjectId failed: %d\n", ret);
  2323. }
  2324. }
  2325. #endif /* HAVE_OID_DECODING */
  2326. #endif /* ASN_DUMP_OID */
  2327. if (checkOid != NULL &&
  2328. (checkOidSz != actualOidSz ||
  2329. XMEMCMP(actualOid, checkOid, checkOidSz) != 0)) {
  2330. WOLFSSL_MSG("OID Check Failed");
  2331. return ASN_UNKNOWN_OID_E;
  2332. }
  2333. }
  2334. }
  2335. #endif /* NO_VERIFY_OID */
  2336. return ret;
  2337. }
  2338. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  2339. {
  2340. word32 idx = *inOutIdx;
  2341. int length;
  2342. int ret;
  2343. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  2344. if (ret != 0)
  2345. return ret;
  2346. idx += length;
  2347. *inOutIdx = idx;
  2348. return 0;
  2349. }
  2350. int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  2351. word32 oidType, word32 maxIdx)
  2352. {
  2353. int length;
  2354. word32 idx = *inOutIdx;
  2355. int ret;
  2356. *oid = 0;
  2357. WOLFSSL_ENTER("GetAlgoId");
  2358. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  2359. return ASN_PARSE_E;
  2360. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  2361. return ASN_OBJECT_ID_E;
  2362. /* could have NULL tag and 0 terminator, but may not */
  2363. if (idx < maxIdx) {
  2364. word32 localIdx = idx; /*use localIdx to not advance when checking tag*/
  2365. byte tag;
  2366. if (GetASNTag(input, &localIdx, &tag, maxIdx) == 0) {
  2367. if (tag == ASN_TAG_NULL) {
  2368. ret = GetASNNull(input, &idx, maxIdx);
  2369. if (ret != 0)
  2370. return ret;
  2371. }
  2372. }
  2373. }
  2374. *inOutIdx = idx;
  2375. return 0;
  2376. }
  2377. #ifndef NO_RSA
  2378. #ifndef HAVE_USER_RSA
  2379. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  2380. word32 inSz)
  2381. {
  2382. int version, length;
  2383. if (inOutIdx == NULL || input == NULL || key == NULL) {
  2384. return BAD_FUNC_ARG;
  2385. }
  2386. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2387. return ASN_PARSE_E;
  2388. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  2389. return ASN_PARSE_E;
  2390. key->type = RSA_PRIVATE;
  2391. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  2392. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  2393. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  2394. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  2395. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  2396. GetInt(&key->q, input, inOutIdx, inSz) < 0)
  2397. #else
  2398. SkipInt(input, inOutIdx, inSz) < 0 ||
  2399. SkipInt(input, inOutIdx, inSz) < 0 ||
  2400. SkipInt(input, inOutIdx, inSz) < 0 )
  2401. #endif
  2402. return ASN_RSA_KEY_E;
  2403. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)) \
  2404. && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
  2405. if (GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  2406. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  2407. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  2408. #else
  2409. if (SkipInt(input, inOutIdx, inSz) < 0 ||
  2410. SkipInt(input, inOutIdx, inSz) < 0 ||
  2411. SkipInt(input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  2412. #endif
  2413. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  2414. if (wc_InitRsaHw(key) != 0) {
  2415. return BAD_STATE_E;
  2416. }
  2417. #endif
  2418. return 0;
  2419. }
  2420. #endif /* HAVE_USER_RSA */
  2421. #endif /* NO_RSA */
  2422. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  2423. /* Remove PKCS8 header, place inOutIdx at beginning of traditional,
  2424. * return traditional length on success, negative on error */
  2425. int ToTraditionalInline_ex(const byte* input, word32* inOutIdx, word32 sz,
  2426. word32* algId)
  2427. {
  2428. word32 idx;
  2429. int version, length;
  2430. int ret;
  2431. byte tag;
  2432. if (input == NULL || inOutIdx == NULL)
  2433. return BAD_FUNC_ARG;
  2434. idx = *inOutIdx;
  2435. if (GetSequence(input, &idx, &length, sz) < 0)
  2436. return ASN_PARSE_E;
  2437. if (GetMyVersion(input, &idx, &version, sz) < 0)
  2438. return ASN_PARSE_E;
  2439. if (GetAlgoId(input, &idx, algId, oidKeyType, sz) < 0)
  2440. return ASN_PARSE_E;
  2441. if (GetASNTag(input, &idx, &tag, sz) < 0)
  2442. return ASN_PARSE_E;
  2443. idx = idx - 1; /* reset idx after finding tag */
  2444. if (tag == ASN_OBJECT_ID) {
  2445. if (SkipObjectId(input, &idx, sz) < 0)
  2446. return ASN_PARSE_E;
  2447. }
  2448. ret = GetOctetString(input, &idx, &length, sz);
  2449. if (ret < 0) {
  2450. if (ret == BUFFER_E)
  2451. return ASN_PARSE_E;
  2452. /* Some private keys don't expect an octet string */
  2453. WOLFSSL_MSG("Couldn't find Octet string");
  2454. }
  2455. *inOutIdx = idx;
  2456. return length;
  2457. }
  2458. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  2459. {
  2460. word32 oid;
  2461. return ToTraditionalInline_ex(input, inOutIdx, sz, &oid);
  2462. }
  2463. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  2464. int ToTraditional_ex(byte* input, word32 sz, word32* algId)
  2465. {
  2466. word32 inOutIdx = 0;
  2467. int length;
  2468. if (input == NULL)
  2469. return BAD_FUNC_ARG;
  2470. length = ToTraditionalInline_ex(input, &inOutIdx, sz, algId);
  2471. if (length < 0)
  2472. return length;
  2473. if (length + inOutIdx > sz)
  2474. return BUFFER_E;
  2475. XMEMMOVE(input, input + inOutIdx, length);
  2476. return length;
  2477. }
  2478. int ToTraditional(byte* input, word32 sz)
  2479. {
  2480. word32 oid;
  2481. return ToTraditional_ex(input, sz, &oid);
  2482. }
  2483. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  2484. #if defined(HAVE_PKCS8) && !defined(NO_CERTS)
  2485. /* find beginning of traditional key inside PKCS#8 unencrypted buffer
  2486. * return traditional length on success, with inOutIdx at beginning of
  2487. * traditional
  2488. * return negative on failure/error */
  2489. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  2490. {
  2491. int length;
  2492. word32 algId;
  2493. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  2494. return BAD_FUNC_ARG;
  2495. length = ToTraditionalInline_ex(input, inOutIdx, sz, &algId);
  2496. return length;
  2497. }
  2498. /* PKCS#8 from RFC 5208
  2499. * This function takes in a DER key and converts it to PKCS#8 format. Used
  2500. * in creating PKCS#12 shrouded key bags.
  2501. * Reverse of ToTraditional
  2502. *
  2503. * PrivateKeyInfo ::= SEQUENCE {
  2504. * version Version,
  2505. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  2506. * privateKey PrivateKey,
  2507. * attributes optional
  2508. * }
  2509. * Version ::= INTEGER
  2510. * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
  2511. * PrivateKey ::= OCTET STRING
  2512. *
  2513. * out buffer to place result in
  2514. * outSz size of out buffer
  2515. * key buffer with DER key
  2516. * keySz size of key buffer
  2517. * algoID algorithm ID i.e. RSAk
  2518. * curveOID ECC curve oid if used. Should be NULL for RSA keys.
  2519. * oidSz size of curve oid. Is set to 0 if curveOID is NULL.
  2520. *
  2521. * Returns the size of PKCS#8 placed into out. In error cases returns negative
  2522. * values.
  2523. */
  2524. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  2525. int algoID, const byte* curveOID, word32 oidSz)
  2526. {
  2527. word32 keyIdx = 0;
  2528. word32 tmpSz = 0;
  2529. word32 sz;
  2530. /* If out is NULL then return the max size needed
  2531. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  2532. if (out == NULL && outSz != NULL) {
  2533. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  2534. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  2535. if (curveOID != NULL)
  2536. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  2537. WOLFSSL_MSG("Checking size of PKCS8");
  2538. return LENGTH_ONLY_E;
  2539. }
  2540. WOLFSSL_ENTER("wc_CreatePKCS8Key()");
  2541. if (key == NULL || out == NULL || outSz == NULL) {
  2542. return BAD_FUNC_ARG;
  2543. }
  2544. /* check the buffer has enough room for largest possible size */
  2545. if (curveOID != NULL) {
  2546. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  2547. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  2548. return BUFFER_E;
  2549. }
  2550. else {
  2551. oidSz = 0; /* with no curveOID oid size must be 0 */
  2552. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  2553. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  2554. return BUFFER_E;
  2555. }
  2556. /* PrivateKeyInfo ::= SEQUENCE */
  2557. keyIdx += MAX_SEQ_SZ; /* save room for sequence */
  2558. /* version Version
  2559. * no header information just INTEGER */
  2560. sz = SetMyVersion(PKCS8v0, out + keyIdx, 0);
  2561. tmpSz += sz; keyIdx += sz;
  2562. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  2563. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  2564. if (curveOID != NULL && oidSz > 0) {
  2565. byte buf[MAX_LENGTH_SZ];
  2566. sz = SetLength(oidSz, buf);
  2567. sz += 1; /* plus one for ASN object id */
  2568. }
  2569. sz = SetAlgoID(algoID, out + keyIdx, oidKeyType, oidSz + sz);
  2570. tmpSz += sz; keyIdx += sz;
  2571. /* privateKey PrivateKey *
  2572. * pkcs8 ecc uses slightly different format. Places curve oid in
  2573. * buffer */
  2574. if (curveOID != NULL && oidSz > 0) {
  2575. sz = SetObjectId(oidSz, out + keyIdx);
  2576. keyIdx += sz; tmpSz += sz;
  2577. XMEMCPY(out + keyIdx, curveOID, oidSz);
  2578. keyIdx += oidSz; tmpSz += oidSz;
  2579. }
  2580. sz = SetOctetString(keySz, out + keyIdx);
  2581. keyIdx += sz; tmpSz += sz;
  2582. XMEMCPY(out + keyIdx, key, keySz);
  2583. tmpSz += keySz;
  2584. /* attributes optional
  2585. * No attributes currently added */
  2586. /* rewind and add sequence */
  2587. sz = SetSequence(tmpSz, out);
  2588. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  2589. return tmpSz + sz;
  2590. }
  2591. #endif /* HAVE_PKCS8 && !NO_CERTS */
  2592. #if defined(HAVE_PKCS12) || !defined(NO_CHECK_PRIVATE_KEY)
  2593. /* check that the private key is a pair for the public key
  2594. * return 1 (true) on match
  2595. * return 0 or negative value on failure/error
  2596. *
  2597. * privKey : buffer holding DER format private key
  2598. * privKeySz : size of private key buffer
  2599. * pubKey : buffer holding DER format public key
  2600. * pubKeySz : size of public key buffer
  2601. * ks : type of key */
  2602. int wc_CheckPrivateKey(const byte* privKey, word32 privKeySz,
  2603. const byte* pubKey, word32 pubKeySz, enum Key_Sum ks)
  2604. {
  2605. int ret;
  2606. (void)privKeySz;
  2607. (void)pubKeySz;
  2608. (void)ks;
  2609. if (privKey == NULL || pubKey == NULL) {
  2610. return BAD_FUNC_ARG;
  2611. }
  2612. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  2613. /* test if RSA key */
  2614. if (ks == RSAk) {
  2615. #ifdef WOLFSSL_SMALL_STACK
  2616. RsaKey* a;
  2617. RsaKey* b = NULL;
  2618. #else
  2619. RsaKey a[1], b[1];
  2620. #endif
  2621. word32 keyIdx = 0;
  2622. #ifdef WOLFSSL_SMALL_STACK
  2623. a = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  2624. if (a == NULL)
  2625. return MEMORY_E;
  2626. b = (RsaKey*)XMALLOC(sizeof(RsaKey), NULL, DYNAMIC_TYPE_RSA);
  2627. if (b == NULL) {
  2628. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  2629. return MEMORY_E;
  2630. }
  2631. #endif
  2632. if ((ret = wc_InitRsaKey(a, NULL)) < 0) {
  2633. #ifdef WOLFSSL_SMALL_STACK
  2634. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  2635. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  2636. #endif
  2637. return ret;
  2638. }
  2639. if ((ret = wc_InitRsaKey(b, NULL)) < 0) {
  2640. wc_FreeRsaKey(a);
  2641. #ifdef WOLFSSL_SMALL_STACK
  2642. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  2643. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  2644. #endif
  2645. return ret;
  2646. }
  2647. if ((ret = wc_RsaPrivateKeyDecode(privKey, &keyIdx, a, privKeySz)) == 0) {
  2648. WOLFSSL_MSG("Checking RSA key pair");
  2649. keyIdx = 0; /* reset to 0 for parsing public key */
  2650. if ((ret = wc_RsaPublicKeyDecode(pubKey, &keyIdx, b,
  2651. pubKeySz)) == 0) {
  2652. /* limit for user RSA crypto because of RsaKey
  2653. * dereference. */
  2654. #if defined(HAVE_USER_RSA)
  2655. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  2656. ret = 1; /* return first RSA cert as match */
  2657. #else
  2658. /* both keys extracted successfully now check n and e
  2659. * values are the same. This is dereferencing RsaKey */
  2660. if (mp_cmp(&(a->n), &(b->n)) != MP_EQ ||
  2661. mp_cmp(&(a->e), &(b->e)) != MP_EQ) {
  2662. ret = MP_CMP_E;
  2663. }
  2664. else
  2665. ret = 1;
  2666. #endif
  2667. }
  2668. }
  2669. wc_FreeRsaKey(b);
  2670. wc_FreeRsaKey(a);
  2671. #ifdef WOLFSSL_SMALL_STACK
  2672. XFREE(b, NULL, DYNAMIC_TYPE_RSA);
  2673. XFREE(a, NULL, DYNAMIC_TYPE_RSA);
  2674. #endif
  2675. }
  2676. else
  2677. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  2678. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  2679. if (ks == ECDSAk) {
  2680. #ifdef WOLFSSL_SMALL_STACK
  2681. ecc_key* key_pair;
  2682. byte* privDer;
  2683. #else
  2684. ecc_key key_pair[1];
  2685. byte privDer[MAX_ECC_BYTES];
  2686. #endif
  2687. word32 privSz = MAX_ECC_BYTES;
  2688. word32 keyIdx = 0;
  2689. #ifdef WOLFSSL_SMALL_STACK
  2690. key_pair = (ecc_key*)XMALLOC(sizeof(ecc_key), NULL, DYNAMIC_TYPE_ECC);
  2691. if (key_pair == NULL)
  2692. return MEMORY_E;
  2693. privDer = (byte*)XMALLOC(MAX_ECC_BYTES, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2694. if (privDer == NULL) {
  2695. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  2696. return MEMORY_E;
  2697. }
  2698. #endif
  2699. if ((ret = wc_ecc_init(key_pair)) < 0) {
  2700. #ifdef WOLFSSL_SMALL_STACK
  2701. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2702. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  2703. #endif
  2704. return ret;
  2705. }
  2706. if ((ret = wc_EccPrivateKeyDecode(privKey, &keyIdx, key_pair,
  2707. privKeySz)) == 0) {
  2708. WOLFSSL_MSG("Checking ECC key pair");
  2709. if ((ret = wc_ecc_export_private_only(key_pair, privDer, &privSz))
  2710. == 0) {
  2711. wc_ecc_free(key_pair);
  2712. ret = wc_ecc_init(key_pair);
  2713. if (ret == 0) {
  2714. ret = wc_ecc_import_private_key(privDer,
  2715. privSz, pubKey,
  2716. pubKeySz, key_pair);
  2717. }
  2718. /* public and private extracted successfully now check if is
  2719. * a pair and also do sanity checks on key. wc_ecc_check_key
  2720. * checks that private * base generator equals pubkey */
  2721. if (ret == 0) {
  2722. if ((ret = wc_ecc_check_key(key_pair)) == 0) {
  2723. ret = 1;
  2724. }
  2725. }
  2726. ForceZero(privDer, privSz);
  2727. }
  2728. }
  2729. wc_ecc_free(key_pair);
  2730. #ifdef WOLFSSL_SMALL_STACK
  2731. XFREE(privDer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2732. XFREE(key_pair, NULL, DYNAMIC_TYPE_ECC);
  2733. #endif
  2734. }
  2735. else
  2736. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  2737. #if defined(HAVE_ED25519) && !defined(NO_ASN_CRYPT)
  2738. if (ks == ED25519k) {
  2739. #ifdef WOLFSSL_SMALL_STACK
  2740. ed25519_key* key_pair;
  2741. #else
  2742. ed25519_key key_pair[1];
  2743. #endif
  2744. word32 keyIdx = 0;
  2745. #ifdef WOLFSSL_SMALL_STACK
  2746. key_pair = (ed25519_key*)XMALLOC(sizeof(ed25519_key), NULL,
  2747. DYNAMIC_TYPE_ED25519);
  2748. if (key_pair == NULL)
  2749. return MEMORY_E;
  2750. #endif
  2751. if ((ret = wc_ed25519_init(key_pair)) < 0) {
  2752. #ifdef WOLFSSL_SMALL_STACK
  2753. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  2754. #endif
  2755. return ret;
  2756. }
  2757. if ((ret = wc_Ed25519PrivateKeyDecode(privKey, &keyIdx, key_pair,
  2758. privKeySz)) == 0) {
  2759. WOLFSSL_MSG("Checking ED25519 key pair");
  2760. keyIdx = 0;
  2761. if ((ret = wc_ed25519_import_public(pubKey, pubKeySz,
  2762. key_pair)) == 0) {
  2763. /* public and private extracted successfully no check if is
  2764. * a pair and also do sanity checks on key. wc_ecc_check_key
  2765. * checks that private * base generator equals pubkey */
  2766. if ((ret = wc_ed25519_check_key(key_pair)) == 0)
  2767. ret = 1;
  2768. }
  2769. }
  2770. wc_ed25519_free(key_pair);
  2771. #ifdef WOLFSSL_SMALL_STACK
  2772. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED25519);
  2773. #endif
  2774. }
  2775. else
  2776. #endif /* HAVE_ED25519 && !NO_ASN_CRYPT */
  2777. #if defined(HAVE_ED448) && !defined(NO_ASN_CRYPT)
  2778. if (ks == ED448k) {
  2779. #ifdef WOLFSSL_SMALL_STACK
  2780. ed448_key* key_pair = NULL;
  2781. #else
  2782. ed448_key key_pair[1];
  2783. #endif
  2784. word32 keyIdx = 0;
  2785. #ifdef WOLFSSL_SMALL_STACK
  2786. key_pair = (ed448_key*)XMALLOC(sizeof(ed448_key), NULL,
  2787. DYNAMIC_TYPE_ED448);
  2788. if (key_pair == NULL)
  2789. return MEMORY_E;
  2790. #endif
  2791. if ((ret = wc_ed448_init(key_pair)) < 0) {
  2792. #ifdef WOLFSSL_SMALL_STACK
  2793. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  2794. #endif
  2795. return ret;
  2796. }
  2797. if ((ret = wc_Ed448PrivateKeyDecode(privKey, &keyIdx, key_pair,
  2798. privKeySz)) == 0) {
  2799. WOLFSSL_MSG("Checking ED448 key pair");
  2800. keyIdx = 0;
  2801. if ((ret = wc_ed448_import_public(pubKey, pubKeySz,
  2802. key_pair)) == 0) {
  2803. /* public and private extracted successfully no check if is
  2804. * a pair and also do sanity checks on key. wc_ecc_check_key
  2805. * checks that private * base generator equals pubkey */
  2806. if ((ret = wc_ed448_check_key(key_pair)) == 0)
  2807. ret = 1;
  2808. }
  2809. }
  2810. wc_ed448_free(key_pair);
  2811. #ifdef WOLFSSL_SMALL_STACK
  2812. XFREE(key_pair, NULL, DYNAMIC_TYPE_ED448);
  2813. #endif
  2814. }
  2815. else
  2816. #endif /* HAVE_ED448 && !NO_ASN_CRYPT */
  2817. {
  2818. ret = 0;
  2819. }
  2820. (void)ks;
  2821. return ret;
  2822. }
  2823. /* check that the private key is a pair for the public key in certificate
  2824. * return 1 (true) on match
  2825. * return 0 or negative value on failure/error
  2826. *
  2827. * key : buffer holding DER format key
  2828. * keySz : size of key buffer
  2829. * der : a initialized and parsed DecodedCert holding a certificate */
  2830. int wc_CheckPrivateKeyCert(const byte* key, word32 keySz, DecodedCert* der)
  2831. {
  2832. if (key == NULL || der == NULL) {
  2833. return BAD_FUNC_ARG;
  2834. }
  2835. return wc_CheckPrivateKey(key, keySz, der->publicKey,
  2836. der->pubKeySize, (enum Key_Sum) der->keyOID);
  2837. }
  2838. #endif /* HAVE_PKCS12 || !NO_CHECK_PRIVATE_KEY */
  2839. #ifndef NO_PWDBASED
  2840. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  2841. /* Check To see if PKCS version algo is supported, set id if it is return 0
  2842. < 0 on error */
  2843. static int CheckAlgo(int first, int second, int* id, int* version, int* blockSz)
  2844. {
  2845. *id = ALGO_ID_E;
  2846. *version = PKCS5; /* default */
  2847. if (blockSz) *blockSz = 8; /* default */
  2848. if (first == 1) {
  2849. switch (second) {
  2850. #if !defined(NO_SHA)
  2851. #ifndef NO_RC4
  2852. case PBE_SHA1_RC4_128:
  2853. *id = PBE_SHA1_RC4_128;
  2854. *version = PKCS12v1;
  2855. return 0;
  2856. #endif
  2857. #ifndef NO_DES3
  2858. case PBE_SHA1_DES3:
  2859. *id = PBE_SHA1_DES3;
  2860. *version = PKCS12v1;
  2861. if (blockSz) *blockSz = DES_BLOCK_SIZE;
  2862. return 0;
  2863. case PBE_SHA1_DES:
  2864. *id = PBE_SHA1_DES;
  2865. *version = PKCS12v1;
  2866. if (blockSz) *blockSz = DES_BLOCK_SIZE;
  2867. return 0;
  2868. #endif
  2869. #ifdef WC_RC2
  2870. case PBE_SHA1_40RC2_CBC:
  2871. *id = PBE_SHA1_40RC2_CBC;
  2872. *version = PKCS12v1;
  2873. if (blockSz) *blockSz = RC2_BLOCK_SIZE;
  2874. return 0;
  2875. #endif
  2876. #endif /* !NO_SHA */
  2877. default:
  2878. return ALGO_ID_E;
  2879. }
  2880. }
  2881. if (first != PKCS5)
  2882. return ASN_INPUT_E; /* VERSION ERROR */
  2883. if (second == PBES2) {
  2884. *version = PKCS5v2;
  2885. return 0;
  2886. }
  2887. switch (second) {
  2888. #ifndef NO_DES3
  2889. #ifndef NO_MD5
  2890. case 3: /* see RFC 2898 for ids */
  2891. *id = PBE_MD5_DES;
  2892. if (blockSz) *blockSz = DES_BLOCK_SIZE;
  2893. return 0;
  2894. #endif
  2895. #ifndef NO_SHA
  2896. case 10:
  2897. *id = PBE_SHA1_DES;
  2898. if (blockSz) *blockSz = DES_BLOCK_SIZE;
  2899. return 0;
  2900. #endif
  2901. #endif /* !NO_DES3 */
  2902. default:
  2903. return ALGO_ID_E;
  2904. }
  2905. }
  2906. /* Check To see if PKCS v2 algo is supported, set id if it is return 0
  2907. < 0 on error */
  2908. static int CheckAlgoV2(int oid, int* id, int* blockSz)
  2909. {
  2910. if (blockSz) *blockSz = 8; /* default */
  2911. (void)id; /* not used if AES and DES3 disabled */
  2912. switch (oid) {
  2913. #if !defined(NO_DES3) && !defined(NO_SHA)
  2914. case DESb:
  2915. *id = PBE_SHA1_DES;
  2916. if (blockSz) *blockSz = DES_BLOCK_SIZE;
  2917. return 0;
  2918. case DES3b:
  2919. *id = PBE_SHA1_DES3;
  2920. if (blockSz) *blockSz = DES_BLOCK_SIZE;
  2921. return 0;
  2922. #endif
  2923. #ifdef WOLFSSL_AES_256
  2924. case AES256CBCb:
  2925. *id = PBE_AES256_CBC;
  2926. if (blockSz) *blockSz = AES_BLOCK_SIZE;
  2927. return 0;
  2928. #endif
  2929. #ifdef WOLFSSL_AES_128
  2930. case AES128CBCb:
  2931. *id = PBE_AES128_CBC;
  2932. if (blockSz) *blockSz = AES_BLOCK_SIZE;
  2933. return 0;
  2934. #endif
  2935. default:
  2936. WOLFSSL_MSG("No PKCS v2 algo found");
  2937. return ALGO_ID_E;
  2938. }
  2939. }
  2940. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  2941. #ifdef HAVE_PKCS8
  2942. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  2943. int* algoID, void* heap)
  2944. {
  2945. word32 tmpIdx = 0;
  2946. if (key == NULL || algoID == NULL)
  2947. return BAD_FUNC_ARG;
  2948. *algoID = 0;
  2949. #if !defined(NO_RSA) && !defined(NO_ASN_CRYPT)
  2950. {
  2951. RsaKey *rsa = (RsaKey *)XMALLOC(sizeof *rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2952. if (rsa == NULL)
  2953. return MEMORY_E;
  2954. wc_InitRsaKey(rsa, heap);
  2955. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, rsa, keySz) == 0) {
  2956. *algoID = RSAk;
  2957. }
  2958. else {
  2959. WOLFSSL_MSG("Not RSA DER key");
  2960. }
  2961. wc_FreeRsaKey(rsa);
  2962. XFREE(rsa, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2963. }
  2964. #endif /* !NO_RSA && !NO_ASN_CRYPT */
  2965. #if defined(HAVE_ECC) && !defined(NO_ASN_CRYPT)
  2966. if (*algoID == 0) {
  2967. ecc_key *ecc = (ecc_key *)XMALLOC(sizeof *ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2968. if (ecc == NULL)
  2969. return MEMORY_E;
  2970. tmpIdx = 0;
  2971. wc_ecc_init_ex(ecc, heap, INVALID_DEVID);
  2972. if (wc_EccPrivateKeyDecode(key, &tmpIdx, ecc, keySz) == 0) {
  2973. *algoID = ECDSAk;
  2974. /* now find oid */
  2975. if (wc_ecc_get_oid(ecc->dp->oidSum, curveOID, oidSz) < 0) {
  2976. WOLFSSL_MSG("Error getting ECC curve OID");
  2977. wc_ecc_free(ecc);
  2978. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2979. return BAD_FUNC_ARG;
  2980. }
  2981. }
  2982. else {
  2983. WOLFSSL_MSG("Not ECC DER key either");
  2984. }
  2985. wc_ecc_free(ecc);
  2986. XFREE(ecc, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2987. }
  2988. #endif /* HAVE_ECC && !NO_ASN_CRYPT */
  2989. #if defined(HAVE_ED25519) && !defined(NO_ASN_CRYPT)
  2990. if (*algoID != RSAk && *algoID != ECDSAk) {
  2991. ed25519_key *ed25519 = (ed25519_key *)XMALLOC(sizeof *ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2992. if (ed25519 == NULL)
  2993. return MEMORY_E;
  2994. tmpIdx = 0;
  2995. if (wc_ed25519_init(ed25519) == 0) {
  2996. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, ed25519, keySz) == 0) {
  2997. *algoID = ED25519k;
  2998. }
  2999. else {
  3000. WOLFSSL_MSG("Not ED25519 DER key");
  3001. }
  3002. wc_ed25519_free(ed25519);
  3003. }
  3004. else {
  3005. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  3006. }
  3007. XFREE(ed25519, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3008. }
  3009. #endif /* HAVE_ED25519 && !NO_ASN_CRYPT */
  3010. #if defined(HAVE_ED448) && !defined(NO_ASN_CRYPT)
  3011. if (*algoID != RSAk && *algoID != ECDSAk && *algoID != ED25519k) {
  3012. ed448_key *ed448 = (ed448_key *)XMALLOC(sizeof *ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3013. if (ed448 == NULL)
  3014. return MEMORY_E;
  3015. tmpIdx = 0;
  3016. if (wc_ed448_init(ed448) == 0) {
  3017. if (wc_Ed448PrivateKeyDecode(key, &tmpIdx, ed448, keySz) == 0) {
  3018. *algoID = ED448k;
  3019. }
  3020. else {
  3021. WOLFSSL_MSG("Not ED448 DER key");
  3022. }
  3023. wc_ed448_free(ed448);
  3024. }
  3025. else {
  3026. WOLFSSL_MSG("GetKeyOID wc_ed448_init failed");
  3027. }
  3028. XFREE(ed448, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3029. }
  3030. #endif /* HAVE_ED448 && !NO_ASN_CRYPT */
  3031. /* if flag is not set then is neither RSA or ECC key that could be
  3032. * found */
  3033. if (*algoID == 0) {
  3034. WOLFSSL_MSG("Bad key DER or compile options");
  3035. return BAD_FUNC_ARG;
  3036. }
  3037. (void)tmpIdx;
  3038. (void)curveOID;
  3039. (void)oidSz;
  3040. (void)keySz;
  3041. (void)heap;
  3042. return 1;
  3043. }
  3044. #endif /* HAVE_PKCS8 */
  3045. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  3046. #define PKCS8_MIN_BLOCK_SIZE 8
  3047. static int Pkcs8Pad(byte* buf, int sz, int blockSz)
  3048. {
  3049. int i, padSz;
  3050. /* calculate pad size */
  3051. padSz = blockSz - (sz & (blockSz - 1));
  3052. /* pad with padSz value */
  3053. if (buf) {
  3054. for (i = 0; i < padSz; i++) {
  3055. buf[sz+i] = (byte)(padSz & 0xFF);
  3056. }
  3057. }
  3058. /* return adjusted length */
  3059. return sz + padSz;
  3060. }
  3061. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  3062. #ifdef HAVE_PKCS8
  3063. /*
  3064. * Used when creating PKCS12 shrouded key bags
  3065. * vPKCS is the version of PKCS to use
  3066. * vAlgo is the algorithm version to use
  3067. *
  3068. * if salt is NULL a random number is generated
  3069. *
  3070. * returns the size of encrypted data on success
  3071. */
  3072. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  3073. const char* password, int passwordSz, int vPKCS, int vAlgo,
  3074. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  3075. {
  3076. int algoID = 0;
  3077. byte* tmp;
  3078. word32 tmpSz = 0;
  3079. word32 sz;
  3080. word32 seqSz;
  3081. word32 inOutIdx = 0;
  3082. word32 totalSz = 0;
  3083. int version, id;
  3084. int ret;
  3085. int blockSz = 0;
  3086. const byte* curveOID = NULL;
  3087. word32 oidSz = 0;
  3088. #ifdef WOLFSSL_SMALL_STACK
  3089. byte* saltTmp = NULL;
  3090. byte* cbcIv = NULL;
  3091. #else
  3092. byte saltTmp[MAX_IV_SIZE];
  3093. byte cbcIv[MAX_IV_SIZE];
  3094. #endif
  3095. WOLFSSL_ENTER("UnTraditionalEnc()");
  3096. if (saltSz > MAX_SALT_SIZE)
  3097. return ASN_PARSE_E;
  3098. inOutIdx += MAX_SEQ_SZ; /* leave room for size of finished shroud */
  3099. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0) {
  3100. WOLFSSL_MSG("Bad/Unsupported algorithm ID");
  3101. return ASN_INPUT_E; /* Algo ID error */
  3102. }
  3103. if (out != NULL) {
  3104. if (*outSz < inOutIdx + MAX_ALGO_SZ + MAX_SALT_SIZE + MAX_SEQ_SZ + 1 +
  3105. MAX_LENGTH_SZ + MAX_SHORT_SZ + 1)
  3106. return BUFFER_E;
  3107. if (version == PKCS5v2) {
  3108. WOLFSSL_MSG("PKCS5v2 Not supported yet\n");
  3109. return ASN_VERSION_E;
  3110. }
  3111. if (salt == NULL || saltSz == 0) {
  3112. saltSz = 8;
  3113. #ifdef WOLFSSL_SMALL_STACK
  3114. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3115. if (saltTmp == NULL)
  3116. return MEMORY_E;
  3117. #endif
  3118. salt = saltTmp;
  3119. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  3120. WOLFSSL_MSG("Error generating random salt");
  3121. #ifdef WOLFSSL_SMALL_STACK
  3122. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3123. #endif
  3124. return ret;
  3125. }
  3126. }
  3127. /* leave room for a sequence (contains salt and iterations int) */
  3128. inOutIdx += MAX_SEQ_SZ; sz = 0;
  3129. inOutIdx += MAX_ALGO_SZ;
  3130. /* place salt in buffer */
  3131. out[inOutIdx++] = ASN_OCTET_STRING; sz++;
  3132. tmpSz = SetLength(saltSz, out + inOutIdx);
  3133. inOutIdx += tmpSz; sz += tmpSz;
  3134. XMEMCPY(out + inOutIdx, salt, saltSz);
  3135. inOutIdx += saltSz; sz += saltSz;
  3136. /* place iteration count in buffer */
  3137. ret = SetShortInt(out, &inOutIdx, itt, *outSz);
  3138. if (ret < 0) {
  3139. #ifdef WOLFSSL_SMALL_STACK
  3140. if (saltTmp != NULL)
  3141. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3142. #endif
  3143. return ret;
  3144. }
  3145. sz += (word32)ret;
  3146. /* wind back index and set sequence then clean up buffer */
  3147. inOutIdx -= (sz + MAX_SEQ_SZ);
  3148. tmpSz = SetSequence(sz, out + inOutIdx);
  3149. XMEMMOVE(out + inOutIdx + tmpSz, out + inOutIdx + MAX_SEQ_SZ, sz);
  3150. totalSz += tmpSz + sz; sz += tmpSz;
  3151. /* add in algo ID */
  3152. inOutIdx -= MAX_ALGO_SZ;
  3153. tmpSz = SetAlgoID(id, out + inOutIdx, oidPBEType, sz);
  3154. XMEMMOVE(out + inOutIdx + tmpSz, out + inOutIdx + MAX_ALGO_SZ, sz);
  3155. totalSz += tmpSz; inOutIdx += tmpSz + sz;
  3156. /* octet string containing encrypted key */
  3157. out[inOutIdx++] = ASN_OCTET_STRING; totalSz++;
  3158. }
  3159. /* check key type and get OID if ECC */
  3160. if ((ret = wc_GetKeyOID(key, keySz, &curveOID, &oidSz, &algoID, heap))< 0) {
  3161. WOLFSSL_MSG("Error getting key OID");
  3162. #ifdef WOLFSSL_SMALL_STACK
  3163. if (saltTmp != NULL)
  3164. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3165. #endif
  3166. return ret;
  3167. }
  3168. /* PKCS#8 wrapping around key */
  3169. if (wc_CreatePKCS8Key(NULL, &tmpSz, key, keySz, algoID, curveOID, oidSz)
  3170. != LENGTH_ONLY_E) {
  3171. #ifdef WOLFSSL_SMALL_STACK
  3172. if (saltTmp != NULL)
  3173. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3174. #endif
  3175. return MEMORY_E;
  3176. }
  3177. /* check if should return max size */
  3178. if (out == NULL) {
  3179. /* account for salt size */
  3180. if (salt == NULL || saltSz == 0) {
  3181. tmpSz += MAX_SALT_SIZE;
  3182. }
  3183. else {
  3184. tmpSz += saltSz;
  3185. }
  3186. /* plus 3 for tags */
  3187. *outSz = tmpSz + MAX_ALGO_SZ + MAX_LENGTH_SZ +MAX_LENGTH_SZ + MAX_SEQ_SZ
  3188. + MAX_LENGTH_SZ + MAX_SEQ_SZ + 3;
  3189. #ifdef WOLFSSL_SMALL_STACK
  3190. if (saltTmp != NULL)
  3191. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3192. #endif
  3193. return LENGTH_ONLY_E;
  3194. }
  3195. /* reserve buffer for crypto and make sure it supports full blocks */
  3196. tmp = (byte*)XMALLOC(tmpSz + (blockSz-1), heap, DYNAMIC_TYPE_TMP_BUFFER);
  3197. if (tmp == NULL) {
  3198. #ifdef WOLFSSL_SMALL_STACK
  3199. if (saltTmp != NULL)
  3200. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3201. #endif
  3202. return MEMORY_E;
  3203. }
  3204. if ((ret = wc_CreatePKCS8Key(tmp, &tmpSz, key, keySz, algoID, curveOID,
  3205. oidSz)) < 0) {
  3206. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3207. WOLFSSL_MSG("Error wrapping key with PKCS#8");
  3208. #ifdef WOLFSSL_SMALL_STACK
  3209. if (saltTmp != NULL)
  3210. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3211. #endif
  3212. return ret;
  3213. }
  3214. tmpSz = ret;
  3215. /* adjust size to pad */
  3216. tmpSz = Pkcs8Pad(tmp, tmpSz, blockSz);
  3217. #ifdef WOLFSSL_SMALL_STACK
  3218. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3219. if (cbcIv == NULL) {
  3220. if (saltTmp != NULL)
  3221. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3222. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3223. return MEMORY_E;
  3224. }
  3225. #endif
  3226. /* encrypt PKCS#8 wrapped key */
  3227. if ((ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id,
  3228. tmp, tmpSz, version, cbcIv, 1, 0)) < 0) {
  3229. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3230. WOLFSSL_MSG("Error encrypting key");
  3231. #ifdef WOLFSSL_SMALL_STACK
  3232. if (saltTmp != NULL)
  3233. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3234. if (cbcIv != NULL)
  3235. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3236. #endif
  3237. return ret; /* encryption failure */
  3238. }
  3239. totalSz += tmpSz;
  3240. #ifdef WOLFSSL_SMALL_STACK
  3241. if (saltTmp != NULL)
  3242. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3243. if (cbcIv != NULL)
  3244. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3245. #endif
  3246. if (*outSz < inOutIdx + tmpSz + MAX_LENGTH_SZ) {
  3247. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3248. return BUFFER_E;
  3249. }
  3250. /* set length of key and copy over encrypted key */
  3251. seqSz = SetLength(tmpSz, out + inOutIdx);
  3252. inOutIdx += seqSz; totalSz += seqSz;
  3253. XMEMCPY(out + inOutIdx, tmp, tmpSz);
  3254. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3255. /* set total size at beginning */
  3256. sz = SetSequence(totalSz, out);
  3257. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, totalSz);
  3258. (void)rng;
  3259. return totalSz + sz;
  3260. }
  3261. static int GetAlgoV2(int encAlgId, const byte** oid, int *len, int* id,
  3262. int *blkSz)
  3263. {
  3264. int ret = 0;
  3265. switch (encAlgId) {
  3266. #if !defined(NO_DES3) && !defined(NO_SHA)
  3267. case DESb:
  3268. *len = sizeof(blkDesCbcOid);
  3269. *oid = blkDesCbcOid;
  3270. *id = PBE_SHA1_DES;
  3271. *blkSz = 8;
  3272. break;
  3273. case DES3b:
  3274. *len = sizeof(blkDes3CbcOid);
  3275. *oid = blkDes3CbcOid;
  3276. *id = PBE_SHA1_DES3;
  3277. *blkSz = 8;
  3278. break;
  3279. #endif
  3280. #if defined(WOLFSSL_AES_256) && defined(HAVE_AES_CBC)
  3281. case AES256CBCb:
  3282. *len = sizeof(blkAes256CbcOid);
  3283. *oid = blkAes256CbcOid;
  3284. *id = PBE_AES256_CBC;
  3285. *blkSz = 16;
  3286. break;
  3287. #endif
  3288. default:
  3289. (void)len;
  3290. (void)oid;
  3291. (void)id;
  3292. (void)blkSz;
  3293. ret = ALGO_ID_E;
  3294. }
  3295. return ret;
  3296. }
  3297. /* Converts Encrypted PKCS#8 to 'traditional' (i.e. PKCS#8 removed from
  3298. * decrypted key.)
  3299. */
  3300. int TraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  3301. const char* password, int passwordSz, int vPKCS, int vAlgo,
  3302. int encAlgId, byte* salt, word32 saltSz, int itt, WC_RNG* rng,
  3303. void* heap)
  3304. {
  3305. int ret = 0;
  3306. int version, blockSz, id;
  3307. word32 idx = 0, encIdx;
  3308. #ifdef WOLFSSL_SMALL_STACK
  3309. byte* saltTmp = NULL;
  3310. #else
  3311. byte saltTmp[MAX_SALT_SIZE];
  3312. #endif
  3313. byte cbcIv[MAX_IV_SIZE];
  3314. byte *pkcs8Key = NULL;
  3315. word32 pkcs8KeySz = 0, padSz = 0;
  3316. int algId = 0;
  3317. const byte* curveOid = NULL;
  3318. word32 curveOidSz = 0;
  3319. const byte* pbeOid = NULL;
  3320. word32 pbeOidSz = 0;
  3321. const byte* encOid = NULL;
  3322. int encOidSz = 0;
  3323. word32 pbeLen = 0, kdfLen = 0, encLen = 0;
  3324. word32 innerLen = 0, outerLen;
  3325. ret = CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz);
  3326. /* create random salt if one not provided */
  3327. if (ret == 0 && (salt == NULL || saltSz == 0)) {
  3328. saltSz = 8;
  3329. #ifdef WOLFSSL_SMALL_STACK
  3330. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3331. if (saltTmp == NULL)
  3332. return MEMORY_E;
  3333. #endif
  3334. salt = saltTmp;
  3335. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  3336. WOLFSSL_MSG("Error generating random salt");
  3337. #ifdef WOLFSSL_SMALL_STACK
  3338. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3339. #endif
  3340. return ret;
  3341. }
  3342. }
  3343. if (ret == 0) {
  3344. /* check key type and get OID if ECC */
  3345. ret = wc_GetKeyOID(key, keySz, &curveOid, &curveOidSz, &algId, heap);
  3346. if (ret == 1)
  3347. ret = 0;
  3348. }
  3349. if (ret == 0) {
  3350. ret = wc_CreatePKCS8Key(NULL, &pkcs8KeySz, key, keySz, algId, curveOid,
  3351. curveOidSz);
  3352. if (ret == LENGTH_ONLY_E)
  3353. ret = 0;
  3354. }
  3355. if (ret == 0) {
  3356. pkcs8Key = (byte*)XMALLOC(pkcs8KeySz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3357. if (pkcs8Key == NULL)
  3358. ret = MEMORY_E;
  3359. }
  3360. if (ret == 0) {
  3361. ret = wc_CreatePKCS8Key(pkcs8Key, &pkcs8KeySz, key, keySz, algId,
  3362. curveOid, curveOidSz);
  3363. if (ret >= 0) {
  3364. pkcs8KeySz = ret;
  3365. ret = 0;
  3366. }
  3367. }
  3368. if (ret == 0 && version == PKCS5v2)
  3369. ret = GetAlgoV2(encAlgId, &encOid, &encOidSz, &id, &blockSz);
  3370. if (ret == 0) {
  3371. padSz = (blockSz - (pkcs8KeySz & (blockSz - 1))) & (blockSz - 1);
  3372. /* inner = OCT salt INT itt */
  3373. innerLen = 2 + saltSz + 2 + (itt < 256 ? 1 : 2);
  3374. if (version != PKCS5v2) {
  3375. pbeOid = OidFromId(id, oidPBEType, &pbeOidSz);
  3376. /* pbe = OBJ pbse1 SEQ [ inner ] */
  3377. pbeLen = 2 + pbeOidSz + 2 + innerLen;
  3378. }
  3379. else {
  3380. pbeOid = pbes2;
  3381. pbeOidSz = sizeof(pbes2);
  3382. /* kdf = OBJ pbkdf2 [ SEQ innerLen ] */
  3383. kdfLen = 2 + sizeof(pbkdf2Oid) + 2 + innerLen;
  3384. /* enc = OBJ enc_alg OCT iv */
  3385. encLen = 2 + encOidSz + 2 + blockSz;
  3386. /* pbe = OBJ pbse2 SEQ [ SEQ [ kdf ] SEQ [ enc ] ] */
  3387. pbeLen = 2 + sizeof(pbes2) + 2 + 2 + kdfLen + 2 + encLen;
  3388. ret = wc_RNG_GenerateBlock(rng, cbcIv, blockSz);
  3389. }
  3390. }
  3391. if (ret == 0) {
  3392. /* outer = SEQ [ pbe ] OCT encrypted_PKCS#8_key */
  3393. outerLen = 2 + pbeLen;
  3394. outerLen += SetOctetString(pkcs8KeySz + padSz, out);
  3395. outerLen += pkcs8KeySz + padSz;
  3396. idx += SetSequence(outerLen, out + idx);
  3397. encIdx = idx + outerLen - pkcs8KeySz - padSz;
  3398. /* Put Encrypted content in place. */
  3399. XMEMCPY(out + encIdx, pkcs8Key, pkcs8KeySz);
  3400. if (padSz > 0) {
  3401. XMEMSET(out + encIdx + pkcs8KeySz, padSz, padSz);
  3402. pkcs8KeySz += padSz;
  3403. }
  3404. ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id,
  3405. out + encIdx, pkcs8KeySz, version, cbcIv, 1, 0);
  3406. }
  3407. if (ret == 0) {
  3408. if (version != PKCS5v2) {
  3409. /* PBE algorithm */
  3410. idx += SetSequence(pbeLen, out + idx);
  3411. idx += SetObjectId(pbeOidSz, out + idx);
  3412. XMEMCPY(out + idx, pbeOid, pbeOidSz);
  3413. idx += pbeOidSz;
  3414. }
  3415. else {
  3416. /* PBES2 algorithm identifier */
  3417. idx += SetSequence(pbeLen, out + idx);
  3418. idx += SetObjectId(pbeOidSz, out + idx);
  3419. XMEMCPY(out + idx, pbeOid, pbeOidSz);
  3420. idx += pbeOidSz;
  3421. /* PBES2 Parameters: SEQ [ kdf ] SEQ [ enc ] */
  3422. idx += SetSequence(2 + kdfLen + 2 + encLen, out + idx);
  3423. /* KDF Algorithm Identifier */
  3424. idx += SetSequence(kdfLen, out + idx);
  3425. idx += SetObjectId(sizeof(pbkdf2Oid), out + idx);
  3426. XMEMCPY(out + idx, pbkdf2Oid, sizeof(pbkdf2Oid));
  3427. idx += sizeof(pbkdf2Oid);
  3428. }
  3429. idx += SetSequence(innerLen, out + idx);
  3430. idx += SetOctetString(saltSz, out + idx);
  3431. XMEMCPY(out + idx, salt, saltSz); idx += saltSz;
  3432. ret = SetShortInt(out, &idx, itt, *outSz);
  3433. if (ret > 0)
  3434. ret = 0;
  3435. }
  3436. if (ret == 0) {
  3437. if (version == PKCS5v2) {
  3438. /* Encryption Algorithm Identifier */
  3439. idx += SetSequence(encLen, out + idx);
  3440. idx += SetObjectId(encOidSz, out + idx);
  3441. XMEMCPY(out + idx, encOid, encOidSz);
  3442. idx += encOidSz;
  3443. /* Encryption Algorithm Parameter: CBC IV */
  3444. idx += SetOctetString(blockSz, out + idx);
  3445. XMEMCPY(out + idx, cbcIv, blockSz);
  3446. idx += blockSz;
  3447. }
  3448. idx += SetOctetString(pkcs8KeySz, out + idx);
  3449. /* Default PRF - no need to write out OID */
  3450. idx += pkcs8KeySz;
  3451. ret = idx;
  3452. }
  3453. if (pkcs8Key != NULL) {
  3454. ForceZero(pkcs8Key, pkcs8KeySz);
  3455. XFREE(pkcs8Key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3456. }
  3457. #ifdef WOLFSSL_SMALL_STACK
  3458. if (saltTmp != NULL) {
  3459. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3460. }
  3461. #endif
  3462. (void)rng;
  3463. return ret;
  3464. }
  3465. #endif /* HAVE_PKCS8 */
  3466. #if defined(HAVE_PKCS8) || defined(HAVE_PKCS12)
  3467. /* decrypt PKCS
  3468. *
  3469. * NOTE: input buffer is overwritten with decrypted data!
  3470. *
  3471. * input[in/out] data to decrypt and results are written to
  3472. * sz size of input buffer
  3473. * password password if used. Can be NULL for no password
  3474. * passwordSz size of password buffer
  3475. *
  3476. * returns the total size of decrypted content on success.
  3477. */
  3478. int DecryptContent(byte* input, word32 sz, const char* password, int passwordSz)
  3479. {
  3480. word32 inOutIdx = 0, seqEnd, oid, shaOid = 0;
  3481. int ret = 0, first, second, length = 0, version, saltSz, id;
  3482. int iterations = 0, keySz = 0;
  3483. #ifdef WOLFSSL_SMALL_STACK
  3484. byte* salt = NULL;
  3485. byte* cbcIv = NULL;
  3486. #else
  3487. byte salt[MAX_SALT_SIZE];
  3488. byte cbcIv[MAX_IV_SIZE];
  3489. #endif
  3490. byte tag;
  3491. if (passwordSz < 0) {
  3492. WOLFSSL_MSG("Bad password size");
  3493. return BAD_FUNC_ARG;
  3494. }
  3495. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  3496. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3497. }
  3498. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  3499. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  3500. if (CheckAlgo(first, second, &id, &version, NULL) < 0) {
  3501. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  3502. }
  3503. if (version == PKCS5v2) {
  3504. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  3505. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3506. }
  3507. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  3508. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3509. }
  3510. if (oid != PBKDF2_OID) {
  3511. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3512. }
  3513. }
  3514. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  3515. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3516. }
  3517. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  3518. * DEFAULT items. */
  3519. seqEnd = inOutIdx + length;
  3520. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  3521. if (ret < 0)
  3522. goto exit_dc;
  3523. if (saltSz > MAX_SALT_SIZE) {
  3524. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3525. }
  3526. #ifdef WOLFSSL_SMALL_STACK
  3527. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3528. if (salt == NULL) {
  3529. ERROR_OUT(MEMORY_E, exit_dc);
  3530. }
  3531. #endif
  3532. XMEMCPY(salt, &input[inOutIdx], saltSz);
  3533. inOutIdx += saltSz;
  3534. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  3535. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3536. }
  3537. /* OPTIONAL key length */
  3538. if (seqEnd > inOutIdx) {
  3539. word32 localIdx = inOutIdx;
  3540. if (GetASNTag(input, &localIdx, &tag, sz) < 0) {
  3541. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3542. }
  3543. if (tag == ASN_INTEGER &&
  3544. GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  3545. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3546. }
  3547. }
  3548. /* DEFAULT HMAC is SHA-1 */
  3549. if (seqEnd > inOutIdx) {
  3550. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  3551. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3552. }
  3553. shaOid = oid;
  3554. }
  3555. #ifdef WOLFSSL_SMALL_STACK
  3556. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3557. if (cbcIv == NULL) {
  3558. ERROR_OUT(MEMORY_E, exit_dc);
  3559. }
  3560. #endif
  3561. if (version == PKCS5v2) {
  3562. /* get encryption algo */
  3563. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  3564. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3565. }
  3566. if (CheckAlgoV2(oid, &id, NULL) < 0) {
  3567. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  3568. }
  3569. if (shaOid == 0)
  3570. shaOid = oid;
  3571. ret = GetOctetString(input, &inOutIdx, &length, sz);
  3572. if (ret < 0)
  3573. goto exit_dc;
  3574. if (length > MAX_IV_SIZE) {
  3575. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3576. }
  3577. XMEMCPY(cbcIv, &input[inOutIdx], length);
  3578. inOutIdx += length;
  3579. }
  3580. if (GetASNTag(input, &inOutIdx, &tag, sz) < 0) {
  3581. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3582. }
  3583. if (tag != (ASN_CONTEXT_SPECIFIC | 0) && tag != ASN_OCTET_STRING) {
  3584. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3585. }
  3586. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  3587. ERROR_OUT(ASN_PARSE_E, exit_dc);
  3588. }
  3589. ret = wc_CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  3590. input + inOutIdx, length, version, cbcIv, 0, shaOid);
  3591. exit_dc:
  3592. #ifdef WOLFSSL_SMALL_STACK
  3593. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3594. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3595. #endif
  3596. if (ret == 0) {
  3597. XMEMMOVE(input, input + inOutIdx, length);
  3598. ret = length;
  3599. }
  3600. return ret;
  3601. }
  3602. /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
  3603. of input */
  3604. int ToTraditionalEnc(byte* input, word32 sz,const char* password,
  3605. int passwordSz, word32* algId)
  3606. {
  3607. int ret, length;
  3608. word32 inOutIdx = 0;
  3609. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  3610. ret = ASN_PARSE_E;
  3611. }
  3612. else {
  3613. ret = DecryptContent(input + inOutIdx, sz - inOutIdx, password,
  3614. passwordSz);
  3615. if (ret > 0) {
  3616. XMEMMOVE(input, input + inOutIdx, ret);
  3617. ret = ToTraditional_ex(input, ret, algId);
  3618. }
  3619. }
  3620. return ret;
  3621. }
  3622. #endif /* HAVE_PKCS8 || HAVE_PKCS12 */
  3623. #ifdef HAVE_PKCS12
  3624. /* encrypt PKCS 12 content
  3625. *
  3626. * NOTE: if out is NULL then outSz is set with the total buffer size needed and
  3627. * the error value LENGTH_ONLY_E is returned.
  3628. *
  3629. * input data to encrypt
  3630. * inputSz size of input buffer
  3631. * out buffer to hold the result
  3632. * outSz size of out buffer
  3633. * password password if used. Can be NULL for no password
  3634. * passwordSz size of password buffer
  3635. * vPKCS version of PKCS i.e. PKCS5v2
  3636. * vAlgo algorithm version
  3637. * salt buffer holding salt if used. If NULL then a random salt is created
  3638. * saltSz size of salt buffer if it is not NULL
  3639. * itt number of iterations used
  3640. * rng random number generator to use
  3641. * heap possible heap hint for mallocs/frees
  3642. *
  3643. * returns the total size of encrypted content on success.
  3644. *
  3645. * data returned is :
  3646. * [ seq - obj [ seq -salt,itt]] , construct with encrypted data
  3647. */
  3648. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  3649. const char* password, int passwordSz, int vPKCS, int vAlgo,
  3650. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  3651. {
  3652. word32 sz;
  3653. word32 inOutIdx = 0;
  3654. word32 tmpIdx = 0;
  3655. word32 totalSz = 0;
  3656. word32 seqSz;
  3657. word32 innerSz;
  3658. int ret;
  3659. int version, id, blockSz = 0;
  3660. #ifdef WOLFSSL_SMALL_STACK
  3661. byte* saltTmp = NULL;
  3662. byte* cbcIv = NULL;
  3663. #else
  3664. byte saltTmp[MAX_SALT_SIZE];
  3665. byte cbcIv[MAX_IV_SIZE];
  3666. #endif
  3667. byte seq[MAX_SEQ_SZ];
  3668. byte shr[MAX_SHORT_SZ];
  3669. word32 maxShr = MAX_SHORT_SZ;
  3670. word32 algoSz;
  3671. const byte* algoName;
  3672. (void)heap;
  3673. WOLFSSL_ENTER("EncryptContent()");
  3674. if (CheckAlgo(vPKCS, vAlgo, &id, &version, &blockSz) < 0)
  3675. return ASN_INPUT_E; /* Algo ID error */
  3676. if (version == PKCS5v2) {
  3677. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  3678. return BAD_FUNC_ARG;
  3679. }
  3680. if (saltSz > MAX_SALT_SIZE)
  3681. return ASN_PARSE_E;
  3682. if (outSz == NULL) {
  3683. return BAD_FUNC_ARG;
  3684. }
  3685. /* calculate size */
  3686. /* size of constructed string at end */
  3687. sz = Pkcs8Pad(NULL, inputSz, blockSz);
  3688. totalSz = ASN_TAG_SZ;
  3689. totalSz += SetLength(sz, seq);
  3690. totalSz += sz;
  3691. /* size of sequence holding object id and sub sequence of salt and itt */
  3692. algoName = OidFromId(id, oidPBEType, &algoSz);
  3693. if (algoName == NULL) {
  3694. WOLFSSL_MSG("Unknown Algorithm");
  3695. return 0;
  3696. }
  3697. innerSz = SetObjectId(algoSz, seq);
  3698. innerSz += algoSz;
  3699. /* get subsequence of salt and itt */
  3700. if (salt == NULL || saltSz == 0) {
  3701. sz = 8;
  3702. }
  3703. else {
  3704. sz = saltSz;
  3705. }
  3706. seqSz = SetOctetString(sz, seq);
  3707. seqSz += sz;
  3708. tmpIdx = 0;
  3709. ret = SetShortInt(shr, &tmpIdx, itt, maxShr);
  3710. if (ret >= 0) {
  3711. seqSz += ret;
  3712. }
  3713. else {
  3714. return ret;
  3715. }
  3716. innerSz += seqSz + SetSequence(seqSz, seq);
  3717. totalSz += innerSz + SetSequence(innerSz, seq);
  3718. if (out == NULL) {
  3719. *outSz = totalSz;
  3720. return LENGTH_ONLY_E;
  3721. }
  3722. inOutIdx = 0;
  3723. if (totalSz > *outSz)
  3724. return BUFFER_E;
  3725. inOutIdx += SetSequence(innerSz, out + inOutIdx);
  3726. inOutIdx += SetObjectId(algoSz, out + inOutIdx);
  3727. XMEMCPY(out + inOutIdx, algoName, algoSz);
  3728. inOutIdx += algoSz;
  3729. inOutIdx += SetSequence(seqSz, out + inOutIdx);
  3730. /* create random salt if one not provided */
  3731. if (salt == NULL || saltSz == 0) {
  3732. saltSz = 8;
  3733. #ifdef WOLFSSL_SMALL_STACK
  3734. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3735. if (saltTmp == NULL)
  3736. return MEMORY_E;
  3737. #endif
  3738. salt = saltTmp;
  3739. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  3740. WOLFSSL_MSG("Error generating random salt");
  3741. #ifdef WOLFSSL_SMALL_STACK
  3742. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3743. #endif
  3744. return ret;
  3745. }
  3746. }
  3747. inOutIdx += SetOctetString(saltSz, out + inOutIdx);
  3748. if (saltSz + inOutIdx > *outSz) {
  3749. #ifdef WOLFSSL_SMALL_STACK
  3750. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3751. #endif
  3752. return BUFFER_E;
  3753. }
  3754. XMEMCPY(out + inOutIdx, salt, saltSz);
  3755. inOutIdx += saltSz;
  3756. /* place iteration setting in buffer */
  3757. ret = SetShortInt(out, &inOutIdx, itt, *outSz);
  3758. if (ret < 0) {
  3759. #ifdef WOLFSSL_SMALL_STACK
  3760. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3761. #endif
  3762. return ret;
  3763. }
  3764. if (inOutIdx + 1 > *outSz) {
  3765. #ifdef WOLFSSL_SMALL_STACK
  3766. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3767. #endif
  3768. return BUFFER_E;
  3769. }
  3770. out[inOutIdx++] = ASN_CONTEXT_SPECIFIC | 0;
  3771. /* get pad size and verify buffer room */
  3772. sz = Pkcs8Pad(NULL, inputSz, blockSz);
  3773. if (sz + inOutIdx > *outSz) {
  3774. #ifdef WOLFSSL_SMALL_STACK
  3775. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3776. #endif
  3777. return BUFFER_E;
  3778. }
  3779. inOutIdx += SetLength(sz, out + inOutIdx);
  3780. /* copy input to output buffer and pad end */
  3781. XMEMCPY(out + inOutIdx, input, inputSz);
  3782. sz = Pkcs8Pad(out + inOutIdx, inputSz, blockSz);
  3783. #ifdef WOLFSSL_SMALL_STACK
  3784. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3785. if (cbcIv == NULL) {
  3786. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3787. return MEMORY_E;
  3788. }
  3789. #endif
  3790. /* encrypt */
  3791. if ((ret = wc_CryptKey(password, passwordSz, salt, saltSz, itt, id,
  3792. out + inOutIdx, sz, version, cbcIv, 1, 0)) < 0) {
  3793. #ifdef WOLFSSL_SMALL_STACK
  3794. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3795. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3796. #endif
  3797. return ret; /* encrypt failure */
  3798. }
  3799. #ifdef WOLFSSL_SMALL_STACK
  3800. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3801. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  3802. #endif
  3803. (void)rng;
  3804. return inOutIdx + sz;
  3805. }
  3806. #endif /* HAVE_PKCS12 */
  3807. #endif /* NO_PWDBASED */
  3808. #ifndef NO_RSA
  3809. #ifndef HAVE_USER_RSA
  3810. #ifdef WOLFSSL_RENESAS_TSIP
  3811. /* This function is to retrieve key position information in a cert.*
  3812. * The information will be used to call TSIP TLS-linked API for *
  3813. * certificate verification. */
  3814. static int RsaPublicKeyDecodeRawIndex(const byte* input, word32* inOutIdx,
  3815. word32 inSz, word32* key_n,
  3816. word32* key_n_len, word32* key_e,
  3817. word32* key_e_len)
  3818. {
  3819. int ret = 0;
  3820. int length = 0;
  3821. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  3822. byte b;
  3823. #endif
  3824. if (input == NULL || inOutIdx == NULL)
  3825. return BAD_FUNC_ARG;
  3826. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3827. return ASN_PARSE_E;
  3828. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  3829. if ((*inOutIdx + 1) > inSz)
  3830. return BUFFER_E;
  3831. b = input[*inOutIdx];
  3832. if (b != ASN_INTEGER) {
  3833. /* not from decoded cert, will have algo id, skip past */
  3834. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3835. return ASN_PARSE_E;
  3836. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  3837. return ASN_PARSE_E;
  3838. /* Option NULL ASN.1 tag */
  3839. if (*inOutIdx >= inSz) {
  3840. return BUFFER_E;
  3841. }
  3842. if (input[*inOutIdx] == ASN_TAG_NULL) {
  3843. ret = GetASNNull(input, inOutIdx, inSz);
  3844. if (ret != 0)
  3845. return ret;
  3846. }
  3847. /* should have bit tag length and seq next */
  3848. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  3849. if (ret != 0)
  3850. return ret;
  3851. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3852. return ASN_PARSE_E;
  3853. }
  3854. #endif /* OPENSSL_EXTRA */
  3855. /* Get modulus */
  3856. ret = GetASNInt(input, inOutIdx, &length, inSz);
  3857. *key_n += *inOutIdx;
  3858. if (ret < 0) {
  3859. return ASN_RSA_KEY_E;
  3860. }
  3861. if (key_n_len)
  3862. *key_n_len = length;
  3863. *inOutIdx += length;
  3864. /* Get exponent */
  3865. ret = GetASNInt(input, inOutIdx, &length, inSz);
  3866. *key_e += *inOutIdx;
  3867. if (ret < 0) {
  3868. return ASN_RSA_KEY_E;
  3869. }
  3870. if (key_e_len)
  3871. *key_e_len = length;
  3872. return ret;
  3873. }
  3874. #endif /* WOLFSSL_RENESAS_TSIP */
  3875. int wc_RsaPublicKeyDecode_ex(const byte* input, word32* inOutIdx, word32 inSz,
  3876. const byte** n, word32* nSz, const byte** e, word32* eSz)
  3877. {
  3878. int ret = 0;
  3879. int length = 0;
  3880. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  3881. word32 localIdx;
  3882. byte tag;
  3883. #endif
  3884. if (input == NULL || inOutIdx == NULL)
  3885. return BAD_FUNC_ARG;
  3886. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3887. return ASN_PARSE_E;
  3888. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  3889. localIdx = *inOutIdx;
  3890. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  3891. return BUFFER_E;
  3892. if (tag != ASN_INTEGER) {
  3893. /* not from decoded cert, will have algo id, skip past */
  3894. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3895. return ASN_PARSE_E;
  3896. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  3897. return ASN_PARSE_E;
  3898. /* Option NULL ASN.1 tag */
  3899. if (*inOutIdx >= inSz) {
  3900. return BUFFER_E;
  3901. }
  3902. localIdx = *inOutIdx;
  3903. if (GetASNTag(input, &localIdx, &tag, inSz) < 0)
  3904. return ASN_PARSE_E;
  3905. if (tag == ASN_TAG_NULL) {
  3906. ret = GetASNNull(input, inOutIdx, inSz);
  3907. if (ret != 0)
  3908. return ret;
  3909. }
  3910. /* should have bit tag length and seq next */
  3911. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  3912. if (ret != 0)
  3913. return ret;
  3914. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  3915. return ASN_PARSE_E;
  3916. }
  3917. #endif /* OPENSSL_EXTRA */
  3918. /* Get modulus */
  3919. ret = GetASNInt(input, inOutIdx, &length, inSz);
  3920. if (ret < 0) {
  3921. return ASN_RSA_KEY_E;
  3922. }
  3923. if (nSz)
  3924. *nSz = length;
  3925. if (n)
  3926. *n = &input[*inOutIdx];
  3927. *inOutIdx += length;
  3928. /* Get exponent */
  3929. ret = GetASNInt(input, inOutIdx, &length, inSz);
  3930. if (ret < 0) {
  3931. return ASN_RSA_KEY_E;
  3932. }
  3933. if (eSz)
  3934. *eSz = length;
  3935. if (e)
  3936. *e = &input[*inOutIdx];
  3937. *inOutIdx += length;
  3938. return ret;
  3939. }
  3940. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  3941. word32 inSz)
  3942. {
  3943. int ret;
  3944. const byte *n = NULL, *e = NULL;
  3945. word32 nSz = 0, eSz = 0;
  3946. if (key == NULL)
  3947. return BAD_FUNC_ARG;
  3948. ret = wc_RsaPublicKeyDecode_ex(input, inOutIdx, inSz, &n, &nSz, &e, &eSz);
  3949. if (ret == 0) {
  3950. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, e, eSz, key);
  3951. }
  3952. return ret;
  3953. }
  3954. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  3955. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  3956. word32 eSz, RsaKey* key)
  3957. {
  3958. if (n == NULL || e == NULL || key == NULL)
  3959. return BAD_FUNC_ARG;
  3960. key->type = RSA_PUBLIC;
  3961. if (mp_init(&key->n) != MP_OKAY)
  3962. return MP_INIT_E;
  3963. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  3964. mp_clear(&key->n);
  3965. return ASN_GETINT_E;
  3966. }
  3967. #ifdef HAVE_WOLF_BIGINT
  3968. if ((int)nSz > 0 && wc_bigint_from_unsigned_bin(&key->n.raw, n, nSz) != 0) {
  3969. mp_clear(&key->n);
  3970. return ASN_GETINT_E;
  3971. }
  3972. #endif /* HAVE_WOLF_BIGINT */
  3973. if (mp_init(&key->e) != MP_OKAY) {
  3974. mp_clear(&key->n);
  3975. return MP_INIT_E;
  3976. }
  3977. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  3978. mp_clear(&key->n);
  3979. mp_clear(&key->e);
  3980. return ASN_GETINT_E;
  3981. }
  3982. #ifdef HAVE_WOLF_BIGINT
  3983. if ((int)eSz > 0 && wc_bigint_from_unsigned_bin(&key->e.raw, e, eSz) != 0) {
  3984. mp_clear(&key->n);
  3985. mp_clear(&key->e);
  3986. return ASN_GETINT_E;
  3987. }
  3988. #endif /* HAVE_WOLF_BIGINT */
  3989. #ifdef WOLFSSL_XILINX_CRYPT
  3990. if (wc_InitRsaHw(key) != 0) {
  3991. return BAD_STATE_E;
  3992. }
  3993. #endif
  3994. return 0;
  3995. }
  3996. #endif /* HAVE_USER_RSA */
  3997. #endif /* !NO_RSA */
  3998. #ifndef NO_DH
  3999. /* Supports either:
  4000. * - DH params G/P (PKCS#3 DH) file or
  4001. * - DH key file (if WOLFSSL_DH_EXTRA enabled) */
  4002. /* The wc_DhParamsLoad function also loads DH params, but directly into buffers, not DhKey */
  4003. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  4004. {
  4005. int ret = 0;
  4006. int length;
  4007. #ifdef WOLFSSL_DH_EXTRA
  4008. #if !defined(HAVE_FIPS) || \
  4009. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  4010. word32 oid = 0, temp = 0;
  4011. #endif
  4012. #endif
  4013. WOLFSSL_ENTER("wc_DhKeyDecode");
  4014. if (inOutIdx == NULL)
  4015. return BAD_FUNC_ARG;
  4016. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4017. return ASN_PARSE_E;
  4018. #ifdef WOLFSSL_DH_EXTRA
  4019. #if !defined(HAVE_FIPS) || \
  4020. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  4021. temp = *inOutIdx;
  4022. #endif
  4023. #endif
  4024. /* Assume input started after 1.2.840.113549.1.3.1 dhKeyAgreement */
  4025. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  4026. ret = ASN_DH_KEY_E;
  4027. }
  4028. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  4029. mp_clear(&key->p);
  4030. ret = ASN_DH_KEY_E;
  4031. }
  4032. #ifdef WOLFSSL_DH_EXTRA
  4033. #if !defined(HAVE_FIPS) || \
  4034. (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))
  4035. /* If ASN_DH_KEY_E: Check if input started at beginning of key */
  4036. if (ret == ASN_DH_KEY_E) {
  4037. *inOutIdx = temp;
  4038. /* the version (0) */
  4039. if (GetASNInt(input, inOutIdx, &length, inSz) < 0) {
  4040. return ASN_PARSE_E;
  4041. }
  4042. *inOutIdx += length;
  4043. /* Size of dhKeyAgreement section */
  4044. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4045. return ASN_PARSE_E;
  4046. /* Check for dhKeyAgreement */
  4047. ret = GetObjectId(input, inOutIdx, &oid, oidKeyType, inSz);
  4048. if (oid != DHk || ret < 0)
  4049. return ASN_DH_KEY_E;
  4050. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4051. return ASN_PARSE_E;
  4052. if (GetInt(&key->p, input, inOutIdx, inSz) < 0) {
  4053. return ASN_DH_KEY_E;
  4054. }
  4055. if (ret == 0 && GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  4056. mp_clear(&key->p);
  4057. return ASN_DH_KEY_E;
  4058. }
  4059. }
  4060. temp = *inOutIdx;
  4061. ret = (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) == 0);
  4062. if (ret > 0) {
  4063. /* Found Bit String */
  4064. if (GetInt(&key->pub, input, inOutIdx, inSz) == 0) {
  4065. WOLFSSL_MSG("Found Public Key");
  4066. ret = 0;
  4067. }
  4068. } else {
  4069. *inOutIdx = temp;
  4070. ret = (GetOctetString(input, inOutIdx, &length, inSz) >= 0);
  4071. if (ret > 0) {
  4072. /* Found Octet String */
  4073. if (GetInt(&key->priv, input, inOutIdx, inSz) == 0) {
  4074. WOLFSSL_MSG("Found Private Key");
  4075. /* Compute public */
  4076. ret = mp_exptmod(&key->g, &key->priv, &key->p, &key->pub);
  4077. }
  4078. } else {
  4079. /* Don't use length from failed CheckBitString/GetOctetString */
  4080. *inOutIdx = temp;
  4081. ret = 0;
  4082. }
  4083. }
  4084. #endif /* !HAVE_FIPS || HAVE_FIPS_VERSION > 2 */
  4085. #endif /* WOLFSSL_DH_EXTRA */
  4086. WOLFSSL_LEAVE("wc_DhKeyDecode", ret);
  4087. return ret;
  4088. }
  4089. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  4090. byte* g, word32* gInOutSz)
  4091. {
  4092. word32 idx = 0;
  4093. int ret;
  4094. int length;
  4095. if (GetSequence(input, &idx, &length, inSz) <= 0)
  4096. return ASN_PARSE_E;
  4097. ret = GetASNInt(input, &idx, &length, inSz);
  4098. if (ret != 0)
  4099. return ret;
  4100. if (length <= (int)*pInOutSz) {
  4101. XMEMCPY(p, &input[idx], length);
  4102. *pInOutSz = length;
  4103. }
  4104. else {
  4105. return BUFFER_E;
  4106. }
  4107. idx += length;
  4108. ret = GetASNInt(input, &idx, &length, inSz);
  4109. if (ret != 0)
  4110. return ret;
  4111. if (length <= (int)*gInOutSz) {
  4112. XMEMCPY(g, &input[idx], length);
  4113. *gInOutSz = length;
  4114. }
  4115. else {
  4116. return BUFFER_E;
  4117. }
  4118. return 0;
  4119. }
  4120. #endif /* !NO_DH */
  4121. #ifndef NO_DSA
  4122. int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  4123. word32 inSz)
  4124. {
  4125. int length;
  4126. int ret = 0;
  4127. word32 oid;
  4128. if (input == NULL || inOutIdx == NULL || key == NULL)
  4129. return BAD_FUNC_ARG;
  4130. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4131. return ASN_PARSE_E;
  4132. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  4133. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  4134. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  4135. GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  4136. ret = ASN_DH_KEY_E;
  4137. if (ret != 0) {
  4138. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4139. return ASN_PARSE_E;
  4140. ret = GetObjectId(input, inOutIdx, &oid, oidIgnoreType, inSz);
  4141. if (ret != 0)
  4142. return ret;
  4143. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4144. return ASN_PARSE_E;
  4145. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  4146. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  4147. GetInt(&key->g, input, inOutIdx, inSz) < 0)
  4148. return ASN_DH_KEY_E;
  4149. if (CheckBitString(input, inOutIdx, &length, inSz, 0, NULL) < 0)
  4150. return ASN_PARSE_E;
  4151. if (GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  4152. return ASN_DH_KEY_E;
  4153. ret = 0;
  4154. }
  4155. key->type = DSA_PUBLIC;
  4156. return ret;
  4157. }
  4158. int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  4159. word32 inSz)
  4160. {
  4161. int length, version, ret = 0, temp = 0;
  4162. /* Sanity checks on input */
  4163. if (input == NULL || inOutIdx == NULL || key == NULL) {
  4164. return BAD_FUNC_ARG;
  4165. }
  4166. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  4167. return ASN_PARSE_E;
  4168. temp = (int)*inOutIdx;
  4169. /* Default case expects a certificate with OctetString but no version ID */
  4170. ret = GetInt(&key->p, input, inOutIdx, inSz);
  4171. if (ret < 0) {
  4172. mp_clear(&key->p);
  4173. ret = ASN_PARSE_E;
  4174. }
  4175. else {
  4176. ret = GetInt(&key->q, input, inOutIdx, inSz);
  4177. if (ret < 0) {
  4178. mp_clear(&key->p);
  4179. mp_clear(&key->q);
  4180. ret = ASN_PARSE_E;
  4181. }
  4182. else {
  4183. ret = GetInt(&key->g, input, inOutIdx, inSz);
  4184. if (ret < 0) {
  4185. mp_clear(&key->p);
  4186. mp_clear(&key->q);
  4187. mp_clear(&key->g);
  4188. ret = ASN_PARSE_E;
  4189. }
  4190. else {
  4191. ret = GetOctetString(input, inOutIdx, &length, inSz);
  4192. if (ret < 0) {
  4193. mp_clear(&key->p);
  4194. mp_clear(&key->q);
  4195. mp_clear(&key->g);
  4196. ret = ASN_PARSE_E;
  4197. }
  4198. else {
  4199. ret = GetInt(&key->y, input, inOutIdx, inSz);
  4200. if (ret < 0) {
  4201. mp_clear(&key->p);
  4202. mp_clear(&key->q);
  4203. mp_clear(&key->g);
  4204. mp_clear(&key->y);
  4205. ret = ASN_PARSE_E;
  4206. }
  4207. }
  4208. }
  4209. }
  4210. }
  4211. /* An alternate pass if default certificate fails parsing */
  4212. if (ret == ASN_PARSE_E) {
  4213. *inOutIdx = temp;
  4214. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  4215. return ASN_PARSE_E;
  4216. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  4217. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  4218. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  4219. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  4220. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  4221. return ASN_DH_KEY_E;
  4222. }
  4223. key->type = DSA_PRIVATE;
  4224. return 0;
  4225. }
  4226. static mp_int* GetDsaInt(DsaKey* key, int idx)
  4227. {
  4228. if (idx == 0)
  4229. return &key->p;
  4230. if (idx == 1)
  4231. return &key->q;
  4232. if (idx == 2)
  4233. return &key->g;
  4234. if (idx == 3)
  4235. return &key->y;
  4236. if (idx == 4)
  4237. return &key->x;
  4238. return NULL;
  4239. }
  4240. /* Release Tmp DSA resources */
  4241. static WC_INLINE void FreeTmpDsas(byte** tmps, void* heap)
  4242. {
  4243. int i;
  4244. for (i = 0; i < DSA_INTS; i++)
  4245. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  4246. (void)heap;
  4247. }
  4248. #if !defined(HAVE_SELFTEST) && (defined(WOLFSSL_KEY_GEN) || \
  4249. defined(WOLFSSL_CERT_GEN))
  4250. /* Write a public DSA key to output */
  4251. int wc_SetDsaPublicKey(byte* output, DsaKey* key,
  4252. int outLen, int with_header)
  4253. {
  4254. /* p, g, q = DSA params, y = public exponent */
  4255. #ifdef WOLFSSL_SMALL_STACK
  4256. byte* p = NULL;
  4257. byte* g = NULL;
  4258. byte* q = NULL;
  4259. byte* y = NULL;
  4260. #else
  4261. byte p[MAX_DSA_INT_SZ];
  4262. byte g[MAX_DSA_INT_SZ];
  4263. byte q[MAX_DSA_INT_SZ];
  4264. byte y[MAX_DSA_INT_SZ];
  4265. #endif
  4266. byte innerSeq[MAX_SEQ_SZ];
  4267. byte outerSeq[MAX_SEQ_SZ];
  4268. byte bitString[1 + MAX_LENGTH_SZ + 1];
  4269. int idx, pSz, gSz, qSz, ySz, innerSeqSz, outerSeqSz, bitStringSz = 0;
  4270. WOLFSSL_ENTER("wc_SetDsaPublicKey");
  4271. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ) {
  4272. return BAD_FUNC_ARG;
  4273. }
  4274. /* p */
  4275. #ifdef WOLFSSL_SMALL_STACK
  4276. p = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4277. if (p == NULL)
  4278. return MEMORY_E;
  4279. #endif
  4280. if ((pSz = SetASNIntMP(&key->p, MAX_DSA_INT_SZ, p)) < 0) {
  4281. WOLFSSL_MSG("SetASNIntMP Error with p");
  4282. #ifdef WOLFSSL_SMALL_STACK
  4283. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4284. #endif
  4285. return pSz;
  4286. }
  4287. /* q */
  4288. #ifdef WOLFSSL_SMALL_STACK
  4289. q = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4290. if (q == NULL)
  4291. return MEMORY_E;
  4292. #endif
  4293. if ((qSz = SetASNIntMP(&key->q, MAX_DSA_INT_SZ, q)) < 0) {
  4294. WOLFSSL_MSG("SetASNIntMP Error with q");
  4295. #ifdef WOLFSSL_SMALL_STACK
  4296. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4297. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4298. #endif
  4299. return qSz;
  4300. }
  4301. /* g */
  4302. #ifdef WOLFSSL_SMALL_STACK
  4303. g = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4304. if (g == NULL)
  4305. return MEMORY_E;
  4306. #endif
  4307. if ((gSz = SetASNIntMP(&key->g, MAX_DSA_INT_SZ, g)) < 0) {
  4308. WOLFSSL_MSG("SetASNIntMP Error with g");
  4309. #ifdef WOLFSSL_SMALL_STACK
  4310. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4311. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4312. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4313. #endif
  4314. return gSz;
  4315. }
  4316. /* y */
  4317. #ifdef WOLFSSL_SMALL_STACK
  4318. y = (byte*)XMALLOC(MAX_DSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4319. if (y == NULL)
  4320. return MEMORY_E;
  4321. #endif
  4322. if ((ySz = SetASNIntMP(&key->y, MAX_DSA_INT_SZ, y)) < 0) {
  4323. WOLFSSL_MSG("SetASNIntMP Error with y");
  4324. #ifdef WOLFSSL_SMALL_STACK
  4325. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4326. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4327. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4328. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4329. #endif
  4330. return ySz;
  4331. }
  4332. innerSeqSz = SetSequence(pSz + qSz + gSz, innerSeq);
  4333. /* check output size */
  4334. if ((innerSeqSz + pSz + qSz + gSz) > outLen) {
  4335. #ifdef WOLFSSL_SMALL_STACK
  4336. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4337. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4338. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4339. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4340. #endif
  4341. WOLFSSL_MSG("Error, output size smaller than outlen");
  4342. return BUFFER_E;
  4343. }
  4344. if (with_header) {
  4345. int algoSz;
  4346. #ifdef WOLFSSL_SMALL_STACK
  4347. byte* algo = NULL;
  4348. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4349. if (algo == NULL) {
  4350. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4351. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4352. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4353. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4354. return MEMORY_E;
  4355. }
  4356. #else
  4357. byte algo[MAX_ALGO_SZ];
  4358. #endif
  4359. algoSz = SetAlgoID(DSAk, algo, oidKeyType, 0);
  4360. bitStringSz = SetBitString(ySz, 0, bitString);
  4361. outerSeqSz = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz,
  4362. outerSeq);
  4363. idx = SetSequence(algoSz + innerSeqSz + pSz + qSz + gSz + bitStringSz +
  4364. ySz + outerSeqSz, output);
  4365. /* check output size */
  4366. if ((idx + algoSz + bitStringSz + innerSeqSz + pSz + qSz + gSz + ySz) >
  4367. outLen) {
  4368. #ifdef WOLFSSL_SMALL_STACK
  4369. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4370. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4371. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4372. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4373. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4374. #endif
  4375. WOLFSSL_MSG("Error, output size smaller than outlen");
  4376. return BUFFER_E;
  4377. }
  4378. /* outerSeq */
  4379. XMEMCPY(output + idx, outerSeq, outerSeqSz);
  4380. idx += outerSeqSz;
  4381. /* algo */
  4382. XMEMCPY(output + idx, algo, algoSz);
  4383. idx += algoSz;
  4384. #ifdef WOLFSSL_SMALL_STACK
  4385. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4386. #endif
  4387. } else {
  4388. idx = 0;
  4389. }
  4390. /* innerSeq */
  4391. XMEMCPY(output + idx, innerSeq, innerSeqSz);
  4392. idx += innerSeqSz;
  4393. /* p */
  4394. XMEMCPY(output + idx, p, pSz);
  4395. idx += pSz;
  4396. /* q */
  4397. XMEMCPY(output + idx, q, qSz);
  4398. idx += qSz;
  4399. /* g */
  4400. XMEMCPY(output + idx, g, gSz);
  4401. idx += gSz;
  4402. /* bit string */
  4403. if (bitStringSz > 0) {
  4404. XMEMCPY(output + idx, bitString, bitStringSz);
  4405. idx += bitStringSz;
  4406. }
  4407. /* y */
  4408. XMEMCPY(output + idx, y, ySz);
  4409. idx += ySz;
  4410. #ifdef WOLFSSL_SMALL_STACK
  4411. XFREE(p, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4412. XFREE(q, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4413. XFREE(g, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4414. XFREE(y, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4415. #endif
  4416. return idx;
  4417. }
  4418. /* Convert DSA Public key to DER format, write to output (inLen), return bytes
  4419. written */
  4420. int wc_DsaKeyToPublicDer(DsaKey* key, byte* output, word32 inLen)
  4421. {
  4422. return wc_SetDsaPublicKey(output, key, inLen, 1);
  4423. }
  4424. #endif /* !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  4425. /* Convert private DsaKey key to DER format, write to output (inLen),
  4426. return bytes written */
  4427. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  4428. {
  4429. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  4430. word32 sizes[DSA_INTS];
  4431. int i, j, outLen, ret = 0, mpSz;
  4432. byte seq[MAX_SEQ_SZ];
  4433. byte ver[MAX_VERSION_SZ];
  4434. byte* tmps[DSA_INTS];
  4435. if (!key || !output)
  4436. return BAD_FUNC_ARG;
  4437. if (key->type != DSA_PRIVATE)
  4438. return BAD_FUNC_ARG;
  4439. for (i = 0; i < DSA_INTS; i++)
  4440. tmps[i] = NULL;
  4441. /* write all big ints from key to DER tmps */
  4442. for (i = 0; i < DSA_INTS; i++) {
  4443. mp_int* keyInt = GetDsaInt(key, i);
  4444. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  4445. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  4446. DYNAMIC_TYPE_DSA);
  4447. if (tmps[i] == NULL) {
  4448. ret = MEMORY_E;
  4449. break;
  4450. }
  4451. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  4452. if (mpSz < 0) {
  4453. ret = mpSz;
  4454. break;
  4455. }
  4456. intTotalLen += (sizes[i] = mpSz);
  4457. }
  4458. if (ret != 0) {
  4459. FreeTmpDsas(tmps, key->heap);
  4460. return ret;
  4461. }
  4462. /* make headers */
  4463. verSz = SetMyVersion(0, ver, FALSE);
  4464. seqSz = SetSequence(verSz + intTotalLen, seq);
  4465. outLen = seqSz + verSz + intTotalLen;
  4466. if (outLen > (int)inLen) {
  4467. FreeTmpDsas(tmps, key->heap);
  4468. return BAD_FUNC_ARG;
  4469. }
  4470. /* write to output */
  4471. XMEMCPY(output, seq, seqSz);
  4472. j = seqSz;
  4473. XMEMCPY(output + j, ver, verSz);
  4474. j += verSz;
  4475. for (i = 0; i < DSA_INTS; i++) {
  4476. XMEMCPY(output + j, tmps[i], sizes[i]);
  4477. j += sizes[i];
  4478. }
  4479. FreeTmpDsas(tmps, key->heap);
  4480. return outLen;
  4481. }
  4482. #endif /* NO_DSA */
  4483. void InitDecodedCert(DecodedCert* cert,
  4484. const byte* source, word32 inSz, void* heap)
  4485. {
  4486. if (cert != NULL) {
  4487. XMEMSET(cert, 0, sizeof(DecodedCert));
  4488. cert->subjectCNEnc = CTC_UTF8;
  4489. cert->issuer[0] = '\0';
  4490. cert->subject[0] = '\0';
  4491. cert->source = source; /* don't own */
  4492. cert->maxIdx = inSz; /* can't go over this index */
  4493. cert->heap = heap;
  4494. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  4495. #ifdef WOLFSSL_CERT_GEN
  4496. cert->subjectSNEnc = CTC_UTF8;
  4497. cert->subjectCEnc = CTC_PRINTABLE;
  4498. cert->subjectLEnc = CTC_UTF8;
  4499. cert->subjectSTEnc = CTC_UTF8;
  4500. cert->subjectOEnc = CTC_UTF8;
  4501. cert->subjectOUEnc = CTC_UTF8;
  4502. #endif /* WOLFSSL_CERT_GEN */
  4503. #ifndef NO_CERTS
  4504. InitSignatureCtx(&cert->sigCtx, heap, INVALID_DEVID);
  4505. #endif
  4506. }
  4507. }
  4508. void FreeAltNames(DNS_entry* altNames, void* heap)
  4509. {
  4510. (void)heap;
  4511. while (altNames) {
  4512. DNS_entry* tmp = altNames->next;
  4513. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  4514. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  4515. altNames = tmp;
  4516. }
  4517. }
  4518. #ifndef IGNORE_NAME_CONSTRAINTS
  4519. void FreeNameSubtrees(Base_entry* names, void* heap)
  4520. {
  4521. (void)heap;
  4522. while (names) {
  4523. Base_entry* tmp = names->next;
  4524. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  4525. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  4526. names = tmp;
  4527. }
  4528. }
  4529. #endif /* IGNORE_NAME_CONSTRAINTS */
  4530. void FreeDecodedCert(DecodedCert* cert)
  4531. {
  4532. if (cert == NULL)
  4533. return;
  4534. if (cert->subjectCNStored == 1)
  4535. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  4536. if (cert->pubKeyStored == 1)
  4537. XFREE((void*)cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  4538. if (cert->weOwnAltNames && cert->altNames)
  4539. FreeAltNames(cert->altNames, cert->heap);
  4540. #ifndef IGNORE_NAME_CONSTRAINTS
  4541. if (cert->altEmailNames)
  4542. FreeAltNames(cert->altEmailNames, cert->heap);
  4543. if (cert->altDirNames)
  4544. FreeAltNames(cert->altDirNames, cert->heap);
  4545. if (cert->permittedNames)
  4546. FreeNameSubtrees(cert->permittedNames, cert->heap);
  4547. if (cert->excludedNames)
  4548. FreeNameSubtrees(cert->excludedNames, cert->heap);
  4549. #endif /* IGNORE_NAME_CONSTRAINTS */
  4550. #ifdef WOLFSSL_SEP
  4551. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  4552. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  4553. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  4554. #endif /* WOLFSSL_SEP */
  4555. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  4556. !defined(WOLFCRYPT_ONLY)
  4557. if (cert->issuerName != NULL)
  4558. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->issuerName);
  4559. if (cert->subjectName != NULL)
  4560. wolfSSL_X509_NAME_free((WOLFSSL_X509_NAME*)cert->subjectName);
  4561. #endif /* OPENSSL_EXTRA */
  4562. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  4563. if (cert->tsip_encRsaKeyIdx != NULL)
  4564. XFREE(cert->tsip_encRsaKeyIdx, cert->heap, DYNAMIC_TYPE_RSA);
  4565. #endif
  4566. #ifndef NO_CERTS
  4567. FreeSignatureCtx(&cert->sigCtx);
  4568. #endif
  4569. }
  4570. static int GetCertHeader(DecodedCert* cert)
  4571. {
  4572. int ret = 0, len;
  4573. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  4574. return ASN_PARSE_E;
  4575. /* Reset the max index for the size indicated in the outer wrapper. */
  4576. cert->maxIdx = len + cert->srcIdx;
  4577. cert->certBegin = cert->srcIdx;
  4578. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  4579. return ASN_PARSE_E;
  4580. cert->sigIndex = len + cert->srcIdx;
  4581. if (cert->sigIndex > cert->maxIdx)
  4582. return ASN_PARSE_E;
  4583. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  4584. cert->sigIndex) < 0)
  4585. return ASN_PARSE_E;
  4586. if (GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  4587. &cert->serialSz, cert->sigIndex) < 0)
  4588. return ASN_PARSE_E;
  4589. return ret;
  4590. }
  4591. #if !defined(NO_RSA)
  4592. /* Store Rsa Key, may save later, Dsa could use in future */
  4593. static int StoreRsaKey(DecodedCert* cert, word32 bitStringEnd)
  4594. {
  4595. int length;
  4596. word32 recvd = cert->srcIdx;
  4597. if (GetSequence(cert->source, &cert->srcIdx, &length, bitStringEnd) < 0)
  4598. return ASN_PARSE_E;
  4599. recvd = cert->srcIdx - recvd;
  4600. length += recvd;
  4601. while (recvd--)
  4602. cert->srcIdx--;
  4603. #if defined(WOLFSSL_RENESAS_TSIP)
  4604. cert->sigCtx.pubkey_n_start = cert->sigCtx.pubkey_e_start = cert->srcIdx;
  4605. #endif
  4606. cert->pubKeySize = length;
  4607. cert->publicKey = cert->source + cert->srcIdx;
  4608. cert->srcIdx += length;
  4609. return 0;
  4610. }
  4611. #endif /* !NO_RSA */
  4612. #ifdef HAVE_ECC
  4613. /* return 0 on success if the ECC curve oid sum is supported */
  4614. static int CheckCurve(word32 oid)
  4615. {
  4616. int ret = 0;
  4617. word32 oidSz = 0;
  4618. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  4619. if (ret < 0 || oidSz == 0) {
  4620. WOLFSSL_MSG("CheckCurve not found");
  4621. ret = ALGO_ID_E;
  4622. }
  4623. return ret;
  4624. }
  4625. #endif /* HAVE_ECC */
  4626. static int GetKey(DecodedCert* cert)
  4627. {
  4628. int length;
  4629. #ifndef NO_DSA
  4630. int tmpLen;
  4631. #endif
  4632. #if defined(HAVE_ECC) || defined(HAVE_NTRU) || !defined(NO_DSA)
  4633. int tmpIdx = cert->srcIdx;
  4634. #endif
  4635. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  4636. return ASN_PARSE_E;
  4637. #ifndef NO_DSA
  4638. tmpLen = length + 4;
  4639. #endif
  4640. if (GetAlgoId(cert->source, &cert->srcIdx,
  4641. &cert->keyOID, oidKeyType, cert->maxIdx) < 0)
  4642. return ASN_PARSE_E;
  4643. switch (cert->keyOID) {
  4644. #ifndef NO_RSA
  4645. case RSAk:
  4646. {
  4647. int ret;
  4648. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  4649. cert->maxIdx, 1, NULL);
  4650. if (ret != 0)
  4651. return ret;
  4652. #ifdef HAVE_OCSP
  4653. ret = CalcHashId(cert->source + cert->srcIdx, length,
  4654. cert->subjectKeyHash);
  4655. if (ret != 0)
  4656. return ret;
  4657. #endif
  4658. return StoreRsaKey(cert, cert->srcIdx + length);
  4659. }
  4660. #endif /* NO_RSA */
  4661. #ifdef HAVE_NTRU
  4662. case NTRUk:
  4663. {
  4664. const byte* key = &cert->source[tmpIdx];
  4665. byte* next = (byte*)key;
  4666. word16 keyLen;
  4667. word32 rc;
  4668. word32 remaining = cert->maxIdx - cert->srcIdx;
  4669. byte* publicKey;
  4670. #ifdef WOLFSSL_SMALL_STACK
  4671. byte* keyBlob = NULL;
  4672. #else
  4673. byte keyBlob[MAX_NTRU_KEY_SZ];
  4674. #endif
  4675. rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  4676. &keyLen, NULL, &next, &remaining);
  4677. if (rc != NTRU_OK)
  4678. return ASN_NTRU_KEY_E;
  4679. if (keyLen > MAX_NTRU_KEY_SZ)
  4680. return ASN_NTRU_KEY_E;
  4681. #ifdef WOLFSSL_SMALL_STACK
  4682. keyBlob = (byte*)XMALLOC(MAX_NTRU_KEY_SZ, cert->heap,
  4683. DYNAMIC_TYPE_TMP_BUFFER);
  4684. if (keyBlob == NULL)
  4685. return MEMORY_E;
  4686. #endif
  4687. rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  4688. &keyLen, keyBlob, &next, &remaining);
  4689. if (rc != NTRU_OK) {
  4690. #ifdef WOLFSSL_SMALL_STACK
  4691. XFREE(keyBlob, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4692. #endif
  4693. return ASN_NTRU_KEY_E;
  4694. }
  4695. if ( (next - key) < 0) {
  4696. #ifdef WOLFSSL_SMALL_STACK
  4697. XFREE(keyBlob, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4698. #endif
  4699. return ASN_NTRU_KEY_E;
  4700. }
  4701. cert->srcIdx = tmpIdx + (int)(next - key);
  4702. publicKey = (byte*)XMALLOC(keyLen, cert->heap,
  4703. DYNAMIC_TYPE_PUBLIC_KEY);
  4704. if (publicKey == NULL) {
  4705. #ifdef WOLFSSL_SMALL_STACK
  4706. XFREE(keyBlob, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4707. #endif
  4708. return MEMORY_E;
  4709. }
  4710. XMEMCPY(publicKey, keyBlob, keyLen);
  4711. cert->publicKey = publicKey;
  4712. cert->pubKeyStored = 1;
  4713. cert->pubKeySize = keyLen;
  4714. #ifdef WOLFSSL_SMALL_STACK
  4715. XFREE(keyBlob, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4716. #endif
  4717. return 0;
  4718. }
  4719. #endif /* HAVE_NTRU */
  4720. #ifdef HAVE_ECC
  4721. case ECDSAk:
  4722. {
  4723. int ret;
  4724. byte seq[5];
  4725. int pubLen = length + 1 + SetLength(length, seq);
  4726. word32 localIdx;
  4727. byte* publicKey;
  4728. byte tag;
  4729. localIdx = cert->srcIdx;
  4730. if (GetASNTag(cert->source, &localIdx, &tag, cert->maxIdx) < 0)
  4731. return ASN_PARSE_E;
  4732. if (tag != (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  4733. if (GetObjectId(cert->source, &cert->srcIdx,
  4734. &cert->pkCurveOID, oidCurveType, cert->maxIdx) < 0)
  4735. return ASN_PARSE_E;
  4736. if (CheckCurve(cert->pkCurveOID) < 0)
  4737. return ECC_CURVE_OID_E;
  4738. /* key header */
  4739. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  4740. cert->maxIdx, 1, NULL);
  4741. if (ret != 0)
  4742. return ret;
  4743. #ifdef HAVE_OCSP
  4744. ret = CalcHashId(cert->source + cert->srcIdx, length,
  4745. cert->subjectKeyHash);
  4746. if (ret != 0)
  4747. return ret;
  4748. #endif
  4749. }
  4750. publicKey = (byte*)XMALLOC(pubLen, cert->heap,
  4751. DYNAMIC_TYPE_PUBLIC_KEY);
  4752. if (publicKey == NULL)
  4753. return MEMORY_E;
  4754. XMEMCPY(publicKey, &cert->source[tmpIdx], pubLen);
  4755. cert->publicKey = publicKey;
  4756. cert->pubKeyStored = 1;
  4757. cert->pubKeySize = pubLen;
  4758. cert->srcIdx = tmpIdx + pubLen;
  4759. return 0;
  4760. }
  4761. #endif /* HAVE_ECC */
  4762. #ifdef HAVE_ED25519
  4763. case ED25519k:
  4764. {
  4765. byte* publicKey;
  4766. int ret;
  4767. cert->pkCurveOID = ED25519k;
  4768. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  4769. cert->maxIdx, 1, NULL);
  4770. if (ret != 0)
  4771. return ret;
  4772. #ifdef HAVE_OCSP
  4773. ret = CalcHashId(cert->source + cert->srcIdx, length,
  4774. cert->subjectKeyHash);
  4775. if (ret != 0)
  4776. return ret;
  4777. #endif
  4778. publicKey = (byte*) XMALLOC(length, cert->heap,
  4779. DYNAMIC_TYPE_PUBLIC_KEY);
  4780. if (publicKey == NULL)
  4781. return MEMORY_E;
  4782. XMEMCPY(publicKey, &cert->source[cert->srcIdx], length);
  4783. cert->publicKey = publicKey;
  4784. cert->pubKeyStored = 1;
  4785. cert->pubKeySize = length;
  4786. cert->srcIdx += length;
  4787. return 0;
  4788. }
  4789. #endif /* HAVE_ED25519 */
  4790. #ifdef HAVE_ED448
  4791. case ED448k:
  4792. {
  4793. byte* publicKey;
  4794. int ret;
  4795. cert->pkCurveOID = ED448k;
  4796. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  4797. cert->maxIdx, 1, NULL);
  4798. if (ret != 0)
  4799. return ret;
  4800. #ifdef HAVE_OCSP
  4801. ret = CalcHashId(cert->source + cert->srcIdx, length,
  4802. cert->subjectKeyHash);
  4803. if (ret != 0)
  4804. return ret;
  4805. #endif
  4806. publicKey = (byte*) XMALLOC(length, cert->heap,
  4807. DYNAMIC_TYPE_PUBLIC_KEY);
  4808. if (publicKey == NULL)
  4809. return MEMORY_E;
  4810. XMEMCPY(publicKey, &cert->source[cert->srcIdx], length);
  4811. cert->publicKey = publicKey;
  4812. cert->pubKeyStored = 1;
  4813. cert->pubKeySize = length;
  4814. cert->srcIdx += length;
  4815. return 0;
  4816. }
  4817. #endif /* HAVE_ED448 */
  4818. #ifndef NO_DSA
  4819. case DSAk:
  4820. {
  4821. int ret;
  4822. ret = GetSequence(cert->source, &cert->srcIdx, &length,
  4823. cert->maxIdx);
  4824. if (ret < 0)
  4825. return ret;
  4826. ret = SkipInt(cert->source, &cert->srcIdx, cert->maxIdx);
  4827. if (ret != 0)
  4828. return ret;
  4829. ret = SkipInt(cert->source, &cert->srcIdx, cert->maxIdx);
  4830. if (ret != 0)
  4831. return ret;
  4832. ret = SkipInt(cert->source, &cert->srcIdx, cert->maxIdx);
  4833. if (ret != 0)
  4834. return ret;
  4835. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  4836. cert->maxIdx, 1, NULL);
  4837. if (ret != 0)
  4838. return ret;
  4839. ret = GetASNInt(cert->source, &cert->srcIdx, &length, cert->maxIdx);
  4840. if (ret !=0)
  4841. return ASN_PARSE_E;
  4842. cert->publicKey = cert->source + tmpIdx;
  4843. cert->pubKeySize = tmpLen;
  4844. cert->srcIdx += length;
  4845. return 0;
  4846. }
  4847. #endif /* NO_DSA */
  4848. default:
  4849. WOLFSSL_MSG("Unknown or not compiled in key OID");
  4850. return ASN_UNKNOWN_OID_E;
  4851. }
  4852. }
  4853. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4854. #if defined(HAVE_ECC)
  4855. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  4856. value */
  4857. WOLFSSL_API int EccEnumToNID(int n)
  4858. {
  4859. WOLFSSL_ENTER("EccEnumToNID()");
  4860. switch(n) {
  4861. case ECC_SECP192R1:
  4862. return NID_X9_62_prime192v1;
  4863. case ECC_PRIME192V2:
  4864. return NID_X9_62_prime192v2;
  4865. case ECC_PRIME192V3:
  4866. return NID_X9_62_prime192v3;
  4867. case ECC_PRIME239V1:
  4868. return NID_X9_62_prime239v1;
  4869. case ECC_PRIME239V2:
  4870. return NID_X9_62_prime239v2;
  4871. case ECC_PRIME239V3:
  4872. return NID_X9_62_prime239v3;
  4873. case ECC_SECP256R1:
  4874. return NID_X9_62_prime256v1;
  4875. case ECC_SECP112R1:
  4876. return NID_secp112r1;
  4877. case ECC_SECP112R2:
  4878. return NID_secp112r2;
  4879. case ECC_SECP128R1:
  4880. return NID_secp128r1;
  4881. case ECC_SECP128R2:
  4882. return NID_secp128r2;
  4883. case ECC_SECP160R1:
  4884. return NID_secp160r1;
  4885. case ECC_SECP160R2:
  4886. return NID_secp160r2;
  4887. case ECC_SECP224R1:
  4888. return NID_secp224r1;
  4889. case ECC_SECP384R1:
  4890. return NID_secp384r1;
  4891. case ECC_SECP521R1:
  4892. return NID_secp521r1;
  4893. case ECC_SECP160K1:
  4894. return NID_secp160k1;
  4895. case ECC_SECP192K1:
  4896. return NID_secp192k1;
  4897. case ECC_SECP224K1:
  4898. return NID_secp224k1;
  4899. case ECC_SECP256K1:
  4900. return NID_secp256k1;
  4901. case ECC_BRAINPOOLP160R1:
  4902. return NID_brainpoolP160r1;
  4903. case ECC_BRAINPOOLP192R1:
  4904. return NID_brainpoolP192r1;
  4905. case ECC_BRAINPOOLP224R1:
  4906. return NID_brainpoolP224r1;
  4907. case ECC_BRAINPOOLP256R1:
  4908. return NID_brainpoolP256r1;
  4909. case ECC_BRAINPOOLP320R1:
  4910. return NID_brainpoolP320r1;
  4911. case ECC_BRAINPOOLP384R1:
  4912. return NID_brainpoolP384r1;
  4913. case ECC_BRAINPOOLP512R1:
  4914. return NID_brainpoolP512r1;
  4915. default:
  4916. WOLFSSL_MSG("NID not found");
  4917. return -1;
  4918. }
  4919. }
  4920. #endif /* HAVE_ECC */
  4921. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4922. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4923. int wc_OBJ_sn2nid(const char *sn)
  4924. {
  4925. const struct {
  4926. const char *sn;
  4927. int nid;
  4928. } sn2nid[] = {
  4929. {WOLFSSL_COMMON_NAME, NID_commonName},
  4930. {WOLFSSL_COUNTRY_NAME, NID_countryName},
  4931. {WOLFSSL_LOCALITY_NAME, NID_localityName},
  4932. {WOLFSSL_STATE_NAME, NID_stateOrProvinceName},
  4933. {WOLFSSL_ORG_NAME, NID_organizationName},
  4934. {WOLFSSL_ORGUNIT_NAME, NID_organizationalUnitName},
  4935. {WOLFSSL_EMAIL_ADDR, NID_emailAddress},
  4936. {NULL, -1}};
  4937. int i;
  4938. #ifdef HAVE_ECC
  4939. char curveName[16]; /* Same as MAX_CURVE_NAME_SZ but can't include that
  4940. * symbol in this file */
  4941. int eccEnum;
  4942. #endif
  4943. WOLFSSL_ENTER("OBJ_sn2nid");
  4944. for(i=0; sn2nid[i].sn != NULL; i++) {
  4945. if(XSTRNCMP(sn, sn2nid[i].sn, XSTRLEN(sn2nid[i].sn)) == 0) {
  4946. return sn2nid[i].nid;
  4947. }
  4948. }
  4949. #ifdef HAVE_ECC
  4950. /* Nginx uses this OpenSSL string. */
  4951. if (XSTRNCMP(sn, "prime256v1", 10) == 0)
  4952. sn = "SECP256R1";
  4953. /* OpenSSL allows lowercase curve names */
  4954. for (i = 0; i < (int)(sizeof(curveName) - 1) && *sn; i++) {
  4955. curveName[i] = (char)XTOUPPER(*sn++);
  4956. }
  4957. curveName[i] = '\0';
  4958. /* find based on name and return NID */
  4959. for (i = 0;
  4960. #ifndef WOLFSSL_ECC_CURVE_STATIC
  4961. ecc_sets[i].size != 0 && ecc_sets[i].name != NULL;
  4962. #else
  4963. ecc_sets[i].size != 0;
  4964. #endif
  4965. i++) {
  4966. if (XSTRNCMP(curveName, ecc_sets[i].name, ECC_MAXNAME) == 0) {
  4967. eccEnum = ecc_sets[i].id;
  4968. /* Convert enum value in ecc_curve_id to OpenSSL NID */
  4969. return EccEnumToNID(eccEnum);
  4970. }
  4971. }
  4972. #endif
  4973. return NID_undef;
  4974. }
  4975. #endif
  4976. /* Routine for calculating hashId */
  4977. int CalcHashId(const byte* data, word32 len, byte* hash)
  4978. {
  4979. int ret;
  4980. #if defined(NO_SHA) && !defined(NO_SHA256)
  4981. ret = wc_Sha256Hash(data, len, hash);
  4982. #elif !defined(NO_SHA)
  4983. ret = wc_ShaHash(data, len, hash);
  4984. #else
  4985. ret = NOT_COMPILED_IN;
  4986. (void)data;
  4987. (void)len;
  4988. (void)hash;
  4989. #endif
  4990. return ret;
  4991. }
  4992. /* process NAME, either issuer or subject
  4993. * returns 0 on success and negative values on fail */
  4994. int GetName(DecodedCert* cert, int nameType, int maxIdx)
  4995. {
  4996. int length; /* length of all distinguished names */
  4997. int dummy;
  4998. int ret;
  4999. char* full;
  5000. byte* hash;
  5001. word32 idx, localIdx = 0;
  5002. byte tag;
  5003. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5004. !defined(WOLFCRYPT_ONLY)
  5005. WOLFSSL_X509_NAME* dName;
  5006. #endif /* OPENSSL_EXTRA */
  5007. WOLFSSL_MSG("Getting Cert Name");
  5008. if (nameType == ISSUER) {
  5009. full = cert->issuer;
  5010. hash = cert->issuerHash;
  5011. }
  5012. else {
  5013. full = cert->subject;
  5014. hash = cert->subjectHash;
  5015. }
  5016. if (cert->srcIdx >= (word32)maxIdx) {
  5017. return BUFFER_E;
  5018. }
  5019. localIdx = cert->srcIdx;
  5020. if (GetASNTag(cert->source, &localIdx, &tag, maxIdx) < 0) {
  5021. return ASN_PARSE_E;
  5022. }
  5023. if (tag == ASN_OBJECT_ID) {
  5024. WOLFSSL_MSG("Trying optional prefix...");
  5025. if (SkipObjectId(cert->source, &cert->srcIdx, maxIdx) < 0)
  5026. return ASN_PARSE_E;
  5027. WOLFSSL_MSG("Got optional prefix");
  5028. }
  5029. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  5030. * calculated over the entire DER encoding of the Name field, including
  5031. * the tag and length. */
  5032. idx = cert->srcIdx;
  5033. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  5034. return ASN_PARSE_E;
  5035. ret = CalcHashId(&cert->source[idx], length + cert->srcIdx - idx, hash);
  5036. if (ret != 0)
  5037. return ret;
  5038. length += cert->srcIdx;
  5039. idx = 0;
  5040. #if defined(HAVE_PKCS7) || defined(WOLFSSL_CERT_EXT)
  5041. /* store pointer to raw issuer */
  5042. if (nameType == ISSUER) {
  5043. cert->issuerRaw = &cert->source[cert->srcIdx];
  5044. cert->issuerRawLen = length - cert->srcIdx;
  5045. }
  5046. #endif
  5047. #ifndef IGNORE_NAME_CONSTRAINTS
  5048. if (nameType == SUBJECT) {
  5049. cert->subjectRaw = &cert->source[cert->srcIdx];
  5050. cert->subjectRawLen = length - cert->srcIdx;
  5051. }
  5052. #endif
  5053. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5054. !defined(WOLFCRYPT_ONLY)
  5055. dName = wolfSSL_X509_NAME_new();
  5056. if (dName == NULL) {
  5057. return MEMORY_E;
  5058. }
  5059. #endif /* OPENSSL_EXTRA */
  5060. while (cert->srcIdx < (word32)length) {
  5061. byte b = 0;
  5062. byte joint[3];
  5063. byte tooBig = FALSE;
  5064. int oidSz;
  5065. const char* copy = NULL;
  5066. int copyLen = 0;
  5067. int strLen = 0;
  5068. byte id = 0;
  5069. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  5070. && !defined(WOLFCRYPT_ONLY)
  5071. int nid = NID_undef;
  5072. int enc;
  5073. #endif /* OPENSSL_EXTRA */
  5074. if (GetSet(cert->source, &cert->srcIdx, &dummy, maxIdx) < 0) {
  5075. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  5076. }
  5077. if (GetSequence(cert->source, &cert->srcIdx, &dummy, maxIdx) <= 0) {
  5078. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5079. !defined(WOLFCRYPT_ONLY)
  5080. wolfSSL_X509_NAME_free(dName);
  5081. #endif /* OPENSSL_EXTRA */
  5082. return ASN_PARSE_E;
  5083. }
  5084. ret = GetASNObjectId(cert->source, &cert->srcIdx, &oidSz, maxIdx);
  5085. if (ret != 0) {
  5086. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5087. !defined(WOLFCRYPT_ONLY)
  5088. wolfSSL_X509_NAME_free(dName);
  5089. #endif /* OPENSSL_EXTRA */
  5090. return ret;
  5091. }
  5092. /* make sure there is room for joint */
  5093. if ((cert->srcIdx + sizeof(joint)) > (word32)maxIdx) {
  5094. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5095. !defined(WOLFCRYPT_ONLY)
  5096. wolfSSL_X509_NAME_free(dName);
  5097. #endif /* OPENSSL_EXTRA */
  5098. return ASN_PARSE_E;
  5099. }
  5100. XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
  5101. /* v1 name types */
  5102. if (joint[0] == 0x55 && joint[1] == 0x04) {
  5103. cert->srcIdx += 3;
  5104. id = joint[2];
  5105. if (GetHeader(cert->source, &b, &cert->srcIdx, &strLen,
  5106. maxIdx, 1) < 0) {
  5107. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5108. !defined(WOLFCRYPT_ONLY)
  5109. wolfSSL_X509_NAME_free(dName);
  5110. #endif /* OPENSSL_EXTRA */
  5111. return ASN_PARSE_E;
  5112. }
  5113. if (id == ASN_COMMON_NAME) {
  5114. if (nameType == SUBJECT) {
  5115. cert->subjectCN = (char *)&cert->source[cert->srcIdx];
  5116. cert->subjectCNLen = strLen;
  5117. cert->subjectCNEnc = b;
  5118. }
  5119. copy = WOLFSSL_COMMON_NAME;
  5120. copyLen = sizeof(WOLFSSL_COMMON_NAME) - 1;
  5121. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  5122. && !defined(WOLFCRYPT_ONLY)
  5123. nid = NID_commonName;
  5124. #endif /* OPENSSL_EXTRA */
  5125. }
  5126. else if (id == ASN_SUR_NAME) {
  5127. copy = WOLFSSL_SUR_NAME;
  5128. copyLen = sizeof(WOLFSSL_SUR_NAME) - 1;
  5129. #ifdef WOLFSSL_CERT_GEN
  5130. if (nameType == SUBJECT) {
  5131. cert->subjectSN = (char*)&cert->source[cert->srcIdx];
  5132. cert->subjectSNLen = strLen;
  5133. cert->subjectSNEnc = b;
  5134. }
  5135. #endif /* WOLFSSL_CERT_GEN */
  5136. #if (defined(OPENSSL_EXTRA) || \
  5137. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5138. && !defined(WOLFCRYPT_ONLY)
  5139. nid = NID_surname;
  5140. #endif /* OPENSSL_EXTRA */
  5141. }
  5142. else if (id == ASN_COUNTRY_NAME) {
  5143. copy = WOLFSSL_COUNTRY_NAME;
  5144. copyLen = sizeof(WOLFSSL_COUNTRY_NAME) - 1;
  5145. #ifdef WOLFSSL_CERT_GEN
  5146. if (nameType == SUBJECT) {
  5147. cert->subjectC = (char*)&cert->source[cert->srcIdx];
  5148. cert->subjectCLen = strLen;
  5149. cert->subjectCEnc = b;
  5150. }
  5151. #endif /* WOLFSSL_CERT_GEN */
  5152. #if (defined(OPENSSL_EXTRA) || \
  5153. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5154. && !defined(WOLFCRYPT_ONLY)
  5155. nid = NID_countryName;
  5156. #endif /* OPENSSL_EXTRA */
  5157. }
  5158. else if (id == ASN_LOCALITY_NAME) {
  5159. copy = WOLFSSL_LOCALITY_NAME;
  5160. copyLen = sizeof(WOLFSSL_LOCALITY_NAME) - 1;
  5161. #ifdef WOLFSSL_CERT_GEN
  5162. if (nameType == SUBJECT) {
  5163. cert->subjectL = (char*)&cert->source[cert->srcIdx];
  5164. cert->subjectLLen = strLen;
  5165. cert->subjectLEnc = b;
  5166. }
  5167. #endif /* WOLFSSL_CERT_GEN */
  5168. #if (defined(OPENSSL_EXTRA) || \
  5169. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5170. && !defined(WOLFCRYPT_ONLY)
  5171. nid = NID_localityName;
  5172. #endif /* OPENSSL_EXTRA */
  5173. }
  5174. else if (id == ASN_STATE_NAME) {
  5175. copy = WOLFSSL_STATE_NAME;
  5176. copyLen = sizeof(WOLFSSL_STATE_NAME) - 1;
  5177. #ifdef WOLFSSL_CERT_GEN
  5178. if (nameType == SUBJECT) {
  5179. cert->subjectST = (char*)&cert->source[cert->srcIdx];
  5180. cert->subjectSTLen = strLen;
  5181. cert->subjectSTEnc = b;
  5182. }
  5183. #endif /* WOLFSSL_CERT_GEN */
  5184. #if (defined(OPENSSL_EXTRA) || \
  5185. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5186. && !defined(WOLFCRYPT_ONLY)
  5187. nid = NID_stateOrProvinceName;
  5188. #endif /* OPENSSL_EXTRA */
  5189. }
  5190. else if (id == ASN_ORG_NAME) {
  5191. copy = WOLFSSL_ORG_NAME;
  5192. copyLen = sizeof(WOLFSSL_ORG_NAME) - 1;
  5193. #ifdef WOLFSSL_CERT_GEN
  5194. if (nameType == SUBJECT) {
  5195. cert->subjectO = (char*)&cert->source[cert->srcIdx];
  5196. cert->subjectOLen = strLen;
  5197. cert->subjectOEnc = b;
  5198. }
  5199. #endif /* WOLFSSL_CERT_GEN */
  5200. #if (defined(OPENSSL_EXTRA) || \
  5201. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5202. && !defined(WOLFCRYPT_ONLY)
  5203. nid = NID_organizationName;
  5204. #endif /* OPENSSL_EXTRA */
  5205. }
  5206. else if (id == ASN_ORGUNIT_NAME) {
  5207. copy = WOLFSSL_ORGUNIT_NAME;
  5208. copyLen = sizeof(WOLFSSL_ORGUNIT_NAME) - 1;
  5209. #ifdef WOLFSSL_CERT_GEN
  5210. if (nameType == SUBJECT) {
  5211. cert->subjectOU = (char*)&cert->source[cert->srcIdx];
  5212. cert->subjectOULen = strLen;
  5213. cert->subjectOUEnc = b;
  5214. }
  5215. #endif /* WOLFSSL_CERT_GEN */
  5216. #if (defined(OPENSSL_EXTRA) || \
  5217. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5218. && !defined(WOLFCRYPT_ONLY)
  5219. nid = NID_organizationalUnitName;
  5220. #endif /* OPENSSL_EXTRA */
  5221. }
  5222. else if (id == ASN_SERIAL_NUMBER) {
  5223. copy = WOLFSSL_SERIAL_NUMBER;
  5224. copyLen = sizeof(WOLFSSL_SERIAL_NUMBER) - 1;
  5225. #ifdef WOLFSSL_CERT_GEN
  5226. if (nameType == SUBJECT) {
  5227. cert->subjectSND = (char*)&cert->source[cert->srcIdx];
  5228. cert->subjectSNDLen = strLen;
  5229. cert->subjectSNDEnc = b;
  5230. }
  5231. #endif /* WOLFSSL_CERT_GEN */
  5232. #if (defined(OPENSSL_EXTRA) || \
  5233. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5234. && !defined(WOLFCRYPT_ONLY)
  5235. nid = NID_serialNumber;
  5236. #endif /* OPENSSL_EXTRA */
  5237. }
  5238. #ifdef WOLFSSL_CERT_EXT
  5239. else if (id == ASN_BUS_CAT) {
  5240. copy = WOLFSSL_BUS_CAT;
  5241. copyLen = sizeof(WOLFSSL_BUS_CAT) - 1;
  5242. #ifdef WOLFSSL_CERT_GEN
  5243. if (nameType == SUBJECT) {
  5244. cert->subjectBC = (char*)&cert->source[cert->srcIdx];
  5245. cert->subjectBCLen = strLen;
  5246. cert->subjectBCEnc = b;
  5247. }
  5248. #endif /* WOLFSSL_CERT_GEN */
  5249. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) \
  5250. && !defined(WOLFCRYPT_ONLY)
  5251. nid = NID_businessCategory;
  5252. #endif /* OPENSSL_EXTRA */
  5253. }
  5254. #endif /* WOLFSSL_CERT_EXT */
  5255. }
  5256. #ifdef WOLFSSL_CERT_EXT
  5257. else if ((cert->srcIdx + ASN_JOI_PREFIX_SZ + 2 <= (word32)maxIdx) &&
  5258. (0 == XMEMCMP(&cert->source[cert->srcIdx], ASN_JOI_PREFIX,
  5259. ASN_JOI_PREFIX_SZ)) &&
  5260. ((cert->source[cert->srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_C) ||
  5261. (cert->source[cert->srcIdx+ASN_JOI_PREFIX_SZ] == ASN_JOI_ST)))
  5262. {
  5263. cert->srcIdx += ASN_JOI_PREFIX_SZ;
  5264. id = cert->source[cert->srcIdx++];
  5265. b = cert->source[cert->srcIdx++]; /* encoding */
  5266. if (GetLength(cert->source, &cert->srcIdx, &strLen,
  5267. maxIdx) < 0) {
  5268. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5269. !defined(WOLFCRYPT_ONLY)
  5270. wolfSSL_X509_NAME_free(dName);
  5271. #endif /* OPENSSL_EXTRA */
  5272. return ASN_PARSE_E;
  5273. }
  5274. /* Check for jurisdiction of incorporation country name */
  5275. if (id == ASN_JOI_C) {
  5276. copy = WOLFSSL_JOI_C;
  5277. copyLen = sizeof(WOLFSSL_JOI_C) - 1;
  5278. #ifdef WOLFSSL_CERT_GEN
  5279. if (nameType == SUBJECT) {
  5280. cert->subjectJC = (char*)&cert->source[cert->srcIdx];
  5281. cert->subjectJCLen = strLen;
  5282. cert->subjectJCEnc = b;
  5283. }
  5284. #endif /* WOLFSSL_CERT_GEN */
  5285. #if (defined(OPENSSL_EXTRA) || \
  5286. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5287. && !defined(WOLFCRYPT_ONLY)
  5288. nid = NID_jurisdictionCountryName;
  5289. #endif /* OPENSSL_EXTRA */
  5290. }
  5291. /* Check for jurisdiction of incorporation state name */
  5292. else if (id == ASN_JOI_ST) {
  5293. copy = WOLFSSL_JOI_ST;
  5294. copyLen = sizeof(WOLFSSL_JOI_ST) - 1;
  5295. #ifdef WOLFSSL_CERT_GEN
  5296. if (nameType == SUBJECT) {
  5297. cert->subjectJS = (char*)&cert->source[cert->srcIdx];
  5298. cert->subjectJSLen = strLen;
  5299. cert->subjectJSEnc = b;
  5300. }
  5301. #endif /* WOLFSSL_CERT_GEN */
  5302. #if (defined(OPENSSL_EXTRA) || \
  5303. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5304. && !defined(WOLFCRYPT_ONLY)
  5305. nid = NID_jurisdictionStateOrProvinceName;
  5306. #endif /* OPENSSL_EXTRA */
  5307. }
  5308. if ((strLen + copyLen) > (int)(ASN_NAME_MAX - idx)) {
  5309. WOLFSSL_MSG("ASN Name too big, skipping");
  5310. tooBig = TRUE;
  5311. }
  5312. }
  5313. #endif /* WOLFSSL_CERT_EXT */
  5314. else {
  5315. /* skip */
  5316. byte email = FALSE;
  5317. byte pilot = FALSE;
  5318. if (joint[0] == 0x2a && joint[1] == 0x86) { /* email id hdr */
  5319. id = ASN_EMAIL_NAME;
  5320. email = TRUE;
  5321. }
  5322. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr */
  5323. /* last value of OID is the type of pilot attribute */
  5324. id = cert->source[cert->srcIdx + oidSz - 1];
  5325. pilot = TRUE;
  5326. }
  5327. cert->srcIdx += oidSz + 1;
  5328. if (GetLength(cert->source, &cert->srcIdx, &strLen, maxIdx) < 0) {
  5329. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5330. !defined(WOLFCRYPT_ONLY)
  5331. wolfSSL_X509_NAME_free(dName);
  5332. #endif /* OPENSSL_EXTRA */
  5333. return ASN_PARSE_E;
  5334. }
  5335. if (strLen > (int)(ASN_NAME_MAX - idx)) {
  5336. WOLFSSL_MSG("ASN name too big, skipping");
  5337. tooBig = TRUE;
  5338. }
  5339. if (email) {
  5340. copyLen = sizeof(WOLFSSL_EMAIL_ADDR) - 1;
  5341. if ((copyLen + strLen) > (int)(ASN_NAME_MAX - idx)) {
  5342. WOLFSSL_MSG("ASN name too big, skipping");
  5343. tooBig = TRUE;
  5344. }
  5345. else {
  5346. copy = WOLFSSL_EMAIL_ADDR;
  5347. }
  5348. #ifdef WOLFSSL_CERT_GEN
  5349. if (nameType == SUBJECT) {
  5350. cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
  5351. cert->subjectEmailLen = strLen;
  5352. }
  5353. #endif /* WOLFSSL_CERT_GEN */
  5354. #if (defined(OPENSSL_EXTRA) || \
  5355. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5356. && !defined(WOLFCRYPT_ONLY)
  5357. nid = NID_emailAddress;
  5358. #endif /* OPENSSL_EXTRA */
  5359. #ifndef IGNORE_NAME_CONSTRAINTS
  5360. {
  5361. DNS_entry* emailName;
  5362. emailName = (DNS_entry*)XMALLOC(sizeof(DNS_entry),
  5363. cert->heap, DYNAMIC_TYPE_ALTNAME);
  5364. if (emailName == NULL) {
  5365. WOLFSSL_MSG("\tOut of Memory");
  5366. #if (defined(OPENSSL_EXTRA) || \
  5367. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5368. !defined(WOLFCRYPT_ONLY)
  5369. wolfSSL_X509_NAME_free(dName);
  5370. #endif /* OPENSSL_EXTRA */
  5371. return MEMORY_E;
  5372. }
  5373. emailName->type = 0;
  5374. emailName->name = (char*)XMALLOC(strLen + 1,
  5375. cert->heap, DYNAMIC_TYPE_ALTNAME);
  5376. if (emailName->name == NULL) {
  5377. WOLFSSL_MSG("\tOut of Memory");
  5378. XFREE(emailName, cert->heap, DYNAMIC_TYPE_ALTNAME);
  5379. #if (defined(OPENSSL_EXTRA) || \
  5380. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5381. !defined(WOLFCRYPT_ONLY)
  5382. wolfSSL_X509_NAME_free(dName);
  5383. #endif /* OPENSSL_EXTRA */
  5384. return MEMORY_E;
  5385. }
  5386. emailName->len = strLen;
  5387. XMEMCPY(emailName->name, &cert->source[cert->srcIdx],
  5388. strLen);
  5389. emailName->name[strLen] = '\0';
  5390. emailName->next = cert->altEmailNames;
  5391. cert->altEmailNames = emailName;
  5392. }
  5393. #endif /* IGNORE_NAME_CONSTRAINTS */
  5394. }
  5395. if (pilot) {
  5396. switch (id) {
  5397. case ASN_USER_ID:
  5398. copy = WOLFSSL_USER_ID;
  5399. copyLen = sizeof(WOLFSSL_USER_ID) - 1;
  5400. #if (defined(OPENSSL_EXTRA) || \
  5401. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5402. && !defined(WOLFCRYPT_ONLY)
  5403. nid = NID_userId;
  5404. #endif /* OPENSSL_EXTRA */
  5405. break;
  5406. case ASN_DOMAIN_COMPONENT:
  5407. copy = WOLFSSL_DOMAIN_COMPONENT;
  5408. copyLen = sizeof(WOLFSSL_DOMAIN_COMPONENT) - 1;
  5409. #if (defined(OPENSSL_EXTRA) || \
  5410. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5411. && !defined(WOLFCRYPT_ONLY)
  5412. nid = NID_domainComponent;
  5413. #endif /* OPENSSL_EXTRA */
  5414. break;
  5415. case ASN_FAVOURITE_DRINK:
  5416. copy = WOLFSSL_FAVOURITE_DRINK;
  5417. copyLen = sizeof(WOLFSSL_FAVOURITE_DRINK) - 1;
  5418. #if (defined(OPENSSL_EXTRA) || \
  5419. defined(OPENSSL_EXTRA_X509_SMALL)) \
  5420. && !defined(WOLFCRYPT_ONLY)
  5421. nid = NID_favouriteDrink;
  5422. #endif /* OPENSSL_EXTRA */
  5423. break;
  5424. default:
  5425. WOLFSSL_MSG("Unknown pilot attribute type");
  5426. #if (defined(OPENSSL_EXTRA) || \
  5427. defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5428. !defined(WOLFCRYPT_ONLY)
  5429. wolfSSL_X509_NAME_free(dName);
  5430. #endif /* OPENSSL_EXTRA */
  5431. return ASN_PARSE_E;
  5432. }
  5433. }
  5434. }
  5435. if ((copyLen + strLen) > (int)(ASN_NAME_MAX - idx))
  5436. {
  5437. WOLFSSL_MSG("ASN Name too big, skipping");
  5438. tooBig = TRUE;
  5439. }
  5440. if ((copy != NULL) && !tooBig) {
  5441. XMEMCPY(&full[idx], copy, copyLen);
  5442. idx += copyLen;
  5443. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
  5444. idx += strLen;
  5445. }
  5446. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5447. !defined(WOLFCRYPT_ONLY)
  5448. switch (b) {
  5449. case CTC_UTF8:
  5450. enc = MBSTRING_UTF8;
  5451. break;
  5452. case CTC_PRINTABLE:
  5453. enc = V_ASN1_PRINTABLESTRING;
  5454. break;
  5455. default:
  5456. WOLFSSL_MSG("Unknown encoding type, using UTF8 by default");
  5457. enc = MBSTRING_UTF8;
  5458. }
  5459. if (nid != NID_undef) {
  5460. if (wolfSSL_X509_NAME_add_entry_by_NID(dName, nid, enc,
  5461. &cert->source[cert->srcIdx], strLen, -1, -1) !=
  5462. WOLFSSL_SUCCESS) {
  5463. wolfSSL_X509_NAME_free(dName);
  5464. return ASN_PARSE_E;
  5465. }
  5466. }
  5467. #endif /* OPENSSL_EXTRA */
  5468. cert->srcIdx += strLen;
  5469. }
  5470. full[idx++] = 0;
  5471. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)) && \
  5472. !defined(WOLFCRYPT_ONLY)
  5473. if (nameType == ISSUER) {
  5474. cert->issuerName = dName;
  5475. }
  5476. else {
  5477. cert->subjectName = dName;
  5478. }
  5479. #endif
  5480. return 0;
  5481. }
  5482. #ifndef NO_ASN_TIME
  5483. /* two byte date/time, add to value */
  5484. static WC_INLINE int GetTime(int* value, const byte* date, int* idx)
  5485. {
  5486. int i = *idx;
  5487. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  5488. date[i+1] > 0x39) {
  5489. return ASN_PARSE_E;
  5490. }
  5491. *value += btoi(date[i++]) * 10;
  5492. *value += btoi(date[i++]);
  5493. *idx = i;
  5494. return 0;
  5495. }
  5496. #ifdef WOLFSSL_LINUXKM
  5497. static WC_INLINE int GetTime_Long(long* value, const byte* date, int* idx)
  5498. {
  5499. int i = *idx;
  5500. if (date[i] < 0x30 || date[i] > 0x39 || date[i+1] < 0x30 ||
  5501. date[i+1] > 0x39) {
  5502. return ASN_PARSE_E;
  5503. }
  5504. *value += (long)btoi(date[i++]) * 10;
  5505. *value += (long)btoi(date[i++]);
  5506. *idx = i;
  5507. return 0;
  5508. }
  5509. #endif
  5510. int ExtractDate(const unsigned char* date, unsigned char format,
  5511. struct tm* certTime, int* idx)
  5512. {
  5513. XMEMSET(certTime, 0, sizeof(struct tm));
  5514. if (format == ASN_UTC_TIME) {
  5515. if (btoi(date[*idx]) >= 5)
  5516. certTime->tm_year = 1900;
  5517. else
  5518. certTime->tm_year = 2000;
  5519. }
  5520. else { /* format == GENERALIZED_TIME */
  5521. #ifdef WOLFSSL_LINUXKM
  5522. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  5523. #else
  5524. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  5525. #endif
  5526. certTime->tm_year *= 100;
  5527. }
  5528. #ifdef AVR
  5529. /* Extract the time from the struct tm and adjust tm_year, tm_mon */
  5530. /* AVR libc stores these as uint8_t instead of int */
  5531. /* AVR time_t also offsets from midnight 1 Jan 2000 */
  5532. int tm_year = certTime->tm_year - 2000;
  5533. int tm_mon = certTime->tm_mon - 1;
  5534. int tm_mday = certTime->tm_mday;
  5535. int tm_hour = certTime->tm_hour;
  5536. int tm_min = certTime->tm_min;
  5537. int tm_sec = certTime->tm_sec;
  5538. #ifdef WOLFSSL_LINUXKM
  5539. if (GetTime_Long(&tm_year, date, idx) != 0) return 0;
  5540. #else
  5541. if (GetTime(&tm_year, date, idx) != 0) return 0;
  5542. #endif
  5543. if (GetTime(&tm_mon , date, idx) != 0) return 0;
  5544. if (GetTime(&tm_mday, date, idx) != 0) return 0;
  5545. if (GetTime(&tm_hour, date, idx) != 0) return 0;
  5546. if (GetTime(&tm_min , date, idx) != 0) return 0;
  5547. if (GetTime(&tm_sec , date, idx) != 0) return 0;
  5548. /* Re-populate certTime with computed values */
  5549. certTime->tm_year = tm_year;
  5550. certTime->tm_mon = tm_mon;
  5551. certTime->tm_mday = tm_mday;
  5552. certTime->tm_hour = tm_hour;
  5553. certTime->tm_min = tm_min;
  5554. certTime->tm_sec = tm_sec;
  5555. #else
  5556. /* adjust tm_year, tm_mon */
  5557. #ifdef WOLFSSL_LINUXKM
  5558. if (GetTime_Long(&certTime->tm_year, date, idx) != 0) return 0;
  5559. #else
  5560. if (GetTime(&certTime->tm_year, date, idx) != 0) return 0;
  5561. #endif
  5562. certTime->tm_year -= 1900;
  5563. if (GetTime(&certTime->tm_mon , date, idx) != 0) return 0;
  5564. certTime->tm_mon -= 1;
  5565. if (GetTime(&certTime->tm_mday, date, idx) != 0) return 0;
  5566. if (GetTime(&certTime->tm_hour, date, idx) != 0) return 0;
  5567. if (GetTime(&certTime->tm_min , date, idx) != 0) return 0;
  5568. if (GetTime(&certTime->tm_sec , date, idx) != 0) return 0;
  5569. #endif
  5570. return 1;
  5571. }
  5572. #if defined(OPENSSL_ALL) || defined(WOLFSSL_MYSQL_COMPATIBLE) || \
  5573. defined(OPENSSL_EXTRA) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  5574. int GetTimeString(byte* date, int format, char* buf, int len)
  5575. {
  5576. struct tm t;
  5577. int idx = 0;
  5578. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  5579. return 0;
  5580. }
  5581. if (date[idx] != 'Z') {
  5582. WOLFSSL_MSG("UTCtime, not Zulu") ;
  5583. return 0;
  5584. }
  5585. /* place month in buffer */
  5586. buf[0] = '\0';
  5587. switch(t.tm_mon) {
  5588. case 0: XSTRNCAT(buf, "Jan ", 5); break;
  5589. case 1: XSTRNCAT(buf, "Feb ", 5); break;
  5590. case 2: XSTRNCAT(buf, "Mar ", 5); break;
  5591. case 3: XSTRNCAT(buf, "Apr ", 5); break;
  5592. case 4: XSTRNCAT(buf, "May ", 5); break;
  5593. case 5: XSTRNCAT(buf, "Jun ", 5); break;
  5594. case 6: XSTRNCAT(buf, "Jul ", 5); break;
  5595. case 7: XSTRNCAT(buf, "Aug ", 5); break;
  5596. case 8: XSTRNCAT(buf, "Sep ", 5); break;
  5597. case 9: XSTRNCAT(buf, "Oct ", 5); break;
  5598. case 10: XSTRNCAT(buf, "Nov ", 5); break;
  5599. case 11: XSTRNCAT(buf, "Dec ", 5); break;
  5600. default:
  5601. return 0;
  5602. }
  5603. idx = 4; /* use idx now for char buffer */
  5604. XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  5605. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, (int)t.tm_year + 1900);
  5606. return 1;
  5607. }
  5608. #endif /* OPENSSL_ALL || WOLFSSL_MYSQL_COMPATIBLE || WOLFSSL_NGINX || WOLFSSL_HAPROXY */
  5609. #if !defined(NO_ASN_TIME) && defined(HAVE_PKCS7)
  5610. /* Set current time string, either UTC or GeneralizedTime.
  5611. * (void*) tm should be a pointer to time_t, output is placed in buf.
  5612. *
  5613. * Return time string length placed in buf on success, negative on error */
  5614. int GetAsnTimeString(void* currTime, byte* buf, word32 len)
  5615. {
  5616. struct tm* ts = NULL;
  5617. struct tm* tmpTime = NULL;
  5618. byte* data_ptr = buf;
  5619. word32 data_len = 0;
  5620. int year, mon, day, hour, mini, sec;
  5621. #if defined(NEED_TMP_TIME)
  5622. struct tm tmpTimeStorage;
  5623. tmpTime = &tmpTimeStorage;
  5624. #else
  5625. (void)tmpTime;
  5626. #endif
  5627. WOLFSSL_ENTER("SetAsnTimeString");
  5628. if (buf == NULL || len == 0)
  5629. return BAD_FUNC_ARG;
  5630. ts = (struct tm *)XGMTIME((time_t*)currTime, tmpTime);
  5631. if (ts == NULL){
  5632. WOLFSSL_MSG("failed to get time data.");
  5633. return ASN_TIME_E;
  5634. }
  5635. /* Note ASN_UTC_TIME_SIZE and ASN_GENERALIZED_TIME_SIZE include space for
  5636. * the null terminator. ASN encoded values leave off the terminator. */
  5637. if (ts->tm_year >= 50 && ts->tm_year < 150) {
  5638. /* UTC Time */
  5639. char utc_str[ASN_UTC_TIME_SIZE];
  5640. data_len = ASN_UTC_TIME_SIZE - 1 + 2;
  5641. if (len < data_len)
  5642. return BUFFER_E;
  5643. if (ts->tm_year >= 50 && ts->tm_year < 100) {
  5644. year = ts->tm_year;
  5645. } else if (ts->tm_year >= 100 && ts->tm_year < 150) {
  5646. year = ts->tm_year - 100;
  5647. }
  5648. else {
  5649. WOLFSSL_MSG("unsupported year range");
  5650. return BAD_FUNC_ARG;
  5651. }
  5652. mon = ts->tm_mon + 1;
  5653. day = ts->tm_mday;
  5654. hour = ts->tm_hour;
  5655. mini = ts->tm_min;
  5656. sec = ts->tm_sec;
  5657. XSNPRINTF((char *)utc_str, ASN_UTC_TIME_SIZE,
  5658. "%02d%02d%02d%02d%02d%02dZ", year, mon, day, hour, mini, sec);
  5659. *data_ptr = (byte) ASN_UTC_TIME; data_ptr++;
  5660. /* -1 below excludes null terminator */
  5661. *data_ptr = (byte) ASN_UTC_TIME_SIZE - 1; data_ptr++;
  5662. XMEMCPY(data_ptr,(byte *)utc_str, ASN_UTC_TIME_SIZE - 1);
  5663. } else {
  5664. /* GeneralizedTime */
  5665. char gt_str[ASN_GENERALIZED_TIME_SIZE];
  5666. data_len = ASN_GENERALIZED_TIME_SIZE - 1 + 2;
  5667. if (len < data_len)
  5668. return BUFFER_E;
  5669. year = ts->tm_year + 1900;
  5670. mon = ts->tm_mon + 1;
  5671. day = ts->tm_mday;
  5672. hour = ts->tm_hour;
  5673. mini = ts->tm_min;
  5674. sec = ts->tm_sec;
  5675. XSNPRINTF((char *)gt_str, ASN_GENERALIZED_TIME_SIZE,
  5676. "%4d%02d%02d%02d%02d%02dZ", year, mon, day, hour, mini, sec);
  5677. *data_ptr = (byte) ASN_GENERALIZED_TIME; data_ptr++;
  5678. /* -1 below excludes null terminator */
  5679. *data_ptr = (byte) ASN_GENERALIZED_TIME_SIZE - 1; data_ptr++;
  5680. XMEMCPY(data_ptr,(byte *)gt_str, ASN_GENERALIZED_TIME_SIZE - 1);
  5681. }
  5682. return data_len;
  5683. }
  5684. #endif /* !NO_ASN_TIME && HAVE_PKCS7 */
  5685. #if defined(USE_WOLF_VALIDDATE)
  5686. /* to the second */
  5687. int DateGreaterThan(const struct tm* a, const struct tm* b)
  5688. {
  5689. if (a->tm_year > b->tm_year)
  5690. return 1;
  5691. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  5692. return 1;
  5693. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  5694. a->tm_mday > b->tm_mday)
  5695. return 1;
  5696. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  5697. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  5698. return 1;
  5699. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  5700. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  5701. a->tm_min > b->tm_min)
  5702. return 1;
  5703. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  5704. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  5705. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  5706. return 1;
  5707. return 0; /* false */
  5708. }
  5709. static WC_INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  5710. {
  5711. return DateGreaterThan(b,a);
  5712. }
  5713. /* like atoi but only use first byte */
  5714. /* Make sure before and after dates are valid */
  5715. int wc_ValidateDate(const byte* date, byte format, int dateType)
  5716. {
  5717. time_t ltime;
  5718. struct tm certTime;
  5719. struct tm* localTime;
  5720. struct tm* tmpTime;
  5721. int i = 0;
  5722. int timeDiff = 0 ;
  5723. int diffHH = 0 ; int diffMM = 0 ;
  5724. int diffSign = 0 ;
  5725. #if defined(NEED_TMP_TIME)
  5726. struct tm tmpTimeStorage;
  5727. tmpTime = &tmpTimeStorage;
  5728. #else
  5729. tmpTime = NULL;
  5730. #endif
  5731. (void)tmpTime;
  5732. ltime = XTIME(0);
  5733. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  5734. if (dateType == BEFORE) {
  5735. WOLFSSL_MSG("Skewing local time for before date check");
  5736. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  5737. }
  5738. #endif
  5739. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  5740. if (dateType == AFTER) {
  5741. WOLFSSL_MSG("Skewing local time for after date check");
  5742. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  5743. }
  5744. #endif
  5745. if (!ExtractDate(date, format, &certTime, &i)) {
  5746. WOLFSSL_MSG("Error extracting the date");
  5747. return 0;
  5748. }
  5749. if ((date[i] == '+') || (date[i] == '-')) {
  5750. WOLFSSL_MSG("Using time differential, not Zulu") ;
  5751. diffSign = date[i++] == '+' ? 1 : -1 ;
  5752. if (GetTime(&diffHH, date, &i) != 0)
  5753. return 0;
  5754. if (GetTime(&diffMM, date, &i) != 0)
  5755. return 0;
  5756. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  5757. } else if (date[i] != 'Z') {
  5758. WOLFSSL_MSG("UTCtime, neither Zulu or time differential") ;
  5759. return 0;
  5760. }
  5761. ltime -= (time_t)timeDiff ;
  5762. localTime = XGMTIME(&ltime, tmpTime);
  5763. if (localTime == NULL) {
  5764. WOLFSSL_MSG("XGMTIME failed");
  5765. return 0;
  5766. }
  5767. if (dateType == BEFORE) {
  5768. if (DateLessThan(localTime, &certTime)) {
  5769. WOLFSSL_MSG("Date BEFORE check failed");
  5770. return 0;
  5771. }
  5772. }
  5773. else { /* dateType == AFTER */
  5774. if (DateGreaterThan(localTime, &certTime)) {
  5775. WOLFSSL_MSG("Date AFTER check failed");
  5776. return 0;
  5777. }
  5778. }
  5779. return 1;
  5780. }
  5781. #endif /* USE_WOLF_VALIDDATE */
  5782. int wc_GetTime(void* timePtr, word32 timeSize)
  5783. {
  5784. time_t* ltime = (time_t*)timePtr;
  5785. if (timePtr == NULL) {
  5786. return BAD_FUNC_ARG;
  5787. }
  5788. if ((word32)sizeof(time_t) > timeSize) {
  5789. return BUFFER_E;
  5790. }
  5791. *ltime = XTIME(0);
  5792. return 0;
  5793. }
  5794. #endif /* !NO_ASN_TIME */
  5795. /* Get date buffer, format and length. Returns 0=success or error */
  5796. static int GetDateInfo(const byte* source, word32* idx, const byte** pDate,
  5797. byte* pFormat, int* pLength, word32 maxIdx)
  5798. {
  5799. int length;
  5800. byte format;
  5801. if (source == NULL || idx == NULL)
  5802. return BAD_FUNC_ARG;
  5803. /* get ASN format header */
  5804. if (*idx+1 > maxIdx)
  5805. return BUFFER_E;
  5806. format = source[*idx];
  5807. *idx += 1;
  5808. if (format != ASN_UTC_TIME && format != ASN_GENERALIZED_TIME)
  5809. return ASN_TIME_E;
  5810. /* get length */
  5811. if (GetLength(source, idx, &length, maxIdx) < 0)
  5812. return ASN_PARSE_E;
  5813. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  5814. return ASN_DATE_SZ_E;
  5815. /* return format, date and length */
  5816. if (pFormat)
  5817. *pFormat = format;
  5818. if (pDate)
  5819. *pDate = &source[*idx];
  5820. if (pLength)
  5821. *pLength = length;
  5822. *idx += length;
  5823. return 0;
  5824. }
  5825. static int GetDate(DecodedCert* cert, int dateType, int verify, int maxIdx)
  5826. {
  5827. int ret, length;
  5828. const byte *datePtr = NULL;
  5829. byte date[MAX_DATE_SIZE];
  5830. byte format;
  5831. word32 startIdx = 0;
  5832. if (dateType == BEFORE)
  5833. cert->beforeDate = &cert->source[cert->srcIdx];
  5834. else
  5835. cert->afterDate = &cert->source[cert->srcIdx];
  5836. startIdx = cert->srcIdx;
  5837. ret = GetDateInfo(cert->source, &cert->srcIdx, &datePtr, &format,
  5838. &length, maxIdx);
  5839. if (ret < 0)
  5840. return ret;
  5841. XMEMSET(date, 0, MAX_DATE_SIZE);
  5842. XMEMCPY(date, datePtr, length);
  5843. if (dateType == BEFORE)
  5844. cert->beforeDateLen = cert->srcIdx - startIdx;
  5845. else
  5846. cert->afterDateLen = cert->srcIdx - startIdx;
  5847. #ifndef NO_ASN_TIME
  5848. if (verify != NO_VERIFY && verify != VERIFY_SKIP_DATE &&
  5849. !XVALIDATE_DATE(date, format, dateType)) {
  5850. if (dateType == BEFORE)
  5851. return ASN_BEFORE_DATE_E;
  5852. else
  5853. return ASN_AFTER_DATE_E;
  5854. }
  5855. #else
  5856. (void)verify;
  5857. #endif
  5858. return 0;
  5859. }
  5860. static int GetValidity(DecodedCert* cert, int verify, int maxIdx)
  5861. {
  5862. int length;
  5863. int badDate = 0;
  5864. if (GetSequence(cert->source, &cert->srcIdx, &length, maxIdx) < 0)
  5865. return ASN_PARSE_E;
  5866. maxIdx = cert->srcIdx + length;
  5867. if (GetDate(cert, BEFORE, verify, maxIdx) < 0)
  5868. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  5869. if (GetDate(cert, AFTER, verify, maxIdx) < 0)
  5870. return ASN_AFTER_DATE_E;
  5871. if (badDate != 0)
  5872. return badDate;
  5873. return 0;
  5874. }
  5875. int wc_GetDateInfo(const byte* certDate, int certDateSz, const byte** date,
  5876. byte* format, int* length)
  5877. {
  5878. int ret;
  5879. word32 idx = 0;
  5880. ret = GetDateInfo(certDate, &idx, date, format, length, certDateSz);
  5881. if (ret < 0)
  5882. return ret;
  5883. return 0;
  5884. }
  5885. #ifndef NO_ASN_TIME
  5886. int wc_GetDateAsCalendarTime(const byte* date, int length, byte format,
  5887. struct tm* timearg)
  5888. {
  5889. int idx = 0;
  5890. (void)length;
  5891. if (!ExtractDate(date, format, timearg, &idx))
  5892. return ASN_TIME_E;
  5893. return 0;
  5894. }
  5895. #if defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_ALT_NAMES)
  5896. int wc_GetCertDates(Cert* cert, struct tm* before, struct tm* after)
  5897. {
  5898. int ret = 0;
  5899. const byte* date;
  5900. byte format;
  5901. int length;
  5902. if (cert == NULL)
  5903. return BAD_FUNC_ARG;
  5904. if (before && cert->beforeDateSz > 0) {
  5905. ret = wc_GetDateInfo(cert->beforeDate, cert->beforeDateSz, &date,
  5906. &format, &length);
  5907. if (ret == 0)
  5908. ret = wc_GetDateAsCalendarTime(date, length, format, before);
  5909. }
  5910. if (after && cert->afterDateSz > 0) {
  5911. ret = wc_GetDateInfo(cert->afterDate, cert->afterDateSz, &date,
  5912. &format, &length);
  5913. if (ret == 0)
  5914. ret = wc_GetDateAsCalendarTime(date, length, format, after);
  5915. }
  5916. return ret;
  5917. }
  5918. #endif /* WOLFSSL_CERT_GEN && WOLFSSL_ALT_NAMES */
  5919. #endif /* !NO_ASN_TIME */
  5920. /* parses certificate up to point of X.509 public key
  5921. *
  5922. * if cert date is invalid then badDate gets set to error value, otherwise is 0
  5923. *
  5924. * returns a negative value on fail case
  5925. */
  5926. int wc_GetPubX509(DecodedCert* cert, int verify, int* badDate)
  5927. {
  5928. int ret;
  5929. if (cert == NULL || badDate == NULL)
  5930. return BAD_FUNC_ARG;
  5931. *badDate = 0;
  5932. if ( (ret = GetCertHeader(cert)) < 0)
  5933. return ret;
  5934. WOLFSSL_MSG("Got Cert Header");
  5935. #ifdef WOLFSSL_CERT_REQ
  5936. if (!cert->isCSR) {
  5937. #endif
  5938. /* Using the sigIndex as the upper bound because that's where the
  5939. * actual certificate data ends. */
  5940. if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
  5941. oidSigType, cert->sigIndex)) < 0)
  5942. return ret;
  5943. WOLFSSL_MSG("Got Algo ID");
  5944. if ( (ret = GetName(cert, ISSUER, cert->sigIndex)) < 0)
  5945. return ret;
  5946. if ( (ret = GetValidity(cert, verify, cert->sigIndex)) < 0)
  5947. *badDate = ret;
  5948. #ifdef WOLFSSL_CERT_REQ
  5949. }
  5950. #endif
  5951. if ( (ret = GetName(cert, SUBJECT, cert->sigIndex)) < 0)
  5952. return ret;
  5953. WOLFSSL_MSG("Got Subject Name");
  5954. return ret;
  5955. }
  5956. int DecodeToKey(DecodedCert* cert, int verify)
  5957. {
  5958. int badDate = 0;
  5959. int ret;
  5960. if ( (ret = wc_GetPubX509(cert, verify, &badDate)) < 0)
  5961. return ret;
  5962. /* Determine if self signed */
  5963. cert->selfSigned = XMEMCMP(cert->issuerHash,
  5964. cert->subjectHash,
  5965. KEYID_SIZE) == 0 ? 1 : 0;
  5966. if ( (ret = GetKey(cert)) < 0)
  5967. return ret;
  5968. WOLFSSL_MSG("Got Key");
  5969. if (badDate != 0)
  5970. return badDate;
  5971. return ret;
  5972. }
  5973. #ifndef NO_CERTS
  5974. static int GetSignature(DecodedCert* cert)
  5975. {
  5976. int length;
  5977. int ret;
  5978. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  5979. NULL);
  5980. if (ret != 0)
  5981. return ret;
  5982. cert->sigLength = length;
  5983. cert->signature = &cert->source[cert->srcIdx];
  5984. cert->srcIdx += cert->sigLength;
  5985. if (cert->srcIdx != cert->maxIdx)
  5986. return ASN_PARSE_E;
  5987. return 0;
  5988. }
  5989. #endif
  5990. static word32 SetOctetString8Bit(word32 len, byte* output)
  5991. {
  5992. output[0] = ASN_OCTET_STRING;
  5993. output[1] = (byte)len;
  5994. return 2;
  5995. }
  5996. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  5997. {
  5998. word32 idx = SetOctetString8Bit(digSz, output);
  5999. XMEMCPY(&output[idx], digest, digSz);
  6000. return idx + digSz;
  6001. }
  6002. static word32 BytePrecision(word32 value)
  6003. {
  6004. word32 i;
  6005. for (i = (word32)sizeof(value); i; --i)
  6006. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  6007. break;
  6008. return i;
  6009. }
  6010. word32 SetLength(word32 length, byte* output)
  6011. {
  6012. word32 i = 0, j;
  6013. if (length < ASN_LONG_LENGTH) {
  6014. if (output)
  6015. output[i] = (byte)length;
  6016. i++;
  6017. }
  6018. else {
  6019. if (output)
  6020. output[i] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  6021. i++;
  6022. for (j = BytePrecision(length); j; --j) {
  6023. if (output)
  6024. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  6025. i++;
  6026. }
  6027. }
  6028. return i;
  6029. }
  6030. word32 SetSequence(word32 len, byte* output)
  6031. {
  6032. if (output)
  6033. output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
  6034. return SetLength(len, output ? output + 1 : NULL) + 1;
  6035. }
  6036. word32 SetOctetString(word32 len, byte* output)
  6037. {
  6038. output[0] = ASN_OCTET_STRING;
  6039. return SetLength(len, output + 1) + 1;
  6040. }
  6041. /* Write a set header to output */
  6042. word32 SetSet(word32 len, byte* output)
  6043. {
  6044. output[0] = ASN_SET | ASN_CONSTRUCTED;
  6045. return SetLength(len, output + 1) + 1;
  6046. }
  6047. word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  6048. {
  6049. output[0] = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  6050. | ASN_CONTEXT_SPECIFIC | number;
  6051. return SetLength(len, output + 1) + 1;
  6052. }
  6053. word32 SetExplicit(byte number, word32 len, byte* output)
  6054. {
  6055. output[0] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number;
  6056. return SetLength(len, output + 1) + 1;
  6057. }
  6058. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  6059. static int SetCurve(ecc_key* key, byte* output)
  6060. {
  6061. #ifdef HAVE_OID_ENCODING
  6062. int ret;
  6063. #endif
  6064. int idx = 0;
  6065. word32 oidSz = 0;
  6066. /* validate key */
  6067. if (key == NULL || key->dp == NULL) {
  6068. return BAD_FUNC_ARG;
  6069. }
  6070. #ifdef HAVE_OID_ENCODING
  6071. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  6072. if (ret != 0) {
  6073. return ret;
  6074. }
  6075. #else
  6076. oidSz = key->dp->oidSz;
  6077. #endif
  6078. idx += SetObjectId(oidSz, output);
  6079. #ifdef HAVE_OID_ENCODING
  6080. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  6081. if (ret != 0) {
  6082. return ret;
  6083. }
  6084. #else
  6085. XMEMCPY(output+idx, key->dp->oid, oidSz);
  6086. #endif
  6087. idx += oidSz;
  6088. return idx;
  6089. }
  6090. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  6091. #ifdef HAVE_ECC
  6092. static WC_INLINE int IsSigAlgoECDSA(int algoOID)
  6093. {
  6094. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  6095. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  6096. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  6097. return 1;
  6098. }
  6099. return 0;
  6100. }
  6101. #endif
  6102. word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  6103. {
  6104. word32 tagSz, idSz, seqSz, algoSz = 0;
  6105. const byte* algoName = 0;
  6106. byte ID_Length[1 + MAX_LENGTH_SZ];
  6107. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  6108. int length = 0;
  6109. tagSz = (type == oidHashType ||
  6110. (type == oidSigType
  6111. #ifdef HAVE_ECC
  6112. && !IsSigAlgoECDSA(algoOID)
  6113. #endif
  6114. #ifdef HAVE_ED25519
  6115. && algoOID != ED25519k
  6116. #endif
  6117. #ifdef HAVE_ED448
  6118. && algoOID != ED448k
  6119. #endif
  6120. ) ||
  6121. (type == oidKeyType && algoOID == RSAk)) ? 2 : 0;
  6122. algoName = OidFromId(algoOID, type, &algoSz);
  6123. if (algoName == NULL) {
  6124. WOLFSSL_MSG("Unknown Algorithm");
  6125. return 0;
  6126. }
  6127. idSz = SetObjectId(algoSz, ID_Length);
  6128. seqSz = SetSequence(idSz + algoSz + tagSz + curveSz, seqArray);
  6129. /* Copy only algo to output for DSA keys */
  6130. if (algoOID == DSAk && output) {
  6131. XMEMCPY(output, ID_Length, idSz);
  6132. XMEMCPY(output + idSz, algoName, algoSz);
  6133. if (tagSz == 2)
  6134. SetASNNull(&output[seqSz + idSz + algoSz]);
  6135. }
  6136. else if (output) {
  6137. XMEMCPY(output, seqArray, seqSz);
  6138. XMEMCPY(output + seqSz, ID_Length, idSz);
  6139. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  6140. if (tagSz == 2)
  6141. SetASNNull(&output[seqSz + idSz + algoSz]);
  6142. }
  6143. if (algoOID == DSAk)
  6144. length = idSz + algoSz + tagSz;
  6145. else
  6146. length = seqSz + idSz + algoSz + tagSz;
  6147. return length;
  6148. }
  6149. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  6150. int hashOID)
  6151. {
  6152. byte digArray[MAX_ENCODED_DIG_SZ];
  6153. byte algoArray[MAX_ALGO_SZ];
  6154. byte seqArray[MAX_SEQ_SZ];
  6155. word32 encDigSz, algoSz, seqSz;
  6156. encDigSz = SetDigest(digest, digSz, digArray);
  6157. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  6158. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  6159. XMEMCPY(out, seqArray, seqSz);
  6160. XMEMCPY(out + seqSz, algoArray, algoSz);
  6161. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  6162. return encDigSz + algoSz + seqSz;
  6163. }
  6164. #ifndef NO_CERTS
  6165. int wc_GetCTC_HashOID(int type)
  6166. {
  6167. int ret;
  6168. enum wc_HashType hType;
  6169. hType = wc_HashTypeConvert(type);
  6170. ret = wc_HashGetOID(hType);
  6171. if (ret < 0)
  6172. ret = 0; /* backwards compatibility */
  6173. return ret;
  6174. }
  6175. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  6176. {
  6177. if (sigCtx) {
  6178. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  6179. sigCtx->devId = devId;
  6180. sigCtx->heap = heap;
  6181. }
  6182. }
  6183. void FreeSignatureCtx(SignatureCtx* sigCtx)
  6184. {
  6185. if (sigCtx == NULL)
  6186. return;
  6187. if (sigCtx->digest) {
  6188. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  6189. sigCtx->digest = NULL;
  6190. }
  6191. #if !(defined(NO_RSA) && defined(NO_DSA))
  6192. if (sigCtx->sigCpy) {
  6193. XFREE(sigCtx->sigCpy, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  6194. sigCtx->sigCpy = NULL;
  6195. }
  6196. #endif
  6197. #ifndef NO_ASN_CRYPT
  6198. if (sigCtx->key.ptr) {
  6199. switch (sigCtx->keyOID) {
  6200. #ifndef NO_RSA
  6201. case RSAk:
  6202. wc_FreeRsaKey(sigCtx->key.rsa);
  6203. XFREE(sigCtx->key.ptr, sigCtx->heap, DYNAMIC_TYPE_RSA);
  6204. break;
  6205. #endif /* !NO_RSA */
  6206. #ifndef NO_DSA
  6207. case DSAk:
  6208. wc_FreeDsaKey(sigCtx->key.dsa);
  6209. XFREE(sigCtx->key.dsa, sigCtx->heap, DYNAMIC_TYPE_DSA);
  6210. break;
  6211. #endif
  6212. #ifdef HAVE_ECC
  6213. case ECDSAk:
  6214. wc_ecc_free(sigCtx->key.ecc);
  6215. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  6216. break;
  6217. #endif /* HAVE_ECC */
  6218. #ifdef HAVE_ED25519
  6219. case ED25519k:
  6220. wc_ed25519_free(sigCtx->key.ed25519);
  6221. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  6222. break;
  6223. #endif /* HAVE_ED25519 */
  6224. #ifdef HAVE_ED448
  6225. case ED448k:
  6226. wc_ed448_free(sigCtx->key.ed448);
  6227. XFREE(sigCtx->key.ed448, sigCtx->heap, DYNAMIC_TYPE_ED448);
  6228. break;
  6229. #endif /* HAVE_ED448 */
  6230. default:
  6231. break;
  6232. } /* switch (keyOID) */
  6233. sigCtx->key.ptr = NULL;
  6234. }
  6235. #endif
  6236. /* reset state, we are done */
  6237. sigCtx->state = SIG_STATE_BEGIN;
  6238. }
  6239. #ifndef NO_ASN_CRYPT
  6240. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  6241. byte* digest, int* typeH, int* digestSz, int verify)
  6242. {
  6243. int ret = 0;
  6244. switch (sigOID) {
  6245. #if defined(WOLFSSL_MD2)
  6246. case CTC_MD2wRSA:
  6247. if (!verify) {
  6248. ret = HASH_TYPE_E;
  6249. WOLFSSL_MSG("MD2 not supported for signing");
  6250. }
  6251. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  6252. *typeH = MD2h;
  6253. *digestSz = MD2_DIGEST_SIZE;
  6254. }
  6255. break;
  6256. #endif
  6257. #ifndef NO_MD5
  6258. case CTC_MD5wRSA:
  6259. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  6260. *typeH = MD5h;
  6261. *digestSz = WC_MD5_DIGEST_SIZE;
  6262. }
  6263. break;
  6264. #endif
  6265. #ifndef NO_SHA
  6266. case CTC_SHAwRSA:
  6267. case CTC_SHAwDSA:
  6268. case CTC_SHAwECDSA:
  6269. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  6270. *typeH = SHAh;
  6271. *digestSz = WC_SHA_DIGEST_SIZE;
  6272. }
  6273. break;
  6274. #endif
  6275. #ifdef WOLFSSL_SHA224
  6276. case CTC_SHA224wRSA:
  6277. case CTC_SHA224wECDSA:
  6278. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  6279. *typeH = SHA224h;
  6280. *digestSz = WC_SHA224_DIGEST_SIZE;
  6281. }
  6282. break;
  6283. #endif
  6284. #ifndef NO_SHA256
  6285. case CTC_SHA256wRSA:
  6286. case CTC_SHA256wECDSA:
  6287. case CTC_SHA256wDSA:
  6288. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  6289. *typeH = SHA256h;
  6290. *digestSz = WC_SHA256_DIGEST_SIZE;
  6291. }
  6292. break;
  6293. #endif
  6294. #ifdef WOLFSSL_SHA384
  6295. case CTC_SHA384wRSA:
  6296. case CTC_SHA384wECDSA:
  6297. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  6298. *typeH = SHA384h;
  6299. *digestSz = WC_SHA384_DIGEST_SIZE;
  6300. }
  6301. break;
  6302. #endif
  6303. #ifdef WOLFSSL_SHA512
  6304. case CTC_SHA512wRSA:
  6305. case CTC_SHA512wECDSA:
  6306. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  6307. *typeH = SHA512h;
  6308. *digestSz = WC_SHA512_DIGEST_SIZE;
  6309. }
  6310. break;
  6311. #endif
  6312. #ifdef HAVE_ED25519
  6313. case CTC_ED25519:
  6314. /* Hashes done in signing operation.
  6315. * Two dependent hashes with prefixes performed.
  6316. */
  6317. break;
  6318. #endif
  6319. #ifdef HAVE_ED448
  6320. case CTC_ED448:
  6321. /* Hashes done in signing operation.
  6322. * Two dependent hashes with prefixes performed.
  6323. */
  6324. break;
  6325. #endif
  6326. default:
  6327. ret = HASH_TYPE_E;
  6328. WOLFSSL_MSG("Hash for Signature has unsupported type");
  6329. }
  6330. (void)buf;
  6331. (void)bufSz;
  6332. (void)sigOID;
  6333. (void)digest;
  6334. (void)digestSz;
  6335. (void)typeH;
  6336. (void)verify;
  6337. return ret;
  6338. }
  6339. #endif /* !NO_ASN_CRYPT */
  6340. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  6341. static int ConfirmSignature(SignatureCtx* sigCtx,
  6342. const byte* buf, word32 bufSz,
  6343. const byte* key, word32 keySz, word32 keyOID,
  6344. const byte* sig, word32 sigSz, word32 sigOID, byte* rsaKeyIdx)
  6345. {
  6346. int ret = 0;
  6347. #ifndef WOLFSSL_RENESAS_TSIP_TLS
  6348. (void)rsaKeyIdx;
  6349. #endif
  6350. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  6351. keySz == 0 || sig == NULL || sigSz == 0) {
  6352. return BAD_FUNC_ARG;
  6353. }
  6354. (void)key;
  6355. (void)keySz;
  6356. (void)sig;
  6357. (void)sigSz;
  6358. WOLFSSL_ENTER("ConfirmSignature");
  6359. #ifndef NO_ASN_CRYPT
  6360. switch (sigCtx->state) {
  6361. case SIG_STATE_BEGIN:
  6362. {
  6363. sigCtx->keyOID = keyOID; /* must set early for cleanup */
  6364. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  6365. DYNAMIC_TYPE_DIGEST);
  6366. if (sigCtx->digest == NULL) {
  6367. ERROR_OUT(MEMORY_E, exit_cs);
  6368. }
  6369. sigCtx->state = SIG_STATE_HASH;
  6370. } /* SIG_STATE_BEGIN */
  6371. FALL_THROUGH;
  6372. case SIG_STATE_HASH:
  6373. {
  6374. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  6375. &sigCtx->typeH, &sigCtx->digestSz, 1);
  6376. if (ret != 0) {
  6377. goto exit_cs;
  6378. }
  6379. sigCtx->state = SIG_STATE_KEY;
  6380. } /* SIG_STATE_HASH */
  6381. FALL_THROUGH;
  6382. case SIG_STATE_KEY:
  6383. {
  6384. switch (keyOID) {
  6385. #ifndef NO_RSA
  6386. case RSAk:
  6387. {
  6388. word32 idx = 0;
  6389. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  6390. sigCtx->heap, DYNAMIC_TYPE_RSA);
  6391. sigCtx->sigCpy = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  6392. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  6393. if (sigCtx->key.rsa == NULL || sigCtx->sigCpy == NULL) {
  6394. ERROR_OUT(MEMORY_E, exit_cs);
  6395. }
  6396. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  6397. sigCtx->devId)) != 0) {
  6398. goto exit_cs;
  6399. }
  6400. if (sigSz > MAX_ENCODED_SIG_SZ) {
  6401. WOLFSSL_MSG("Verify Signature is too big");
  6402. ERROR_OUT(BUFFER_E, exit_cs);
  6403. }
  6404. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  6405. keySz)) != 0) {
  6406. WOLFSSL_MSG("ASN Key decode error RSA");
  6407. goto exit_cs;
  6408. }
  6409. XMEMCPY(sigCtx->sigCpy, sig, sigSz);
  6410. sigCtx->out = NULL;
  6411. #ifdef WOLFSSL_ASYNC_CRYPT
  6412. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  6413. #endif
  6414. break;
  6415. }
  6416. #endif /* !NO_RSA */
  6417. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  6418. case DSAk:
  6419. {
  6420. word32 idx = 0;
  6421. if (sigSz < DSA_SIG_SIZE) {
  6422. WOLFSSL_MSG("Verify Signature is too small");
  6423. ERROR_OUT(BUFFER_E, exit_cs);
  6424. }
  6425. sigCtx->key.dsa = (DsaKey*)XMALLOC(sizeof(DsaKey),
  6426. sigCtx->heap, DYNAMIC_TYPE_DSA);
  6427. sigCtx->sigCpy = (byte*)XMALLOC(sigSz,
  6428. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  6429. if (sigCtx->key.dsa == NULL || sigCtx->sigCpy == NULL) {
  6430. ERROR_OUT(MEMORY_E, exit_cs);
  6431. }
  6432. if ((ret = wc_InitDsaKey_h(sigCtx->key.dsa, sigCtx->heap)) != 0) {
  6433. WOLFSSL_MSG("wc_InitDsaKey_h error");
  6434. goto exit_cs;
  6435. }
  6436. if ((ret = wc_DsaPublicKeyDecode(key, &idx, sigCtx->key.dsa,
  6437. keySz)) != 0) {
  6438. WOLFSSL_MSG("ASN Key decode error RSA");
  6439. goto exit_cs;
  6440. }
  6441. if (sigSz != DSA_SIG_SIZE) {
  6442. #ifdef HAVE_ECC
  6443. /* Try to parse it as the contents of a bitstring */
  6444. mp_int r, s;
  6445. idx = 0;
  6446. if (DecodeECC_DSA_Sig(sig + idx, sigSz - idx,
  6447. &r, &s) != 0) {
  6448. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  6449. "incorrect format");
  6450. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  6451. }
  6452. if (mp_to_unsigned_bin_len(&r, sigCtx->sigCpy,
  6453. DSA_HALF_SIZE) != MP_OKAY ||
  6454. mp_to_unsigned_bin_len(&s,
  6455. sigCtx->sigCpy + DSA_HALF_SIZE,
  6456. DSA_HALF_SIZE) != MP_OKAY) {
  6457. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  6458. "incorrect format");
  6459. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  6460. }
  6461. mp_free(&r);
  6462. mp_free(&s);
  6463. #else
  6464. WOLFSSL_MSG("DSA Sig is in unrecognized or "
  6465. "incorrect format");
  6466. ERROR_OUT(ASN_SIG_CONFIRM_E, exit_cs);
  6467. #endif
  6468. }
  6469. else {
  6470. XMEMCPY(sigCtx->sigCpy, sig, DSA_SIG_SIZE);
  6471. }
  6472. break;
  6473. }
  6474. #endif /* !NO_DSA && !HAVE_SELFTEST */
  6475. #ifdef HAVE_ECC
  6476. case ECDSAk:
  6477. {
  6478. word32 idx = 0;
  6479. sigCtx->verify = 0;
  6480. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  6481. sigCtx->heap, DYNAMIC_TYPE_ECC);
  6482. if (sigCtx->key.ecc == NULL) {
  6483. ERROR_OUT(MEMORY_E, exit_cs);
  6484. }
  6485. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  6486. sigCtx->devId)) < 0) {
  6487. goto exit_cs;
  6488. }
  6489. ret = wc_EccPublicKeyDecode(key, &idx, sigCtx->key.ecc,
  6490. keySz);
  6491. if (ret < 0) {
  6492. WOLFSSL_MSG("ASN Key import error ECC");
  6493. goto exit_cs;
  6494. }
  6495. #ifdef WOLFSSL_ASYNC_CRYPT
  6496. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  6497. #endif
  6498. break;
  6499. }
  6500. #endif /* HAVE_ECC */
  6501. #ifdef HAVE_ED25519
  6502. case ED25519k:
  6503. {
  6504. sigCtx->verify = 0;
  6505. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  6506. sizeof(ed25519_key), sigCtx->heap,
  6507. DYNAMIC_TYPE_ED25519);
  6508. if (sigCtx->key.ed25519 == NULL) {
  6509. ERROR_OUT(MEMORY_E, exit_cs);
  6510. }
  6511. if ((ret = wc_ed25519_init(sigCtx->key.ed25519)) < 0) {
  6512. goto exit_cs;
  6513. }
  6514. if ((ret = wc_ed25519_import_public(key, keySz,
  6515. sigCtx->key.ed25519)) < 0) {
  6516. WOLFSSL_MSG("ASN Key import error ED25519");
  6517. goto exit_cs;
  6518. }
  6519. #ifdef WOLFSSL_ASYNC_CRYPT
  6520. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  6521. #endif
  6522. break;
  6523. }
  6524. #endif
  6525. #ifdef HAVE_ED448
  6526. case ED448k:
  6527. {
  6528. sigCtx->verify = 0;
  6529. sigCtx->key.ed448 = (ed448_key*)XMALLOC(
  6530. sizeof(ed448_key), sigCtx->heap,
  6531. DYNAMIC_TYPE_ED448);
  6532. if (sigCtx->key.ed448 == NULL) {
  6533. ERROR_OUT(MEMORY_E, exit_cs);
  6534. }
  6535. if ((ret = wc_ed448_init(sigCtx->key.ed448)) < 0) {
  6536. goto exit_cs;
  6537. }
  6538. if ((ret = wc_ed448_import_public(key, keySz,
  6539. sigCtx->key.ed448)) < 0) {
  6540. WOLFSSL_MSG("ASN Key import error ED448");
  6541. goto exit_cs;
  6542. }
  6543. #ifdef WOLFSSL_ASYNC_CRYPT
  6544. sigCtx->asyncDev = &sigCtx->key.ed448->asyncDev;
  6545. #endif
  6546. break;
  6547. }
  6548. #endif
  6549. default:
  6550. WOLFSSL_MSG("Verify Key type unknown");
  6551. ret = ASN_UNKNOWN_OID_E;
  6552. break;
  6553. } /* switch (keyOID) */
  6554. if (ret != 0) {
  6555. goto exit_cs;
  6556. }
  6557. sigCtx->state = SIG_STATE_DO;
  6558. #ifdef WOLFSSL_ASYNC_CRYPT
  6559. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  6560. /* make sure event is initialized */
  6561. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  6562. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  6563. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  6564. }
  6565. #endif
  6566. } /* SIG_STATE_KEY */
  6567. FALL_THROUGH;
  6568. case SIG_STATE_DO:
  6569. {
  6570. switch (keyOID) {
  6571. #ifndef NO_RSA
  6572. case RSAk:
  6573. {
  6574. #ifdef HAVE_PK_CALLBACKS
  6575. if (sigCtx->pkCbRsa) {
  6576. ret = sigCtx->pkCbRsa(
  6577. sigCtx->sigCpy, sigSz, &sigCtx->out,
  6578. key, keySz,
  6579. sigCtx->pkCtxRsa);
  6580. }
  6581. else
  6582. #endif /* HAVE_PK_CALLBACKS */
  6583. {
  6584. #ifdef WOLFSSL_RENESAS_TSIP_TLS
  6585. if (rsaKeyIdx != NULL)
  6586. {
  6587. ret = tsip_tls_CertVerify(buf, bufSz, sigCtx->sigCpy,
  6588. sigSz,
  6589. sigCtx->pubkey_n_start - sigCtx->certBegin,
  6590. sigCtx->pubkey_n_len - 1,
  6591. sigCtx->pubkey_e_start - sigCtx->certBegin,
  6592. sigCtx->pubkey_e_len - 1,
  6593. rsaKeyIdx);
  6594. if (ret == 0){
  6595. sigCtx->verifyByTSIP = 1;
  6596. ret = 0;
  6597. } else {
  6598. WOLFSSL_MSG("RSA Verify by tsip didn't match");
  6599. ret = ASN_SIG_CONFIRM_E;
  6600. }
  6601. } else
  6602. #endif
  6603. ret = wc_RsaSSL_VerifyInline(sigCtx->sigCpy, sigSz,
  6604. &sigCtx->out, sigCtx->key.rsa);
  6605. }
  6606. break;
  6607. }
  6608. #endif /* !NO_RSA */
  6609. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  6610. case DSAk:
  6611. {
  6612. ret = wc_DsaVerify(sigCtx->digest, sigCtx->sigCpy,
  6613. sigCtx->key.dsa, &sigCtx->verify);
  6614. break;
  6615. }
  6616. #endif /* !NO_DSA && !HAVE_SELFTEST */
  6617. #if defined(HAVE_ECC)
  6618. case ECDSAk:
  6619. {
  6620. #ifdef HAVE_PK_CALLBACKS
  6621. if (sigCtx->pkCbEcc) {
  6622. ret = sigCtx->pkCbEcc(
  6623. sig, sigSz,
  6624. sigCtx->digest, sigCtx->digestSz,
  6625. key, keySz, &sigCtx->verify,
  6626. sigCtx->pkCtxEcc);
  6627. }
  6628. else
  6629. #endif /* HAVE_PK_CALLBACKS */
  6630. {
  6631. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  6632. sigCtx->digestSz, &sigCtx->verify,
  6633. sigCtx->key.ecc);
  6634. }
  6635. break;
  6636. }
  6637. #endif /* HAVE_ECC */
  6638. #ifdef HAVE_ED25519
  6639. case ED25519k:
  6640. {
  6641. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  6642. &sigCtx->verify, sigCtx->key.ed25519);
  6643. break;
  6644. }
  6645. #endif
  6646. #ifdef HAVE_ED448
  6647. case ED448k:
  6648. {
  6649. ret = wc_ed448_verify_msg(sig, sigSz, buf, bufSz,
  6650. &sigCtx->verify, sigCtx->key.ed448,
  6651. NULL, 0);
  6652. break;
  6653. }
  6654. #endif
  6655. default:
  6656. break;
  6657. } /* switch (keyOID) */
  6658. #ifdef WOLFSSL_ASYNC_CRYPT
  6659. if (ret == WC_PENDING_E) {
  6660. goto exit_cs;
  6661. }
  6662. #endif
  6663. if (ret < 0) {
  6664. /* treat all RSA errors as ASN_SIG_CONFIRM_E */
  6665. ret = ASN_SIG_CONFIRM_E;
  6666. goto exit_cs;
  6667. }
  6668. sigCtx->state = SIG_STATE_CHECK;
  6669. } /* SIG_STATE_DO */
  6670. FALL_THROUGH;
  6671. case SIG_STATE_CHECK:
  6672. {
  6673. switch (keyOID) {
  6674. #ifndef NO_RSA
  6675. case RSAk:
  6676. {
  6677. int encodedSigSz, verifySz;
  6678. #ifdef WOLFSSL_RENESAS_TSIP
  6679. if (sigCtx->verifyByTSIP == 1) break;
  6680. #endif
  6681. #ifdef WOLFSSL_SMALL_STACK
  6682. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  6683. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  6684. if (encodedSig == NULL) {
  6685. ERROR_OUT(MEMORY_E, exit_cs);
  6686. }
  6687. #else
  6688. byte encodedSig[MAX_ENCODED_SIG_SZ];
  6689. #endif
  6690. verifySz = ret;
  6691. /* make sure we're right justified */
  6692. encodedSigSz = wc_EncodeSignature(encodedSig,
  6693. sigCtx->digest, sigCtx->digestSz, sigCtx->typeH);
  6694. if (encodedSigSz == verifySz && sigCtx->out != NULL &&
  6695. XMEMCMP(sigCtx->out, encodedSig, encodedSigSz) == 0) {
  6696. ret = 0;
  6697. }
  6698. else {
  6699. WOLFSSL_MSG("RSA SSL verify match encode error");
  6700. ret = ASN_SIG_CONFIRM_E;
  6701. }
  6702. #ifdef WOLFSSL_SMALL_STACK
  6703. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  6704. #endif
  6705. break;
  6706. }
  6707. #endif /* NO_RSA */
  6708. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  6709. case DSAk:
  6710. {
  6711. if (sigCtx->verify == 1) {
  6712. ret = 0;
  6713. }
  6714. else {
  6715. WOLFSSL_MSG("DSA Verify didn't match");
  6716. ret = ASN_SIG_CONFIRM_E;
  6717. }
  6718. break;
  6719. }
  6720. #endif /* !NO_DSA && !HAVE_SELFTEST */
  6721. #ifdef HAVE_ECC
  6722. case ECDSAk:
  6723. {
  6724. if (sigCtx->verify == 1) {
  6725. ret = 0;
  6726. }
  6727. else {
  6728. WOLFSSL_MSG("ECC Verify didn't match");
  6729. ret = ASN_SIG_CONFIRM_E;
  6730. }
  6731. break;
  6732. }
  6733. #endif /* HAVE_ECC */
  6734. #ifdef HAVE_ED25519
  6735. case ED25519k:
  6736. {
  6737. if (sigCtx->verify == 1) {
  6738. ret = 0;
  6739. }
  6740. else {
  6741. WOLFSSL_MSG("ED25519 Verify didn't match");
  6742. ret = ASN_SIG_CONFIRM_E;
  6743. }
  6744. break;
  6745. }
  6746. #endif /* HAVE_ED25519 */
  6747. #ifdef HAVE_ED448
  6748. case ED448k:
  6749. {
  6750. if (sigCtx->verify == 1) {
  6751. ret = 0;
  6752. }
  6753. else {
  6754. WOLFSSL_MSG("ED448 Verify didn't match");
  6755. ret = ASN_SIG_CONFIRM_E;
  6756. }
  6757. break;
  6758. }
  6759. #endif /* HAVE_ED448 */
  6760. default:
  6761. break;
  6762. } /* switch (keyOID) */
  6763. break;
  6764. } /* SIG_STATE_CHECK */
  6765. default:
  6766. break;
  6767. } /* switch (sigCtx->state) */
  6768. exit_cs:
  6769. #endif /* !NO_ASN_CRYPT */
  6770. (void)keyOID;
  6771. (void)sigOID;
  6772. WOLFSSL_LEAVE("ConfirmSignature", ret);
  6773. #ifdef WOLFSSL_ASYNC_CRYPT
  6774. if (ret == WC_PENDING_E)
  6775. return ret;
  6776. #endif
  6777. FreeSignatureCtx(sigCtx);
  6778. return ret;
  6779. }
  6780. #ifndef IGNORE_NAME_CONSTRAINTS
  6781. static int MatchBaseName(int type, const char* name, int nameSz,
  6782. const char* base, int baseSz)
  6783. {
  6784. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  6785. name[0] == '.' || nameSz < baseSz ||
  6786. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE))
  6787. return 0;
  6788. /* If an email type, handle special cases where the base is only
  6789. * a domain, or is an email address itself. */
  6790. if (type == ASN_RFC822_TYPE) {
  6791. const char* p = NULL;
  6792. int count = 0;
  6793. if (base[0] != '.') {
  6794. p = base;
  6795. count = 0;
  6796. /* find the '@' in the base */
  6797. while (*p != '@' && count < baseSz) {
  6798. count++;
  6799. p++;
  6800. }
  6801. /* No '@' in base, reset p to NULL */
  6802. if (count >= baseSz)
  6803. p = NULL;
  6804. }
  6805. if (p == NULL) {
  6806. /* Base isn't an email address, it is a domain name,
  6807. * wind the name forward one character past its '@'. */
  6808. p = name;
  6809. count = 0;
  6810. while (*p != '@' && count < baseSz) {
  6811. count++;
  6812. p++;
  6813. }
  6814. if (count < baseSz && *p == '@') {
  6815. name = p + 1;
  6816. nameSz -= count + 1;
  6817. }
  6818. }
  6819. }
  6820. if ((type == ASN_DNS_TYPE || type == ASN_RFC822_TYPE) && base[0] == '.') {
  6821. int szAdjust = nameSz - baseSz;
  6822. name += szAdjust;
  6823. nameSz -= szAdjust;
  6824. }
  6825. while (nameSz > 0) {
  6826. if (XTOLOWER((unsigned char)*name++) !=
  6827. XTOLOWER((unsigned char)*base++))
  6828. return 0;
  6829. nameSz--;
  6830. }
  6831. return 1;
  6832. }
  6833. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  6834. {
  6835. if (signer == NULL || cert == NULL)
  6836. return 0;
  6837. /* Check against the excluded list */
  6838. if (signer->excludedNames) {
  6839. Base_entry* base = signer->excludedNames;
  6840. while (base != NULL) {
  6841. switch (base->type) {
  6842. case ASN_DNS_TYPE:
  6843. {
  6844. DNS_entry* name = cert->altNames;
  6845. while (name != NULL) {
  6846. if (MatchBaseName(ASN_DNS_TYPE,
  6847. name->name, name->len,
  6848. base->name, base->nameSz)) {
  6849. return 0;
  6850. }
  6851. name = name->next;
  6852. }
  6853. break;
  6854. }
  6855. case ASN_RFC822_TYPE:
  6856. {
  6857. DNS_entry* name = cert->altEmailNames;
  6858. while (name != NULL) {
  6859. if (MatchBaseName(ASN_RFC822_TYPE,
  6860. name->name, name->len,
  6861. base->name, base->nameSz)) {
  6862. return 0;
  6863. }
  6864. name = name->next;
  6865. }
  6866. break;
  6867. }
  6868. case ASN_DIR_TYPE:
  6869. {
  6870. /* allow permitted dirName smaller than actual subject */
  6871. if (cert->subjectRawLen >= base->nameSz &&
  6872. XMEMCMP(cert->subjectRaw, base->name,
  6873. base->nameSz) == 0) {
  6874. return 0;
  6875. }
  6876. #ifndef WOLFSSL_NO_ASN_STRICT
  6877. /* RFC 5280 section 4.2.1.10
  6878. "Restrictions of the form directoryName MUST be
  6879. applied to the subject field .... and to any names
  6880. of type directoryName in the subjectAltName
  6881. extension"
  6882. */
  6883. if (cert->altDirNames != NULL) {
  6884. DNS_entry* cur = cert->altDirNames;
  6885. while (cur != NULL) {
  6886. if (XMEMCMP(cur->name, base->name, base->nameSz)
  6887. == 0) {
  6888. WOLFSSL_MSG("DIR alt name constraint err");
  6889. return 0;
  6890. }
  6891. cur = cur->next;
  6892. }
  6893. }
  6894. #endif /* !WOLFSSL_NO_ASN_STRICT */
  6895. break;
  6896. }
  6897. default:
  6898. break;
  6899. }; /* switch */
  6900. base = base->next;
  6901. }
  6902. }
  6903. /* Check against the permitted list */
  6904. if (signer->permittedNames != NULL) {
  6905. int needDns = 0;
  6906. int matchDns = 0;
  6907. int needEmail = 0;
  6908. int matchEmail = 0;
  6909. int needDir = 0;
  6910. int matchDir = 0;
  6911. Base_entry* base = signer->permittedNames;
  6912. while (base != NULL) {
  6913. switch (base->type) {
  6914. case ASN_DNS_TYPE:
  6915. {
  6916. DNS_entry* name = cert->altNames;
  6917. if (name != NULL)
  6918. needDns = 1;
  6919. while (name != NULL) {
  6920. matchDns = MatchBaseName(ASN_DNS_TYPE,
  6921. name->name, name->len,
  6922. base->name, base->nameSz);
  6923. name = name->next;
  6924. }
  6925. break;
  6926. }
  6927. case ASN_RFC822_TYPE:
  6928. {
  6929. DNS_entry* name = cert->altEmailNames;
  6930. if (name != NULL)
  6931. needEmail = 1;
  6932. while (name != NULL) {
  6933. matchEmail = MatchBaseName(ASN_DNS_TYPE,
  6934. name->name, name->len,
  6935. base->name, base->nameSz);
  6936. name = name->next;
  6937. }
  6938. break;
  6939. }
  6940. case ASN_DIR_TYPE:
  6941. {
  6942. /* allow permitted dirName smaller than actual subject */
  6943. needDir = 1;
  6944. if (cert->subjectRaw != NULL &&
  6945. cert->subjectRawLen >= base->nameSz &&
  6946. XMEMCMP(cert->subjectRaw, base->name,
  6947. base->nameSz) == 0) {
  6948. matchDir = 1;
  6949. #ifndef WOLFSSL_NO_ASN_STRICT
  6950. /* RFC 5280 section 4.2.1.10
  6951. "Restrictions of the form directoryName MUST be
  6952. applied to the subject field .... and to any names
  6953. of type directoryName in the subjectAltName
  6954. extension"
  6955. */
  6956. if (cert->altDirNames != NULL) {
  6957. DNS_entry* cur = cert->altDirNames;
  6958. while (cur != NULL) {
  6959. if (XMEMCMP(cur->name, base->name, base->nameSz)
  6960. != 0) {
  6961. WOLFSSL_MSG("DIR alt name constraint err");
  6962. matchDir = 0; /* did not match */
  6963. }
  6964. cur = cur->next;
  6965. }
  6966. }
  6967. #endif /* !WOLFSSL_NO_ASN_STRICT */
  6968. }
  6969. break;
  6970. }
  6971. default:
  6972. break;
  6973. } /* switch */
  6974. base = base->next;
  6975. }
  6976. if ((needDns && !matchDns) ||
  6977. (needEmail && !matchEmail) ||
  6978. (needDir && !matchDir)) {
  6979. return 0;
  6980. }
  6981. }
  6982. return 1;
  6983. }
  6984. #endif /* IGNORE_NAME_CONSTRAINTS */
  6985. static int DecodeAltNames(const byte* input, int sz, DecodedCert* cert)
  6986. {
  6987. word32 idx = 0;
  6988. int length = 0;
  6989. WOLFSSL_ENTER("DecodeAltNames");
  6990. if (GetSequence(input, &idx, &length, sz) < 0) {
  6991. WOLFSSL_MSG("\tBad Sequence");
  6992. return ASN_PARSE_E;
  6993. }
  6994. if (length == 0) {
  6995. /* RFC 5280 4.2.1.6. Subject Alternative Name
  6996. If the subjectAltName extension is present, the sequence MUST
  6997. contain at least one entry. */
  6998. return ASN_PARSE_E;
  6999. }
  7000. cert->weOwnAltNames = 1;
  7001. while (length > 0) {
  7002. byte b = input[idx++];
  7003. length--;
  7004. /* Save DNS Type names in the altNames list. */
  7005. /* Save Other Type names in the cert's OidMap */
  7006. if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  7007. DNS_entry* dnsEntry;
  7008. int strLen;
  7009. word32 lenStartIdx = idx;
  7010. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7011. WOLFSSL_MSG("\tfail: str length");
  7012. return ASN_PARSE_E;
  7013. }
  7014. length -= (idx - lenStartIdx);
  7015. dnsEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  7016. DYNAMIC_TYPE_ALTNAME);
  7017. if (dnsEntry == NULL) {
  7018. WOLFSSL_MSG("\tOut of Memory");
  7019. return MEMORY_E;
  7020. }
  7021. dnsEntry->type = ASN_DNS_TYPE;
  7022. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  7023. DYNAMIC_TYPE_ALTNAME);
  7024. if (dnsEntry->name == NULL) {
  7025. WOLFSSL_MSG("\tOut of Memory");
  7026. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  7027. return MEMORY_E;
  7028. }
  7029. dnsEntry->len = strLen;
  7030. XMEMCPY(dnsEntry->name, &input[idx], strLen);
  7031. dnsEntry->name[strLen] = '\0';
  7032. dnsEntry->next = cert->altNames;
  7033. cert->altNames = dnsEntry;
  7034. length -= strLen;
  7035. idx += strLen;
  7036. }
  7037. #ifndef IGNORE_NAME_CONSTRAINTS
  7038. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_DIR_TYPE)) {
  7039. DNS_entry* dirEntry;
  7040. int strLen;
  7041. word32 lenStartIdx = idx;
  7042. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7043. WOLFSSL_MSG("\tfail: str length");
  7044. return ASN_PARSE_E;
  7045. }
  7046. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  7047. WOLFSSL_MSG("\tfail: seq length");
  7048. return ASN_PARSE_E;
  7049. }
  7050. length -= (idx - lenStartIdx);
  7051. dirEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  7052. DYNAMIC_TYPE_ALTNAME);
  7053. if (dirEntry == NULL) {
  7054. WOLFSSL_MSG("\tOut of Memory");
  7055. return MEMORY_E;
  7056. }
  7057. dirEntry->type = ASN_DIR_TYPE;
  7058. dirEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  7059. DYNAMIC_TYPE_ALTNAME);
  7060. if (dirEntry->name == NULL) {
  7061. WOLFSSL_MSG("\tOut of Memory");
  7062. XFREE(dirEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  7063. return MEMORY_E;
  7064. }
  7065. dirEntry->len = strLen;
  7066. XMEMCPY(dirEntry->name, &input[idx], strLen);
  7067. dirEntry->name[strLen] = '\0';
  7068. dirEntry->next = cert->altDirNames;
  7069. cert->altDirNames = dirEntry;
  7070. length -= strLen;
  7071. idx += strLen;
  7072. }
  7073. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  7074. DNS_entry* emailEntry;
  7075. int strLen;
  7076. word32 lenStartIdx = idx;
  7077. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7078. WOLFSSL_MSG("\tfail: str length");
  7079. return ASN_PARSE_E;
  7080. }
  7081. length -= (idx - lenStartIdx);
  7082. emailEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  7083. DYNAMIC_TYPE_ALTNAME);
  7084. if (emailEntry == NULL) {
  7085. WOLFSSL_MSG("\tOut of Memory");
  7086. return MEMORY_E;
  7087. }
  7088. emailEntry->type = ASN_RFC822_TYPE;
  7089. emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  7090. DYNAMIC_TYPE_ALTNAME);
  7091. if (emailEntry->name == NULL) {
  7092. WOLFSSL_MSG("\tOut of Memory");
  7093. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  7094. return MEMORY_E;
  7095. }
  7096. emailEntry->len = strLen;
  7097. XMEMCPY(emailEntry->name, &input[idx], strLen);
  7098. emailEntry->name[strLen] = '\0';
  7099. emailEntry->next = cert->altEmailNames;
  7100. cert->altEmailNames = emailEntry;
  7101. length -= strLen;
  7102. idx += strLen;
  7103. }
  7104. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  7105. DNS_entry* uriEntry;
  7106. int strLen;
  7107. word32 lenStartIdx = idx;
  7108. WOLFSSL_MSG("\tPutting URI into list but not using");
  7109. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7110. WOLFSSL_MSG("\tfail: str length");
  7111. return ASN_PARSE_E;
  7112. }
  7113. length -= (idx - lenStartIdx);
  7114. /* check that strLen at index is not past input buffer */
  7115. if (strLen + (int)idx > sz) {
  7116. return BUFFER_E;
  7117. }
  7118. #ifndef WOLFSSL_NO_ASN_STRICT
  7119. /* Verify RFC 5280 Sec 4.2.1.6 rule:
  7120. "The name MUST NOT be a relative URI" */
  7121. {
  7122. int i;
  7123. /* skip past scheme (i.e http,ftp,...) finding first ':' char */
  7124. for (i = 0; i < strLen; i++) {
  7125. if (input[idx + i] == ':') {
  7126. break;
  7127. }
  7128. if (input[idx + i] == '/') {
  7129. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  7130. return ASN_ALT_NAME_E;
  7131. }
  7132. }
  7133. /* test if no ':' char was found and test that the next two
  7134. * chars are // to match the pattern "://" */
  7135. if (i >= strLen - 2 || (input[idx + i + 1] != '/' ||
  7136. input[idx + i + 2] != '/')) {
  7137. WOLFSSL_MSG("\tAlt Name must be absolute URI");
  7138. return ASN_ALT_NAME_E;
  7139. }
  7140. }
  7141. #endif
  7142. uriEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  7143. DYNAMIC_TYPE_ALTNAME);
  7144. if (uriEntry == NULL) {
  7145. WOLFSSL_MSG("\tOut of Memory");
  7146. return MEMORY_E;
  7147. }
  7148. uriEntry->type = ASN_URI_TYPE;
  7149. uriEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  7150. DYNAMIC_TYPE_ALTNAME);
  7151. if (uriEntry->name == NULL) {
  7152. WOLFSSL_MSG("\tOut of Memory");
  7153. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  7154. return MEMORY_E;
  7155. }
  7156. uriEntry->len = strLen;
  7157. XMEMCPY(uriEntry->name, &input[idx], strLen);
  7158. uriEntry->name[strLen] = '\0';
  7159. uriEntry->next = cert->altNames;
  7160. cert->altNames = uriEntry;
  7161. length -= strLen;
  7162. idx += strLen;
  7163. }
  7164. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_IP_ALT_NAME)
  7165. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_IP_TYPE)) {
  7166. DNS_entry* ipAddr;
  7167. int strLen;
  7168. word32 lenStartIdx = idx;
  7169. WOLFSSL_MSG("Decoding Subject Alt. Name: IP Address");
  7170. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7171. WOLFSSL_MSG("\tfail: str length");
  7172. return ASN_PARSE_E;
  7173. }
  7174. length -= (idx - lenStartIdx);
  7175. /* check that strLen at index is not past input buffer */
  7176. if (strLen + (int)idx > sz) {
  7177. return BUFFER_E;
  7178. }
  7179. ipAddr = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  7180. DYNAMIC_TYPE_ALTNAME);
  7181. if (ipAddr == NULL) {
  7182. WOLFSSL_MSG("\tOut of Memory");
  7183. return MEMORY_E;
  7184. }
  7185. ipAddr->type = ASN_IP_TYPE;
  7186. ipAddr->name = (char*)XMALLOC(strLen + 1, cert->heap,
  7187. DYNAMIC_TYPE_ALTNAME);
  7188. if (ipAddr->name == NULL) {
  7189. WOLFSSL_MSG("\tOut of Memory");
  7190. XFREE(ipAddr, cert->heap, DYNAMIC_TYPE_ALTNAME);
  7191. return MEMORY_E;
  7192. }
  7193. ipAddr->len = strLen;
  7194. XMEMCPY(ipAddr->name, &input[idx], strLen);
  7195. ipAddr->name[strLen] = '\0';
  7196. ipAddr->next = cert->altNames;
  7197. cert->altNames = ipAddr;
  7198. length -= strLen;
  7199. idx += strLen;
  7200. }
  7201. #endif /* WOLFSSL_QT || OPENSSL_ALL */
  7202. #endif /* IGNORE_NAME_CONSTRAINTS */
  7203. #ifdef WOLFSSL_SEP
  7204. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE))
  7205. {
  7206. int strLen;
  7207. word32 lenStartIdx = idx;
  7208. word32 oid = 0;
  7209. int ret;
  7210. byte tag;
  7211. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7212. WOLFSSL_MSG("\tfail: other name length");
  7213. return ASN_PARSE_E;
  7214. }
  7215. /* Consume the rest of this sequence. */
  7216. length -= (strLen + idx - lenStartIdx);
  7217. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  7218. WOLFSSL_MSG("\tbad OID");
  7219. return ASN_PARSE_E;
  7220. }
  7221. if (oid != HW_NAME_OID) {
  7222. WOLFSSL_MSG("\tincorrect OID");
  7223. return ASN_PARSE_E;
  7224. }
  7225. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  7226. return ASN_PARSE_E;
  7227. }
  7228. if (tag != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  7229. WOLFSSL_MSG("\twrong type");
  7230. return ASN_PARSE_E;
  7231. }
  7232. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7233. WOLFSSL_MSG("\tfail: str len");
  7234. return ASN_PARSE_E;
  7235. }
  7236. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  7237. WOLFSSL_MSG("\tBad Sequence");
  7238. return ASN_PARSE_E;
  7239. }
  7240. ret = GetASNObjectId(input, &idx, &strLen, sz);
  7241. if (ret != 0) {
  7242. WOLFSSL_MSG("\tbad OID");
  7243. return ret;
  7244. }
  7245. cert->hwType = (byte*)XMALLOC(strLen, cert->heap,
  7246. DYNAMIC_TYPE_X509_EXT);
  7247. if (cert->hwType == NULL) {
  7248. WOLFSSL_MSG("\tOut of Memory");
  7249. return MEMORY_E;
  7250. }
  7251. XMEMCPY(cert->hwType, &input[idx], strLen);
  7252. cert->hwTypeSz = strLen;
  7253. idx += strLen;
  7254. ret = GetOctetString(input, &idx, &strLen, sz);
  7255. if (ret < 0)
  7256. return ret;
  7257. cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap,
  7258. DYNAMIC_TYPE_X509_EXT);
  7259. if (cert->hwSerialNum == NULL) {
  7260. WOLFSSL_MSG("\tOut of Memory");
  7261. return MEMORY_E;
  7262. }
  7263. XMEMCPY(cert->hwSerialNum, &input[idx], strLen);
  7264. cert->hwSerialNum[strLen] = '\0';
  7265. cert->hwSerialNumSz = strLen;
  7266. idx += strLen;
  7267. }
  7268. #endif /* WOLFSSL_SEP */
  7269. else {
  7270. int strLen;
  7271. word32 lenStartIdx = idx;
  7272. WOLFSSL_MSG("\tUnsupported name type, skipping");
  7273. if (GetLength(input, &idx, &strLen, sz) < 0) {
  7274. WOLFSSL_MSG("\tfail: unsupported name length");
  7275. return ASN_PARSE_E;
  7276. }
  7277. length -= (strLen + idx - lenStartIdx);
  7278. idx += strLen;
  7279. }
  7280. }
  7281. return 0;
  7282. }
  7283. static int DecodeBasicCaConstraint(const byte* input, int sz, DecodedCert* cert)
  7284. {
  7285. word32 idx = 0;
  7286. int length = 0;
  7287. int ret;
  7288. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  7289. if (GetSequence(input, &idx, &length, sz) < 0) {
  7290. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  7291. return ASN_PARSE_E;
  7292. }
  7293. if (length == 0)
  7294. return 0;
  7295. /* If the basic ca constraint is false, this extension may be named, but
  7296. * left empty. So, if the length is 0, just return. */
  7297. ret = GetBoolean(input, &idx, sz);
  7298. #ifndef WOLFSSL_X509_BASICCONS_INT
  7299. if (ret < 0) {
  7300. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN");
  7301. return ret;
  7302. }
  7303. cert->isCA = (byte)ret;
  7304. #else
  7305. if (ret < 0) {
  7306. if(input[idx] == ASN_INTEGER) {
  7307. /* For OpenSSL compatibility, if ASN_INTEGER it is valid format */
  7308. cert->isCA = FALSE;
  7309. } else return ret;
  7310. } else
  7311. cert->isCA = (byte)ret;
  7312. #endif
  7313. /* If there isn't any more data, return. */
  7314. if (idx >= (word32)sz) {
  7315. return 0;
  7316. }
  7317. ret = GetInteger7Bit(input, &idx, sz);
  7318. if (ret < 0)
  7319. return ret;
  7320. cert->pathLength = (byte)ret;
  7321. cert->pathLengthSet = 1;
  7322. return 0;
  7323. }
  7324. #define CRLDP_FULL_NAME 0
  7325. /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
  7326. #define GENERALNAME_URI 6
  7327. /* From RFC3280 SS4.2.1.7, GeneralName */
  7328. static int DecodeCrlDist(const byte* input, int sz, DecodedCert* cert)
  7329. {
  7330. word32 idx = 0, localIdx;
  7331. int length = 0;
  7332. byte tag = 0;
  7333. WOLFSSL_ENTER("DecodeCrlDist");
  7334. /* Unwrap the list of Distribution Points*/
  7335. if (GetSequence(input, &idx, &length, sz) < 0)
  7336. return ASN_PARSE_E;
  7337. /* Unwrap a single Distribution Point */
  7338. if (GetSequence(input, &idx, &length, sz) < 0)
  7339. return ASN_PARSE_E;
  7340. /* The Distribution Point has three explicit optional members
  7341. * First check for a DistributionPointName
  7342. */
  7343. localIdx = idx;
  7344. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  7345. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  7346. {
  7347. idx++;
  7348. if (GetLength(input, &idx, &length, sz) < 0)
  7349. return ASN_PARSE_E;
  7350. localIdx = idx;
  7351. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  7352. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED |
  7353. CRLDP_FULL_NAME))
  7354. {
  7355. idx++;
  7356. if (GetLength(input, &idx, &length, sz) < 0)
  7357. return ASN_PARSE_E;
  7358. localIdx = idx;
  7359. if (GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  7360. tag == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
  7361. {
  7362. idx++;
  7363. if (GetLength(input, &idx, &length, sz) < 0)
  7364. return ASN_PARSE_E;
  7365. cert->extCrlInfoSz = length;
  7366. cert->extCrlInfo = input + idx;
  7367. idx += length;
  7368. }
  7369. else
  7370. /* This isn't a URI, skip it. */
  7371. idx += length;
  7372. }
  7373. else {
  7374. /* This isn't a FULLNAME, skip it. */
  7375. idx += length;
  7376. }
  7377. }
  7378. /* Check for reasonFlags */
  7379. localIdx = idx;
  7380. if (idx < (word32)sz &&
  7381. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  7382. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  7383. {
  7384. idx++;
  7385. if (GetLength(input, &idx, &length, sz) < 0)
  7386. return ASN_PARSE_E;
  7387. idx += length;
  7388. }
  7389. /* Check for cRLIssuer */
  7390. localIdx = idx;
  7391. if (idx < (word32)sz &&
  7392. GetASNTag(input, &localIdx, &tag, sz) == 0 &&
  7393. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  7394. {
  7395. idx++;
  7396. if (GetLength(input, &idx, &length, sz) < 0)
  7397. return ASN_PARSE_E;
  7398. idx += length;
  7399. }
  7400. if (idx < (word32)sz)
  7401. {
  7402. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  7403. "but we only use the first one.");
  7404. }
  7405. return 0;
  7406. }
  7407. static int DecodeAuthInfo(const byte* input, int sz, DecodedCert* cert)
  7408. /*
  7409. * Read Authority Information Access records. If there are
  7410. * any issues, return without saving the record.
  7411. */
  7412. {
  7413. word32 idx = 0;
  7414. int length = 0;
  7415. int count = 0;
  7416. byte b = 0;
  7417. word32 oid;
  7418. WOLFSSL_ENTER("DecodeAuthInfo");
  7419. /* Unwrap the list of AIAs */
  7420. if (GetSequence(input, &idx, &length, sz) < 0)
  7421. return ASN_PARSE_E;
  7422. while ((idx < (word32)sz) && (count < MAX_AIA_SZ)) {
  7423. /* Unwrap a single AIA */
  7424. if (GetSequence(input, &idx, &length, sz) < 0)
  7425. return ASN_PARSE_E;
  7426. oid = 0;
  7427. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  7428. return ASN_PARSE_E;
  7429. /* Only supporting URIs right now. */
  7430. if (GetASNTag(input, &idx, &b, sz) < 0)
  7431. return ASN_PARSE_E;
  7432. if (GetLength(input, &idx, &length, sz) < 0)
  7433. return ASN_PARSE_E;
  7434. /* Set ocsp entry */
  7435. if (b == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI) &&
  7436. oid == AIA_OCSP_OID)
  7437. {
  7438. cert->extAuthInfoSz = length;
  7439. cert->extAuthInfo = input + idx;
  7440. count++;
  7441. #if !defined(OPENSSL_ALL) || !defined(WOLFSSL_QT)
  7442. break;
  7443. #endif
  7444. }
  7445. #if defined(OPENSSL_ALL) || defined(WOLFSSL_QT)
  7446. /* Set CaIssuers entry */
  7447. else if ((b == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI)) &&
  7448. oid == AIA_CA_ISSUER_OID)
  7449. {
  7450. cert->extAuthInfoCaIssuerSz = length;
  7451. cert->extAuthInfoCaIssuer = input + idx;
  7452. count++;
  7453. }
  7454. #endif
  7455. idx += length;
  7456. }
  7457. return 0;
  7458. }
  7459. static int DecodeAuthKeyId(const byte* input, int sz, DecodedCert* cert)
  7460. {
  7461. word32 idx = 0;
  7462. int length = 0, ret = 0;
  7463. byte tag;
  7464. WOLFSSL_ENTER("DecodeAuthKeyId");
  7465. if (GetSequence(input, &idx, &length, sz) < 0) {
  7466. WOLFSSL_MSG("\tfail: should be a SEQUENCE\n");
  7467. return ASN_PARSE_E;
  7468. }
  7469. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  7470. return ASN_PARSE_E;
  7471. }
  7472. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  7473. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
  7474. cert->extAuthKeyIdSet = 0;
  7475. return 0;
  7476. }
  7477. if (GetLength(input, &idx, &length, sz) <= 0) {
  7478. WOLFSSL_MSG("\tfail: extension data length");
  7479. return ASN_PARSE_E;
  7480. }
  7481. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7482. cert->extAuthKeyIdSrc = &input[idx];
  7483. cert->extAuthKeyIdSz = length;
  7484. #endif /* OPENSSL_EXTRA */
  7485. if (length == KEYID_SIZE) {
  7486. XMEMCPY(cert->extAuthKeyId, input + idx, length);
  7487. }
  7488. else
  7489. ret = CalcHashId(input + idx, length, cert->extAuthKeyId);
  7490. return ret;
  7491. }
  7492. static int DecodeSubjKeyId(const byte* input, int sz, DecodedCert* cert)
  7493. {
  7494. word32 idx = 0;
  7495. int length = 0, ret = 0;
  7496. WOLFSSL_ENTER("DecodeSubjKeyId");
  7497. if (sz <= 0)
  7498. return ASN_PARSE_E;
  7499. ret = GetOctetString(input, &idx, &length, sz);
  7500. if (ret < 0)
  7501. return ret;
  7502. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7503. cert->extSubjKeyIdSrc = &input[idx];
  7504. cert->extSubjKeyIdSz = length;
  7505. #endif /* OPENSSL_EXTRA */
  7506. if (length == KEYID_SIZE) {
  7507. XMEMCPY(cert->extSubjKeyId, input + idx, length);
  7508. }
  7509. else
  7510. ret = CalcHashId(input + idx, length, cert->extSubjKeyId);
  7511. return ret;
  7512. }
  7513. static int DecodeKeyUsage(const byte* input, int sz, DecodedCert* cert)
  7514. {
  7515. word32 idx = 0;
  7516. int length;
  7517. int ret;
  7518. WOLFSSL_ENTER("DecodeKeyUsage");
  7519. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  7520. if (ret != 0)
  7521. return ret;
  7522. cert->extKeyUsage = (word16)(input[idx]);
  7523. if (length == 2)
  7524. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  7525. return 0;
  7526. }
  7527. static int DecodeExtKeyUsage(const byte* input, int sz, DecodedCert* cert)
  7528. {
  7529. word32 idx = 0, oid;
  7530. int length, ret;
  7531. WOLFSSL_MSG("DecodeExtKeyUsage");
  7532. if (GetSequence(input, &idx, &length, sz) < 0) {
  7533. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  7534. return ASN_PARSE_E;
  7535. }
  7536. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7537. cert->extExtKeyUsageSrc = input + idx;
  7538. cert->extExtKeyUsageSz = length;
  7539. #endif
  7540. while (idx < (word32)sz) {
  7541. ret = GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz);
  7542. if (ret == ASN_UNKNOWN_OID_E)
  7543. continue;
  7544. else if (ret < 0)
  7545. return ret;
  7546. switch (oid) {
  7547. case EKU_ANY_OID:
  7548. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  7549. break;
  7550. case EKU_SERVER_AUTH_OID:
  7551. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  7552. break;
  7553. case EKU_CLIENT_AUTH_OID:
  7554. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  7555. break;
  7556. case EKU_CODESIGNING_OID:
  7557. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  7558. break;
  7559. case EKU_EMAILPROTECT_OID:
  7560. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  7561. break;
  7562. case EKU_TIMESTAMP_OID:
  7563. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  7564. break;
  7565. case EKU_OCSP_SIGN_OID:
  7566. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  7567. break;
  7568. default:
  7569. break;
  7570. }
  7571. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7572. cert->extExtKeyUsageCount++;
  7573. #endif
  7574. }
  7575. return 0;
  7576. }
  7577. #ifndef IGNORE_NAME_CONSTRAINTS
  7578. #define ASN_TYPE_MASK 0xF
  7579. static int DecodeSubtree(const byte* input, int sz,
  7580. Base_entry** head, void* heap)
  7581. {
  7582. word32 idx = 0;
  7583. (void)heap;
  7584. while (idx < (word32)sz) {
  7585. int seqLength, strLength;
  7586. word32 nameIdx;
  7587. byte b, bType;
  7588. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  7589. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  7590. return ASN_PARSE_E;
  7591. }
  7592. nameIdx = idx;
  7593. b = input[nameIdx++];
  7594. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  7595. WOLFSSL_MSG("\tinvalid length");
  7596. return ASN_PARSE_E;
  7597. }
  7598. /* Get type, LSB 4-bits */
  7599. bType = (b & ASN_TYPE_MASK);
  7600. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  7601. bType == ASN_DIR_TYPE) {
  7602. Base_entry* entry;
  7603. /* if constructed has leading sequence */
  7604. if (b & ASN_CONSTRUCTED) {
  7605. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  7606. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  7607. return ASN_PARSE_E;
  7608. }
  7609. }
  7610. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  7611. DYNAMIC_TYPE_ALTNAME);
  7612. if (entry == NULL) {
  7613. WOLFSSL_MSG("allocate error");
  7614. return MEMORY_E;
  7615. }
  7616. entry->name = (char*)XMALLOC(strLength, heap, DYNAMIC_TYPE_ALTNAME);
  7617. if (entry->name == NULL) {
  7618. WOLFSSL_MSG("allocate error");
  7619. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  7620. return MEMORY_E;
  7621. }
  7622. XMEMCPY(entry->name, &input[nameIdx], strLength);
  7623. entry->nameSz = strLength;
  7624. entry->type = bType;
  7625. entry->next = *head;
  7626. *head = entry;
  7627. }
  7628. idx += seqLength;
  7629. }
  7630. return 0;
  7631. }
  7632. static int DecodeNameConstraints(const byte* input, int sz, DecodedCert* cert)
  7633. {
  7634. word32 idx = 0;
  7635. int length = 0;
  7636. WOLFSSL_ENTER("DecodeNameConstraints");
  7637. if (GetSequence(input, &idx, &length, sz) < 0) {
  7638. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  7639. return ASN_PARSE_E;
  7640. }
  7641. while (idx < (word32)sz) {
  7642. byte b = input[idx++];
  7643. Base_entry** subtree = NULL;
  7644. if (GetLength(input, &idx, &length, sz) <= 0) {
  7645. WOLFSSL_MSG("\tinvalid length");
  7646. return ASN_PARSE_E;
  7647. }
  7648. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  7649. subtree = &cert->permittedNames;
  7650. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  7651. subtree = &cert->excludedNames;
  7652. else {
  7653. WOLFSSL_MSG("\tinvalid subtree");
  7654. return ASN_PARSE_E;
  7655. }
  7656. if (DecodeSubtree(input + idx, length, subtree, cert->heap) < 0) {
  7657. WOLFSSL_MSG("\terror parsing subtree");
  7658. return ASN_PARSE_E;
  7659. }
  7660. idx += length;
  7661. }
  7662. return 0;
  7663. }
  7664. #endif /* IGNORE_NAME_CONSTRAINTS */
  7665. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || \
  7666. defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7667. /* Decode ITU-T X.690 OID format to a string representation
  7668. * return string length */
  7669. int DecodePolicyOID(char *out, word32 outSz, const byte *in, word32 inSz)
  7670. {
  7671. word32 val, inIdx = 0, outIdx = 0;
  7672. int w = 0;
  7673. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  7674. return BAD_FUNC_ARG;
  7675. /* The first byte expands into b/40 dot b%40. */
  7676. val = in[inIdx++];
  7677. w = XSNPRINTF(out, outSz, "%u.%u", val / 40, val % 40);
  7678. if (w < 0)
  7679. goto exit;
  7680. outIdx += w;
  7681. val = 0;
  7682. while (inIdx < inSz && outIdx < outSz) {
  7683. /* extract the next OID digit from in to val */
  7684. /* first bit is used to set if value is coded on 1 or multiple bytes */
  7685. if (in[inIdx] & 0x80) {
  7686. val += in[inIdx] & 0x7F;
  7687. val *= 128;
  7688. }
  7689. else {
  7690. /* write val as text into out */
  7691. val += in[inIdx];
  7692. w = XSNPRINTF(out + outIdx, outSz - outIdx, ".%u", val);
  7693. if (w < 0)
  7694. goto exit;
  7695. outIdx += w;
  7696. val = 0;
  7697. }
  7698. inIdx++;
  7699. }
  7700. if (outIdx == outSz)
  7701. outIdx--;
  7702. out[outIdx] = 0;
  7703. w = (int)outIdx;
  7704. exit:
  7705. return w;
  7706. }
  7707. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  7708. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_QT)
  7709. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  7710. static int DecodeCertPolicy(const byte* input, int sz, DecodedCert* cert)
  7711. {
  7712. word32 idx = 0;
  7713. word32 oldIdx;
  7714. int ret;
  7715. int total_length = 0, policy_length = 0, length = 0;
  7716. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  7717. !defined(WOLFSSL_DUP_CERTPOL)
  7718. int i;
  7719. #endif
  7720. WOLFSSL_ENTER("DecodeCertPolicy");
  7721. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  7722. /* Check if cert is null before dereferencing below */
  7723. if (cert == NULL)
  7724. return BAD_FUNC_ARG;
  7725. #endif
  7726. #if defined(WOLFSSL_CERT_EXT)
  7727. cert->extCertPoliciesNb = 0;
  7728. #endif
  7729. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  7730. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  7731. return ASN_PARSE_E;
  7732. }
  7733. /* Validate total length */
  7734. if (total_length > (sz - (int)idx)) {
  7735. WOLFSSL_MSG("\tCertPolicy length mismatch");
  7736. return ASN_PARSE_E;
  7737. }
  7738. /* Unwrap certificatePolicies */
  7739. do {
  7740. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  7741. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  7742. return ASN_PARSE_E;
  7743. }
  7744. oldIdx = idx;
  7745. ret = GetASNObjectId(input, &idx, &length, sz);
  7746. if (ret != 0)
  7747. return ret;
  7748. policy_length -= idx - oldIdx;
  7749. if (length > 0) {
  7750. /* Verify length won't overrun buffer */
  7751. if (length > (sz - (int)idx)) {
  7752. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  7753. return ASN_PARSE_E;
  7754. }
  7755. #if defined(WOLFSSL_SEP)
  7756. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  7757. DYNAMIC_TYPE_X509_EXT);
  7758. if (cert->deviceType == NULL) {
  7759. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  7760. return MEMORY_E;
  7761. }
  7762. cert->deviceTypeSz = length;
  7763. XMEMCPY(cert->deviceType, input + idx, length);
  7764. break;
  7765. #elif defined(WOLFSSL_CERT_EXT)
  7766. /* decode cert policy */
  7767. if (DecodePolicyOID(cert->extCertPolicies[
  7768. cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  7769. input + idx, length) <= 0) {
  7770. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  7771. return ASN_PARSE_E;
  7772. }
  7773. #ifndef WOLFSSL_DUP_CERTPOL
  7774. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  7775. * NOT appear more than once in a certificate policies
  7776. * extension". This is a sanity check for duplicates.
  7777. * extCertPolicies should only have OID values, additional
  7778. * qualifiers need to be stored in a separate array. */
  7779. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  7780. if (XMEMCMP(cert->extCertPolicies[i],
  7781. cert->extCertPolicies[cert->extCertPoliciesNb],
  7782. MAX_CERTPOL_SZ) == 0) {
  7783. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  7784. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  7785. return CERTPOLICIES_E;
  7786. }
  7787. }
  7788. #endif /* !WOLFSSL_DUP_CERTPOL */
  7789. cert->extCertPoliciesNb++;
  7790. #else
  7791. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  7792. return 0;
  7793. #endif
  7794. }
  7795. idx += policy_length;
  7796. } while((int)idx < total_length
  7797. #if defined(WOLFSSL_CERT_EXT)
  7798. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  7799. #endif
  7800. );
  7801. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  7802. return 0;
  7803. }
  7804. #endif /* WOLFSSL_SEP */
  7805. /* Macro to check if bit is set, if not sets and return success.
  7806. Otherwise returns failure */
  7807. /* Macro required here because bit-field operation */
  7808. #ifndef WOLFSSL_NO_ASN_STRICT
  7809. #define VERIFY_AND_SET_OID(bit) \
  7810. if (bit == 0) \
  7811. bit = 1; \
  7812. else \
  7813. return ASN_OBJECT_ID_E;
  7814. #else
  7815. /* With no strict defined, the verify is skipped */
  7816. #define VERIFY_AND_SET_OID(bit) bit = 1;
  7817. #endif
  7818. static int DecodeCertExtensions(DecodedCert* cert)
  7819. /*
  7820. * Processing the Certificate Extensions. This does not modify the current
  7821. * index. It is works starting with the recorded extensions pointer.
  7822. */
  7823. {
  7824. int ret = 0;
  7825. word32 idx = 0;
  7826. int sz = cert->extensionsSz;
  7827. const byte* input = cert->extensions;
  7828. int length;
  7829. word32 oid;
  7830. byte critical = 0;
  7831. byte criticalFail = 0;
  7832. byte tag = 0;
  7833. WOLFSSL_ENTER("DecodeCertExtensions");
  7834. if (input == NULL || sz == 0)
  7835. return BAD_FUNC_ARG;
  7836. #ifdef WOLFSSL_CERT_REQ
  7837. if (!cert->isCSR)
  7838. #endif
  7839. { /* Not included in CSR */
  7840. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  7841. return ASN_PARSE_E;
  7842. }
  7843. if (tag != ASN_EXTENSIONS) {
  7844. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  7845. return ASN_PARSE_E;
  7846. }
  7847. if (GetLength(input, &idx, &length, sz) < 0) {
  7848. WOLFSSL_MSG("\tfail: invalid length");
  7849. return ASN_PARSE_E;
  7850. }
  7851. }
  7852. if (GetSequence(input, &idx, &length, sz) < 0) {
  7853. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  7854. return ASN_PARSE_E;
  7855. }
  7856. while (idx < (word32)sz) {
  7857. word32 localIdx;
  7858. if (GetSequence(input, &idx, &length, sz) < 0) {
  7859. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  7860. return ASN_PARSE_E;
  7861. }
  7862. oid = 0;
  7863. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  7864. WOLFSSL_MSG("\tfail: OBJECT ID");
  7865. return ret;
  7866. }
  7867. /* check for critical flag */
  7868. critical = 0;
  7869. if ((idx + 1) > (word32)sz) {
  7870. WOLFSSL_MSG("\tfail: malformed buffer");
  7871. return BUFFER_E;
  7872. }
  7873. localIdx = idx;
  7874. if (GetASNTag(input, &localIdx, &tag, sz) == 0) {
  7875. if (tag == ASN_BOOLEAN) {
  7876. ret = GetBoolean(input, &idx, sz);
  7877. if (ret < 0) {
  7878. WOLFSSL_MSG("\tfail: critical boolean");
  7879. return ret;
  7880. }
  7881. critical = (byte)ret;
  7882. }
  7883. }
  7884. /* process the extension based on the OID */
  7885. ret = GetOctetString(input, &idx, &length, sz);
  7886. if (ret < 0) {
  7887. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  7888. return ret;
  7889. }
  7890. switch (oid) {
  7891. case BASIC_CA_OID:
  7892. VERIFY_AND_SET_OID(cert->extBasicConstSet);
  7893. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7894. cert->extBasicConstCrit = critical;
  7895. #endif
  7896. if (DecodeBasicCaConstraint(&input[idx], length, cert) < 0)
  7897. return ASN_PARSE_E;
  7898. break;
  7899. case CRL_DIST_OID:
  7900. VERIFY_AND_SET_OID(cert->extCRLdistSet);
  7901. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7902. cert->extCRLdistCrit = critical;
  7903. #endif
  7904. if (DecodeCrlDist(&input[idx], length, cert) < 0)
  7905. return ASN_PARSE_E;
  7906. break;
  7907. case AUTH_INFO_OID:
  7908. VERIFY_AND_SET_OID(cert->extAuthInfoSet);
  7909. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7910. cert->extAuthInfoCrit = critical;
  7911. #endif
  7912. if (DecodeAuthInfo(&input[idx], length, cert) < 0)
  7913. return ASN_PARSE_E;
  7914. break;
  7915. case ALT_NAMES_OID:
  7916. VERIFY_AND_SET_OID(cert->extSubjAltNameSet);
  7917. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7918. cert->extSubjAltNameCrit = critical;
  7919. #endif
  7920. ret = DecodeAltNames(&input[idx], length, cert);
  7921. if (ret < 0)
  7922. return ret;
  7923. break;
  7924. case AUTH_KEY_OID:
  7925. VERIFY_AND_SET_OID(cert->extAuthKeyIdSet);
  7926. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7927. cert->extAuthKeyIdCrit = critical;
  7928. #endif
  7929. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  7930. /* This check is added due to RFC 5280 section 4.2.1.1
  7931. * stating that conforming CA's must mark this extension
  7932. * as non-critical. When parsing extensions check that
  7933. * certificate was made in compliance with this. */
  7934. if (critical) {
  7935. WOLFSSL_MSG("Critical Auth Key ID is not allowed");
  7936. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  7937. return ASN_CRIT_EXT_E;
  7938. }
  7939. #endif
  7940. if (DecodeAuthKeyId(&input[idx], length, cert) < 0)
  7941. return ASN_PARSE_E;
  7942. break;
  7943. case SUBJ_KEY_OID:
  7944. VERIFY_AND_SET_OID(cert->extSubjKeyIdSet);
  7945. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7946. cert->extSubjKeyIdCrit = critical;
  7947. #endif
  7948. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  7949. /* This check is added due to RFC 5280 section 4.2.1.2
  7950. * stating that conforming CA's must mark this extension
  7951. * as non-critical. When parsing extensions check that
  7952. * certificate was made in compliance with this. */
  7953. if (critical) {
  7954. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  7955. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  7956. return ASN_CRIT_EXT_E;
  7957. }
  7958. #endif
  7959. if (DecodeSubjKeyId(&input[idx], length, cert) < 0)
  7960. return ASN_PARSE_E;
  7961. break;
  7962. case CERT_POLICY_OID:
  7963. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_QT)
  7964. VERIFY_AND_SET_OID(cert->extCertPolicySet);
  7965. #if defined(OPENSSL_EXTRA) || \
  7966. defined(OPENSSL_EXTRA_X509_SMALL)
  7967. cert->extCertPolicyCrit = critical;
  7968. #endif
  7969. #endif
  7970. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT) || \
  7971. defined(WOLFSSL_QT)
  7972. if (DecodeCertPolicy(&input[idx], length, cert) < 0) {
  7973. return ASN_PARSE_E;
  7974. }
  7975. #else
  7976. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  7977. #endif
  7978. break;
  7979. case KEY_USAGE_OID:
  7980. VERIFY_AND_SET_OID(cert->extKeyUsageSet);
  7981. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7982. cert->extKeyUsageCrit = critical;
  7983. #endif
  7984. if (DecodeKeyUsage(&input[idx], length, cert) < 0)
  7985. return ASN_PARSE_E;
  7986. break;
  7987. case EXT_KEY_USAGE_OID:
  7988. VERIFY_AND_SET_OID(cert->extExtKeyUsageSet);
  7989. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7990. cert->extExtKeyUsageCrit = critical;
  7991. #endif
  7992. if (DecodeExtKeyUsage(&input[idx], length, cert) < 0)
  7993. return ASN_PARSE_E;
  7994. break;
  7995. #ifndef IGNORE_NAME_CONSTRAINTS
  7996. case NAME_CONS_OID:
  7997. #ifndef WOLFSSL_NO_ASN_STRICT
  7998. /* Verify RFC 5280 Sec 4.2.1.10 rule:
  7999. "The name constraints extension,
  8000. which MUST be used only in a CA certificate" */
  8001. if (!cert->isCA) {
  8002. WOLFSSL_MSG("Name constraints allowed only for CA certs");
  8003. return ASN_NAME_INVALID_E;
  8004. }
  8005. #endif
  8006. VERIFY_AND_SET_OID(cert->extNameConstraintSet);
  8007. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8008. cert->extNameConstraintCrit = critical;
  8009. #endif
  8010. if (DecodeNameConstraints(&input[idx], length, cert) < 0)
  8011. return ASN_PARSE_E;
  8012. break;
  8013. #endif /* IGNORE_NAME_CONSTRAINTS */
  8014. case INHIBIT_ANY_OID:
  8015. VERIFY_AND_SET_OID(cert->inhibitAnyOidSet);
  8016. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  8017. break;
  8018. #ifndef IGNORE_NETSCAPE_CERT_TYPE
  8019. case NETSCAPE_CT_OID:
  8020. WOLFSSL_MSG("Netscape certificate type extension not supported "
  8021. "yet.");
  8022. if (CheckBitString(input, &idx, &length, idx + length, 0,
  8023. NULL) < 0) {
  8024. return ASN_PARSE_E;
  8025. }
  8026. break;
  8027. #endif
  8028. #ifdef HAVE_OCSP
  8029. case OCSP_NOCHECK_OID:
  8030. VERIFY_AND_SET_OID(cert->ocspNoCheckSet);
  8031. ret = GetASNNull(input, &idx, sz);
  8032. length = 0; /* idx is already incremented, reset length to 0 */
  8033. if (ret != 0)
  8034. return ASN_PARSE_E;
  8035. break;
  8036. #endif
  8037. default:
  8038. #ifndef WOLFSSL_NO_ASN_STRICT
  8039. /* While it is a failure to not support critical extensions,
  8040. * still parse the certificate ignoring the unsupported
  8041. * extension to allow caller to accept it with the verify
  8042. * callback. */
  8043. if (critical)
  8044. criticalFail = 1;
  8045. #endif
  8046. break;
  8047. }
  8048. idx += length;
  8049. }
  8050. return criticalFail ? ASN_CRIT_EXT_E : 0;
  8051. }
  8052. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  8053. {
  8054. int ret;
  8055. char* ptr;
  8056. ret = ParseCertRelative(cert, type, verify, cm);
  8057. if (ret < 0)
  8058. return ret;
  8059. if (cert->subjectCNLen > 0) {
  8060. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  8061. DYNAMIC_TYPE_SUBJECT_CN);
  8062. if (ptr == NULL)
  8063. return MEMORY_E;
  8064. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  8065. ptr[cert->subjectCNLen] = '\0';
  8066. cert->subjectCN = ptr;
  8067. cert->subjectCNStored = 1;
  8068. }
  8069. if (cert->keyOID == RSAk &&
  8070. cert->publicKey != NULL && cert->pubKeySize > 0) {
  8071. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  8072. DYNAMIC_TYPE_PUBLIC_KEY);
  8073. if (ptr == NULL)
  8074. return MEMORY_E;
  8075. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  8076. cert->publicKey = (byte *)ptr;
  8077. cert->pubKeyStored = 1;
  8078. }
  8079. return ret;
  8080. }
  8081. /* from SSL proper, for locking can't do find here anymore */
  8082. #ifdef __cplusplus
  8083. extern "C" {
  8084. #endif
  8085. Signer* GetCA(void* signers, byte* hash);
  8086. #ifndef NO_SKID
  8087. Signer* GetCAByName(void* signers, byte* hash);
  8088. #endif
  8089. #ifdef __cplusplus
  8090. }
  8091. #endif
  8092. #if defined(WOLFCRYPT_ONLY) || defined(NO_CERTS)
  8093. /* dummy functions, not using wolfSSL so don't need actual ones */
  8094. Signer* GetCA(void* signers, byte* hash)
  8095. {
  8096. (void)hash;
  8097. return (Signer*)signers;
  8098. }
  8099. #ifndef NO_SKID
  8100. Signer* GetCAByName(void* signers, byte* hash)
  8101. {
  8102. (void)hash;
  8103. return (Signer*)signers;
  8104. }
  8105. #endif /* NO_SKID */
  8106. #endif /* WOLFCRYPT_ONLY || NO_CERTS */
  8107. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  8108. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  8109. {
  8110. Signer* ca = NULL;
  8111. if (cert->extSubjKeyIdSet)
  8112. ca = GetCA(cm, cert->extSubjKeyId);
  8113. if (ca == NULL)
  8114. ca = GetCAByName(cm, cert->subjectHash);
  8115. if (ca) {
  8116. if ((ca->pubKeySize == cert->pubKeySize) &&
  8117. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  8118. return ca;
  8119. }
  8120. }
  8121. return NULL;
  8122. }
  8123. #endif
  8124. #if defined(WOLFSSL_SMALL_CERT_VERIFY) || defined(OPENSSL_EXTRA)
  8125. /* Only quick step through the certificate to find fields that are then used
  8126. * in certificate signature verification.
  8127. * Must use the signature OID from the signed part of the certificate.
  8128. * Works also on certificate signing requests.
  8129. *
  8130. * This is only for minimizing dynamic memory usage during TLS certificate
  8131. * chain processing.
  8132. * Doesn't support:
  8133. * OCSP Only: alt lookup using subject and pub key w/o sig check
  8134. */
  8135. static int CheckCertSignature_ex(const byte* cert, word32 certSz, void* heap,
  8136. void* cm, const byte* pubKey, word32 pubKeySz, int pubKeyOID, int req)
  8137. {
  8138. #ifndef WOLFSSL_SMALL_STACK
  8139. SignatureCtx sigCtx[1];
  8140. #else
  8141. SignatureCtx* sigCtx;
  8142. #endif
  8143. byte hash[KEYID_SIZE];
  8144. Signer* ca = NULL;
  8145. word32 idx = 0;
  8146. int len;
  8147. word32 tbsCertIdx = 0;
  8148. word32 sigIndex = 0;
  8149. word32 signatureOID = 0;
  8150. word32 oid = 0;
  8151. word32 issuerIdx = 0;
  8152. word32 issuerSz = 0;
  8153. #ifndef NO_SKID
  8154. int extLen = 0;
  8155. word32 extIdx = 0;
  8156. word32 extEndIdx = 0;
  8157. int extAuthKeyIdSet = 0;
  8158. #endif
  8159. int ret = 0;
  8160. word32 localIdx;
  8161. byte tag;
  8162. if (cert == NULL) {
  8163. return BAD_FUNC_ARG;
  8164. }
  8165. #ifdef WOLFSSL_SMALL_STACK
  8166. sigCtx = (SignatureCtx*)XMALLOC(sizeof(*sigCtx), heap, DYNAMIC_TYPE_SIGNATURE);
  8167. if (sigCtx == NULL)
  8168. return MEMORY_E;
  8169. #endif
  8170. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  8171. /* Certificate SEQUENCE */
  8172. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8173. ret = ASN_PARSE_E;
  8174. if (ret == 0) {
  8175. tbsCertIdx = idx;
  8176. /* TBSCertificate SEQUENCE */
  8177. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8178. ret = ASN_PARSE_E;
  8179. }
  8180. if (ret == 0) {
  8181. sigIndex = len + idx;
  8182. if ((idx + 1) > certSz)
  8183. ret = BUFFER_E;
  8184. }
  8185. if (ret == 0) {
  8186. /* version - optional */
  8187. localIdx = idx;
  8188. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  8189. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  8190. idx++;
  8191. if (GetLength(cert, &idx, &len, certSz) < 0)
  8192. ret = ASN_PARSE_E;
  8193. idx += len;
  8194. }
  8195. }
  8196. }
  8197. if (ret == 0) {
  8198. /* serialNumber */
  8199. if (GetASNHeader(cert, ASN_INTEGER, &idx, &len, certSz) < 0)
  8200. ret = ASN_PARSE_E;
  8201. }
  8202. if (ret == 0) {
  8203. idx += len;
  8204. /* signature */
  8205. if (!req &&
  8206. GetAlgoId(cert, &idx, &signatureOID, oidSigType, certSz) < 0)
  8207. ret = ASN_PARSE_E;
  8208. }
  8209. if (ret == 0) {
  8210. issuerIdx = idx;
  8211. /* issuer for cert or subject for csr */
  8212. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8213. ret = ASN_PARSE_E;
  8214. }
  8215. if (ret == 0) {
  8216. issuerSz = len + idx - issuerIdx;
  8217. }
  8218. #ifndef NO_SKID
  8219. if (!req && ret == 0) {
  8220. idx += len;
  8221. /* validity */
  8222. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8223. ret = ASN_PARSE_E;
  8224. }
  8225. if (!req && ret == 0) {
  8226. idx += len;
  8227. /* subject */
  8228. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8229. ret = ASN_PARSE_E;
  8230. }
  8231. if (ret == 0) {
  8232. idx += len;
  8233. /* subjectPublicKeyInfo */
  8234. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8235. ret = ASN_PARSE_E;
  8236. }
  8237. if (req && ret == 0) {
  8238. idx += len;
  8239. /* attributes */
  8240. if (GetASNHeader_ex(cert,
  8241. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &idx,
  8242. &len, certSz, 1) < 0)
  8243. ret = ASN_PARSE_E;
  8244. }
  8245. if (!req) {
  8246. if (ret == 0) {
  8247. idx += len;
  8248. if ((idx + 1) > certSz)
  8249. ret = BUFFER_E;
  8250. }
  8251. if (ret == 0) {
  8252. /* issuerUniqueID - optional */
  8253. localIdx = idx;
  8254. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  8255. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) {
  8256. idx++;
  8257. if (GetLength(cert, &idx, &len, certSz) < 0)
  8258. ret = ASN_PARSE_E;
  8259. idx += len;
  8260. }
  8261. }
  8262. }
  8263. if (ret == 0) {
  8264. if ((idx + 1) > certSz)
  8265. ret = BUFFER_E;
  8266. }
  8267. if (ret == 0) {
  8268. /* subjectUniqueID - optional */
  8269. localIdx = idx;
  8270. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0) {
  8271. if (tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)) {
  8272. idx++;
  8273. if (GetLength(cert, &idx, &len, certSz) < 0)
  8274. ret = ASN_PARSE_E;
  8275. idx += len;
  8276. }
  8277. }
  8278. }
  8279. if (ret == 0) {
  8280. if ((idx + 1) > certSz)
  8281. ret = BUFFER_E;
  8282. }
  8283. /* extensions - optional */
  8284. localIdx = idx;
  8285. if (ret == 0 && GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  8286. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 3)) {
  8287. idx++;
  8288. if (GetLength(cert, &idx, &extLen, certSz) < 0)
  8289. ret = ASN_PARSE_E;
  8290. if (ret == 0) {
  8291. if (GetSequence(cert, &idx, &extLen, certSz) < 0)
  8292. ret = ASN_PARSE_E;
  8293. }
  8294. if (ret == 0) {
  8295. extEndIdx = idx + extLen;
  8296. /* Check each extension for the ones we want. */
  8297. while (ret == 0 && idx < extEndIdx) {
  8298. if (GetSequence(cert, &idx, &len, certSz) < 0)
  8299. ret = ASN_PARSE_E;
  8300. if (ret == 0) {
  8301. extIdx = idx;
  8302. if (GetObjectId(cert, &extIdx, &oid, oidCertExtType,
  8303. certSz) < 0) {
  8304. ret = ASN_PARSE_E;
  8305. }
  8306. if (ret == 0) {
  8307. if ((extIdx + 1) > certSz)
  8308. ret = BUFFER_E;
  8309. }
  8310. }
  8311. if (ret == 0) {
  8312. localIdx = extIdx;
  8313. if (GetASNTag(cert, &localIdx, &tag, certSz) == 0 &&
  8314. tag == ASN_BOOLEAN) {
  8315. if (GetBoolean(cert, &extIdx, certSz) < 0)
  8316. ret = ASN_PARSE_E;
  8317. }
  8318. }
  8319. if (ret == 0) {
  8320. if (GetOctetString(cert, &extIdx, &extLen, certSz) < 0)
  8321. ret = ASN_PARSE_E;
  8322. }
  8323. if (ret == 0) {
  8324. switch (oid) {
  8325. case AUTH_KEY_OID:
  8326. if (GetSequence(cert, &extIdx, &extLen, certSz) < 0)
  8327. ret = ASN_PARSE_E;
  8328. if (ret == 0 && (extIdx + 1) >= certSz)
  8329. ret = BUFFER_E;
  8330. if (ret == 0 &&
  8331. GetASNTag(cert, &extIdx, &tag, certSz) == 0 &&
  8332. tag == (ASN_CONTEXT_SPECIFIC | 0)) {
  8333. if (GetLength(cert, &extIdx, &extLen, certSz) <= 0)
  8334. ret = ASN_PARSE_E;
  8335. if (ret == 0) {
  8336. extAuthKeyIdSet = 1;
  8337. if (extLen == KEYID_SIZE)
  8338. XMEMCPY(hash, cert + extIdx, extLen);
  8339. else {
  8340. ret = CalcHashId(cert + extIdx, extLen,
  8341. hash);
  8342. }
  8343. }
  8344. }
  8345. break;
  8346. default:
  8347. break;
  8348. }
  8349. }
  8350. idx += len;
  8351. }
  8352. }
  8353. }
  8354. }
  8355. else if (ret == 0) {
  8356. idx += len;
  8357. }
  8358. if (ret == 0 && pubKey == NULL) {
  8359. if (extAuthKeyIdSet)
  8360. ca = GetCA(cm, hash);
  8361. if (ca == NULL) {
  8362. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  8363. if (ret == 0)
  8364. ca = GetCAByName(cm, hash);
  8365. }
  8366. }
  8367. #else
  8368. if (ret == 0 && pubKey == NULL) {
  8369. ret = CalcHashId(cert + issuerIdx, issuerSz, hash);
  8370. if (ret == 0)
  8371. ca = GetCA(cm, hash);
  8372. }
  8373. #endif /* !NO_SKID */
  8374. if (ca == NULL && pubKey == NULL)
  8375. ret = ASN_NO_SIGNER_E;
  8376. if (ret == 0) {
  8377. idx = sigIndex;
  8378. /* signatureAlgorithm */
  8379. if (GetAlgoId(cert, &idx, &oid, oidSigType, certSz) < 0)
  8380. ret = ASN_PARSE_E;
  8381. /* In CSR signature data is not present in body */
  8382. if (req)
  8383. signatureOID = oid;
  8384. }
  8385. if (ret == 0) {
  8386. if (oid != signatureOID)
  8387. ret = ASN_SIG_OID_E;
  8388. }
  8389. if (ret == 0) {
  8390. /* signatureValue */
  8391. if (CheckBitString(cert, &idx, &len, certSz, 1, NULL) < 0)
  8392. ret = ASN_PARSE_E;
  8393. }
  8394. if (ret == 0) {
  8395. if (pubKey != NULL) {
  8396. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  8397. sigIndex - tbsCertIdx,
  8398. pubKey, pubKeySz, pubKeyOID,
  8399. cert + idx, len, signatureOID, NULL);
  8400. }
  8401. else {
  8402. ret = ConfirmSignature(sigCtx, cert + tbsCertIdx,
  8403. sigIndex - tbsCertIdx,
  8404. ca->publicKey, ca->pubKeySize, ca->keyOID,
  8405. cert + idx, len, signatureOID, NULL);
  8406. }
  8407. if (ret != 0) {
  8408. WOLFSSL_MSG("Confirm signature failed");
  8409. }
  8410. }
  8411. FreeSignatureCtx(sigCtx);
  8412. #ifdef WOLFSSL_SMALL_STACK
  8413. if (sigCtx != NULL)
  8414. XFREE(sigCtx, heap, DYNAMIC_TYPE_SIGNATURE);
  8415. #endif
  8416. return ret;
  8417. }
  8418. #ifdef OPENSSL_EXTRA
  8419. /* Call CheckCertSignature_ex using a public key buffer for verification
  8420. */
  8421. int CheckCertSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  8422. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  8423. {
  8424. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  8425. pubKey, pubKeySz, pubKeyOID, 0);
  8426. }
  8427. #ifdef WOLFSSL_CERT_REQ
  8428. int CheckCSRSignaturePubKey(const byte* cert, word32 certSz, void* heap,
  8429. const byte* pubKey, word32 pubKeySz, int pubKeyOID)
  8430. {
  8431. return CheckCertSignature_ex(cert, certSz, heap, NULL,
  8432. pubKey, pubKeySz, pubKeyOID, 1);
  8433. }
  8434. #endif /* WOLFSSL_CERT_REQ */
  8435. #endif /* OPENSSL_EXTRA */
  8436. #ifdef WOLFSSL_SMALL_CERT_VERIFY
  8437. /* Call CheckCertSignature_ex using a certificate manager (cm)
  8438. */
  8439. int CheckCertSignature(const byte* cert, word32 certSz, void* heap, void* cm)
  8440. {
  8441. return CheckCertSignature_ex(cert, certSz, heap, cm, NULL, 0, 0, 0);
  8442. }
  8443. #endif /* WOLFSSL_SMALL_CERT_VERIFY */
  8444. #endif /* WOLFSSL_SMALL_CERT_VERIFY || OPENSSL_EXTRA */
  8445. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  8446. {
  8447. int ret = 0;
  8448. int checkPathLen = 0;
  8449. int decrementMaxPathLen = 0;
  8450. word32 confirmOID = 0;
  8451. #if defined(WOLFSSL_RENESAS_TSIP)
  8452. int idx = 0;
  8453. #endif
  8454. byte* tsip_encRsaKeyIdx;
  8455. #ifdef WOLFSSL_CERT_REQ
  8456. int len = 0;
  8457. #endif
  8458. if (cert == NULL) {
  8459. return BAD_FUNC_ARG;
  8460. }
  8461. #ifdef WOLFSSL_CERT_REQ
  8462. if (type == CERTREQ_TYPE)
  8463. cert->isCSR = 1;
  8464. #endif
  8465. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  8466. cert->badDate = 0;
  8467. cert->criticalExt = 0;
  8468. if ((ret = DecodeToKey(cert, verify)) < 0) {
  8469. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  8470. cert->badDate = ret;
  8471. else
  8472. return ret;
  8473. }
  8474. WOLFSSL_MSG("Parsed Past Key");
  8475. #ifdef WOLFSSL_CERT_REQ
  8476. /* Read attributes */
  8477. if (cert->isCSR) {
  8478. if (GetASNHeader_ex(cert->source,
  8479. ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED, &cert->srcIdx,
  8480. &len, cert->maxIdx, 1) < 0) {
  8481. WOLFSSL_MSG("GetASNHeader_ex error");
  8482. return ASN_PARSE_E;
  8483. }
  8484. if (len) {
  8485. word32 attrMaxIdx = cert->srcIdx + len;
  8486. word32 oid;
  8487. byte tag;
  8488. if (attrMaxIdx > cert->maxIdx) {
  8489. WOLFSSL_MSG("Attribute length greater than CSR length");
  8490. return ASN_PARSE_E;
  8491. }
  8492. while (cert->srcIdx < attrMaxIdx) {
  8493. /* Attributes have the structure:
  8494. * SEQ -> OID -> SET -> ATTRIBUTE */
  8495. if (GetSequence(cert->source, &cert->srcIdx, &len,
  8496. attrMaxIdx) < 0) {
  8497. WOLFSSL_MSG("attr GetSequence error");
  8498. return ASN_PARSE_E;
  8499. }
  8500. if (GetObjectId(cert->source, &cert->srcIdx, &oid,
  8501. oidCsrAttrType, attrMaxIdx) < 0) {
  8502. WOLFSSL_MSG("attr GetObjectId error");
  8503. return ASN_PARSE_E;
  8504. }
  8505. if (GetSet(cert->source, &cert->srcIdx, &len,
  8506. attrMaxIdx) < 0) {
  8507. WOLFSSL_MSG("attr GetSet error");
  8508. return ASN_PARSE_E;
  8509. }
  8510. switch (oid) {
  8511. case CHALLENGE_PASSWORD_OID:
  8512. if (GetHeader(cert->source, &tag,
  8513. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  8514. WOLFSSL_MSG("attr GetHeader error");
  8515. return ASN_PARSE_E;
  8516. }
  8517. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  8518. tag != ASN_IA5_STRING) {
  8519. WOLFSSL_MSG("Unsupported attribute value format");
  8520. return ASN_PARSE_E;
  8521. }
  8522. cert->cPwd = (char*)cert->source + cert->srcIdx;
  8523. cert->cPwdLen = len;
  8524. cert->srcIdx += len;
  8525. break;
  8526. case SERIAL_NUMBER_OID:
  8527. if (GetHeader(cert->source, &tag,
  8528. &cert->srcIdx, &len, attrMaxIdx, 1) < 0) {
  8529. WOLFSSL_MSG("attr GetHeader error");
  8530. return ASN_PARSE_E;
  8531. }
  8532. if (tag != ASN_PRINTABLE_STRING && tag != ASN_UTF8STRING &&
  8533. tag != ASN_IA5_STRING) {
  8534. WOLFSSL_MSG("Unsupported attribute value format");
  8535. return ASN_PARSE_E;
  8536. }
  8537. cert->sNum = (char*)cert->source + cert->srcIdx;
  8538. cert->sNumLen = len;
  8539. cert->srcIdx += len;
  8540. if (cert->sNumLen <= EXTERNAL_SERIAL_SIZE) {
  8541. XMEMCPY(cert->serial, cert->sNum, cert->sNumLen);
  8542. cert->serialSz = cert->sNumLen;
  8543. }
  8544. break;
  8545. case EXTENSION_REQUEST_OID:
  8546. /* save extensions */
  8547. cert->extensions = &cert->source[cert->srcIdx];
  8548. cert->extensionsSz = len;
  8549. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  8550. if ((ret = DecodeCertExtensions(cert)) < 0) {
  8551. if (ret == ASN_CRIT_EXT_E)
  8552. cert->criticalExt = ret;
  8553. else
  8554. return ret;
  8555. }
  8556. cert->srcIdx += len;
  8557. break;
  8558. default:
  8559. WOLFSSL_MSG("Unsupported attribute type");
  8560. return ASN_PARSE_E;
  8561. }
  8562. }
  8563. }
  8564. }
  8565. #endif
  8566. if (cert->srcIdx < cert->sigIndex) {
  8567. #ifndef ALLOW_V1_EXTENSIONS
  8568. if (cert->version < 2) {
  8569. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  8570. return ASN_VERSION_E;
  8571. }
  8572. #endif
  8573. /* save extensions */
  8574. cert->extensions = &cert->source[cert->srcIdx];
  8575. cert->extensionsSz = cert->sigIndex - cert->srcIdx;
  8576. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  8577. if ((ret = DecodeCertExtensions(cert)) < 0) {
  8578. if (ret == ASN_CRIT_EXT_E)
  8579. cert->criticalExt = ret;
  8580. else
  8581. return ret;
  8582. }
  8583. #ifdef HAVE_OCSP
  8584. /* trust for the lifetime of the responder's cert*/
  8585. if (cert->ocspNoCheckSet && verify == VERIFY_OCSP)
  8586. verify = NO_VERIFY;
  8587. #endif
  8588. /* advance past extensions */
  8589. cert->srcIdx = cert->sigIndex;
  8590. }
  8591. if ((ret = GetAlgoId(cert->source, &cert->srcIdx,
  8592. #ifdef WOLFSSL_CERT_REQ
  8593. !cert->isCSR ? &confirmOID : &cert->signatureOID,
  8594. #else
  8595. &confirmOID,
  8596. #endif
  8597. oidSigType, cert->maxIdx)) < 0)
  8598. return ret;
  8599. if ((ret = GetSignature(cert)) < 0)
  8600. return ret;
  8601. if (confirmOID != cert->signatureOID
  8602. #ifdef WOLFSSL_CERT_REQ
  8603. && !cert->isCSR
  8604. #endif
  8605. )
  8606. return ASN_SIG_OID_E;
  8607. #ifndef NO_SKID
  8608. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  8609. cert->pubKeySize > 0) {
  8610. ret = CalcHashId(cert->publicKey, cert->pubKeySize,
  8611. cert->extSubjKeyId);
  8612. if (ret != 0)
  8613. return ret;
  8614. }
  8615. #endif /* !NO_SKID */
  8616. if (!cert->selfSigned || (verify != NO_VERIFY && type != CA_TYPE &&
  8617. type != TRUSTED_PEER_TYPE)) {
  8618. cert->ca = NULL;
  8619. #ifndef NO_SKID
  8620. if (cert->extAuthKeyIdSet) {
  8621. cert->ca = GetCA(cm, cert->extAuthKeyId);
  8622. }
  8623. if (cert->ca == NULL && cert->extSubjKeyIdSet
  8624. && verify != VERIFY_OCSP) {
  8625. cert->ca = GetCA(cm, cert->extSubjKeyId);
  8626. }
  8627. if (cert->ca != NULL && XMEMCMP(cert->issuerHash,
  8628. cert->ca->subjectNameHash, KEYID_SIZE) != 0) {
  8629. cert->ca = NULL;
  8630. }
  8631. if (cert->ca == NULL) {
  8632. cert->ca = GetCAByName(cm, cert->issuerHash);
  8633. /* If AKID is available then this CA doesn't have the public
  8634. * key required */
  8635. if (cert->ca && cert->extAuthKeyIdSet) {
  8636. WOLFSSL_MSG("CA SKID doesn't match AKID");
  8637. cert->ca = NULL;
  8638. }
  8639. }
  8640. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  8641. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  8642. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  8643. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  8644. if (cert->ca) {
  8645. ret = 0; /* success */
  8646. goto exit_pcr;
  8647. }
  8648. }
  8649. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  8650. #else
  8651. cert->ca = GetCA(cm, cert->issuerHash);
  8652. #endif /* !NO_SKID */
  8653. if (cert->ca) {
  8654. WOLFSSL_MSG("CA found");
  8655. }
  8656. }
  8657. if (cert->selfSigned) {
  8658. cert->maxPathLen = WOLFSSL_MAX_PATH_LEN;
  8659. } else {
  8660. /* RFC 5280 Section 4.2.1.9:
  8661. *
  8662. * load/receive check
  8663. *
  8664. * 1) Is CA boolean set?
  8665. * No - SKIP CHECK
  8666. * Yes - Check key usage
  8667. * 2) Is Key usage extension present?
  8668. * No - goto 3
  8669. * Yes - check keyCertSign assertion
  8670. * 2.a) Is keyCertSign asserted?
  8671. * No - goto 4
  8672. * Yes - goto 3
  8673. * 3) Is pathLen set?
  8674. * No - goto 4
  8675. * Yes - check pathLen against maxPathLen.
  8676. * 3.a) Is pathLen less than maxPathLen?
  8677. * No - goto 4
  8678. * Yes - set maxPathLen to pathLen and EXIT
  8679. * 4) Is maxPathLen > 0?
  8680. * Yes - Reduce by 1
  8681. * No - ERROR
  8682. */
  8683. if (cert->ca && cert->pathLengthSet) {
  8684. cert->maxPathLen = cert->pathLength;
  8685. if (cert->isCA) {
  8686. WOLFSSL_MSG("\tCA boolean set");
  8687. if (cert->extKeyUsageSet) {
  8688. WOLFSSL_MSG("\tExtension Key Usage Set");
  8689. if ((cert->extKeyUsage & KEYUSE_KEY_CERT_SIGN) != 0) {
  8690. checkPathLen = 1;
  8691. } else {
  8692. decrementMaxPathLen = 1;
  8693. }
  8694. } else {
  8695. checkPathLen = 1;
  8696. } /* !cert->ca check */
  8697. } /* cert is not a CA (assuming entity cert) */
  8698. if (checkPathLen && cert->pathLengthSet) {
  8699. if (cert->pathLength < cert->ca->maxPathLen) {
  8700. WOLFSSL_MSG("\tmaxPathLen status: set to pathLength");
  8701. cert->maxPathLen = cert->pathLength;
  8702. } else {
  8703. decrementMaxPathLen = 1;
  8704. }
  8705. }
  8706. if (decrementMaxPathLen && cert->ca->maxPathLen > 0) {
  8707. WOLFSSL_MSG("\tmaxPathLen status: reduce by 1");
  8708. cert->maxPathLen = cert->ca->maxPathLen - 1;
  8709. if (verify != NO_VERIFY && type != CA_TYPE &&
  8710. type != TRUSTED_PEER_TYPE) {
  8711. WOLFSSL_MSG("\tmaxPathLen status: OK");
  8712. }
  8713. } else if (decrementMaxPathLen && cert->ca->maxPathLen == 0) {
  8714. cert->maxPathLen = 0;
  8715. if (verify != NO_VERIFY && type != CA_TYPE &&
  8716. type != TRUSTED_PEER_TYPE) {
  8717. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  8718. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  8719. return ASN_PATHLEN_INV_E;
  8720. }
  8721. }
  8722. } else if (cert->ca && cert->isCA) {
  8723. /* case where cert->pathLength extension is not set */
  8724. if (cert->ca->maxPathLen > 0) {
  8725. cert->maxPathLen = cert->ca->maxPathLen - 1;
  8726. } else {
  8727. cert->maxPathLen = 0;
  8728. if (verify != NO_VERIFY && type != CA_TYPE &&
  8729. type != TRUSTED_PEER_TYPE) {
  8730. WOLFSSL_MSG("\tNon-entity cert, maxPathLen is 0");
  8731. WOLFSSL_MSG("\tmaxPathLen status: ERROR");
  8732. return ASN_PATHLEN_INV_E;
  8733. }
  8734. }
  8735. }
  8736. }
  8737. #ifdef HAVE_OCSP
  8738. if (verify != NO_VERIFY && type != CA_TYPE &&
  8739. type != TRUSTED_PEER_TYPE) {
  8740. if (cert->ca) {
  8741. /* Need the CA's public key hash for OCSP */
  8742. XMEMCPY(cert->issuerKeyHash, cert->ca->subjectKeyHash,
  8743. KEYID_SIZE);
  8744. }
  8745. }
  8746. #endif /* HAVE_OCSP */
  8747. }
  8748. #if defined(WOLFSSL_RENESAS_TSIP)
  8749. /* prepare for TSIP TLS cert verification API use */
  8750. if (cert->keyOID == RSAk) {
  8751. /* to call TSIP API, it needs keys position info in bytes */
  8752. if ((ret = RsaPublicKeyDecodeRawIndex(cert->publicKey, (word32*)&idx,
  8753. cert->pubKeySize,
  8754. &cert->sigCtx.pubkey_n_start,
  8755. &cert->sigCtx.pubkey_n_len,
  8756. &cert->sigCtx.pubkey_e_start,
  8757. &cert->sigCtx.pubkey_e_len)) != 0) {
  8758. WOLFSSL_MSG("Decoding index from cert failed.");
  8759. return ret;
  8760. }
  8761. cert->sigCtx.certBegin = cert->certBegin;
  8762. }
  8763. /* check if we can use TSIP for cert verification */
  8764. /* if the ca is verified as tsip root ca. */
  8765. /* TSIP can only handle 2048 bits(256 byte) key. */
  8766. if (cert->ca && tsip_checkCA(cert->ca->cm_idx) != 0 &&
  8767. cert->sigCtx.pubkey_n_len == 256) {
  8768. /* assign memory to encrypted tsip Rsa key index */
  8769. if (!cert->tsip_encRsaKeyIdx)
  8770. cert->tsip_encRsaKeyIdx =
  8771. (byte*)XMALLOC(TSIP_TLS_ENCPUBKEY_SZ_BY_CERTVRFY,
  8772. cert->heap, DYNAMIC_TYPE_RSA);
  8773. if (cert->tsip_encRsaKeyIdx == NULL)
  8774. return MEMORY_E;
  8775. } else {
  8776. if (cert->ca) {
  8777. /* TSIP isn't usable */
  8778. if (tsip_checkCA(cert->ca->cm_idx) == 0)
  8779. WOLFSSL_MSG("TSIP isn't usable because the ca isn't verified "
  8780. "by TSIP.");
  8781. else if (cert->sigCtx.pubkey_n_len != 256)
  8782. WOLFSSL_MSG("TSIP isn't usable because the ca isn't signed by "
  8783. "RSA 2048.");
  8784. else
  8785. WOLFSSL_MSG("TSIP isn't usable");
  8786. }
  8787. cert->tsip_encRsaKeyIdx = NULL;
  8788. }
  8789. tsip_encRsaKeyIdx = cert->tsip_encRsaKeyIdx;
  8790. #else
  8791. tsip_encRsaKeyIdx = NULL;
  8792. #endif
  8793. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  8794. if (cert->ca) {
  8795. if (verify == VERIFY || verify == VERIFY_OCSP ||
  8796. verify == VERIFY_SKIP_DATE) {
  8797. /* try to confirm/verify signature */
  8798. if ((ret = ConfirmSignature(&cert->sigCtx,
  8799. cert->source + cert->certBegin,
  8800. cert->sigIndex - cert->certBegin,
  8801. cert->ca->publicKey, cert->ca->pubKeySize,
  8802. cert->ca->keyOID, cert->signature,
  8803. cert->sigLength, cert->signatureOID,
  8804. tsip_encRsaKeyIdx)) != 0) {
  8805. if (ret != WC_PENDING_E) {
  8806. WOLFSSL_MSG("Confirm signature failed");
  8807. }
  8808. return ret;
  8809. }
  8810. }
  8811. #ifndef IGNORE_NAME_CONSTRAINTS
  8812. if (verify == VERIFY || verify == VERIFY_OCSP ||
  8813. verify == VERIFY_NAME || verify == VERIFY_SKIP_DATE) {
  8814. /* check that this cert's name is permitted by the signer's
  8815. * name constraints */
  8816. if (!ConfirmNameConstraints(cert->ca, cert)) {
  8817. WOLFSSL_MSG("Confirm name constraint failed");
  8818. return ASN_NAME_INVALID_E;
  8819. }
  8820. }
  8821. #endif /* IGNORE_NAME_CONSTRAINTS */
  8822. }
  8823. else {
  8824. /* no signer */
  8825. WOLFSSL_MSG("No CA signer to verify with");
  8826. return ASN_NO_SIGNER_E;
  8827. }
  8828. }
  8829. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  8830. exit_pcr:
  8831. #endif
  8832. if (cert->badDate != 0) {
  8833. if (verify != VERIFY_SKIP_DATE) {
  8834. return cert->badDate;
  8835. }
  8836. WOLFSSL_MSG("Date error: Verify option is skipping");
  8837. }
  8838. if (cert->criticalExt != 0)
  8839. return cert->criticalExt;
  8840. return ret;
  8841. }
  8842. /* Create and init an new signer */
  8843. Signer* MakeSigner(void* heap)
  8844. {
  8845. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  8846. DYNAMIC_TYPE_SIGNER);
  8847. if (signer) {
  8848. XMEMSET(signer, 0, sizeof(Signer));
  8849. }
  8850. (void)heap;
  8851. return signer;
  8852. }
  8853. /* Free an individual signer */
  8854. void FreeSigner(Signer* signer, void* heap)
  8855. {
  8856. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  8857. XFREE((void*)signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  8858. #ifndef IGNORE_NAME_CONSTRAINTS
  8859. if (signer->permittedNames)
  8860. FreeNameSubtrees(signer->permittedNames, heap);
  8861. if (signer->excludedNames)
  8862. FreeNameSubtrees(signer->excludedNames, heap);
  8863. #endif
  8864. #ifdef WOLFSSL_SIGNER_DER_CERT
  8865. FreeDer(&signer->derCert);
  8866. #endif
  8867. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  8868. (void)heap;
  8869. }
  8870. /* Free the whole singer table with number of rows */
  8871. void FreeSignerTable(Signer** table, int rows, void* heap)
  8872. {
  8873. int i;
  8874. for (i = 0; i < rows; i++) {
  8875. Signer* signer = table[i];
  8876. while (signer) {
  8877. Signer* next = signer->next;
  8878. FreeSigner(signer, heap);
  8879. signer = next;
  8880. }
  8881. table[i] = NULL;
  8882. }
  8883. }
  8884. #ifdef WOLFSSL_TRUST_PEER_CERT
  8885. /* Free an individual trusted peer cert */
  8886. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  8887. {
  8888. if (tp == NULL) {
  8889. return;
  8890. }
  8891. if (tp->name) {
  8892. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  8893. }
  8894. if (tp->sig) {
  8895. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  8896. }
  8897. #ifndef IGNORE_NAME_CONSTRAINTS
  8898. if (tp->permittedNames)
  8899. FreeNameSubtrees(tp->permittedNames, heap);
  8900. if (tp->excludedNames)
  8901. FreeNameSubtrees(tp->excludedNames, heap);
  8902. #endif
  8903. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  8904. (void)heap;
  8905. }
  8906. /* Free the whole Trusted Peer linked list */
  8907. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  8908. {
  8909. int i;
  8910. for (i = 0; i < rows; i++) {
  8911. TrustedPeerCert* tp = table[i];
  8912. while (tp) {
  8913. TrustedPeerCert* next = tp->next;
  8914. FreeTrustedPeer(tp, heap);
  8915. tp = next;
  8916. }
  8917. table[i] = NULL;
  8918. }
  8919. }
  8920. #endif /* WOLFSSL_TRUST_PEER_CERT */
  8921. int SetMyVersion(word32 version, byte* output, int header)
  8922. {
  8923. int i = 0;
  8924. if (output == NULL)
  8925. return BAD_FUNC_ARG;
  8926. if (header) {
  8927. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  8928. output[i++] = 3;
  8929. }
  8930. output[i++] = ASN_INTEGER;
  8931. output[i++] = 0x01;
  8932. output[i++] = (byte)version;
  8933. return i;
  8934. }
  8935. int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  8936. word32 outputSz, int maxSnSz)
  8937. {
  8938. int i;
  8939. int snSzInt = (int)snSz;
  8940. if (sn == NULL || output == NULL || snSzInt < 0)
  8941. return BAD_FUNC_ARG;
  8942. /* remove leading zeros */
  8943. while (snSzInt > 0 && sn[0] == 0) {
  8944. snSzInt--;
  8945. sn++;
  8946. }
  8947. /* RFC 5280 - 4.1.2.2:
  8948. * Serial numbers must be a positive value (and not zero) */
  8949. if (snSzInt == 0)
  8950. return BAD_FUNC_ARG;
  8951. if (sn[0] & 0x80)
  8952. maxSnSz--;
  8953. /* truncate if input is too long */
  8954. if (snSzInt > maxSnSz)
  8955. snSzInt = maxSnSz;
  8956. i = SetASNInt(snSzInt, sn[0], NULL);
  8957. /* truncate if input is too long */
  8958. if (snSzInt > (int)outputSz - i)
  8959. snSzInt = (int)outputSz - i;
  8960. /* sanity check number of bytes to copy */
  8961. if (snSzInt <= 0) {
  8962. return BUFFER_E;
  8963. }
  8964. /* write out ASN.1 Integer */
  8965. (void)SetASNInt(snSzInt, sn[0], output);
  8966. XMEMCPY(output + i, sn, snSzInt);
  8967. /* compute final length */
  8968. i += snSzInt;
  8969. return i;
  8970. }
  8971. #endif /* !NO_CERTS */
  8972. int GetSerialNumber(const byte* input, word32* inOutIdx,
  8973. byte* serial, int* serialSz, word32 maxIdx)
  8974. {
  8975. int result = 0;
  8976. int ret;
  8977. WOLFSSL_ENTER("GetSerialNumber");
  8978. if (serial == NULL || input == NULL || serialSz == NULL) {
  8979. return BAD_FUNC_ARG;
  8980. }
  8981. /* First byte is ASN type */
  8982. if ((*inOutIdx+1) > maxIdx) {
  8983. WOLFSSL_MSG("Bad idx first");
  8984. return BUFFER_E;
  8985. }
  8986. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  8987. if (ret != 0)
  8988. return ret;
  8989. if (*serialSz > EXTERNAL_SERIAL_SIZE) {
  8990. WOLFSSL_MSG("Serial size bad");
  8991. return ASN_PARSE_E;
  8992. }
  8993. /* return serial */
  8994. XMEMCPY(serial, &input[*inOutIdx], *serialSz);
  8995. *inOutIdx += *serialSz;
  8996. return result;
  8997. }
  8998. #ifndef NO_CERTS
  8999. int AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  9000. {
  9001. int ret = BAD_FUNC_ARG;
  9002. if (pDer) {
  9003. int dynType = 0;
  9004. DerBuffer* der;
  9005. /* Determine dynamic type */
  9006. switch (type) {
  9007. case CA_TYPE: dynType = DYNAMIC_TYPE_CA; break;
  9008. case CERT_TYPE: dynType = DYNAMIC_TYPE_CERT; break;
  9009. case CRL_TYPE: dynType = DYNAMIC_TYPE_CRL; break;
  9010. case DSA_TYPE: dynType = DYNAMIC_TYPE_DSA; break;
  9011. case ECC_TYPE: dynType = DYNAMIC_TYPE_ECC; break;
  9012. case RSA_TYPE: dynType = DYNAMIC_TYPE_RSA; break;
  9013. default: dynType = DYNAMIC_TYPE_KEY; break;
  9014. }
  9015. /* Setup new buffer */
  9016. *pDer = (DerBuffer*)XMALLOC(sizeof(DerBuffer) + length, heap, dynType);
  9017. if (*pDer == NULL) {
  9018. return MEMORY_E;
  9019. }
  9020. XMEMSET(*pDer, 0, sizeof(DerBuffer) + length);
  9021. der = *pDer;
  9022. der->type = type;
  9023. der->dynType = dynType; /* Cache this for FreeDer */
  9024. der->heap = heap;
  9025. der->buffer = (byte*)der + sizeof(DerBuffer);
  9026. der->length = length;
  9027. ret = 0; /* Success */
  9028. }
  9029. return ret;
  9030. }
  9031. void FreeDer(DerBuffer** pDer)
  9032. {
  9033. if (pDer && *pDer)
  9034. {
  9035. DerBuffer* der = (DerBuffer*)*pDer;
  9036. /* ForceZero private keys */
  9037. if (der->type == PRIVATEKEY_TYPE) {
  9038. ForceZero(der->buffer, der->length);
  9039. }
  9040. der->buffer = NULL;
  9041. der->length = 0;
  9042. XFREE(der, der->heap, der->dynType);
  9043. *pDer = NULL;
  9044. }
  9045. }
  9046. int wc_AllocDer(DerBuffer** pDer, word32 length, int type, void* heap)
  9047. {
  9048. return AllocDer(pDer, length, type, heap);
  9049. }
  9050. void wc_FreeDer(DerBuffer** pDer)
  9051. {
  9052. FreeDer(pDer);
  9053. }
  9054. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  9055. /* Note: If items added make sure MAX_X509_HEADER_SZ is
  9056. updated to reflect maximum length and pem_struct_min_sz
  9057. to reflect minimum size */
  9058. wcchar BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  9059. wcchar END_CERT = "-----END CERTIFICATE-----";
  9060. #ifdef WOLFSSL_CERT_REQ
  9061. wcchar BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  9062. wcchar END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  9063. #endif
  9064. #ifndef NO_DH
  9065. wcchar BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  9066. wcchar END_DH_PARAM = "-----END DH PARAMETERS-----";
  9067. #endif
  9068. #ifndef NO_DSA
  9069. wcchar BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  9070. wcchar END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  9071. #endif
  9072. wcchar BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  9073. wcchar END_X509_CRL = "-----END X509 CRL-----";
  9074. wcchar BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  9075. wcchar END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  9076. wcchar BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  9077. wcchar END_PRIV_KEY = "-----END PRIVATE KEY-----";
  9078. wcchar BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  9079. wcchar END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  9080. #ifdef HAVE_ECC
  9081. wcchar BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  9082. wcchar END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  9083. #endif
  9084. #if defined(HAVE_ECC) || defined(HAVE_ED25519) || defined(HAVE_ED448) || \
  9085. !defined(NO_DSA)
  9086. wcchar BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  9087. wcchar END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  9088. #endif
  9089. #ifdef OPENSSL_EXTRA
  9090. const char BEGIN_PRIV_KEY_PREFIX[] = "-----BEGIN";
  9091. const char PRIV_KEY_SUFFIX[] = "PRIVATE KEY-----";
  9092. const char END_PRIV_KEY_PREFIX[] = "-----END";
  9093. #endif
  9094. wcchar BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  9095. wcchar END_PUB_KEY = "-----END PUBLIC KEY-----";
  9096. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  9097. wcchar BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  9098. wcchar END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  9099. #endif
  9100. const int pem_struct_min_sz = XSTR_SIZEOF("-----BEGIN X509 CRL-----"
  9101. "-----END X509 CRL-----");
  9102. static WC_INLINE const char* SkipEndOfLineChars(const char* line,
  9103. const char* endOfLine)
  9104. {
  9105. /* eat end of line characters */
  9106. while (line < endOfLine &&
  9107. (line[0] == '\r' || line[0] == '\n')) {
  9108. line++;
  9109. }
  9110. return line;
  9111. }
  9112. int wc_PemGetHeaderFooter(int type, const char** header, const char** footer)
  9113. {
  9114. int ret = BAD_FUNC_ARG;
  9115. switch (type) {
  9116. case CA_TYPE: /* same as below */
  9117. case TRUSTED_PEER_TYPE:
  9118. case CERT_TYPE:
  9119. if (header) *header = BEGIN_CERT;
  9120. if (footer) *footer = END_CERT;
  9121. ret = 0;
  9122. break;
  9123. case CRL_TYPE:
  9124. if (header) *header = BEGIN_X509_CRL;
  9125. if (footer) *footer = END_X509_CRL;
  9126. ret = 0;
  9127. break;
  9128. #ifndef NO_DH
  9129. case DH_PARAM_TYPE:
  9130. if (header) *header = BEGIN_DH_PARAM;
  9131. if (footer) *footer = END_DH_PARAM;
  9132. ret = 0;
  9133. break;
  9134. #endif
  9135. #ifndef NO_DSA
  9136. case DSA_PARAM_TYPE:
  9137. if (header) *header = BEGIN_DSA_PARAM;
  9138. if (footer) *footer = END_DSA_PARAM;
  9139. ret = 0;
  9140. break;
  9141. #endif
  9142. #ifdef WOLFSSL_CERT_REQ
  9143. case CERTREQ_TYPE:
  9144. if (header) *header = BEGIN_CERT_REQ;
  9145. if (footer) *footer = END_CERT_REQ;
  9146. ret = 0;
  9147. break;
  9148. #endif
  9149. #ifndef NO_DSA
  9150. case DSA_TYPE:
  9151. case DSA_PRIVATEKEY_TYPE:
  9152. if (header) *header = BEGIN_DSA_PRIV;
  9153. if (footer) *footer = END_DSA_PRIV;
  9154. ret = 0;
  9155. break;
  9156. #endif
  9157. #ifdef HAVE_ECC
  9158. case ECC_TYPE:
  9159. case ECC_PRIVATEKEY_TYPE:
  9160. if (header) *header = BEGIN_EC_PRIV;
  9161. if (footer) *footer = END_EC_PRIV;
  9162. ret = 0;
  9163. break;
  9164. #endif
  9165. case RSA_TYPE:
  9166. case PRIVATEKEY_TYPE:
  9167. if (header) *header = BEGIN_RSA_PRIV;
  9168. if (footer) *footer = END_RSA_PRIV;
  9169. ret = 0;
  9170. break;
  9171. #ifdef HAVE_ED25519
  9172. case ED25519_TYPE:
  9173. #endif
  9174. #ifdef HAVE_ED448
  9175. case ED448_TYPE:
  9176. #endif
  9177. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  9178. case EDDSA_PRIVATEKEY_TYPE:
  9179. if (header) *header = BEGIN_EDDSA_PRIV;
  9180. if (footer) *footer = END_EDDSA_PRIV;
  9181. ret = 0;
  9182. break;
  9183. #endif
  9184. case PUBLICKEY_TYPE:
  9185. case ECC_PUBLICKEY_TYPE:
  9186. if (header) *header = BEGIN_PUB_KEY;
  9187. if (footer) *footer = END_PUB_KEY;
  9188. ret = 0;
  9189. break;
  9190. #ifndef NO_DH
  9191. case DH_PRIVATEKEY_TYPE:
  9192. #endif
  9193. case PKCS8_PRIVATEKEY_TYPE:
  9194. if (header) *header = BEGIN_PRIV_KEY;
  9195. if (footer) *footer = END_PRIV_KEY;
  9196. ret = 0;
  9197. break;
  9198. case PKCS8_ENC_PRIVATEKEY_TYPE:
  9199. if (header) *header = BEGIN_ENC_PRIV_KEY;
  9200. if (footer) *footer = END_ENC_PRIV_KEY;
  9201. ret = 0;
  9202. break;
  9203. default:
  9204. break;
  9205. }
  9206. return ret;
  9207. }
  9208. #ifdef WOLFSSL_ENCRYPTED_KEYS
  9209. static wcchar kProcTypeHeader = "Proc-Type";
  9210. static wcchar kDecInfoHeader = "DEK-Info";
  9211. #ifdef WOLFSSL_PEM_TO_DER
  9212. #ifndef NO_DES3
  9213. static wcchar kEncTypeDes = "DES-CBC";
  9214. static wcchar kEncTypeDes3 = "DES-EDE3-CBC";
  9215. #endif
  9216. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  9217. static wcchar kEncTypeAesCbc128 = "AES-128-CBC";
  9218. #endif
  9219. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  9220. static wcchar kEncTypeAesCbc192 = "AES-192-CBC";
  9221. #endif
  9222. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  9223. static wcchar kEncTypeAesCbc256 = "AES-256-CBC";
  9224. #endif
  9225. int wc_EncryptedInfoGet(EncryptedInfo* info, const char* cipherInfo)
  9226. {
  9227. int ret = 0;
  9228. if (info == NULL || cipherInfo == NULL)
  9229. return BAD_FUNC_ARG;
  9230. /* determine cipher information */
  9231. #ifndef NO_DES3
  9232. if (XSTRNCMP(cipherInfo, kEncTypeDes, XSTRLEN(kEncTypeDes)) == 0) {
  9233. info->cipherType = WC_CIPHER_DES;
  9234. info->keySz = DES_KEY_SIZE;
  9235. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  9236. }
  9237. else if (XSTRNCMP(cipherInfo, kEncTypeDes3, XSTRLEN(kEncTypeDes3)) == 0) {
  9238. info->cipherType = WC_CIPHER_DES3;
  9239. info->keySz = DES3_KEY_SIZE;
  9240. if (info->ivSz == 0) info->ivSz = DES_IV_SIZE;
  9241. }
  9242. else
  9243. #endif /* !NO_DES3 */
  9244. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_128)
  9245. if (XSTRNCMP(cipherInfo, kEncTypeAesCbc128, XSTRLEN(kEncTypeAesCbc128)) == 0) {
  9246. info->cipherType = WC_CIPHER_AES_CBC;
  9247. info->keySz = AES_128_KEY_SIZE;
  9248. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  9249. }
  9250. else
  9251. #endif
  9252. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_192)
  9253. if (XSTRNCMP(cipherInfo, kEncTypeAesCbc192, XSTRLEN(kEncTypeAesCbc192)) == 0) {
  9254. info->cipherType = WC_CIPHER_AES_CBC;
  9255. info->keySz = AES_192_KEY_SIZE;
  9256. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  9257. }
  9258. else
  9259. #endif
  9260. #if !defined(NO_AES) && defined(HAVE_AES_CBC) && defined(WOLFSSL_AES_256)
  9261. if (XSTRNCMP(cipherInfo, kEncTypeAesCbc256, XSTRLEN(kEncTypeAesCbc256)) == 0) {
  9262. info->cipherType = WC_CIPHER_AES_CBC;
  9263. info->keySz = AES_256_KEY_SIZE;
  9264. if (info->ivSz == 0) info->ivSz = AES_IV_SIZE;
  9265. }
  9266. else
  9267. #endif
  9268. {
  9269. ret = NOT_COMPILED_IN;
  9270. }
  9271. return ret;
  9272. }
  9273. int wc_EncryptedInfoParse(EncryptedInfo* info, const char** pBuffer,
  9274. size_t bufSz)
  9275. {
  9276. int err = 0;
  9277. const char* bufferStart;
  9278. const char* bufferEnd;
  9279. char* line;
  9280. word32 lineSz;
  9281. char* finish;
  9282. word32 finishSz;
  9283. char* start = NULL;
  9284. word32 startSz;
  9285. const char* newline = NULL;
  9286. if (info == NULL || pBuffer == NULL || bufSz == 0)
  9287. return BAD_FUNC_ARG;
  9288. bufferStart = *pBuffer;
  9289. bufferEnd = bufferStart + bufSz;
  9290. /* find encrypted info marker */
  9291. line = XSTRNSTR(bufferStart, kProcTypeHeader,
  9292. min((word32)bufSz, PEM_LINE_LEN));
  9293. if (line != NULL) {
  9294. if (line >= bufferEnd) {
  9295. return BUFFER_E;
  9296. }
  9297. lineSz = (word32)(bufferEnd - line);
  9298. /* find DEC-Info marker */
  9299. start = XSTRNSTR(line, kDecInfoHeader, min(lineSz, PEM_LINE_LEN));
  9300. if (start == NULL)
  9301. return BUFFER_E;
  9302. /* skip dec-info and ": " */
  9303. start += XSTRLEN(kDecInfoHeader);
  9304. if (start >= bufferEnd)
  9305. return BUFFER_E;
  9306. if (start[0] == ':') {
  9307. start++;
  9308. if (start >= bufferEnd)
  9309. return BUFFER_E;
  9310. }
  9311. if (start[0] == ' ')
  9312. start++;
  9313. startSz = (word32)(bufferEnd - start);
  9314. finish = XSTRNSTR(start, ",", min(startSz, PEM_LINE_LEN));
  9315. if ((start != NULL) && (finish != NULL) && (start < finish)) {
  9316. if (finish >= bufferEnd) {
  9317. return BUFFER_E;
  9318. }
  9319. finishSz = (word32)(bufferEnd - finish);
  9320. newline = XSTRNSTR(finish, "\r", min(finishSz, PEM_LINE_LEN));
  9321. /* get cipher name */
  9322. if (NAME_SZ < (finish - start)) /* buffer size of info->name */
  9323. return BUFFER_E;
  9324. if (XMEMCPY(info->name, start, finish - start) == NULL)
  9325. return BUFFER_E;
  9326. info->name[finish - start] = '\0'; /* null term */
  9327. /* populate info */
  9328. err = wc_EncryptedInfoGet(info, info->name);
  9329. if (err != 0)
  9330. return err;
  9331. /* get IV */
  9332. if (finishSz < info->ivSz + 1)
  9333. return BUFFER_E;
  9334. if (newline == NULL) {
  9335. newline = XSTRNSTR(finish, "\n", min(finishSz,
  9336. PEM_LINE_LEN));
  9337. }
  9338. if ((newline != NULL) && (newline > finish)) {
  9339. finish++;
  9340. info->ivSz = (word32)(newline - finish);
  9341. if (info->ivSz > IV_SZ)
  9342. return BUFFER_E;
  9343. if (XMEMCPY(info->iv, finish, info->ivSz) == NULL)
  9344. return BUFFER_E;
  9345. info->set = 1;
  9346. }
  9347. else
  9348. return BUFFER_E;
  9349. }
  9350. else
  9351. return BUFFER_E;
  9352. /* eat end of line characters */
  9353. newline = SkipEndOfLineChars(newline, bufferEnd);
  9354. /* return new headerEnd */
  9355. *pBuffer = newline;
  9356. }
  9357. return err;
  9358. }
  9359. #endif /* WOLFSSL_PEM_TO_DER */
  9360. #ifdef WOLFSSL_DER_TO_PEM
  9361. static int wc_EncryptedInfoAppend(char* dest, int destSz, char* cipherInfo)
  9362. {
  9363. if (cipherInfo != NULL) {
  9364. int cipherInfoStrLen = (int)XSTRLEN((char*)cipherInfo);
  9365. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3))
  9366. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (9+14+10+3);
  9367. if (destSz - (int)XSTRLEN(dest) >= cipherInfoStrLen + (9+14+8+2+2+1)) {
  9368. /* strncat's src length needs to include the NULL */
  9369. XSTRNCAT(dest, kProcTypeHeader, 10);
  9370. XSTRNCAT(dest, ": 4,ENCRYPTED\n", 15);
  9371. XSTRNCAT(dest, kDecInfoHeader, 9);
  9372. XSTRNCAT(dest, ": ", 3);
  9373. XSTRNCAT(dest, cipherInfo, destSz - (int)XSTRLEN(dest) - 1);
  9374. XSTRNCAT(dest, "\n\n", 4);
  9375. }
  9376. }
  9377. return 0;
  9378. }
  9379. #endif /* WOLFSSL_DER_TO_PEM */
  9380. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  9381. #ifdef WOLFSSL_DER_TO_PEM
  9382. /* Used for compatibility API */
  9383. int wc_DerToPem(const byte* der, word32 derSz,
  9384. byte* output, word32 outSz, int type)
  9385. {
  9386. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  9387. }
  9388. /* convert der buffer to pem into output, can't do inplace, der and output
  9389. need to be different */
  9390. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  9391. byte *cipher_info, int type)
  9392. {
  9393. const char* headerStr = NULL;
  9394. const char* footerStr = NULL;
  9395. #ifdef WOLFSSL_SMALL_STACK
  9396. char* header = NULL;
  9397. char* footer = NULL;
  9398. #else
  9399. char header[MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE];
  9400. char footer[MAX_X509_HEADER_SZ];
  9401. #endif
  9402. int headerLen = MAX_X509_HEADER_SZ + HEADER_ENCRYPTED_KEY_SIZE;
  9403. int footerLen = MAX_X509_HEADER_SZ;
  9404. int i;
  9405. int err;
  9406. int outLen; /* return length or error */
  9407. (void)cipher_info;
  9408. if (der == output) /* no in place conversion */
  9409. return BAD_FUNC_ARG;
  9410. err = wc_PemGetHeaderFooter(type, &headerStr, &footerStr);
  9411. if (err != 0)
  9412. return err;
  9413. #ifdef WOLFSSL_SMALL_STACK
  9414. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9415. if (header == NULL)
  9416. return MEMORY_E;
  9417. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9418. if (footer == NULL) {
  9419. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9420. return MEMORY_E;
  9421. }
  9422. #endif
  9423. /* build header and footer based on type */
  9424. XSTRNCPY(header, headerStr, headerLen - 1);
  9425. header[headerLen - 2] = 0;
  9426. XSTRNCPY(footer, footerStr, footerLen - 1);
  9427. footer[footerLen - 2] = 0;
  9428. /* add new line to end */
  9429. XSTRNCAT(header, "\n", 2);
  9430. XSTRNCAT(footer, "\n", 2);
  9431. #ifdef WOLFSSL_ENCRYPTED_KEYS
  9432. err = wc_EncryptedInfoAppend(header, headerLen, (char*)cipher_info);
  9433. if (err != 0) {
  9434. #ifdef WOLFSSL_SMALL_STACK
  9435. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9436. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9437. #endif
  9438. return err;
  9439. }
  9440. #endif
  9441. headerLen = (int)XSTRLEN(header);
  9442. footerLen = (int)XSTRLEN(footer);
  9443. /* if null output and 0 size passed in then return size needed */
  9444. if (!output && outSz == 0) {
  9445. #ifdef WOLFSSL_SMALL_STACK
  9446. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9447. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9448. #endif
  9449. outLen = 0;
  9450. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  9451. != LENGTH_ONLY_E) {
  9452. return err;
  9453. }
  9454. return headerLen + footerLen + outLen;
  9455. }
  9456. if (!der || !output) {
  9457. #ifdef WOLFSSL_SMALL_STACK
  9458. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9459. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9460. #endif
  9461. return BAD_FUNC_ARG;
  9462. }
  9463. /* don't even try if outSz too short */
  9464. if (outSz < headerLen + footerLen + derSz) {
  9465. #ifdef WOLFSSL_SMALL_STACK
  9466. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9467. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9468. #endif
  9469. return BAD_FUNC_ARG;
  9470. }
  9471. /* header */
  9472. XMEMCPY(output, header, headerLen);
  9473. i = headerLen;
  9474. #ifdef WOLFSSL_SMALL_STACK
  9475. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9476. #endif
  9477. /* body */
  9478. outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */
  9479. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  9480. #ifdef WOLFSSL_SMALL_STACK
  9481. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9482. #endif
  9483. return err;
  9484. }
  9485. i += outLen;
  9486. /* footer */
  9487. if ( (i + footerLen) > (int)outSz) {
  9488. #ifdef WOLFSSL_SMALL_STACK
  9489. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9490. #endif
  9491. return BAD_FUNC_ARG;
  9492. }
  9493. XMEMCPY(output + i, footer, footerLen);
  9494. #ifdef WOLFSSL_SMALL_STACK
  9495. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9496. #endif
  9497. return outLen + headerLen + footerLen;
  9498. }
  9499. #endif /* WOLFSSL_DER_TO_PEM */
  9500. #ifdef WOLFSSL_PEM_TO_DER
  9501. /* Remove PEM header/footer, convert to ASN1, store any encrypted data
  9502. info->consumed tracks of PEM bytes consumed in case multiple parts */
  9503. int PemToDer(const unsigned char* buff, long longSz, int type,
  9504. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* keyFormat)
  9505. {
  9506. const char* header = NULL;
  9507. const char* footer = NULL;
  9508. const char* headerEnd;
  9509. const char* footerEnd;
  9510. const char* consumedEnd;
  9511. const char* bufferEnd = (const char*)(buff + longSz);
  9512. long neededSz;
  9513. int ret = 0;
  9514. int sz = (int)longSz;
  9515. int encrypted_key = 0;
  9516. DerBuffer* der;
  9517. #if defined(HAVE_PKCS8) || defined(WOLFSSL_ENCRYPTED_KEYS)
  9518. word32 algId = 0;
  9519. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_DES3) && !defined(NO_WOLFSSL_SKIP_TRAILING_PAD)
  9520. int padVal = 0;
  9521. #endif
  9522. #endif
  9523. #ifdef OPENSSL_EXTRA
  9524. char beginBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  9525. char endBuf[PEM_LINE_LEN + 1]; /* add 1 for null terminator */
  9526. #endif
  9527. WOLFSSL_ENTER("PemToDer");
  9528. /* get PEM header and footer based on type */
  9529. ret = wc_PemGetHeaderFooter(type, &header, &footer);
  9530. if (ret != 0)
  9531. return ret;
  9532. /* map header if not found for type */
  9533. for (;;) {
  9534. headerEnd = XSTRNSTR((char*)buff, header, sz);
  9535. if (headerEnd) {
  9536. break;
  9537. } else
  9538. if (type == PRIVATEKEY_TYPE) {
  9539. if (header == BEGIN_RSA_PRIV) {
  9540. header = BEGIN_PRIV_KEY; footer = END_PRIV_KEY;
  9541. } else
  9542. if (header == BEGIN_PRIV_KEY) {
  9543. header = BEGIN_ENC_PRIV_KEY; footer = END_ENC_PRIV_KEY;
  9544. } else
  9545. #ifdef HAVE_ECC
  9546. if (header == BEGIN_ENC_PRIV_KEY) {
  9547. header = BEGIN_EC_PRIV; footer = END_EC_PRIV;
  9548. } else
  9549. if (header == BEGIN_EC_PRIV) {
  9550. header = BEGIN_DSA_PRIV; footer = END_DSA_PRIV;
  9551. } else
  9552. #endif
  9553. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  9554. #ifdef HAVE_ECC
  9555. if (header == BEGIN_DSA_PRIV)
  9556. #else
  9557. if (header == BEGIN_ENC_PRIV_KEY)
  9558. #endif
  9559. {
  9560. header = BEGIN_EDDSA_PRIV; footer = END_EDDSA_PRIV;
  9561. } else
  9562. #endif
  9563. {
  9564. break;
  9565. }
  9566. } else
  9567. #ifdef HAVE_CRL
  9568. if ((type == CRL_TYPE) && (header != BEGIN_X509_CRL)) {
  9569. header = BEGIN_X509_CRL; footer = END_X509_CRL;
  9570. } else
  9571. #endif
  9572. {
  9573. break;
  9574. }
  9575. }
  9576. if (!headerEnd) {
  9577. #ifdef OPENSSL_EXTRA
  9578. if (type == PRIVATEKEY_TYPE) {
  9579. const char* beginEnd;
  9580. int endLen;
  9581. /* see if there is a -----BEGIN * PRIVATE KEY----- header */
  9582. headerEnd = XSTRNSTR((char*)buff, PRIV_KEY_SUFFIX, sz);
  9583. if (headerEnd) {
  9584. beginEnd = headerEnd + XSTR_SIZEOF(PRIV_KEY_SUFFIX);
  9585. if (beginEnd >= (char*)buff + sz) {
  9586. return BUFFER_E;
  9587. }
  9588. /* back up to BEGIN_PRIV_KEY_PREFIX */
  9589. while (headerEnd > (char*)buff &&
  9590. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  9591. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 &&
  9592. *headerEnd != '\n') {
  9593. headerEnd--;
  9594. }
  9595. if (headerEnd <= (char*)buff ||
  9596. XSTRNCMP(headerEnd, BEGIN_PRIV_KEY_PREFIX,
  9597. XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX)) != 0 ||
  9598. beginEnd - headerEnd > PEM_LINE_LEN) {
  9599. WOLFSSL_MSG("Couldn't find PEM header");
  9600. return ASN_NO_PEM_HEADER;
  9601. }
  9602. /* headerEnd now points to beginning of header */
  9603. XMEMCPY(beginBuf, headerEnd, beginEnd - headerEnd);
  9604. beginBuf[beginEnd - headerEnd] = '\0';
  9605. /* look for matching footer */
  9606. footer = XSTRNSTR(beginEnd,
  9607. beginBuf + XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX),
  9608. (unsigned int)((char*)buff + sz - beginEnd));
  9609. if (!footer) {
  9610. WOLFSSL_MSG("Couldn't find PEM footer");
  9611. return ASN_NO_PEM_HEADER;
  9612. }
  9613. footer -= XSTR_SIZEOF(END_PRIV_KEY_PREFIX);
  9614. if (footer > (char*)buff + sz - XSTR_SIZEOF(END_PRIV_KEY_PREFIX)
  9615. || XSTRNCMP(footer, END_PRIV_KEY_PREFIX,
  9616. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)) != 0) {
  9617. WOLFSSL_MSG("Unexpected footer for PEM");
  9618. return BUFFER_E;
  9619. }
  9620. endLen = (unsigned int)(beginEnd - headerEnd -
  9621. (XSTR_SIZEOF(BEGIN_PRIV_KEY_PREFIX) -
  9622. XSTR_SIZEOF(END_PRIV_KEY_PREFIX)));
  9623. XMEMCPY(endBuf, footer, endLen);
  9624. endBuf[endLen] = '\0';
  9625. header = beginBuf;
  9626. footer = endBuf;
  9627. headerEnd = beginEnd;
  9628. }
  9629. }
  9630. if (!headerEnd) {
  9631. WOLFSSL_MSG("Couldn't find PEM header");
  9632. return ASN_NO_PEM_HEADER;
  9633. }
  9634. #else
  9635. WOLFSSL_MSG("Couldn't find PEM header");
  9636. return ASN_NO_PEM_HEADER;
  9637. #endif
  9638. } else {
  9639. headerEnd += XSTRLEN(header);
  9640. }
  9641. /* eat end of line characters */
  9642. headerEnd = SkipEndOfLineChars(headerEnd, bufferEnd);
  9643. if (type == PRIVATEKEY_TYPE) {
  9644. /* keyFormat is Key_Sum enum */
  9645. if (keyFormat) {
  9646. #ifdef HAVE_ECC
  9647. if (header == BEGIN_EC_PRIV)
  9648. *keyFormat = ECDSAk;
  9649. #endif
  9650. #if !defined(NO_DSA)
  9651. if (header == BEGIN_DSA_PRIV)
  9652. *keyFormat = DSAk;
  9653. #endif
  9654. }
  9655. }
  9656. #ifdef WOLFSSL_ENCRYPTED_KEYS
  9657. if (info) {
  9658. ret = wc_EncryptedInfoParse(info, &headerEnd, bufferEnd - headerEnd);
  9659. if (ret < 0)
  9660. return ret;
  9661. if (info->set)
  9662. encrypted_key = 1;
  9663. }
  9664. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  9665. /* find footer */
  9666. footerEnd = XSTRNSTR(headerEnd, footer, (unsigned int)((char*)buff + sz - headerEnd));
  9667. if (!footerEnd) {
  9668. if (info)
  9669. info->consumed = longSz; /* No more certs if no footer */
  9670. return BUFFER_E;
  9671. }
  9672. consumedEnd = footerEnd + XSTRLEN(footer);
  9673. if (consumedEnd < bufferEnd) { /* handle no end of line on last line */
  9674. /* eat end of line characters */
  9675. consumedEnd = SkipEndOfLineChars(consumedEnd, bufferEnd);
  9676. /* skip possible null term */
  9677. if (consumedEnd < bufferEnd && consumedEnd[0] == '\0')
  9678. consumedEnd++;
  9679. }
  9680. if (info)
  9681. info->consumed = (long)(consumedEnd - (const char*)buff);
  9682. /* set up der buffer */
  9683. neededSz = (long)(footerEnd - headerEnd);
  9684. if (neededSz > sz || neededSz <= 0)
  9685. return BUFFER_E;
  9686. ret = AllocDer(pDer, (word32)neededSz, type, heap);
  9687. if (ret < 0) {
  9688. return ret;
  9689. }
  9690. der = *pDer;
  9691. if (Base64_Decode((byte*)headerEnd, (word32)neededSz,
  9692. der->buffer, &der->length) < 0)
  9693. return BUFFER_E;
  9694. if ((header == BEGIN_PRIV_KEY
  9695. #ifdef OPENSSL_EXTRA
  9696. || header == beginBuf
  9697. #endif
  9698. #ifdef HAVE_ECC
  9699. || header == BEGIN_EC_PRIV
  9700. #endif
  9701. ) && !encrypted_key)
  9702. {
  9703. #ifdef HAVE_PKCS8
  9704. /* pkcs8 key, convert and adjust length */
  9705. if ((ret = ToTraditional_ex(der->buffer, der->length, &algId)) > 0) {
  9706. der->length = ret;
  9707. if (keyFormat) {
  9708. *keyFormat = algId;
  9709. }
  9710. }
  9711. else {
  9712. /* ignore failure here and assume key is not pkcs8 wrapped */
  9713. }
  9714. #endif
  9715. return 0;
  9716. }
  9717. #ifdef WOLFSSL_ENCRYPTED_KEYS
  9718. if (encrypted_key || header == BEGIN_ENC_PRIV_KEY) {
  9719. int passwordSz = NAME_SZ;
  9720. #ifdef WOLFSSL_SMALL_STACK
  9721. char* password = NULL;
  9722. #else
  9723. char password[NAME_SZ];
  9724. #endif
  9725. if (!info || !info->passwd_cb) {
  9726. WOLFSSL_MSG("No password callback set");
  9727. return NO_PASSWORD;
  9728. }
  9729. #ifdef WOLFSSL_SMALL_STACK
  9730. password = (char*)XMALLOC(passwordSz, heap, DYNAMIC_TYPE_STRING);
  9731. if (password == NULL)
  9732. return MEMORY_E;
  9733. #endif
  9734. /* get password */
  9735. ret = info->passwd_cb(password, passwordSz, PEM_PASS_READ,
  9736. info->passwd_userdata);
  9737. if (ret >= 0) {
  9738. passwordSz = ret;
  9739. /* convert and adjust length */
  9740. if (header == BEGIN_ENC_PRIV_KEY) {
  9741. #ifndef NO_PWDBASED
  9742. ret = ToTraditionalEnc(der->buffer, der->length,
  9743. password, passwordSz, &algId);
  9744. if (ret >= 0) {
  9745. der->length = ret;
  9746. if (keyFormat) {
  9747. *keyFormat = algId;
  9748. }
  9749. ret = 0;
  9750. }
  9751. #else
  9752. ret = NOT_COMPILED_IN;
  9753. #endif
  9754. }
  9755. /* decrypt the key */
  9756. else {
  9757. if (passwordSz == 0) {
  9758. /* The key is encrypted but does not have a password */
  9759. WOLFSSL_MSG("No password for encrypted key");
  9760. ret = NO_PASSWORD;
  9761. }
  9762. else {
  9763. ret = wc_BufferKeyDecrypt(info, der->buffer, der->length,
  9764. (byte*)password, passwordSz, WC_MD5);
  9765. #ifndef NO_WOLFSSL_SKIP_TRAILING_PAD
  9766. #ifndef NO_DES3
  9767. if (info->cipherType == WC_CIPHER_DES3) {
  9768. /* Assuming there is padding:
  9769. * (der->length > 0 && der->length > DES_BLOCK_SIZE &&
  9770. * (der->length % DES_BLOCK_SIZE) != 0)
  9771. * and assuming the last value signifies the number of
  9772. * padded bytes IE if last value is 0x08 then there are
  9773. * 8 bytes of padding:
  9774. * padVal = der->buffer[der->length-1];
  9775. * then strip this padding before proceeding:
  9776. * der->length -= padVal;
  9777. */
  9778. if (der->length > DES_BLOCK_SIZE &&
  9779. (der->length % DES_BLOCK_SIZE) != 0) {
  9780. padVal = der->buffer[der->length-1];
  9781. if (padVal < DES_BLOCK_SIZE) {
  9782. der->length -= padVal;
  9783. }
  9784. }
  9785. }
  9786. #endif /* !NO_DES3 */
  9787. #endif /* !NO_WOLFSSL_SKIP_TRAILING_PAD */
  9788. }
  9789. }
  9790. #ifdef OPENSSL_EXTRA
  9791. if (ret) {
  9792. PEMerr(0, PEM_R_BAD_DECRYPT);
  9793. }
  9794. #endif
  9795. ForceZero(password, passwordSz);
  9796. }
  9797. #ifdef OPENSSL_EXTRA
  9798. else {
  9799. PEMerr(0, PEM_R_BAD_PASSWORD_READ);
  9800. }
  9801. #endif
  9802. #ifdef WOLFSSL_SMALL_STACK
  9803. XFREE(password, heap, DYNAMIC_TYPE_STRING);
  9804. #endif
  9805. }
  9806. #endif /* WOLFSSL_ENCRYPTED_KEYS */
  9807. return ret;
  9808. }
  9809. int wc_PemToDer(const unsigned char* buff, long longSz, int type,
  9810. DerBuffer** pDer, void* heap, EncryptedInfo* info, int* eccKey)
  9811. {
  9812. return PemToDer(buff, longSz, type, pDer, heap, info, eccKey);
  9813. }
  9814. /* our KeyPemToDer password callback, password in userData */
  9815. static WC_INLINE int OurPasswordCb(char* passwd, int sz, int rw, void* userdata)
  9816. {
  9817. (void)rw;
  9818. if (userdata == NULL)
  9819. return 0;
  9820. XSTRNCPY(passwd, (char*)userdata, sz);
  9821. return min((word32)sz, (word32)XSTRLEN((char*)userdata));
  9822. }
  9823. /* Return bytes written to buff or < 0 for error */
  9824. int wc_KeyPemToDer(const unsigned char* pem, int pemSz,
  9825. unsigned char* buff, int buffSz, const char* pass)
  9826. {
  9827. int eccKey = 0;
  9828. int ret;
  9829. DerBuffer* der = NULL;
  9830. #ifdef WOLFSSL_SMALL_STACK
  9831. EncryptedInfo* info = NULL;
  9832. #else
  9833. EncryptedInfo info[1];
  9834. #endif
  9835. WOLFSSL_ENTER("wc_KeyPemToDer");
  9836. if (pem == NULL || buff == NULL || buffSz <= 0) {
  9837. WOLFSSL_MSG("Bad pem der args");
  9838. return BAD_FUNC_ARG;
  9839. }
  9840. #ifdef WOLFSSL_SMALL_STACK
  9841. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  9842. DYNAMIC_TYPE_ENCRYPTEDINFO);
  9843. if (info == NULL)
  9844. return MEMORY_E;
  9845. #endif
  9846. XMEMSET(info, 0, sizeof(EncryptedInfo));
  9847. info->passwd_cb = OurPasswordCb;
  9848. info->passwd_userdata = (void*)pass;
  9849. ret = PemToDer(pem, pemSz, PRIVATEKEY_TYPE, &der, NULL, info, &eccKey);
  9850. #ifdef WOLFSSL_SMALL_STACK
  9851. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  9852. #endif
  9853. if (ret < 0 || der == NULL) {
  9854. WOLFSSL_MSG("Bad Pem To Der");
  9855. }
  9856. else {
  9857. if (der->length <= (word32)buffSz) {
  9858. XMEMCPY(buff, der->buffer, der->length);
  9859. ret = der->length;
  9860. }
  9861. else {
  9862. WOLFSSL_MSG("Bad der length");
  9863. ret = BAD_FUNC_ARG;
  9864. }
  9865. }
  9866. FreeDer(&der);
  9867. return ret;
  9868. }
  9869. /* Return bytes written to buff or < 0 for error */
  9870. int wc_CertPemToDer(const unsigned char* pem, int pemSz,
  9871. unsigned char* buff, int buffSz, int type)
  9872. {
  9873. int eccKey = 0;
  9874. int ret;
  9875. DerBuffer* der = NULL;
  9876. WOLFSSL_ENTER("wc_CertPemToDer");
  9877. if (pem == NULL || buff == NULL || buffSz <= 0) {
  9878. WOLFSSL_MSG("Bad pem der args");
  9879. return BAD_FUNC_ARG;
  9880. }
  9881. if (type != CERT_TYPE && type != CA_TYPE && type != CERTREQ_TYPE) {
  9882. WOLFSSL_MSG("Bad cert type");
  9883. return BAD_FUNC_ARG;
  9884. }
  9885. ret = PemToDer(pem, pemSz, type, &der, NULL, NULL, &eccKey);
  9886. if (ret < 0 || der == NULL) {
  9887. WOLFSSL_MSG("Bad Pem To Der");
  9888. }
  9889. else {
  9890. if (der->length <= (word32)buffSz) {
  9891. XMEMCPY(buff, der->buffer, der->length);
  9892. ret = der->length;
  9893. }
  9894. else {
  9895. WOLFSSL_MSG("Bad der length");
  9896. ret = BAD_FUNC_ARG;
  9897. }
  9898. }
  9899. FreeDer(&der);
  9900. return ret;
  9901. }
  9902. #endif /* WOLFSSL_PEM_TO_DER */
  9903. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  9904. #ifdef WOLFSSL_PEM_TO_DER
  9905. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  9906. /* Return bytes written to buff or < 0 for error */
  9907. int wc_PubKeyPemToDer(const unsigned char* pem, int pemSz,
  9908. unsigned char* buff, int buffSz)
  9909. {
  9910. int ret;
  9911. DerBuffer* der = NULL;
  9912. WOLFSSL_ENTER("wc_PubKeyPemToDer");
  9913. if (pem == NULL || buff == NULL || buffSz <= 0) {
  9914. WOLFSSL_MSG("Bad pem der args");
  9915. return BAD_FUNC_ARG;
  9916. }
  9917. ret = PemToDer(pem, pemSz, PUBLICKEY_TYPE, &der, NULL, NULL, NULL);
  9918. if (ret < 0 || der == NULL) {
  9919. WOLFSSL_MSG("Bad Pem To Der");
  9920. }
  9921. else {
  9922. if (der->length <= (word32)buffSz) {
  9923. XMEMCPY(buff, der->buffer, der->length);
  9924. ret = der->length;
  9925. }
  9926. else {
  9927. WOLFSSL_MSG("Bad der length");
  9928. ret = BAD_FUNC_ARG;
  9929. }
  9930. }
  9931. FreeDer(&der);
  9932. return ret;
  9933. }
  9934. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  9935. #endif /* WOLFSSL_PEM_TO_DER */
  9936. #ifndef NO_FILESYSTEM
  9937. #ifdef WOLFSSL_CERT_GEN
  9938. /* load pem cert from file into der buffer, return der size or error */
  9939. int wc_PemCertToDer(const char* fileName, unsigned char* derBuf, int derSz)
  9940. {
  9941. #ifdef WOLFSSL_SMALL_STACK
  9942. byte staticBuffer[1]; /* force XMALLOC */
  9943. #else
  9944. byte staticBuffer[FILE_BUFFER_SIZE];
  9945. #endif
  9946. byte* fileBuf = staticBuffer;
  9947. int dynamic = 0;
  9948. int ret = 0;
  9949. long sz = 0;
  9950. XFILE file;
  9951. DerBuffer* converted = NULL;
  9952. WOLFSSL_ENTER("wc_PemCertToDer");
  9953. if (fileName == NULL) {
  9954. ret = BAD_FUNC_ARG;
  9955. }
  9956. else {
  9957. file = XFOPEN(fileName, "rb");
  9958. if (file == XBADFILE) {
  9959. ret = BUFFER_E;
  9960. }
  9961. }
  9962. if (ret == 0) {
  9963. if(XFSEEK(file, 0, XSEEK_END) != 0)
  9964. ret = BUFFER_E;
  9965. sz = XFTELL(file);
  9966. XREWIND(file);
  9967. if (sz <= 0) {
  9968. ret = BUFFER_E;
  9969. }
  9970. else if (sz > (long)sizeof(staticBuffer)) {
  9971. #ifdef WOLFSSL_STATIC_MEMORY
  9972. WOLFSSL_MSG("File was larger then static buffer");
  9973. return MEMORY_E;
  9974. #endif
  9975. fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
  9976. if (fileBuf == NULL)
  9977. ret = MEMORY_E;
  9978. else
  9979. dynamic = 1;
  9980. }
  9981. if (ret == 0) {
  9982. if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
  9983. ret = BUFFER_E;
  9984. }
  9985. #ifdef WOLFSSL_PEM_TO_DER
  9986. else {
  9987. ret = PemToDer(fileBuf, sz, CA_TYPE, &converted, 0, NULL,NULL);
  9988. }
  9989. #endif
  9990. if (ret == 0) {
  9991. if (converted->length < (word32)derSz) {
  9992. XMEMCPY(derBuf, converted->buffer, converted->length);
  9993. ret = converted->length;
  9994. }
  9995. else
  9996. ret = BUFFER_E;
  9997. }
  9998. FreeDer(&converted);
  9999. }
  10000. XFCLOSE(file);
  10001. if (dynamic)
  10002. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  10003. }
  10004. return ret;
  10005. }
  10006. #endif /* WOLFSSL_CERT_GEN */
  10007. #if defined(WOLFSSL_CERT_EXT) || defined(WOLFSSL_PUB_PEM_TO_DER)
  10008. /* load pem public key from file into der buffer, return der size or error */
  10009. int wc_PemPubKeyToDer(const char* fileName,
  10010. unsigned char* derBuf, int derSz)
  10011. {
  10012. #ifdef WOLFSSL_SMALL_STACK
  10013. byte staticBuffer[1]; /* force XMALLOC */
  10014. #else
  10015. byte staticBuffer[FILE_BUFFER_SIZE];
  10016. #endif
  10017. byte* fileBuf = staticBuffer;
  10018. int dynamic = 0;
  10019. int ret = 0;
  10020. long sz = 0;
  10021. XFILE file;
  10022. DerBuffer* converted = NULL;
  10023. WOLFSSL_ENTER("wc_PemPubKeyToDer");
  10024. if (fileName == NULL) {
  10025. ret = BAD_FUNC_ARG;
  10026. }
  10027. else {
  10028. file = XFOPEN(fileName, "rb");
  10029. if (file == XBADFILE) {
  10030. ret = BUFFER_E;
  10031. }
  10032. }
  10033. if (ret == 0) {
  10034. if(XFSEEK(file, 0, XSEEK_END) != 0)
  10035. ret = BUFFER_E;
  10036. sz = XFTELL(file);
  10037. XREWIND(file);
  10038. if (sz <= 0) {
  10039. ret = BUFFER_E;
  10040. }
  10041. else if (sz > (long)sizeof(staticBuffer)) {
  10042. #ifdef WOLFSSL_STATIC_MEMORY
  10043. WOLFSSL_MSG("File was larger then static buffer");
  10044. return MEMORY_E;
  10045. #endif
  10046. fileBuf = (byte*)XMALLOC(sz, NULL, DYNAMIC_TYPE_FILE);
  10047. if (fileBuf == NULL)
  10048. ret = MEMORY_E;
  10049. else
  10050. dynamic = 1;
  10051. }
  10052. if (ret == 0) {
  10053. if ((size_t)XFREAD(fileBuf, 1, sz, file) != (size_t)sz) {
  10054. ret = BUFFER_E;
  10055. }
  10056. #ifdef WOLFSSL_PEM_TO_DER
  10057. else {
  10058. ret = PemToDer(fileBuf, sz, PUBLICKEY_TYPE, &converted,
  10059. 0, NULL, NULL);
  10060. }
  10061. #endif
  10062. if (ret == 0) {
  10063. if (converted->length < (word32)derSz) {
  10064. XMEMCPY(derBuf, converted->buffer, converted->length);
  10065. ret = converted->length;
  10066. }
  10067. else
  10068. ret = BUFFER_E;
  10069. }
  10070. FreeDer(&converted);
  10071. }
  10072. XFCLOSE(file);
  10073. if (dynamic)
  10074. XFREE(fileBuf, NULL, DYNAMIC_TYPE_FILE);
  10075. }
  10076. return ret;
  10077. }
  10078. #endif /* WOLFSSL_CERT_EXT || WOLFSSL_PUB_PEM_TO_DER */
  10079. #endif /* !NO_FILESYSTEM */
  10080. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  10081. ((defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(HAVE_USER_RSA)))
  10082. /* USER RSA ifdef portions used instead of refactor in consideration for
  10083. possible fips build */
  10084. /* Write a public RSA key to output */
  10085. static int SetRsaPublicKey(byte* output, RsaKey* key,
  10086. int outLen, int with_header)
  10087. {
  10088. #ifdef WOLFSSL_SMALL_STACK
  10089. byte* n = NULL;
  10090. byte* e = NULL;
  10091. #else
  10092. byte n[MAX_RSA_INT_SZ];
  10093. byte e[MAX_RSA_E_SZ];
  10094. #endif
  10095. byte seq[MAX_SEQ_SZ];
  10096. byte bitString[1 + MAX_LENGTH_SZ + 1];
  10097. int nSz;
  10098. int eSz;
  10099. int seqSz;
  10100. int bitStringSz;
  10101. int idx;
  10102. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ)
  10103. return BAD_FUNC_ARG;
  10104. /* n */
  10105. #ifdef WOLFSSL_SMALL_STACK
  10106. n = (byte*)XMALLOC(MAX_RSA_INT_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10107. if (n == NULL)
  10108. return MEMORY_E;
  10109. #endif
  10110. #ifdef HAVE_USER_RSA
  10111. nSz = SetASNIntRSA(key->n, n);
  10112. #else
  10113. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, n);
  10114. #endif
  10115. if (nSz < 0) {
  10116. #ifdef WOLFSSL_SMALL_STACK
  10117. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10118. #endif
  10119. return nSz;
  10120. }
  10121. /* e */
  10122. #ifdef WOLFSSL_SMALL_STACK
  10123. e = (byte*)XMALLOC(MAX_RSA_E_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10124. if (e == NULL) {
  10125. #ifdef WOLFSSL_SMALL_STACK
  10126. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10127. #endif
  10128. return MEMORY_E;
  10129. }
  10130. #endif
  10131. #ifdef HAVE_USER_RSA
  10132. eSz = SetASNIntRSA(key->e, e);
  10133. #else
  10134. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, e);
  10135. #endif
  10136. if (eSz < 0) {
  10137. #ifdef WOLFSSL_SMALL_STACK
  10138. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10139. XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10140. #endif
  10141. return eSz;
  10142. }
  10143. seqSz = SetSequence(nSz + eSz, seq);
  10144. /* check output size */
  10145. if ( (seqSz + nSz + eSz) > outLen) {
  10146. #ifdef WOLFSSL_SMALL_STACK
  10147. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10148. XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10149. #endif
  10150. return BUFFER_E;
  10151. }
  10152. /* headers */
  10153. if (with_header) {
  10154. int algoSz;
  10155. #ifdef WOLFSSL_SMALL_STACK
  10156. byte* algo;
  10157. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10158. if (algo == NULL) {
  10159. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10160. XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10161. return MEMORY_E;
  10162. }
  10163. #else
  10164. byte algo[MAX_ALGO_SZ];
  10165. #endif
  10166. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  10167. bitStringSz = SetBitString(seqSz + nSz + eSz, 0, bitString);
  10168. idx = SetSequence(nSz + eSz + seqSz + bitStringSz + algoSz, output);
  10169. /* check output size */
  10170. if ( (idx + algoSz + bitStringSz + seqSz + nSz + eSz) > outLen) {
  10171. #ifdef WOLFSSL_SMALL_STACK
  10172. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10173. XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10174. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10175. #endif
  10176. return BUFFER_E;
  10177. }
  10178. /* algo */
  10179. XMEMCPY(output + idx, algo, algoSz);
  10180. idx += algoSz;
  10181. /* bit string */
  10182. XMEMCPY(output + idx, bitString, bitStringSz);
  10183. idx += bitStringSz;
  10184. #ifdef WOLFSSL_SMALL_STACK
  10185. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10186. #endif
  10187. }
  10188. else
  10189. idx = 0;
  10190. /* seq */
  10191. XMEMCPY(output + idx, seq, seqSz);
  10192. idx += seqSz;
  10193. /* n */
  10194. XMEMCPY(output + idx, n, nSz);
  10195. idx += nSz;
  10196. /* e */
  10197. XMEMCPY(output + idx, e, eSz);
  10198. idx += eSz;
  10199. #ifdef WOLFSSL_SMALL_STACK
  10200. XFREE(n, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10201. XFREE(e, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10202. #endif
  10203. return idx;
  10204. }
  10205. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || (WOLFSSL_KEY_GEN &&
  10206. !HAVE_USER_RSA))) */
  10207. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA))
  10208. int wc_RsaPublicKeyDerSize(RsaKey* key, int with_header)
  10209. {
  10210. int idx = 0;
  10211. int nSz, eSz, seqSz, bitStringSz, algoSz;
  10212. if (key == NULL)
  10213. return BAD_FUNC_ARG;
  10214. /* n */
  10215. #ifdef HAVE_USER_RSA
  10216. nSz = SetASNIntRSA(key->n, NULL);
  10217. #else
  10218. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, NULL);
  10219. #endif
  10220. if (nSz < 0) {
  10221. return nSz;
  10222. }
  10223. /* e */
  10224. #ifdef HAVE_USER_RSA
  10225. eSz = SetASNIntRSA(key->e, NULL);
  10226. #else
  10227. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, NULL);
  10228. #endif
  10229. if (eSz < 0) {
  10230. return eSz;
  10231. }
  10232. seqSz = SetSequence(nSz + eSz, NULL);
  10233. /* headers */
  10234. if (with_header) {
  10235. algoSz = SetAlgoID(RSAk, NULL, oidKeyType, 0);
  10236. bitStringSz = SetBitString(seqSz + nSz + eSz, 0, NULL);
  10237. idx += SetSequence(nSz + eSz + seqSz + bitStringSz + algoSz, NULL);
  10238. /* algo */
  10239. idx += algoSz;
  10240. /* bit string */
  10241. idx += bitStringSz;
  10242. }
  10243. /* seq */
  10244. idx += seqSz;
  10245. /* n */
  10246. idx += nSz;
  10247. /* e */
  10248. idx += eSz;
  10249. return idx;
  10250. }
  10251. #endif /* !NO_RSA && WOLFSSL_CERT_GEN */
  10252. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  10253. static mp_int* GetRsaInt(RsaKey* key, int idx)
  10254. {
  10255. if (idx == 0)
  10256. return &key->n;
  10257. if (idx == 1)
  10258. return &key->e;
  10259. if (idx == 2)
  10260. return &key->d;
  10261. if (idx == 3)
  10262. return &key->p;
  10263. if (idx == 4)
  10264. return &key->q;
  10265. if (idx == 5)
  10266. return &key->dP;
  10267. if (idx == 6)
  10268. return &key->dQ;
  10269. if (idx == 7)
  10270. return &key->u;
  10271. return NULL;
  10272. }
  10273. /* Release Tmp RSA resources */
  10274. static WC_INLINE void FreeTmpRsas(byte** tmps, void* heap)
  10275. {
  10276. int i;
  10277. (void)heap;
  10278. for (i = 0; i < RSA_INTS; i++)
  10279. XFREE(tmps[i], heap, DYNAMIC_TYPE_RSA);
  10280. }
  10281. /* Convert RsaKey key to DER format, write to output (inLen), return bytes
  10282. written */
  10283. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  10284. {
  10285. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  10286. word32 sizes[RSA_INTS];
  10287. int i, j, outLen, ret = 0, mpSz;
  10288. byte seq[MAX_SEQ_SZ];
  10289. byte ver[MAX_VERSION_SZ];
  10290. byte* tmps[RSA_INTS];
  10291. if (!key)
  10292. return BAD_FUNC_ARG;
  10293. if (key->type != RSA_PRIVATE)
  10294. return BAD_FUNC_ARG;
  10295. for (i = 0; i < RSA_INTS; i++)
  10296. tmps[i] = NULL;
  10297. /* write all big ints from key to DER tmps */
  10298. for (i = 0; i < RSA_INTS; i++) {
  10299. mp_int* keyInt = GetRsaInt(key, i);
  10300. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  10301. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  10302. DYNAMIC_TYPE_RSA);
  10303. if (tmps[i] == NULL) {
  10304. ret = MEMORY_E;
  10305. break;
  10306. }
  10307. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  10308. if (mpSz < 0) {
  10309. ret = mpSz;
  10310. break;
  10311. }
  10312. intTotalLen += (sizes[i] = mpSz);
  10313. }
  10314. if (ret != 0) {
  10315. FreeTmpRsas(tmps, key->heap);
  10316. return ret;
  10317. }
  10318. /* make headers */
  10319. verSz = SetMyVersion(0, ver, FALSE);
  10320. seqSz = SetSequence(verSz + intTotalLen, seq);
  10321. outLen = seqSz + verSz + intTotalLen;
  10322. if (output) {
  10323. if (outLen > (int)inLen) {
  10324. FreeTmpRsas(tmps, key->heap);
  10325. return BAD_FUNC_ARG;
  10326. }
  10327. /* write to output */
  10328. XMEMCPY(output, seq, seqSz);
  10329. j = seqSz;
  10330. XMEMCPY(output + j, ver, verSz);
  10331. j += verSz;
  10332. for (i = 0; i < RSA_INTS; i++) {
  10333. XMEMCPY(output + j, tmps[i], sizes[i]);
  10334. j += sizes[i];
  10335. }
  10336. }
  10337. FreeTmpRsas(tmps, key->heap);
  10338. return outLen;
  10339. }
  10340. #endif
  10341. #if (defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA)) && !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  10342. /* Convert Rsa Public key to DER format, write to output (inLen), return bytes
  10343. written */
  10344. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  10345. {
  10346. return SetRsaPublicKey(output, key, inLen, 1);
  10347. }
  10348. #endif /* (WOLFSSL_KEY_GEN || OPENSSL_EXTRA) && !NO_RSA && !HAVE_USER_RSA */
  10349. #ifdef WOLFSSL_CERT_GEN
  10350. /* Initialize and Set Certificate defaults:
  10351. version = 3 (0x2)
  10352. serial = 0
  10353. sigType = SHA_WITH_RSA
  10354. issuer = blank
  10355. daysValid = 500
  10356. selfSigned = 1 (true) use subject as issuer
  10357. subject = blank
  10358. */
  10359. int wc_InitCert(Cert* cert)
  10360. {
  10361. #ifdef WOLFSSL_MULTI_ATTRIB
  10362. int i = 0;
  10363. #endif
  10364. if (cert == NULL) {
  10365. return BAD_FUNC_ARG;
  10366. }
  10367. XMEMSET(cert, 0, sizeof(Cert));
  10368. cert->version = 2; /* version 3 is hex 2 */
  10369. #ifndef NO_SHA
  10370. cert->sigType = CTC_SHAwRSA;
  10371. #elif !defined(NO_SHA256)
  10372. cert->sigType = CTC_SHA256wRSA;
  10373. #else
  10374. cert->sigType = 0;
  10375. #endif
  10376. cert->daysValid = 500;
  10377. cert->selfSigned = 1;
  10378. cert->keyType = RSA_KEY;
  10379. cert->issuer.countryEnc = CTC_PRINTABLE;
  10380. cert->issuer.stateEnc = CTC_UTF8;
  10381. cert->issuer.localityEnc = CTC_UTF8;
  10382. cert->issuer.surEnc = CTC_UTF8;
  10383. cert->issuer.orgEnc = CTC_UTF8;
  10384. cert->issuer.unitEnc = CTC_UTF8;
  10385. cert->issuer.commonNameEnc = CTC_UTF8;
  10386. cert->subject.countryEnc = CTC_PRINTABLE;
  10387. cert->subject.stateEnc = CTC_UTF8;
  10388. cert->subject.localityEnc = CTC_UTF8;
  10389. cert->subject.surEnc = CTC_UTF8;
  10390. cert->subject.orgEnc = CTC_UTF8;
  10391. cert->subject.unitEnc = CTC_UTF8;
  10392. cert->subject.commonNameEnc = CTC_UTF8;
  10393. #ifdef WOLFSSL_MULTI_ATTRIB
  10394. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  10395. cert->issuer.name[i].type = CTC_UTF8;
  10396. cert->subject.name[i].type = CTC_UTF8;
  10397. }
  10398. #endif /* WOLFSSL_MULTI_ATTRIB */
  10399. #ifdef WOLFSSL_HEAP_TEST
  10400. cert->heap = (void*)WOLFSSL_HEAP_TEST;
  10401. #endif
  10402. return 0;
  10403. }
  10404. /* DER encoded x509 Certificate */
  10405. typedef struct DerCert {
  10406. byte size[MAX_LENGTH_SZ]; /* length encoded */
  10407. byte version[MAX_VERSION_SZ]; /* version encoded */
  10408. byte serial[(int)CTC_SERIAL_SIZE + (int)MAX_LENGTH_SZ]; /* serial number encoded */
  10409. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  10410. byte issuer[ASN_NAME_MAX]; /* issuer encoded */
  10411. byte subject[ASN_NAME_MAX]; /* subject encoded */
  10412. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  10413. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
  10414. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  10415. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  10416. #ifdef WOLFSSL_CERT_EXT
  10417. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  10418. byte akid[MAX_KID_SZ]; /* Authority Key Identifier extension */
  10419. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  10420. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  10421. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  10422. #endif
  10423. #ifdef WOLFSSL_CERT_REQ
  10424. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  10425. #endif
  10426. #ifdef WOLFSSL_ALT_NAMES
  10427. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  10428. #endif
  10429. int sizeSz; /* encoded size length */
  10430. int versionSz; /* encoded version length */
  10431. int serialSz; /* encoded serial length */
  10432. int sigAlgoSz; /* encoded sig algo length */
  10433. int issuerSz; /* encoded issuer length */
  10434. int subjectSz; /* encoded subject length */
  10435. int validitySz; /* encoded validity length */
  10436. int publicKeySz; /* encoded public key length */
  10437. int caSz; /* encoded CA extension length */
  10438. #ifdef WOLFSSL_CERT_EXT
  10439. int skidSz; /* encoded SKID extension length */
  10440. int akidSz; /* encoded SKID extension length */
  10441. int keyUsageSz; /* encoded KeyUsage extension length */
  10442. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  10443. int certPoliciesSz; /* encoded CertPolicies extension length*/
  10444. #endif
  10445. #ifdef WOLFSSL_ALT_NAMES
  10446. int altNamesSz; /* encoded AltNames extension length */
  10447. #endif
  10448. int extensionsSz; /* encoded extensions total length */
  10449. int total; /* total encoded lengths */
  10450. #ifdef WOLFSSL_CERT_REQ
  10451. int attribSz;
  10452. #endif
  10453. } DerCert;
  10454. #ifdef WOLFSSL_CERT_REQ
  10455. /* Write a set header to output */
  10456. static word32 SetPrintableString(word32 len, byte* output)
  10457. {
  10458. output[0] = ASN_PRINTABLE_STRING;
  10459. return SetLength(len, output + 1) + 1;
  10460. }
  10461. static word32 SetUTF8String(word32 len, byte* output)
  10462. {
  10463. output[0] = ASN_UTF8STRING;
  10464. return SetLength(len, output + 1) + 1;
  10465. }
  10466. #endif /* WOLFSSL_CERT_REQ */
  10467. #ifndef WOLFSSL_CERT_GEN_CACHE
  10468. /* wc_SetCert_Free is only public when WOLFSSL_CERT_GEN_CACHE is not defined */
  10469. static
  10470. #endif
  10471. void wc_SetCert_Free(Cert* cert)
  10472. {
  10473. if (cert != NULL) {
  10474. cert->der = NULL;
  10475. if (cert->decodedCert) {
  10476. FreeDecodedCert((DecodedCert*)cert->decodedCert);
  10477. XFREE(cert->decodedCert, cert->heap, DYNAMIC_TYPE_DCERT);
  10478. cert->decodedCert = NULL;
  10479. }
  10480. }
  10481. }
  10482. static int wc_SetCert_LoadDer(Cert* cert, const byte* der, word32 derSz)
  10483. {
  10484. int ret;
  10485. if (cert == NULL) {
  10486. ret = BAD_FUNC_ARG;
  10487. }
  10488. else {
  10489. /* Allocate DecodedCert struct and Zero */
  10490. cert->decodedCert = (void*)XMALLOC(sizeof(DecodedCert), cert->heap,
  10491. DYNAMIC_TYPE_DCERT);
  10492. if (cert->decodedCert == NULL) {
  10493. ret = MEMORY_E;
  10494. }
  10495. else {
  10496. XMEMSET(cert->decodedCert, 0, sizeof(DecodedCert));
  10497. InitDecodedCert((DecodedCert*)cert->decodedCert, der, derSz,
  10498. cert->heap);
  10499. ret = ParseCertRelative((DecodedCert*)cert->decodedCert,
  10500. CERT_TYPE, 0, NULL);
  10501. if (ret >= 0) {
  10502. cert->der = (byte*)der;
  10503. }
  10504. else {
  10505. wc_SetCert_Free(cert);
  10506. }
  10507. }
  10508. }
  10509. return ret;
  10510. }
  10511. #endif /* WOLFSSL_CERT_GEN */
  10512. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)
  10513. /* Write a public ECC key to output */
  10514. static int SetEccPublicKey(byte* output, ecc_key* key, int with_header)
  10515. {
  10516. byte bitString[1 + MAX_LENGTH_SZ + 1];
  10517. int algoSz;
  10518. int curveSz;
  10519. int bitStringSz;
  10520. int idx;
  10521. word32 pubSz = ECC_BUFSIZE;
  10522. #ifdef WOLFSSL_SMALL_STACK
  10523. byte* algo = NULL;
  10524. byte* curve = NULL;
  10525. byte* pub;
  10526. #else
  10527. byte algo[MAX_ALGO_SZ];
  10528. byte curve[MAX_ALGO_SZ];
  10529. byte pub[ECC_BUFSIZE];
  10530. #endif
  10531. int ret;
  10532. #ifdef WOLFSSL_SMALL_STACK
  10533. pub = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10534. if (pub == NULL)
  10535. return MEMORY_E;
  10536. #endif
  10537. #if defined(HAVE_SELFTEST) || defined(HAVE_FIPS)
  10538. /* older version of ecc.c can not handle dp being NULL */
  10539. if (key != NULL && key->dp == NULL) {
  10540. ret = BAD_FUNC_ARG;
  10541. }
  10542. else {
  10543. ret = wc_ecc_export_x963(key, pub, &pubSz);
  10544. }
  10545. #else
  10546. ret = wc_ecc_export_x963(key, pub, &pubSz);
  10547. #endif
  10548. if (ret != 0) {
  10549. #ifdef WOLFSSL_SMALL_STACK
  10550. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10551. #endif
  10552. return ret;
  10553. }
  10554. /* headers */
  10555. if (with_header) {
  10556. #ifdef WOLFSSL_SMALL_STACK
  10557. curve = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10558. if (curve == NULL) {
  10559. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10560. return MEMORY_E;
  10561. }
  10562. #endif
  10563. curveSz = SetCurve(key, curve);
  10564. if (curveSz <= 0) {
  10565. #ifdef WOLFSSL_SMALL_STACK
  10566. XFREE(curve, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10567. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10568. #endif
  10569. return curveSz;
  10570. }
  10571. #ifdef WOLFSSL_SMALL_STACK
  10572. algo = (byte*)XMALLOC(MAX_ALGO_SZ, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10573. if (algo == NULL) {
  10574. XFREE(curve, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10575. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10576. return MEMORY_E;
  10577. }
  10578. #endif
  10579. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, curveSz);
  10580. bitStringSz = SetBitString(pubSz, 0, bitString);
  10581. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, output);
  10582. /* algo */
  10583. if (output)
  10584. XMEMCPY(output + idx, algo, algoSz);
  10585. idx += algoSz;
  10586. /* curve */
  10587. if (output)
  10588. XMEMCPY(output + idx, curve, curveSz);
  10589. idx += curveSz;
  10590. /* bit string */
  10591. if (output)
  10592. XMEMCPY(output + idx, bitString, bitStringSz);
  10593. idx += bitStringSz;
  10594. }
  10595. else
  10596. idx = 0;
  10597. /* pub */
  10598. if (output)
  10599. XMEMCPY(output + idx, pub, pubSz);
  10600. idx += pubSz;
  10601. #ifdef WOLFSSL_SMALL_STACK
  10602. if (with_header) {
  10603. XFREE(algo, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10604. XFREE(curve, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10605. }
  10606. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10607. #endif
  10608. return idx;
  10609. }
  10610. /* returns the size of buffer used, the public ECC key in DER format is stored
  10611. in output buffer
  10612. with_AlgCurve is a flag for when to include a header that has the Algorithm
  10613. and Curve information */
  10614. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  10615. int with_AlgCurve)
  10616. {
  10617. word32 infoSz = 0;
  10618. word32 keySz = 0;
  10619. int ret;
  10620. if (key == NULL) {
  10621. return BAD_FUNC_ARG;
  10622. }
  10623. if (with_AlgCurve) {
  10624. /* buffer space for algorithm/curve */
  10625. infoSz += MAX_SEQ_SZ;
  10626. infoSz += 2 * MAX_ALGO_SZ;
  10627. /* buffer space for public key sequence */
  10628. infoSz += MAX_SEQ_SZ;
  10629. infoSz += TRAILING_ZERO;
  10630. }
  10631. #if defined(HAVE_SELFTEST) || defined(HAVE_FIPS)
  10632. /* older version of ecc.c can not handle dp being NULL */
  10633. if (key->dp == NULL) {
  10634. keySz = 1 + 2 * MAX_ECC_BYTES;
  10635. ret = LENGTH_ONLY_E;
  10636. }
  10637. else {
  10638. ret = wc_ecc_export_x963(key, NULL, &keySz);
  10639. }
  10640. #else
  10641. ret = wc_ecc_export_x963(key, NULL, &keySz);
  10642. #endif
  10643. if (ret != LENGTH_ONLY_E) {
  10644. WOLFSSL_MSG("Error in getting ECC public key size");
  10645. return ret;
  10646. }
  10647. /* if output null then just return size */
  10648. if (output == NULL) {
  10649. return keySz + infoSz;
  10650. }
  10651. if (inLen < keySz + infoSz) {
  10652. return BUFFER_E;
  10653. }
  10654. return SetEccPublicKey(output, key, with_AlgCurve);
  10655. }
  10656. int wc_EccPublicKeyDerSize(ecc_key* key, int with_AlgCurve)
  10657. {
  10658. return wc_EccPublicKeyToDer(key, NULL, 0, with_AlgCurve);
  10659. }
  10660. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  10661. #if defined(HAVE_ED25519) && (defined(WOLFSSL_CERT_GEN) || \
  10662. defined(WOLFSSL_KEY_GEN))
  10663. /* Write a public ECC key to output */
  10664. static int SetEd25519PublicKey(byte* output, ed25519_key* key, int with_header)
  10665. {
  10666. byte bitString[1 + MAX_LENGTH_SZ + 1];
  10667. int algoSz;
  10668. int bitStringSz;
  10669. int idx;
  10670. word32 pubSz = ED25519_PUB_KEY_SIZE;
  10671. #ifdef WOLFSSL_SMALL_STACK
  10672. byte* algo = NULL;
  10673. byte* pub;
  10674. #else
  10675. byte algo[MAX_ALGO_SZ];
  10676. byte pub[ED25519_PUB_KEY_SIZE];
  10677. #endif
  10678. #ifdef WOLFSSL_SMALL_STACK
  10679. pub = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10680. if (pub == NULL)
  10681. return MEMORY_E;
  10682. #endif
  10683. idx = wc_ed25519_export_public(key, pub, &pubSz);
  10684. if (idx != 0) {
  10685. #ifdef WOLFSSL_SMALL_STACK
  10686. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10687. #endif
  10688. return idx;
  10689. }
  10690. /* headers */
  10691. if (with_header) {
  10692. #ifdef WOLFSSL_SMALL_STACK
  10693. algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10694. if (algo == NULL) {
  10695. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10696. return MEMORY_E;
  10697. }
  10698. #endif
  10699. algoSz = SetAlgoID(ED25519k, algo, oidKeyType, 0);
  10700. bitStringSz = SetBitString(pubSz, 0, bitString);
  10701. idx = SetSequence(pubSz + bitStringSz + algoSz, output);
  10702. /* algo */
  10703. XMEMCPY(output + idx, algo, algoSz);
  10704. idx += algoSz;
  10705. /* bit string */
  10706. XMEMCPY(output + idx, bitString, bitStringSz);
  10707. idx += bitStringSz;
  10708. }
  10709. else
  10710. idx = 0;
  10711. /* pub */
  10712. XMEMCPY(output + idx, pub, pubSz);
  10713. idx += pubSz;
  10714. #ifdef WOLFSSL_SMALL_STACK
  10715. if (with_header) {
  10716. XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10717. }
  10718. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10719. #endif
  10720. return idx;
  10721. }
  10722. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  10723. int withAlg)
  10724. {
  10725. word32 infoSz = 0;
  10726. word32 keySz = 0;
  10727. int ret;
  10728. if (output == NULL || key == NULL) {
  10729. return BAD_FUNC_ARG;
  10730. }
  10731. if (withAlg) {
  10732. /* buffer space for algorithm */
  10733. infoSz += MAX_SEQ_SZ;
  10734. infoSz += MAX_ALGO_SZ;
  10735. /* buffer space for public key sequence */
  10736. infoSz += MAX_SEQ_SZ;
  10737. infoSz += TRAILING_ZERO;
  10738. }
  10739. if ((ret = wc_ed25519_export_public(key, output, &keySz)) != BUFFER_E) {
  10740. WOLFSSL_MSG("Error in getting ECC public key size");
  10741. return ret;
  10742. }
  10743. if (inLen < keySz + infoSz) {
  10744. return BUFFER_E;
  10745. }
  10746. return SetEd25519PublicKey(output, key, withAlg);
  10747. }
  10748. #endif /* HAVE_ED25519 && (WOLFSSL_CERT_GEN || WOLFSSL_KEY_GEN) */
  10749. #if defined(HAVE_ED448) && (defined(WOLFSSL_CERT_GEN) || \
  10750. defined(WOLFSSL_KEY_GEN))
  10751. /* Write a public ECC key to output */
  10752. static int SetEd448PublicKey(byte* output, ed448_key* key, int with_header)
  10753. {
  10754. byte bitString[1 + MAX_LENGTH_SZ + 1];
  10755. int algoSz;
  10756. int bitStringSz;
  10757. int idx;
  10758. word32 pubSz = ED448_PUB_KEY_SIZE;
  10759. #ifdef WOLFSSL_SMALL_STACK
  10760. byte* algo = NULL;
  10761. byte* pub = NULL;
  10762. #else
  10763. byte algo[MAX_ALGO_SZ];
  10764. byte pub[ED448_PUB_KEY_SIZE];
  10765. #endif
  10766. #ifdef WOLFSSL_SMALL_STACK
  10767. pub = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10768. if (pub == NULL)
  10769. return MEMORY_E;
  10770. #endif
  10771. idx = wc_ed448_export_public(key, pub, &pubSz);
  10772. if (idx != 0) {
  10773. #ifdef WOLFSSL_SMALL_STACK
  10774. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10775. #endif
  10776. return idx;
  10777. }
  10778. /* headers */
  10779. if (with_header) {
  10780. #ifdef WOLFSSL_SMALL_STACK
  10781. algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10782. if (algo == NULL) {
  10783. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10784. return MEMORY_E;
  10785. }
  10786. #endif
  10787. algoSz = SetAlgoID(ED448k, algo, oidKeyType, 0);
  10788. bitStringSz = SetBitString(pubSz, 0, bitString);
  10789. idx = SetSequence(pubSz + bitStringSz + algoSz, output);
  10790. /* algo */
  10791. XMEMCPY(output + idx, algo, algoSz);
  10792. idx += algoSz;
  10793. /* bit string */
  10794. XMEMCPY(output + idx, bitString, bitStringSz);
  10795. idx += bitStringSz;
  10796. }
  10797. else
  10798. idx = 0;
  10799. /* pub */
  10800. XMEMCPY(output + idx, pub, pubSz);
  10801. idx += pubSz;
  10802. #ifdef WOLFSSL_SMALL_STACK
  10803. if (with_header) {
  10804. XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10805. }
  10806. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10807. #endif
  10808. return idx;
  10809. }
  10810. int wc_Ed448PublicKeyToDer(ed448_key* key, byte* output, word32 inLen,
  10811. int withAlg)
  10812. {
  10813. word32 infoSz = 0;
  10814. word32 keySz = 0;
  10815. int ret;
  10816. if (output == NULL || key == NULL) {
  10817. return BAD_FUNC_ARG;
  10818. }
  10819. if (withAlg) {
  10820. /* buffer space for algorithm */
  10821. infoSz += MAX_SEQ_SZ;
  10822. infoSz += MAX_ALGO_SZ;
  10823. /* buffer space for public key sequence */
  10824. infoSz += MAX_SEQ_SZ;
  10825. infoSz += TRAILING_ZERO;
  10826. }
  10827. if ((ret = wc_ed448_export_public(key, output, &keySz)) != BUFFER_E) {
  10828. WOLFSSL_MSG("Error in getting ECC public key size");
  10829. return ret;
  10830. }
  10831. if (inLen < keySz + infoSz) {
  10832. return BUFFER_E;
  10833. }
  10834. return SetEd448PublicKey(output, key, withAlg);
  10835. }
  10836. #endif /* HAVE_ED448 && (WOLFSSL_CERT_GEN || WOLFSSL_KEY_GEN) */
  10837. #ifdef WOLFSSL_CERT_GEN
  10838. static WC_INLINE byte itob(int number)
  10839. {
  10840. return (byte)number + 0x30;
  10841. }
  10842. /* write time to output, format */
  10843. static void SetTime(struct tm* date, byte* output)
  10844. {
  10845. int i = 0;
  10846. output[i++] = itob((date->tm_year % 10000) / 1000);
  10847. output[i++] = itob((date->tm_year % 1000) / 100);
  10848. output[i++] = itob((date->tm_year % 100) / 10);
  10849. output[i++] = itob( date->tm_year % 10);
  10850. output[i++] = itob(date->tm_mon / 10);
  10851. output[i++] = itob(date->tm_mon % 10);
  10852. output[i++] = itob(date->tm_mday / 10);
  10853. output[i++] = itob(date->tm_mday % 10);
  10854. output[i++] = itob(date->tm_hour / 10);
  10855. output[i++] = itob(date->tm_hour % 10);
  10856. output[i++] = itob(date->tm_min / 10);
  10857. output[i++] = itob(date->tm_min % 10);
  10858. output[i++] = itob(date->tm_sec / 10);
  10859. output[i++] = itob(date->tm_sec % 10);
  10860. output[i] = 'Z'; /* Zulu profile */
  10861. }
  10862. #ifdef WOLFSSL_ALT_NAMES
  10863. /* Copy Dates from cert, return bytes written */
  10864. static int CopyValidity(byte* output, Cert* cert)
  10865. {
  10866. int seqSz;
  10867. WOLFSSL_ENTER("CopyValidity");
  10868. /* headers and output */
  10869. seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
  10870. if (output) {
  10871. XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
  10872. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  10873. cert->afterDateSz);
  10874. }
  10875. return seqSz + cert->beforeDateSz + cert->afterDateSz;
  10876. }
  10877. #endif
  10878. /* Get Which Name from index */
  10879. const char* GetOneCertName(CertName* name, int idx)
  10880. {
  10881. switch (idx) {
  10882. case 0:
  10883. return name->country;
  10884. case 1:
  10885. return name->state;
  10886. case 2:
  10887. return name->locality;
  10888. case 3:
  10889. return name->sur;
  10890. case 4:
  10891. return name->org;
  10892. case 5:
  10893. return name->unit;
  10894. case 6:
  10895. return name->commonName;
  10896. case 7:
  10897. return name->serialDev;
  10898. #ifdef WOLFSSL_CERT_EXT
  10899. case 8:
  10900. return name->busCat;
  10901. case 9:
  10902. #else
  10903. case 8:
  10904. #endif
  10905. return name->email;
  10906. default:
  10907. return 0;
  10908. }
  10909. }
  10910. /* Get Which Name Encoding from index */
  10911. static char GetNameType(CertName* name, int idx)
  10912. {
  10913. switch (idx) {
  10914. case 0:
  10915. return name->countryEnc;
  10916. case 1:
  10917. return name->stateEnc;
  10918. case 2:
  10919. return name->localityEnc;
  10920. case 3:
  10921. return name->surEnc;
  10922. case 4:
  10923. return name->orgEnc;
  10924. case 5:
  10925. return name->unitEnc;
  10926. case 6:
  10927. return name->commonNameEnc;
  10928. case 7:
  10929. return name->serialDevEnc;
  10930. #ifdef WOLFSSL_CERT_EXT
  10931. case 8:
  10932. return name->busCatEnc;
  10933. case 9:
  10934. #else
  10935. case 8:
  10936. #endif
  10937. /* FALL THROUGH */
  10938. /* The last index, email name, does not have encoding type.
  10939. The empty case here is to keep track of it for future reference. */
  10940. default:
  10941. return 0;
  10942. }
  10943. }
  10944. /* Get ASN Name from index */
  10945. byte GetCertNameId(int idx)
  10946. {
  10947. switch (idx) {
  10948. case 0:
  10949. return ASN_COUNTRY_NAME;
  10950. case 1:
  10951. return ASN_STATE_NAME;
  10952. case 2:
  10953. return ASN_LOCALITY_NAME;
  10954. case 3:
  10955. return ASN_SUR_NAME;
  10956. case 4:
  10957. return ASN_ORG_NAME;
  10958. case 5:
  10959. return ASN_ORGUNIT_NAME;
  10960. case 6:
  10961. return ASN_COMMON_NAME;
  10962. case 7:
  10963. return ASN_SERIAL_NUMBER;
  10964. #ifdef WOLFSSL_CERT_EXT
  10965. case 8:
  10966. return ASN_BUS_CAT;
  10967. case 9:
  10968. #else
  10969. case 8:
  10970. #endif
  10971. return ASN_EMAIL_NAME;
  10972. default:
  10973. return 0;
  10974. }
  10975. }
  10976. /*
  10977. Extensions ::= SEQUENCE OF Extension
  10978. Extension ::= SEQUENCE {
  10979. extnId OBJECT IDENTIFIER,
  10980. critical BOOLEAN DEFAULT FALSE,
  10981. extnValue OCTET STRING }
  10982. */
  10983. /* encode all extensions, return total bytes written */
  10984. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  10985. const byte* ext, int extSz)
  10986. {
  10987. if (out == NULL || IdxInOut == NULL || ext == NULL)
  10988. return BAD_FUNC_ARG;
  10989. if (outSz < (word32)(*IdxInOut+extSz))
  10990. return BUFFER_E;
  10991. XMEMCPY(&out[*IdxInOut], ext, extSz); /* extensions */
  10992. *IdxInOut += extSz;
  10993. return *IdxInOut;
  10994. }
  10995. /* encode extensions header, return total bytes written */
  10996. static int SetExtensionsHeader(byte* out, word32 outSz, int extSz)
  10997. {
  10998. byte sequence[MAX_SEQ_SZ];
  10999. byte len[MAX_LENGTH_SZ];
  11000. int seqSz, lenSz, idx = 0;
  11001. if (out == NULL)
  11002. return BAD_FUNC_ARG;
  11003. if (outSz < 3)
  11004. return BUFFER_E;
  11005. seqSz = SetSequence(extSz, sequence);
  11006. /* encode extensions length provided */
  11007. lenSz = SetLength(extSz+seqSz, len);
  11008. if (outSz < (word32)(lenSz+seqSz+1))
  11009. return BUFFER_E;
  11010. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  11011. XMEMCPY(&out[idx], len, lenSz); /* length */
  11012. idx += lenSz;
  11013. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  11014. idx += seqSz;
  11015. return idx;
  11016. }
  11017. /* encode CA basic constraint true, return total bytes written */
  11018. static int SetCa(byte* out, word32 outSz)
  11019. {
  11020. const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  11021. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
  11022. if (out == NULL)
  11023. return BAD_FUNC_ARG;
  11024. if (outSz < sizeof(ca))
  11025. return BUFFER_E;
  11026. XMEMCPY(out, ca, sizeof(ca));
  11027. return (int)sizeof(ca);
  11028. }
  11029. #ifdef WOLFSSL_CERT_EXT
  11030. /* encode OID and associated value, return total bytes written */
  11031. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  11032. byte *in, word32 inSz)
  11033. {
  11034. int idx = 0;
  11035. if (out == NULL || oid == NULL || in == NULL)
  11036. return BAD_FUNC_ARG;
  11037. if (outSz < 3)
  11038. return BUFFER_E;
  11039. /* sequence, + 1 => byte to put value size */
  11040. idx = SetSequence(inSz + oidSz + 1, out);
  11041. if ((idx + inSz + oidSz + 1) > outSz)
  11042. return BUFFER_E;
  11043. XMEMCPY(out+idx, oid, oidSz);
  11044. idx += oidSz;
  11045. out[idx++] = (byte)inSz;
  11046. XMEMCPY(out+idx, in, inSz);
  11047. return (idx+inSz);
  11048. }
  11049. /* encode Subject Key Identifier, return total bytes written
  11050. * RFC5280 : non-critical */
  11051. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  11052. {
  11053. byte skid_len[1 + MAX_LENGTH_SZ];
  11054. byte skid_enc_len[MAX_LENGTH_SZ];
  11055. int idx = 0, skid_lenSz, skid_enc_lenSz;
  11056. const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  11057. if (output == NULL || input == NULL)
  11058. return BAD_FUNC_ARG;
  11059. /* Octet String header */
  11060. skid_lenSz = SetOctetString(length, skid_len);
  11061. /* length of encoded value */
  11062. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  11063. if (outSz < 3)
  11064. return BUFFER_E;
  11065. idx = SetSequence(length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz,
  11066. output);
  11067. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  11068. return BUFFER_E;
  11069. /* put oid */
  11070. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  11071. idx += sizeof(skid_oid);
  11072. /* put encoded len */
  11073. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  11074. idx += skid_enc_lenSz;
  11075. /* put octet header */
  11076. XMEMCPY(output+idx, skid_len, skid_lenSz);
  11077. idx += skid_lenSz;
  11078. /* put value */
  11079. XMEMCPY(output+idx, input, length);
  11080. idx += length;
  11081. return idx;
  11082. }
  11083. /* encode Authority Key Identifier, return total bytes written
  11084. * RFC5280 : non-critical */
  11085. static int SetAKID(byte* output, word32 outSz,
  11086. byte *input, word32 length, void* heap)
  11087. {
  11088. byte *enc_val;
  11089. int ret, enc_valSz;
  11090. const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04 };
  11091. const byte akid_cs[] = { 0x80 };
  11092. (void)heap;
  11093. if (output == NULL || input == NULL)
  11094. return BAD_FUNC_ARG;
  11095. enc_valSz = length + 3 + sizeof(akid_cs);
  11096. enc_val = (byte *)XMALLOC(enc_valSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  11097. if (enc_val == NULL)
  11098. return MEMORY_E;
  11099. /* sequence for ContentSpec & value */
  11100. ret = SetOidValue(enc_val, enc_valSz, akid_cs, sizeof(akid_cs),
  11101. input, length);
  11102. if (ret > 0) {
  11103. enc_valSz = ret;
  11104. ret = SetOidValue(output, outSz, akid_oid, sizeof(akid_oid),
  11105. enc_val, enc_valSz);
  11106. }
  11107. XFREE(enc_val, heap, DYNAMIC_TYPE_TMP_BUFFER);
  11108. return ret;
  11109. }
  11110. /* encode Key Usage, return total bytes written
  11111. * RFC5280 : critical */
  11112. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  11113. {
  11114. byte ku[5];
  11115. int idx;
  11116. const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  11117. 0x01, 0x01, 0xff, 0x04};
  11118. if (output == NULL)
  11119. return BAD_FUNC_ARG;
  11120. idx = SetBitString16Bit(input, ku);
  11121. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  11122. ku, idx);
  11123. }
  11124. static int SetOjectIdValue(byte* output, word32 outSz, int* idx,
  11125. const byte* oid, word32 oidSz)
  11126. {
  11127. /* verify room */
  11128. if (*idx + 2 + oidSz >= outSz)
  11129. return ASN_PARSE_E;
  11130. *idx += SetObjectId(oidSz, &output[*idx]);
  11131. XMEMCPY(&output[*idx], oid, oidSz);
  11132. *idx += oidSz;
  11133. return 0;
  11134. }
  11135. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  11136. static int SetExtKeyUsage(Cert* cert, byte* output, word32 outSz, byte input)
  11137. {
  11138. int idx = 0, oidListSz = 0, totalSz, ret = 0;
  11139. const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  11140. if (output == NULL)
  11141. return BAD_FUNC_ARG;
  11142. /* Skip to OID List */
  11143. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  11144. idx = totalSz;
  11145. /* Build OID List */
  11146. /* If any set, then just use it */
  11147. if (input & EXTKEYUSE_ANY) {
  11148. ret |= SetOjectIdValue(output, outSz, &idx,
  11149. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  11150. }
  11151. else {
  11152. if (input & EXTKEYUSE_SERVER_AUTH)
  11153. ret |= SetOjectIdValue(output, outSz, &idx,
  11154. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  11155. if (input & EXTKEYUSE_CLIENT_AUTH)
  11156. ret |= SetOjectIdValue(output, outSz, &idx,
  11157. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  11158. if (input & EXTKEYUSE_CODESIGN)
  11159. ret |= SetOjectIdValue(output, outSz, &idx,
  11160. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  11161. if (input & EXTKEYUSE_EMAILPROT)
  11162. ret |= SetOjectIdValue(output, outSz, &idx,
  11163. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  11164. if (input & EXTKEYUSE_TIMESTAMP)
  11165. ret |= SetOjectIdValue(output, outSz, &idx,
  11166. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  11167. if (input & EXTKEYUSE_OCSP_SIGN)
  11168. ret |= SetOjectIdValue(output, outSz, &idx,
  11169. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  11170. #ifdef WOLFSSL_EKU_OID
  11171. /* iterate through OID values */
  11172. if (input & EXTKEYUSE_USER) {
  11173. int i, sz;
  11174. for (i = 0; i < CTC_MAX_EKU_NB; i++) {
  11175. sz = cert->extKeyUsageOIDSz[i];
  11176. if (sz > 0) {
  11177. ret |= SetOjectIdValue(output, outSz, &idx,
  11178. cert->extKeyUsageOID[i], sz);
  11179. }
  11180. }
  11181. }
  11182. #endif /* WOLFSSL_EKU_OID */
  11183. }
  11184. if (ret != 0)
  11185. return ASN_PARSE_E;
  11186. /* Calculate Sizes */
  11187. oidListSz = idx - totalSz;
  11188. totalSz = idx - 2; /* exclude first seq/len (2) */
  11189. /* 1. Seq + Total Len (2) */
  11190. idx = SetSequence(totalSz, output);
  11191. /* 2. Object ID (2) */
  11192. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  11193. idx += sizeof(extkeyusage_oid);
  11194. /* 3. Octet String (2) */
  11195. idx += SetOctetString(totalSz - idx, &output[idx]);
  11196. /* 4. Seq + OidListLen (2) */
  11197. idx += SetSequence(oidListSz, &output[idx]);
  11198. /* 5. Oid List (already set in-place above) */
  11199. idx += oidListSz;
  11200. (void)cert;
  11201. return idx;
  11202. }
  11203. /* encode Certificate Policies, return total bytes written
  11204. * each input value must be ITU-T X.690 formatted : a.b.c...
  11205. * input must be an array of values with a NULL terminated for the latest
  11206. * RFC5280 : non-critical */
  11207. static int SetCertificatePolicies(byte *output,
  11208. word32 outputSz,
  11209. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  11210. word16 nb_certpol,
  11211. void* heap)
  11212. {
  11213. byte oid[MAX_OID_SZ],
  11214. der_oid[MAX_CERTPOL_NB][MAX_OID_SZ],
  11215. out[MAX_CERTPOL_SZ];
  11216. word32 oidSz;
  11217. word32 outSz, i = 0, der_oidSz[MAX_CERTPOL_NB];
  11218. int ret;
  11219. const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  11220. const byte oid_oid[] = { 0x06 };
  11221. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  11222. return BAD_FUNC_ARG;
  11223. for (i = 0; i < nb_certpol; i++) {
  11224. oidSz = sizeof(oid);
  11225. XMEMSET(oid, 0, oidSz);
  11226. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  11227. if (ret != 0)
  11228. return ret;
  11229. /* compute sequence value for the oid */
  11230. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  11231. sizeof(oid_oid), oid, oidSz);
  11232. if (ret <= 0)
  11233. return ret;
  11234. else
  11235. der_oidSz[i] = (word32)ret;
  11236. }
  11237. /* concatenate oid, keep two byte for sequence/size of the created value */
  11238. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  11239. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  11240. outSz += der_oidSz[i];
  11241. }
  11242. /* add sequence */
  11243. ret = SetSequence(outSz-2, out);
  11244. if (ret <= 0)
  11245. return ret;
  11246. /* add Policy OID to compute final value */
  11247. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  11248. out, outSz);
  11249. }
  11250. #endif /* WOLFSSL_CERT_EXT */
  11251. #ifdef WOLFSSL_ALT_NAMES
  11252. /* encode Alternative Names, return total bytes written */
  11253. static int SetAltNames(byte *output, word32 outSz,
  11254. const byte *input, word32 length)
  11255. {
  11256. byte san_len[1 + MAX_LENGTH_SZ];
  11257. int idx = 0, san_lenSz;
  11258. const byte san_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x11 };
  11259. if (output == NULL || input == NULL)
  11260. return BAD_FUNC_ARG;
  11261. if (outSz < length)
  11262. return BUFFER_E;
  11263. /* Octet String header */
  11264. san_lenSz = SetOctetString(length, san_len);
  11265. if (outSz < MAX_SEQ_SZ)
  11266. return BUFFER_E;
  11267. idx = SetSequence(length + sizeof(san_oid) + san_lenSz, output);
  11268. if ((length + sizeof(san_oid) + san_lenSz) > outSz)
  11269. return BUFFER_E;
  11270. /* put oid */
  11271. XMEMCPY(output+idx, san_oid, sizeof(san_oid));
  11272. idx += sizeof(san_oid);
  11273. /* put octet header */
  11274. XMEMCPY(output+idx, san_len, san_lenSz);
  11275. idx += san_lenSz;
  11276. /* put value */
  11277. XMEMCPY(output+idx, input, length);
  11278. idx += length;
  11279. return idx;
  11280. }
  11281. #ifdef WOLFSSL_CERT_GEN
  11282. int FlattenAltNames(byte* output, word32 outputSz, const DNS_entry* names)
  11283. {
  11284. word32 idx;
  11285. const DNS_entry* curName;
  11286. word32 namesSz = 0;
  11287. if (output == NULL)
  11288. return BAD_FUNC_ARG;
  11289. if (names == NULL)
  11290. return 0;
  11291. curName = names;
  11292. do {
  11293. namesSz += curName->len + 2 +
  11294. ((curName->len < ASN_LONG_LENGTH) ? 0
  11295. : BytePrecision(curName->len));
  11296. curName = curName->next;
  11297. } while (curName != NULL);
  11298. if (outputSz < MAX_SEQ_SZ + namesSz)
  11299. return BUFFER_E;
  11300. idx = SetSequence(namesSz, output);
  11301. curName = names;
  11302. do {
  11303. output[idx] = ASN_CONTEXT_SPECIFIC | curName->type;
  11304. if (curName->type == ASN_DIR_TYPE) {
  11305. output[idx] |= ASN_CONSTRUCTED;
  11306. }
  11307. idx++;
  11308. idx += SetLength(curName->len, output + idx);
  11309. XMEMCPY(output + idx, curName->name, curName->len);
  11310. idx += curName->len;
  11311. curName = curName->next;
  11312. } while (curName != NULL);
  11313. return idx;
  11314. }
  11315. #endif /* WOLFSSL_CERT_GEN */
  11316. #endif /* WOLFSSL_ALT_NAMES */
  11317. /* Encodes one attribute of the name (issuer/subject)
  11318. *
  11319. * name structure to hold result of encoding
  11320. * nameStr value to be encoded
  11321. * nameType type of encoding i.e CTC_UTF8
  11322. * type id of attribute i.e ASN_COMMON_NAME
  11323. * emailType type of email i.e CTC_UTF8
  11324. * returns length on success
  11325. */
  11326. static int wc_EncodeName_ex(EncodedName* name, const char* nameStr, char nameType,
  11327. byte type, byte emailType)
  11328. {
  11329. word32 idx = 0;
  11330. /* bottom up */
  11331. byte firstLen[1 + MAX_LENGTH_SZ];
  11332. byte secondLen[MAX_LENGTH_SZ];
  11333. byte sequence[MAX_SEQ_SZ];
  11334. byte set[MAX_SET_SZ];
  11335. int strLen;
  11336. int thisLen;
  11337. int firstSz, secondSz, seqSz, setSz;
  11338. if (nameStr == NULL) {
  11339. name->used = 0;
  11340. return 0;
  11341. }
  11342. thisLen = strLen = (int)XSTRLEN(nameStr);
  11343. if (strLen == 0) { /* no user data for this item */
  11344. name->used = 0;
  11345. return 0;
  11346. }
  11347. /* Restrict country code size */
  11348. if (ASN_COUNTRY_NAME == type && strLen != CTC_COUNTRY_SIZE) {
  11349. WOLFSSL_MSG("Country code size error");
  11350. return ASN_COUNTRY_SIZE_E;
  11351. }
  11352. secondSz = SetLength(strLen, secondLen);
  11353. thisLen += secondSz;
  11354. switch (type) {
  11355. case ASN_EMAIL_NAME: /* email */
  11356. thisLen += EMAIL_JOINT_LEN;
  11357. firstSz = EMAIL_JOINT_LEN;
  11358. break;
  11359. case ASN_DOMAIN_COMPONENT:
  11360. thisLen += PILOT_JOINT_LEN;
  11361. firstSz = PILOT_JOINT_LEN;
  11362. break;
  11363. default:
  11364. thisLen++; /* str type */
  11365. thisLen += JOINT_LEN;
  11366. firstSz = JOINT_LEN + 1;
  11367. }
  11368. thisLen++; /* id type */
  11369. firstSz = SetObjectId(firstSz, firstLen);
  11370. thisLen += firstSz;
  11371. seqSz = SetSequence(thisLen, sequence);
  11372. thisLen += seqSz;
  11373. setSz = SetSet(thisLen, set);
  11374. thisLen += setSz;
  11375. if (thisLen > (int)sizeof(name->encoded)) {
  11376. return BUFFER_E;
  11377. }
  11378. /* store it */
  11379. idx = 0;
  11380. /* set */
  11381. XMEMCPY(name->encoded, set, setSz);
  11382. idx += setSz;
  11383. /* seq */
  11384. XMEMCPY(name->encoded + idx, sequence, seqSz);
  11385. idx += seqSz;
  11386. /* asn object id */
  11387. XMEMCPY(name->encoded + idx, firstLen, firstSz);
  11388. idx += firstSz;
  11389. switch (type) {
  11390. case ASN_EMAIL_NAME:
  11391. {
  11392. const byte EMAIL_OID[] = {
  11393. 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01
  11394. };
  11395. /* email joint id */
  11396. XMEMCPY(name->encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
  11397. idx += (int)sizeof(EMAIL_OID);
  11398. name->encoded[idx++] = emailType;
  11399. break;
  11400. }
  11401. case ASN_DOMAIN_COMPONENT:
  11402. {
  11403. const byte PILOT_OID[] = {
  11404. 0x09, 0x92, 0x26, 0x89, 0x93, 0xF2, 0x2C, 0x64, 0x01
  11405. };
  11406. XMEMCPY(name->encoded + idx, PILOT_OID, sizeof(PILOT_OID));
  11407. idx += (int)sizeof(PILOT_OID);
  11408. /* id type */
  11409. name->encoded[idx++] = type;
  11410. /* str type */
  11411. name->encoded[idx++] = nameType;
  11412. break;
  11413. }
  11414. default:
  11415. name->encoded[idx++] = 0x55;
  11416. name->encoded[idx++] = 0x04;
  11417. /* id type */
  11418. name->encoded[idx++] = type;
  11419. /* str type */
  11420. name->encoded[idx++] = nameType;
  11421. }
  11422. /* second length */
  11423. XMEMCPY(name->encoded + idx, secondLen, secondSz);
  11424. idx += secondSz;
  11425. /* str value */
  11426. XMEMCPY(name->encoded + idx, nameStr, strLen);
  11427. idx += strLen;
  11428. name->type = type;
  11429. name->totalLen = idx;
  11430. name->used = 1;
  11431. return idx;
  11432. }
  11433. /* canonical encoding one attribute of the name (issuer/subject)
  11434. * call wc_EncodeName_ex with CTC_UTF8 for email type
  11435. *
  11436. * name structure to hold result of encoding
  11437. * nameStr value to be encoded
  11438. * nameType type of encoding i.e CTC_UTF8
  11439. * type id of attribute i.e ASN_COMMON_NAME
  11440. *
  11441. * returns length on success
  11442. */
  11443. int wc_EncodeNameCanonical(EncodedName* name, const char* nameStr, char nameType,
  11444. byte type)
  11445. {
  11446. return wc_EncodeName_ex(name, nameStr, nameType, type, 0x0c/* CTC_UTF8 */);
  11447. }
  11448. /* Encodes one attribute of the name (issuer/subject)
  11449. * call we_EncodeName_ex with 0x16, IA5String for email type
  11450. * name structure to hold result of encoding
  11451. * nameStr value to be encoded
  11452. * nameType type of encoding i.e CTC_UTF8
  11453. * type id of attribute i.e ASN_COMMON_NAME
  11454. *
  11455. * returns length on success
  11456. */
  11457. int wc_EncodeName(EncodedName* name, const char* nameStr, char nameType,
  11458. byte type)
  11459. {
  11460. return wc_EncodeName_ex(name, nameStr, nameType, type, ASN_IA5_STRING);
  11461. }
  11462. /* encode CertName into output, return total bytes written */
  11463. int SetName(byte* output, word32 outputSz, CertName* name)
  11464. {
  11465. int totalBytes = 0, i, idx;
  11466. #ifdef WOLFSSL_SMALL_STACK
  11467. EncodedName* names = NULL;
  11468. #else
  11469. EncodedName names[NAME_ENTRIES];
  11470. #endif
  11471. #ifdef WOLFSSL_MULTI_ATTRIB
  11472. EncodedName addNames[CTC_MAX_ATTRIB];
  11473. int j, type;
  11474. #endif
  11475. if (output == NULL || name == NULL)
  11476. return BAD_FUNC_ARG;
  11477. if (outputSz < 3)
  11478. return BUFFER_E;
  11479. #ifdef WOLFSSL_SMALL_STACK
  11480. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  11481. DYNAMIC_TYPE_TMP_BUFFER);
  11482. if (names == NULL)
  11483. return MEMORY_E;
  11484. #endif
  11485. for (i = 0; i < NAME_ENTRIES; i++) {
  11486. int ret;
  11487. const char* nameStr = GetOneCertName(name, i);
  11488. ret = wc_EncodeName(&names[i], nameStr, GetNameType(name, i),
  11489. GetCertNameId(i));
  11490. if (ret < 0) {
  11491. #ifdef WOLFSSL_SMALL_STACK
  11492. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11493. #endif
  11494. WOLFSSL_MSG("EncodeName failed");
  11495. return BUFFER_E;
  11496. }
  11497. totalBytes += ret;
  11498. }
  11499. #ifdef WOLFSSL_MULTI_ATTRIB
  11500. for (i = 0; i < CTC_MAX_ATTRIB; i++) {
  11501. if (name->name[i].sz > 0) {
  11502. int ret;
  11503. ret = wc_EncodeName(&addNames[i], name->name[i].value,
  11504. name->name[i].type, name->name[i].id);
  11505. if (ret < 0) {
  11506. #ifdef WOLFSSL_SMALL_STACK
  11507. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11508. #endif
  11509. WOLFSSL_MSG("EncodeName on multiple attributes failed\n");
  11510. return BUFFER_E;
  11511. }
  11512. totalBytes += ret;
  11513. }
  11514. else {
  11515. addNames[i].used = 0;
  11516. }
  11517. }
  11518. #endif /* WOLFSSL_MULTI_ATTRIB */
  11519. /* header */
  11520. idx = SetSequence(totalBytes, output);
  11521. totalBytes += idx;
  11522. if (totalBytes > ASN_NAME_MAX) {
  11523. #ifdef WOLFSSL_SMALL_STACK
  11524. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11525. #endif
  11526. WOLFSSL_MSG("Total Bytes is greater than ASN_NAME_MAX");
  11527. return BUFFER_E;
  11528. }
  11529. for (i = 0; i < NAME_ENTRIES; i++) {
  11530. #ifdef WOLFSSL_MULTI_ATTRIB
  11531. type = GetCertNameId(i);
  11532. /* list all DC values before OUs */
  11533. if (type == ASN_ORGUNIT_NAME) {
  11534. type = ASN_DOMAIN_COMPONENT;
  11535. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  11536. if (name->name[j].sz > 0 && type == name->name[j].id) {
  11537. if (outputSz < (word32)(idx+addNames[j].totalLen)) {
  11538. #ifdef WOLFSSL_SMALL_STACK
  11539. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11540. #endif
  11541. WOLFSSL_MSG("Not enough space left for DC value");
  11542. return BUFFER_E;
  11543. }
  11544. XMEMCPY(output + idx, addNames[j].encoded,
  11545. addNames[j].totalLen);
  11546. idx += addNames[j].totalLen;
  11547. }
  11548. }
  11549. type = ASN_ORGUNIT_NAME;
  11550. }
  11551. /* write all similar types to the buffer */
  11552. for (j = 0; j < CTC_MAX_ATTRIB; j++) {
  11553. if (name->name[j].sz > 0 && type == name->name[j].id) {
  11554. if (outputSz < (word32)(idx+addNames[j].totalLen)) {
  11555. #ifdef WOLFSSL_SMALL_STACK
  11556. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11557. #endif
  11558. return BUFFER_E;
  11559. }
  11560. XMEMCPY(output + idx, addNames[j].encoded,
  11561. addNames[j].totalLen);
  11562. idx += addNames[j].totalLen;
  11563. }
  11564. }
  11565. #endif /* WOLFSSL_MULTI_ATTRIB */
  11566. if (names[i].used) {
  11567. if (outputSz < (word32)(idx+names[i].totalLen)) {
  11568. #ifdef WOLFSSL_SMALL_STACK
  11569. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11570. #endif
  11571. return BUFFER_E;
  11572. }
  11573. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  11574. idx += names[i].totalLen;
  11575. }
  11576. }
  11577. #ifdef WOLFSSL_SMALL_STACK
  11578. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11579. #endif
  11580. return totalBytes;
  11581. }
  11582. /* Set Date validity from now until now + daysValid
  11583. * return size in bytes written to output, 0 on error */
  11584. static int SetValidity(byte* output, int daysValid)
  11585. {
  11586. byte before[MAX_DATE_SIZE];
  11587. byte after[MAX_DATE_SIZE];
  11588. int beforeSz;
  11589. int afterSz;
  11590. int seqSz;
  11591. time_t now;
  11592. time_t then;
  11593. struct tm* tmpTime;
  11594. struct tm* expandedTime;
  11595. struct tm localTime;
  11596. #if defined(NEED_TMP_TIME)
  11597. /* for use with gmtime_r */
  11598. struct tm tmpTimeStorage;
  11599. tmpTime = &tmpTimeStorage;
  11600. #else
  11601. tmpTime = NULL;
  11602. #endif
  11603. (void)tmpTime;
  11604. now = XTIME(0);
  11605. /* before now */
  11606. before[0] = ASN_GENERALIZED_TIME;
  11607. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  11608. /* subtract 1 day of seconds for more compliance */
  11609. then = now - 86400;
  11610. expandedTime = XGMTIME(&then, tmpTime);
  11611. if (expandedTime == NULL) {
  11612. WOLFSSL_MSG("XGMTIME failed");
  11613. return 0; /* error */
  11614. }
  11615. localTime = *expandedTime;
  11616. /* adjust */
  11617. localTime.tm_year += 1900;
  11618. localTime.tm_mon += 1;
  11619. SetTime(&localTime, before + beforeSz);
  11620. beforeSz += ASN_GEN_TIME_SZ;
  11621. after[0] = ASN_GENERALIZED_TIME;
  11622. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  11623. /* add daysValid of seconds */
  11624. then = now + (daysValid * (time_t)86400);
  11625. expandedTime = XGMTIME(&then, tmpTime);
  11626. if (expandedTime == NULL) {
  11627. WOLFSSL_MSG("XGMTIME failed");
  11628. return 0; /* error */
  11629. }
  11630. localTime = *expandedTime;
  11631. /* adjust */
  11632. localTime.tm_year += 1900;
  11633. localTime.tm_mon += 1;
  11634. SetTime(&localTime, after + afterSz);
  11635. afterSz += ASN_GEN_TIME_SZ;
  11636. /* headers and output */
  11637. seqSz = SetSequence(beforeSz + afterSz, output);
  11638. XMEMCPY(output + seqSz, before, beforeSz);
  11639. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  11640. return seqSz + beforeSz + afterSz;
  11641. }
  11642. /* encode info from cert into DER encoded format */
  11643. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  11644. WC_RNG* rng, const byte* ntruKey, word16 ntruSz, DsaKey* dsaKey,
  11645. ed25519_key* ed25519Key, ed448_key* ed448Key)
  11646. {
  11647. int ret;
  11648. if (cert == NULL || der == NULL || rng == NULL)
  11649. return BAD_FUNC_ARG;
  11650. /* make sure at least one key type is provided */
  11651. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  11652. dsaKey == NULL && ed448Key == NULL && ntruKey == NULL) {
  11653. return PUBLIC_KEY_E;
  11654. }
  11655. /* init */
  11656. XMEMSET(der, 0, sizeof(DerCert));
  11657. /* version */
  11658. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  11659. /* serial number (must be positive) */
  11660. if (cert->serialSz == 0) {
  11661. /* generate random serial */
  11662. cert->serialSz = CTC_GEN_SERIAL_SZ;
  11663. ret = wc_RNG_GenerateBlock(rng, cert->serial, cert->serialSz);
  11664. if (ret != 0)
  11665. return ret;
  11666. /* Clear the top bit to avoid a negative value */
  11667. cert->serial[0] &= 0x7f;
  11668. }
  11669. der->serialSz = SetSerialNumber(cert->serial, cert->serialSz, der->serial,
  11670. sizeof(der->serial), CTC_SERIAL_SIZE);
  11671. if (der->serialSz < 0)
  11672. return der->serialSz;
  11673. /* signature algo */
  11674. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  11675. if (der->sigAlgoSz <= 0)
  11676. return ALGO_ID_E;
  11677. /* public key */
  11678. #ifndef NO_RSA
  11679. if (cert->keyType == RSA_KEY) {
  11680. if (rsaKey == NULL)
  11681. return PUBLIC_KEY_E;
  11682. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  11683. sizeof(der->publicKey), 1);
  11684. }
  11685. #endif
  11686. #ifdef HAVE_ECC
  11687. if (cert->keyType == ECC_KEY) {
  11688. if (eccKey == NULL)
  11689. return PUBLIC_KEY_E;
  11690. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey, 1);
  11691. }
  11692. #endif
  11693. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  11694. if (cert->keyType == DSA_KEY) {
  11695. if (dsaKey == NULL)
  11696. return PUBLIC_KEY_E;
  11697. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  11698. sizeof(der->publicKey), 1);
  11699. }
  11700. #endif
  11701. #ifdef HAVE_ED25519
  11702. if (cert->keyType == ED25519_KEY) {
  11703. if (ed25519Key == NULL)
  11704. return PUBLIC_KEY_E;
  11705. der->publicKeySz = SetEd25519PublicKey(der->publicKey, ed25519Key, 1);
  11706. }
  11707. #endif
  11708. #ifdef HAVE_ED448
  11709. if (cert->keyType == ED448_KEY) {
  11710. if (ed448Key == NULL)
  11711. return PUBLIC_KEY_E;
  11712. der->publicKeySz = SetEd448PublicKey(der->publicKey, ed448Key, 1);
  11713. }
  11714. #endif
  11715. #ifdef HAVE_NTRU
  11716. if (cert->keyType == NTRU_KEY) {
  11717. word32 rc;
  11718. word16 encodedSz;
  11719. if (ntruKey == NULL)
  11720. return PUBLIC_KEY_E;
  11721. rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo(ntruSz,
  11722. ntruKey, &encodedSz, NULL);
  11723. if (rc != NTRU_OK)
  11724. return PUBLIC_KEY_E;
  11725. if (encodedSz > MAX_PUBLIC_KEY_SZ)
  11726. return PUBLIC_KEY_E;
  11727. rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo(ntruSz,
  11728. ntruKey, &encodedSz, der->publicKey);
  11729. if (rc != NTRU_OK)
  11730. return PUBLIC_KEY_E;
  11731. der->publicKeySz = encodedSz;
  11732. }
  11733. #else
  11734. (void)ntruSz;
  11735. #endif /* HAVE_NTRU */
  11736. if (der->publicKeySz <= 0)
  11737. return PUBLIC_KEY_E;
  11738. der->validitySz = 0;
  11739. #ifdef WOLFSSL_ALT_NAMES
  11740. /* date validity copy ? */
  11741. if (cert->beforeDateSz && cert->afterDateSz) {
  11742. der->validitySz = CopyValidity(der->validity, cert);
  11743. if (der->validitySz <= 0)
  11744. return DATE_E;
  11745. }
  11746. #endif
  11747. /* date validity */
  11748. if (der->validitySz == 0) {
  11749. der->validitySz = SetValidity(der->validity, cert->daysValid);
  11750. if (der->validitySz <= 0)
  11751. return DATE_E;
  11752. }
  11753. /* subject name */
  11754. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  11755. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  11756. /* Use the raw subject */
  11757. int idx;
  11758. der->subjectSz = min(sizeof(der->subject),
  11759. (word32)XSTRLEN((const char*)cert->sbjRaw));
  11760. /* header */
  11761. idx = SetSequence(der->subjectSz, der->subject);
  11762. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  11763. return SUBJECT_E;
  11764. }
  11765. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  11766. der->subjectSz);
  11767. der->subjectSz += idx;
  11768. }
  11769. else
  11770. #endif
  11771. {
  11772. /* Use the name structure */
  11773. der->subjectSz = SetName(der->subject, sizeof(der->subject),
  11774. &cert->subject);
  11775. }
  11776. if (der->subjectSz <= 0)
  11777. return SUBJECT_E;
  11778. /* issuer name */
  11779. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  11780. if (XSTRLEN((const char*)cert->issRaw) > 0) {
  11781. /* Use the raw issuer */
  11782. int idx;
  11783. der->issuerSz = min(sizeof(der->issuer),
  11784. (word32)XSTRLEN((const char*)cert->issRaw));
  11785. /* header */
  11786. idx = SetSequence(der->issuerSz, der->issuer);
  11787. if (der->issuerSz + idx > (int)sizeof(der->issuer)) {
  11788. return ISSUER_E;
  11789. }
  11790. XMEMCPY((char*)der->issuer + idx, (const char*)cert->issRaw,
  11791. der->issuerSz);
  11792. der->issuerSz += idx;
  11793. }
  11794. else
  11795. #endif
  11796. {
  11797. /* Use the name structure */
  11798. der->issuerSz = SetName(der->issuer, sizeof(der->issuer),
  11799. cert->selfSigned ? &cert->subject : &cert->issuer);
  11800. }
  11801. if (der->issuerSz <= 0)
  11802. return ISSUER_E;
  11803. /* set the extensions */
  11804. der->extensionsSz = 0;
  11805. /* CA */
  11806. if (cert->isCA) {
  11807. der->caSz = SetCa(der->ca, sizeof(der->ca));
  11808. if (der->caSz <= 0)
  11809. return CA_TRUE_E;
  11810. der->extensionsSz += der->caSz;
  11811. }
  11812. else
  11813. der->caSz = 0;
  11814. #ifdef WOLFSSL_ALT_NAMES
  11815. /* Alternative Name */
  11816. if (cert->altNamesSz) {
  11817. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  11818. cert->altNames, cert->altNamesSz);
  11819. if (der->altNamesSz <= 0)
  11820. return ALT_NAME_E;
  11821. der->extensionsSz += der->altNamesSz;
  11822. }
  11823. else
  11824. der->altNamesSz = 0;
  11825. #endif
  11826. #ifdef WOLFSSL_CERT_EXT
  11827. /* SKID */
  11828. if (cert->skidSz) {
  11829. /* check the provided SKID size */
  11830. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  11831. return SKID_E;
  11832. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  11833. cert (CTC_MAX_SKID_SIZE). */
  11834. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  11835. cert->skid, cert->skidSz);
  11836. if (der->skidSz <= 0)
  11837. return SKID_E;
  11838. der->extensionsSz += der->skidSz;
  11839. }
  11840. else
  11841. der->skidSz = 0;
  11842. /* AKID */
  11843. if (cert->akidSz) {
  11844. /* check the provided AKID size */
  11845. if (cert->akidSz > (int)min(CTC_MAX_AKID_SIZE, sizeof(der->akid)))
  11846. return AKID_E;
  11847. der->akidSz = SetAKID(der->akid, sizeof(der->akid),
  11848. cert->akid, cert->akidSz, cert->heap);
  11849. if (der->akidSz <= 0)
  11850. return AKID_E;
  11851. der->extensionsSz += der->akidSz;
  11852. }
  11853. else
  11854. der->akidSz = 0;
  11855. /* Key Usage */
  11856. if (cert->keyUsage != 0){
  11857. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  11858. cert->keyUsage);
  11859. if (der->keyUsageSz <= 0)
  11860. return KEYUSAGE_E;
  11861. der->extensionsSz += der->keyUsageSz;
  11862. }
  11863. else
  11864. der->keyUsageSz = 0;
  11865. /* Extended Key Usage */
  11866. if (cert->extKeyUsage != 0){
  11867. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  11868. sizeof(der->extKeyUsage), cert->extKeyUsage);
  11869. if (der->extKeyUsageSz <= 0)
  11870. return EXTKEYUSAGE_E;
  11871. der->extensionsSz += der->extKeyUsageSz;
  11872. }
  11873. else
  11874. der->extKeyUsageSz = 0;
  11875. /* Certificate Policies */
  11876. if (cert->certPoliciesNb != 0) {
  11877. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  11878. sizeof(der->certPolicies),
  11879. cert->certPolicies,
  11880. cert->certPoliciesNb,
  11881. cert->heap);
  11882. if (der->certPoliciesSz <= 0)
  11883. return CERTPOLICIES_E;
  11884. der->extensionsSz += der->certPoliciesSz;
  11885. }
  11886. else
  11887. der->certPoliciesSz = 0;
  11888. #endif /* WOLFSSL_CERT_EXT */
  11889. /* put extensions */
  11890. if (der->extensionsSz > 0) {
  11891. /* put the start of extensions sequence (ID, Size) */
  11892. der->extensionsSz = SetExtensionsHeader(der->extensions,
  11893. sizeof(der->extensions),
  11894. der->extensionsSz);
  11895. if (der->extensionsSz <= 0)
  11896. return EXTENSIONS_E;
  11897. /* put CA */
  11898. if (der->caSz) {
  11899. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11900. &der->extensionsSz,
  11901. der->ca, der->caSz);
  11902. if (ret == 0)
  11903. return EXTENSIONS_E;
  11904. }
  11905. #ifdef WOLFSSL_ALT_NAMES
  11906. /* put Alternative Names */
  11907. if (der->altNamesSz) {
  11908. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11909. &der->extensionsSz,
  11910. der->altNames, der->altNamesSz);
  11911. if (ret <= 0)
  11912. return EXTENSIONS_E;
  11913. }
  11914. #endif
  11915. #ifdef WOLFSSL_CERT_EXT
  11916. /* put SKID */
  11917. if (der->skidSz) {
  11918. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11919. &der->extensionsSz,
  11920. der->skid, der->skidSz);
  11921. if (ret <= 0)
  11922. return EXTENSIONS_E;
  11923. }
  11924. /* put AKID */
  11925. if (der->akidSz) {
  11926. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11927. &der->extensionsSz,
  11928. der->akid, der->akidSz);
  11929. if (ret <= 0)
  11930. return EXTENSIONS_E;
  11931. }
  11932. /* put KeyUsage */
  11933. if (der->keyUsageSz) {
  11934. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11935. &der->extensionsSz,
  11936. der->keyUsage, der->keyUsageSz);
  11937. if (ret <= 0)
  11938. return EXTENSIONS_E;
  11939. }
  11940. /* put ExtendedKeyUsage */
  11941. if (der->extKeyUsageSz) {
  11942. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11943. &der->extensionsSz,
  11944. der->extKeyUsage, der->extKeyUsageSz);
  11945. if (ret <= 0)
  11946. return EXTENSIONS_E;
  11947. }
  11948. /* put Certificate Policies */
  11949. if (der->certPoliciesSz) {
  11950. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  11951. &der->extensionsSz,
  11952. der->certPolicies, der->certPoliciesSz);
  11953. if (ret <= 0)
  11954. return EXTENSIONS_E;
  11955. }
  11956. #endif /* WOLFSSL_CERT_EXT */
  11957. }
  11958. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  11959. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  11960. der->extensionsSz;
  11961. return 0;
  11962. }
  11963. /* write DER encoded cert to buffer, size already checked */
  11964. static int WriteCertBody(DerCert* der, byte* buf)
  11965. {
  11966. int idx;
  11967. /* signed part header */
  11968. idx = SetSequence(der->total, buf);
  11969. /* version */
  11970. XMEMCPY(buf + idx, der->version, der->versionSz);
  11971. idx += der->versionSz;
  11972. /* serial */
  11973. XMEMCPY(buf + idx, der->serial, der->serialSz);
  11974. idx += der->serialSz;
  11975. /* sig algo */
  11976. XMEMCPY(buf + idx, der->sigAlgo, der->sigAlgoSz);
  11977. idx += der->sigAlgoSz;
  11978. /* issuer */
  11979. XMEMCPY(buf + idx, der->issuer, der->issuerSz);
  11980. idx += der->issuerSz;
  11981. /* validity */
  11982. XMEMCPY(buf + idx, der->validity, der->validitySz);
  11983. idx += der->validitySz;
  11984. /* subject */
  11985. XMEMCPY(buf + idx, der->subject, der->subjectSz);
  11986. idx += der->subjectSz;
  11987. /* public key */
  11988. XMEMCPY(buf + idx, der->publicKey, der->publicKeySz);
  11989. idx += der->publicKeySz;
  11990. if (der->extensionsSz) {
  11991. /* extensions */
  11992. XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz,
  11993. (int)sizeof(der->extensions)));
  11994. idx += der->extensionsSz;
  11995. }
  11996. return idx;
  11997. }
  11998. /* Make RSA signature from buffer (sz), write to sig (sigSz) */
  11999. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buf, int sz,
  12000. byte* sig, int sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  12001. ed25519_key* ed25519Key, ed448_key* ed448Key, WC_RNG* rng, int sigAlgoType,
  12002. void* heap)
  12003. {
  12004. int digestSz = 0, typeH = 0, ret = 0;
  12005. (void)digestSz;
  12006. (void)typeH;
  12007. (void)buf;
  12008. (void)sz;
  12009. (void)sig;
  12010. (void)sigSz;
  12011. (void)rsaKey;
  12012. (void)eccKey;
  12013. (void)ed25519Key;
  12014. (void)ed448Key;
  12015. (void)rng;
  12016. (void)heap;
  12017. switch (certSignCtx->state) {
  12018. case CERTSIGN_STATE_BEGIN:
  12019. case CERTSIGN_STATE_DIGEST:
  12020. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  12021. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  12022. DYNAMIC_TYPE_TMP_BUFFER);
  12023. if (certSignCtx->digest == NULL) {
  12024. ret = MEMORY_E; goto exit_ms;
  12025. }
  12026. ret = HashForSignature(buf, sz, sigAlgoType, certSignCtx->digest,
  12027. &typeH, &digestSz, 0);
  12028. /* set next state, since WC_PENDING_E rentry for these are not "call again" */
  12029. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  12030. if (ret != 0) {
  12031. goto exit_ms;
  12032. }
  12033. FALL_THROUGH;
  12034. case CERTSIGN_STATE_ENCODE:
  12035. #ifndef NO_RSA
  12036. if (rsaKey) {
  12037. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  12038. DYNAMIC_TYPE_TMP_BUFFER);
  12039. if (certSignCtx->encSig == NULL) {
  12040. ret = MEMORY_E; goto exit_ms;
  12041. }
  12042. /* signature */
  12043. certSignCtx->encSigSz = wc_EncodeSignature(certSignCtx->encSig,
  12044. certSignCtx->digest, digestSz, typeH);
  12045. }
  12046. #endif /* !NO_RSA */
  12047. FALL_THROUGH;
  12048. case CERTSIGN_STATE_DO:
  12049. certSignCtx->state = CERTSIGN_STATE_DO;
  12050. ret = ALGO_ID_E; /* default to error */
  12051. #ifndef NO_RSA
  12052. if (rsaKey) {
  12053. /* signature */
  12054. ret = wc_RsaSSL_Sign(certSignCtx->encSig, certSignCtx->encSigSz,
  12055. sig, sigSz, rsaKey, rng);
  12056. }
  12057. #endif /* !NO_RSA */
  12058. #ifdef HAVE_ECC
  12059. if (!rsaKey && eccKey) {
  12060. word32 outSz = sigSz;
  12061. ret = wc_ecc_sign_hash(certSignCtx->digest, digestSz,
  12062. sig, &outSz, rng, eccKey);
  12063. if (ret == 0)
  12064. ret = outSz;
  12065. }
  12066. #endif /* HAVE_ECC */
  12067. #ifdef HAVE_ED25519
  12068. if (!rsaKey && !eccKey && ed25519Key) {
  12069. word32 outSz = sigSz;
  12070. ret = wc_ed25519_sign_msg(buf, sz, sig, &outSz, ed25519Key);
  12071. if (ret == 0)
  12072. ret = outSz;
  12073. }
  12074. #endif /* HAVE_ECC */
  12075. #ifdef HAVE_ED448
  12076. if (!rsaKey && !eccKey && !ed25519Key && ed448Key) {
  12077. word32 outSz = sigSz;
  12078. ret = wc_ed448_sign_msg(buf, sz, sig, &outSz, ed448Key, NULL, 0);
  12079. if (ret == 0)
  12080. ret = outSz;
  12081. }
  12082. #endif /* HAVE_ECC */
  12083. break;
  12084. }
  12085. exit_ms:
  12086. #ifdef WOLFSSL_ASYNC_CRYPT
  12087. if (ret == WC_PENDING_E) {
  12088. return ret;
  12089. }
  12090. #endif
  12091. #ifndef NO_RSA
  12092. if (rsaKey) {
  12093. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  12094. }
  12095. #endif /* !NO_RSA */
  12096. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  12097. certSignCtx->digest = NULL;
  12098. /* reset state */
  12099. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  12100. return ret;
  12101. }
  12102. /* add signature to end of buffer, size of buffer assumed checked, return
  12103. new length */
  12104. int AddSignature(byte* buf, int bodySz, const byte* sig, int sigSz,
  12105. int sigAlgoType)
  12106. {
  12107. byte seq[MAX_SEQ_SZ];
  12108. int idx = bodySz, seqSz;
  12109. /* algo */
  12110. idx += SetAlgoID(sigAlgoType, buf ? buf + idx : NULL, oidSigType, 0);
  12111. /* bit string */
  12112. idx += SetBitString(sigSz, 0, buf ? buf + idx : NULL);
  12113. /* signature */
  12114. if (buf)
  12115. XMEMCPY(buf + idx, sig, sigSz);
  12116. idx += sigSz;
  12117. /* make room for overall header */
  12118. seqSz = SetSequence(idx, seq);
  12119. if (buf) {
  12120. XMEMMOVE(buf + seqSz, buf, idx);
  12121. XMEMCPY(buf, seq, seqSz);
  12122. }
  12123. return idx + seqSz;
  12124. }
  12125. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  12126. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  12127. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  12128. DsaKey* dsaKey, const byte* ntruKey, word16 ntruSz,
  12129. ed25519_key* ed25519Key, ed448_key* ed448Key)
  12130. {
  12131. int ret;
  12132. #ifdef WOLFSSL_SMALL_STACK
  12133. DerCert* der;
  12134. #else
  12135. DerCert der[1];
  12136. #endif
  12137. if (derBuffer == NULL)
  12138. return BAD_FUNC_ARG;
  12139. if (eccKey)
  12140. cert->keyType = ECC_KEY;
  12141. else if (rsaKey)
  12142. cert->keyType = RSA_KEY;
  12143. else if (dsaKey)
  12144. cert->keyType = DSA_KEY;
  12145. else if (ed25519Key)
  12146. cert->keyType = ED25519_KEY;
  12147. else if (ed448Key)
  12148. cert->keyType = ED448_KEY;
  12149. else if (ntruKey)
  12150. cert->keyType = NTRU_KEY;
  12151. else
  12152. return BAD_FUNC_ARG;
  12153. #ifdef WOLFSSL_SMALL_STACK
  12154. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12155. if (der == NULL)
  12156. return MEMORY_E;
  12157. #endif
  12158. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, ntruKey, ntruSz, dsaKey,
  12159. ed25519Key, ed448Key);
  12160. if (ret == 0) {
  12161. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  12162. ret = BUFFER_E;
  12163. else
  12164. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  12165. }
  12166. #ifdef WOLFSSL_SMALL_STACK
  12167. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12168. #endif
  12169. return ret;
  12170. }
  12171. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  12172. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  12173. void* key, WC_RNG* rng)
  12174. {
  12175. RsaKey* rsaKey = NULL;
  12176. DsaKey* dsaKey = NULL;
  12177. ecc_key* eccKey = NULL;
  12178. ed25519_key* ed25519Key = NULL;
  12179. ed448_key* ed448Key = NULL;
  12180. if (keyType == RSA_TYPE)
  12181. rsaKey = (RsaKey*)key;
  12182. else if (keyType == DSA_TYPE)
  12183. dsaKey = (DsaKey*)key;
  12184. else if (keyType == ECC_TYPE)
  12185. eccKey = (ecc_key*)key;
  12186. else if (keyType == ED25519_TYPE)
  12187. ed25519Key = (ed25519_key*)key;
  12188. else if (keyType == ED448_TYPE)
  12189. ed448Key = (ed448_key*)key;
  12190. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, dsaKey,
  12191. NULL, 0, ed25519Key, ed448Key);
  12192. }
  12193. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  12194. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  12195. ecc_key* eccKey, WC_RNG* rng)
  12196. {
  12197. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, NULL, 0,
  12198. NULL, NULL);
  12199. }
  12200. #ifdef HAVE_NTRU
  12201. int wc_MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
  12202. const byte* ntruKey, word16 keySz, WC_RNG* rng)
  12203. {
  12204. return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, NULL,
  12205. ntruKey, keySz, NULL, NULL);
  12206. }
  12207. #endif /* HAVE_NTRU */
  12208. #ifdef WOLFSSL_CERT_REQ
  12209. static int SetReqAttrib(byte* output, char* pw, int pwPrintableString,
  12210. int extSz)
  12211. {
  12212. const byte erOid[] =
  12213. { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
  12214. 0x09, 0x0e };
  12215. int sz = 0; /* overall size */
  12216. int cpSz = 0; /* Challenge Password section size */
  12217. int cpSeqSz = 0;
  12218. int cpSetSz = 0;
  12219. int cpStrSz = 0;
  12220. int pwSz = 0;
  12221. int erSz = 0; /* Extension Request section size */
  12222. int erSeqSz = 0;
  12223. int erSetSz = 0;
  12224. byte cpSeq[MAX_SEQ_SZ];
  12225. byte cpSet[MAX_SET_SZ];
  12226. byte cpStr[MAX_PRSTR_SZ];
  12227. byte erSeq[MAX_SEQ_SZ];
  12228. byte erSet[MAX_SET_SZ];
  12229. output[0] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  12230. sz++;
  12231. if (pw && pw[0]) {
  12232. pwSz = (int)XSTRLEN(pw);
  12233. if (pwPrintableString) {
  12234. cpStrSz = SetPrintableString(pwSz, cpStr);
  12235. } else {
  12236. cpStrSz = SetUTF8String(pwSz, cpStr);
  12237. }
  12238. cpSetSz = SetSet(cpStrSz + pwSz, cpSet);
  12239. /* +2 for tag and length parts of the TLV triplet */
  12240. cpSeqSz = SetSequence(2 + sizeof(attrChallengePasswordOid) + cpSetSz +
  12241. cpStrSz + pwSz, cpSeq);
  12242. cpSz = cpSeqSz + 2 + sizeof(attrChallengePasswordOid) + cpSetSz +
  12243. cpStrSz + pwSz;
  12244. }
  12245. if (extSz) {
  12246. erSetSz = SetSet(extSz, erSet);
  12247. erSeqSz = SetSequence(erSetSz + sizeof(erOid) + extSz, erSeq);
  12248. erSz = extSz + erSetSz + erSeqSz + sizeof(erOid);
  12249. }
  12250. /* Put the pieces together. */
  12251. sz += SetLength(cpSz + erSz, &output[sz]);
  12252. if (cpSz) {
  12253. XMEMCPY(&output[sz], cpSeq, cpSeqSz);
  12254. sz += cpSeqSz;
  12255. sz += SetObjectId(sizeof(attrChallengePasswordOid), output + sz);
  12256. XMEMCPY(&output[sz], attrChallengePasswordOid,
  12257. sizeof(attrChallengePasswordOid));
  12258. sz += sizeof(attrChallengePasswordOid);
  12259. XMEMCPY(&output[sz], cpSet, cpSetSz);
  12260. sz += cpSetSz;
  12261. XMEMCPY(&output[sz], cpStr, cpStrSz);
  12262. sz += cpStrSz;
  12263. XMEMCPY(&output[sz], pw, pwSz);
  12264. sz += pwSz;
  12265. }
  12266. if (erSz) {
  12267. XMEMCPY(&output[sz], erSeq, erSeqSz);
  12268. sz += erSeqSz;
  12269. XMEMCPY(&output[sz], erOid, sizeof(erOid));
  12270. sz += sizeof(erOid);
  12271. XMEMCPY(&output[sz], erSet, erSetSz);
  12272. sz += erSetSz;
  12273. /* The actual extension data will be tacked onto the output later. */
  12274. }
  12275. return sz;
  12276. }
  12277. /* encode info from cert into DER encoded format */
  12278. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  12279. DsaKey* dsaKey, ecc_key* eccKey,
  12280. ed25519_key* ed25519Key, ed448_key* ed448Key)
  12281. {
  12282. (void)eccKey;
  12283. (void)ed25519Key;
  12284. (void)ed448Key;
  12285. if (cert == NULL || der == NULL)
  12286. return BAD_FUNC_ARG;
  12287. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL &&
  12288. dsaKey == NULL && ed448Key == NULL) {
  12289. return PUBLIC_KEY_E;
  12290. }
  12291. /* init */
  12292. XMEMSET(der, 0, sizeof(DerCert));
  12293. /* version */
  12294. der->versionSz = SetMyVersion(cert->version, der->version, FALSE);
  12295. /* subject name */
  12296. #if defined(WOLFSSL_CERT_EXT) || defined(OPENSSL_EXTRA)
  12297. if (XSTRLEN((const char*)cert->sbjRaw) > 0) {
  12298. /* Use the raw subject */
  12299. int idx;
  12300. der->subjectSz = min(sizeof(der->subject),
  12301. (word32)XSTRLEN((const char*)cert->sbjRaw));
  12302. /* header */
  12303. idx = SetSequence(der->subjectSz, der->subject);
  12304. if (der->subjectSz + idx > (int)sizeof(der->subject)) {
  12305. return SUBJECT_E;
  12306. }
  12307. XMEMCPY((char*)der->subject + idx, (const char*)cert->sbjRaw,
  12308. der->subjectSz);
  12309. der->subjectSz += idx;
  12310. }
  12311. else
  12312. #endif
  12313. {
  12314. der->subjectSz = SetName(der->subject, sizeof(der->subject),
  12315. &cert->subject);
  12316. }
  12317. if (der->subjectSz <= 0)
  12318. return SUBJECT_E;
  12319. /* public key */
  12320. #ifndef NO_RSA
  12321. if (cert->keyType == RSA_KEY) {
  12322. if (rsaKey == NULL)
  12323. return PUBLIC_KEY_E;
  12324. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  12325. sizeof(der->publicKey), 1);
  12326. }
  12327. #endif
  12328. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST)
  12329. if (cert->keyType == DSA_KEY) {
  12330. if (dsaKey == NULL)
  12331. return PUBLIC_KEY_E;
  12332. der->publicKeySz = wc_SetDsaPublicKey(der->publicKey, dsaKey,
  12333. sizeof(der->publicKey), 1);
  12334. }
  12335. #endif
  12336. #ifdef HAVE_ECC
  12337. if (cert->keyType == ECC_KEY) {
  12338. if (eccKey == NULL)
  12339. return PUBLIC_KEY_E;
  12340. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey, 1);
  12341. }
  12342. #endif
  12343. #ifdef HAVE_ED25519
  12344. if (cert->keyType == ED25519_KEY) {
  12345. if (ed25519Key == NULL)
  12346. return PUBLIC_KEY_E;
  12347. der->publicKeySz = SetEd25519PublicKey(der->publicKey, ed25519Key, 1);
  12348. }
  12349. #endif
  12350. #ifdef HAVE_ED448
  12351. if (cert->keyType == ED448_KEY) {
  12352. if (ed448Key == NULL)
  12353. return PUBLIC_KEY_E;
  12354. der->publicKeySz = SetEd448PublicKey(der->publicKey, ed448Key, 1);
  12355. }
  12356. #endif
  12357. if (der->publicKeySz <= 0)
  12358. return PUBLIC_KEY_E;
  12359. /* set the extensions */
  12360. der->extensionsSz = 0;
  12361. /* CA */
  12362. if (cert->isCA) {
  12363. der->caSz = SetCa(der->ca, sizeof(der->ca));
  12364. if (der->caSz <= 0)
  12365. return CA_TRUE_E;
  12366. der->extensionsSz += der->caSz;
  12367. }
  12368. else
  12369. der->caSz = 0;
  12370. #ifdef WOLFSSL_ALT_NAMES
  12371. /* Alternative Name */
  12372. if (cert->altNamesSz) {
  12373. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  12374. cert->altNames, cert->altNamesSz);
  12375. if (der->altNamesSz <= 0)
  12376. return ALT_NAME_E;
  12377. der->extensionsSz += der->altNamesSz;
  12378. }
  12379. else
  12380. der->altNamesSz = 0;
  12381. #endif
  12382. #ifdef WOLFSSL_CERT_EXT
  12383. /* SKID */
  12384. if (cert->skidSz) {
  12385. /* check the provided SKID size */
  12386. if (cert->skidSz > (int)min(CTC_MAX_SKID_SIZE, sizeof(der->skid)))
  12387. return SKID_E;
  12388. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  12389. cert->skid, cert->skidSz);
  12390. if (der->skidSz <= 0)
  12391. return SKID_E;
  12392. der->extensionsSz += der->skidSz;
  12393. }
  12394. else
  12395. der->skidSz = 0;
  12396. /* Key Usage */
  12397. if (cert->keyUsage != 0){
  12398. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  12399. cert->keyUsage);
  12400. if (der->keyUsageSz <= 0)
  12401. return KEYUSAGE_E;
  12402. der->extensionsSz += der->keyUsageSz;
  12403. }
  12404. else
  12405. der->keyUsageSz = 0;
  12406. /* Extended Key Usage */
  12407. if (cert->extKeyUsage != 0){
  12408. der->extKeyUsageSz = SetExtKeyUsage(cert, der->extKeyUsage,
  12409. sizeof(der->extKeyUsage), cert->extKeyUsage);
  12410. if (der->extKeyUsageSz <= 0)
  12411. return EXTKEYUSAGE_E;
  12412. der->extensionsSz += der->extKeyUsageSz;
  12413. }
  12414. else
  12415. der->extKeyUsageSz = 0;
  12416. #endif /* WOLFSSL_CERT_EXT */
  12417. /* put extensions */
  12418. if (der->extensionsSz > 0) {
  12419. int ret;
  12420. /* put the start of sequence (ID, Size) */
  12421. der->extensionsSz = SetSequence(der->extensionsSz, der->extensions);
  12422. if (der->extensionsSz <= 0)
  12423. return EXTENSIONS_E;
  12424. /* put CA */
  12425. if (der->caSz) {
  12426. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  12427. &der->extensionsSz,
  12428. der->ca, der->caSz);
  12429. if (ret <= 0)
  12430. return EXTENSIONS_E;
  12431. }
  12432. #ifdef WOLFSSL_ALT_NAMES
  12433. /* put Alternative Names */
  12434. if (der->altNamesSz) {
  12435. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  12436. &der->extensionsSz,
  12437. der->altNames, der->altNamesSz);
  12438. if (ret <= 0)
  12439. return EXTENSIONS_E;
  12440. }
  12441. #endif
  12442. #ifdef WOLFSSL_CERT_EXT
  12443. /* put SKID */
  12444. if (der->skidSz) {
  12445. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  12446. &der->extensionsSz,
  12447. der->skid, der->skidSz);
  12448. if (ret <= 0)
  12449. return EXTENSIONS_E;
  12450. }
  12451. /* put AKID */
  12452. if (der->akidSz) {
  12453. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  12454. &der->extensionsSz,
  12455. der->akid, der->akidSz);
  12456. if (ret <= 0)
  12457. return EXTENSIONS_E;
  12458. }
  12459. /* put KeyUsage */
  12460. if (der->keyUsageSz) {
  12461. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  12462. &der->extensionsSz,
  12463. der->keyUsage, der->keyUsageSz);
  12464. if (ret <= 0)
  12465. return EXTENSIONS_E;
  12466. }
  12467. /* put ExtendedKeyUsage */
  12468. if (der->extKeyUsageSz) {
  12469. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  12470. &der->extensionsSz,
  12471. der->extKeyUsage, der->extKeyUsageSz);
  12472. if (ret <= 0)
  12473. return EXTENSIONS_E;
  12474. }
  12475. #endif /* WOLFSSL_CERT_EXT */
  12476. }
  12477. der->attribSz = SetReqAttrib(der->attrib, cert->challengePw,
  12478. cert->challengePwPrintableString,
  12479. der->extensionsSz);
  12480. if (der->attribSz <= 0)
  12481. return REQ_ATTRIBUTE_E;
  12482. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  12483. der->extensionsSz + der->attribSz;
  12484. return 0;
  12485. }
  12486. /* write DER encoded cert req to buffer, size already checked */
  12487. static int WriteCertReqBody(DerCert* der, byte* buf)
  12488. {
  12489. int idx;
  12490. /* signed part header */
  12491. idx = SetSequence(der->total, buf);
  12492. /* version */
  12493. if (buf)
  12494. XMEMCPY(buf + idx, der->version, der->versionSz);
  12495. idx += der->versionSz;
  12496. /* subject */
  12497. if (buf)
  12498. XMEMCPY(buf + idx, der->subject, der->subjectSz);
  12499. idx += der->subjectSz;
  12500. /* public key */
  12501. if (buf)
  12502. XMEMCPY(buf + idx, der->publicKey, der->publicKeySz);
  12503. idx += der->publicKeySz;
  12504. /* attributes */
  12505. if (buf)
  12506. XMEMCPY(buf + idx, der->attrib, der->attribSz);
  12507. idx += der->attribSz;
  12508. /* extensions */
  12509. if (der->extensionsSz) {
  12510. if (buf)
  12511. XMEMCPY(buf + idx, der->extensions, min(der->extensionsSz,
  12512. (int)sizeof(der->extensions)));
  12513. idx += der->extensionsSz;
  12514. }
  12515. return idx;
  12516. }
  12517. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  12518. RsaKey* rsaKey, DsaKey* dsaKey, ecc_key* eccKey,
  12519. ed25519_key* ed25519Key, ed448_key* ed448Key)
  12520. {
  12521. int ret;
  12522. #ifdef WOLFSSL_SMALL_STACK
  12523. DerCert* der;
  12524. #else
  12525. DerCert der[1];
  12526. #endif
  12527. if (eccKey)
  12528. cert->keyType = ECC_KEY;
  12529. else if (rsaKey)
  12530. cert->keyType = RSA_KEY;
  12531. else if (dsaKey)
  12532. cert->keyType = DSA_KEY;
  12533. else if (ed25519Key)
  12534. cert->keyType = ED25519_KEY;
  12535. else if (ed448Key)
  12536. cert->keyType = ED448_KEY;
  12537. else
  12538. return BAD_FUNC_ARG;
  12539. #ifdef WOLFSSL_SMALL_STACK
  12540. der = (DerCert*)XMALLOC(sizeof(DerCert), cert->heap,
  12541. DYNAMIC_TYPE_TMP_BUFFER);
  12542. if (der == NULL)
  12543. return MEMORY_E;
  12544. #endif
  12545. ret = EncodeCertReq(cert, der, rsaKey, dsaKey, eccKey, ed25519Key, ed448Key);
  12546. if (ret == 0) {
  12547. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  12548. ret = BUFFER_E;
  12549. else
  12550. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  12551. }
  12552. #ifdef WOLFSSL_SMALL_STACK
  12553. XFREE(der, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12554. #endif
  12555. return ret;
  12556. }
  12557. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  12558. void* key)
  12559. {
  12560. RsaKey* rsaKey = NULL;
  12561. DsaKey* dsaKey = NULL;
  12562. ecc_key* eccKey = NULL;
  12563. ed25519_key* ed25519Key = NULL;
  12564. ed448_key* ed448Key = NULL;
  12565. if (keyType == RSA_TYPE)
  12566. rsaKey = (RsaKey*)key;
  12567. else if (keyType == DSA_TYPE)
  12568. dsaKey = (DsaKey*)key;
  12569. else if (keyType == ECC_TYPE)
  12570. eccKey = (ecc_key*)key;
  12571. else if (keyType == ED25519_TYPE)
  12572. ed25519Key = (ed25519_key*)key;
  12573. else if (keyType == ED448_TYPE)
  12574. ed448Key = (ed448_key*)key;
  12575. return MakeCertReq(cert, derBuffer, derSz, rsaKey, dsaKey, eccKey, ed25519Key,
  12576. ed448Key);
  12577. }
  12578. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  12579. RsaKey* rsaKey, ecc_key* eccKey)
  12580. {
  12581. return MakeCertReq(cert, derBuffer, derSz, rsaKey, NULL, eccKey, NULL, NULL);
  12582. }
  12583. #endif /* WOLFSSL_CERT_REQ */
  12584. static int SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  12585. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  12586. ed448_key* ed448Key, WC_RNG* rng)
  12587. {
  12588. int sigSz = 0;
  12589. void* heap = NULL;
  12590. CertSignCtx* certSignCtx;
  12591. #ifndef WOLFSSL_ASYNC_CRYPT
  12592. CertSignCtx certSignCtx_lcl;
  12593. certSignCtx = &certSignCtx_lcl;
  12594. XMEMSET(certSignCtx, 0, sizeof(CertSignCtx));
  12595. #else
  12596. certSignCtx = NULL;
  12597. #endif
  12598. if (requestSz < 0)
  12599. return requestSz;
  12600. /* locate ctx */
  12601. if (rsaKey) {
  12602. #ifndef NO_RSA
  12603. #ifdef WOLFSSL_ASYNC_CRYPT
  12604. certSignCtx = &rsaKey->certSignCtx;
  12605. #endif
  12606. heap = rsaKey->heap;
  12607. #else
  12608. return NOT_COMPILED_IN;
  12609. #endif /* NO_RSA */
  12610. }
  12611. else if (eccKey) {
  12612. #ifdef HAVE_ECC
  12613. #ifdef WOLFSSL_ASYNC_CRYPT
  12614. certSignCtx = &eccKey->certSignCtx;
  12615. #endif
  12616. heap = eccKey->heap;
  12617. #else
  12618. return NOT_COMPILED_IN;
  12619. #endif /* HAVE_ECC */
  12620. }
  12621. #ifdef WOLFSSL_ASYNC_CRYPT
  12622. if (certSignCtx == NULL) {
  12623. return BAD_FUNC_ARG;
  12624. }
  12625. #endif
  12626. if (certSignCtx->sig == NULL) {
  12627. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  12628. DYNAMIC_TYPE_TMP_BUFFER);
  12629. if (certSignCtx->sig == NULL)
  12630. return MEMORY_E;
  12631. }
  12632. sigSz = MakeSignature(certSignCtx, buf, requestSz, certSignCtx->sig,
  12633. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, ed448Key, rng, sType,
  12634. heap);
  12635. #ifdef WOLFSSL_ASYNC_CRYPT
  12636. if (sigSz == WC_PENDING_E) {
  12637. /* Not free'ing certSignCtx->sig here because it could still be in use
  12638. * with async operations. */
  12639. return sigSz;
  12640. }
  12641. #endif
  12642. if (sigSz >= 0) {
  12643. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  12644. sigSz = BUFFER_E;
  12645. else
  12646. sigSz = AddSignature(buf, requestSz, certSignCtx->sig, sigSz,
  12647. sType);
  12648. }
  12649. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  12650. certSignCtx->sig = NULL;
  12651. return sigSz;
  12652. }
  12653. int wc_SignCert_ex(int requestSz, int sType, byte* buf, word32 buffSz,
  12654. int keyType, void* key, WC_RNG* rng)
  12655. {
  12656. RsaKey* rsaKey = NULL;
  12657. ecc_key* eccKey = NULL;
  12658. ed25519_key* ed25519Key = NULL;
  12659. ed448_key* ed448Key = NULL;
  12660. if (keyType == RSA_TYPE)
  12661. rsaKey = (RsaKey*)key;
  12662. else if (keyType == ECC_TYPE)
  12663. eccKey = (ecc_key*)key;
  12664. else if (keyType == ED25519_TYPE)
  12665. ed25519Key = (ed25519_key*)key;
  12666. else if (keyType == ED448_TYPE)
  12667. ed448Key = (ed448_key*)key;
  12668. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, ed25519Key,
  12669. ed448Key, rng);
  12670. }
  12671. int wc_SignCert(int requestSz, int sType, byte* buf, word32 buffSz,
  12672. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  12673. {
  12674. return SignCert(requestSz, sType, buf, buffSz, rsaKey, eccKey, NULL, NULL,
  12675. rng);
  12676. }
  12677. int wc_MakeSelfCert(Cert* cert, byte* buf, word32 buffSz,
  12678. RsaKey* key, WC_RNG* rng)
  12679. {
  12680. int ret;
  12681. ret = wc_MakeCert(cert, buf, buffSz, key, NULL, rng);
  12682. if (ret < 0)
  12683. return ret;
  12684. return wc_SignCert(cert->bodySz, cert->sigType,
  12685. buf, buffSz, key, NULL, rng);
  12686. }
  12687. #ifdef WOLFSSL_CERT_EXT
  12688. /* Get raw subject from cert, which may contain OIDs not parsed by Decode.
  12689. The raw subject pointer will only be valid while "cert" is valid. */
  12690. int wc_GetSubjectRaw(byte **subjectRaw, Cert *cert)
  12691. {
  12692. int rc = BAD_FUNC_ARG;
  12693. if ((subjectRaw != NULL) && (cert != NULL)) {
  12694. *subjectRaw = cert->sbjRaw;
  12695. rc = 0;
  12696. }
  12697. return rc;
  12698. }
  12699. /* Set KID from public key */
  12700. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  12701. byte *ntruKey, word16 ntruKeySz,
  12702. ed25519_key* ed25519Key, ed448_key* ed448Key,
  12703. int kid_type)
  12704. {
  12705. byte *buf;
  12706. int bufferSz, ret;
  12707. if (cert == NULL ||
  12708. (rsakey == NULL && eckey == NULL && ntruKey == NULL &&
  12709. ed25519Key == NULL && ed448Key == NULL) ||
  12710. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  12711. return BAD_FUNC_ARG;
  12712. buf = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  12713. DYNAMIC_TYPE_TMP_BUFFER);
  12714. if (buf == NULL)
  12715. return MEMORY_E;
  12716. /* Public Key */
  12717. bufferSz = -1;
  12718. #ifndef NO_RSA
  12719. /* RSA public key */
  12720. if (rsakey != NULL)
  12721. bufferSz = SetRsaPublicKey(buf, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  12722. #endif
  12723. #ifdef HAVE_ECC
  12724. /* ECC public key */
  12725. if (eckey != NULL)
  12726. bufferSz = SetEccPublicKey(buf, eckey, 0);
  12727. #endif
  12728. #ifdef HAVE_NTRU
  12729. /* NTRU public key */
  12730. if (ntruKey != NULL) {
  12731. bufferSz = MAX_PUBLIC_KEY_SZ;
  12732. ret = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo(
  12733. ntruKeySz, ntruKey, (word16 *)(&bufferSz), buf);
  12734. if (ret != NTRU_OK)
  12735. bufferSz = -1;
  12736. }
  12737. #else
  12738. (void)ntruKeySz;
  12739. #endif
  12740. #ifdef HAVE_ED25519
  12741. /* ED25519 public key */
  12742. if (ed25519Key != NULL)
  12743. bufferSz = SetEd25519PublicKey(buf, ed25519Key, 0);
  12744. #endif
  12745. #ifdef HAVE_ED448
  12746. /* ED448 public key */
  12747. if (ed448Key != NULL)
  12748. bufferSz = SetEd448PublicKey(buf, ed448Key, 0);
  12749. #endif
  12750. if (bufferSz <= 0) {
  12751. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12752. return PUBLIC_KEY_E;
  12753. }
  12754. /* Compute SKID by hashing public key */
  12755. if (kid_type == SKID_TYPE) {
  12756. ret = CalcHashId(buf, bufferSz, cert->skid);
  12757. cert->skidSz = KEYID_SIZE;
  12758. }
  12759. else if (kid_type == AKID_TYPE) {
  12760. ret = CalcHashId(buf, bufferSz, cert->akid);
  12761. cert->akidSz = KEYID_SIZE;
  12762. }
  12763. else
  12764. ret = BAD_FUNC_ARG;
  12765. XFREE(buf, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12766. return ret;
  12767. }
  12768. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  12769. {
  12770. RsaKey* rsaKey = NULL;
  12771. ecc_key* eccKey = NULL;
  12772. ed25519_key* ed25519Key = NULL;
  12773. ed448_key* ed448Key = NULL;
  12774. if (keyType == RSA_TYPE)
  12775. rsaKey = (RsaKey*)key;
  12776. else if (keyType == ECC_TYPE)
  12777. eccKey = (ecc_key*)key;
  12778. else if (keyType == ED25519_TYPE)
  12779. ed25519Key = (ed25519_key*)key;
  12780. else if (keyType == ED448_TYPE)
  12781. ed448Key = (ed448_key*)key;
  12782. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, NULL, 0, ed25519Key,
  12783. ed448Key, SKID_TYPE);
  12784. }
  12785. /* Set SKID from RSA or ECC public key */
  12786. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  12787. {
  12788. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, 0, NULL, NULL,
  12789. SKID_TYPE);
  12790. }
  12791. #ifdef HAVE_NTRU
  12792. /* Set SKID from NTRU public key */
  12793. int wc_SetSubjectKeyIdFromNtruPublicKey(Cert *cert,
  12794. byte *ntruKey, word16 ntruKeySz)
  12795. {
  12796. return SetKeyIdFromPublicKey(cert, NULL,NULL,ntruKey, ntruKeySz, NULL, NULL,
  12797. SKID_TYPE);
  12798. }
  12799. #endif
  12800. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  12801. {
  12802. RsaKey* rsaKey = NULL;
  12803. ecc_key* eccKey = NULL;
  12804. ed25519_key* ed25519Key = NULL;
  12805. ed448_key* ed448Key = NULL;
  12806. if (keyType == RSA_TYPE)
  12807. rsaKey = (RsaKey*)key;
  12808. else if (keyType == ECC_TYPE)
  12809. eccKey = (ecc_key*)key;
  12810. else if (keyType == ED25519_TYPE)
  12811. ed25519Key = (ed25519_key*)key;
  12812. else if (keyType == ED448_TYPE)
  12813. ed448Key = (ed448_key*)key;
  12814. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, NULL, 0, ed25519Key,
  12815. ed448Key, AKID_TYPE);
  12816. }
  12817. /* Set SKID from RSA or ECC public key */
  12818. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  12819. {
  12820. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, 0, NULL, NULL,
  12821. AKID_TYPE);
  12822. }
  12823. #if !defined(NO_FILESYSTEM) && !defined(NO_ASN_CRYPT)
  12824. /* Set SKID from public key file in PEM */
  12825. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  12826. {
  12827. int ret, derSz;
  12828. byte* der;
  12829. word32 idx;
  12830. RsaKey *rsakey = NULL;
  12831. ecc_key *eckey = NULL;
  12832. if (cert == NULL || file == NULL)
  12833. return BAD_FUNC_ARG;
  12834. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  12835. if (der == NULL) {
  12836. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  12837. return MEMORY_E;
  12838. }
  12839. derSz = MAX_PUBLIC_KEY_SZ;
  12840. XMEMSET(der, 0, derSz);
  12841. derSz = wc_PemPubKeyToDer(file, der, derSz);
  12842. if (derSz <= 0) {
  12843. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12844. return derSz;
  12845. }
  12846. /* Load PubKey in internal structure */
  12847. #ifndef NO_RSA
  12848. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  12849. if (rsakey == NULL) {
  12850. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12851. return MEMORY_E;
  12852. }
  12853. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  12854. WOLFSSL_MSG("wc_InitRsaKey failure");
  12855. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  12856. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12857. return MEMORY_E;
  12858. }
  12859. idx = 0;
  12860. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, derSz);
  12861. if (ret != 0)
  12862. #endif
  12863. {
  12864. #ifndef NO_RSA
  12865. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  12866. wc_FreeRsaKey(rsakey);
  12867. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  12868. rsakey = NULL;
  12869. #endif
  12870. #ifdef HAVE_ECC
  12871. /* Check to load ecc public key */
  12872. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  12873. DYNAMIC_TYPE_ECC);
  12874. if (eckey == NULL) {
  12875. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12876. return MEMORY_E;
  12877. }
  12878. if (wc_ecc_init(eckey) != 0) {
  12879. WOLFSSL_MSG("wc_ecc_init failure");
  12880. wc_ecc_free(eckey);
  12881. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  12882. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12883. return MEMORY_E;
  12884. }
  12885. idx = 0;
  12886. ret = wc_EccPublicKeyDecode(der, &idx, eckey, derSz);
  12887. if (ret != 0) {
  12888. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  12889. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12890. wc_ecc_free(eckey);
  12891. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  12892. return PUBLIC_KEY_E;
  12893. }
  12894. #else
  12895. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12896. return PUBLIC_KEY_E;
  12897. #endif /* HAVE_ECC */
  12898. }
  12899. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12900. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  12901. #ifndef NO_RSA
  12902. wc_FreeRsaKey(rsakey);
  12903. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  12904. #endif
  12905. #ifdef HAVE_ECC
  12906. wc_ecc_free(eckey);
  12907. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  12908. #endif
  12909. return ret;
  12910. }
  12911. #endif /* !NO_FILESYSTEM && !NO_ASN_CRYPT */
  12912. static int SetAuthKeyIdFromDcert(Cert* cert, DecodedCert* decoded)
  12913. {
  12914. int ret = 0;
  12915. /* Subject Key Id not found !! */
  12916. if (decoded->extSubjKeyIdSet == 0) {
  12917. ret = ASN_NO_SKID;
  12918. }
  12919. /* SKID invalid size */
  12920. else if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  12921. ret = MEMORY_E;
  12922. }
  12923. else {
  12924. /* Put the SKID of CA to AKID of certificate */
  12925. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  12926. cert->akidSz = KEYID_SIZE;
  12927. }
  12928. return ret;
  12929. }
  12930. /* Set AKID from certificate contains in buffer (DER encoded) */
  12931. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  12932. {
  12933. int ret = 0;
  12934. if (cert == NULL) {
  12935. ret = BAD_FUNC_ARG;
  12936. }
  12937. else {
  12938. /* Check if decodedCert is cached */
  12939. if (cert->der != der) {
  12940. /* Allocate cache for the decoded cert */
  12941. ret = wc_SetCert_LoadDer(cert, der, derSz);
  12942. }
  12943. if (ret >= 0) {
  12944. ret = SetAuthKeyIdFromDcert(cert, (DecodedCert*)cert->decodedCert);
  12945. #ifndef WOLFSSL_CERT_GEN_CACHE
  12946. wc_SetCert_Free(cert);
  12947. #endif
  12948. }
  12949. }
  12950. return ret;
  12951. }
  12952. #ifndef NO_FILESYSTEM
  12953. /* Set AKID from certificate file in PEM */
  12954. int wc_SetAuthKeyId(Cert *cert, const char* file)
  12955. {
  12956. int ret;
  12957. int derSz;
  12958. byte* der;
  12959. if (cert == NULL || file == NULL)
  12960. return BAD_FUNC_ARG;
  12961. der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  12962. if (der == NULL) {
  12963. WOLFSSL_MSG("wc_SetAuthKeyId OOF Problem");
  12964. return MEMORY_E;
  12965. }
  12966. derSz = wc_PemCertToDer(file, der, EIGHTK_BUF);
  12967. if (derSz <= 0)
  12968. {
  12969. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12970. return derSz;
  12971. }
  12972. ret = wc_SetAuthKeyIdFromCert(cert, der, derSz);
  12973. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  12974. return ret;
  12975. }
  12976. #endif /* !NO_FILESYSTEM */
  12977. /* Set KeyUsage from human readable string */
  12978. int wc_SetKeyUsage(Cert *cert, const char *value)
  12979. {
  12980. int ret = 0;
  12981. char *token, *str, *ptr;
  12982. word32 len;
  12983. if (cert == NULL || value == NULL)
  12984. return BAD_FUNC_ARG;
  12985. cert->keyUsage = 0;
  12986. /* duplicate string (including terminator) */
  12987. len = (word32)XSTRLEN(value);
  12988. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12989. if (str == NULL)
  12990. return MEMORY_E;
  12991. XMEMCPY(str, value, len+1);
  12992. /* parse value, and set corresponding Key Usage value */
  12993. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  12994. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  12995. return KEYUSAGE_E;
  12996. }
  12997. while (token != NULL)
  12998. {
  12999. len = (word32)XSTRLEN(token);
  13000. if (!XSTRNCASECMP(token, "digitalSignature", len))
  13001. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  13002. else if (!XSTRNCASECMP(token, "nonRepudiation", len) ||
  13003. !XSTRNCASECMP(token, "contentCommitment", len))
  13004. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  13005. else if (!XSTRNCASECMP(token, "keyEncipherment", len))
  13006. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  13007. else if (!XSTRNCASECMP(token, "dataEncipherment", len))
  13008. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  13009. else if (!XSTRNCASECMP(token, "keyAgreement", len))
  13010. cert->keyUsage |= KEYUSE_KEY_AGREE;
  13011. else if (!XSTRNCASECMP(token, "keyCertSign", len))
  13012. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  13013. else if (!XSTRNCASECMP(token, "cRLSign", len))
  13014. cert->keyUsage |= KEYUSE_CRL_SIGN;
  13015. else if (!XSTRNCASECMP(token, "encipherOnly", len))
  13016. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  13017. else if (!XSTRNCASECMP(token, "decipherOnly", len))
  13018. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  13019. else {
  13020. ret = KEYUSAGE_E;
  13021. break;
  13022. }
  13023. token = XSTRTOK(NULL, ",", &ptr);
  13024. }
  13025. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13026. return ret;
  13027. }
  13028. /* Set ExtendedKeyUsage from human readable string */
  13029. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  13030. {
  13031. int ret = 0;
  13032. char *token, *str, *ptr;
  13033. word32 len;
  13034. if (cert == NULL || value == NULL)
  13035. return BAD_FUNC_ARG;
  13036. cert->extKeyUsage = 0;
  13037. /* duplicate string (including terminator) */
  13038. len = (word32)XSTRLEN(value);
  13039. str = (char*)XMALLOC(len+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13040. if (str == NULL)
  13041. return MEMORY_E;
  13042. XMEMCPY(str, value, len+1);
  13043. /* parse value, and set corresponding Key Usage value */
  13044. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  13045. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13046. return EXTKEYUSAGE_E;
  13047. }
  13048. while (token != NULL)
  13049. {
  13050. len = (word32)XSTRLEN(token);
  13051. if (!XSTRNCASECMP(token, "any", len))
  13052. cert->extKeyUsage |= EXTKEYUSE_ANY;
  13053. else if (!XSTRNCASECMP(token, "serverAuth", len))
  13054. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  13055. else if (!XSTRNCASECMP(token, "clientAuth", len))
  13056. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  13057. else if (!XSTRNCASECMP(token, "codeSigning", len))
  13058. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  13059. else if (!XSTRNCASECMP(token, "emailProtection", len))
  13060. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  13061. else if (!XSTRNCASECMP(token, "timeStamping", len))
  13062. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  13063. else if (!XSTRNCASECMP(token, "OCSPSigning", len))
  13064. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  13065. else {
  13066. ret = EXTKEYUSAGE_E;
  13067. break;
  13068. }
  13069. token = XSTRTOK(NULL, ",", &ptr);
  13070. }
  13071. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13072. return ret;
  13073. }
  13074. #ifdef WOLFSSL_EKU_OID
  13075. /*
  13076. * cert structure to set EKU oid in
  13077. * oid the oid in byte representation
  13078. * sz size of oid buffer
  13079. * idx index of array to place oid
  13080. *
  13081. * returns 0 on success
  13082. */
  13083. int wc_SetExtKeyUsageOID(Cert *cert, const char *in, word32 sz, byte idx,
  13084. void* heap)
  13085. {
  13086. byte oid[MAX_OID_SZ];
  13087. word32 oidSz = MAX_OID_SZ;
  13088. if (idx >= CTC_MAX_EKU_NB || sz >= CTC_MAX_EKU_OID_SZ) {
  13089. WOLFSSL_MSG("Either idx or sz was too large");
  13090. return BAD_FUNC_ARG;
  13091. }
  13092. if (EncodePolicyOID(oid, &oidSz, in, heap) != 0) {
  13093. return BUFFER_E;
  13094. }
  13095. XMEMCPY(cert->extKeyUsageOID[idx], oid, oidSz);
  13096. cert->extKeyUsageOIDSz[idx] = oidSz;
  13097. cert->extKeyUsage |= EXTKEYUSE_USER;
  13098. return 0;
  13099. }
  13100. #endif /* WOLFSSL_EKU_OID */
  13101. #endif /* WOLFSSL_CERT_EXT */
  13102. #ifdef WOLFSSL_ALT_NAMES
  13103. static int SetAltNamesFromDcert(Cert* cert, DecodedCert* decoded)
  13104. {
  13105. int ret = 0;
  13106. cert->altNamesSz = 0;
  13107. if (decoded->altNames) {
  13108. ret = FlattenAltNames(cert->altNames,
  13109. sizeof(cert->altNames), decoded->altNames);
  13110. if (ret >= 0) {
  13111. cert->altNamesSz = ret;
  13112. ret = 0;
  13113. }
  13114. }
  13115. return ret;
  13116. }
  13117. #ifndef NO_FILESYSTEM
  13118. /* Set Alt Names from der cert, return 0 on success */
  13119. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
  13120. {
  13121. int ret;
  13122. #ifdef WOLFSSL_SMALL_STACK
  13123. DecodedCert* decoded;
  13124. #else
  13125. DecodedCert decoded[1];
  13126. #endif
  13127. if (derSz < 0)
  13128. return derSz;
  13129. #ifdef WOLFSSL_SMALL_STACK
  13130. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), cert->heap,
  13131. DYNAMIC_TYPE_TMP_BUFFER);
  13132. if (decoded == NULL)
  13133. return MEMORY_E;
  13134. #endif
  13135. InitDecodedCert(decoded, der, derSz, NULL);
  13136. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  13137. if (ret < 0) {
  13138. WOLFSSL_MSG("ParseCertRelative error");
  13139. }
  13140. else {
  13141. ret = SetAltNamesFromDcert(cert, decoded);
  13142. }
  13143. FreeDecodedCert(decoded);
  13144. #ifdef WOLFSSL_SMALL_STACK
  13145. XFREE(decoded, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13146. #endif
  13147. return ret < 0 ? ret : 0;
  13148. }
  13149. #endif
  13150. static int SetDatesFromDcert(Cert* cert, DecodedCert* decoded)
  13151. {
  13152. int ret = 0;
  13153. if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  13154. WOLFSSL_MSG("Couldn't extract dates");
  13155. ret = -1;
  13156. }
  13157. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  13158. decoded->afterDateLen > MAX_DATE_SIZE) {
  13159. WOLFSSL_MSG("Bad date size");
  13160. ret = -1;
  13161. }
  13162. else {
  13163. XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen);
  13164. XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen);
  13165. cert->beforeDateSz = decoded->beforeDateLen;
  13166. cert->afterDateSz = decoded->afterDateLen;
  13167. }
  13168. return ret;
  13169. }
  13170. #endif /* WOLFSSL_ALT_NAMES */
  13171. static void SetNameFromDcert(CertName* cn, DecodedCert* decoded)
  13172. {
  13173. int sz;
  13174. if (decoded->subjectCN) {
  13175. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  13176. : CTC_NAME_SIZE - 1;
  13177. XSTRNCPY(cn->commonName, decoded->subjectCN, sz);
  13178. cn->commonName[sz] = '\0';
  13179. cn->commonNameEnc = decoded->subjectCNEnc;
  13180. }
  13181. if (decoded->subjectC) {
  13182. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  13183. : CTC_NAME_SIZE - 1;
  13184. XSTRNCPY(cn->country, decoded->subjectC, sz);
  13185. cn->country[sz] = '\0';
  13186. cn->countryEnc = decoded->subjectCEnc;
  13187. }
  13188. if (decoded->subjectST) {
  13189. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  13190. : CTC_NAME_SIZE - 1;
  13191. XSTRNCPY(cn->state, decoded->subjectST, sz);
  13192. cn->state[sz] = '\0';
  13193. cn->stateEnc = decoded->subjectSTEnc;
  13194. }
  13195. if (decoded->subjectL) {
  13196. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  13197. : CTC_NAME_SIZE - 1;
  13198. XSTRNCPY(cn->locality, decoded->subjectL, sz);
  13199. cn->locality[sz] = '\0';
  13200. cn->localityEnc = decoded->subjectLEnc;
  13201. }
  13202. if (decoded->subjectO) {
  13203. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  13204. : CTC_NAME_SIZE - 1;
  13205. XSTRNCPY(cn->org, decoded->subjectO, sz);
  13206. cn->org[sz] = '\0';
  13207. cn->orgEnc = decoded->subjectOEnc;
  13208. }
  13209. if (decoded->subjectOU) {
  13210. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  13211. : CTC_NAME_SIZE - 1;
  13212. XSTRNCPY(cn->unit, decoded->subjectOU, sz);
  13213. cn->unit[sz] = '\0';
  13214. cn->unitEnc = decoded->subjectOUEnc;
  13215. }
  13216. if (decoded->subjectSN) {
  13217. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  13218. : CTC_NAME_SIZE - 1;
  13219. XSTRNCPY(cn->sur, decoded->subjectSN, sz);
  13220. cn->sur[sz] = '\0';
  13221. cn->surEnc = decoded->subjectSNEnc;
  13222. }
  13223. if (decoded->subjectSND) {
  13224. sz = (decoded->subjectSNDLen < CTC_NAME_SIZE) ? decoded->subjectSNDLen
  13225. : CTC_NAME_SIZE - 1;
  13226. XSTRNCPY(cn->serialDev, decoded->subjectSND, sz);
  13227. cn->serialDev[sz] = '\0';
  13228. cn->serialDevEnc = decoded->subjectSNDEnc;
  13229. }
  13230. #ifdef WOLFSSL_CERT_EXT
  13231. if (decoded->subjectBC) {
  13232. sz = (decoded->subjectBCLen < CTC_NAME_SIZE) ? decoded->subjectBCLen
  13233. : CTC_NAME_SIZE - 1;
  13234. XSTRNCPY(cn->busCat, decoded->subjectBC, sz);
  13235. cn->busCat[sz] = '\0';
  13236. cn->busCatEnc = decoded->subjectBCEnc;
  13237. }
  13238. if (decoded->subjectJC) {
  13239. sz = (decoded->subjectJCLen < CTC_NAME_SIZE) ? decoded->subjectJCLen
  13240. : CTC_NAME_SIZE - 1;
  13241. XSTRNCPY(cn->joiC, decoded->subjectJC, sz);
  13242. cn->joiC[sz] = '\0';
  13243. cn->joiCEnc = decoded->subjectJCEnc;
  13244. }
  13245. if (decoded->subjectJS) {
  13246. sz = (decoded->subjectJSLen < CTC_NAME_SIZE) ? decoded->subjectJSLen
  13247. : CTC_NAME_SIZE - 1;
  13248. XSTRNCPY(cn->joiSt, decoded->subjectJS, sz);
  13249. cn->joiSt[sz] = '\0';
  13250. cn->joiStEnc = decoded->subjectJSEnc;
  13251. }
  13252. #endif
  13253. if (decoded->subjectEmail) {
  13254. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  13255. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  13256. XSTRNCPY(cn->email, decoded->subjectEmail, sz);
  13257. cn->email[sz] = '\0';
  13258. }
  13259. }
  13260. #ifndef NO_FILESYSTEM
  13261. /* Set cn name from der buffer, return 0 on success */
  13262. static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
  13263. {
  13264. int ret;
  13265. #ifdef WOLFSSL_SMALL_STACK
  13266. DecodedCert* decoded;
  13267. #else
  13268. DecodedCert decoded[1];
  13269. #endif
  13270. if (derSz < 0)
  13271. return derSz;
  13272. #ifdef WOLFSSL_SMALL_STACK
  13273. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  13274. DYNAMIC_TYPE_TMP_BUFFER);
  13275. if (decoded == NULL)
  13276. return MEMORY_E;
  13277. #endif
  13278. InitDecodedCert(decoded, der, derSz, NULL);
  13279. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  13280. if (ret < 0) {
  13281. WOLFSSL_MSG("ParseCertRelative error");
  13282. }
  13283. else {
  13284. SetNameFromDcert(cn, decoded);
  13285. }
  13286. FreeDecodedCert(decoded);
  13287. #ifdef WOLFSSL_SMALL_STACK
  13288. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13289. #endif
  13290. return ret < 0 ? ret : 0;
  13291. }
  13292. /* Set cert issuer from issuerFile in PEM */
  13293. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  13294. {
  13295. int ret;
  13296. int derSz;
  13297. byte* der;
  13298. if (cert == NULL) {
  13299. return BAD_FUNC_ARG;
  13300. }
  13301. der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  13302. if (der == NULL) {
  13303. WOLFSSL_MSG("wc_SetIssuer OOF Problem");
  13304. return MEMORY_E;
  13305. }
  13306. derSz = wc_PemCertToDer(issuerFile, der, EIGHTK_BUF);
  13307. cert->selfSigned = 0;
  13308. ret = SetNameFromCert(&cert->issuer, der, derSz);
  13309. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  13310. return ret;
  13311. }
  13312. /* Set cert subject from subjectFile in PEM */
  13313. int wc_SetSubject(Cert* cert, const char* subjectFile)
  13314. {
  13315. int ret;
  13316. int derSz;
  13317. byte* der;
  13318. if (cert == NULL) {
  13319. return BAD_FUNC_ARG;
  13320. }
  13321. der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  13322. if (der == NULL) {
  13323. WOLFSSL_MSG("wc_SetSubject OOF Problem");
  13324. return MEMORY_E;
  13325. }
  13326. derSz = wc_PemCertToDer(subjectFile, der, EIGHTK_BUF);
  13327. ret = SetNameFromCert(&cert->subject, der, derSz);
  13328. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  13329. return ret;
  13330. }
  13331. #ifdef WOLFSSL_ALT_NAMES
  13332. /* Set alt names from file in PEM */
  13333. int wc_SetAltNames(Cert* cert, const char* file)
  13334. {
  13335. int ret;
  13336. int derSz;
  13337. byte* der;
  13338. if (cert == NULL) {
  13339. return BAD_FUNC_ARG;
  13340. }
  13341. der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  13342. if (der == NULL) {
  13343. WOLFSSL_MSG("wc_SetAltNames OOF Problem");
  13344. return MEMORY_E;
  13345. }
  13346. derSz = wc_PemCertToDer(file, der, EIGHTK_BUF);
  13347. ret = SetAltNamesFromCert(cert, der, derSz);
  13348. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  13349. return ret;
  13350. }
  13351. #endif /* WOLFSSL_ALT_NAMES */
  13352. #endif /* !NO_FILESYSTEM */
  13353. /* Set cert issuer from DER buffer */
  13354. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  13355. {
  13356. int ret = 0;
  13357. if (cert == NULL) {
  13358. ret = BAD_FUNC_ARG;
  13359. }
  13360. else {
  13361. cert->selfSigned = 0;
  13362. /* Check if decodedCert is cached */
  13363. if (cert->der != der) {
  13364. /* Allocate cache for the decoded cert */
  13365. ret = wc_SetCert_LoadDer(cert, der, derSz);
  13366. }
  13367. if (ret >= 0) {
  13368. SetNameFromDcert(&cert->issuer, (DecodedCert*)cert->decodedCert);
  13369. #ifndef WOLFSSL_CERT_GEN_CACHE
  13370. wc_SetCert_Free(cert);
  13371. #endif
  13372. }
  13373. }
  13374. return ret;
  13375. }
  13376. /* Set cert subject from DER buffer */
  13377. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  13378. {
  13379. int ret = 0;
  13380. if (cert == NULL) {
  13381. ret = BAD_FUNC_ARG;
  13382. }
  13383. else {
  13384. /* Check if decodedCert is cached */
  13385. if (cert->der != der) {
  13386. /* Allocate cache for the decoded cert */
  13387. ret = wc_SetCert_LoadDer(cert, der, derSz);
  13388. }
  13389. if (ret >= 0) {
  13390. SetNameFromDcert(&cert->subject, (DecodedCert*)cert->decodedCert);
  13391. #ifndef WOLFSSL_CERT_GEN_CACHE
  13392. wc_SetCert_Free(cert);
  13393. #endif
  13394. }
  13395. }
  13396. return ret;
  13397. }
  13398. #ifdef WOLFSSL_CERT_EXT
  13399. /* Set cert raw subject from DER buffer */
  13400. int wc_SetSubjectRaw(Cert* cert, const byte* der, int derSz)
  13401. {
  13402. int ret = 0;
  13403. if (cert == NULL) {
  13404. ret = BAD_FUNC_ARG;
  13405. }
  13406. else {
  13407. /* Check if decodedCert is cached */
  13408. if (cert->der != der) {
  13409. /* Allocate cache for the decoded cert */
  13410. ret = wc_SetCert_LoadDer(cert, der, derSz);
  13411. }
  13412. if (ret >= 0) {
  13413. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  13414. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  13415. (int)sizeof(CertName))) {
  13416. XMEMCPY(cert->sbjRaw,
  13417. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  13418. ((DecodedCert*)cert->decodedCert)->subjectRawLen);
  13419. }
  13420. #ifndef WOLFSSL_CERT_GEN_CACHE
  13421. wc_SetCert_Free(cert);
  13422. #endif
  13423. }
  13424. }
  13425. return ret;
  13426. }
  13427. /* Set cert raw issuer from DER buffer */
  13428. int wc_SetIssuerRaw(Cert* cert, const byte* der, int derSz)
  13429. {
  13430. int ret = 0;
  13431. if (cert == NULL) {
  13432. ret = BAD_FUNC_ARG;
  13433. }
  13434. else {
  13435. /* Check if decodedCert is cached */
  13436. if (cert->der != der) {
  13437. /* Allocate cache for the decoded cert */
  13438. ret = wc_SetCert_LoadDer(cert, der, derSz);
  13439. }
  13440. if (ret >= 0) {
  13441. if ((((DecodedCert*)cert->decodedCert)->subjectRaw) &&
  13442. (((DecodedCert*)cert->decodedCert)->subjectRawLen <=
  13443. (int)sizeof(CertName))) {
  13444. /* Copy the subject to the issuer field */
  13445. XMEMCPY(cert->issRaw,
  13446. ((DecodedCert*)cert->decodedCert)->subjectRaw,
  13447. ((DecodedCert*)cert->decodedCert)->subjectRawLen);
  13448. }
  13449. #ifndef WOLFSSL_CERT_GEN_CACHE
  13450. wc_SetCert_Free(cert);
  13451. #endif
  13452. }
  13453. }
  13454. return ret;
  13455. }
  13456. #endif
  13457. #ifdef WOLFSSL_ALT_NAMES
  13458. /* Set cert alt names from DER buffer */
  13459. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  13460. {
  13461. int ret = 0;
  13462. if (cert == NULL) {
  13463. ret = BAD_FUNC_ARG;
  13464. }
  13465. else {
  13466. /* Check if decodedCert is cached */
  13467. if (cert->der != der) {
  13468. /* Allocate cache for the decoded cert */
  13469. ret = wc_SetCert_LoadDer(cert, der, derSz);
  13470. }
  13471. if (ret >= 0) {
  13472. ret = SetAltNamesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  13473. #ifndef WOLFSSL_CERT_GEN_CACHE
  13474. wc_SetCert_Free(cert);
  13475. #endif
  13476. }
  13477. }
  13478. return(ret);
  13479. }
  13480. /* Set cert dates from DER buffer */
  13481. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  13482. {
  13483. int ret = 0;
  13484. if (cert == NULL) {
  13485. ret = BAD_FUNC_ARG;
  13486. }
  13487. else {
  13488. /* Check if decodedCert is cached */
  13489. if (cert->der != der) {
  13490. /* Allocate cache for the decoded cert */
  13491. ret = wc_SetCert_LoadDer(cert, der, derSz);
  13492. }
  13493. if (ret >= 0) {
  13494. ret = SetDatesFromDcert(cert, (DecodedCert*)cert->decodedCert);
  13495. #ifndef WOLFSSL_CERT_GEN_CACHE
  13496. wc_SetCert_Free(cert);
  13497. #endif
  13498. }
  13499. }
  13500. return(ret);
  13501. }
  13502. #endif /* WOLFSSL_ALT_NAMES */
  13503. #endif /* WOLFSSL_CERT_GEN */
  13504. #if (defined(WOLFSSL_CERT_GEN) && defined(WOLFSSL_CERT_EXT)) \
  13505. || defined(OPENSSL_EXTRA)
  13506. /* Encode OID string representation to ITU-T X.690 format */
  13507. int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  13508. {
  13509. word32 val, idx = 0, nb_val;
  13510. char *token, *str, *ptr;
  13511. word32 len;
  13512. (void)heap;
  13513. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  13514. return BAD_FUNC_ARG;
  13515. /* duplicate string (including terminator) */
  13516. len = (word32)XSTRLEN(in);
  13517. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  13518. if (str == NULL)
  13519. return MEMORY_E;
  13520. XMEMCPY(str, in, len+1);
  13521. nb_val = 0;
  13522. /* parse value, and set corresponding Policy OID value */
  13523. token = XSTRTOK(str, ".", &ptr);
  13524. while (token != NULL)
  13525. {
  13526. val = (word32)XATOI(token);
  13527. if (nb_val == 0) {
  13528. if (val > 2) {
  13529. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  13530. return ASN_OBJECT_ID_E;
  13531. }
  13532. out[idx] = (byte)(40 * val);
  13533. }
  13534. else if (nb_val == 1) {
  13535. if (val > 127) {
  13536. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  13537. return ASN_OBJECT_ID_E;
  13538. }
  13539. if (idx > *outSz) {
  13540. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  13541. return BUFFER_E;
  13542. }
  13543. out[idx++] += (byte)val;
  13544. }
  13545. else {
  13546. word32 tb = 0, x;
  13547. int i = 0;
  13548. byte oid[MAX_OID_SZ];
  13549. while (val >= 128) {
  13550. x = val % 128;
  13551. val /= 128;
  13552. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  13553. }
  13554. if ((idx+(word32)i) > *outSz) {
  13555. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  13556. return BUFFER_E;
  13557. }
  13558. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  13559. /* push value in the right order */
  13560. while (i >= 0)
  13561. out[idx++] = oid[i--];
  13562. }
  13563. token = XSTRTOK(NULL, ".", &ptr);
  13564. nb_val++;
  13565. }
  13566. *outSz = idx;
  13567. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  13568. return 0;
  13569. }
  13570. #endif /* WOLFSSL_CERT_EXT || OPENSSL_EXTRA */
  13571. #endif /* !NO_CERTS */
  13572. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  13573. /* Helper function for wolfSSL_i2d_DHparams */
  13574. int StoreDHparams(byte* out, word32* outLen, mp_int* p, mp_int* g)
  13575. {
  13576. word32 idx = 0;
  13577. int pSz;
  13578. int gSz;
  13579. unsigned int tmp;
  13580. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  13581. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  13582. int pLeadingZero = mp_leading_bit(p);
  13583. int gLeadingZero = mp_leading_bit(g);
  13584. int pLen = mp_unsigned_bin_size(p);
  13585. int gLen = mp_unsigned_bin_size(g);
  13586. WOLFSSL_ENTER("StoreDHparams");
  13587. if (out == NULL) {
  13588. WOLFSSL_MSG("Null buffer error");
  13589. return BUFFER_E;
  13590. }
  13591. tmp = pLeadingZero + gLeadingZero + pLen + gLen;
  13592. if (*outLen < (tmp + headerSz)) {
  13593. return BUFFER_E;
  13594. }
  13595. /* Set sequence */
  13596. idx = SetSequence(tmp + headerSz + 2, out);
  13597. /* Encode p */
  13598. pSz = SetASNIntMP(p, -1, &out[idx]);
  13599. if (pSz < 0) {
  13600. WOLFSSL_MSG("SetASNIntMP failed");
  13601. return pSz;
  13602. }
  13603. idx += pSz;
  13604. /* Encode g */
  13605. gSz = SetASNIntMP(g, -1, &out[idx]);
  13606. if (gSz < 0) {
  13607. WOLFSSL_MSG("SetASNIntMP failed");
  13608. return gSz;
  13609. }
  13610. idx += gSz;
  13611. *outLen = idx;
  13612. return 0;
  13613. }
  13614. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  13615. #ifdef HAVE_ECC
  13616. /* Der Encode r & s ints into out, outLen is (in/out) size */
  13617. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  13618. {
  13619. word32 idx = 0;
  13620. int rSz; /* encoding size */
  13621. int sSz;
  13622. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  13623. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  13624. int rLeadingZero = mp_leading_bit(r);
  13625. int sLeadingZero = mp_leading_bit(s);
  13626. int rLen = mp_unsigned_bin_size(r); /* big int size */
  13627. int sLen = mp_unsigned_bin_size(s);
  13628. if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero +
  13629. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  13630. return BUFFER_E;
  13631. idx = SetSequence(rLen + rLeadingZero + sLen+sLeadingZero + headerSz, out);
  13632. /* store r */
  13633. rSz = SetASNIntMP(r, *outLen - idx, &out[idx]);
  13634. if (rSz < 0)
  13635. return rSz;
  13636. idx += rSz;
  13637. /* store s */
  13638. sSz = SetASNIntMP(s, *outLen - idx, &out[idx]);
  13639. if (sSz < 0)
  13640. return sSz;
  13641. idx += sSz;
  13642. *outLen = idx;
  13643. return 0;
  13644. }
  13645. /* determine if leading bit is set */
  13646. static int is_leading_bit_set(const byte* input, word32 sz)
  13647. {
  13648. byte c = 0;
  13649. if (sz > 0)
  13650. c = input[0];
  13651. return (c & 0x80) != 0;
  13652. }
  13653. static int trim_leading_zeros(const byte** input, word32 sz)
  13654. {
  13655. int i, leadingZeroCount = 0;
  13656. const byte* tmp = *input;
  13657. for (i=0; i<(int)sz; i++) {
  13658. if (tmp[i] != 0)
  13659. break;
  13660. leadingZeroCount++;
  13661. }
  13662. /* catch all zero case */
  13663. if (sz > 0 && leadingZeroCount == (int)sz) {
  13664. leadingZeroCount--;
  13665. }
  13666. *input += leadingZeroCount;
  13667. sz -= leadingZeroCount;
  13668. return sz;
  13669. }
  13670. /* Der Encode r & s ints into out, outLen is (in/out) size */
  13671. /* All input/outputs are assumed to be big-endian */
  13672. int StoreECC_DSA_Sig_Bin(byte* out, word32* outLen, const byte* r, word32 rLen,
  13673. const byte* s, word32 sLen)
  13674. {
  13675. int ret;
  13676. word32 idx;
  13677. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  13678. int rAddLeadZero, sAddLeadZero;
  13679. if ((out == NULL) || (outLen == NULL) || (r == NULL) || (s == NULL))
  13680. return BAD_FUNC_ARG;
  13681. /* Trim leading zeros */
  13682. rLen = trim_leading_zeros(&r, rLen);
  13683. sLen = trim_leading_zeros(&s, sLen);
  13684. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  13685. /* Add leading zero if MSB is set */
  13686. rAddLeadZero = is_leading_bit_set(r, rLen);
  13687. sAddLeadZero = is_leading_bit_set(s, sLen);
  13688. if (*outLen < (rLen + rAddLeadZero + sLen + sAddLeadZero +
  13689. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  13690. return BUFFER_E;
  13691. idx = SetSequence(rLen+rAddLeadZero + sLen+sAddLeadZero + headerSz, out);
  13692. /* store r */
  13693. ret = SetASNInt(rLen, rAddLeadZero ? 0x80 : 0x00, &out[idx]);
  13694. if (ret < 0)
  13695. return ret;
  13696. idx += ret;
  13697. XMEMCPY(&out[idx], r, rLen);
  13698. idx += rLen;
  13699. /* store s */
  13700. ret = SetASNInt(sLen, sAddLeadZero ? 0x80 : 0x00, &out[idx]);
  13701. if (ret < 0)
  13702. return ret;
  13703. idx += ret;
  13704. XMEMCPY(&out[idx], s, sLen);
  13705. idx += sLen;
  13706. *outLen = idx;
  13707. return 0;
  13708. }
  13709. /* Der Decode ECC-DSA Signature with R/S as unsigned bin */
  13710. /* All input/outputs are assumed to be big-endian */
  13711. int DecodeECC_DSA_Sig_Bin(const byte* sig, word32 sigLen, byte* r, word32* rLen,
  13712. byte* s, word32* sLen)
  13713. {
  13714. int ret;
  13715. word32 idx = 0;
  13716. int len = 0;
  13717. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  13718. return ASN_ECC_KEY_E;
  13719. }
  13720. #ifndef NO_STRICT_ECDSA_LEN
  13721. /* enable strict length checking for signature */
  13722. if (sigLen != idx + (word32)len) {
  13723. return ASN_ECC_KEY_E;
  13724. }
  13725. #else
  13726. /* allow extra signature bytes at end */
  13727. if ((word32)len > (sigLen - idx)) {
  13728. return ASN_ECC_KEY_E;
  13729. }
  13730. #endif
  13731. ret = GetASNInt(sig, &idx, &len, sigLen);
  13732. if (ret != 0)
  13733. return ret;
  13734. if (rLen)
  13735. *rLen = len;
  13736. if (r)
  13737. XMEMCPY(r, (byte*)sig + idx, len);
  13738. idx += len;
  13739. ret = GetASNInt(sig, &idx, &len, sigLen);
  13740. if (ret != 0)
  13741. return ret;
  13742. if (sLen)
  13743. *sLen = len;
  13744. if (s)
  13745. XMEMCPY(s, (byte*)sig + idx, len);
  13746. return ret;
  13747. }
  13748. #endif
  13749. #if defined(HAVE_ECC) || !defined(NO_DSA)
  13750. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  13751. {
  13752. word32 idx = 0;
  13753. int len = 0;
  13754. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  13755. return ASN_ECC_KEY_E;
  13756. }
  13757. #ifndef NO_STRICT_ECDSA_LEN
  13758. /* enable strict length checking for signature */
  13759. if (sigLen != idx + (word32)len) {
  13760. return ASN_ECC_KEY_E;
  13761. }
  13762. #else
  13763. /* allow extra signature bytes at end */
  13764. if ((word32)len > (sigLen - idx)) {
  13765. return ASN_ECC_KEY_E;
  13766. }
  13767. #endif
  13768. if (GetInt(r, sig, &idx, sigLen) < 0) {
  13769. return ASN_ECC_KEY_E;
  13770. }
  13771. if (GetInt(s, sig, &idx, sigLen) < 0) {
  13772. mp_clear(r);
  13773. return ASN_ECC_KEY_E;
  13774. }
  13775. return 0;
  13776. }
  13777. #endif
  13778. #ifdef HAVE_ECC
  13779. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  13780. word32 inSz)
  13781. {
  13782. word32 oidSum;
  13783. int version, length;
  13784. int privSz, pubSz = 0;
  13785. byte b;
  13786. int ret = 0;
  13787. int curve_id = ECC_CURVE_DEF;
  13788. #ifdef WOLFSSL_SMALL_STACK
  13789. byte* priv;
  13790. byte* pub = NULL;
  13791. #else
  13792. byte priv[ECC_MAXSIZE+1];
  13793. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  13794. #endif
  13795. byte* pubData = NULL;
  13796. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  13797. return BAD_FUNC_ARG;
  13798. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  13799. return ASN_PARSE_E;
  13800. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  13801. return ASN_PARSE_E;
  13802. if (*inOutIdx >= inSz)
  13803. return ASN_PARSE_E;
  13804. b = input[*inOutIdx];
  13805. *inOutIdx += 1;
  13806. /* priv type */
  13807. if (b != 4 && b != 6 && b != 7)
  13808. return ASN_PARSE_E;
  13809. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  13810. return ASN_PARSE_E;
  13811. privSz = length;
  13812. if (privSz > ECC_MAXSIZE)
  13813. return BUFFER_E;
  13814. #ifdef WOLFSSL_SMALL_STACK
  13815. priv = (byte*)XMALLOC(privSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13816. if (priv == NULL)
  13817. return MEMORY_E;
  13818. #endif
  13819. /* priv key */
  13820. XMEMCPY(priv, &input[*inOutIdx], privSz);
  13821. *inOutIdx += length;
  13822. if ((*inOutIdx + 1) < inSz) {
  13823. /* prefix 0, may have */
  13824. b = input[*inOutIdx];
  13825. if (b == ECC_PREFIX_0) {
  13826. *inOutIdx += 1;
  13827. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  13828. ret = ASN_PARSE_E;
  13829. else {
  13830. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  13831. inSz);
  13832. if (ret == 0) {
  13833. if ((ret = CheckCurve(oidSum)) < 0)
  13834. ret = ECC_CURVE_OID_E;
  13835. else {
  13836. curve_id = ret;
  13837. ret = 0;
  13838. }
  13839. }
  13840. }
  13841. }
  13842. }
  13843. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  13844. /* prefix 1 */
  13845. b = input[*inOutIdx];
  13846. *inOutIdx += 1;
  13847. if (b != ECC_PREFIX_1) {
  13848. ret = ASN_ECC_KEY_E;
  13849. }
  13850. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  13851. ret = ASN_PARSE_E;
  13852. }
  13853. else {
  13854. /* key header */
  13855. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  13856. if (ret == 0) {
  13857. /* pub key */
  13858. pubSz = length;
  13859. if (pubSz > 2*(ECC_MAXSIZE+1))
  13860. ret = BUFFER_E;
  13861. else {
  13862. #ifdef WOLFSSL_SMALL_STACK
  13863. pub = (byte*)XMALLOC(pubSz, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13864. if (pub == NULL)
  13865. ret = MEMORY_E;
  13866. else
  13867. #endif
  13868. {
  13869. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  13870. *inOutIdx += length;
  13871. pubData = pub;
  13872. }
  13873. }
  13874. }
  13875. }
  13876. }
  13877. if (ret == 0) {
  13878. ret = wc_ecc_import_private_key_ex(priv, privSz, pubData, pubSz, key,
  13879. curve_id);
  13880. }
  13881. #ifdef WOLFSSL_SMALL_STACK
  13882. XFREE(priv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13883. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  13884. #endif
  13885. return ret;
  13886. }
  13887. #ifdef WOLFSSL_CUSTOM_CURVES
  13888. static void ByteToHex(byte n, char* str)
  13889. {
  13890. const char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
  13891. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
  13892. str[0] = hexChar[n >> 4];
  13893. str[1] = hexChar[n & 0xf];
  13894. }
  13895. /* returns 0 on success */
  13896. static int ASNToHexString(const byte* input, word32* inOutIdx, char** out,
  13897. word32 inSz, void* heap, int heapType)
  13898. {
  13899. int len;
  13900. int i;
  13901. char* str;
  13902. word32 localIdx;
  13903. byte tag;
  13904. if (*inOutIdx >= inSz) {
  13905. return BUFFER_E;
  13906. }
  13907. localIdx = *inOutIdx;
  13908. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 && tag == ASN_INTEGER) {
  13909. if (GetASNInt(input, inOutIdx, &len, inSz) < 0)
  13910. return ASN_PARSE_E;
  13911. }
  13912. else {
  13913. if (GetOctetString(input, inOutIdx, &len, inSz) < 0)
  13914. return ASN_PARSE_E;
  13915. }
  13916. str = (char*)XMALLOC(len * 2 + 1, heap, heapType);
  13917. for (i=0; i<len; i++)
  13918. ByteToHex(input[*inOutIdx + i], str + i*2);
  13919. str[len*2] = '\0';
  13920. *inOutIdx += len;
  13921. *out = str;
  13922. (void)heap;
  13923. (void)heapType;
  13924. return 0;
  13925. }
  13926. #endif /* WOLFSSL_CUSTOM_CURVES */
  13927. #ifdef WOLFSSL_CUSTOM_CURVES
  13928. static int EccKeyParamCopy(char** dst, char* src)
  13929. {
  13930. int ret = 0;
  13931. #ifdef WOLFSSL_ECC_CURVE_STATIC
  13932. word32 length;
  13933. #endif
  13934. if (dst == NULL || src == NULL)
  13935. return BAD_FUNC_ARG;
  13936. #ifndef WOLFSSL_ECC_CURVE_STATIC
  13937. *dst = src;
  13938. #else
  13939. length = (int)XSTRLEN(src) + 1;
  13940. if (length > MAX_ECC_STRING) {
  13941. WOLFSSL_MSG("ECC Param too large for buffer");
  13942. ret = BUFFER_E;
  13943. }
  13944. else {
  13945. XSTRNCPY(*dst, src, length);
  13946. }
  13947. XFREE(src, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  13948. #endif
  13949. return ret;
  13950. }
  13951. #endif /* WOLFSSL_CUSTOM_CURVES */
  13952. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  13953. ecc_key* key, word32 inSz)
  13954. {
  13955. int ret;
  13956. int version, length;
  13957. int curve_id = ECC_CURVE_DEF;
  13958. word32 oidSum, localIdx;
  13959. byte tag, isPrivFormat = 0;
  13960. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  13961. return BAD_FUNC_ARG;
  13962. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  13963. return ASN_PARSE_E;
  13964. /* Check if ECC private key is being used and skip private portion */
  13965. if (GetMyVersion(input, inOutIdx, &version, inSz) >= 0) {
  13966. isPrivFormat = 1;
  13967. /* Type private key */
  13968. if (*inOutIdx >= inSz)
  13969. return ASN_PARSE_E;
  13970. tag = input[*inOutIdx];
  13971. *inOutIdx += 1;
  13972. if (tag != 4 && tag != 6 && tag != 7)
  13973. return ASN_PARSE_E;
  13974. /* Skip Private Key */
  13975. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  13976. return ASN_PARSE_E;
  13977. if (length > ECC_MAXSIZE)
  13978. return BUFFER_E;
  13979. *inOutIdx += length;
  13980. /* Private Curve Header */
  13981. if (*inOutIdx >= inSz)
  13982. return ASN_PARSE_E;
  13983. tag = input[*inOutIdx];
  13984. *inOutIdx += 1;
  13985. if (tag != ECC_PREFIX_0)
  13986. return ASN_ECC_KEY_E;
  13987. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  13988. return ASN_PARSE_E;
  13989. }
  13990. /* Standard ECC public key */
  13991. else {
  13992. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  13993. return ASN_PARSE_E;
  13994. ret = SkipObjectId(input, inOutIdx, inSz);
  13995. if (ret != 0)
  13996. return ret;
  13997. }
  13998. if (*inOutIdx >= inSz) {
  13999. return BUFFER_E;
  14000. }
  14001. localIdx = *inOutIdx;
  14002. if (GetASNTag(input, &localIdx, &tag, inSz) == 0 &&
  14003. tag == (ASN_SEQUENCE | ASN_CONSTRUCTED)) {
  14004. #ifdef WOLFSSL_CUSTOM_CURVES
  14005. ecc_set_type* curve;
  14006. int len;
  14007. char* point = NULL;
  14008. ret = 0;
  14009. curve = (ecc_set_type*)XMALLOC(sizeof(*curve), key->heap,
  14010. DYNAMIC_TYPE_ECC_BUFFER);
  14011. if (curve == NULL)
  14012. ret = MEMORY_E;
  14013. if (ret == 0) {
  14014. static const char customName[] = "Custom";
  14015. XMEMSET(curve, 0, sizeof(*curve));
  14016. #ifndef WOLFSSL_ECC_CURVE_STATIC
  14017. curve->name = customName;
  14018. #else
  14019. XMEMCPY((void*)curve->name, customName, sizeof(customName));
  14020. #endif
  14021. curve->id = ECC_CURVE_CUSTOM;
  14022. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14023. ret = ASN_PARSE_E;
  14024. }
  14025. if (ret == 0) {
  14026. GetInteger7Bit(input, inOutIdx, inSz);
  14027. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14028. ret = ASN_PARSE_E;
  14029. }
  14030. if (ret == 0) {
  14031. char* p = NULL;
  14032. SkipObjectId(input, inOutIdx, inSz);
  14033. ret = ASNToHexString(input, inOutIdx, &p, inSz,
  14034. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14035. if (ret == 0)
  14036. ret = EccKeyParamCopy((char**)&curve->prime, p);
  14037. }
  14038. if (ret == 0) {
  14039. curve->size = (int)XSTRLEN(curve->prime) / 2;
  14040. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14041. ret = ASN_PARSE_E;
  14042. }
  14043. if (ret == 0) {
  14044. char* af = NULL;
  14045. ret = ASNToHexString(input, inOutIdx, &af, inSz,
  14046. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14047. if (ret == 0)
  14048. ret = EccKeyParamCopy((char**)&curve->Af, af);
  14049. }
  14050. if (ret == 0) {
  14051. char* bf = NULL;
  14052. ret = ASNToHexString(input, inOutIdx, &bf, inSz,
  14053. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14054. if (ret == 0)
  14055. ret = EccKeyParamCopy((char**)&curve->Bf, bf);
  14056. }
  14057. if (ret == 0) {
  14058. localIdx = *inOutIdx;
  14059. if (*inOutIdx < inSz && GetASNTag(input, &localIdx, &tag, inSz)
  14060. == 0 && tag == ASN_BIT_STRING) {
  14061. len = 0;
  14062. ret = GetASNHeader(input, ASN_BIT_STRING, inOutIdx, &len, inSz);
  14063. *inOutIdx += len;
  14064. }
  14065. }
  14066. if (ret == 0) {
  14067. ret = ASNToHexString(input, inOutIdx, (char**)&point, inSz,
  14068. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14069. /* sanity check that point buffer is not smaller than the expected
  14070. * size to hold ( 0 4 || Gx || Gy )
  14071. * where Gx and Gy are each the size of curve->size * 2 */
  14072. if (ret == 0 && (int)XSTRLEN(point) < (curve->size * 4) + 2) {
  14073. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14074. ret = BUFFER_E;
  14075. }
  14076. }
  14077. if (ret == 0) {
  14078. #ifndef WOLFSSL_ECC_CURVE_STATIC
  14079. curve->Gx = (const char*)XMALLOC(curve->size * 2 + 2, key->heap,
  14080. DYNAMIC_TYPE_ECC_BUFFER);
  14081. curve->Gy = (const char*)XMALLOC(curve->size * 2 + 2, key->heap,
  14082. DYNAMIC_TYPE_ECC_BUFFER);
  14083. if (curve->Gx == NULL || curve->Gy == NULL) {
  14084. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14085. ret = MEMORY_E;
  14086. }
  14087. #else
  14088. if (curve->size * 2 + 2 > MAX_ECC_STRING) {
  14089. WOLFSSL_MSG("curve size is too large to fit in buffer");
  14090. ret = BUFFER_E;
  14091. }
  14092. #endif
  14093. }
  14094. if (ret == 0) {
  14095. char* o = NULL;
  14096. XMEMCPY((char*)curve->Gx, point + 2, curve->size * 2);
  14097. XMEMCPY((char*)curve->Gy, point + curve->size * 2 + 2,
  14098. curve->size * 2);
  14099. ((char*)curve->Gx)[curve->size * 2] = '\0';
  14100. ((char*)curve->Gy)[curve->size * 2] = '\0';
  14101. XFREE(point, key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14102. ret = ASNToHexString(input, inOutIdx, &o, inSz,
  14103. key->heap, DYNAMIC_TYPE_ECC_BUFFER);
  14104. if (ret == 0)
  14105. ret = EccKeyParamCopy((char**)&curve->order, o);
  14106. }
  14107. if (ret == 0) {
  14108. curve->cofactor = GetInteger7Bit(input, inOutIdx, inSz);
  14109. #ifndef WOLFSSL_ECC_CURVE_STATIC
  14110. curve->oid = NULL;
  14111. #else
  14112. XMEMSET((void*)curve->oid, 0, sizeof(curve->oid));
  14113. #endif
  14114. curve->oidSz = 0;
  14115. curve->oidSum = 0;
  14116. if (wc_ecc_set_custom_curve(key, curve) < 0) {
  14117. ret = ASN_PARSE_E;
  14118. }
  14119. #ifdef WOLFSSL_CUSTOM_CURVES
  14120. key->deallocSet = 1;
  14121. #endif
  14122. curve = NULL;
  14123. }
  14124. if (curve != NULL)
  14125. wc_ecc_free_curve(curve, key->heap);
  14126. if (ret < 0)
  14127. return ret;
  14128. #else
  14129. return ASN_PARSE_E;
  14130. #endif /* WOLFSSL_CUSTOM_CURVES */
  14131. }
  14132. else {
  14133. /* ecc params information */
  14134. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  14135. if (ret != 0)
  14136. return ret;
  14137. /* get curve id */
  14138. if ((ret = CheckCurve(oidSum)) < 0)
  14139. return ECC_CURVE_OID_E;
  14140. else {
  14141. curve_id = ret;
  14142. }
  14143. }
  14144. if (isPrivFormat) {
  14145. /* Public Curve Header - skip */
  14146. if (*inOutIdx >= inSz)
  14147. return ASN_PARSE_E;
  14148. tag = input[*inOutIdx];
  14149. *inOutIdx += 1;
  14150. if (tag != ECC_PREFIX_1)
  14151. return ASN_ECC_KEY_E;
  14152. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  14153. return ASN_PARSE_E;
  14154. }
  14155. /* key header */
  14156. ret = CheckBitString(input, inOutIdx, &length, inSz, 1, NULL);
  14157. if (ret != 0)
  14158. return ret;
  14159. /* This is the raw point data compressed or uncompressed. */
  14160. if (wc_ecc_import_x963_ex(input + *inOutIdx, length, key,
  14161. curve_id) != 0) {
  14162. return ASN_ECC_KEY_E;
  14163. }
  14164. *inOutIdx += length;
  14165. return 0;
  14166. }
  14167. #if defined(HAVE_ECC_KEY_EXPORT) && !defined(NO_ASN_CRYPT)
  14168. /* build DER formatted ECC key, include optional public key if requested,
  14169. * return length on success, negative on error */
  14170. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 *inLen,
  14171. int pubIn)
  14172. {
  14173. byte curve[MAX_ALGO_SZ+2];
  14174. byte ver[MAX_VERSION_SZ];
  14175. byte seq[MAX_SEQ_SZ];
  14176. int ret, totalSz, curveSz, verSz;
  14177. int privHdrSz = ASN_ECC_HEADER_SZ;
  14178. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  14179. #ifdef WOLFSSL_NO_MALLOC
  14180. byte prv[MAX_ECC_BYTES + ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  14181. byte pub[(MAX_ECC_BYTES * 2) + 1 + ASN_ECC_CONTEXT_SZ +
  14182. ASN_ECC_HEADER_SZ + MAX_SEQ_SZ];
  14183. #else
  14184. byte *prv = NULL, *pub = NULL;
  14185. #endif
  14186. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  14187. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  14188. if (key == NULL || (output == NULL && inLen == NULL))
  14189. return BAD_FUNC_ARG;
  14190. /* curve */
  14191. curve[curveidx++] = ECC_PREFIX_0;
  14192. curveidx++ /* to put the size after computation */;
  14193. curveSz = SetCurve(key, curve+curveidx);
  14194. if (curveSz < 0)
  14195. return curveSz;
  14196. /* set computed size */
  14197. curve[1] = (byte)curveSz;
  14198. curveidx += curveSz;
  14199. /* private */
  14200. privSz = key->dp->size;
  14201. #ifdef WOLFSSL_QNX_CAAM
  14202. /* check if is a black key, and add MAC size if so */
  14203. if (key->blackKey > 0) {
  14204. privSz = privSz + WC_CAAM_MAC_SZ;
  14205. }
  14206. #endif
  14207. #ifndef WOLFSSL_NO_MALLOC
  14208. prv = (byte*)XMALLOC(privSz + privHdrSz + MAX_SEQ_SZ,
  14209. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14210. if (prv == NULL) {
  14211. return MEMORY_E;
  14212. }
  14213. #else
  14214. if (sizeof(prv) < privSz + privHdrSz + MAX_SEQ_SZ) {
  14215. return BUFFER_E;
  14216. }
  14217. #endif
  14218. if (privSz < ASN_LONG_LENGTH) {
  14219. prvidx += SetOctetString8Bit(privSz, &prv[prvidx]);
  14220. }
  14221. else {
  14222. prvidx += SetOctetString(privSz, &prv[prvidx]);
  14223. }
  14224. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  14225. if (ret < 0) {
  14226. #ifndef WOLFSSL_NO_MALLOC
  14227. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14228. #endif
  14229. return ret;
  14230. }
  14231. prvidx += privSz;
  14232. /* pubIn */
  14233. if (pubIn) {
  14234. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  14235. if (ret != LENGTH_ONLY_E) {
  14236. #ifndef WOLFSSL_NO_MALLOC
  14237. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14238. #endif
  14239. return ret;
  14240. }
  14241. #ifndef WOLFSSL_NO_MALLOC
  14242. pub = (byte*)XMALLOC(pubSz + pubHdrSz + MAX_SEQ_SZ,
  14243. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14244. if (pub == NULL) {
  14245. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14246. return MEMORY_E;
  14247. }
  14248. #else
  14249. if (sizeof(pub) < pubSz + pubHdrSz + MAX_SEQ_SZ) {
  14250. return BUFFER_E;
  14251. }
  14252. #endif
  14253. pub[pubidx++] = ECC_PREFIX_1;
  14254. if (pubSz > 128) /* leading zero + extra size byte */
  14255. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  14256. else /* leading zero */
  14257. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  14258. /* SetBitString adds leading zero */
  14259. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  14260. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  14261. if (ret != 0) {
  14262. #ifndef WOLFSSL_NO_MALLOC
  14263. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14264. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14265. #endif
  14266. return ret;
  14267. }
  14268. pubidx += pubSz;
  14269. }
  14270. /* make headers */
  14271. verSz = SetMyVersion(1, ver, FALSE);
  14272. seqSz = SetSequence(verSz + prvidx + pubidx + curveidx, seq);
  14273. totalSz = prvidx + pubidx + curveidx + verSz + seqSz;
  14274. if (output == NULL) {
  14275. *inLen = totalSz;
  14276. #ifndef WOLFSSL_NO_MALLOC
  14277. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14278. if (pub) {
  14279. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14280. }
  14281. #endif
  14282. return LENGTH_ONLY_E;
  14283. }
  14284. if (inLen != NULL && totalSz > (int)*inLen) {
  14285. #ifndef WOLFSSL_NO_MALLOC
  14286. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14287. if (pubIn) {
  14288. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14289. }
  14290. #endif
  14291. return BAD_FUNC_ARG;
  14292. }
  14293. /* write out */
  14294. /* seq */
  14295. XMEMCPY(output + idx, seq, seqSz);
  14296. idx = seqSz;
  14297. /* ver */
  14298. XMEMCPY(output + idx, ver, verSz);
  14299. idx += verSz;
  14300. /* private */
  14301. XMEMCPY(output + idx, prv, prvidx);
  14302. idx += prvidx;
  14303. #ifndef WOLFSSL_NO_MALLOC
  14304. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14305. #endif
  14306. /* curve */
  14307. XMEMCPY(output + idx, curve, curveidx);
  14308. idx += curveidx;
  14309. /* pubIn */
  14310. if (pubIn) {
  14311. XMEMCPY(output + idx, pub, pubidx);
  14312. /* idx += pubidx; not used after write, if more data remove comment */
  14313. #ifndef WOLFSSL_NO_MALLOC
  14314. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14315. #endif
  14316. }
  14317. return totalSz;
  14318. }
  14319. /* Write a Private ecc key, including public to DER format,
  14320. * length on success else < 0 */
  14321. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  14322. {
  14323. return wc_BuildEccKeyDer(key, output, &inLen, 1);
  14324. }
  14325. /* Write only private ecc key to DER format,
  14326. * length on success else < 0 */
  14327. int wc_EccKeyDerSize(ecc_key* key, int pub)
  14328. {
  14329. word32 sz = 0;
  14330. int ret;
  14331. ret = wc_BuildEccKeyDer(key, NULL, &sz, pub);
  14332. if (ret != LENGTH_ONLY_E) {
  14333. return ret;
  14334. }
  14335. return sz;
  14336. }
  14337. /* Write only private ecc key to DER format,
  14338. * length on success else < 0 */
  14339. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  14340. {
  14341. return wc_BuildEccKeyDer(key, output, &inLen, 0);
  14342. }
  14343. #ifdef HAVE_PKCS8
  14344. /* Write only private ecc key or both private and public parts to unencrypted
  14345. * PKCS#8 format.
  14346. *
  14347. * If output is NULL, places required PKCS#8 buffer size in outLen and
  14348. * returns LENGTH_ONLY_E.
  14349. *
  14350. * return length on success else < 0 */
  14351. static int eccToPKCS8(ecc_key* key, byte* output, word32* outLen,
  14352. int includePublic)
  14353. {
  14354. int ret, tmpDerSz;
  14355. int algoID = 0;
  14356. word32 oidSz = 0;
  14357. word32 pkcs8Sz = 0;
  14358. const byte* curveOID = NULL;
  14359. #ifdef WOLFSSL_NO_MALLOC
  14360. byte tmpDer[ECC_BUFSIZE];
  14361. #else
  14362. byte* tmpDer = NULL;
  14363. #endif
  14364. word32 sz = ECC_BUFSIZE;
  14365. if (key == NULL || key->dp == NULL || outLen == NULL)
  14366. return BAD_FUNC_ARG;
  14367. /* set algoID, get curve OID */
  14368. algoID = ECDSAk;
  14369. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  14370. if (ret < 0)
  14371. return ret;
  14372. #ifndef WOLFSSL_NO_MALLOC
  14373. /* temp buffer for plain DER key */
  14374. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14375. if (tmpDer == NULL)
  14376. return MEMORY_E;
  14377. #endif
  14378. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  14379. tmpDerSz = wc_BuildEccKeyDer(key, tmpDer, &sz, includePublic);
  14380. if (tmpDerSz < 0) {
  14381. #ifndef WOLFSSL_NO_MALLOC
  14382. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14383. #endif
  14384. return tmpDerSz;
  14385. }
  14386. /* get pkcs8 expected output size */
  14387. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  14388. curveOID, oidSz);
  14389. if (ret != LENGTH_ONLY_E) {
  14390. #ifndef WOLFSSL_NO_MALLOC
  14391. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14392. #endif
  14393. return ret;
  14394. }
  14395. if (output == NULL) {
  14396. #ifndef WOLFSSL_NO_MALLOC
  14397. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14398. #endif
  14399. *outLen = pkcs8Sz;
  14400. return LENGTH_ONLY_E;
  14401. }
  14402. else if (*outLen < pkcs8Sz) {
  14403. #ifndef WOLFSSL_NO_MALLOC
  14404. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14405. #endif
  14406. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  14407. return BUFFER_E;
  14408. }
  14409. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  14410. algoID, curveOID, oidSz);
  14411. if (ret < 0) {
  14412. #ifndef WOLFSSL_NO_MALLOC
  14413. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14414. #endif
  14415. return ret;
  14416. }
  14417. #ifndef WOLFSSL_NO_MALLOC
  14418. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  14419. #endif
  14420. *outLen = ret;
  14421. return ret;
  14422. }
  14423. /* Write only private ecc key to unencrypted PKCS#8 format.
  14424. *
  14425. * return length on success else < 0 */
  14426. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  14427. {
  14428. return eccToPKCS8(key, output, outLen, 0);
  14429. }
  14430. /* Write both private and public ecc keys to unencrypted PKCS#8 format.
  14431. *
  14432. * return length on success else < 0 */
  14433. int wc_EccKeyToPKCS8(ecc_key* key, byte* output,
  14434. word32* outLen)
  14435. {
  14436. return eccToPKCS8(key, output, outLen, 1);
  14437. }
  14438. #endif /* HAVE_PKCS8 */
  14439. #endif /* HAVE_ECC_KEY_EXPORT && !NO_ASN_CRYPT */
  14440. #endif /* HAVE_ECC */
  14441. #ifdef HAVE_ED25519
  14442. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  14443. ed25519_key* key, word32 inSz)
  14444. {
  14445. word32 oid;
  14446. int ret, version, length, endKeyIdx, privSz, pubSz;
  14447. const byte* priv;
  14448. const byte* pub;
  14449. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  14450. return BAD_FUNC_ARG;
  14451. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  14452. endKeyIdx = *inOutIdx + length;
  14453. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  14454. return ASN_PARSE_E;
  14455. if (version != 0) {
  14456. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  14457. return ASN_PARSE_E;
  14458. }
  14459. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  14460. return ASN_PARSE_E;
  14461. if (oid != ED25519k)
  14462. return ASN_PARSE_E;
  14463. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  14464. return ASN_PARSE_E;
  14465. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  14466. return ASN_PARSE_E;
  14467. priv = input + *inOutIdx;
  14468. *inOutIdx += privSz;
  14469. }
  14470. else {
  14471. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  14472. return ASN_PARSE_E;
  14473. if (privSz != 32)
  14474. return ASN_PARSE_E;
  14475. priv = input + *inOutIdx;
  14476. *inOutIdx += privSz;
  14477. endKeyIdx = *inOutIdx;
  14478. }
  14479. if (endKeyIdx == (int)*inOutIdx) {
  14480. ret = wc_ed25519_import_private_only(priv, privSz, key);
  14481. }
  14482. else {
  14483. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1,
  14484. inOutIdx, &length, inSz) < 0) {
  14485. return ASN_PARSE_E;
  14486. }
  14487. if (GetOctetString(input, inOutIdx, &pubSz, inSz) < 0)
  14488. return ASN_PARSE_E;
  14489. pub = input + *inOutIdx;
  14490. *inOutIdx += pubSz;
  14491. ret = wc_ed25519_import_private_key(priv, privSz, pub, pubSz, key);
  14492. }
  14493. if (ret == 0 && endKeyIdx != (int)*inOutIdx)
  14494. return ASN_PARSE_E;
  14495. return ret;
  14496. }
  14497. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  14498. ed25519_key* key, word32 inSz)
  14499. {
  14500. int length;
  14501. int ret;
  14502. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  14503. return BAD_FUNC_ARG;
  14504. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14505. return ASN_PARSE_E;
  14506. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14507. return ASN_PARSE_E;
  14508. ret = SkipObjectId(input, inOutIdx, inSz);
  14509. if (ret != 0)
  14510. return ret;
  14511. /* key header */
  14512. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  14513. if (ret != 0)
  14514. return ret;
  14515. /* This is the raw point data compressed or uncompressed. */
  14516. if (wc_ed25519_import_public(input + *inOutIdx, inSz - *inOutIdx, key) != 0)
  14517. return ASN_ECC_KEY_E;
  14518. return 0;
  14519. }
  14520. #ifdef WOLFSSL_KEY_GEN
  14521. /* build DER formatted ED25519 key,
  14522. * return length on success, negative on error */
  14523. static int wc_BuildEd25519KeyDer(ed25519_key* key, byte* output, word32 inLen,
  14524. int pubOut)
  14525. {
  14526. byte algoArray[MAX_ALGO_SZ];
  14527. byte ver[MAX_VERSION_SZ];
  14528. byte seq[MAX_SEQ_SZ];
  14529. int ret;
  14530. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0;
  14531. if (key == NULL || output == NULL || inLen == 0)
  14532. return BAD_FUNC_ARG;
  14533. if (pubOut)
  14534. pubSz = 2 + 2 + ED25519_PUB_KEY_SIZE;
  14535. privSz = 2 + 2 + ED25519_KEY_SIZE;
  14536. algoSz = SetAlgoID(ED25519k, algoArray, oidKeyType, 0);
  14537. verSz = SetMyVersion(0, ver, FALSE);
  14538. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, seq);
  14539. if (seqSz + verSz + algoSz + privSz + pubSz > inLen)
  14540. return BAD_FUNC_ARG;
  14541. /* write out */
  14542. /* seq */
  14543. XMEMCPY(output + idx, seq, seqSz);
  14544. idx = seqSz;
  14545. /* ver */
  14546. XMEMCPY(output + idx, ver, verSz);
  14547. idx += verSz;
  14548. /* algo */
  14549. XMEMCPY(output + idx, algoArray, algoSz);
  14550. idx += algoSz;
  14551. /* privKey */
  14552. idx += SetOctetString(2 + ED25519_KEY_SIZE, output + idx);
  14553. idx += SetOctetString(ED25519_KEY_SIZE, output + idx);
  14554. ret = wc_ed25519_export_private_only(key, output + idx, &privSz);
  14555. if (ret != 0)
  14556. return ret;
  14557. idx += privSz;
  14558. /* pubKey */
  14559. if (pubOut) {
  14560. idx += SetExplicit(1, 2 + ED25519_PUB_KEY_SIZE, output + idx);
  14561. idx += SetOctetString(ED25519_KEY_SIZE, output + idx);
  14562. ret = wc_ed25519_export_public(key, output + idx, &pubSz);
  14563. if (ret != 0)
  14564. return ret;
  14565. idx += pubSz;
  14566. }
  14567. return idx;
  14568. }
  14569. /* Write a Private ecc key, including public to DER format,
  14570. * length on success else < 0 */
  14571. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  14572. {
  14573. return wc_BuildEd25519KeyDer(key, output, inLen, 1);
  14574. }
  14575. /* Write only private ecc key to DER format,
  14576. * length on success else < 0 */
  14577. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  14578. {
  14579. return wc_BuildEd25519KeyDer(key, output, inLen, 0);
  14580. }
  14581. #endif /* WOLFSSL_KEY_GEN */
  14582. #endif /* HAVE_ED25519 */
  14583. #ifdef HAVE_ED448
  14584. int wc_Ed448PrivateKeyDecode(const byte* input, word32* inOutIdx,
  14585. ed448_key* key, word32 inSz)
  14586. {
  14587. word32 oid;
  14588. int ret, version, length, endKeyIdx, privSz, pubSz;
  14589. const byte* priv;
  14590. const byte* pub;
  14591. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  14592. return BAD_FUNC_ARG;
  14593. if (GetSequence(input, inOutIdx, &length, inSz) >= 0) {
  14594. endKeyIdx = *inOutIdx + length;
  14595. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  14596. return ASN_PARSE_E;
  14597. if (version != 0) {
  14598. WOLFSSL_MSG("Unrecognized version of ED448 private key");
  14599. return ASN_PARSE_E;
  14600. }
  14601. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  14602. return ASN_PARSE_E;
  14603. if (oid != ED448k)
  14604. return ASN_PARSE_E;
  14605. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  14606. return ASN_PARSE_E;
  14607. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  14608. return ASN_PARSE_E;
  14609. priv = input + *inOutIdx;
  14610. *inOutIdx += privSz;
  14611. }
  14612. else {
  14613. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  14614. return ASN_PARSE_E;
  14615. if (privSz != 57)
  14616. return ASN_PARSE_E;
  14617. priv = input + *inOutIdx;
  14618. *inOutIdx += privSz;
  14619. endKeyIdx = *inOutIdx;
  14620. }
  14621. if (endKeyIdx == (int)*inOutIdx) {
  14622. ret = wc_ed448_import_private_only(priv, privSz, key);
  14623. }
  14624. else {
  14625. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1,
  14626. inOutIdx, &length, inSz) < 0) {
  14627. return ASN_PARSE_E;
  14628. }
  14629. if (GetOctetString(input, inOutIdx, &pubSz, inSz) < 0)
  14630. return ASN_PARSE_E;
  14631. pub = input + *inOutIdx;
  14632. *inOutIdx += pubSz;
  14633. ret = wc_ed448_import_private_key(priv, privSz, pub, pubSz, key);
  14634. }
  14635. if (ret == 0 && endKeyIdx != (int)*inOutIdx)
  14636. return ASN_PARSE_E;
  14637. return ret;
  14638. }
  14639. int wc_Ed448PublicKeyDecode(const byte* input, word32* inOutIdx,
  14640. ed448_key* key, word32 inSz)
  14641. {
  14642. int length;
  14643. int ret;
  14644. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  14645. return BAD_FUNC_ARG;
  14646. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14647. return ASN_PARSE_E;
  14648. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  14649. return ASN_PARSE_E;
  14650. ret = SkipObjectId(input, inOutIdx, inSz);
  14651. if (ret != 0)
  14652. return ret;
  14653. /* key header */
  14654. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  14655. if (ret != 0)
  14656. return ret;
  14657. /* This is the raw point data compressed or uncompressed. */
  14658. if (wc_ed448_import_public(input + *inOutIdx, inSz - *inOutIdx, key) != 0)
  14659. return ASN_ECC_KEY_E;
  14660. return 0;
  14661. }
  14662. #ifdef WOLFSSL_KEY_GEN
  14663. /* build DER formatted ED448 key,
  14664. * return length on success, negative on error */
  14665. static int wc_BuildEd448KeyDer(ed448_key* key, byte* output, word32 inLen,
  14666. int pubOut)
  14667. {
  14668. byte algoArray[MAX_ALGO_SZ];
  14669. byte ver[MAX_VERSION_SZ];
  14670. byte seq[MAX_SEQ_SZ];
  14671. int ret;
  14672. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0;
  14673. if (key == NULL || output == NULL || inLen == 0)
  14674. return BAD_FUNC_ARG;
  14675. if (pubOut) {
  14676. pubSz = 2 + 2 + ED448_PUB_KEY_SIZE;
  14677. }
  14678. privSz = 2 + 2 + ED448_KEY_SIZE;
  14679. algoSz = SetAlgoID(ED448k, algoArray, oidKeyType, 0);
  14680. verSz = SetMyVersion(0, ver, FALSE);
  14681. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, seq);
  14682. if (seqSz + verSz + algoSz + privSz + pubSz > inLen)
  14683. return BAD_FUNC_ARG;
  14684. /* write out */
  14685. /* seq */
  14686. XMEMCPY(output + idx, seq, seqSz);
  14687. idx = seqSz;
  14688. /* ver */
  14689. XMEMCPY(output + idx, ver, verSz);
  14690. idx += verSz;
  14691. /* algo */
  14692. XMEMCPY(output + idx, algoArray, algoSz);
  14693. idx += algoSz;
  14694. /* privKey */
  14695. idx += SetOctetString(2 + ED448_KEY_SIZE, output + idx);
  14696. idx += SetOctetString(ED448_KEY_SIZE, output + idx);
  14697. ret = wc_ed448_export_private_only(key, output + idx, &privSz);
  14698. if (ret != 0)
  14699. return ret;
  14700. idx += privSz;
  14701. /* pubKey */
  14702. if (pubOut) {
  14703. idx += SetExplicit(1, 2 + ED448_PUB_KEY_SIZE, output + idx);
  14704. idx += SetOctetString(ED448_KEY_SIZE, output + idx);
  14705. ret = wc_ed448_export_public(key, output + idx, &pubSz);
  14706. if (ret != 0)
  14707. return ret;
  14708. idx += pubSz;
  14709. }
  14710. return idx;
  14711. }
  14712. /* Write a Private ecc key, including public to DER format,
  14713. * length on success else < 0 */
  14714. int wc_Ed448KeyToDer(ed448_key* key, byte* output, word32 inLen)
  14715. {
  14716. return wc_BuildEd448KeyDer(key, output, inLen, 1);
  14717. }
  14718. /* Write only private ecc key to DER format,
  14719. * length on success else < 0 */
  14720. int wc_Ed448PrivateKeyToDer(ed448_key* key, byte* output, word32 inLen)
  14721. {
  14722. return wc_BuildEd448KeyDer(key, output, inLen, 0);
  14723. }
  14724. #endif /* WOLFSSL_KEY_GEN */
  14725. #endif /* HAVE_ED448 */
  14726. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  14727. /* Get raw Date only, no processing, 0 on success */
  14728. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  14729. byte* format, int maxIdx)
  14730. {
  14731. int ret, length;
  14732. const byte *datePtr = NULL;
  14733. WOLFSSL_ENTER("GetBasicDate");
  14734. ret = GetDateInfo(source, idx, &datePtr, format, &length, maxIdx);
  14735. if (ret < 0)
  14736. return ret;
  14737. XMEMCPY(date, datePtr, length);
  14738. return 0;
  14739. }
  14740. #endif /* HAVE_OCSP || HAVE_CRL */
  14741. #ifdef HAVE_OCSP
  14742. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value,
  14743. int sz)
  14744. {
  14745. word32 idx = *inOutIdx;
  14746. word32 len;
  14747. byte tag;
  14748. WOLFSSL_ENTER("GetEnumerated");
  14749. *value = 0;
  14750. if (GetASNTag(input, &idx, &tag, sz) < 0)
  14751. return ASN_PARSE_E;
  14752. if (tag != ASN_ENUMERATED)
  14753. return ASN_PARSE_E;
  14754. if ((int)idx >= sz)
  14755. return BUFFER_E;
  14756. len = input[idx++];
  14757. if (len > 4 || (int)(len + idx) > sz)
  14758. return ASN_PARSE_E;
  14759. while (len--) {
  14760. *value = *value << 8 | input[idx++];
  14761. }
  14762. *inOutIdx = idx;
  14763. return *value;
  14764. }
  14765. static int DecodeSingleResponse(byte* source, word32* ioIndex, word32 size,
  14766. int wrapperSz, OcspEntry* single)
  14767. {
  14768. word32 idx = *ioIndex, prevIndex, oid, localIdx, certIdIdx;
  14769. int length;
  14770. int ret;
  14771. byte tag;
  14772. WOLFSSL_ENTER("DecodeSingleResponse");
  14773. prevIndex = idx;
  14774. /* Wrapper around the Single Response */
  14775. if (GetSequence(source, &idx, &length, size) < 0)
  14776. return ASN_PARSE_E;
  14777. /* Wrapper around the CertID */
  14778. certIdIdx = idx;
  14779. if (GetSequence(source, &idx, &length, size) < 0)
  14780. return ASN_PARSE_E;
  14781. single->rawCertId = source + certIdIdx;
  14782. /* Hash algorithm */
  14783. ret = GetAlgoId(source, &idx, &oid, oidIgnoreType, size);
  14784. if (ret < 0)
  14785. return ret;
  14786. single->hashAlgoOID = oid;
  14787. /* Save reference to the hash of CN */
  14788. ret = GetOctetString(source, &idx, &length, size);
  14789. if (ret < 0)
  14790. return ret;
  14791. XMEMCPY(single->issuerHash, source + idx, length);
  14792. idx += length;
  14793. /* Save reference to the hash of the issuer public key */
  14794. ret = GetOctetString(source, &idx, &length, size);
  14795. if (ret < 0)
  14796. return ret;
  14797. XMEMCPY(single->issuerKeyHash, source + idx, length);
  14798. idx += length;
  14799. /* Get serial number */
  14800. if (GetSerialNumber(source, &idx, single->status->serial, &single->status->serialSz, size) < 0)
  14801. return ASN_PARSE_E;
  14802. single->rawCertIdSize = idx - certIdIdx;
  14803. if (idx >= size)
  14804. return BUFFER_E;
  14805. /* CertStatus */
  14806. switch (source[idx++])
  14807. {
  14808. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  14809. single->status->status = CERT_GOOD;
  14810. idx++;
  14811. break;
  14812. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  14813. single->status->status = CERT_REVOKED;
  14814. if (GetLength(source, &idx, &length, size) < 0)
  14815. return ASN_PARSE_E;
  14816. idx += length;
  14817. break;
  14818. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  14819. single->status->status = CERT_UNKNOWN;
  14820. idx++;
  14821. break;
  14822. default:
  14823. return ASN_PARSE_E;
  14824. }
  14825. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  14826. single->status->thisDateAsn = source + idx;
  14827. localIdx = 0;
  14828. if (GetDateInfo(single->status->thisDateAsn, &localIdx, NULL,
  14829. (byte*)&single->status->thisDateParsed.type,
  14830. &single->status->thisDateParsed.length, size) < 0)
  14831. return ASN_PARSE_E;
  14832. XMEMCPY(single->status->thisDateParsed.data,
  14833. single->status->thisDateAsn + localIdx - single->status->thisDateParsed.length,
  14834. single->status->thisDateParsed.length);
  14835. #endif
  14836. if (GetBasicDate(source, &idx, single->status->thisDate,
  14837. &single->status->thisDateFormat, size) < 0)
  14838. return ASN_PARSE_E;
  14839. #ifndef NO_ASN_TIME
  14840. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  14841. if (!XVALIDATE_DATE(single->status->thisDate, single->status->thisDateFormat, BEFORE))
  14842. return ASN_BEFORE_DATE_E;
  14843. #endif
  14844. #endif
  14845. /* The following items are optional. Only check for them if there is more
  14846. * unprocessed data in the singleResponse wrapper. */
  14847. localIdx = idx;
  14848. if (((int)(idx - prevIndex) < wrapperSz) &&
  14849. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  14850. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  14851. {
  14852. idx++;
  14853. if (GetLength(source, &idx, &length, size) < 0)
  14854. return ASN_PARSE_E;
  14855. #if defined(OPENSSL_ALL) || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  14856. single->status->nextDateAsn = source + idx;
  14857. localIdx = 0;
  14858. if (GetDateInfo(single->status->nextDateAsn, &localIdx, NULL,
  14859. (byte*)&single->status->nextDateParsed.type,
  14860. &single->status->nextDateParsed.length, size) < 0)
  14861. return ASN_PARSE_E;
  14862. XMEMCPY(single->status->nextDateParsed.data,
  14863. single->status->nextDateAsn + localIdx - single->status->nextDateParsed.length,
  14864. single->status->nextDateParsed.length);
  14865. #endif
  14866. if (GetBasicDate(source, &idx, single->status->nextDate,
  14867. &single->status->nextDateFormat, size) < 0)
  14868. return ASN_PARSE_E;
  14869. #ifndef NO_ASN_TIME
  14870. #ifndef WOLFSSL_NO_OCSP_DATE_CHECK
  14871. if (!XVALIDATE_DATE(single->status->nextDate, single->status->nextDateFormat, AFTER))
  14872. return ASN_AFTER_DATE_E;
  14873. #endif
  14874. #endif
  14875. }
  14876. /* Skip the optional extensions in singleResponse. */
  14877. localIdx = idx;
  14878. if (((int)(idx - prevIndex) < wrapperSz) &&
  14879. GetASNTag(source, &localIdx, &tag, size) == 0 &&
  14880. tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  14881. {
  14882. idx++;
  14883. if (GetLength(source, &idx, &length, size) < 0)
  14884. return ASN_PARSE_E;
  14885. idx += length;
  14886. }
  14887. *ioIndex = idx;
  14888. return 0;
  14889. }
  14890. static int DecodeOcspRespExtensions(byte* source,
  14891. word32* ioIndex, OcspResponse* resp, word32 sz)
  14892. {
  14893. word32 idx = *ioIndex;
  14894. int length;
  14895. int ext_bound; /* boundary index for the sequence of extensions */
  14896. word32 oid;
  14897. int ret;
  14898. byte tag;
  14899. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  14900. if ((idx + 1) > sz)
  14901. return BUFFER_E;
  14902. if (GetASNTag(source, &idx, &tag, sz) < 0)
  14903. return ASN_PARSE_E;
  14904. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  14905. return ASN_PARSE_E;
  14906. if (GetLength(source, &idx, &length, sz) < 0)
  14907. return ASN_PARSE_E;
  14908. if (GetSequence(source, &idx, &length, sz) < 0)
  14909. return ASN_PARSE_E;
  14910. ext_bound = idx + length;
  14911. while (idx < (word32)ext_bound) {
  14912. word32 localIdx;
  14913. if (GetSequence(source, &idx, &length, sz) < 0) {
  14914. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  14915. return ASN_PARSE_E;
  14916. }
  14917. oid = 0;
  14918. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  14919. WOLFSSL_MSG("\tfail: OBJECT ID");
  14920. return ASN_PARSE_E;
  14921. }
  14922. /* check for critical flag */
  14923. if ((idx + 1) > (word32)sz) {
  14924. WOLFSSL_MSG("\tfail: malformed buffer");
  14925. return BUFFER_E;
  14926. }
  14927. localIdx = idx;
  14928. if (GetASNTag(source, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  14929. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  14930. ret = GetBoolean(source, &idx, sz);
  14931. if (ret < 0)
  14932. return ret;
  14933. }
  14934. ret = GetOctetString(source, &idx, &length, sz);
  14935. if (ret < 0)
  14936. return ret;
  14937. if (oid == OCSP_NONCE_OID) {
  14938. /* get data inside extra OCTET_STRING */
  14939. ret = GetOctetString(source, &idx, &length, sz);
  14940. if (ret < 0)
  14941. return ret;
  14942. resp->nonce = source + idx;
  14943. resp->nonceSz = length;
  14944. }
  14945. idx += length;
  14946. }
  14947. *ioIndex = idx;
  14948. return 0;
  14949. }
  14950. static int DecodeResponseData(byte* source,
  14951. word32* ioIndex, OcspResponse* resp, word32 size)
  14952. {
  14953. word32 idx = *ioIndex, prev_idx, localIdx;
  14954. int length;
  14955. int version;
  14956. int ret;
  14957. byte tag;
  14958. int wrapperSz;
  14959. OcspEntry* single;
  14960. WOLFSSL_ENTER("DecodeResponseData");
  14961. resp->response = source + idx;
  14962. prev_idx = idx;
  14963. if (GetSequence(source, &idx, &length, size) < 0)
  14964. return ASN_PARSE_E;
  14965. resp->responseSz = length + idx - prev_idx;
  14966. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  14967. * item isn't an EXPLICIT[0], then set version to zero and move
  14968. * onto the next item.
  14969. */
  14970. localIdx = idx;
  14971. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  14972. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  14973. {
  14974. idx += 2; /* Eat the value and length */
  14975. if (GetMyVersion(source, &idx, &version, size) < 0)
  14976. return ASN_PARSE_E;
  14977. } else
  14978. version = 0;
  14979. localIdx = idx;
  14980. if (GetASNTag(source, &localIdx, &tag, size) == 0 &&
  14981. ( tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1) ||
  14982. tag == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2) ))
  14983. {
  14984. idx++; /* advance past ASN tag */
  14985. if (GetLength(source, &idx, &length, size) < 0)
  14986. return ASN_PARSE_E;
  14987. idx += length;
  14988. }
  14989. else
  14990. return ASN_PARSE_E;
  14991. /* save pointer to the producedAt time */
  14992. if (GetBasicDate(source, &idx, resp->producedDate,
  14993. &resp->producedDateFormat, size) < 0)
  14994. return ASN_PARSE_E;
  14995. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  14996. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  14997. return ASN_PARSE_E;
  14998. localIdx = idx;
  14999. single = resp->single;
  15000. while (idx - localIdx < (word32)wrapperSz) {
  15001. ret = DecodeSingleResponse(source, &idx, size, wrapperSz, single);
  15002. if (ret < 0)
  15003. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  15004. if (idx - localIdx < (word32)wrapperSz) {
  15005. single->next = (OcspEntry*)XMALLOC(sizeof(OcspEntry), resp->heap,
  15006. DYNAMIC_TYPE_OCSP_ENTRY);
  15007. if (single->next == NULL) {
  15008. return MEMORY_E;
  15009. }
  15010. single = single->next;
  15011. XMEMSET(single, 0, sizeof(OcspEntry));
  15012. single->isDynamic = 1;
  15013. }
  15014. }
  15015. /*
  15016. * Check the length of the ResponseData against the current index to
  15017. * see if there are extensions, they are optional.
  15018. */
  15019. if (idx - prev_idx < resp->responseSz)
  15020. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  15021. return ASN_PARSE_E;
  15022. *ioIndex = idx;
  15023. return 0;
  15024. }
  15025. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  15026. static int DecodeCerts(byte* source,
  15027. word32* ioIndex, OcspResponse* resp, word32 size)
  15028. {
  15029. word32 idx = *ioIndex;
  15030. byte tag;
  15031. WOLFSSL_ENTER("DecodeCerts");
  15032. if (GetASNTag(source, &idx, &tag, size) < 0)
  15033. return ASN_PARSE_E;
  15034. if (tag == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  15035. {
  15036. int length;
  15037. if (GetLength(source, &idx, &length, size) < 0)
  15038. return ASN_PARSE_E;
  15039. if (GetSequence(source, &idx, &length, size) < 0)
  15040. return ASN_PARSE_E;
  15041. resp->cert = source + idx;
  15042. resp->certSz = length;
  15043. idx += length;
  15044. }
  15045. *ioIndex = idx;
  15046. return 0;
  15047. }
  15048. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  15049. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  15050. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  15051. {
  15052. int length;
  15053. word32 idx = *ioIndex;
  15054. word32 end_index;
  15055. int ret;
  15056. int sigLength;
  15057. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  15058. (void)heap;
  15059. if (GetSequence(source, &idx, &length, size) < 0)
  15060. return ASN_PARSE_E;
  15061. if (idx + length > size)
  15062. return ASN_INPUT_E;
  15063. end_index = idx + length;
  15064. if ((ret = DecodeResponseData(source, &idx, resp, size)) < 0)
  15065. return ret; /* ASN_PARSE_E, ASN_BEFORE_DATE_E, ASN_AFTER_DATE_E */
  15066. /* Get the signature algorithm */
  15067. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0)
  15068. return ASN_PARSE_E;
  15069. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  15070. if (ret != 0)
  15071. return ret;
  15072. resp->sigSz = sigLength;
  15073. resp->sig = source + idx;
  15074. idx += sigLength;
  15075. /*
  15076. * Check the length of the BasicOcspResponse against the current index to
  15077. * see if there are certificates, they are optional.
  15078. */
  15079. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  15080. if (idx < end_index)
  15081. {
  15082. DecodedCert cert;
  15083. if (DecodeCerts(source, &idx, resp, size) < 0)
  15084. return ASN_PARSE_E;
  15085. InitDecodedCert(&cert, resp->cert, resp->certSz, heap);
  15086. /* Don't verify if we don't have access to Cert Manager. */
  15087. ret = ParseCertRelative(&cert, CERT_TYPE,
  15088. noVerify ? NO_VERIFY : VERIFY_OCSP, cm);
  15089. if (ret < 0) {
  15090. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  15091. FreeDecodedCert(&cert);
  15092. return ret;
  15093. }
  15094. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  15095. if ((cert.extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  15096. if (XMEMCMP(cert.subjectHash,
  15097. resp->single->issuerHash, OCSP_DIGEST_SIZE) == 0) {
  15098. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  15099. }
  15100. else {
  15101. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  15102. #ifdef OPENSSL_EXTRA
  15103. resp->verifyError = OCSP_BAD_ISSUER;
  15104. #else
  15105. FreeDecodedCert(&cert);
  15106. return BAD_OCSP_RESPONDER;
  15107. #endif
  15108. }
  15109. }
  15110. #endif
  15111. /* ConfirmSignature is blocking here */
  15112. ret = ConfirmSignature(&cert.sigCtx,
  15113. resp->response, resp->responseSz,
  15114. cert.publicKey, cert.pubKeySize, cert.keyOID,
  15115. resp->sig, resp->sigSz, resp->sigOID, NULL);
  15116. FreeDecodedCert(&cert);
  15117. if (ret != 0) {
  15118. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  15119. return ASN_OCSP_CONFIRM_E;
  15120. }
  15121. }
  15122. else
  15123. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  15124. {
  15125. Signer* ca;
  15126. int sigValid = -1;
  15127. #ifndef NO_SKID
  15128. ca = GetCA(cm, resp->single->issuerKeyHash);
  15129. #else
  15130. ca = GetCA(cm, resp->single->issuerHash);
  15131. #endif
  15132. if (ca) {
  15133. SignatureCtx sigCtx;
  15134. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  15135. /* ConfirmSignature is blocking here */
  15136. sigValid = ConfirmSignature(&sigCtx, resp->response,
  15137. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  15138. resp->sig, resp->sigSz, resp->sigOID, NULL);
  15139. }
  15140. if (ca == NULL || sigValid != 0) {
  15141. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  15142. return ASN_OCSP_CONFIRM_E;
  15143. }
  15144. (void)noVerify;
  15145. }
  15146. *ioIndex = idx;
  15147. return 0;
  15148. }
  15149. void InitOcspResponse(OcspResponse* resp, OcspEntry* single, CertStatus* status,
  15150. byte* source, word32 inSz, void* heap)
  15151. {
  15152. WOLFSSL_ENTER("InitOcspResponse");
  15153. XMEMSET(status, 0, sizeof(CertStatus));
  15154. XMEMSET(single, 0, sizeof(OcspEntry));
  15155. XMEMSET(resp, 0, sizeof(OcspResponse));
  15156. single->status = status;
  15157. resp->responseStatus = -1;
  15158. resp->single = single;
  15159. resp->source = source;
  15160. resp->maxIdx = inSz;
  15161. resp->heap = heap;
  15162. }
  15163. void FreeOcspResponse(OcspResponse* resp)
  15164. {
  15165. OcspEntry *single, *next;
  15166. for (single = resp->single; single; single = next) {
  15167. next = single->next;
  15168. if (single->isDynamic)
  15169. XFREE(single, resp->heap, DYNAMIC_TYPE_OCSP_ENTRY);
  15170. }
  15171. }
  15172. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  15173. {
  15174. int ret;
  15175. int length = 0;
  15176. word32 idx = 0;
  15177. byte* source = resp->source;
  15178. word32 size = resp->maxIdx;
  15179. word32 oid;
  15180. byte tag;
  15181. WOLFSSL_ENTER("OcspResponseDecode");
  15182. /* peel the outer SEQUENCE wrapper */
  15183. if (GetSequence(source, &idx, &length, size) < 0)
  15184. return ASN_PARSE_E;
  15185. /* First get the responseStatus, an ENUMERATED */
  15186. if (GetEnumerated(source, &idx, &resp->responseStatus, size) < 0)
  15187. return ASN_PARSE_E;
  15188. if (resp->responseStatus != OCSP_SUCCESSFUL)
  15189. return 0;
  15190. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  15191. if (idx >= size)
  15192. return ASN_INPUT_E;
  15193. if (GetASNTag(source, &idx, &tag, size) < 0)
  15194. return ASN_PARSE_E;
  15195. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  15196. return ASN_PARSE_E;
  15197. if (GetLength(source, &idx, &length, size) < 0)
  15198. return ASN_PARSE_E;
  15199. /* Get the responseBytes SEQUENCE */
  15200. if (GetSequence(source, &idx, &length, size) < 0)
  15201. return ASN_PARSE_E;
  15202. /* Check ObjectID for the resposeBytes */
  15203. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0)
  15204. return ASN_PARSE_E;
  15205. if (oid != OCSP_BASIC_OID)
  15206. return ASN_PARSE_E;
  15207. ret = GetOctetString(source, &idx, &length, size);
  15208. if (ret < 0)
  15209. return ret;
  15210. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  15211. if (ret < 0)
  15212. return ret;
  15213. return 0;
  15214. }
  15215. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  15216. {
  15217. const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  15218. 0x30, 0x01, 0x02 };
  15219. byte seqArray[5][MAX_SEQ_SZ];
  15220. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  15221. WOLFSSL_ENTER("SetOcspReqExtensions");
  15222. if (!req || !output || !req->nonceSz)
  15223. return 0;
  15224. totalSz += req->nonceSz;
  15225. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  15226. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  15227. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  15228. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  15229. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  15230. if (totalSz > size)
  15231. return 0;
  15232. totalSz = 0;
  15233. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  15234. totalSz += seqSz[4];
  15235. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  15236. totalSz += seqSz[3];
  15237. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  15238. totalSz += seqSz[2];
  15239. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  15240. totalSz += (word32)sizeof(NonceObjId);
  15241. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  15242. totalSz += seqSz[1];
  15243. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  15244. totalSz += seqSz[0];
  15245. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  15246. totalSz += req->nonceSz;
  15247. return totalSz;
  15248. }
  15249. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  15250. {
  15251. byte seqArray[5][MAX_SEQ_SZ];
  15252. /* The ASN.1 of the OCSP Request is an onion of sequences */
  15253. byte algoArray[MAX_ALGO_SZ];
  15254. byte issuerArray[MAX_ENCODED_DIG_SZ];
  15255. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  15256. byte snArray[MAX_SN_SZ];
  15257. byte extArray[MAX_OCSP_EXT_SZ];
  15258. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  15259. int i, snSz;
  15260. WOLFSSL_ENTER("EncodeOcspRequest");
  15261. #ifdef NO_SHA
  15262. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  15263. #else
  15264. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  15265. #endif
  15266. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  15267. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  15268. snSz = SetSerialNumber(req->serial, req->serialSz, snArray,
  15269. MAX_SN_SZ, MAX_SN_SZ);
  15270. extSz = 0;
  15271. if (snSz < 0)
  15272. return snSz;
  15273. if (req->nonceSz) {
  15274. /* TLS Extensions use this function too - put extensions after
  15275. * ASN.1: Context Specific [2].
  15276. */
  15277. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  15278. OCSP_NONCE_EXT_SZ);
  15279. extSz += SetExplicit(2, extSz, extArray);
  15280. }
  15281. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  15282. for (i = 4; i >= 0; i--) {
  15283. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  15284. totalSz += seqSz[i];
  15285. if (i == 2) totalSz += extSz;
  15286. }
  15287. if (output == NULL)
  15288. return totalSz;
  15289. if (totalSz > size)
  15290. return BUFFER_E;
  15291. totalSz = 0;
  15292. for (i = 0; i < 5; i++) {
  15293. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  15294. totalSz += seqSz[i];
  15295. }
  15296. XMEMCPY(output + totalSz, algoArray, algoSz);
  15297. totalSz += algoSz;
  15298. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  15299. totalSz += issuerSz;
  15300. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  15301. totalSz += issuerKeySz;
  15302. XMEMCPY(output + totalSz, snArray, snSz);
  15303. totalSz += snSz;
  15304. if (extSz != 0) {
  15305. XMEMCPY(output + totalSz, extArray, extSz);
  15306. totalSz += extSz;
  15307. }
  15308. return totalSz;
  15309. }
  15310. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  15311. void* heap)
  15312. {
  15313. int ret;
  15314. WOLFSSL_ENTER("InitOcspRequest");
  15315. if (req == NULL)
  15316. return BAD_FUNC_ARG;
  15317. ForceZero(req, sizeof(OcspRequest));
  15318. req->heap = heap;
  15319. if (cert) {
  15320. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  15321. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  15322. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  15323. DYNAMIC_TYPE_OCSP_REQUEST);
  15324. if (req->serial == NULL)
  15325. return MEMORY_E;
  15326. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  15327. req->serialSz = cert->serialSz;
  15328. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  15329. req->url = (byte*)XMALLOC(cert->extAuthInfoSz + 1, req->heap,
  15330. DYNAMIC_TYPE_OCSP_REQUEST);
  15331. if (req->url == NULL) {
  15332. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  15333. return MEMORY_E;
  15334. }
  15335. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  15336. req->urlSz = cert->extAuthInfoSz;
  15337. req->url[req->urlSz] = 0;
  15338. }
  15339. }
  15340. if (useNonce) {
  15341. WC_RNG rng;
  15342. #ifndef HAVE_FIPS
  15343. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  15344. #else
  15345. ret = wc_InitRng(&rng);
  15346. #endif
  15347. if (ret != 0) {
  15348. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
  15349. } else {
  15350. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  15351. WOLFSSL_MSG("\tCannot run RNG. Skipping the OSCP Nonce.");
  15352. else
  15353. req->nonceSz = MAX_OCSP_NONCE_SZ;
  15354. wc_FreeRng(&rng);
  15355. }
  15356. }
  15357. return 0;
  15358. }
  15359. void FreeOcspRequest(OcspRequest* req)
  15360. {
  15361. WOLFSSL_ENTER("FreeOcspRequest");
  15362. if (req) {
  15363. if (req->serial)
  15364. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  15365. req->serial = NULL;
  15366. #ifdef OPENSSL_EXTRA
  15367. if (req->serialInt) {
  15368. if (req->serialInt->isDynamic) {
  15369. XFREE(req->serialInt->data, NULL, DYNAMIC_TYPE_OPENSSL);
  15370. }
  15371. XFREE(req->serialInt, NULL, DYNAMIC_TYPE_OPENSSL);
  15372. }
  15373. req->serialInt = NULL;
  15374. #endif
  15375. if (req->url)
  15376. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  15377. req->url = NULL;
  15378. }
  15379. }
  15380. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  15381. {
  15382. int cmp = -1; /* default as not matching, cmp gets set on each check */
  15383. OcspEntry *single, *next, *prev = NULL, *top;
  15384. WOLFSSL_ENTER("CompareOcspReqResp");
  15385. if (req == NULL) {
  15386. WOLFSSL_MSG("\tReq missing");
  15387. return -1;
  15388. }
  15389. if (resp == NULL || resp->single == NULL) {
  15390. WOLFSSL_MSG("\tResp missing");
  15391. return 1;
  15392. }
  15393. /* Nonces are not critical. The responder may not necessarily add
  15394. * the nonce to the response. */
  15395. if (req->nonceSz && resp->nonce != NULL
  15396. #ifndef WOLFSSL_FORCE_OCSP_NONCE_CHECK
  15397. && resp->nonceSz != 0
  15398. #endif
  15399. ) {
  15400. cmp = req->nonceSz - resp->nonceSz;
  15401. if (cmp != 0) {
  15402. WOLFSSL_MSG("\tnonceSz mismatch");
  15403. return cmp;
  15404. }
  15405. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  15406. if (cmp != 0) {
  15407. WOLFSSL_MSG("\tnonce mismatch");
  15408. return cmp;
  15409. }
  15410. }
  15411. /* match based on found status and return */
  15412. for (single = resp->single; single; single = next) {
  15413. cmp = req->serialSz - single->status->serialSz;
  15414. if (cmp == 0) {
  15415. cmp = XMEMCMP(req->serial, single->status->serial, req->serialSz)
  15416. || XMEMCMP(req->issuerHash, single->issuerHash, OCSP_DIGEST_SIZE)
  15417. || XMEMCMP(req->issuerKeyHash, single->issuerKeyHash, OCSP_DIGEST_SIZE);
  15418. if (cmp == 0) {
  15419. /* match found */
  15420. if (resp->single != single && prev) {
  15421. /* move to top of list */
  15422. top = resp->single;
  15423. resp->single = single;
  15424. prev->next = single->next;
  15425. single->next = top;
  15426. }
  15427. break;
  15428. }
  15429. }
  15430. next = single->next;
  15431. prev = single;
  15432. }
  15433. if (cmp != 0) {
  15434. WOLFSSL_MSG("\trequest and response mismatch");
  15435. return cmp;
  15436. }
  15437. return 0;
  15438. }
  15439. #endif /* HAVE_OCSP */
  15440. /* store WC_SHA hash of NAME */
  15441. int GetNameHash(const byte* source, word32* idx, byte* hash,
  15442. int maxIdx)
  15443. {
  15444. int length; /* length of all distinguished names */
  15445. int ret;
  15446. word32 dummy;
  15447. byte tag;
  15448. WOLFSSL_ENTER("GetNameHash");
  15449. dummy = *idx;
  15450. if (GetASNTag(source, &dummy, &tag, maxIdx) == 0 && tag == ASN_OBJECT_ID) {
  15451. WOLFSSL_MSG("Trying optional prefix...");
  15452. if (GetLength(source, idx, &length, maxIdx) < 0)
  15453. return ASN_PARSE_E;
  15454. *idx += length;
  15455. WOLFSSL_MSG("Got optional prefix");
  15456. }
  15457. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  15458. * calculated over the entire DER encoding of the Name field, including
  15459. * the tag and length. */
  15460. dummy = *idx;
  15461. if (GetSequence(source, idx, &length, maxIdx) < 0)
  15462. return ASN_PARSE_E;
  15463. ret = CalcHashId(source + dummy, length + *idx - dummy, hash);
  15464. *idx += length;
  15465. return ret;
  15466. }
  15467. #ifdef HAVE_CRL
  15468. /* initialize decoded CRL */
  15469. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  15470. {
  15471. WOLFSSL_MSG("InitDecodedCRL");
  15472. XMEMSET(dcrl, 0, sizeof(DecodedCRL));
  15473. dcrl->heap = heap;
  15474. #ifdef WOLFSSL_HEAP_TEST
  15475. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  15476. #endif
  15477. }
  15478. /* free decoded CRL resources */
  15479. void FreeDecodedCRL(DecodedCRL* dcrl)
  15480. {
  15481. RevokedCert* tmp = dcrl->certs;
  15482. WOLFSSL_MSG("FreeDecodedCRL");
  15483. while(tmp) {
  15484. RevokedCert* next = tmp->next;
  15485. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  15486. tmp = next;
  15487. }
  15488. }
  15489. /* Get Revoked Cert list, 0 on success */
  15490. static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
  15491. int maxIdx)
  15492. {
  15493. int ret, len;
  15494. word32 end;
  15495. byte b;
  15496. RevokedCert* rc;
  15497. WOLFSSL_ENTER("GetRevoked");
  15498. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  15499. return ASN_PARSE_E;
  15500. end = *idx + len;
  15501. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  15502. DYNAMIC_TYPE_REVOKED);
  15503. if (rc == NULL) {
  15504. WOLFSSL_MSG("Alloc Revoked Cert failed");
  15505. return MEMORY_E;
  15506. }
  15507. if (GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,
  15508. maxIdx) < 0) {
  15509. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  15510. return ASN_PARSE_E;
  15511. }
  15512. /* add to list */
  15513. rc->next = dcrl->certs;
  15514. dcrl->certs = rc;
  15515. dcrl->totalCerts++;
  15516. /* get date */
  15517. ret = GetDateInfo(buff, idx, NULL, &b, NULL, maxIdx);
  15518. if (ret < 0) {
  15519. WOLFSSL_MSG("Expecting Date");
  15520. return ret;
  15521. }
  15522. /* skip extensions */
  15523. *idx = end;
  15524. return 0;
  15525. }
  15526. /* Get CRL Signature, 0 on success */
  15527. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  15528. int maxIdx)
  15529. {
  15530. int length;
  15531. int ret;
  15532. WOLFSSL_ENTER("GetCRL_Signature");
  15533. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  15534. if (ret != 0)
  15535. return ret;
  15536. dcrl->sigLength = length;
  15537. dcrl->signature = (byte*)&source[*idx];
  15538. *idx += dcrl->sigLength;
  15539. return 0;
  15540. }
  15541. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  15542. word32 tbsSz, const byte* signature, word32 sigSz,
  15543. word32 signatureOID, Signer *ca, void* heap)
  15544. {
  15545. /* try to confirm/verify signature */
  15546. #ifndef IGNORE_KEY_EXTENSIONS
  15547. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  15548. WOLFSSL_MSG("CA cannot sign CRLs");
  15549. return ASN_CRL_NO_SIGNER_E;
  15550. }
  15551. #endif /* IGNORE_KEY_EXTENSIONS */
  15552. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  15553. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  15554. ca->pubKeySize, ca->keyOID, signature, sigSz,
  15555. signatureOID, NULL) != 0) {
  15556. WOLFSSL_MSG("CRL Confirm signature failed");
  15557. return ASN_CRL_CONFIRM_E;
  15558. }
  15559. return 0;
  15560. }
  15561. static int ParseCRL_CertList(DecodedCRL* dcrl, const byte* buf,
  15562. word32* inOutIdx, int sz)
  15563. {
  15564. word32 oid, dateIdx, idx, checkIdx;
  15565. int version;
  15566. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  15567. int doNextDate = 1;
  15568. #endif
  15569. byte tag;
  15570. if (dcrl == NULL || inOutIdx == NULL || buf == NULL) {
  15571. return BAD_FUNC_ARG;
  15572. }
  15573. /* may have version */
  15574. idx = *inOutIdx;
  15575. checkIdx = idx;
  15576. if (GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag == ASN_INTEGER) {
  15577. if (GetMyVersion(buf, &idx, &version, sz) < 0)
  15578. return ASN_PARSE_E;
  15579. }
  15580. if (GetAlgoId(buf, &idx, &oid, oidIgnoreType, sz) < 0)
  15581. return ASN_PARSE_E;
  15582. if (GetNameHash(buf, &idx, dcrl->issuerHash, sz) < 0)
  15583. return ASN_PARSE_E;
  15584. if (GetBasicDate(buf, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  15585. return ASN_PARSE_E;
  15586. dateIdx = idx;
  15587. if (GetBasicDate(buf, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  15588. {
  15589. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  15590. (void)dateIdx;
  15591. return ASN_PARSE_E;
  15592. #else
  15593. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  15594. doNextDate = 0;
  15595. idx = dateIdx;
  15596. #endif
  15597. }
  15598. #ifdef WOLFSSL_NO_CRL_NEXT_DATE
  15599. if (doNextDate)x
  15600. #endif
  15601. {
  15602. #ifndef NO_ASN_TIME
  15603. if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  15604. WOLFSSL_MSG("CRL after date is no longer valid");
  15605. return ASN_AFTER_DATE_E;
  15606. }
  15607. #endif
  15608. }
  15609. checkIdx = idx;
  15610. if (idx != dcrl->sigIndex &&
  15611. GetASNTag(buf, &checkIdx, &tag, sz) == 0 && tag != CRL_EXTENSIONS) {
  15612. int len;
  15613. if (GetSequence(buf, &idx, &len, sz) < 0)
  15614. return ASN_PARSE_E;
  15615. len += idx;
  15616. while (idx < (word32)len) {
  15617. if (GetRevoked(buf, &idx, dcrl, len) < 0)
  15618. return ASN_PARSE_E;
  15619. }
  15620. }
  15621. *inOutIdx = idx;
  15622. return 0;
  15623. }
  15624. #ifndef NO_SKID
  15625. static int ParseCRL_AuthKeyIdExt(const byte* input, int sz, DecodedCRL* dcrl)
  15626. {
  15627. word32 idx = 0;
  15628. int length = 0, ret = 0;
  15629. byte tag;
  15630. WOLFSSL_ENTER("ParseCRL_AuthKeyIdExt");
  15631. if (GetSequence(input, &idx, &length, sz) < 0) {
  15632. WOLFSSL_MSG("\tfail: should be a SEQUENCE\n");
  15633. return ASN_PARSE_E;
  15634. }
  15635. if (GetASNTag(input, &idx, &tag, sz) < 0) {
  15636. return ASN_PARSE_E;
  15637. }
  15638. if (tag != (ASN_CONTEXT_SPECIFIC | 0)) {
  15639. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
  15640. return 0;
  15641. }
  15642. if (GetLength(input, &idx, &length, sz) <= 0) {
  15643. WOLFSSL_MSG("\tfail: extension data length");
  15644. return ASN_PARSE_E;
  15645. }
  15646. dcrl->extAuthKeyIdSet = 1;
  15647. if (length == KEYID_SIZE) {
  15648. XMEMCPY(dcrl->extAuthKeyId, input + idx, length);
  15649. }
  15650. else {
  15651. ret = CalcHashId(input + idx, length, dcrl->extAuthKeyId);
  15652. }
  15653. return ret;
  15654. }
  15655. #endif
  15656. static int ParseCRL_Extensions(DecodedCRL* dcrl, const byte* buf,
  15657. word32* inOutIdx, word32 sz)
  15658. {
  15659. int length;
  15660. word32 idx;
  15661. word32 ext_bound; /* boundary index for the sequence of extensions */
  15662. word32 oid;
  15663. byte tag;
  15664. WOLFSSL_ENTER("ParseCRL_Extensions");
  15665. (void)dcrl;
  15666. if (inOutIdx == NULL)
  15667. return BAD_FUNC_ARG;
  15668. idx = *inOutIdx;
  15669. /* CRL Extensions are optional */
  15670. if ((idx + 1) > sz)
  15671. return 0;
  15672. /* CRL Extensions are optional */
  15673. if (GetASNTag(buf, &idx, &tag, sz) < 0)
  15674. return 0;
  15675. /* CRL Extensions are optional */
  15676. if (tag != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  15677. return 0;
  15678. if (GetLength(buf, &idx, &length, sz) < 0)
  15679. return ASN_PARSE_E;
  15680. if (GetSequence(buf, &idx, &length, sz) < 0)
  15681. return ASN_PARSE_E;
  15682. ext_bound = idx + length;
  15683. while (idx < (word32)ext_bound) {
  15684. word32 localIdx;
  15685. int ret;
  15686. if (GetSequence(buf, &idx, &length, sz) < 0) {
  15687. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  15688. return ASN_PARSE_E;
  15689. }
  15690. oid = 0;
  15691. if (GetObjectId(buf, &idx, &oid, oidCrlExtType, sz) < 0) {
  15692. WOLFSSL_MSG("\tfail: OBJECT ID");
  15693. return ASN_PARSE_E;
  15694. }
  15695. /* check for critical flag */
  15696. if ((idx + 1) > (word32)sz) {
  15697. WOLFSSL_MSG("\tfail: malformed buffer");
  15698. return BUFFER_E;
  15699. }
  15700. localIdx = idx;
  15701. if (GetASNTag(buf, &localIdx, &tag, sz) == 0 && tag == ASN_BOOLEAN) {
  15702. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  15703. ret = GetBoolean(buf, &idx, sz);
  15704. if (ret < 0)
  15705. return ret;
  15706. }
  15707. ret = GetOctetString(buf, &idx, &length, sz);
  15708. if (ret < 0)
  15709. return ret;
  15710. if (oid == AUTH_KEY_OID) {
  15711. #ifndef NO_SKID
  15712. ret = ParseCRL_AuthKeyIdExt(buf + idx, length, dcrl);
  15713. if (ret < 0) {
  15714. WOLFSSL_MSG("\tcouldn't parse AuthKeyId extension");
  15715. return ret;
  15716. }
  15717. #endif
  15718. }
  15719. idx += length;
  15720. }
  15721. *inOutIdx = idx;
  15722. return 0;
  15723. }
  15724. /* parse crl buffer into decoded state, 0 on success */
  15725. int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
  15726. {
  15727. int len;
  15728. word32 idx = 0;
  15729. Signer* ca = NULL;
  15730. SignatureCtx sigCtx;
  15731. WOLFSSL_MSG("ParseCRL");
  15732. /* raw crl hash */
  15733. /* hash here if needed for optimized comparisons
  15734. * wc_Sha sha;
  15735. * wc_InitSha(&sha);
  15736. * wc_ShaUpdate(&sha, buff, sz);
  15737. * wc_ShaFinal(&sha, dcrl->crlHash); */
  15738. if (GetSequence(buff, &idx, &len, sz) < 0)
  15739. return ASN_PARSE_E;
  15740. dcrl->certBegin = idx;
  15741. /* Normalize sz for the length inside the outer sequence. */
  15742. sz = len + idx;
  15743. if (GetSequence(buff, &idx, &len, sz) < 0)
  15744. return ASN_PARSE_E;
  15745. dcrl->sigIndex = len + idx;
  15746. if (ParseCRL_CertList(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  15747. return ASN_PARSE_E;
  15748. if (ParseCRL_Extensions(dcrl, buff, &idx, dcrl->sigIndex) < 0)
  15749. return ASN_PARSE_E;
  15750. idx = dcrl->sigIndex;
  15751. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  15752. return ASN_PARSE_E;
  15753. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  15754. return ASN_PARSE_E;
  15755. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  15756. if experiencing issues uncomment NO_SKID define in CRL section of
  15757. wolfssl/wolfcrypt/settings.h */
  15758. #ifndef NO_SKID
  15759. if (dcrl->extAuthKeyIdSet) {
  15760. ca = GetCA(cm, dcrl->extAuthKeyId); /* more unique than issuerHash */
  15761. }
  15762. if (ca != NULL && XMEMCMP(dcrl->issuerHash, ca->subjectNameHash,
  15763. KEYID_SIZE) != 0) {
  15764. ca = NULL;
  15765. }
  15766. if (ca == NULL) {
  15767. ca = GetCAByName(cm, dcrl->issuerHash); /* last resort */
  15768. /* If AKID is available then this CA doesn't have the public
  15769. * key required */
  15770. if (ca && dcrl->extAuthKeyIdSet) {
  15771. WOLFSSL_MSG("CA SKID doesn't match AKID");
  15772. ca = NULL;
  15773. }
  15774. }
  15775. #else
  15776. ca = GetCA(cm, dcrl->issuerHash);
  15777. #endif /* !NO_SKID */
  15778. WOLFSSL_MSG("About to verify CRL signature");
  15779. if (ca == NULL) {
  15780. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  15781. return ASN_CRL_NO_SIGNER_E;
  15782. }
  15783. WOLFSSL_MSG("Found CRL issuer CA");
  15784. return VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  15785. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  15786. dcrl->signatureOID, ca, dcrl->heap);
  15787. }
  15788. #endif /* HAVE_CRL */
  15789. #ifdef WOLFSSL_CERT_PIV
  15790. int wc_ParseCertPIV(wc_CertPIV* piv, const byte* buf, word32 totalSz)
  15791. {
  15792. int length = 0;
  15793. word32 idx = 0;
  15794. WOLFSSL_ENTER("wc_ParseCertPIV");
  15795. if (piv == NULL || buf == NULL || totalSz == 0)
  15796. return BAD_FUNC_ARG;
  15797. XMEMSET(piv, 0, sizeof(wc_CertPIV));
  15798. /* Detect Identiv PIV (with 0x0A, 0x0B and 0x0C sections) */
  15799. /* Certificate (0A 82 05FA) */
  15800. if (GetASNHeader(buf, ASN_PIV_CERT, &idx, &length, totalSz) >= 0) {
  15801. /* Identiv Type PIV card */
  15802. piv->isIdentiv = 1;
  15803. piv->cert = &buf[idx];
  15804. piv->certSz = length;
  15805. idx += length;
  15806. /* Nonce (0B 14) */
  15807. if (GetASNHeader(buf, ASN_PIV_NONCE, &idx, &length, totalSz) >= 0) {
  15808. piv->nonce = &buf[idx];
  15809. piv->nonceSz = length;
  15810. idx += length;
  15811. }
  15812. /* Signed Nonce (0C 82 0100) */
  15813. if (GetASNHeader(buf, ASN_PIV_SIGNED_NONCE, &idx, &length, totalSz) >= 0) {
  15814. piv->signedNonce = &buf[idx];
  15815. piv->signedNonceSz = length;
  15816. }
  15817. idx = 0;
  15818. buf = piv->cert;
  15819. totalSz = piv->certSz;
  15820. }
  15821. /* Certificate Buffer Total Size (53 82 05F6) */
  15822. if (GetASNHeader(buf, ASN_APPLICATION | ASN_PRINTABLE_STRING, &idx,
  15823. &length, totalSz) < 0) {
  15824. return ASN_PARSE_E;
  15825. }
  15826. /* PIV Certificate (70 82 05ED) */
  15827. if (GetASNHeader(buf, ASN_PIV_TAG_CERT, &idx, &length,
  15828. totalSz) < 0) {
  15829. return ASN_PARSE_E;
  15830. }
  15831. /* Capture certificate buffer pointer and length */
  15832. piv->cert = &buf[idx];
  15833. piv->certSz = length;
  15834. idx += length;
  15835. /* PIV Certificate Info (71 01 00) */
  15836. if (GetASNHeader(buf, ASN_PIV_TAG_CERT_INFO, &idx, &length,
  15837. totalSz) >= 0) {
  15838. if (length >= 1) {
  15839. piv->compression = (buf[idx] & ASN_PIV_CERT_INFO_COMPRESSED);
  15840. piv->isX509 = (buf[idx] & ASN_PIV_CERT_INFO_ISX509);
  15841. }
  15842. idx += length;
  15843. }
  15844. /* PIV Error Detection (FE 00) */
  15845. if (GetASNHeader(buf, ASN_PIV_TAG_ERR_DET, &idx, &length,
  15846. totalSz) >= 0) {
  15847. piv->certErrDet = &buf[idx];
  15848. piv->certErrDetSz = length;
  15849. idx += length;
  15850. }
  15851. return 0;
  15852. }
  15853. #endif /* WOLFSSL_CERT_PIV */
  15854. #ifdef HAVE_SMIME
  15855. /*****************************************************************************
  15856. * wc_MIME_parse_headers - Reads the char array in and parses out MIME headers
  15857. * and parameters into headers. Will continue until in has no more content.
  15858. *
  15859. * RETURNS:
  15860. * returns zero on success, non-zero on error.
  15861. */
  15862. int wc_MIME_parse_headers(char* in, int inLen, MimeHdr** headers)
  15863. {
  15864. MimeHdr* nextHdr = NULL;
  15865. MimeHdr* curHdr = NULL;
  15866. MimeParam* nextParam = NULL;
  15867. size_t start = 0;
  15868. size_t end = 0;
  15869. char* nameAttr = NULL;
  15870. char* bodyVal = NULL;
  15871. MimeTypes mimeType = MIME_HDR;
  15872. MimeStatus mimeStatus = MIME_NAMEATTR;
  15873. int ret = -1;
  15874. size_t pos = 0;
  15875. size_t lineLen = 0;
  15876. char* curLine = NULL;
  15877. char* ptr = NULL;
  15878. if (in == NULL || inLen <= 0 || in[inLen] != '\0' || headers == NULL) {
  15879. ret = BAD_FUNC_ARG;
  15880. goto error;
  15881. }
  15882. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL, DYNAMIC_TYPE_PKCS7);
  15883. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  15884. DYNAMIC_TYPE_PKCS7);
  15885. if (nextHdr == NULL || nextParam == NULL) {
  15886. ret = MEMORY_E;
  15887. goto error;
  15888. }
  15889. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  15890. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  15891. curLine = XSTRTOK(in, "\r\n", &ptr);
  15892. if (curLine == NULL) {
  15893. ret = ASN_PARSE_E;
  15894. goto error;
  15895. }
  15896. while (curLine != NULL) {
  15897. /* Leftover from previous line, add params to previous header. */
  15898. if (curLine[0] == ' ' && curHdr) {
  15899. mimeType = MIME_PARAM;
  15900. }
  15901. else {
  15902. mimeType = MIME_HDR;
  15903. }
  15904. start = end = 0;
  15905. lineLen = XSTRLEN(curLine);
  15906. if (lineLen == 0) {
  15907. ret = BAD_FUNC_ARG;
  15908. goto error;
  15909. }
  15910. for (pos = 0; pos < lineLen; pos++) {
  15911. char cur = curLine[pos];
  15912. if (mimeStatus == MIME_NAMEATTR && ((cur == ':' &&
  15913. mimeType == MIME_HDR) || (cur == '=' &&
  15914. mimeType == MIME_PARAM)) && pos >= 1) {
  15915. mimeStatus = MIME_BODYVAL;
  15916. end = pos-1;
  15917. ret = wc_MIME_header_strip(curLine, &nameAttr, start, end);
  15918. if (ret) {
  15919. goto error;
  15920. }
  15921. start = pos+1;
  15922. }
  15923. else if (mimeStatus == MIME_BODYVAL && cur == ';' && pos >= 1) {
  15924. end = pos-1;
  15925. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  15926. if (ret) {
  15927. goto error;
  15928. }
  15929. if (mimeType == MIME_HDR) {
  15930. nextHdr->name = nameAttr;
  15931. nameAttr = NULL;
  15932. nextHdr->body = bodyVal;
  15933. bodyVal = NULL;
  15934. nextHdr->next = curHdr;
  15935. curHdr = nextHdr;
  15936. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  15937. DYNAMIC_TYPE_PKCS7);
  15938. if (nextHdr == NULL) {
  15939. ret = MEMORY_E;
  15940. goto error;
  15941. }
  15942. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  15943. }
  15944. else {
  15945. nextParam->attribute = nameAttr;
  15946. nameAttr = NULL;
  15947. nextParam->value = bodyVal;
  15948. bodyVal = NULL;
  15949. nextParam->next = curHdr->params;
  15950. curHdr->params = nextParam;
  15951. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  15952. DYNAMIC_TYPE_PKCS7);
  15953. if (nextParam == NULL) {
  15954. ret = MEMORY_E;
  15955. goto error;
  15956. }
  15957. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  15958. }
  15959. mimeType = MIME_PARAM;
  15960. mimeStatus = MIME_NAMEATTR;
  15961. start = pos+1;
  15962. }
  15963. }
  15964. end = lineLen-1;
  15965. /* Omit newline characters. */
  15966. while ((curLine[end] == '\r' || curLine[end] == '\n') && end > 0) {
  15967. end--;
  15968. }
  15969. if (end >= start && mimeStatus == MIME_BODYVAL) {
  15970. ret = wc_MIME_header_strip(curLine, &bodyVal, start, end);
  15971. if (ret) {
  15972. goto error;
  15973. }
  15974. if (mimeType == MIME_HDR) {
  15975. nextHdr->name = nameAttr;
  15976. nameAttr = NULL;
  15977. nextHdr->body = bodyVal;
  15978. bodyVal = NULL;
  15979. nextHdr->next = curHdr;
  15980. curHdr = nextHdr;
  15981. nextHdr = (MimeHdr*)XMALLOC(sizeof(MimeHdr), NULL,
  15982. DYNAMIC_TYPE_PKCS7);
  15983. if (nextHdr == NULL) {
  15984. ret = MEMORY_E;
  15985. goto error;
  15986. }
  15987. XMEMSET(nextHdr, 0, (word32)sizeof(MimeHdr));
  15988. } else {
  15989. nextParam->attribute = nameAttr;
  15990. nameAttr = NULL;
  15991. nextParam->value = bodyVal;
  15992. bodyVal = NULL;
  15993. nextParam->next = curHdr->params;
  15994. curHdr->params = nextParam;
  15995. nextParam = (MimeParam*)XMALLOC(sizeof(MimeParam), NULL,
  15996. DYNAMIC_TYPE_PKCS7);
  15997. if (nextParam == NULL) {
  15998. ret = MEMORY_E;
  15999. goto error;
  16000. }
  16001. XMEMSET(nextParam, 0, (word32)sizeof(MimeParam));
  16002. }
  16003. }
  16004. curLine = XSTRTOK(NULL, "\r\n", &ptr);
  16005. mimeStatus = MIME_NAMEATTR;
  16006. }
  16007. *headers = curHdr;
  16008. XFREE(nextHdr, NULL, DYNAMIC_TYPE_PKCS7);
  16009. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  16010. return 0;
  16011. error:
  16012. wc_MIME_free_hdrs(curHdr);
  16013. wc_MIME_free_hdrs(nextHdr);
  16014. if (nameAttr != NULL)
  16015. XFREE(nameAttr, NULL, DYNAMIC_TYPE_PKCS7);
  16016. if (bodyVal != NULL)
  16017. XFREE(bodyVal, NULL, DYNAMIC_TYPE_PKCS7);
  16018. XFREE(nextParam, NULL, DYNAMIC_TYPE_PKCS7);
  16019. return ret;
  16020. }
  16021. /*****************************************************************************
  16022. * wc_MIME_header_strip - Reads the string in from indices start to end, strips
  16023. * out disallowed/separator characters and places the rest into *out.
  16024. *
  16025. * RETURNS:
  16026. * returns zero on success, non-zero on error.
  16027. */
  16028. int wc_MIME_header_strip(char* in, char** out, size_t start, size_t end)
  16029. {
  16030. size_t inPos = start;
  16031. size_t outPos = 0;
  16032. size_t inLen = 0;
  16033. if (end < start || in == NULL || out == NULL) {
  16034. return BAD_FUNC_ARG;
  16035. }
  16036. inLen = XSTRLEN(in);
  16037. if (start > inLen || end > inLen) {
  16038. return BAD_FUNC_ARG;
  16039. }
  16040. *out = (char*)XMALLOC(((end-start)+2)*sizeof(char), NULL,
  16041. DYNAMIC_TYPE_PKCS7);
  16042. if (*out == NULL) {
  16043. return MEMORY_E;
  16044. }
  16045. while (inPos <= end) {
  16046. if (in[inPos] >= MIME_HEADER_ASCII_MIN && in[inPos] <=
  16047. MIME_HEADER_ASCII_MAX && in[inPos] != ';' && in[inPos] != '\"') {
  16048. (*out)[outPos] = in[inPos];
  16049. outPos++;
  16050. }
  16051. inPos++;
  16052. }
  16053. (*out)[outPos] = '\0';
  16054. return 0;
  16055. }
  16056. /*****************************************************************************
  16057. * wc_MIME_find_header_name - Searches through all given headers until a header with
  16058. * a name matching the provided name is found.
  16059. *
  16060. * RETURNS:
  16061. * returns a pointer to the found header, if no match was found, returns NULL.
  16062. */
  16063. MimeHdr* wc_MIME_find_header_name(const char* name, MimeHdr* header)
  16064. {
  16065. size_t len = XSTRLEN(name);
  16066. while (header) {
  16067. if (!XSTRNCMP(name, header->name, len)) {
  16068. return header;
  16069. }
  16070. header = header->next;
  16071. }
  16072. return header;
  16073. }
  16074. /*****************************************************************************
  16075. * wc_MIME_find_param_attr - Searches through all parameters until a parameter
  16076. * with a attribute matching the provided attribute is found.
  16077. *
  16078. * RETURNS:
  16079. * returns a pointer to the found parameter, if no match was found,
  16080. * returns NULL.
  16081. */
  16082. MimeParam* wc_MIME_find_param_attr(const char* attribute,
  16083. MimeParam* param)
  16084. {
  16085. size_t len = XSTRLEN(attribute);
  16086. while (param) {
  16087. if (!XSTRNCMP(attribute, param->attribute, len)) {
  16088. return param;
  16089. }
  16090. param = param->next;
  16091. }
  16092. return param;
  16093. }
  16094. /*****************************************************************************
  16095. * wc_MIME_canonicalize - Canonicalize a line by converting all line endings
  16096. * to CRLF.
  16097. *
  16098. * RETURNS:
  16099. * returns a pointer to a canonicalized line on success, NULL on error.
  16100. */
  16101. char* wc_MIME_canonicalize(const char* line)
  16102. {
  16103. size_t end = 0;
  16104. char* canonLine = NULL;
  16105. if (line == NULL || XSTRLEN(line) == 0) {
  16106. return NULL;
  16107. }
  16108. end = XSTRLEN(line);
  16109. while (end >= 1 && ((line[end-1] == '\r') || (line[end-1] == '\n'))) {
  16110. end--;
  16111. }
  16112. /* Need 2 chars for \r\n and 1 for EOL */
  16113. canonLine = (char*)XMALLOC((end+3)*sizeof(char), NULL, DYNAMIC_TYPE_PKCS7);
  16114. if (canonLine == NULL) {
  16115. return NULL;
  16116. }
  16117. XSTRNCPY(canonLine, line, end);
  16118. canonLine[end] = '\r';
  16119. canonLine[end+1] = '\n';
  16120. canonLine[end+2] = '\0';
  16121. return canonLine;
  16122. }
  16123. /*****************************************************************************
  16124. * wc_MIME_free_hdrs - Frees all MIME headers, parameters and strings starting from
  16125. * the provided header pointer.
  16126. *
  16127. * RETURNS:
  16128. * returns zero on success, non-zero on error.
  16129. */
  16130. int wc_MIME_free_hdrs(MimeHdr* head)
  16131. {
  16132. MimeHdr* curHdr = NULL;
  16133. MimeParam* curParam = NULL;
  16134. while (head) {
  16135. while (head->params) {
  16136. curParam = head->params;
  16137. head->params = head->params->next;
  16138. XFREE(curParam->attribute, NULL, DYNAMIC_TYPE_PKCS7);
  16139. XFREE(curParam->value, NULL, DYNAMIC_TYPE_PKCS7);
  16140. XFREE(curParam, NULL, DYNAMIC_TYPE_PKCS7);
  16141. }
  16142. curHdr = head;
  16143. head = head->next;
  16144. XFREE(curHdr->name, NULL, DYNAMIC_TYPE_PKCS7);
  16145. XFREE(curHdr->body, NULL, DYNAMIC_TYPE_PKCS7);
  16146. XFREE(curHdr, NULL, DYNAMIC_TYPE_PKCS7);
  16147. }
  16148. return 0;
  16149. }
  16150. #endif /* HAVE_SMIME */
  16151. #undef ERROR_OUT
  16152. #endif /* !NO_ASN */
  16153. #ifdef WOLFSSL_SEP
  16154. #endif /* WOLFSSL_SEP */