asn.c 341 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043
  1. /* asn.c
  2. *
  3. * Copyright (C) 2006-2017 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. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. /*
  26. ASN Options:
  27. * NO_ASN_TIME: Disables time parts of the ASN code for systems without an RTC
  28. or wishing to save space.
  29. * IGNORE_NAME_CONSTRAINTS: Skip ASN name checks.
  30. * ASN_DUMP_OID: Allows dump of OID information for debugging.
  31. * RSA_DECODE_EXTRA: Decodes extra information in RSA public key.
  32. * WOLFSSL_CERT_GEN: Cert generation. Saves extra certificate info in GetName.
  33. * WOLFSSL_NO_OCSP_OPTIONAL_CERTS: Skip optional OCSP certs (responder issuer
  34. must still be trusted)
  35. * WOLFSSL_NO_TRUSTED_CERTS_VERIFY: Workaround for situation where entire cert
  36. chain is not loaded. This only matches on subject and public key and
  37. does not perform a PKI validation, so it is not a secure solution.
  38. Only enabled for OCSP.
  39. * WOLFSSL_NO_OCSP_ISSUER_CHECK: Can be defined for backwards compatibility to
  40. disable checking of OCSP subject hash with issuer hash.
  41. * WOLFSSL_ALT_CERT_CHAINS: Allows matching multiple CA's to validate
  42. chain based on issuer and public key (includes signature confirmation)
  43. */
  44. #ifndef NO_ASN
  45. #ifdef HAVE_RTP_SYS
  46. #include "os.h" /* dc_rtc_api needs */
  47. #include "dc_rtc_api.h" /* to get current time */
  48. #endif
  49. #include <wolfssl/wolfcrypt/asn.h>
  50. #include <wolfssl/wolfcrypt/coding.h>
  51. #include <wolfssl/wolfcrypt/md2.h>
  52. #include <wolfssl/wolfcrypt/hmac.h>
  53. #include <wolfssl/wolfcrypt/error-crypt.h>
  54. #include <wolfssl/wolfcrypt/pwdbased.h>
  55. #include <wolfssl/wolfcrypt/des3.h>
  56. #include <wolfssl/wolfcrypt/logging.h>
  57. #include <wolfssl/wolfcrypt/random.h>
  58. #include <wolfssl/wolfcrypt/hash.h>
  59. #ifdef NO_INLINE
  60. #include <wolfssl/wolfcrypt/misc.h>
  61. #else
  62. #define WOLFSSL_MISC_INCLUDED
  63. #include <wolfcrypt/src/misc.c>
  64. #endif
  65. #ifndef NO_PWDBASED
  66. #include <wolfssl/wolfcrypt/aes.h>
  67. #endif
  68. #ifndef NO_RC4
  69. #include <wolfssl/wolfcrypt/arc4.h>
  70. #endif
  71. #ifdef HAVE_NTRU
  72. #include "libntruencrypt/ntru_crypto.h"
  73. #endif
  74. #if defined(WOLFSSL_SHA512) || defined(WOLFSSL_SHA384)
  75. #include <wolfssl/wolfcrypt/sha512.h>
  76. #endif
  77. #ifndef NO_SHA256
  78. #include <wolfssl/wolfcrypt/sha256.h>
  79. #endif
  80. #ifdef HAVE_ECC
  81. #include <wolfssl/wolfcrypt/ecc.h>
  82. #endif
  83. #ifdef HAVE_ED25519
  84. #include <wolfssl/wolfcrypt/ed25519.h>
  85. #endif
  86. #ifndef NO_RSA
  87. #include <wolfssl/wolfcrypt/rsa.h>
  88. #endif
  89. #ifdef WOLFSSL_DEBUG_ENCODING
  90. #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  91. #if MQX_USE_IO_OLD
  92. #include <fio.h>
  93. #else
  94. #include <nio.h>
  95. #endif
  96. #else
  97. #include <stdio.h>
  98. #endif
  99. #endif
  100. #ifndef NO_ASN_TIME
  101. /* two byte date/time, add to value */
  102. static INLINE void GetTime(int* value, const byte* date, int* idx)
  103. {
  104. int i = *idx;
  105. *value += btoi(date[i++]) * 10;
  106. *value += btoi(date[i++]);
  107. *idx = i;
  108. }
  109. #endif /* !NO_ASN_TIME */
  110. #ifdef _MSC_VER
  111. /* 4996 warning to use MS extensions e.g., strcpy_s instead of XSTRNCPY */
  112. #pragma warning(disable: 4996)
  113. #endif
  114. #define ERROR_OUT(err, eLabel) { ret = (err); goto eLabel; }
  115. WOLFSSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len,
  116. word32 maxIdx)
  117. {
  118. int length = 0;
  119. word32 idx = *inOutIdx;
  120. byte b;
  121. *len = 0; /* default length */
  122. if ((idx + 1) > maxIdx) { /* for first read */
  123. WOLFSSL_MSG("GetLength bad index on input");
  124. return BUFFER_E;
  125. }
  126. b = input[idx++];
  127. if (b >= ASN_LONG_LENGTH) {
  128. word32 bytes = b & 0x7F;
  129. if ((idx + bytes) > maxIdx) { /* for reading bytes */
  130. WOLFSSL_MSG("GetLength bad long length");
  131. return BUFFER_E;
  132. }
  133. while (bytes--) {
  134. b = input[idx++];
  135. length = (length << 8) | b;
  136. }
  137. }
  138. else
  139. length = b;
  140. if ((idx + length) > maxIdx) { /* for user of length */
  141. WOLFSSL_MSG("GetLength value exceeds buffer length");
  142. return BUFFER_E;
  143. }
  144. *inOutIdx = idx;
  145. if (length > 0)
  146. *len = length;
  147. return length;
  148. }
  149. /* Get the DER/BER encoding of an ASN.1 header.
  150. *
  151. * input Buffer holding DER/BER encoded data.
  152. * tag ASN.1 tag value expected in header.
  153. * inOutIdx Current index into buffer to parse.
  154. * len The number of bytes in the ASN.1 data.
  155. * maxIdx Length of data in buffer.
  156. * returns BUFFER_E when there is not enough data to parse.
  157. * ASN_PARSE_E when the expected tag is not found or length is invalid.
  158. * Otherwise, the number of bytes in the ASN.1 data.
  159. */
  160. static int GetASNHeader(const byte* input, byte tag, word32* inOutIdx, int* len,
  161. word32 maxIdx)
  162. {
  163. word32 idx = *inOutIdx;
  164. byte b;
  165. int length;
  166. if ((idx + 1) > maxIdx)
  167. return BUFFER_E;
  168. b = input[idx++];
  169. if (b != tag)
  170. return ASN_PARSE_E;
  171. if (GetLength(input, &idx, &length, maxIdx) < 0)
  172. return ASN_PARSE_E;
  173. *len = length;
  174. *inOutIdx = idx;
  175. return length;
  176. }
  177. WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len,
  178. word32 maxIdx)
  179. {
  180. return GetASNHeader(input, ASN_SEQUENCE | ASN_CONSTRUCTED, inOutIdx, len,
  181. maxIdx);
  182. }
  183. WOLFSSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len,
  184. word32 maxIdx)
  185. {
  186. return GetASNHeader(input, ASN_SET | ASN_CONSTRUCTED, inOutIdx, len,
  187. maxIdx);
  188. }
  189. /* Get the DER/BER encoded ASN.1 NULL element.
  190. * Ensure that the all fields are as expected and move index past the element.
  191. *
  192. * input Buffer holding DER/BER encoded data.
  193. * inOutIdx Current index into buffer to parse.
  194. * maxIdx Length of data in buffer.
  195. * returns BUFFER_E when there is not enough data to parse.
  196. * ASN_TAG_NULL_E when the NULL tag is not found.
  197. * ASN_EXPECT_0_E when the length is not zero.
  198. * Otherwise, 0 to indicate success.
  199. */
  200. static int GetASNNull(const byte* input, word32* inOutIdx, word32 maxIdx)
  201. {
  202. word32 idx = *inOutIdx;
  203. byte b;
  204. if ((idx + 2) > maxIdx)
  205. return BUFFER_E;
  206. b = input[idx++];
  207. if (b != ASN_TAG_NULL)
  208. return ASN_TAG_NULL_E;
  209. if (input[idx++] != 0)
  210. return ASN_EXPECT_0_E;
  211. *inOutIdx = idx;
  212. return 0;
  213. }
  214. /* Set the DER/BER encoding of the ASN.1 NULL element.
  215. *
  216. * output Buffer to write into.
  217. * returns the number of bytes added to the buffer.
  218. */
  219. static int SetASNNull(byte* output)
  220. {
  221. output[0] = ASN_TAG_NULL;
  222. output[1] = 0;
  223. return 2;
  224. }
  225. /* Get the DER/BER encoding of an ASN.1 BOOLEAN.
  226. *
  227. * input Buffer holding DER/BER encoded data.
  228. * inOutIdx Current index into buffer to parse.
  229. * maxIdx Length of data in buffer.
  230. * returns BUFFER_E when there is not enough data to parse.
  231. * ASN_PARSE_E when the BOOLEAN tag is not found or length is not 1.
  232. * Otherwise, 0 to indicate the value was false and 1 to indicate true.
  233. */
  234. static int GetBoolean(const byte* input, word32* inOutIdx, word32 maxIdx)
  235. {
  236. word32 idx = *inOutIdx;
  237. byte b;
  238. if ((idx + 3) > maxIdx)
  239. return BUFFER_E;
  240. b = input[idx++];
  241. if (b != ASN_BOOLEAN)
  242. return ASN_PARSE_E;
  243. if (input[idx++] != 1)
  244. return ASN_PARSE_E;
  245. b = input[idx++] != 0;
  246. *inOutIdx = idx;
  247. return b;
  248. }
  249. #ifdef ASN1_SET_BOOLEAN
  250. /* Set the DER/BER encoding of the ASN.1 NULL element.
  251. * Note: Function not required as yet.
  252. *
  253. * val Boolean value to encode.
  254. * output Buffer to write into.
  255. * returns the number of bytes added to the buffer.
  256. */
  257. static int SetBoolean(int val, byte* output)
  258. {
  259. output[0] = ASN_BOOLEAN;
  260. output[1] = 1;
  261. output[2] = val ? -1 : 0;
  262. return 3;
  263. }
  264. #endif
  265. /* Get the DER/BER encoding of an ASN.1 OCTET_STRING header.
  266. *
  267. * input Buffer holding DER/BER encoded data.
  268. * inOutIdx Current index into buffer to parse.
  269. * len The number of bytes in the ASN.1 data.
  270. * maxIdx Length of data in buffer.
  271. * returns BUFFER_E when there is not enough data to parse.
  272. * ASN_PARSE_E when the OCTET_STRING tag is not found or length is
  273. * invalid.
  274. * Otherwise, the number of bytes in the ASN.1 data.
  275. */
  276. static int GetOctetString(const byte* input, word32* inOutIdx, int* len,
  277. word32 maxIdx)
  278. {
  279. return GetASNHeader(input, ASN_OCTET_STRING, inOutIdx, len, maxIdx);
  280. }
  281. /* Get the DER/BER encoding of an ASN.1 INTEGER header.
  282. * Removes the leading zero byte when found.
  283. *
  284. * input Buffer holding DER/BER encoded data.
  285. * inOutIdx Current index into buffer to parse.
  286. * len The number of bytes in the ASN.1 data (excluding any leading zero).
  287. * maxIdx Length of data in buffer.
  288. * returns BUFFER_E when there is not enough data to parse.
  289. * ASN_PARSE_E when the INTEGER tag is not found, length is invalid,
  290. * or invalid use of or missing leading zero.
  291. * Otherwise, 0 to indicate success.
  292. */
  293. static int GetASNInt(const byte* input, word32* inOutIdx, int* len,
  294. word32 maxIdx)
  295. {
  296. int ret;
  297. ret = GetASNHeader(input, ASN_INTEGER, inOutIdx, len, maxIdx);
  298. if (ret < 0)
  299. return ret;
  300. if (*len > 0) {
  301. /* remove leading zero, unless there is only one 0x00 byte */
  302. if ((input[*inOutIdx] == 0x00) && (*len > 1)) {
  303. (*inOutIdx)++;
  304. (*len)--;
  305. if (*len > 0 && (input[*inOutIdx] & 0x80) == 0)
  306. return ASN_PARSE_E;
  307. }
  308. }
  309. return 0;
  310. }
  311. /* Get the DER/BER encoding of an ASN.1 INTEGER that has a value of no more than
  312. * 7 bits.
  313. *
  314. * input Buffer holding DER/BER encoded data.
  315. * inOutIdx Current index into buffer to parse.
  316. * maxIdx Length of data in buffer.
  317. * returns BUFFER_E when there is not enough data to parse.
  318. * ASN_PARSE_E when the INTEGER tag is not found or length is invalid.
  319. * Otherwise, the 7-bit value.
  320. */
  321. static int GetInteger7Bit(const byte* input, word32* inOutIdx, word32 maxIdx)
  322. {
  323. word32 idx = *inOutIdx;
  324. byte b;
  325. if ((idx + 3) > maxIdx)
  326. return BUFFER_E;
  327. if (input[idx++] != ASN_INTEGER)
  328. return ASN_PARSE_E;
  329. if (input[idx++] != 1)
  330. return ASN_PARSE_E;
  331. b = input[idx++];
  332. *inOutIdx = idx;
  333. return b;
  334. }
  335. #ifndef NO_DSA
  336. static char sigSha1wDsaName[] = "SHAwDSA";
  337. #endif /* NO_DSA */
  338. #ifndef NO_RSA
  339. static char sigMd2wRsaName[] = "MD2wRSA";
  340. static char sigMd5wRsaName[] = "MD5wRSA";
  341. static char sigSha1wRsaName[] = "SHAwRSA";
  342. static char sigSha224wRsaName[] = "SHA224wRSA";
  343. static char sigSha256wRsaName[] = "SHA256wRSA";
  344. static char sigSha384wRsaName[] = "SHA384wRSA";
  345. static char sigSha512wRsaName[] = "SHA512wRSA";
  346. #endif /* NO_RSA */
  347. #ifdef HAVE_ECC
  348. static char sigSha1wEcdsaName[] = "SHAwECDSA";
  349. static char sigSha224wEcdsaName[] = "SHA224wECDSA";
  350. static char sigSha256wEcdsaName[] = "SHA256wECDSA";
  351. static char sigSha384wEcdsaName[] = "SHA384wECDSA";
  352. static char sigSha512wEcdsaName[] = "SHA512wECDSA";
  353. #endif /* HAVE_ECC */
  354. static char sigUnknownName[] = "Unknown";
  355. /* Get the human readable string for a signature type
  356. *
  357. * oid Oid value for signature
  358. */
  359. char* GetSigName(int oid) {
  360. switch (oid) {
  361. #ifndef NO_DSA
  362. case CTC_SHAwDSA:
  363. return sigSha1wDsaName;
  364. #endif /* NO_DSA */
  365. #ifndef NO_RSA
  366. case CTC_MD2wRSA:
  367. return sigMd2wRsaName;
  368. case CTC_MD5wRSA:
  369. return sigMd5wRsaName;
  370. case CTC_SHAwRSA:
  371. return sigSha1wRsaName;
  372. case CTC_SHA224wRSA:
  373. return sigSha224wRsaName;
  374. case CTC_SHA256wRSA:
  375. return sigSha256wRsaName;
  376. case CTC_SHA384wRSA:
  377. return sigSha384wRsaName;
  378. case CTC_SHA512wRSA:
  379. return sigSha512wRsaName;
  380. #endif /* NO_RSA */
  381. #ifdef HAVE_ECC
  382. case CTC_SHAwECDSA:
  383. return sigSha1wEcdsaName;
  384. case CTC_SHA224wECDSA:
  385. return sigSha224wEcdsaName;
  386. case CTC_SHA256wECDSA:
  387. return sigSha256wEcdsaName;
  388. case CTC_SHA384wECDSA:
  389. return sigSha384wEcdsaName;
  390. case CTC_SHA512wECDSA:
  391. return sigSha512wEcdsaName;
  392. #endif /* HAVE_ECC */
  393. default:
  394. return sigUnknownName;
  395. }
  396. }
  397. #if !defined(NO_DSA) || defined(HAVE_ECC) || \
  398. (!defined(NO_RSA) && \
  399. (defined(WOLFSSL_CERT_GEN) || \
  400. (defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA))))
  401. /* Set the DER/BER encoding of the ASN.1 INTEGER header.
  402. *
  403. * len Length of data to encode.
  404. * firstByte First byte of data, most significant byte of integer, to encode.
  405. * output Buffer to write into.
  406. * returns the number of bytes added to the buffer.
  407. */
  408. static int SetASNInt(int len, byte firstByte, byte* output)
  409. {
  410. word32 idx = 0;
  411. output[idx++] = ASN_INTEGER;
  412. if (firstByte & 0x80)
  413. len++;
  414. idx += SetLength(len, output + idx);
  415. if (firstByte & 0x80)
  416. output[idx++] = 0x00;
  417. return idx;
  418. }
  419. #endif
  420. #if !defined(NO_DSA) || defined(HAVE_ECC) || defined(WOLFSSL_CERT_GEN) || \
  421. (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && !defined(HAVE_USER_RSA))
  422. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int.
  423. * The number is assumed to be positive.
  424. *
  425. * n Multi-precision integer to encode.
  426. * maxSz Maximum size of the encoded integer.
  427. * A negative value indicates no check of length requested.
  428. * output Buffer to write into.
  429. * returns BUFFER_E when the data is too long for the buffer.
  430. * MP_TO_E when encoding the integer fails.
  431. * Otherwise, the number of bytes added to the buffer.
  432. */
  433. static int SetASNIntMP(mp_int* n, int maxSz, byte* output)
  434. {
  435. int idx = 0;
  436. int leadingBit;
  437. int length;
  438. int err;
  439. leadingBit = mp_leading_bit(n);
  440. length = mp_unsigned_bin_size(n);
  441. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  442. if (maxSz >= 0 && (idx + length) > maxSz)
  443. return BUFFER_E;
  444. err = mp_to_unsigned_bin(n, output + idx);
  445. if (err != MP_OKAY)
  446. return MP_TO_E;
  447. idx += length;
  448. return idx;
  449. }
  450. #endif
  451. #if !defined(NO_RSA) && defined(HAVE_USER_RSA) && defined(WOLFSSL_CERT_GEN)
  452. /* Set the DER/BER encoding of the ASN.1 INTEGER element with an mp_int from
  453. * an RSA key.
  454. * The number is assumed to be positive.
  455. *
  456. * n Multi-precision integer to encode.
  457. * output Buffer to write into.
  458. * returns BUFFER_E when the data is too long for the buffer.
  459. * MP_TO_E when encoding the integer fails.
  460. * Otherwise, the number of bytes added to the buffer.
  461. */
  462. static int SetASNIntRSA(mp_int* n, byte* output)
  463. {
  464. int idx = 0;
  465. int leadingBit;
  466. int length;
  467. int err;
  468. leadingBit = wc_Rsa_leading_bit(n);
  469. length = wc_Rsa_unsigned_bin_size(n);
  470. idx = SetASNInt(length, leadingBit ? 0x80 : 0x00, output);
  471. if ((idx + length) > MAX_RSA_INT_SZ)
  472. return BUFFER_E;
  473. err = wc_Rsa_to_unsigned_bin(n, output + idx, length);
  474. if (err != MP_OKAY)
  475. return MP_TO_E;
  476. idx += length;
  477. return idx;
  478. }
  479. #endif /* !NO_RSA && HAVE_USER_RSA && WOLFSSL_CERT_GEN */
  480. /* Windows header clash for WinCE using GetVersion */
  481. WOLFSSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx,
  482. int* version, word32 maxIdx)
  483. {
  484. word32 idx = *inOutIdx;
  485. if ((idx + MIN_VERSION_SZ) > maxIdx)
  486. return ASN_PARSE_E;
  487. if (input[idx++] != ASN_INTEGER)
  488. return ASN_PARSE_E;
  489. if (input[idx++] != 0x01)
  490. return ASN_VERSION_E;
  491. *version = input[idx++];
  492. *inOutIdx = idx;
  493. return *version;
  494. }
  495. #ifndef NO_PWDBASED
  496. /* Get small count integer, 32 bits or less */
  497. int GetShortInt(const byte* input, word32* inOutIdx, int* number, word32 maxIdx)
  498. {
  499. word32 idx = *inOutIdx;
  500. word32 len;
  501. *number = 0;
  502. /* check for type and length bytes */
  503. if ((idx + 2) > maxIdx)
  504. return BUFFER_E;
  505. if (input[idx++] != ASN_INTEGER)
  506. return ASN_PARSE_E;
  507. len = input[idx++];
  508. if (len > 4)
  509. return ASN_PARSE_E;
  510. if (len + idx > maxIdx)
  511. return ASN_PARSE_E;
  512. while (len--) {
  513. *number = *number << 8 | input[idx++];
  514. }
  515. *inOutIdx = idx;
  516. return *number;
  517. }
  518. #endif /* !NO_PWDBASED */
  519. /* May not have one, not an error */
  520. static int GetExplicitVersion(const byte* input, word32* inOutIdx, int* version,
  521. word32 maxIdx)
  522. {
  523. word32 idx = *inOutIdx;
  524. WOLFSSL_ENTER("GetExplicitVersion");
  525. if ((idx + 1) > maxIdx)
  526. return BUFFER_E;
  527. if (input[idx++] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  528. *inOutIdx = ++idx; /* skip header */
  529. return GetMyVersion(input, inOutIdx, version, maxIdx);
  530. }
  531. /* go back as is */
  532. *version = 0;
  533. return 0;
  534. }
  535. int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx, word32 maxIdx)
  536. {
  537. word32 idx = *inOutIdx;
  538. int ret;
  539. int length;
  540. ret = GetASNInt(input, &idx, &length, maxIdx);
  541. if (ret != 0)
  542. return ret;
  543. if (mp_init(mpi) != MP_OKAY)
  544. return MP_INIT_E;
  545. if (mp_read_unsigned_bin(mpi, (byte*)input + idx, length) != 0) {
  546. mp_clear(mpi);
  547. return ASN_GETINT_E;
  548. }
  549. #ifdef HAVE_WOLF_BIGINT
  550. if (wc_bigint_from_unsigned_bin(&mpi->raw, input + idx, length) != 0) {
  551. mp_clear(mpi);
  552. return ASN_GETINT_E;
  553. }
  554. #endif /* HAVE_WOLF_BIGINT */
  555. *inOutIdx = idx + length;
  556. return 0;
  557. }
  558. static int CheckBitString(const byte* input, word32* inOutIdx, int* len,
  559. word32 maxIdx, int zeroBits, byte* unusedBits)
  560. {
  561. word32 idx = *inOutIdx;
  562. int length;
  563. byte b;
  564. if ((idx + 1) > maxIdx)
  565. return BUFFER_E;
  566. if (input[idx++] != ASN_BIT_STRING)
  567. return ASN_BITSTR_E;
  568. if (GetLength(input, &idx, &length, maxIdx) < 0)
  569. return ASN_PARSE_E;
  570. /* extra sanity check that length is greater than 0 */
  571. if (length <= 0) {
  572. WOLFSSL_MSG("Error length was 0 in CheckBitString");
  573. return BUFFER_E;
  574. }
  575. if (idx + 1 > maxIdx) {
  576. WOLFSSL_MSG("Attempted buffer read larger than input buffer");
  577. return BUFFER_E;
  578. }
  579. b = input[idx];
  580. if (zeroBits && b != 0x00)
  581. return ASN_EXPECT_0_E;
  582. if (b >= 0x08)
  583. return ASN_PARSE_E;
  584. if (b != 0) {
  585. if ((byte)(input[idx + length - 1] << (8 - b)) != 0)
  586. return ASN_PARSE_E;
  587. }
  588. idx++;
  589. length--; /* length has been checked for greater than 0 */
  590. *inOutIdx = idx;
  591. if (len != NULL)
  592. *len = length;
  593. if (unusedBits != NULL)
  594. *unusedBits = b;
  595. return 0;
  596. }
  597. /* RSA (with CertGen or KeyGen) OR ECC OR ED25519 (with CertGen or KeyGen) */
  598. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA) && \
  599. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN))) || \
  600. defined(HAVE_ECC) || \
  601. (defined(HAVE_ED25519) && \
  602. (defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN)))
  603. /* Set the DER/BER encoding of the ASN.1 BIT_STRING header.
  604. *
  605. * len Length of data to encode.
  606. * unusedBits The number of unused bits in the last byte of data.
  607. * That is, the number of least significant zero bits before a one.
  608. * The last byte is the most-significant non-zero byte of a number.
  609. * output Buffer to write into.
  610. * returns the number of bytes added to the buffer.
  611. */
  612. static word32 SetBitString(word32 len, byte unusedBits, byte* output)
  613. {
  614. word32 idx = 0;
  615. output[idx++] = ASN_BIT_STRING;
  616. idx += SetLength(len + 1, output + idx);
  617. output[idx++] = unusedBits;
  618. return idx;
  619. }
  620. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 */
  621. #if defined(WOLFSSL_CERT_GEN) || defined(WOLFSSL_KEY_GEN)
  622. #if (!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || \
  623. defined(HAVE_ECC) || defined(HAVE_ED25519)
  624. #ifdef WOLFSSL_CERT_EXT
  625. /* Set the DER/BER encoding of the ASN.1 BIT_STRING with a 16-bit value.
  626. *
  627. * val 16-bit value to encode.
  628. * output Buffer to write into.
  629. * returns the number of bytes added to the buffer.
  630. */
  631. static word32 SetBitString16Bit(word16 val, byte* output)
  632. {
  633. word32 idx;
  634. int len;
  635. byte lastByte;
  636. byte unusedBits = 0;
  637. if ((val >> 8) != 0) {
  638. len = 2;
  639. lastByte = (byte)(val >> 8);
  640. }
  641. else {
  642. len = 1;
  643. lastByte = (byte)val;
  644. }
  645. while (((lastByte >> unusedBits) & 0x01) == 0x00)
  646. unusedBits++;
  647. idx = SetBitString(len, unusedBits, output);
  648. output[idx++] = (byte)val;
  649. if (len > 1)
  650. output[idx++] = (byte)(val >> 8);
  651. return idx;
  652. }
  653. #endif /* WOLFSSL_CERT_EXT */
  654. #endif /* !NO_RSA || HAVE_ECC || HAVE_ED25519 */
  655. #endif /* WOLFSSL_CERT_GEN || WOLFSSL_KEY_GEN */
  656. /* hashType */
  657. static const byte hashMd2hOid[] = {42, 134, 72, 134, 247, 13, 2, 2};
  658. static const byte hashMd5hOid[] = {42, 134, 72, 134, 247, 13, 2, 5};
  659. static const byte hashSha1hOid[] = {43, 14, 3, 2, 26};
  660. static const byte hashSha224hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 4};
  661. static const byte hashSha256hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 1};
  662. static const byte hashSha384hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 2};
  663. static const byte hashSha512hOid[] = {96, 134, 72, 1, 101, 3, 4, 2, 3};
  664. /* hmacType */
  665. static const byte hmacSha224Oid[] = {42, 134, 72, 134, 247, 13, 2, 8};
  666. static const byte hmacSha256Oid[] = {42, 134, 72, 134, 247, 13, 2, 9};
  667. static const byte hmacSha384Oid[] = {42, 134, 72, 134, 247, 13, 2, 10};
  668. static const byte hmacSha512Oid[] = {42, 134, 72, 134, 247, 13, 2, 11};
  669. /* sigType */
  670. #ifndef NO_DSA
  671. static const byte sigSha1wDsaOid[] = {42, 134, 72, 206, 56, 4, 3};
  672. #endif /* NO_DSA */
  673. #ifndef NO_RSA
  674. static const byte sigMd2wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 2};
  675. static const byte sigMd5wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 4};
  676. static const byte sigSha1wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 5};
  677. static const byte sigSha224wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,14};
  678. static const byte sigSha256wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,11};
  679. static const byte sigSha384wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,12};
  680. static const byte sigSha512wRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1,13};
  681. #endif /* NO_RSA */
  682. #ifdef HAVE_ECC
  683. static const byte sigSha1wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 1};
  684. static const byte sigSha224wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 1};
  685. static const byte sigSha256wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 2};
  686. static const byte sigSha384wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 3};
  687. static const byte sigSha512wEcdsaOid[] = {42, 134, 72, 206, 61, 4, 3, 4};
  688. #endif /* HAVE_ECC */
  689. #ifdef HAVE_ED25519
  690. static const byte sigEd25519Oid[] = {43, 101, 112};
  691. #endif /* HAVE_ED25519 */
  692. /* keyType */
  693. #ifndef NO_DSA
  694. static const byte keyDsaOid[] = {42, 134, 72, 206, 56, 4, 1};
  695. #endif /* NO_DSA */
  696. #ifndef NO_RSA
  697. static const byte keyRsaOid[] = {42, 134, 72, 134, 247, 13, 1, 1, 1};
  698. #endif /* NO_RSA */
  699. #ifdef HAVE_NTRU
  700. static const byte keyNtruOid[] = {43, 6, 1, 4, 1, 193, 22, 1, 1, 1, 1};
  701. #endif /* HAVE_NTRU */
  702. #ifdef HAVE_ECC
  703. static const byte keyEcdsaOid[] = {42, 134, 72, 206, 61, 2, 1};
  704. #endif /* HAVE_ECC */
  705. #ifdef HAVE_ED25519
  706. static const byte keyEd25519Oid[] = {43, 101, 112};
  707. #endif /* HAVE_ED25519 */
  708. /* curveType */
  709. #ifdef HAVE_ECC
  710. /* See "ecc_sets" table in ecc.c */
  711. #endif /* HAVE_ECC */
  712. /* blkType */
  713. static const byte blkAes128CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 2};
  714. static const byte blkAes192CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 22};
  715. static const byte blkAes256CbcOid[] = {96, 134, 72, 1, 101, 3, 4, 1, 42};
  716. static const byte blkDesCbcOid[] = {43, 14, 3, 2, 7};
  717. static const byte blkDes3CbcOid[] = {42, 134, 72, 134, 247, 13, 3, 7};
  718. /* keyWrapType */
  719. static const byte wrapAes128Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 5};
  720. static const byte wrapAes192Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 25};
  721. static const byte wrapAes256Oid[] = {96, 134, 72, 1, 101, 3, 4, 1, 45};
  722. /* cmsKeyAgreeType */
  723. static const byte dhSinglePass_stdDH_sha1kdf_Oid[] =
  724. {43, 129, 5, 16, 134, 72, 63, 0, 2};
  725. static const byte dhSinglePass_stdDH_sha224kdf_Oid[] = {43, 129, 4, 1, 11, 0};
  726. static const byte dhSinglePass_stdDH_sha256kdf_Oid[] = {43, 129, 4, 1, 11, 1};
  727. static const byte dhSinglePass_stdDH_sha384kdf_Oid[] = {43, 129, 4, 1, 11, 2};
  728. static const byte dhSinglePass_stdDH_sha512kdf_Oid[] = {43, 129, 4, 1, 11, 3};
  729. /* ocspType */
  730. #ifdef HAVE_OCSP
  731. static const byte ocspBasicOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 1};
  732. static const byte ocspNonceOid[] = {43, 6, 1, 5, 5, 7, 48, 1, 2};
  733. #endif /* HAVE_OCSP */
  734. /* certExtType */
  735. static const byte extBasicCaOid[] = {85, 29, 19};
  736. static const byte extAltNamesOid[] = {85, 29, 17};
  737. static const byte extCrlDistOid[] = {85, 29, 31};
  738. static const byte extAuthInfoOid[] = {43, 6, 1, 5, 5, 7, 1, 1};
  739. static const byte extAuthKeyOid[] = {85, 29, 35};
  740. static const byte extSubjKeyOid[] = {85, 29, 14};
  741. static const byte extCertPolicyOid[] = {85, 29, 32};
  742. static const byte extKeyUsageOid[] = {85, 29, 15};
  743. static const byte extInhibitAnyOid[] = {85, 29, 54};
  744. static const byte extExtKeyUsageOid[] = {85, 29, 37};
  745. static const byte extNameConsOid[] = {85, 29, 30};
  746. /* certAuthInfoType */
  747. static const byte extAuthInfoOcspOid[] = {43, 6, 1, 5, 5, 7, 48, 1};
  748. static const byte extAuthInfoCaIssuerOid[] = {43, 6, 1, 5, 5, 7, 48, 2};
  749. /* certPolicyType */
  750. static const byte extCertPolicyAnyOid[] = {85, 29, 32, 0};
  751. /* certKeyUseType */
  752. static const byte extAltNamesHwNameOid[] = {43, 6, 1, 5, 5, 7, 8, 4};
  753. /* certKeyUseType */
  754. static const byte extExtKeyUsageAnyOid[] = {85, 29, 37, 0};
  755. static const byte extExtKeyUsageServerAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 1};
  756. static const byte extExtKeyUsageClientAuthOid[] = {43, 6, 1, 5, 5, 7, 3, 2};
  757. static const byte extExtKeyUsageCodeSigningOid[] = {43, 6, 1, 5, 5, 7, 3, 3};
  758. static const byte extExtKeyUsageEmailProtectOid[] = {43, 6, 1, 5, 5, 7, 3, 4};
  759. static const byte extExtKeyUsageTimestampOid[] = {43, 6, 1, 5, 5, 7, 3, 8};
  760. static const byte extExtKeyUsageOcspSignOid[] = {43, 6, 1, 5, 5, 7, 3, 9};
  761. /* kdfType */
  762. static const byte pbkdf2Oid[] = {42, 134, 72, 134, 247, 13, 1, 5, 12};
  763. /* PKCS5 */
  764. static const byte pbeSha1Des[] = {42, 134, 72, 134, 247, 13, 1, 5, 10};
  765. /* PKCS12 */
  766. static const byte pbeSha1RC4128[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 1};
  767. static const byte pbeSha1Des3[] = {42, 134, 72, 134, 247, 13, 1, 12, 1, 3};
  768. /* returns a pointer to the OID string on success and NULL on fail */
  769. const byte* OidFromId(word32 id, word32 type, word32* oidSz)
  770. {
  771. const byte* oid = NULL;
  772. *oidSz = 0;
  773. switch (type) {
  774. case oidHashType:
  775. switch (id) {
  776. case MD2h:
  777. oid = hashMd2hOid;
  778. *oidSz = sizeof(hashMd2hOid);
  779. break;
  780. case MD5h:
  781. oid = hashMd5hOid;
  782. *oidSz = sizeof(hashMd5hOid);
  783. break;
  784. case SHAh:
  785. oid = hashSha1hOid;
  786. *oidSz = sizeof(hashSha1hOid);
  787. break;
  788. case SHA224h:
  789. oid = hashSha224hOid;
  790. *oidSz = sizeof(hashSha224hOid);
  791. break;
  792. case SHA256h:
  793. oid = hashSha256hOid;
  794. *oidSz = sizeof(hashSha256hOid);
  795. break;
  796. case SHA384h:
  797. oid = hashSha384hOid;
  798. *oidSz = sizeof(hashSha384hOid);
  799. break;
  800. case SHA512h:
  801. oid = hashSha512hOid;
  802. *oidSz = sizeof(hashSha512hOid);
  803. break;
  804. }
  805. break;
  806. case oidSigType:
  807. switch (id) {
  808. #ifndef NO_DSA
  809. case CTC_SHAwDSA:
  810. oid = sigSha1wDsaOid;
  811. *oidSz = sizeof(sigSha1wDsaOid);
  812. break;
  813. #endif /* NO_DSA */
  814. #ifndef NO_RSA
  815. case CTC_MD2wRSA:
  816. oid = sigMd2wRsaOid;
  817. *oidSz = sizeof(sigMd2wRsaOid);
  818. break;
  819. case CTC_MD5wRSA:
  820. oid = sigMd5wRsaOid;
  821. *oidSz = sizeof(sigMd5wRsaOid);
  822. break;
  823. case CTC_SHAwRSA:
  824. oid = sigSha1wRsaOid;
  825. *oidSz = sizeof(sigSha1wRsaOid);
  826. break;
  827. case CTC_SHA224wRSA:
  828. oid = sigSha224wRsaOid;
  829. *oidSz = sizeof(sigSha224wRsaOid);
  830. break;
  831. case CTC_SHA256wRSA:
  832. oid = sigSha256wRsaOid;
  833. *oidSz = sizeof(sigSha256wRsaOid);
  834. break;
  835. case CTC_SHA384wRSA:
  836. oid = sigSha384wRsaOid;
  837. *oidSz = sizeof(sigSha384wRsaOid);
  838. break;
  839. case CTC_SHA512wRSA:
  840. oid = sigSha512wRsaOid;
  841. *oidSz = sizeof(sigSha512wRsaOid);
  842. break;
  843. #endif /* NO_RSA */
  844. #ifdef HAVE_ECC
  845. case CTC_SHAwECDSA:
  846. oid = sigSha1wEcdsaOid;
  847. *oidSz = sizeof(sigSha1wEcdsaOid);
  848. break;
  849. case CTC_SHA224wECDSA:
  850. oid = sigSha224wEcdsaOid;
  851. *oidSz = sizeof(sigSha224wEcdsaOid);
  852. break;
  853. case CTC_SHA256wECDSA:
  854. oid = sigSha256wEcdsaOid;
  855. *oidSz = sizeof(sigSha256wEcdsaOid);
  856. break;
  857. case CTC_SHA384wECDSA:
  858. oid = sigSha384wEcdsaOid;
  859. *oidSz = sizeof(sigSha384wEcdsaOid);
  860. break;
  861. case CTC_SHA512wECDSA:
  862. oid = sigSha512wEcdsaOid;
  863. *oidSz = sizeof(sigSha512wEcdsaOid);
  864. break;
  865. #endif /* HAVE_ECC */
  866. #ifdef HAVE_ED25519
  867. case CTC_ED25519:
  868. oid = sigEd25519Oid;
  869. *oidSz = sizeof(sigEd25519Oid);
  870. break;
  871. #endif
  872. default:
  873. break;
  874. }
  875. break;
  876. case oidKeyType:
  877. switch (id) {
  878. #ifndef NO_DSA
  879. case DSAk:
  880. oid = keyDsaOid;
  881. *oidSz = sizeof(keyDsaOid);
  882. break;
  883. #endif /* NO_DSA */
  884. #ifndef NO_RSA
  885. case RSAk:
  886. oid = keyRsaOid;
  887. *oidSz = sizeof(keyRsaOid);
  888. break;
  889. #endif /* NO_RSA */
  890. #ifdef HAVE_NTRU
  891. case NTRUk:
  892. oid = keyNtruOid;
  893. *oidSz = sizeof(keyNtruOid);
  894. break;
  895. #endif /* HAVE_NTRU */
  896. #ifdef HAVE_ECC
  897. case ECDSAk:
  898. oid = keyEcdsaOid;
  899. *oidSz = sizeof(keyEcdsaOid);
  900. break;
  901. #endif /* HAVE_ECC */
  902. #ifdef HAVE_ED25519
  903. case ED25519k:
  904. oid = keyEd25519Oid;
  905. *oidSz = sizeof(keyEd25519Oid);
  906. break;
  907. #endif /* HAVE_ED25519 */
  908. default:
  909. break;
  910. }
  911. break;
  912. #ifdef HAVE_ECC
  913. case oidCurveType:
  914. if (wc_ecc_get_oid(id, &oid, oidSz) < 0) {
  915. WOLFSSL_MSG("ECC OID not found");
  916. }
  917. break;
  918. #endif /* HAVE_ECC */
  919. case oidBlkType:
  920. switch (id) {
  921. case AES128CBCb:
  922. oid = blkAes128CbcOid;
  923. *oidSz = sizeof(blkAes128CbcOid);
  924. break;
  925. case AES192CBCb:
  926. oid = blkAes192CbcOid;
  927. *oidSz = sizeof(blkAes192CbcOid);
  928. break;
  929. case AES256CBCb:
  930. oid = blkAes256CbcOid;
  931. *oidSz = sizeof(blkAes256CbcOid);
  932. break;
  933. case DESb:
  934. oid = blkDesCbcOid;
  935. *oidSz = sizeof(blkDesCbcOid);
  936. break;
  937. case DES3b:
  938. oid = blkDes3CbcOid;
  939. *oidSz = sizeof(blkDes3CbcOid);
  940. break;
  941. }
  942. break;
  943. #ifdef HAVE_OCSP
  944. case oidOcspType:
  945. switch (id) {
  946. case OCSP_BASIC_OID:
  947. oid = ocspBasicOid;
  948. *oidSz = sizeof(ocspBasicOid);
  949. break;
  950. case OCSP_NONCE_OID:
  951. oid = ocspNonceOid;
  952. *oidSz = sizeof(ocspNonceOid);
  953. break;
  954. }
  955. break;
  956. #endif /* HAVE_OCSP */
  957. case oidCertExtType:
  958. switch (id) {
  959. case BASIC_CA_OID:
  960. oid = extBasicCaOid;
  961. *oidSz = sizeof(extBasicCaOid);
  962. break;
  963. case ALT_NAMES_OID:
  964. oid = extAltNamesOid;
  965. *oidSz = sizeof(extAltNamesOid);
  966. break;
  967. case CRL_DIST_OID:
  968. oid = extCrlDistOid;
  969. *oidSz = sizeof(extCrlDistOid);
  970. break;
  971. case AUTH_INFO_OID:
  972. oid = extAuthInfoOid;
  973. *oidSz = sizeof(extAuthInfoOid);
  974. break;
  975. case AUTH_KEY_OID:
  976. oid = extAuthKeyOid;
  977. *oidSz = sizeof(extAuthKeyOid);
  978. break;
  979. case SUBJ_KEY_OID:
  980. oid = extSubjKeyOid;
  981. *oidSz = sizeof(extSubjKeyOid);
  982. break;
  983. case CERT_POLICY_OID:
  984. oid = extCertPolicyOid;
  985. *oidSz = sizeof(extCertPolicyOid);
  986. break;
  987. case KEY_USAGE_OID:
  988. oid = extKeyUsageOid;
  989. *oidSz = sizeof(extKeyUsageOid);
  990. break;
  991. case INHIBIT_ANY_OID:
  992. oid = extInhibitAnyOid;
  993. *oidSz = sizeof(extInhibitAnyOid);
  994. break;
  995. case EXT_KEY_USAGE_OID:
  996. oid = extExtKeyUsageOid;
  997. *oidSz = sizeof(extExtKeyUsageOid);
  998. break;
  999. case NAME_CONS_OID:
  1000. oid = extNameConsOid;
  1001. *oidSz = sizeof(extNameConsOid);
  1002. break;
  1003. }
  1004. break;
  1005. case oidCertAuthInfoType:
  1006. switch (id) {
  1007. case AIA_OCSP_OID:
  1008. oid = extAuthInfoOcspOid;
  1009. *oidSz = sizeof(extAuthInfoOcspOid);
  1010. break;
  1011. case AIA_CA_ISSUER_OID:
  1012. oid = extAuthInfoCaIssuerOid;
  1013. *oidSz = sizeof(extAuthInfoCaIssuerOid);
  1014. break;
  1015. }
  1016. break;
  1017. case oidCertPolicyType:
  1018. switch (id) {
  1019. case CP_ANY_OID:
  1020. oid = extCertPolicyAnyOid;
  1021. *oidSz = sizeof(extCertPolicyAnyOid);
  1022. break;
  1023. }
  1024. break;
  1025. case oidCertAltNameType:
  1026. switch (id) {
  1027. case HW_NAME_OID:
  1028. oid = extAltNamesHwNameOid;
  1029. *oidSz = sizeof(extAltNamesHwNameOid);
  1030. break;
  1031. }
  1032. break;
  1033. case oidCertKeyUseType:
  1034. switch (id) {
  1035. case EKU_ANY_OID:
  1036. oid = extExtKeyUsageAnyOid;
  1037. *oidSz = sizeof(extExtKeyUsageAnyOid);
  1038. break;
  1039. case EKU_SERVER_AUTH_OID:
  1040. oid = extExtKeyUsageServerAuthOid;
  1041. *oidSz = sizeof(extExtKeyUsageServerAuthOid);
  1042. break;
  1043. case EKU_CLIENT_AUTH_OID:
  1044. oid = extExtKeyUsageClientAuthOid;
  1045. *oidSz = sizeof(extExtKeyUsageClientAuthOid);
  1046. break;
  1047. case EKU_CODESIGNING_OID:
  1048. oid = extExtKeyUsageCodeSigningOid;
  1049. *oidSz = sizeof(extExtKeyUsageCodeSigningOid);
  1050. break;
  1051. case EKU_EMAILPROTECT_OID:
  1052. oid = extExtKeyUsageEmailProtectOid;
  1053. *oidSz = sizeof(extExtKeyUsageEmailProtectOid);
  1054. break;
  1055. case EKU_TIMESTAMP_OID:
  1056. oid = extExtKeyUsageTimestampOid;
  1057. *oidSz = sizeof(extExtKeyUsageTimestampOid);
  1058. break;
  1059. case EKU_OCSP_SIGN_OID:
  1060. oid = extExtKeyUsageOcspSignOid;
  1061. *oidSz = sizeof(extExtKeyUsageOcspSignOid);
  1062. break;
  1063. }
  1064. break;
  1065. case oidKdfType:
  1066. switch (id) {
  1067. case PBKDF2_OID:
  1068. oid = pbkdf2Oid;
  1069. *oidSz = sizeof(pbkdf2Oid);
  1070. break;
  1071. }
  1072. break;
  1073. case oidPBEType:
  1074. switch (id) {
  1075. case PBE_SHA1_RC4_128:
  1076. oid = pbeSha1RC4128;
  1077. *oidSz = sizeof(pbeSha1RC4128);
  1078. break;
  1079. case PBE_SHA1_DES:
  1080. oid = pbeSha1Des;
  1081. *oidSz = sizeof(pbeSha1Des);
  1082. break;
  1083. case PBE_SHA1_DES3:
  1084. oid = pbeSha1Des3;
  1085. *oidSz = sizeof(pbeSha1Des3);
  1086. break;
  1087. }
  1088. break;
  1089. case oidKeyWrapType:
  1090. switch (id) {
  1091. case AES128_WRAP:
  1092. oid = wrapAes128Oid;
  1093. *oidSz = sizeof(wrapAes128Oid);
  1094. break;
  1095. case AES192_WRAP:
  1096. oid = wrapAes192Oid;
  1097. *oidSz = sizeof(wrapAes192Oid);
  1098. break;
  1099. case AES256_WRAP:
  1100. oid = wrapAes256Oid;
  1101. *oidSz = sizeof(wrapAes256Oid);
  1102. break;
  1103. }
  1104. break;
  1105. case oidCmsKeyAgreeType:
  1106. switch (id) {
  1107. case dhSinglePass_stdDH_sha1kdf_scheme:
  1108. oid = dhSinglePass_stdDH_sha1kdf_Oid;
  1109. *oidSz = sizeof(dhSinglePass_stdDH_sha1kdf_Oid);
  1110. break;
  1111. case dhSinglePass_stdDH_sha224kdf_scheme:
  1112. oid = dhSinglePass_stdDH_sha224kdf_Oid;
  1113. *oidSz = sizeof(dhSinglePass_stdDH_sha224kdf_Oid);
  1114. break;
  1115. case dhSinglePass_stdDH_sha256kdf_scheme:
  1116. oid = dhSinglePass_stdDH_sha256kdf_Oid;
  1117. *oidSz = sizeof(dhSinglePass_stdDH_sha256kdf_Oid);
  1118. break;
  1119. case dhSinglePass_stdDH_sha384kdf_scheme:
  1120. oid = dhSinglePass_stdDH_sha384kdf_Oid;
  1121. *oidSz = sizeof(dhSinglePass_stdDH_sha384kdf_Oid);
  1122. break;
  1123. case dhSinglePass_stdDH_sha512kdf_scheme:
  1124. oid = dhSinglePass_stdDH_sha512kdf_Oid;
  1125. *oidSz = sizeof(dhSinglePass_stdDH_sha512kdf_Oid);
  1126. break;
  1127. }
  1128. break;
  1129. case oidHmacType:
  1130. switch (id) {
  1131. case HMAC_SHA224_OID:
  1132. oid = hmacSha224Oid;
  1133. *oidSz = sizeof(hmacSha224Oid);
  1134. break;
  1135. case HMAC_SHA256_OID:
  1136. oid = hmacSha256Oid;
  1137. *oidSz = sizeof(hmacSha256Oid);
  1138. break;
  1139. case HMAC_SHA384_OID:
  1140. oid = hmacSha384Oid;
  1141. *oidSz = sizeof(hmacSha384Oid);
  1142. break;
  1143. case HMAC_SHA512_OID:
  1144. oid = hmacSha512Oid;
  1145. *oidSz = sizeof(hmacSha512Oid);
  1146. break;
  1147. }
  1148. break;
  1149. case oidIgnoreType:
  1150. default:
  1151. break;
  1152. }
  1153. return oid;
  1154. }
  1155. #ifdef HAVE_OID_ENCODING
  1156. int EncodeObjectId(const word16* in, word32 inSz, byte* out, word32* outSz)
  1157. {
  1158. int i, x, len;
  1159. word32 d, t;
  1160. /* check args */
  1161. if (in == NULL || outSz == NULL) {
  1162. return BAD_FUNC_ARG;
  1163. }
  1164. /* compute length of encoded OID */
  1165. d = (in[0] * 40) + in[1];
  1166. len = 0;
  1167. for (i = 1; i < (int)inSz; i++) {
  1168. x = 0;
  1169. t = d;
  1170. while (t) {
  1171. x++;
  1172. t >>= 1;
  1173. }
  1174. len += (x / 7) + ((x % 7) ? 1 : 0) + (d == 0 ? 1 : 0);
  1175. if (i < (int)inSz - 1) {
  1176. d = in[i + 1];
  1177. }
  1178. }
  1179. if (out) {
  1180. /* verify length */
  1181. if ((int)*outSz < len) {
  1182. return BUFFER_E; /* buffer provided is not large enough */
  1183. }
  1184. /* calc first byte */
  1185. d = (in[0] * 40) + in[1];
  1186. /* encode bytes */
  1187. x = 0;
  1188. for (i = 1; i < (int)inSz; i++) {
  1189. if (d) {
  1190. int y = x, z;
  1191. byte mask = 0;
  1192. while (d) {
  1193. out[x++] = (byte)((d & 0x7F) | mask);
  1194. d >>= 7;
  1195. mask |= 0x80; /* upper bit is set on all but the last byte */
  1196. }
  1197. /* now swap bytes y...x-1 */
  1198. z = x - 1;
  1199. while (y < z) {
  1200. mask = out[y];
  1201. out[y] = out[z];
  1202. out[z] = mask;
  1203. ++y;
  1204. --z;
  1205. }
  1206. }
  1207. else {
  1208. out[x++] = 0x00; /* zero value */
  1209. }
  1210. /* next word */
  1211. if (i < (int)inSz - 1) {
  1212. d = in[i + 1];
  1213. }
  1214. }
  1215. }
  1216. /* return length */
  1217. *outSz = len;
  1218. return 0;
  1219. }
  1220. #endif /* HAVE_OID_ENCODING */
  1221. #ifdef HAVE_OID_DECODING
  1222. int DecodeObjectId(const byte* in, word32 inSz, word16* out, word32* outSz)
  1223. {
  1224. int x = 0, y = 0;
  1225. word32 t = 0;
  1226. /* check args */
  1227. if (in == NULL || outSz == NULL) {
  1228. return BAD_FUNC_ARG;
  1229. }
  1230. /* decode bytes */
  1231. while (inSz--) {
  1232. t = (t << 7) | (in[x] & 0x7F);
  1233. if (!(in[x] & 0x80)) {
  1234. if (y >= (int)*outSz) {
  1235. return BUFFER_E;
  1236. }
  1237. if (y == 0) {
  1238. out[0] = (t / 40);
  1239. out[1] = (t % 40);
  1240. y = 2;
  1241. }
  1242. else {
  1243. out[y++] = t;
  1244. }
  1245. t = 0; /* reset tmp */
  1246. }
  1247. x++;
  1248. }
  1249. /* return length */
  1250. *outSz = y;
  1251. return 0;
  1252. }
  1253. #endif /* HAVE_OID_DECODING */
  1254. /* Get the DER/BER encoding of an ASN.1 OBJECT_ID header.
  1255. *
  1256. * input Buffer holding DER/BER encoded data.
  1257. * inOutIdx Current index into buffer to parse.
  1258. * len The number of bytes in the ASN.1 data.
  1259. * maxIdx Length of data in buffer.
  1260. * returns BUFFER_E when there is not enough data to parse.
  1261. * ASN_OBJECt_ID_E when the OBJECT_ID tag is not found.
  1262. * ASN_PARSE_E when length is invalid.
  1263. * Otherwise, 0 to indicate success.
  1264. */
  1265. static int GetASNObjectId(const byte* input, word32* inOutIdx, int* len,
  1266. word32 maxIdx)
  1267. {
  1268. word32 idx = *inOutIdx;
  1269. byte b;
  1270. int length;
  1271. if ((idx + 1) > maxIdx)
  1272. return BUFFER_E;
  1273. b = input[idx++];
  1274. if (b != ASN_OBJECT_ID)
  1275. return ASN_OBJECT_ID_E;
  1276. if (GetLength(input, &idx, &length, maxIdx) < 0)
  1277. return ASN_PARSE_E;
  1278. *len = length;
  1279. *inOutIdx = idx;
  1280. return 0;
  1281. }
  1282. /* Set the DER/BER encoding of the ASN.1 OBJECT_ID header.
  1283. *
  1284. * len Length of the OBJECT_ID data.
  1285. * output Buffer to write into.
  1286. * returns the number of bytes added to the buffer.
  1287. */
  1288. static int SetObjectId(int len, byte* output)
  1289. {
  1290. int idx = 0;
  1291. output[idx++] = ASN_OBJECT_ID;
  1292. idx += SetLength(len, output + idx);
  1293. return idx;
  1294. }
  1295. int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
  1296. word32 oidType, word32 maxIdx)
  1297. {
  1298. int ret = 0, length;
  1299. word32 idx = *inOutIdx;
  1300. #ifndef NO_VERIFY_OID
  1301. word32 actualOidSz = 0;
  1302. const byte* actualOid;
  1303. #endif /* NO_VERIFY_OID */
  1304. (void)oidType;
  1305. WOLFSSL_ENTER("GetObjectId()");
  1306. *oid = 0;
  1307. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  1308. if (ret != 0)
  1309. return ret;
  1310. #ifndef NO_VERIFY_OID
  1311. actualOid = &input[idx];
  1312. if (length > 0)
  1313. actualOidSz = (word32)length;
  1314. #endif /* NO_VERIFY_OID */
  1315. while (length--) {
  1316. /* odd HC08 compiler behavior here when input[idx++] */
  1317. *oid += (word32)input[idx];
  1318. idx++;
  1319. }
  1320. /* just sum it up for now */
  1321. *inOutIdx = idx;
  1322. #ifndef NO_VERIFY_OID
  1323. {
  1324. const byte* checkOid = NULL;
  1325. word32 checkOidSz;
  1326. #ifdef ASN_DUMP_OID
  1327. word32 i;
  1328. #endif
  1329. if (oidType != oidIgnoreType) {
  1330. checkOid = OidFromId(*oid, oidType, &checkOidSz);
  1331. #ifdef ASN_DUMP_OID
  1332. /* support for dumping OID information */
  1333. printf("OID (Type %d, Sz %d, Sum %d): ", oidType, actualOidSz, *oid);
  1334. for (i=0; i<actualOidSz; i++) {
  1335. printf("%d, ", actualOid[i]);
  1336. }
  1337. printf("\n");
  1338. #ifdef HAVE_OID_DECODING
  1339. {
  1340. word16 decOid[16];
  1341. word32 decOidSz = sizeof(decOid);
  1342. ret = DecodeObjectId(actualOid, actualOidSz, decOid, &decOidSz);
  1343. if (ret == 0) {
  1344. printf(" Decoded (Sz %d): ", decOidSz);
  1345. for (i=0; i<decOidSz; i++) {
  1346. printf("%d.", decOid[i]);
  1347. }
  1348. printf("\n");
  1349. }
  1350. else {
  1351. printf("DecodeObjectId failed: %d\n", ret);
  1352. }
  1353. }
  1354. #endif /* HAVE_OID_DECODING */
  1355. #endif /* ASN_DUMP_OID */
  1356. if (checkOid != NULL &&
  1357. (checkOidSz != actualOidSz ||
  1358. XMEMCMP(actualOid, checkOid, checkOidSz) != 0)) {
  1359. WOLFSSL_MSG("OID Check Failed");
  1360. return ASN_UNKNOWN_OID_E;
  1361. }
  1362. }
  1363. }
  1364. #endif /* NO_VERIFY_OID */
  1365. return ret;
  1366. }
  1367. static int SkipObjectId(const byte* input, word32* inOutIdx, word32 maxIdx)
  1368. {
  1369. word32 idx = *inOutIdx;
  1370. int length;
  1371. int ret;
  1372. ret = GetASNObjectId(input, &idx, &length, maxIdx);
  1373. if (ret != 0)
  1374. return ret;
  1375. idx += length;
  1376. *inOutIdx = idx;
  1377. return 0;
  1378. }
  1379. WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
  1380. word32 oidType, word32 maxIdx)
  1381. {
  1382. int length;
  1383. word32 idx = *inOutIdx;
  1384. int ret;
  1385. *oid = 0;
  1386. WOLFSSL_ENTER("GetAlgoId");
  1387. if (GetSequence(input, &idx, &length, maxIdx) < 0)
  1388. return ASN_PARSE_E;
  1389. if (GetObjectId(input, &idx, oid, oidType, maxIdx) < 0)
  1390. return ASN_OBJECT_ID_E;
  1391. /* could have NULL tag and 0 terminator, but may not */
  1392. if (input[idx] == ASN_TAG_NULL) {
  1393. ret = GetASNNull(input, &idx, maxIdx);
  1394. if (ret != 0)
  1395. return ret;
  1396. }
  1397. *inOutIdx = idx;
  1398. return 0;
  1399. }
  1400. #ifndef NO_RSA
  1401. #ifndef HAVE_USER_RSA
  1402. int wc_RsaPrivateKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  1403. word32 inSz)
  1404. {
  1405. int version, length;
  1406. if (inOutIdx == NULL) {
  1407. return BAD_FUNC_ARG;
  1408. }
  1409. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  1410. return ASN_PARSE_E;
  1411. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  1412. return ASN_PARSE_E;
  1413. key->type = RSA_PRIVATE;
  1414. if (GetInt(&key->n, input, inOutIdx, inSz) < 0 ||
  1415. GetInt(&key->e, input, inOutIdx, inSz) < 0 ||
  1416. GetInt(&key->d, input, inOutIdx, inSz) < 0 ||
  1417. GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  1418. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  1419. GetInt(&key->dP, input, inOutIdx, inSz) < 0 ||
  1420. GetInt(&key->dQ, input, inOutIdx, inSz) < 0 ||
  1421. GetInt(&key->u, input, inOutIdx, inSz) < 0 ) return ASN_RSA_KEY_E;
  1422. #ifdef WOLFSSL_XILINX_CRYPT
  1423. if (wc_InitRsaHw(key) != 0) {
  1424. return BAD_STATE_E;
  1425. }
  1426. #endif
  1427. return 0;
  1428. }
  1429. #endif /* HAVE_USER_RSA */
  1430. #endif /* NO_RSA */
  1431. /* Remove PKCS8 header, place inOutIdx at beginning of traditional,
  1432. * return traditional length on success, negative on error */
  1433. int ToTraditionalInline(const byte* input, word32* inOutIdx, word32 sz)
  1434. {
  1435. word32 idx, oid;
  1436. int version, length;
  1437. int ret;
  1438. if (input == NULL || inOutIdx == NULL)
  1439. return BAD_FUNC_ARG;
  1440. idx = *inOutIdx;
  1441. if (GetSequence(input, &idx, &length, sz) < 0)
  1442. return ASN_PARSE_E;
  1443. if (GetMyVersion(input, &idx, &version, sz) < 0)
  1444. return ASN_PARSE_E;
  1445. if (GetAlgoId(input, &idx, &oid, oidKeyType, sz) < 0)
  1446. return ASN_PARSE_E;
  1447. if (input[idx] == ASN_OBJECT_ID) {
  1448. if (SkipObjectId(input, &idx, sz) < 0)
  1449. return ASN_PARSE_E;
  1450. }
  1451. ret = GetOctetString(input, &idx, &length, sz);
  1452. if (ret < 0)
  1453. return ret;
  1454. *inOutIdx = idx;
  1455. return length;
  1456. }
  1457. /* Remove PKCS8 header, move beginning of traditional to beginning of input */
  1458. int ToTraditional(byte* input, word32 sz)
  1459. {
  1460. word32 inOutIdx = 0;
  1461. int length;
  1462. if (input == NULL)
  1463. return BAD_FUNC_ARG;
  1464. length = ToTraditionalInline(input, &inOutIdx, sz);
  1465. if (length < 0)
  1466. return length;
  1467. XMEMMOVE(input, input + inOutIdx, length);
  1468. return length;
  1469. }
  1470. /* find beginning of traditional key inside PKCS#8 unencrypted buffer
  1471. * return traditional length on success, with inOutIdx at beginning of
  1472. * traditional
  1473. * return negative on failure/error */
  1474. int wc_GetPkcs8TraditionalOffset(byte* input, word32* inOutIdx, word32 sz)
  1475. {
  1476. int length;
  1477. if (input == NULL || inOutIdx == NULL || (*inOutIdx > sz))
  1478. return BAD_FUNC_ARG;
  1479. length = ToTraditionalInline(input, inOutIdx, sz);
  1480. return length;
  1481. }
  1482. /* PKCS#8 from RFC 5208
  1483. * This function takes in a DER key and converts it to PKCS#8 format. Used
  1484. * in creating PKCS#12 shrouded key bags.
  1485. * Reverse of ToTraditional
  1486. *
  1487. * PrivateKeyInfo ::= SEQUENCE {
  1488. * version Version,
  1489. * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  1490. * privateKey PrivateKey,
  1491. * attributes optional
  1492. * }
  1493. * Version ::= INTEGER
  1494. * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
  1495. * PrivateKey ::= OCTET STRING
  1496. *
  1497. * out buffer to place result in
  1498. * outSz size of out buffer
  1499. * key buffer with DER key
  1500. * keySz size of key buffer
  1501. * algoID algorithm ID i.e. RSAk
  1502. * curveOID ECC curve oid if used. Should be NULL for RSA keys.
  1503. * oidSz size of curve oid. Is set to 0 if curveOID is NULL.
  1504. *
  1505. * Returns the size of PKCS#8 placed into out. In error cases returns negative
  1506. * values.
  1507. */
  1508. int wc_CreatePKCS8Key(byte* out, word32* outSz, byte* key, word32 keySz,
  1509. int algoID, const byte* curveOID, word32 oidSz)
  1510. {
  1511. word32 keyIdx = 0;
  1512. word32 tmpSz = 0;
  1513. word32 sz;
  1514. /* If out is NULL then return the max size needed
  1515. * + 2 for ASN_OBJECT_ID and ASN_OCTET_STRING tags */
  1516. if (out == NULL && outSz != NULL) {
  1517. *outSz = keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  1518. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2;
  1519. if (curveOID != NULL)
  1520. *outSz += oidSz + MAX_LENGTH_SZ + 1;
  1521. WOLFSSL_MSG("Checking size of PKCS8");
  1522. return LENGTH_ONLY_E;
  1523. }
  1524. WOLFSSL_ENTER("wc_CreatePKCS8Key()");
  1525. if (key == NULL || out == NULL || outSz == NULL) {
  1526. return BAD_FUNC_ARG;
  1527. }
  1528. /* check the buffer has enough room for largest possible size */
  1529. if (curveOID != NULL) {
  1530. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  1531. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 3 + oidSz + MAX_LENGTH_SZ))
  1532. return BUFFER_E;
  1533. }
  1534. else {
  1535. oidSz = 0; /* with no curveOID oid size must be 0 */
  1536. if (*outSz < (keySz + MAX_SEQ_SZ + MAX_VERSION_SZ + MAX_ALGO_SZ
  1537. + MAX_LENGTH_SZ + MAX_LENGTH_SZ + 2))
  1538. return BUFFER_E;
  1539. }
  1540. /* PrivateKeyInfo ::= SEQUENCE */
  1541. keyIdx += MAX_SEQ_SZ; /* save room for sequence */
  1542. /* version Version
  1543. * no header information just INTEGER */
  1544. sz = SetMyVersion(PKCS8v0, out + keyIdx, 0);
  1545. tmpSz += sz; keyIdx += sz;
  1546. /* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier */
  1547. sz = 0; /* set sz to 0 and get privateKey oid buffer size needed */
  1548. if (curveOID != NULL && oidSz > 0) {
  1549. byte buf[MAX_LENGTH_SZ];
  1550. sz = SetLength(oidSz, buf);
  1551. sz += 1; /* plus one for ASN object id */
  1552. }
  1553. sz = SetAlgoID(algoID, out + keyIdx, oidKeyType, oidSz + sz);
  1554. tmpSz += sz; keyIdx += sz;
  1555. /* privateKey PrivateKey *
  1556. * pkcs8 ecc uses slightly different format. Places curve oid in
  1557. * buffer */
  1558. if (curveOID != NULL && oidSz > 0) {
  1559. sz = SetObjectId(oidSz, out + keyIdx);
  1560. keyIdx += sz; tmpSz += sz;
  1561. XMEMCPY(out + keyIdx, curveOID, oidSz);
  1562. keyIdx += oidSz; tmpSz += oidSz;
  1563. }
  1564. sz = SetOctetString(keySz, out + keyIdx);
  1565. keyIdx += sz; tmpSz += sz;
  1566. XMEMCPY(out + keyIdx, key, keySz);
  1567. tmpSz += keySz;
  1568. /* attributes optional
  1569. * No attributes currently added */
  1570. /* rewind and add sequence */
  1571. sz = SetSequence(tmpSz, out);
  1572. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, tmpSz);
  1573. return tmpSz + sz;
  1574. }
  1575. /* check that the private key is a pair for the public key in certificate
  1576. * return 1 (true) on match
  1577. * return 0 or negative value on failure/error
  1578. *
  1579. * key : buffer holding DER fromat key
  1580. * keySz : size of key buffer
  1581. * der : a initialized and parsed DecodedCert holding a certificate */
  1582. int wc_CheckPrivateKey(byte* key, word32 keySz, DecodedCert* der)
  1583. {
  1584. int ret;
  1585. (void)keySz;
  1586. if (key == NULL || der == NULL) {
  1587. return BAD_FUNC_ARG;
  1588. }
  1589. #if !defined(NO_RSA)
  1590. /* test if RSA key */
  1591. if (der->keyOID == RSAk) {
  1592. RsaKey a, b;
  1593. word32 keyIdx = 0;
  1594. if ((ret = wc_InitRsaKey(&a, NULL)) < 0)
  1595. return ret;
  1596. if ((ret = wc_InitRsaKey(&b, NULL)) < 0) {
  1597. wc_FreeRsaKey(&a);
  1598. return ret;
  1599. }
  1600. if ((ret = wc_RsaPrivateKeyDecode(key, &keyIdx, &a, keySz)) == 0) {
  1601. WOLFSSL_MSG("Checking RSA key pair");
  1602. keyIdx = 0; /* reset to 0 for parsing public key */
  1603. if ((ret = wc_RsaPublicKeyDecode(der->publicKey, &keyIdx, &b,
  1604. der->pubKeySize)) == 0) {
  1605. /* limit for user RSA crypto because of RsaKey
  1606. * dereference. */
  1607. #if defined(HAVE_USER_RSA)
  1608. WOLFSSL_MSG("Cannot verify RSA pair with user RSA");
  1609. ret = 1; /* return first RSA cert as match */
  1610. #else
  1611. /* both keys extracted successfully now check n and e
  1612. * values are the same. This is dereferencing RsaKey */
  1613. if (mp_cmp(&(a.n), &(b.n)) != MP_EQ ||
  1614. mp_cmp(&(a.e), &(b.e)) != MP_EQ) {
  1615. ret = MP_CMP_E;
  1616. }
  1617. else
  1618. ret = 1;
  1619. #endif
  1620. }
  1621. }
  1622. wc_FreeRsaKey(&b);
  1623. wc_FreeRsaKey(&a);
  1624. }
  1625. else
  1626. #endif /* NO_RSA */
  1627. #ifdef HAVE_ECC
  1628. if (der->keyOID == ECDSAk) {
  1629. ecc_key key_pair;
  1630. byte privDer[MAX_ECC_BYTES];
  1631. word32 privSz = MAX_ECC_BYTES;
  1632. word32 keyIdx = 0;
  1633. if ((ret = wc_ecc_init(&key_pair)) < 0)
  1634. return ret;
  1635. if ((ret = wc_EccPrivateKeyDecode(key, &keyIdx, &key_pair,
  1636. keySz)) == 0) {
  1637. WOLFSSL_MSG("Checking ECC key pair");
  1638. if ((ret = wc_ecc_export_private_only(&key_pair, privDer, &privSz))
  1639. == 0) {
  1640. wc_ecc_free(&key_pair);
  1641. ret = wc_ecc_init(&key_pair);
  1642. if (ret == 0) {
  1643. ret = wc_ecc_import_private_key((const byte*)privDer,
  1644. privSz, (const byte*)der->publicKey,
  1645. der->pubKeySize, &key_pair);
  1646. }
  1647. /* public and private extracted successfuly now check if is
  1648. * a pair and also do sanity checks on key. wc_ecc_check_key
  1649. * checks that private * base generator equals pubkey */
  1650. if (ret == 0) {
  1651. if ((ret = wc_ecc_check_key(&key_pair)) == 0) {
  1652. ret = 1;
  1653. }
  1654. }
  1655. ForceZero(privDer, privSz);
  1656. }
  1657. }
  1658. wc_ecc_free(&key_pair);
  1659. }
  1660. else
  1661. #endif /* HAVE_ECC */
  1662. #ifdef HAVE_ED25519
  1663. if (der->keyOID == ED25519k) {
  1664. word32 keyIdx = 0;
  1665. ed25519_key key_pair;
  1666. if ((ret = wc_ed25519_init(&key_pair)) < 0)
  1667. return ret;
  1668. if ((ret = wc_Ed25519PrivateKeyDecode(key, &keyIdx, &key_pair,
  1669. keySz)) == 0) {
  1670. WOLFSSL_MSG("Checking ED25519 key pair");
  1671. keyIdx = 0;
  1672. if ((ret = wc_ed25519_import_public(der->publicKey, der->pubKeySize,
  1673. &key_pair)) == 0) {
  1674. /* public and private extracted successfuly no check if is
  1675. * a pair and also do sanity checks on key. wc_ecc_check_key
  1676. * checks that private * base generator equals pubkey */
  1677. if ((ret = wc_ed25519_check_key(&key_pair)) == 0)
  1678. ret = 1;
  1679. }
  1680. }
  1681. wc_ed25519_free(&key_pair);
  1682. }
  1683. else
  1684. #endif
  1685. {
  1686. ret = 0;
  1687. }
  1688. (void)keySz;
  1689. return ret;
  1690. }
  1691. #ifndef NO_PWDBASED
  1692. /* Check To see if PKCS version algo is supported, set id if it is return 0
  1693. < 0 on error */
  1694. static int CheckAlgo(int first, int second, int* id, int* version)
  1695. {
  1696. *id = ALGO_ID_E;
  1697. *version = PKCS5; /* default */
  1698. if (first == 1) {
  1699. switch (second) {
  1700. case PBE_SHA1_RC4_128:
  1701. *id = PBE_SHA1_RC4_128;
  1702. *version = PKCS12v1;
  1703. return 0;
  1704. case PBE_SHA1_DES:
  1705. *id = PBE_SHA1_DES;
  1706. *version = PKCS12v1;
  1707. return 0;
  1708. case PBE_SHA1_DES3:
  1709. *id = PBE_SHA1_DES3;
  1710. *version = PKCS12v1;
  1711. return 0;
  1712. default:
  1713. return ALGO_ID_E;
  1714. }
  1715. }
  1716. if (first != PKCS5)
  1717. return ASN_INPUT_E; /* VERSION ERROR */
  1718. if (second == PBES2) {
  1719. *version = PKCS5v2;
  1720. return 0;
  1721. }
  1722. switch (second) {
  1723. case 3: /* see RFC 2898 for ids */
  1724. *id = PBE_MD5_DES;
  1725. return 0;
  1726. case 10:
  1727. *id = PBE_SHA1_DES;
  1728. return 0;
  1729. default:
  1730. return ALGO_ID_E;
  1731. }
  1732. }
  1733. /* Check To see if PKCS v2 algo is supported, set id if it is return 0
  1734. < 0 on error */
  1735. static int CheckAlgoV2(int oid, int* id)
  1736. {
  1737. switch (oid) {
  1738. case DESb:
  1739. *id = PBE_SHA1_DES;
  1740. return 0;
  1741. case DES3b:
  1742. *id = PBE_SHA1_DES3;
  1743. return 0;
  1744. case AES256CBCb:
  1745. *id = PBE_AES256_CBC;
  1746. return 0;
  1747. default:
  1748. return ALGO_ID_E;
  1749. }
  1750. }
  1751. /* Decrypt/Encrypt input in place from parameters based on id
  1752. *
  1753. * returns a negative value on fail case
  1754. */
  1755. static int CryptKey(const char* password, int passwordSz, byte* salt,
  1756. int saltSz, int iterations, int id, byte* input,
  1757. int length, int version, byte* cbcIv, int enc)
  1758. {
  1759. int typeH;
  1760. int derivedLen;
  1761. int ret = 0;
  1762. #ifdef WOLFSSL_SMALL_STACK
  1763. byte* key;
  1764. #else
  1765. byte key[MAX_KEY_SIZE];
  1766. #endif
  1767. (void)input;
  1768. (void)length;
  1769. (void)enc;
  1770. WOLFSSL_ENTER("CryptKey()");
  1771. switch (id) {
  1772. case PBE_MD5_DES:
  1773. typeH = WC_MD5;
  1774. derivedLen = 16; /* may need iv for v1.5 */
  1775. break;
  1776. case PBE_SHA1_DES:
  1777. typeH = WC_SHA;
  1778. derivedLen = 16; /* may need iv for v1.5 */
  1779. break;
  1780. case PBE_SHA1_DES3:
  1781. typeH = WC_SHA;
  1782. derivedLen = 32; /* may need iv for v1.5 */
  1783. break;
  1784. case PBE_SHA1_RC4_128:
  1785. typeH = WC_SHA;
  1786. derivedLen = 16;
  1787. break;
  1788. case PBE_AES256_CBC:
  1789. typeH = WC_SHA256;
  1790. derivedLen = 32;
  1791. break;
  1792. default:
  1793. WOLFSSL_MSG("Unknown/Unsupported encrypt/decrypt id");
  1794. return ALGO_ID_E;
  1795. }
  1796. #ifdef WOLFSSL_SMALL_STACK
  1797. key = (byte*)XMALLOC(MAX_KEY_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1798. if (key == NULL)
  1799. return MEMORY_E;
  1800. #endif
  1801. if (version == PKCS5v2)
  1802. ret = wc_PBKDF2(key, (byte*)password, passwordSz,
  1803. salt, saltSz, iterations, derivedLen, typeH);
  1804. #ifndef NO_SHA
  1805. else if (version == PKCS5)
  1806. ret = wc_PBKDF1(key, (byte*)password, passwordSz,
  1807. salt, saltSz, iterations, derivedLen, typeH);
  1808. #endif
  1809. else if (version == PKCS12v1) {
  1810. int i, idx = 0;
  1811. byte unicodePasswd[MAX_UNICODE_SZ];
  1812. if ( (passwordSz * 2 + 2) > (int)sizeof(unicodePasswd)) {
  1813. #ifdef WOLFSSL_SMALL_STACK
  1814. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1815. #endif
  1816. return UNICODE_SIZE_E;
  1817. }
  1818. for (i = 0; i < passwordSz; i++) {
  1819. unicodePasswd[idx++] = 0x00;
  1820. unicodePasswd[idx++] = (byte)password[i];
  1821. }
  1822. /* add trailing NULL */
  1823. unicodePasswd[idx++] = 0x00;
  1824. unicodePasswd[idx++] = 0x00;
  1825. ret = wc_PKCS12_PBKDF(key, unicodePasswd, idx, salt, saltSz,
  1826. iterations, derivedLen, typeH, 1);
  1827. if (id != PBE_SHA1_RC4_128)
  1828. ret += wc_PKCS12_PBKDF(cbcIv, unicodePasswd, idx, salt, saltSz,
  1829. iterations, 8, typeH, 2);
  1830. }
  1831. else {
  1832. #ifdef WOLFSSL_SMALL_STACK
  1833. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1834. #endif
  1835. WOLFSSL_MSG("Unknown/Unsupported PKCS version");
  1836. return ALGO_ID_E;
  1837. }
  1838. if (ret != 0) {
  1839. #ifdef WOLFSSL_SMALL_STACK
  1840. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1841. #endif
  1842. return ret;
  1843. }
  1844. switch (id) {
  1845. #ifndef NO_DES3
  1846. case PBE_MD5_DES:
  1847. case PBE_SHA1_DES:
  1848. {
  1849. Des des;
  1850. byte* desIv = key + 8;
  1851. if (version == PKCS5v2 || version == PKCS12v1)
  1852. desIv = cbcIv;
  1853. if (enc) {
  1854. ret = wc_Des_SetKey(&des, key, desIv, DES_ENCRYPTION);
  1855. }
  1856. else {
  1857. ret = wc_Des_SetKey(&des, key, desIv, DES_DECRYPTION);
  1858. }
  1859. if (ret != 0) {
  1860. #ifdef WOLFSSL_SMALL_STACK
  1861. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1862. #endif
  1863. return ret;
  1864. }
  1865. if (enc) {
  1866. wc_Des_CbcEncrypt(&des, input, input, length);
  1867. }
  1868. else {
  1869. wc_Des_CbcDecrypt(&des, input, input, length);
  1870. }
  1871. break;
  1872. }
  1873. case PBE_SHA1_DES3:
  1874. {
  1875. Des3 des;
  1876. byte* desIv = key + 24;
  1877. if (version == PKCS5v2 || version == PKCS12v1)
  1878. desIv = cbcIv;
  1879. ret = wc_Des3Init(&des, NULL, INVALID_DEVID);
  1880. if (ret != 0) {
  1881. #ifdef WOLFSSL_SMALL_STACK
  1882. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1883. #endif
  1884. return ret;
  1885. }
  1886. if (enc) {
  1887. ret = wc_Des3_SetKey(&des, key, desIv, DES_ENCRYPTION);
  1888. }
  1889. else {
  1890. ret = wc_Des3_SetKey(&des, key, desIv, DES_DECRYPTION);
  1891. }
  1892. if (ret != 0) {
  1893. #ifdef WOLFSSL_SMALL_STACK
  1894. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1895. #endif
  1896. return ret;
  1897. }
  1898. if (enc) {
  1899. ret = wc_Des3_CbcEncrypt(&des, input, input, length);
  1900. }
  1901. else {
  1902. ret = wc_Des3_CbcDecrypt(&des, input, input, length);
  1903. }
  1904. if (ret != 0) {
  1905. #ifdef WOLFSSL_SMALL_STACK
  1906. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1907. #endif
  1908. return ret;
  1909. }
  1910. break;
  1911. }
  1912. #endif
  1913. #ifndef NO_RC4
  1914. case PBE_SHA1_RC4_128:
  1915. {
  1916. Arc4 dec;
  1917. wc_Arc4SetKey(&dec, key, derivedLen);
  1918. wc_Arc4Process(&dec, input, input, length);
  1919. break;
  1920. }
  1921. #endif
  1922. #ifndef NO_AES
  1923. case PBE_AES256_CBC:
  1924. {
  1925. Aes dec;
  1926. ret = wc_AesInit(&dec, NULL, INVALID_DEVID);
  1927. if (ret == 0)
  1928. ret = wc_AesSetKey(&dec, key, derivedLen,
  1929. cbcIv, AES_DECRYPTION);
  1930. if (ret == 0)
  1931. ret = wc_AesCbcDecrypt(&dec, input, input, length);
  1932. if (ret != 0) {
  1933. #ifdef WOLFSSL_SMALL_STACK
  1934. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1935. #endif
  1936. return ret;
  1937. }
  1938. ForceZero(&dec, sizeof(Aes));
  1939. break;
  1940. }
  1941. #endif
  1942. default:
  1943. #ifdef WOLFSSL_SMALL_STACK
  1944. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1945. #endif
  1946. WOLFSSL_MSG("Unknown/Unsupported encrypt/decryption algorithm");
  1947. return ALGO_ID_E;
  1948. }
  1949. #ifdef WOLFSSL_SMALL_STACK
  1950. XFREE(key, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1951. #endif
  1952. return ret;
  1953. }
  1954. int wc_GetKeyOID(byte* key, word32 keySz, const byte** curveOID, word32* oidSz,
  1955. int* algoID, void* heap)
  1956. {
  1957. word32 tmpIdx = 0;
  1958. #ifdef HAVE_ECC
  1959. ecc_key ecc;
  1960. #endif
  1961. #ifdef HAVE_ED25519
  1962. ed25519_key ed25519;
  1963. #endif
  1964. #ifndef NO_RSA
  1965. RsaKey rsa;
  1966. wc_InitRsaKey(&rsa, heap);
  1967. if (wc_RsaPrivateKeyDecode(key, &tmpIdx, &rsa, keySz) == 0) {
  1968. *algoID = RSAk;
  1969. }
  1970. else {
  1971. WOLFSSL_MSG("Not RSA DER key");
  1972. }
  1973. wc_FreeRsaKey(&rsa);
  1974. #endif /* NO_RSA */
  1975. #ifdef HAVE_ECC
  1976. if (algoID == 0) {
  1977. tmpIdx = 0;
  1978. wc_ecc_init_ex(&ecc, heap, INVALID_DEVID);
  1979. if (wc_EccPrivateKeyDecode(key, &tmpIdx, &ecc, keySz) == 0) {
  1980. *algoID = ECDSAk;
  1981. /* now find oid */
  1982. if (wc_ecc_get_oid(ecc.dp->oidSum, curveOID, oidSz) < 0) {
  1983. WOLFSSL_MSG("Error getting ECC curve OID");
  1984. wc_ecc_free(&ecc);
  1985. return BAD_FUNC_ARG;
  1986. }
  1987. }
  1988. else {
  1989. WOLFSSL_MSG("Not ECC DER key either");
  1990. }
  1991. wc_ecc_free(&ecc);
  1992. }
  1993. #endif /* HAVE_ECC */
  1994. #ifdef HAVE_ED25519
  1995. if (*algoID != RSAk && *algoID != ECDSAk) {
  1996. if (wc_ed25519_init(&ed25519) == 0) {
  1997. if (wc_Ed25519PrivateKeyDecode(key, &tmpIdx, &ed25519, keySz)
  1998. == 0) {
  1999. *algoID = ED25519k;
  2000. }
  2001. else {
  2002. WOLFSSL_MSG("Not ED25519 DER key");
  2003. }
  2004. wc_ed25519_free(&ed25519);
  2005. }
  2006. else {
  2007. WOLFSSL_MSG("GetKeyOID wc_ed25519_init failed");
  2008. }
  2009. }
  2010. #endif
  2011. /* if flag is not set then is neither RSA or ECC key that could be
  2012. * found */
  2013. if (*algoID == 0) {
  2014. WOLFSSL_MSG("Bad key DER or compile options");
  2015. return BAD_FUNC_ARG;
  2016. }
  2017. (void)curveOID;
  2018. (void)oidSz;
  2019. return 1;
  2020. }
  2021. /*
  2022. * Used when creating PKCS12 shrouded key bags
  2023. * vPKCS is the version of PKCS to use
  2024. * vAlgo is the algorithm version to use
  2025. *
  2026. * if salt is NULL a random number is generated
  2027. *
  2028. * returns the size of encrypted data on success
  2029. */
  2030. int UnTraditionalEnc(byte* key, word32 keySz, byte* out, word32* outSz,
  2031. const char* password,int passwordSz, int vPKCS, int vAlgo,
  2032. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  2033. {
  2034. int algoID = 0;
  2035. byte* tmp;
  2036. word32 tmpSz = 0;
  2037. word32 sz;
  2038. word32 seqSz;
  2039. word32 inOutIdx = 0;
  2040. word32 totalSz = 0;
  2041. int version, id;
  2042. int ret;
  2043. const byte* curveOID = NULL;
  2044. word32 oidSz = 0;
  2045. #ifdef WOLFSSL_SMALL_STACK
  2046. byte* saltTmp = NULL;
  2047. byte* cbcIv = NULL;
  2048. #else
  2049. byte saltTmp[MAX_IV_SIZE];
  2050. byte cbcIv[MAX_IV_SIZE];
  2051. #endif
  2052. WOLFSSL_ENTER("UnTraditionalEnc()");
  2053. if (saltSz > MAX_SALT_SIZE)
  2054. return ASN_PARSE_E;
  2055. inOutIdx += MAX_SEQ_SZ; /* leave room for size of finished shroud */
  2056. if (CheckAlgo(vPKCS, vAlgo, &id, &version) < 0) {
  2057. WOLFSSL_MSG("Bad/Unsupported algorithm ID");
  2058. return ASN_INPUT_E; /* Algo ID error */
  2059. }
  2060. if (out != NULL) {
  2061. if (*outSz < inOutIdx + MAX_ALGO_SZ + MAX_SALT_SIZE + MAX_SEQ_SZ + 1 +
  2062. MAX_LENGTH_SZ + MAX_SHORT_SZ + 1)
  2063. return BUFFER_E;
  2064. sz = SetAlgoID(id, out + inOutIdx, oidPBEType, 0);
  2065. totalSz += sz; inOutIdx += sz;
  2066. if (version == PKCS5v2) {
  2067. WOLFSSL_MSG("PKCS5v2 Not supported yet\n");
  2068. }
  2069. if (salt == NULL || saltSz <= 0) {
  2070. saltSz = 8;
  2071. #ifdef WOLFSSL_SMALL_STACK
  2072. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2073. if (saltTmp == NULL)
  2074. return MEMORY_E;
  2075. #endif
  2076. salt = saltTmp;
  2077. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  2078. WOLFSSL_MSG("Error generating random salt");
  2079. #ifdef WOLFSSL_SMALL_STACK
  2080. if (saltTmp != NULL)
  2081. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2082. #endif
  2083. return ret;
  2084. }
  2085. }
  2086. /* leave room for a sequence (contains salt and iterations int) */
  2087. inOutIdx += MAX_SEQ_SZ; sz = 0;
  2088. /* place salt in buffer */
  2089. out[inOutIdx++] = ASN_OCTET_STRING; sz++;
  2090. tmpSz = SetLength(saltSz, out + inOutIdx);
  2091. inOutIdx += tmpSz; sz += tmpSz;
  2092. XMEMCPY(out + inOutIdx, salt, saltSz);
  2093. inOutIdx += saltSz; sz += saltSz;
  2094. /* place iteration count in buffer */
  2095. out[inOutIdx++] = ASN_INTEGER; sz++;
  2096. out[inOutIdx++] = sizeof(word32); sz++;
  2097. out[inOutIdx++] = (itt >> 24) & 0xFF;
  2098. out[inOutIdx++] = (itt >> 16) & 0xFF;
  2099. out[inOutIdx++] = (itt >> 8 ) & 0xFF;
  2100. out[inOutIdx++] = itt & 0xFF;
  2101. sz += 4;
  2102. /* wind back index and set sequence then clean up buffer */
  2103. inOutIdx -= (sz + MAX_SEQ_SZ);
  2104. tmpSz = SetSequence(sz, out + inOutIdx);
  2105. XMEMMOVE(out + inOutIdx + tmpSz, out + inOutIdx + MAX_SEQ_SZ, sz);
  2106. inOutIdx += tmpSz + sz; totalSz += tmpSz + sz;
  2107. /* octet string containing encrypted key */
  2108. out[inOutIdx++] = ASN_OCTET_STRING; totalSz++;
  2109. }
  2110. /* check key type and get OID if ECC */
  2111. if ((ret = wc_GetKeyOID(key, keySz, &curveOID, &oidSz, &algoID, heap))< 0) {
  2112. return ret;
  2113. }
  2114. /* PKCS#8 wrapping around key */
  2115. if (wc_CreatePKCS8Key(NULL, &tmpSz, key, keySz, algoID, curveOID, oidSz)
  2116. != LENGTH_ONLY_E) {
  2117. #ifdef WOLFSSL_SMALL_STACK
  2118. if (saltTmp != NULL)
  2119. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2120. #endif
  2121. return MEMORY_E;
  2122. }
  2123. /* check if should return max size */
  2124. if (out == NULL) {
  2125. /* account for salt size */
  2126. if (salt == NULL || saltSz <= 0) {
  2127. tmpSz += MAX_SALT_SIZE;
  2128. }
  2129. else {
  2130. tmpSz += saltSz;
  2131. }
  2132. /* plus 3 for tags */
  2133. *outSz = tmpSz + MAX_ALGO_SZ + MAX_LENGTH_SZ +MAX_LENGTH_SZ + MAX_SEQ_SZ
  2134. + MAX_LENGTH_SZ + MAX_SEQ_SZ + 3;
  2135. return LENGTH_ONLY_E;
  2136. }
  2137. tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2138. if (tmp == NULL) {
  2139. #ifdef WOLFSSL_SMALL_STACK
  2140. if (saltTmp != NULL)
  2141. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2142. #endif
  2143. return MEMORY_E;
  2144. }
  2145. if ((ret = wc_CreatePKCS8Key(tmp, &tmpSz, key, keySz, algoID, curveOID,
  2146. oidSz)) < 0) {
  2147. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2148. WOLFSSL_MSG("Error wrapping key with PKCS#8");
  2149. #ifdef WOLFSSL_SMALL_STACK
  2150. if (saltTmp != NULL)
  2151. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2152. #endif
  2153. return ret;
  2154. }
  2155. tmpSz = ret;
  2156. #ifdef WOLFSSL_SMALL_STACK
  2157. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2158. if (cbcIv == NULL) {
  2159. if (saltTmp != NULL)
  2160. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2161. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2162. return MEMORY_E;
  2163. }
  2164. #endif
  2165. /* encrypt PKCS#8 wrapped key */
  2166. if ((ret = CryptKey(password, passwordSz, salt, saltSz, itt, id,
  2167. tmp, tmpSz, version, cbcIv, 1)) < 0) {
  2168. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2169. WOLFSSL_MSG("Error encrypting key");
  2170. #ifdef WOLFSSL_SMALL_STACK
  2171. if (saltTmp != NULL)
  2172. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2173. if (cbcIv != NULL)
  2174. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2175. #endif
  2176. return ret; /* encryption failure */
  2177. }
  2178. totalSz += tmpSz;
  2179. #ifdef WOLFSSL_SMALL_STACK
  2180. if (saltTmp != NULL)
  2181. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2182. if (cbcIv != NULL)
  2183. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2184. #endif
  2185. if (*outSz < inOutIdx + tmpSz + MAX_LENGTH_SZ) {
  2186. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2187. return BUFFER_E;
  2188. }
  2189. /* set length of key and copy over encrypted key */
  2190. seqSz = SetLength(tmpSz, out + inOutIdx);
  2191. inOutIdx += seqSz; totalSz += seqSz;
  2192. XMEMCPY(out + inOutIdx, tmp, tmpSz);
  2193. XFREE(tmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2194. /* set total size at begining */
  2195. sz = SetSequence(totalSz, out);
  2196. XMEMMOVE(out + sz, out + MAX_SEQ_SZ, totalSz);
  2197. return totalSz + sz;
  2198. }
  2199. /* Remove Encrypted PKCS8 header, move beginning of traditional to beginning
  2200. of input */
  2201. int ToTraditionalEnc(byte* input, word32 sz,const char* password,int passwordSz)
  2202. {
  2203. word32 inOutIdx = 0, seqEnd, oid;
  2204. int ret = 0, first, second, length = 0, version, saltSz, id;
  2205. int iterations = 0, keySz = 0;
  2206. #ifdef WOLFSSL_SMALL_STACK
  2207. byte* salt = NULL;
  2208. byte* cbcIv = NULL;
  2209. #else
  2210. byte salt[MAX_SALT_SIZE];
  2211. byte cbcIv[MAX_IV_SIZE];
  2212. #endif
  2213. if (passwordSz < 0) {
  2214. WOLFSSL_MSG("Bad password size");
  2215. return BAD_FUNC_ARG;
  2216. }
  2217. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  2218. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2219. }
  2220. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  2221. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2222. }
  2223. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  2224. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  2225. if (CheckAlgo(first, second, &id, &version) < 0) {
  2226. ERROR_OUT(ASN_INPUT_E, exit_tte); /* Algo ID error */
  2227. }
  2228. if (version == PKCS5v2) {
  2229. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  2230. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2231. }
  2232. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  2233. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2234. }
  2235. if (oid != PBKDF2_OID) {
  2236. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2237. }
  2238. }
  2239. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  2240. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2241. }
  2242. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  2243. * DEFAULT items. */
  2244. seqEnd = inOutIdx + length;
  2245. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  2246. if (ret < 0)
  2247. goto exit_tte;
  2248. if (saltSz > MAX_SALT_SIZE) {
  2249. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2250. }
  2251. #ifdef WOLFSSL_SMALL_STACK
  2252. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2253. if (salt == NULL) {
  2254. ERROR_OUT(MEMORY_E, exit_tte);
  2255. }
  2256. #endif
  2257. XMEMCPY(salt, &input[inOutIdx], saltSz);
  2258. inOutIdx += saltSz;
  2259. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  2260. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2261. }
  2262. /* OPTIONAL key length */
  2263. if (seqEnd > inOutIdx && input[inOutIdx] == ASN_INTEGER) {
  2264. if (GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  2265. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2266. }
  2267. }
  2268. /* DEFAULT HMAC is SHA-1 */
  2269. if (seqEnd > inOutIdx) {
  2270. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  2271. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2272. }
  2273. }
  2274. #ifdef WOLFSSL_SMALL_STACK
  2275. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2276. if (cbcIv == NULL) {
  2277. ERROR_OUT(MEMORY_E, exit_tte);
  2278. }
  2279. #endif
  2280. if (version == PKCS5v2) {
  2281. /* get encryption algo */
  2282. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  2283. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2284. }
  2285. if (CheckAlgoV2(oid, &id) < 0) {
  2286. ERROR_OUT(ASN_PARSE_E, exit_tte); /* PKCS v2 algo id error */
  2287. }
  2288. ret = GetOctetString(input, &inOutIdx, &length, sz);
  2289. if (ret < 0)
  2290. goto exit_tte;
  2291. if (length > MAX_IV_SIZE) {
  2292. ERROR_OUT(ASN_PARSE_E, exit_tte);
  2293. }
  2294. XMEMCPY(cbcIv, &input[inOutIdx], length);
  2295. inOutIdx += length;
  2296. }
  2297. ret = GetOctetString(input, &inOutIdx, &length, sz);
  2298. if (ret < 0)
  2299. goto exit_tte;
  2300. ret = CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  2301. input + inOutIdx, length, version, cbcIv, 0);
  2302. exit_tte:
  2303. #ifdef WOLFSSL_SMALL_STACK
  2304. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2305. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2306. #endif
  2307. if (ret == 0) {
  2308. XMEMMOVE(input, input + inOutIdx, length);
  2309. ret = ToTraditional(input, length);
  2310. }
  2311. return ret;
  2312. }
  2313. /* encrypt PKCS 12 content
  2314. *
  2315. * NOTE: if out is NULL then outSz is set with the total buffer size needed and
  2316. * the error value LENGTH_ONLY_E is returned.
  2317. *
  2318. * input data to encrypt
  2319. * inputSz size of input buffer
  2320. * out buffer to hold the result
  2321. * outSz size of out buffer
  2322. * password password if used. Can be NULL for no password
  2323. * passwordSz size of password buffer
  2324. * vPKCS version of PKCS i.e. PKCS5v2
  2325. * vAlgo algorithm version
  2326. * salt buffer holding salt if used. If NULL then a random salt is created
  2327. * saltSz size of salt buffer if it is not NULL
  2328. * itt number of iterations used
  2329. * rng random number generator to use
  2330. * heap possible heap hint for mallocs/frees
  2331. *
  2332. * returns the total size of encrypted content on success.
  2333. */
  2334. int EncryptContent(byte* input, word32 inputSz, byte* out, word32* outSz,
  2335. const char* password, int passwordSz, int vPKCS, int vAlgo,
  2336. byte* salt, word32 saltSz, int itt, WC_RNG* rng, void* heap)
  2337. {
  2338. word32 sz;
  2339. word32 inOutIdx = 0;
  2340. word32 tmpIdx = 0;
  2341. word32 totalSz = 0;
  2342. word32 seqSz;
  2343. int ret;
  2344. int version, id;
  2345. #ifdef WOLFSSL_SMALL_STACK
  2346. byte* saltTmp = NULL;
  2347. byte* cbcIv = NULL;
  2348. #else
  2349. byte saltTmp[MAX_SALT_SIZE];
  2350. byte cbcIv[MAX_IV_SIZE];
  2351. #endif
  2352. (void)heap;
  2353. WOLFSSL_ENTER("EncryptContent()");
  2354. if (CheckAlgo(vPKCS, vAlgo, &id, &version) < 0)
  2355. return ASN_INPUT_E; /* Algo ID error */
  2356. if (version == PKCS5v2) {
  2357. WOLFSSL_MSG("PKCS#5 version 2 not supported yet");
  2358. return BAD_FUNC_ARG;
  2359. }
  2360. if (saltSz > MAX_SALT_SIZE)
  2361. return ASN_PARSE_E;
  2362. if (outSz == NULL) {
  2363. return BAD_FUNC_ARG;
  2364. }
  2365. if (out == NULL) {
  2366. sz = inputSz;
  2367. switch (id) {
  2368. case PBE_MD5_DES:
  2369. case PBE_SHA1_DES:
  2370. case PBE_SHA1_DES3:
  2371. /* set to block size of 8 for DES operations. This rounds up
  2372. * to the nearset multiple of 8 */
  2373. sz &= 0xfffffff8;
  2374. sz += 8;
  2375. break;
  2376. case PBE_SHA1_RC4_128:
  2377. break;
  2378. case -1:
  2379. break;
  2380. default:
  2381. return ALGO_ID_E;
  2382. }
  2383. if (saltSz <= 0) {
  2384. sz += MAX_SALT_SIZE;
  2385. }
  2386. else {
  2387. sz += saltSz;
  2388. }
  2389. /* add 2 for tags */
  2390. *outSz = sz + MAX_ALGO_SZ + MAX_SEQ_SZ + MAX_LENGTH_SZ +
  2391. MAX_LENGTH_SZ + MAX_LENGTH_SZ + MAX_SHORT_SZ + 2;
  2392. return LENGTH_ONLY_E;
  2393. }
  2394. if (inOutIdx + MAX_ALGO_SZ + MAX_SEQ_SZ + 1 > *outSz)
  2395. return BUFFER_E;
  2396. sz = SetAlgoID(id, out + inOutIdx, oidPBEType, 0);
  2397. inOutIdx += sz; totalSz += sz;
  2398. tmpIdx = inOutIdx;
  2399. tmpIdx += MAX_SEQ_SZ; /* save room for salt and itter sequence */
  2400. out[tmpIdx++] = ASN_OCTET_STRING;
  2401. /* create random salt if one not provided */
  2402. if (salt == NULL || saltSz <= 0) {
  2403. saltSz = 8;
  2404. #ifdef WOLFSSL_SMALL_STACK
  2405. saltTmp = (byte*)XMALLOC(saltSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2406. if (saltTmp == NULL)
  2407. return MEMORY_E;
  2408. #endif
  2409. salt = saltTmp;
  2410. if ((ret = wc_RNG_GenerateBlock(rng, saltTmp, saltSz)) != 0) {
  2411. WOLFSSL_MSG("Error generating random salt");
  2412. #ifdef WOLFSSL_SMALL_STACK
  2413. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2414. #endif
  2415. return ret;
  2416. }
  2417. }
  2418. if (tmpIdx + MAX_LENGTH_SZ + saltSz + MAX_SHORT_SZ > *outSz) {
  2419. #ifdef WOLFSSL_SMALL_STACK
  2420. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2421. #endif
  2422. return BUFFER_E;
  2423. }
  2424. sz = SetLength(saltSz, out + tmpIdx);
  2425. tmpIdx += sz;
  2426. XMEMCPY(out + tmpIdx, salt, saltSz);
  2427. tmpIdx += saltSz;
  2428. /* place itteration setting in buffer */
  2429. out[tmpIdx++] = ASN_INTEGER;
  2430. out[tmpIdx++] = sizeof(word32);
  2431. out[tmpIdx++] = (itt >> 24) & 0xFF;
  2432. out[tmpIdx++] = (itt >> 16) & 0xFF;
  2433. out[tmpIdx++] = (itt >> 8) & 0xFF;
  2434. out[tmpIdx++] = itt & 0xFF;
  2435. /* rewind and place sequence */
  2436. sz = tmpIdx - inOutIdx - MAX_SEQ_SZ;
  2437. seqSz = SetSequence(sz, out + inOutIdx);
  2438. XMEMMOVE(out + inOutIdx + seqSz, out + inOutIdx + MAX_SEQ_SZ, sz);
  2439. inOutIdx += seqSz; totalSz += seqSz;
  2440. inOutIdx += sz; totalSz += sz;
  2441. #ifdef WOLFSSL_SMALL_STACK
  2442. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2443. if (cbcIv == NULL) {
  2444. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2445. return MEMORY_E;
  2446. }
  2447. #endif
  2448. if ((ret = CryptKey(password, passwordSz, salt, saltSz, itt, id,
  2449. input, inputSz, version, cbcIv, 1)) < 0) {
  2450. #ifdef WOLFSSL_SMALL_STACK
  2451. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2452. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2453. #endif
  2454. return ret; /* encrypt failure */
  2455. }
  2456. #ifdef WOLFSSL_SMALL_STACK
  2457. XFREE(cbcIv, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2458. XFREE(saltTmp, heap, DYNAMIC_TYPE_TMP_BUFFER);
  2459. #endif
  2460. if (inOutIdx + 1 + MAX_LENGTH_SZ + inputSz > *outSz)
  2461. return BUFFER_E;
  2462. out[inOutIdx++] = ASN_LONG_LENGTH; totalSz++;
  2463. sz = SetLength(inputSz, out + inOutIdx);
  2464. inOutIdx += sz; totalSz += sz;
  2465. XMEMCPY(out + inOutIdx, input, inputSz);
  2466. totalSz += inputSz;
  2467. return totalSz;
  2468. }
  2469. /* decrypt PKCS
  2470. *
  2471. * NOTE: input buffer is overwritten with decrypted data!
  2472. *
  2473. * input[in/out] data to decrypt and results are written to
  2474. * sz size of input buffer
  2475. * password password if used. Can be NULL for no password
  2476. * passwordSz size of password buffer
  2477. *
  2478. * returns the total size of decrypted content on success.
  2479. */
  2480. int DecryptContent(byte* input, word32 sz,const char* password,int passwordSz)
  2481. {
  2482. word32 inOutIdx = 0, seqEnd, oid;
  2483. int ret = 0;
  2484. int first, second, length = 0, version, saltSz, id;
  2485. int iterations = 0, keySz = 0;
  2486. #ifdef WOLFSSL_SMALL_STACK
  2487. byte* salt = NULL;
  2488. byte* cbcIv = NULL;
  2489. #else
  2490. byte salt[MAX_SALT_SIZE];
  2491. byte cbcIv[MAX_IV_SIZE];
  2492. #endif
  2493. if (GetAlgoId(input, &inOutIdx, &oid, oidIgnoreType, sz) < 0) {
  2494. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2495. }
  2496. first = input[inOutIdx - 2]; /* PKCS version always 2nd to last byte */
  2497. second = input[inOutIdx - 1]; /* version.algo, algo id last byte */
  2498. if (CheckAlgo(first, second, &id, &version) < 0) {
  2499. ERROR_OUT(ASN_INPUT_E, exit_dc); /* Algo ID error */
  2500. }
  2501. if (version == PKCS5v2) {
  2502. if (GetSequence(input, &inOutIdx, &length, sz) < 0) {
  2503. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2504. }
  2505. if (GetAlgoId(input, &inOutIdx, &oid, oidKdfType, sz) < 0) {
  2506. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2507. }
  2508. if (oid != PBKDF2_OID) {
  2509. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2510. }
  2511. }
  2512. if (GetSequence(input, &inOutIdx, &length, sz) <= 0) {
  2513. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2514. }
  2515. /* Find the end of this SEQUENCE so we can check for the OPTIONAL and
  2516. * DEFAULT items. */
  2517. seqEnd = inOutIdx + length;
  2518. ret = GetOctetString(input, &inOutIdx, &saltSz, sz);
  2519. if (ret < 0)
  2520. goto exit_dc;
  2521. if (saltSz > MAX_SALT_SIZE) {
  2522. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2523. }
  2524. #ifdef WOLFSSL_SMALL_STACK
  2525. salt = (byte*)XMALLOC(MAX_SALT_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2526. if (salt == NULL) {
  2527. ERROR_OUT(MEMORY_E, exit_dc);
  2528. }
  2529. #endif
  2530. XMEMCPY(salt, &input[inOutIdx], saltSz);
  2531. inOutIdx += saltSz;
  2532. if (GetShortInt(input, &inOutIdx, &iterations, sz) < 0) {
  2533. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2534. }
  2535. /* OPTIONAL key length */
  2536. if (seqEnd > inOutIdx && input[inOutIdx] == ASN_INTEGER) {
  2537. if (GetShortInt(input, &inOutIdx, &keySz, sz) < 0) {
  2538. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2539. }
  2540. }
  2541. /* DEFAULT HMAC is SHA-1 */
  2542. if (seqEnd > inOutIdx) {
  2543. if (GetAlgoId(input, &inOutIdx, &oid, oidHmacType, sz) < 0) {
  2544. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2545. }
  2546. }
  2547. #ifdef WOLFSSL_SMALL_STACK
  2548. cbcIv = (byte*)XMALLOC(MAX_IV_SIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2549. if (cbcIv == NULL) {
  2550. ERROR_OUT(MEMORY_E, exit_dc);
  2551. }
  2552. #endif
  2553. if (version == PKCS5v2) {
  2554. /* get encryption algo */
  2555. if (GetAlgoId(input, &inOutIdx, &oid, oidBlkType, sz) < 0) {
  2556. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2557. }
  2558. if (CheckAlgoV2(oid, &id) < 0) {
  2559. ERROR_OUT(ASN_PARSE_E, exit_dc); /* PKCS v2 algo id error */
  2560. }
  2561. ret = GetOctetString(input, &inOutIdx, &length, sz);
  2562. if (ret < 0)
  2563. goto exit_dc;
  2564. if (length > MAX_IV_SIZE) {
  2565. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2566. }
  2567. XMEMCPY(cbcIv, &input[inOutIdx], length);
  2568. inOutIdx += length;
  2569. }
  2570. if (input[inOutIdx++] != (ASN_CONTEXT_SPECIFIC | 0)) {
  2571. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2572. }
  2573. if (GetLength(input, &inOutIdx, &length, sz) < 0) {
  2574. ERROR_OUT(ASN_PARSE_E, exit_dc);
  2575. }
  2576. ret = CryptKey(password, passwordSz, salt, saltSz, iterations, id,
  2577. input + inOutIdx, length, version, cbcIv, 0);
  2578. exit_dc:
  2579. #ifdef WOLFSSL_SMALL_STACK
  2580. XFREE(salt, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2581. XFREE(cbcIv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  2582. #endif
  2583. if (ret == 0) {
  2584. XMEMMOVE(input, input + inOutIdx, length);
  2585. ret = length;
  2586. }
  2587. return ret;
  2588. }
  2589. #endif /* NO_PWDBASED */
  2590. #ifndef NO_RSA
  2591. #ifndef HAVE_USER_RSA
  2592. int wc_RsaPublicKeyDecode(const byte* input, word32* inOutIdx, RsaKey* key,
  2593. word32 inSz)
  2594. {
  2595. int length;
  2596. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  2597. byte b;
  2598. #endif
  2599. int ret;
  2600. if (input == NULL || inOutIdx == NULL || key == NULL)
  2601. return BAD_FUNC_ARG;
  2602. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2603. return ASN_PARSE_E;
  2604. key->type = RSA_PUBLIC;
  2605. #if defined(OPENSSL_EXTRA) || defined(RSA_DECODE_EXTRA)
  2606. if ((*inOutIdx + 1) > inSz)
  2607. return BUFFER_E;
  2608. b = input[*inOutIdx];
  2609. if (b != ASN_INTEGER) {
  2610. /* not from decoded cert, will have algo id, skip past */
  2611. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2612. return ASN_PARSE_E;
  2613. if (SkipObjectId(input, inOutIdx, inSz) < 0)
  2614. return ASN_PARSE_E;
  2615. /* Option NULL ASN.1 tag */
  2616. if (input[*inOutIdx] == ASN_TAG_NULL) {
  2617. ret = GetASNNull(input, inOutIdx, inSz);
  2618. if (ret != 0)
  2619. return ret;
  2620. }
  2621. /* should have bit tag length and seq next */
  2622. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  2623. if (ret != 0)
  2624. return ret;
  2625. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2626. return ASN_PARSE_E;
  2627. }
  2628. #endif /* OPENSSL_EXTRA */
  2629. if (GetInt(&key->n, input, inOutIdx, inSz) < 0)
  2630. return ASN_RSA_KEY_E;
  2631. if (GetInt(&key->e, input, inOutIdx, inSz) < 0) {
  2632. mp_clear(&key->n);
  2633. return ASN_RSA_KEY_E;
  2634. }
  2635. #ifdef WOLFSSL_XILINX_CRYPT
  2636. if (wc_InitRsaHw(key) != 0) {
  2637. return BAD_STATE_E;
  2638. }
  2639. #endif
  2640. return 0;
  2641. }
  2642. /* import RSA public key elements (n, e) into RsaKey structure (key) */
  2643. int wc_RsaPublicKeyDecodeRaw(const byte* n, word32 nSz, const byte* e,
  2644. word32 eSz, RsaKey* key)
  2645. {
  2646. if (n == NULL || e == NULL || key == NULL)
  2647. return BAD_FUNC_ARG;
  2648. key->type = RSA_PUBLIC;
  2649. if (mp_init(&key->n) != MP_OKAY)
  2650. return MP_INIT_E;
  2651. if (mp_read_unsigned_bin(&key->n, n, nSz) != 0) {
  2652. mp_clear(&key->n);
  2653. return ASN_GETINT_E;
  2654. }
  2655. if (mp_init(&key->e) != MP_OKAY) {
  2656. mp_clear(&key->n);
  2657. return MP_INIT_E;
  2658. }
  2659. if (mp_read_unsigned_bin(&key->e, e, eSz) != 0) {
  2660. mp_clear(&key->n);
  2661. mp_clear(&key->e);
  2662. return ASN_GETINT_E;
  2663. }
  2664. #ifdef WOLFSSL_XILINX_CRYPT
  2665. if (wc_InitRsaHw(key) != 0) {
  2666. return BAD_STATE_E;
  2667. }
  2668. #endif
  2669. return 0;
  2670. }
  2671. #endif /* HAVE_USER_RSA */
  2672. #endif
  2673. #ifndef NO_DH
  2674. int wc_DhKeyDecode(const byte* input, word32* inOutIdx, DhKey* key, word32 inSz)
  2675. {
  2676. int length;
  2677. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2678. return ASN_PARSE_E;
  2679. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  2680. GetInt(&key->g, input, inOutIdx, inSz) < 0) {
  2681. return ASN_DH_KEY_E;
  2682. }
  2683. return 0;
  2684. }
  2685. int wc_DhParamsLoad(const byte* input, word32 inSz, byte* p, word32* pInOutSz,
  2686. byte* g, word32* gInOutSz)
  2687. {
  2688. word32 idx = 0;
  2689. int ret;
  2690. int length;
  2691. if (GetSequence(input, &idx, &length, inSz) <= 0)
  2692. return ASN_PARSE_E;
  2693. ret = GetASNInt(input, &idx, &length, inSz);
  2694. if (ret != 0)
  2695. return ret;
  2696. if (length <= (int)*pInOutSz) {
  2697. XMEMCPY(p, &input[idx], length);
  2698. *pInOutSz = length;
  2699. }
  2700. else {
  2701. return BUFFER_E;
  2702. }
  2703. idx += length;
  2704. ret = GetASNInt(input, &idx, &length, inSz);
  2705. if (ret != 0)
  2706. return ret;
  2707. if (length <= (int)*gInOutSz) {
  2708. XMEMCPY(g, &input[idx], length);
  2709. *gInOutSz = length;
  2710. }
  2711. else {
  2712. return BUFFER_E;
  2713. }
  2714. return 0;
  2715. }
  2716. #endif /* NO_DH */
  2717. #ifndef NO_DSA
  2718. int DsaPublicKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  2719. word32 inSz)
  2720. {
  2721. int length;
  2722. if (input == NULL || inOutIdx == NULL || key == NULL) {
  2723. return BAD_FUNC_ARG;
  2724. }
  2725. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2726. return ASN_PARSE_E;
  2727. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  2728. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  2729. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  2730. GetInt(&key->y, input, inOutIdx, inSz) < 0 )
  2731. return ASN_DH_KEY_E;
  2732. key->type = DSA_PUBLIC;
  2733. return 0;
  2734. }
  2735. int DsaPrivateKeyDecode(const byte* input, word32* inOutIdx, DsaKey* key,
  2736. word32 inSz)
  2737. {
  2738. int length, version;
  2739. /* Sanity checks on input */
  2740. if (input == NULL || inOutIdx == NULL || key == NULL) {
  2741. return BAD_FUNC_ARG;
  2742. }
  2743. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  2744. return ASN_PARSE_E;
  2745. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  2746. return ASN_PARSE_E;
  2747. if (GetInt(&key->p, input, inOutIdx, inSz) < 0 ||
  2748. GetInt(&key->q, input, inOutIdx, inSz) < 0 ||
  2749. GetInt(&key->g, input, inOutIdx, inSz) < 0 ||
  2750. GetInt(&key->y, input, inOutIdx, inSz) < 0 ||
  2751. GetInt(&key->x, input, inOutIdx, inSz) < 0 )
  2752. return ASN_DH_KEY_E;
  2753. key->type = DSA_PRIVATE;
  2754. return 0;
  2755. }
  2756. static mp_int* GetDsaInt(DsaKey* key, int idx)
  2757. {
  2758. if (idx == 0)
  2759. return &key->p;
  2760. if (idx == 1)
  2761. return &key->q;
  2762. if (idx == 2)
  2763. return &key->g;
  2764. if (idx == 3)
  2765. return &key->y;
  2766. if (idx == 4)
  2767. return &key->x;
  2768. return NULL;
  2769. }
  2770. /* Release Tmp DSA resources */
  2771. static INLINE void FreeTmpDsas(byte** tmps, void* heap)
  2772. {
  2773. int i;
  2774. for (i = 0; i < DSA_INTS; i++)
  2775. XFREE(tmps[i], heap, DYNAMIC_TYPE_DSA);
  2776. (void)heap;
  2777. }
  2778. /* Convert DsaKey key to DER format, write to output (inLen), return bytes
  2779. written */
  2780. int wc_DsaKeyToDer(DsaKey* key, byte* output, word32 inLen)
  2781. {
  2782. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  2783. word32 sizes[DSA_INTS];
  2784. int i, j, outLen, ret = 0, mpSz;
  2785. byte seq[MAX_SEQ_SZ];
  2786. byte ver[MAX_VERSION_SZ];
  2787. byte* tmps[DSA_INTS];
  2788. if (!key || !output)
  2789. return BAD_FUNC_ARG;
  2790. if (key->type != DSA_PRIVATE)
  2791. return BAD_FUNC_ARG;
  2792. for (i = 0; i < DSA_INTS; i++)
  2793. tmps[i] = NULL;
  2794. /* write all big ints from key to DER tmps */
  2795. for (i = 0; i < DSA_INTS; i++) {
  2796. mp_int* keyInt = GetDsaInt(key, i);
  2797. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  2798. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  2799. DYNAMIC_TYPE_DSA);
  2800. if (tmps[i] == NULL) {
  2801. ret = MEMORY_E;
  2802. break;
  2803. }
  2804. mpSz = SetASNIntMP(keyInt, -1, tmps[i]);
  2805. if (mpSz < 0) {
  2806. ret = mpSz;
  2807. break;
  2808. }
  2809. intTotalLen += (sizes[i] = mpSz);
  2810. }
  2811. if (ret != 0) {
  2812. FreeTmpDsas(tmps, key->heap);
  2813. return ret;
  2814. }
  2815. /* make headers */
  2816. verSz = SetMyVersion(0, ver, FALSE);
  2817. seqSz = SetSequence(verSz + intTotalLen, seq);
  2818. outLen = seqSz + verSz + intTotalLen;
  2819. if (outLen > (int)inLen)
  2820. return BAD_FUNC_ARG;
  2821. /* write to output */
  2822. XMEMCPY(output, seq, seqSz);
  2823. j = seqSz;
  2824. XMEMCPY(output + j, ver, verSz);
  2825. j += verSz;
  2826. for (i = 0; i < DSA_INTS; i++) {
  2827. XMEMCPY(output + j, tmps[i], sizes[i]);
  2828. j += sizes[i];
  2829. }
  2830. FreeTmpDsas(tmps, key->heap);
  2831. return outLen;
  2832. }
  2833. #endif /* NO_DSA */
  2834. void InitDecodedCert(DecodedCert* cert, byte* source, word32 inSz, void* heap)
  2835. {
  2836. if (cert != NULL) {
  2837. XMEMSET(cert, 0, sizeof(DecodedCert));
  2838. cert->subjectCNEnc = CTC_UTF8;
  2839. cert->issuer[0] = '\0';
  2840. cert->subject[0] = '\0';
  2841. cert->source = source; /* don't own */
  2842. cert->maxIdx = inSz; /* can't go over this index */
  2843. cert->heap = heap;
  2844. #ifdef WOLFSSL_CERT_GEN
  2845. cert->subjectSNEnc = CTC_UTF8;
  2846. cert->subjectCEnc = CTC_PRINTABLE;
  2847. cert->subjectLEnc = CTC_UTF8;
  2848. cert->subjectSTEnc = CTC_UTF8;
  2849. cert->subjectOEnc = CTC_UTF8;
  2850. cert->subjectOUEnc = CTC_UTF8;
  2851. #endif /* WOLFSSL_CERT_GEN */
  2852. InitSignatureCtx(&cert->sigCtx, heap, INVALID_DEVID);
  2853. }
  2854. }
  2855. void FreeAltNames(DNS_entry* altNames, void* heap)
  2856. {
  2857. (void)heap;
  2858. while (altNames) {
  2859. DNS_entry* tmp = altNames->next;
  2860. XFREE(altNames->name, heap, DYNAMIC_TYPE_ALTNAME);
  2861. XFREE(altNames, heap, DYNAMIC_TYPE_ALTNAME);
  2862. altNames = tmp;
  2863. }
  2864. }
  2865. #ifndef IGNORE_NAME_CONSTRAINTS
  2866. void FreeNameSubtrees(Base_entry* names, void* heap)
  2867. {
  2868. (void)heap;
  2869. while (names) {
  2870. Base_entry* tmp = names->next;
  2871. XFREE(names->name, heap, DYNAMIC_TYPE_ALTNAME);
  2872. XFREE(names, heap, DYNAMIC_TYPE_ALTNAME);
  2873. names = tmp;
  2874. }
  2875. }
  2876. #endif /* IGNORE_NAME_CONSTRAINTS */
  2877. void FreeDecodedCert(DecodedCert* cert)
  2878. {
  2879. if (cert->subjectCNStored == 1)
  2880. XFREE(cert->subjectCN, cert->heap, DYNAMIC_TYPE_SUBJECT_CN);
  2881. if (cert->pubKeyStored == 1)
  2882. XFREE(cert->publicKey, cert->heap, DYNAMIC_TYPE_PUBLIC_KEY);
  2883. if (cert->weOwnAltNames && cert->altNames)
  2884. FreeAltNames(cert->altNames, cert->heap);
  2885. #ifndef IGNORE_NAME_CONSTRAINTS
  2886. if (cert->altEmailNames)
  2887. FreeAltNames(cert->altEmailNames, cert->heap);
  2888. if (cert->permittedNames)
  2889. FreeNameSubtrees(cert->permittedNames, cert->heap);
  2890. if (cert->excludedNames)
  2891. FreeNameSubtrees(cert->excludedNames, cert->heap);
  2892. #endif /* IGNORE_NAME_CONSTRAINTS */
  2893. #ifdef WOLFSSL_SEP
  2894. XFREE(cert->deviceType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  2895. XFREE(cert->hwType, cert->heap, DYNAMIC_TYPE_X509_EXT);
  2896. XFREE(cert->hwSerialNum, cert->heap, DYNAMIC_TYPE_X509_EXT);
  2897. #endif /* WOLFSSL_SEP */
  2898. #ifdef OPENSSL_EXTRA
  2899. if (cert->issuerName.fullName != NULL)
  2900. XFREE(cert->issuerName.fullName, cert->heap, DYNAMIC_TYPE_X509);
  2901. if (cert->subjectName.fullName != NULL)
  2902. XFREE(cert->subjectName.fullName, cert->heap, DYNAMIC_TYPE_X509);
  2903. #endif /* OPENSSL_EXTRA */
  2904. FreeSignatureCtx(&cert->sigCtx);
  2905. }
  2906. static int GetCertHeader(DecodedCert* cert)
  2907. {
  2908. int ret = 0, len;
  2909. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  2910. return ASN_PARSE_E;
  2911. cert->certBegin = cert->srcIdx;
  2912. if (GetSequence(cert->source, &cert->srcIdx, &len, cert->maxIdx) < 0)
  2913. return ASN_PARSE_E;
  2914. cert->sigIndex = len + cert->srcIdx;
  2915. if (GetExplicitVersion(cert->source, &cert->srcIdx, &cert->version,
  2916. cert->maxIdx) < 0)
  2917. return ASN_PARSE_E;
  2918. if (GetSerialNumber(cert->source, &cert->srcIdx, cert->serial,
  2919. &cert->serialSz, cert->maxIdx) < 0)
  2920. return ASN_PARSE_E;
  2921. return ret;
  2922. }
  2923. #if !defined(NO_RSA)
  2924. /* Store Rsa Key, may save later, Dsa could use in future */
  2925. static int StoreRsaKey(DecodedCert* cert)
  2926. {
  2927. int length;
  2928. word32 recvd = cert->srcIdx;
  2929. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  2930. return ASN_PARSE_E;
  2931. recvd = cert->srcIdx - recvd;
  2932. length += recvd;
  2933. while (recvd--)
  2934. cert->srcIdx--;
  2935. cert->pubKeySize = length;
  2936. cert->publicKey = cert->source + cert->srcIdx;
  2937. cert->srcIdx += length;
  2938. return 0;
  2939. }
  2940. #endif /* !NO_RSA */
  2941. #ifdef HAVE_ECC
  2942. /* return 0 on success if the ECC curve oid sum is supported */
  2943. static int CheckCurve(word32 oid)
  2944. {
  2945. int ret = 0;
  2946. word32 oidSz = 0;
  2947. ret = wc_ecc_get_oid(oid, NULL, &oidSz);
  2948. if (ret < 0 || oidSz <= 0) {
  2949. WOLFSSL_MSG("CheckCurve not found");
  2950. ret = ALGO_ID_E;
  2951. }
  2952. return ret;
  2953. }
  2954. #endif /* HAVE_ECC */
  2955. static int GetKey(DecodedCert* cert)
  2956. {
  2957. int length;
  2958. #ifdef HAVE_NTRU
  2959. int tmpIdx = cert->srcIdx;
  2960. #endif
  2961. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  2962. return ASN_PARSE_E;
  2963. if (GetAlgoId(cert->source, &cert->srcIdx,
  2964. &cert->keyOID, oidKeyType, cert->maxIdx) < 0)
  2965. return ASN_PARSE_E;
  2966. switch (cert->keyOID) {
  2967. #ifndef NO_RSA
  2968. case RSAk:
  2969. {
  2970. int ret;
  2971. ret = CheckBitString(cert->source, &cert->srcIdx, NULL,
  2972. cert->maxIdx, 1, NULL);
  2973. if (ret != 0)
  2974. return ret;
  2975. return StoreRsaKey(cert);
  2976. }
  2977. #endif /* NO_RSA */
  2978. #ifdef HAVE_NTRU
  2979. case NTRUk:
  2980. {
  2981. const byte* key = &cert->source[tmpIdx];
  2982. byte* next = (byte*)key;
  2983. word16 keyLen;
  2984. word32 rc;
  2985. word32 remaining = cert->maxIdx - cert->srcIdx;
  2986. #ifdef WOLFSSL_SMALL_STACK
  2987. byte* keyBlob = NULL;
  2988. #else
  2989. byte keyBlob[MAX_NTRU_KEY_SZ];
  2990. #endif
  2991. rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  2992. &keyLen, NULL, &next, &remaining);
  2993. if (rc != NTRU_OK)
  2994. return ASN_NTRU_KEY_E;
  2995. if (keyLen > MAX_NTRU_KEY_SZ)
  2996. return ASN_NTRU_KEY_E;
  2997. #ifdef WOLFSSL_SMALL_STACK
  2998. keyBlob = (byte*)XMALLOC(MAX_NTRU_KEY_SZ, NULL,
  2999. DYNAMIC_TYPE_TMP_BUFFER);
  3000. if (keyBlob == NULL)
  3001. return MEMORY_E;
  3002. #endif
  3003. rc = ntru_crypto_ntru_encrypt_subjectPublicKeyInfo2PublicKey(key,
  3004. &keyLen, keyBlob, &next, &remaining);
  3005. if (rc != NTRU_OK) {
  3006. #ifdef WOLFSSL_SMALL_STACK
  3007. XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3008. #endif
  3009. return ASN_NTRU_KEY_E;
  3010. }
  3011. if ( (next - key) < 0) {
  3012. #ifdef WOLFSSL_SMALL_STACK
  3013. XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3014. #endif
  3015. return ASN_NTRU_KEY_E;
  3016. }
  3017. cert->srcIdx = tmpIdx + (int)(next - key);
  3018. cert->publicKey = (byte*) XMALLOC(keyLen, cert->heap,
  3019. DYNAMIC_TYPE_PUBLIC_KEY);
  3020. if (cert->publicKey == NULL) {
  3021. #ifdef WOLFSSL_SMALL_STACK
  3022. XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3023. #endif
  3024. return MEMORY_E;
  3025. }
  3026. XMEMCPY(cert->publicKey, keyBlob, keyLen);
  3027. cert->pubKeyStored = 1;
  3028. cert->pubKeySize = keyLen;
  3029. #ifdef WOLFSSL_SMALL_STACK
  3030. XFREE(keyBlob, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3031. #endif
  3032. return 0;
  3033. }
  3034. #endif /* HAVE_NTRU */
  3035. #ifdef HAVE_ECC
  3036. case ECDSAk:
  3037. {
  3038. int ret;
  3039. if (GetObjectId(cert->source, &cert->srcIdx,
  3040. &cert->pkCurveOID, oidCurveType, cert->maxIdx) < 0)
  3041. return ASN_PARSE_E;
  3042. if (CheckCurve(cert->pkCurveOID) < 0)
  3043. return ECC_CURVE_OID_E;
  3044. /* key header */
  3045. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  3046. cert->maxIdx, 1, NULL);
  3047. if (ret != 0)
  3048. return ret;
  3049. cert->publicKey = (byte*)XMALLOC(length, cert->heap,
  3050. DYNAMIC_TYPE_PUBLIC_KEY);
  3051. if (cert->publicKey == NULL)
  3052. return MEMORY_E;
  3053. XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
  3054. cert->pubKeyStored = 1;
  3055. cert->pubKeySize = length;
  3056. cert->srcIdx += length;
  3057. return 0;
  3058. }
  3059. #endif /* HAVE_ECC */
  3060. #ifdef HAVE_ED25519
  3061. case ED25519k:
  3062. {
  3063. int ret;
  3064. cert->pkCurveOID = ED25519k;
  3065. ret = CheckBitString(cert->source, &cert->srcIdx, &length,
  3066. cert->maxIdx, 1, NULL);
  3067. if (ret != 0)
  3068. return ret;
  3069. cert->publicKey = (byte*) XMALLOC(length, cert->heap,
  3070. DYNAMIC_TYPE_PUBLIC_KEY);
  3071. if (cert->publicKey == NULL)
  3072. return MEMORY_E;
  3073. XMEMCPY(cert->publicKey, &cert->source[cert->srcIdx], length);
  3074. cert->pubKeyStored = 1;
  3075. cert->pubKeySize = length;
  3076. cert->srcIdx += length;
  3077. return 0;
  3078. }
  3079. #endif /* HAVE_ED25519 */
  3080. default:
  3081. return ASN_UNKNOWN_OID_E;
  3082. }
  3083. }
  3084. /* process NAME, either issuer or subject */
  3085. static int GetName(DecodedCert* cert, int nameType)
  3086. {
  3087. int length; /* length of all distinguished names */
  3088. int dummy;
  3089. int ret;
  3090. char* full;
  3091. byte* hash;
  3092. word32 idx;
  3093. #ifdef OPENSSL_EXTRA
  3094. DecodedName* dName =
  3095. (nameType == ISSUER) ? &cert->issuerName : &cert->subjectName;
  3096. int dcnum = 0;
  3097. #endif /* OPENSSL_EXTRA */
  3098. WOLFSSL_MSG("Getting Cert Name");
  3099. if (nameType == ISSUER) {
  3100. full = cert->issuer;
  3101. hash = cert->issuerHash;
  3102. }
  3103. else {
  3104. full = cert->subject;
  3105. hash = cert->subjectHash;
  3106. }
  3107. if (cert->source[cert->srcIdx] == ASN_OBJECT_ID) {
  3108. WOLFSSL_MSG("Trying optional prefix...");
  3109. if (SkipObjectId(cert->source, &cert->srcIdx, cert->maxIdx) < 0)
  3110. return ASN_PARSE_E;
  3111. WOLFSSL_MSG("Got optional prefix");
  3112. }
  3113. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  3114. * calculated over the entire DER encoding of the Name field, including
  3115. * the tag and length. */
  3116. idx = cert->srcIdx;
  3117. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  3118. return ASN_PARSE_E;
  3119. #ifdef NO_SHA
  3120. ret = wc_Sha256Hash(&cert->source[idx], length + cert->srcIdx - idx, hash);
  3121. #else
  3122. ret = wc_ShaHash(&cert->source[idx], length + cert->srcIdx - idx, hash);
  3123. #endif
  3124. if (ret != 0)
  3125. return ret;
  3126. length += cert->srcIdx;
  3127. idx = 0;
  3128. #ifdef HAVE_PKCS7
  3129. /* store pointer to raw issuer */
  3130. if (nameType == ISSUER) {
  3131. cert->issuerRaw = &cert->source[cert->srcIdx];
  3132. cert->issuerRawLen = length - cert->srcIdx;
  3133. }
  3134. #endif
  3135. #ifndef IGNORE_NAME_CONSTRAINTS
  3136. if (nameType == SUBJECT) {
  3137. cert->subjectRaw = &cert->source[cert->srcIdx];
  3138. cert->subjectRawLen = length - cert->srcIdx;
  3139. }
  3140. #endif
  3141. while (cert->srcIdx < (word32)length) {
  3142. byte b;
  3143. byte joint[2];
  3144. byte tooBig = FALSE;
  3145. int oidSz;
  3146. if (GetSet(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) < 0) {
  3147. WOLFSSL_MSG("Cert name lacks set header, trying sequence");
  3148. }
  3149. if (GetSequence(cert->source, &cert->srcIdx, &dummy, cert->maxIdx) <= 0)
  3150. return ASN_PARSE_E;
  3151. ret = GetASNObjectId(cert->source, &cert->srcIdx, &oidSz, cert->maxIdx);
  3152. if (ret != 0)
  3153. return ret;
  3154. /* make sure there is room for joint */
  3155. if ((cert->srcIdx + sizeof(joint)) > cert->maxIdx)
  3156. return ASN_PARSE_E;
  3157. XMEMCPY(joint, &cert->source[cert->srcIdx], sizeof(joint));
  3158. /* v1 name types */
  3159. if (joint[0] == 0x55 && joint[1] == 0x04) {
  3160. byte id;
  3161. byte copy = FALSE;
  3162. int strLen;
  3163. cert->srcIdx += 2;
  3164. id = cert->source[cert->srcIdx++];
  3165. b = cert->source[cert->srcIdx++]; /* encoding */
  3166. if (GetLength(cert->source, &cert->srcIdx, &strLen,
  3167. cert->maxIdx) < 0)
  3168. return ASN_PARSE_E;
  3169. if ( (strLen + 14) > (int)(ASN_NAME_MAX - idx)) {
  3170. /* include biggest pre fix header too 4 = "/serialNumber=" */
  3171. WOLFSSL_MSG("ASN Name too big, skipping");
  3172. tooBig = TRUE;
  3173. }
  3174. if (id == ASN_COMMON_NAME) {
  3175. if (nameType == SUBJECT) {
  3176. cert->subjectCN = (char *)&cert->source[cert->srcIdx];
  3177. cert->subjectCNLen = strLen;
  3178. cert->subjectCNEnc = b;
  3179. }
  3180. if (!tooBig) {
  3181. XMEMCPY(&full[idx], "/CN=", 4);
  3182. idx += 4;
  3183. copy = TRUE;
  3184. }
  3185. #ifdef OPENSSL_EXTRA
  3186. dName->cnIdx = cert->srcIdx;
  3187. dName->cnLen = strLen;
  3188. #endif /* OPENSSL_EXTRA */
  3189. }
  3190. else if (id == ASN_SUR_NAME) {
  3191. if (!tooBig) {
  3192. XMEMCPY(&full[idx], "/SN=", 4);
  3193. idx += 4;
  3194. copy = TRUE;
  3195. }
  3196. #ifdef WOLFSSL_CERT_GEN
  3197. if (nameType == SUBJECT) {
  3198. cert->subjectSN = (char*)&cert->source[cert->srcIdx];
  3199. cert->subjectSNLen = strLen;
  3200. cert->subjectSNEnc = b;
  3201. }
  3202. #endif /* WOLFSSL_CERT_GEN */
  3203. #ifdef OPENSSL_EXTRA
  3204. dName->snIdx = cert->srcIdx;
  3205. dName->snLen = strLen;
  3206. #endif /* OPENSSL_EXTRA */
  3207. }
  3208. else if (id == ASN_COUNTRY_NAME) {
  3209. if (!tooBig) {
  3210. XMEMCPY(&full[idx], "/C=", 3);
  3211. idx += 3;
  3212. copy = TRUE;
  3213. }
  3214. #ifdef WOLFSSL_CERT_GEN
  3215. if (nameType == SUBJECT) {
  3216. cert->subjectC = (char*)&cert->source[cert->srcIdx];
  3217. cert->subjectCLen = strLen;
  3218. cert->subjectCEnc = b;
  3219. }
  3220. #endif /* WOLFSSL_CERT_GEN */
  3221. #ifdef OPENSSL_EXTRA
  3222. dName->cIdx = cert->srcIdx;
  3223. dName->cLen = strLen;
  3224. #endif /* OPENSSL_EXTRA */
  3225. }
  3226. else if (id == ASN_LOCALITY_NAME) {
  3227. if (!tooBig) {
  3228. XMEMCPY(&full[idx], "/L=", 3);
  3229. idx += 3;
  3230. copy = TRUE;
  3231. }
  3232. #ifdef WOLFSSL_CERT_GEN
  3233. if (nameType == SUBJECT) {
  3234. cert->subjectL = (char*)&cert->source[cert->srcIdx];
  3235. cert->subjectLLen = strLen;
  3236. cert->subjectLEnc = b;
  3237. }
  3238. #endif /* WOLFSSL_CERT_GEN */
  3239. #ifdef OPENSSL_EXTRA
  3240. dName->lIdx = cert->srcIdx;
  3241. dName->lLen = strLen;
  3242. #endif /* OPENSSL_EXTRA */
  3243. }
  3244. else if (id == ASN_STATE_NAME) {
  3245. if (!tooBig) {
  3246. XMEMCPY(&full[idx], "/ST=", 4);
  3247. idx += 4;
  3248. copy = TRUE;
  3249. }
  3250. #ifdef WOLFSSL_CERT_GEN
  3251. if (nameType == SUBJECT) {
  3252. cert->subjectST = (char*)&cert->source[cert->srcIdx];
  3253. cert->subjectSTLen = strLen;
  3254. cert->subjectSTEnc = b;
  3255. }
  3256. #endif /* WOLFSSL_CERT_GEN */
  3257. #ifdef OPENSSL_EXTRA
  3258. dName->stIdx = cert->srcIdx;
  3259. dName->stLen = strLen;
  3260. #endif /* OPENSSL_EXTRA */
  3261. }
  3262. else if (id == ASN_ORG_NAME) {
  3263. if (!tooBig) {
  3264. XMEMCPY(&full[idx], "/O=", 3);
  3265. idx += 3;
  3266. copy = TRUE;
  3267. }
  3268. #ifdef WOLFSSL_CERT_GEN
  3269. if (nameType == SUBJECT) {
  3270. cert->subjectO = (char*)&cert->source[cert->srcIdx];
  3271. cert->subjectOLen = strLen;
  3272. cert->subjectOEnc = b;
  3273. }
  3274. #endif /* WOLFSSL_CERT_GEN */
  3275. #ifdef OPENSSL_EXTRA
  3276. dName->oIdx = cert->srcIdx;
  3277. dName->oLen = strLen;
  3278. #endif /* OPENSSL_EXTRA */
  3279. }
  3280. else if (id == ASN_ORGUNIT_NAME) {
  3281. if (!tooBig) {
  3282. XMEMCPY(&full[idx], "/OU=", 4);
  3283. idx += 4;
  3284. copy = TRUE;
  3285. }
  3286. #ifdef WOLFSSL_CERT_GEN
  3287. if (nameType == SUBJECT) {
  3288. cert->subjectOU = (char*)&cert->source[cert->srcIdx];
  3289. cert->subjectOULen = strLen;
  3290. cert->subjectOUEnc = b;
  3291. }
  3292. #endif /* WOLFSSL_CERT_GEN */
  3293. #ifdef OPENSSL_EXTRA
  3294. dName->ouIdx = cert->srcIdx;
  3295. dName->ouLen = strLen;
  3296. #endif /* OPENSSL_EXTRA */
  3297. }
  3298. else if (id == ASN_SERIAL_NUMBER) {
  3299. if (!tooBig) {
  3300. XMEMCPY(&full[idx], "/serialNumber=", 14);
  3301. idx += 14;
  3302. copy = TRUE;
  3303. }
  3304. #ifdef OPENSSL_EXTRA
  3305. dName->snIdx = cert->srcIdx;
  3306. dName->snLen = strLen;
  3307. #endif /* OPENSSL_EXTRA */
  3308. }
  3309. if (copy && !tooBig) {
  3310. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], strLen);
  3311. idx += strLen;
  3312. }
  3313. cert->srcIdx += strLen;
  3314. }
  3315. else {
  3316. /* skip */
  3317. byte email = FALSE;
  3318. byte pilot = FALSE;
  3319. byte id = 0;
  3320. int adv;
  3321. if (joint[0] == 0x2a && joint[1] == 0x86) /* email id hdr */
  3322. email = TRUE;
  3323. if (joint[0] == 0x9 && joint[1] == 0x92) { /* uid id hdr */
  3324. /* last value of OID is the type of pilot attribute */
  3325. id = cert->source[cert->srcIdx + oidSz - 1];
  3326. pilot = TRUE;
  3327. }
  3328. cert->srcIdx += oidSz + 1;
  3329. if (GetLength(cert->source, &cert->srcIdx, &adv, cert->maxIdx) < 0)
  3330. return ASN_PARSE_E;
  3331. if (adv > (int)(ASN_NAME_MAX - idx)) {
  3332. WOLFSSL_MSG("ASN name too big, skipping");
  3333. tooBig = TRUE;
  3334. }
  3335. if (email) {
  3336. if ( (14 + adv) > (int)(ASN_NAME_MAX - idx)) {
  3337. WOLFSSL_MSG("ASN name too big, skipping");
  3338. tooBig = TRUE;
  3339. }
  3340. if (!tooBig) {
  3341. XMEMCPY(&full[idx], "/emailAddress=", 14);
  3342. idx += 14;
  3343. }
  3344. #ifdef WOLFSSL_CERT_GEN
  3345. if (nameType == SUBJECT) {
  3346. cert->subjectEmail = (char*)&cert->source[cert->srcIdx];
  3347. cert->subjectEmailLen = adv;
  3348. }
  3349. #endif /* WOLFSSL_CERT_GEN */
  3350. #ifdef OPENSSL_EXTRA
  3351. dName->emailIdx = cert->srcIdx;
  3352. dName->emailLen = adv;
  3353. #endif /* OPENSSL_EXTRA */
  3354. #ifndef IGNORE_NAME_CONSTRAINTS
  3355. {
  3356. DNS_entry* emailName = NULL;
  3357. emailName = (DNS_entry*)XMALLOC(sizeof(DNS_entry),
  3358. cert->heap, DYNAMIC_TYPE_ALTNAME);
  3359. if (emailName == NULL) {
  3360. WOLFSSL_MSG("\tOut of Memory");
  3361. return MEMORY_E;
  3362. }
  3363. emailName->type = 0;
  3364. emailName->name = (char*)XMALLOC(adv + 1,
  3365. cert->heap, DYNAMIC_TYPE_ALTNAME);
  3366. if (emailName->name == NULL) {
  3367. WOLFSSL_MSG("\tOut of Memory");
  3368. XFREE(emailName, cert->heap, DYNAMIC_TYPE_ALTNAME);
  3369. return MEMORY_E;
  3370. }
  3371. XMEMCPY(emailName->name,
  3372. &cert->source[cert->srcIdx], adv);
  3373. emailName->name[adv] = 0;
  3374. emailName->next = cert->altEmailNames;
  3375. cert->altEmailNames = emailName;
  3376. }
  3377. #endif /* IGNORE_NAME_CONSTRAINTS */
  3378. if (!tooBig) {
  3379. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  3380. idx += adv;
  3381. }
  3382. }
  3383. if (pilot) {
  3384. if ( (5 + adv) > (int)(ASN_NAME_MAX - idx)) {
  3385. WOLFSSL_MSG("ASN name too big, skipping");
  3386. tooBig = TRUE;
  3387. }
  3388. if (!tooBig) {
  3389. switch (id) {
  3390. case ASN_USER_ID:
  3391. XMEMCPY(&full[idx], "/UID=", 5);
  3392. idx += 5;
  3393. #ifdef OPENSSL_EXTRA
  3394. dName->uidIdx = cert->srcIdx;
  3395. dName->uidLen = adv;
  3396. #endif /* OPENSSL_EXTRA */
  3397. break;
  3398. case ASN_DOMAIN_COMPONENT:
  3399. XMEMCPY(&full[idx], "/DC=", 4);
  3400. idx += 4;
  3401. #ifdef OPENSSL_EXTRA
  3402. dName->dcIdx[dcnum] = cert->srcIdx;
  3403. dName->dcLen[dcnum] = adv;
  3404. dName->dcNum = dcnum + 1;
  3405. dcnum++;
  3406. #endif /* OPENSSL_EXTRA */
  3407. break;
  3408. default:
  3409. WOLFSSL_MSG("Unknown pilot attribute type");
  3410. return ASN_PARSE_E;
  3411. }
  3412. XMEMCPY(&full[idx], &cert->source[cert->srcIdx], adv);
  3413. idx += adv;
  3414. }
  3415. }
  3416. cert->srcIdx += adv;
  3417. }
  3418. }
  3419. full[idx++] = 0;
  3420. #ifdef OPENSSL_EXTRA
  3421. {
  3422. int totalLen = 0;
  3423. int i = 0;
  3424. if (dName->cnLen != 0)
  3425. totalLen += dName->cnLen + 4;
  3426. if (dName->snLen != 0)
  3427. totalLen += dName->snLen + 4;
  3428. if (dName->cLen != 0)
  3429. totalLen += dName->cLen + 3;
  3430. if (dName->lLen != 0)
  3431. totalLen += dName->lLen + 3;
  3432. if (dName->stLen != 0)
  3433. totalLen += dName->stLen + 4;
  3434. if (dName->oLen != 0)
  3435. totalLen += dName->oLen + 3;
  3436. if (dName->ouLen != 0)
  3437. totalLen += dName->ouLen + 4;
  3438. if (dName->emailLen != 0)
  3439. totalLen += dName->emailLen + 14;
  3440. if (dName->uidLen != 0)
  3441. totalLen += dName->uidLen + 5;
  3442. if (dName->serialLen != 0)
  3443. totalLen += dName->serialLen + 14;
  3444. if (dName->dcNum != 0){
  3445. for (i = 0;i < dName->dcNum;i++)
  3446. totalLen += dName->dcLen[i] + 4;
  3447. }
  3448. dName->fullName = (char*)XMALLOC(totalLen + 1, cert->heap,
  3449. DYNAMIC_TYPE_X509);
  3450. if (dName->fullName != NULL) {
  3451. idx = 0;
  3452. if (dName->cnLen != 0) {
  3453. dName->entryCount++;
  3454. XMEMCPY(&dName->fullName[idx], "/CN=", 4);
  3455. idx += 4;
  3456. XMEMCPY(&dName->fullName[idx],
  3457. &cert->source[dName->cnIdx], dName->cnLen);
  3458. dName->cnIdx = idx;
  3459. idx += dName->cnLen;
  3460. }
  3461. if (dName->snLen != 0) {
  3462. dName->entryCount++;
  3463. XMEMCPY(&dName->fullName[idx], "/SN=", 4);
  3464. idx += 4;
  3465. XMEMCPY(&dName->fullName[idx],
  3466. &cert->source[dName->snIdx], dName->snLen);
  3467. dName->snIdx = idx;
  3468. idx += dName->snLen;
  3469. }
  3470. if (dName->cLen != 0) {
  3471. dName->entryCount++;
  3472. XMEMCPY(&dName->fullName[idx], "/C=", 3);
  3473. idx += 3;
  3474. XMEMCPY(&dName->fullName[idx],
  3475. &cert->source[dName->cIdx], dName->cLen);
  3476. dName->cIdx = idx;
  3477. idx += dName->cLen;
  3478. }
  3479. if (dName->lLen != 0) {
  3480. dName->entryCount++;
  3481. XMEMCPY(&dName->fullName[idx], "/L=", 3);
  3482. idx += 3;
  3483. XMEMCPY(&dName->fullName[idx],
  3484. &cert->source[dName->lIdx], dName->lLen);
  3485. dName->lIdx = idx;
  3486. idx += dName->lLen;
  3487. }
  3488. if (dName->stLen != 0) {
  3489. dName->entryCount++;
  3490. XMEMCPY(&dName->fullName[idx], "/ST=", 4);
  3491. idx += 4;
  3492. XMEMCPY(&dName->fullName[idx],
  3493. &cert->source[dName->stIdx], dName->stLen);
  3494. dName->stIdx = idx;
  3495. idx += dName->stLen;
  3496. }
  3497. if (dName->oLen != 0) {
  3498. dName->entryCount++;
  3499. XMEMCPY(&dName->fullName[idx], "/O=", 3);
  3500. idx += 3;
  3501. XMEMCPY(&dName->fullName[idx],
  3502. &cert->source[dName->oIdx], dName->oLen);
  3503. dName->oIdx = idx;
  3504. idx += dName->oLen;
  3505. }
  3506. if (dName->ouLen != 0) {
  3507. dName->entryCount++;
  3508. XMEMCPY(&dName->fullName[idx], "/OU=", 4);
  3509. idx += 4;
  3510. XMEMCPY(&dName->fullName[idx],
  3511. &cert->source[dName->ouIdx], dName->ouLen);
  3512. dName->ouIdx = idx;
  3513. idx += dName->ouLen;
  3514. }
  3515. if (dName->emailLen != 0) {
  3516. dName->entryCount++;
  3517. XMEMCPY(&dName->fullName[idx], "/emailAddress=", 14);
  3518. idx += 14;
  3519. XMEMCPY(&dName->fullName[idx],
  3520. &cert->source[dName->emailIdx], dName->emailLen);
  3521. dName->emailIdx = idx;
  3522. idx += dName->emailLen;
  3523. }
  3524. for (i = 0;i < dName->dcNum;i++){
  3525. if (dName->dcLen[i] != 0) {
  3526. dName->entryCount++;
  3527. XMEMCPY(&dName->fullName[idx], "/DC=", 4);
  3528. idx += 4;
  3529. XMEMCPY(&dName->fullName[idx],
  3530. &cert->source[dName->dcIdx[i]], dName->dcLen[i]);
  3531. dName->dcIdx[i] = idx;
  3532. idx += dName->dcLen[i];
  3533. }
  3534. }
  3535. if (dName->uidLen != 0) {
  3536. dName->entryCount++;
  3537. XMEMCPY(&dName->fullName[idx], "/UID=", 5);
  3538. idx += 5;
  3539. XMEMCPY(&dName->fullName[idx],
  3540. &cert->source[dName->uidIdx], dName->uidLen);
  3541. dName->uidIdx = idx;
  3542. idx += dName->uidLen;
  3543. }
  3544. if (dName->serialLen != 0) {
  3545. dName->entryCount++;
  3546. XMEMCPY(&dName->fullName[idx], "/serialNumber=", 14);
  3547. idx += 14;
  3548. XMEMCPY(&dName->fullName[idx],
  3549. &cert->source[dName->serialIdx], dName->serialLen);
  3550. dName->serialIdx = idx;
  3551. idx += dName->serialLen;
  3552. }
  3553. dName->fullName[idx] = '\0';
  3554. dName->fullNameLen = totalLen;
  3555. }
  3556. }
  3557. #endif /* OPENSSL_EXTRA */
  3558. return 0;
  3559. }
  3560. #ifndef NO_ASN_TIME
  3561. #if !defined(NO_TIME_H) && defined(USE_WOLF_VALIDDATE)
  3562. /* to the second */
  3563. static int DateGreaterThan(const struct tm* a, const struct tm* b)
  3564. {
  3565. if (a->tm_year > b->tm_year)
  3566. return 1;
  3567. if (a->tm_year == b->tm_year && a->tm_mon > b->tm_mon)
  3568. return 1;
  3569. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  3570. a->tm_mday > b->tm_mday)
  3571. return 1;
  3572. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  3573. a->tm_mday == b->tm_mday && a->tm_hour > b->tm_hour)
  3574. return 1;
  3575. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  3576. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  3577. a->tm_min > b->tm_min)
  3578. return 1;
  3579. if (a->tm_year == b->tm_year && a->tm_mon == b->tm_mon &&
  3580. a->tm_mday == b->tm_mday && a->tm_hour == b->tm_hour &&
  3581. a->tm_min == b->tm_min && a->tm_sec > b->tm_sec)
  3582. return 1;
  3583. return 0; /* false */
  3584. }
  3585. static INLINE int DateLessThan(const struct tm* a, const struct tm* b)
  3586. {
  3587. return DateGreaterThan(b,a);
  3588. }
  3589. #if defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA) \
  3590. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  3591. int GetTimeString(byte* date, int format, char* buf, int len)
  3592. {
  3593. struct tm t;
  3594. int idx = 0;
  3595. if (!ExtractDate(date, (unsigned char)format, &t, &idx)) {
  3596. return 0;
  3597. }
  3598. if (date[idx] != 'Z') {
  3599. WOLFSSL_MSG("UTCtime, not Zulu") ;
  3600. return 0;
  3601. }
  3602. /* place month in buffer */
  3603. buf[0] = '\0';
  3604. switch(t.tm_mon) {
  3605. case 0: XSTRNCAT(buf, "Jan ", 4); break;
  3606. case 1: XSTRNCAT(buf, "Feb ", 4); break;
  3607. case 2: XSTRNCAT(buf, "Mar ", 4); break;
  3608. case 3: XSTRNCAT(buf, "Apr ", 4); break;
  3609. case 4: XSTRNCAT(buf, "May ", 4); break;
  3610. case 5: XSTRNCAT(buf, "Jun ", 4); break;
  3611. case 6: XSTRNCAT(buf, "Jul ", 4); break;
  3612. case 7: XSTRNCAT(buf, "Aug ", 4); break;
  3613. case 8: XSTRNCAT(buf, "Sep ", 4); break;
  3614. case 9: XSTRNCAT(buf, "Oct ", 4); break;
  3615. case 10: XSTRNCAT(buf, "Nov ", 4); break;
  3616. case 11: XSTRNCAT(buf, "Dec ", 4); break;
  3617. default:
  3618. return 0;
  3619. }
  3620. idx = 4; /* use idx now for char buffer */
  3621. buf[idx] = ' ';
  3622. XSNPRINTF(buf + idx, len - idx, "%2d %02d:%02d:%02d %d GMT",
  3623. t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, t.tm_year + 1900);
  3624. return 1;
  3625. }
  3626. #endif /* WOLFSSL_MYSQL_COMPATIBLE */
  3627. int ExtractDate(const unsigned char* date, unsigned char format,
  3628. struct tm* certTime, int* idx)
  3629. {
  3630. XMEMSET(certTime, 0, sizeof(struct tm));
  3631. if (format == ASN_UTC_TIME) {
  3632. if (btoi(date[0]) >= 5)
  3633. certTime->tm_year = 1900;
  3634. else
  3635. certTime->tm_year = 2000;
  3636. }
  3637. else { /* format == GENERALIZED_TIME */
  3638. certTime->tm_year += btoi(date[*idx]) * 1000; *idx = *idx + 1;
  3639. certTime->tm_year += btoi(date[*idx]) * 100; *idx = *idx + 1;
  3640. }
  3641. /* adjust tm_year, tm_mon */
  3642. GetTime((int*)&certTime->tm_year, date, idx); certTime->tm_year -= 1900;
  3643. GetTime((int*)&certTime->tm_mon, date, idx); certTime->tm_mon -= 1;
  3644. GetTime((int*)&certTime->tm_mday, date, idx);
  3645. GetTime((int*)&certTime->tm_hour, date, idx);
  3646. GetTime((int*)&certTime->tm_min, date, idx);
  3647. GetTime((int*)&certTime->tm_sec, date, idx);
  3648. return 1;
  3649. }
  3650. /* like atoi but only use first byte */
  3651. /* Make sure before and after dates are valid */
  3652. int ValidateDate(const byte* date, byte format, int dateType)
  3653. {
  3654. time_t ltime;
  3655. struct tm certTime;
  3656. struct tm* localTime;
  3657. struct tm* tmpTime = NULL;
  3658. int i = 0;
  3659. int timeDiff = 0 ;
  3660. int diffHH = 0 ; int diffMM = 0 ;
  3661. int diffSign = 0 ;
  3662. #if defined(NEED_TMP_TIME)
  3663. struct tm tmpTimeStorage;
  3664. tmpTime = &tmpTimeStorage;
  3665. #else
  3666. (void)tmpTime;
  3667. #endif
  3668. ltime = XTIME(0);
  3669. #ifdef WOLFSSL_BEFORE_DATE_CLOCK_SKEW
  3670. if (dateType == BEFORE) {
  3671. WOLFSSL_MSG("Skewing local time for before date check");
  3672. ltime += WOLFSSL_BEFORE_DATE_CLOCK_SKEW;
  3673. }
  3674. #endif
  3675. #ifdef WOLFSSL_AFTER_DATE_CLOCK_SKEW
  3676. if (dateType == AFTER) {
  3677. WOLFSSL_MSG("Skewing local time for after date check");
  3678. ltime -= WOLFSSL_AFTER_DATE_CLOCK_SKEW;
  3679. }
  3680. #endif
  3681. if (!ExtractDate(date, format, &certTime, &i)) {
  3682. WOLFSSL_MSG("Error extracting the date");
  3683. return 0;
  3684. }
  3685. if ((date[i] == '+') || (date[i] == '-')) {
  3686. WOLFSSL_MSG("Using time differential, not Zulu") ;
  3687. diffSign = date[i++] == '+' ? 1 : -1 ;
  3688. GetTime(&diffHH, date, &i);
  3689. GetTime(&diffMM, date, &i);
  3690. timeDiff = diffSign * (diffHH*60 + diffMM) * 60 ;
  3691. } else if (date[i] != 'Z') {
  3692. WOLFSSL_MSG("UTCtime, niether Zulu or time differential") ;
  3693. return 0;
  3694. }
  3695. ltime -= (time_t)timeDiff ;
  3696. localTime = XGMTIME(&ltime, tmpTime);
  3697. if (localTime == NULL) {
  3698. WOLFSSL_MSG("XGMTIME failed");
  3699. return 0;
  3700. }
  3701. if (dateType == BEFORE) {
  3702. if (DateLessThan(localTime, &certTime)) {
  3703. WOLFSSL_MSG("Date BEFORE check failed");
  3704. return 0;
  3705. }
  3706. }
  3707. else { /* dateType == AFTER */
  3708. if (DateGreaterThan(localTime, &certTime)) {
  3709. WOLFSSL_MSG("Date AFTER check failed");
  3710. return 0;
  3711. }
  3712. }
  3713. return 1;
  3714. }
  3715. #endif /* !NO_TIME_H && USE_WOLF_VALIDDATE */
  3716. int wc_GetTime(void* timePtr, word32 timeSize)
  3717. {
  3718. time_t* ltime = (time_t*)timePtr;
  3719. if (timePtr == NULL) {
  3720. return BAD_FUNC_ARG;
  3721. }
  3722. if ((word32)sizeof(time_t) > timeSize) {
  3723. return BUFFER_E;
  3724. }
  3725. *ltime = XTIME(0);
  3726. return 0;
  3727. }
  3728. #endif /* !NO_ASN_TIME */
  3729. static int GetDate(DecodedCert* cert, int dateType)
  3730. {
  3731. int length;
  3732. byte date[MAX_DATE_SIZE];
  3733. byte b;
  3734. word32 startIdx = 0;
  3735. XMEMSET(date, 0, MAX_DATE_SIZE);
  3736. if (dateType == BEFORE)
  3737. cert->beforeDate = &cert->source[cert->srcIdx];
  3738. else
  3739. cert->afterDate = &cert->source[cert->srcIdx];
  3740. startIdx = cert->srcIdx;
  3741. b = cert->source[cert->srcIdx++];
  3742. if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME)
  3743. return ASN_TIME_E;
  3744. if (GetLength(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  3745. return ASN_PARSE_E;
  3746. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  3747. return ASN_DATE_SZ_E;
  3748. XMEMCPY(date, &cert->source[cert->srcIdx], length);
  3749. cert->srcIdx += length;
  3750. if (dateType == BEFORE)
  3751. cert->beforeDateLen = cert->srcIdx - startIdx;
  3752. else
  3753. cert->afterDateLen = cert->srcIdx - startIdx;
  3754. #ifndef NO_ASN_TIME
  3755. if (!XVALIDATE_DATE(date, b, dateType)) {
  3756. if (dateType == BEFORE)
  3757. return ASN_BEFORE_DATE_E;
  3758. else
  3759. return ASN_AFTER_DATE_E;
  3760. }
  3761. #endif
  3762. return 0;
  3763. }
  3764. static int GetValidity(DecodedCert* cert, int verify)
  3765. {
  3766. int length;
  3767. int badDate = 0;
  3768. if (GetSequence(cert->source, &cert->srcIdx, &length, cert->maxIdx) < 0)
  3769. return ASN_PARSE_E;
  3770. if (GetDate(cert, BEFORE) < 0 && verify != NO_VERIFY)
  3771. badDate = ASN_BEFORE_DATE_E; /* continue parsing */
  3772. if (GetDate(cert, AFTER) < 0 && verify != NO_VERIFY)
  3773. return ASN_AFTER_DATE_E;
  3774. if (badDate != 0)
  3775. return badDate;
  3776. return 0;
  3777. }
  3778. int DecodeToKey(DecodedCert* cert, int verify)
  3779. {
  3780. int badDate = 0;
  3781. int ret;
  3782. if ( (ret = GetCertHeader(cert)) < 0)
  3783. return ret;
  3784. WOLFSSL_MSG("Got Cert Header");
  3785. if ( (ret = GetAlgoId(cert->source, &cert->srcIdx, &cert->signatureOID,
  3786. oidSigType, cert->maxIdx)) < 0)
  3787. return ret;
  3788. WOLFSSL_MSG("Got Algo ID");
  3789. if ( (ret = GetName(cert, ISSUER)) < 0)
  3790. return ret;
  3791. if ( (ret = GetValidity(cert, verify)) < 0)
  3792. badDate = ret;
  3793. if ( (ret = GetName(cert, SUBJECT)) < 0)
  3794. return ret;
  3795. WOLFSSL_MSG("Got Subject Name");
  3796. if ( (ret = GetKey(cert)) < 0)
  3797. return ret;
  3798. WOLFSSL_MSG("Got Key");
  3799. if (badDate != 0)
  3800. return badDate;
  3801. return ret;
  3802. }
  3803. static int GetSignature(DecodedCert* cert)
  3804. {
  3805. int length;
  3806. int ret;
  3807. ret = CheckBitString(cert->source, &cert->srcIdx, &length, cert->maxIdx, 1,
  3808. NULL);
  3809. if (ret != 0)
  3810. return ret;
  3811. cert->sigLength = length;
  3812. cert->signature = &cert->source[cert->srcIdx];
  3813. cert->srcIdx += cert->sigLength;
  3814. return 0;
  3815. }
  3816. static word32 SetOctetString8Bit(word32 len, byte* output)
  3817. {
  3818. output[0] = ASN_OCTET_STRING;
  3819. output[1] = (byte)len;
  3820. return 2;
  3821. }
  3822. static word32 SetDigest(const byte* digest, word32 digSz, byte* output)
  3823. {
  3824. word32 idx = SetOctetString8Bit(digSz, output);
  3825. XMEMCPY(&output[idx], digest, digSz);
  3826. return idx + digSz;
  3827. }
  3828. static word32 BytePrecision(word32 value)
  3829. {
  3830. word32 i;
  3831. for (i = sizeof(value); i; --i)
  3832. if (value >> ((i - 1) * WOLFSSL_BIT_SIZE))
  3833. break;
  3834. return i;
  3835. }
  3836. WOLFSSL_LOCAL word32 SetLength(word32 length, byte* output)
  3837. {
  3838. word32 i = 0, j;
  3839. if (length < ASN_LONG_LENGTH)
  3840. output[i++] = (byte)length;
  3841. else {
  3842. output[i++] = (byte)(BytePrecision(length) | ASN_LONG_LENGTH);
  3843. for (j = BytePrecision(length); j; --j) {
  3844. output[i] = (byte)(length >> ((j - 1) * WOLFSSL_BIT_SIZE));
  3845. i++;
  3846. }
  3847. }
  3848. return i;
  3849. }
  3850. WOLFSSL_LOCAL word32 SetSequence(word32 len, byte* output)
  3851. {
  3852. output[0] = ASN_SEQUENCE | ASN_CONSTRUCTED;
  3853. return SetLength(len, output + 1) + 1;
  3854. }
  3855. WOLFSSL_LOCAL word32 SetOctetString(word32 len, byte* output)
  3856. {
  3857. output[0] = ASN_OCTET_STRING;
  3858. return SetLength(len, output + 1) + 1;
  3859. }
  3860. /* Write a set header to output */
  3861. WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output)
  3862. {
  3863. output[0] = ASN_SET | ASN_CONSTRUCTED;
  3864. return SetLength(len, output + 1) + 1;
  3865. }
  3866. WOLFSSL_LOCAL word32 SetImplicit(byte tag, byte number, word32 len, byte* output)
  3867. {
  3868. output[0] = ((tag == ASN_SEQUENCE || tag == ASN_SET) ? ASN_CONSTRUCTED : 0)
  3869. | ASN_CONTEXT_SPECIFIC | number;
  3870. return SetLength(len, output + 1) + 1;
  3871. }
  3872. WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output)
  3873. {
  3874. output[0] = ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | number;
  3875. return SetLength(len, output + 1) + 1;
  3876. }
  3877. #if defined(HAVE_ECC)
  3878. static int SetCurve(ecc_key* key, byte* output)
  3879. {
  3880. #ifdef HAVE_OID_ENCODING
  3881. int ret;
  3882. #endif
  3883. int idx = 0;
  3884. word32 oidSz = 0;
  3885. /* validate key */
  3886. if (key == NULL || key->dp == NULL) {
  3887. return BAD_FUNC_ARG;
  3888. }
  3889. #ifdef HAVE_OID_ENCODING
  3890. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, NULL, &oidSz);
  3891. if (ret != 0) {
  3892. return ret;
  3893. }
  3894. #else
  3895. oidSz = key->dp->oidSz;
  3896. #endif
  3897. idx += SetObjectId(oidSz, output);
  3898. #ifdef HAVE_OID_ENCODING
  3899. ret = EncodeObjectId(key->dp->oid, key->dp->oidSz, output+idx, &oidSz);
  3900. if (ret != 0) {
  3901. return ret;
  3902. }
  3903. #else
  3904. XMEMCPY(output+idx, key->dp->oid, oidSz);
  3905. #endif
  3906. idx += oidSz;
  3907. return idx;
  3908. }
  3909. #endif /* HAVE_ECC */
  3910. static INLINE int IsSigAlgoECDSA(int algoOID)
  3911. {
  3912. /* ECDSA sigAlgo must not have ASN1 NULL parameters */
  3913. if (algoOID == CTC_SHAwECDSA || algoOID == CTC_SHA256wECDSA ||
  3914. algoOID == CTC_SHA384wECDSA || algoOID == CTC_SHA512wECDSA) {
  3915. return 1;
  3916. }
  3917. return 0;
  3918. }
  3919. WOLFSSL_LOCAL word32 SetAlgoID(int algoOID, byte* output, int type, int curveSz)
  3920. {
  3921. word32 tagSz, idSz, seqSz, algoSz = 0;
  3922. const byte* algoName = 0;
  3923. byte ID_Length[1 + MAX_LENGTH_SZ];
  3924. byte seqArray[MAX_SEQ_SZ + 1]; /* add object_id to end */
  3925. tagSz = (type == oidHashType ||
  3926. (type == oidSigType && !IsSigAlgoECDSA(algoOID) &&
  3927. algoOID != ED25519k) ||
  3928. (type == oidKeyType && algoOID == RSAk)) ? 2 : 0;
  3929. algoName = OidFromId(algoOID, type, &algoSz);
  3930. if (algoName == NULL) {
  3931. WOLFSSL_MSG("Unknown Algorithm");
  3932. return 0;
  3933. }
  3934. idSz = SetObjectId(algoSz, ID_Length);
  3935. seqSz = SetSequence(idSz + algoSz + tagSz + curveSz, seqArray);
  3936. XMEMCPY(output, seqArray, seqSz);
  3937. XMEMCPY(output + seqSz, ID_Length, idSz);
  3938. XMEMCPY(output + seqSz + idSz, algoName, algoSz);
  3939. if (tagSz == 2)
  3940. SetASNNull(&output[seqSz + idSz + algoSz]);
  3941. return seqSz + idSz + algoSz + tagSz;
  3942. }
  3943. word32 wc_EncodeSignature(byte* out, const byte* digest, word32 digSz,
  3944. int hashOID)
  3945. {
  3946. byte digArray[MAX_ENCODED_DIG_SZ];
  3947. byte algoArray[MAX_ALGO_SZ];
  3948. byte seqArray[MAX_SEQ_SZ];
  3949. word32 encDigSz, algoSz, seqSz;
  3950. encDigSz = SetDigest(digest, digSz, digArray);
  3951. algoSz = SetAlgoID(hashOID, algoArray, oidHashType, 0);
  3952. seqSz = SetSequence(encDigSz + algoSz, seqArray);
  3953. XMEMCPY(out, seqArray, seqSz);
  3954. XMEMCPY(out + seqSz, algoArray, algoSz);
  3955. XMEMCPY(out + seqSz + algoSz, digArray, encDigSz);
  3956. return encDigSz + algoSz + seqSz;
  3957. }
  3958. int wc_GetCTC_HashOID(int type)
  3959. {
  3960. switch (type) {
  3961. #ifdef WOLFSSL_MD2
  3962. case MD2:
  3963. return MD2h;
  3964. #endif
  3965. #ifndef NO_MD5
  3966. case WC_MD5:
  3967. return MD5h;
  3968. #endif
  3969. #ifndef NO_SHA
  3970. case WC_SHA:
  3971. return SHAh;
  3972. #endif
  3973. #ifdef WOLFSSL_SHA224
  3974. case WC_SHA224:
  3975. return SHA224h;
  3976. #endif
  3977. #ifndef NO_SHA256
  3978. case WC_SHA256:
  3979. return SHA256h;
  3980. #endif
  3981. #ifdef WOLFSSL_SHA384
  3982. case WC_SHA384:
  3983. return SHA384h;
  3984. #endif
  3985. #ifdef WOLFSSL_SHA512
  3986. case WC_SHA512:
  3987. return SHA512h;
  3988. #endif
  3989. default:
  3990. return 0;
  3991. };
  3992. }
  3993. void InitSignatureCtx(SignatureCtx* sigCtx, void* heap, int devId)
  3994. {
  3995. if (sigCtx) {
  3996. XMEMSET(sigCtx, 0, sizeof(SignatureCtx));
  3997. sigCtx->devId = devId;
  3998. sigCtx->heap = heap;
  3999. }
  4000. }
  4001. void FreeSignatureCtx(SignatureCtx* sigCtx)
  4002. {
  4003. if (sigCtx == NULL)
  4004. return;
  4005. if (sigCtx->digest) {
  4006. XFREE(sigCtx->digest, sigCtx->heap, DYNAMIC_TYPE_DIGEST);
  4007. sigCtx->digest = NULL;
  4008. }
  4009. #ifndef NO_RSA
  4010. if (sigCtx->plain) {
  4011. XFREE(sigCtx->plain, sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  4012. sigCtx->plain = NULL;
  4013. }
  4014. #endif
  4015. if (sigCtx->key.ptr) {
  4016. switch (sigCtx->keyOID) {
  4017. #ifndef NO_RSA
  4018. case RSAk:
  4019. wc_FreeRsaKey(sigCtx->key.rsa);
  4020. XFREE(sigCtx->key.ptr, sigCtx->heap, DYNAMIC_TYPE_RSA);
  4021. break;
  4022. #endif /* !NO_RSA */
  4023. #ifdef HAVE_ECC
  4024. case ECDSAk:
  4025. wc_ecc_free(sigCtx->key.ecc);
  4026. XFREE(sigCtx->key.ecc, sigCtx->heap, DYNAMIC_TYPE_ECC);
  4027. break;
  4028. #endif /* HAVE_ECC */
  4029. #ifdef HAVE_ED25519
  4030. case ED25519k:
  4031. wc_ed25519_free(sigCtx->key.ed25519);
  4032. XFREE(sigCtx->key.ed25519, sigCtx->heap, DYNAMIC_TYPE_ED25519);
  4033. break;
  4034. #endif /* HAVE_ED25519 */
  4035. default:
  4036. break;
  4037. } /* switch (keyOID) */
  4038. sigCtx->key.ptr = NULL;
  4039. }
  4040. /* reset state, we are done */
  4041. sigCtx->state = SIG_STATE_BEGIN;
  4042. }
  4043. static int HashForSignature(const byte* buf, word32 bufSz, word32 sigOID,
  4044. byte* digest, int* typeH, int* digestSz, int verify)
  4045. {
  4046. int ret = 0;
  4047. (void)verify;
  4048. switch (sigOID) {
  4049. #if defined(WOLFSSL_MD2)
  4050. case CTC_MD2wRSA:
  4051. if (!verify) {
  4052. ret = HASH_TYPE_E;
  4053. WOLFSSL_MSG("MD2 not supported for signing");
  4054. }
  4055. else if ((ret = wc_Md2Hash(buf, bufSz, digest)) == 0) {
  4056. *typeH = MD2h;
  4057. *digestSz = MD2_DIGEST_SIZE;
  4058. }
  4059. break;
  4060. #endif
  4061. #ifndef NO_MD5
  4062. case CTC_MD5wRSA:
  4063. if ((ret = wc_Md5Hash(buf, bufSz, digest)) == 0) {
  4064. *typeH = MD5h;
  4065. *digestSz = WC_MD5_DIGEST_SIZE;
  4066. }
  4067. break;
  4068. #endif
  4069. #ifndef NO_SHA
  4070. case CTC_SHAwRSA:
  4071. case CTC_SHAwDSA:
  4072. case CTC_SHAwECDSA:
  4073. if ((ret = wc_ShaHash(buf, bufSz, digest)) == 0) {
  4074. *typeH = SHAh;
  4075. *digestSz = WC_SHA_DIGEST_SIZE;
  4076. }
  4077. break;
  4078. #endif
  4079. #ifdef WOLFSSL_SHA224
  4080. case CTC_SHA224wRSA:
  4081. case CTC_SHA224wECDSA:
  4082. if ((ret = wc_Sha224Hash(buf, bufSz, digest)) == 0) {
  4083. *typeH = SHA224h;
  4084. *digestSz = WC_SHA224_DIGEST_SIZE;
  4085. }
  4086. break;
  4087. #endif
  4088. #ifndef NO_SHA256
  4089. case CTC_SHA256wRSA:
  4090. case CTC_SHA256wECDSA:
  4091. if ((ret = wc_Sha256Hash(buf, bufSz, digest)) == 0) {
  4092. *typeH = SHA256h;
  4093. *digestSz = WC_SHA256_DIGEST_SIZE;
  4094. }
  4095. break;
  4096. #endif
  4097. #ifdef WOLFSSL_SHA384
  4098. case CTC_SHA384wRSA:
  4099. case CTC_SHA384wECDSA:
  4100. if ((ret = wc_Sha384Hash(buf, bufSz, digest)) == 0) {
  4101. *typeH = SHA384h;
  4102. *digestSz = WC_SHA384_DIGEST_SIZE;
  4103. }
  4104. break;
  4105. #endif
  4106. #ifdef WOLFSSL_SHA512
  4107. case CTC_SHA512wRSA:
  4108. case CTC_SHA512wECDSA:
  4109. if ((ret = wc_Sha512Hash(buf, bufSz, digest)) == 0) {
  4110. *typeH = SHA512h;
  4111. *digestSz = WC_SHA512_DIGEST_SIZE;
  4112. }
  4113. break;
  4114. #endif
  4115. case CTC_ED25519:
  4116. /* Hashes done in signing operation.
  4117. * Two dependent hashes with prefixes performed.
  4118. */
  4119. break;
  4120. default:
  4121. ret = HASH_TYPE_E;
  4122. WOLFSSL_MSG("Hash for Signature has unsupported type");
  4123. }
  4124. return ret;
  4125. }
  4126. /* Return codes: 0=Success, Negative (see error-crypt.h), ASN_SIG_CONFIRM_E */
  4127. static int ConfirmSignature(SignatureCtx* sigCtx,
  4128. const byte* buf, word32 bufSz,
  4129. const byte* key, word32 keySz, word32 keyOID,
  4130. const byte* sig, word32 sigSz, word32 sigOID)
  4131. {
  4132. int ret = 0;
  4133. if (sigCtx == NULL || buf == NULL || bufSz == 0 || key == NULL ||
  4134. keySz == 0 || sig == NULL || sigSz == 0) {
  4135. return BAD_FUNC_ARG;
  4136. }
  4137. (void)key;
  4138. (void)keySz;
  4139. (void)sig;
  4140. (void)sigSz;
  4141. WOLFSSL_ENTER("ConfirmSignature");
  4142. switch (sigCtx->state) {
  4143. case SIG_STATE_BEGIN:
  4144. {
  4145. sigCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, sigCtx->heap,
  4146. DYNAMIC_TYPE_DIGEST);
  4147. if (sigCtx->digest == NULL) {
  4148. ERROR_OUT(MEMORY_E, exit_cs);
  4149. }
  4150. sigCtx->state = SIG_STATE_HASH;
  4151. } /* SIG_STATE_BEGIN */
  4152. FALL_THROUGH;
  4153. case SIG_STATE_HASH:
  4154. {
  4155. ret = HashForSignature(buf, bufSz, sigOID, sigCtx->digest,
  4156. &sigCtx->typeH, &sigCtx->digestSz, 1);
  4157. if (ret != 0) {
  4158. goto exit_cs;
  4159. }
  4160. sigCtx->state = SIG_STATE_KEY;
  4161. } /* SIG_STATE_HASH */
  4162. FALL_THROUGH;
  4163. case SIG_STATE_KEY:
  4164. {
  4165. sigCtx->keyOID = keyOID;
  4166. switch (keyOID) {
  4167. #ifndef NO_RSA
  4168. case RSAk:
  4169. {
  4170. word32 idx = 0;
  4171. sigCtx->key.rsa = (RsaKey*)XMALLOC(sizeof(RsaKey),
  4172. sigCtx->heap, DYNAMIC_TYPE_RSA);
  4173. sigCtx->plain = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  4174. sigCtx->heap, DYNAMIC_TYPE_SIGNATURE);
  4175. if (sigCtx->key.rsa == NULL || sigCtx->plain == NULL) {
  4176. ERROR_OUT(MEMORY_E, exit_cs);
  4177. }
  4178. if ((ret = wc_InitRsaKey_ex(sigCtx->key.rsa, sigCtx->heap,
  4179. sigCtx->devId)) != 0) {
  4180. goto exit_cs;
  4181. }
  4182. if (sigSz > MAX_ENCODED_SIG_SZ) {
  4183. WOLFSSL_MSG("Verify Signature is too big");
  4184. ERROR_OUT(BUFFER_E, exit_cs);
  4185. }
  4186. if ((ret = wc_RsaPublicKeyDecode(key, &idx, sigCtx->key.rsa,
  4187. keySz)) != 0) {
  4188. WOLFSSL_MSG("ASN Key decode error RSA");
  4189. goto exit_cs;
  4190. }
  4191. XMEMCPY(sigCtx->plain, sig, sigSz);
  4192. sigCtx->out = NULL;
  4193. #ifdef WOLFSSL_ASYNC_CRYPT
  4194. sigCtx->asyncDev = &sigCtx->key.rsa->asyncDev;
  4195. #endif
  4196. break;
  4197. }
  4198. #endif /* !NO_RSA */
  4199. #ifdef HAVE_ECC
  4200. case ECDSAk:
  4201. {
  4202. sigCtx->verify = 0;
  4203. sigCtx->key.ecc = (ecc_key*)XMALLOC(sizeof(ecc_key),
  4204. sigCtx->heap, DYNAMIC_TYPE_ECC);
  4205. if (sigCtx->key.ecc == NULL) {
  4206. ERROR_OUT(MEMORY_E, exit_cs);
  4207. }
  4208. if ((ret = wc_ecc_init_ex(sigCtx->key.ecc, sigCtx->heap,
  4209. sigCtx->devId)) < 0) {
  4210. goto exit_cs;
  4211. }
  4212. if ((ret = wc_ecc_import_x963(key, keySz,
  4213. sigCtx->key.ecc)) < 0) {
  4214. WOLFSSL_MSG("ASN Key import error ECC");
  4215. goto exit_cs;
  4216. }
  4217. #ifdef WOLFSSL_ASYNC_CRYPT
  4218. sigCtx->asyncDev = &sigCtx->key.ecc->asyncDev;
  4219. #endif
  4220. break;
  4221. }
  4222. #endif /* HAVE_ECC */
  4223. #ifdef HAVE_ED25519
  4224. case ED25519k:
  4225. {
  4226. sigCtx->verify = 0;
  4227. sigCtx->key.ed25519 = (ed25519_key*)XMALLOC(
  4228. sizeof(ed25519_key), sigCtx->heap,
  4229. DYNAMIC_TYPE_ED25519);
  4230. if (sigCtx->key.ed25519 == NULL) {
  4231. ERROR_OUT(MEMORY_E, exit_cs);
  4232. }
  4233. if ((ret = wc_ed25519_init(sigCtx->key.ed25519)) < 0) {
  4234. goto exit_cs;
  4235. }
  4236. if ((ret = wc_ed25519_import_public(key, keySz,
  4237. sigCtx->key.ed25519)) < 0) {
  4238. WOLFSSL_MSG("ASN Key import error ED25519");
  4239. goto exit_cs;
  4240. }
  4241. #ifdef WOLFSSL_ASYNC_CRYPT
  4242. sigCtx->asyncDev = &sigCtx->key.ed25519->asyncDev;
  4243. #endif
  4244. break;
  4245. }
  4246. #endif
  4247. default:
  4248. WOLFSSL_MSG("Verify Key type unknown");
  4249. ret = ASN_UNKNOWN_OID_E;
  4250. break;
  4251. } /* switch (keyOID) */
  4252. if (ret != 0) {
  4253. goto exit_cs;
  4254. }
  4255. sigCtx->state = SIG_STATE_DO;
  4256. #ifdef WOLFSSL_ASYNC_CRYPT
  4257. if (sigCtx->devId != INVALID_DEVID && sigCtx->asyncDev && sigCtx->asyncCtx) {
  4258. /* make sure event is intialized */
  4259. WOLF_EVENT* event = &sigCtx->asyncDev->event;
  4260. ret = wolfAsync_EventInit(event, WOLF_EVENT_TYPE_ASYNC_WOLFSSL,
  4261. sigCtx->asyncCtx, WC_ASYNC_FLAG_CALL_AGAIN);
  4262. }
  4263. #endif
  4264. } /* SIG_STATE_KEY */
  4265. FALL_THROUGH;
  4266. case SIG_STATE_DO:
  4267. {
  4268. switch (keyOID) {
  4269. #ifndef NO_RSA
  4270. case RSAk:
  4271. {
  4272. ret = wc_RsaSSL_VerifyInline(sigCtx->plain, sigSz,
  4273. &sigCtx->out, sigCtx->key.rsa);
  4274. break;
  4275. }
  4276. #endif /* !NO_RSA */
  4277. #ifdef HAVE_ECC
  4278. case ECDSAk:
  4279. {
  4280. ret = wc_ecc_verify_hash(sig, sigSz, sigCtx->digest,
  4281. sigCtx->digestSz, &sigCtx->verify, sigCtx->key.ecc);
  4282. break;
  4283. }
  4284. #endif /* HAVE_ECC */
  4285. #ifdef HAVE_ED25519
  4286. case ED25519k:
  4287. {
  4288. ret = wc_ed25519_verify_msg(sig, sigSz, buf, bufSz,
  4289. &sigCtx->verify, sigCtx->key.ed25519);
  4290. break;
  4291. }
  4292. #endif
  4293. default:
  4294. break;
  4295. } /* switch (keyOID) */
  4296. if (ret < 0) {
  4297. /* treat all non async RSA errors as ASN_SIG_CONFIRM_E */
  4298. if (ret != WC_PENDING_E)
  4299. ret = ASN_SIG_CONFIRM_E;
  4300. goto exit_cs;
  4301. }
  4302. sigCtx->state = SIG_STATE_CHECK;
  4303. } /* SIG_STATE_DO */
  4304. FALL_THROUGH;
  4305. case SIG_STATE_CHECK:
  4306. {
  4307. switch (keyOID) {
  4308. #ifndef NO_RSA
  4309. case RSAk:
  4310. {
  4311. int encodedSigSz, verifySz;
  4312. #ifdef WOLFSSL_SMALL_STACK
  4313. byte* encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ,
  4314. sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4315. if (encodedSig == NULL) {
  4316. ERROR_OUT(MEMORY_E, exit_cs);
  4317. }
  4318. #else
  4319. byte encodedSig[MAX_ENCODED_SIG_SZ];
  4320. #endif
  4321. verifySz = ret;
  4322. /* make sure we're right justified */
  4323. encodedSigSz = wc_EncodeSignature(encodedSig,
  4324. sigCtx->digest, sigCtx->digestSz, sigCtx->typeH);
  4325. if (encodedSigSz == verifySz &&
  4326. XMEMCMP(sigCtx->out, encodedSig, encodedSigSz) == 0) {
  4327. ret = 0;
  4328. }
  4329. else {
  4330. WOLFSSL_MSG("RSA SSL verify match encode error");
  4331. ret = ASN_SIG_CONFIRM_E;
  4332. }
  4333. #ifdef WOLFSSL_SMALL_STACK
  4334. XFREE(encodedSig, sigCtx->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4335. #endif
  4336. break;
  4337. }
  4338. #endif /* NO_RSA */
  4339. #ifdef HAVE_ECC
  4340. case ECDSAk:
  4341. {
  4342. if (sigCtx->verify == 1) {
  4343. ret = 0;
  4344. }
  4345. else {
  4346. WOLFSSL_MSG("ECC Verify didn't match");
  4347. ret = ASN_SIG_CONFIRM_E;
  4348. }
  4349. break;
  4350. }
  4351. #endif /* HAVE_ECC */
  4352. #ifdef HAVE_ED25519
  4353. case ED25519k:
  4354. {
  4355. if (sigCtx->verify == 1) {
  4356. ret = 0;
  4357. }
  4358. else {
  4359. WOLFSSL_MSG("ED25519 Verify didn't match");
  4360. ret = ASN_SIG_CONFIRM_E;
  4361. }
  4362. break;
  4363. }
  4364. #endif /* HAVE_ED25519 */
  4365. default:
  4366. break;
  4367. } /* switch (keyOID) */
  4368. break;
  4369. } /* SIG_STATE_CHECK */
  4370. } /* switch (sigCtx->state) */
  4371. exit_cs:
  4372. WOLFSSL_LEAVE("ConfirmSignature", ret);
  4373. if (ret != WC_PENDING_E) {
  4374. FreeSignatureCtx(sigCtx);
  4375. }
  4376. return ret;
  4377. }
  4378. #ifndef IGNORE_NAME_CONSTRAINTS
  4379. static int MatchBaseName(int type, const char* name, int nameSz,
  4380. const char* base, int baseSz)
  4381. {
  4382. if (base == NULL || baseSz <= 0 || name == NULL || nameSz <= 0 ||
  4383. name[0] == '.' || nameSz < baseSz ||
  4384. (type != ASN_RFC822_TYPE && type != ASN_DNS_TYPE))
  4385. return 0;
  4386. /* If an email type, handle special cases where the base is only
  4387. * a domain, or is an email address itself. */
  4388. if (type == ASN_RFC822_TYPE) {
  4389. const char* p = NULL;
  4390. int count = 0;
  4391. if (base[0] != '.') {
  4392. p = base;
  4393. count = 0;
  4394. /* find the '@' in the base */
  4395. while (*p != '@' && count < baseSz) {
  4396. count++;
  4397. p++;
  4398. }
  4399. /* No '@' in base, reset p to NULL */
  4400. if (count >= baseSz)
  4401. p = NULL;
  4402. }
  4403. if (p == NULL) {
  4404. /* Base isn't an email address, it is a domain name,
  4405. * wind the name forward one character past its '@'. */
  4406. p = name;
  4407. count = 0;
  4408. while (*p != '@' && count < baseSz) {
  4409. count++;
  4410. p++;
  4411. }
  4412. if (count < baseSz && *p == '@') {
  4413. name = p + 1;
  4414. nameSz -= count + 1;
  4415. }
  4416. }
  4417. }
  4418. if ((type == ASN_DNS_TYPE || type == ASN_RFC822_TYPE) && base[0] == '.') {
  4419. int szAdjust = nameSz - baseSz;
  4420. name += szAdjust;
  4421. nameSz -= szAdjust;
  4422. }
  4423. while (nameSz > 0) {
  4424. if (XTOLOWER((unsigned char)*name++) !=
  4425. XTOLOWER((unsigned char)*base++))
  4426. return 0;
  4427. nameSz--;
  4428. }
  4429. return 1;
  4430. }
  4431. static int ConfirmNameConstraints(Signer* signer, DecodedCert* cert)
  4432. {
  4433. if (signer == NULL || cert == NULL)
  4434. return 0;
  4435. /* Check against the excluded list */
  4436. if (signer->excludedNames) {
  4437. Base_entry* base = signer->excludedNames;
  4438. while (base != NULL) {
  4439. switch (base->type) {
  4440. case ASN_DNS_TYPE:
  4441. {
  4442. DNS_entry* name = cert->altNames;
  4443. while (name != NULL) {
  4444. if (MatchBaseName(ASN_DNS_TYPE,
  4445. name->name, (int)XSTRLEN(name->name),
  4446. base->name, base->nameSz)) {
  4447. return 0;
  4448. }
  4449. name = name->next;
  4450. }
  4451. break;
  4452. }
  4453. case ASN_RFC822_TYPE:
  4454. {
  4455. DNS_entry* name = cert->altEmailNames;
  4456. while (name != NULL) {
  4457. if (MatchBaseName(ASN_RFC822_TYPE,
  4458. name->name, (int)XSTRLEN(name->name),
  4459. base->name, base->nameSz)) {
  4460. return 0;
  4461. }
  4462. name = name->next;
  4463. }
  4464. break;
  4465. }
  4466. case ASN_DIR_TYPE:
  4467. {
  4468. /* allow permitted dirName smaller than actual subject */
  4469. if (cert->subjectRawLen >= base->nameSz &&
  4470. XMEMCMP(cert->subjectRaw, base->name,
  4471. base->nameSz) == 0) {
  4472. return 0;
  4473. }
  4474. break;
  4475. }
  4476. }; /* switch */
  4477. base = base->next;
  4478. }
  4479. }
  4480. /* Check against the permitted list */
  4481. if (signer->permittedNames != NULL) {
  4482. int needDns = 0;
  4483. int matchDns = 0;
  4484. int needEmail = 0;
  4485. int matchEmail = 0;
  4486. int needDir = 0;
  4487. int matchDir = 0;
  4488. Base_entry* base = signer->permittedNames;
  4489. while (base != NULL) {
  4490. switch (base->type) {
  4491. case ASN_DNS_TYPE:
  4492. {
  4493. DNS_entry* name = cert->altNames;
  4494. if (name != NULL)
  4495. needDns = 1;
  4496. while (name != NULL) {
  4497. matchDns = MatchBaseName(ASN_DNS_TYPE,
  4498. name->name, (int)XSTRLEN(name->name),
  4499. base->name, base->nameSz);
  4500. name = name->next;
  4501. }
  4502. break;
  4503. }
  4504. case ASN_RFC822_TYPE:
  4505. {
  4506. DNS_entry* name = cert->altEmailNames;
  4507. if (name != NULL)
  4508. needEmail = 1;
  4509. while (name != NULL) {
  4510. matchEmail = MatchBaseName(ASN_DNS_TYPE,
  4511. name->name, (int)XSTRLEN(name->name),
  4512. base->name, base->nameSz);
  4513. name = name->next;
  4514. }
  4515. break;
  4516. }
  4517. case ASN_DIR_TYPE:
  4518. {
  4519. /* allow permitted dirName smaller than actual subject */
  4520. needDir = 1;
  4521. if (cert->subjectRaw != NULL &&
  4522. cert->subjectRawLen >= base->nameSz &&
  4523. XMEMCMP(cert->subjectRaw, base->name,
  4524. base->nameSz) == 0) {
  4525. matchDir = 1;
  4526. }
  4527. break;
  4528. }
  4529. } /* switch */
  4530. base = base->next;
  4531. }
  4532. if ((needDns && !matchDns) ||
  4533. (needEmail && !matchEmail) ||
  4534. (needDir && !matchDir)) {
  4535. return 0;
  4536. }
  4537. }
  4538. return 1;
  4539. }
  4540. #endif /* IGNORE_NAME_CONSTRAINTS */
  4541. static int DecodeAltNames(byte* input, int sz, DecodedCert* cert)
  4542. {
  4543. word32 idx = 0;
  4544. int length = 0;
  4545. WOLFSSL_ENTER("DecodeAltNames");
  4546. if (GetSequence(input, &idx, &length, sz) < 0) {
  4547. WOLFSSL_MSG("\tBad Sequence");
  4548. return ASN_PARSE_E;
  4549. }
  4550. cert->weOwnAltNames = 1;
  4551. while (length > 0) {
  4552. byte b = input[idx++];
  4553. length--;
  4554. /* Save DNS Type names in the altNames list. */
  4555. /* Save Other Type names in the cert's OidMap */
  4556. if (b == (ASN_CONTEXT_SPECIFIC | ASN_DNS_TYPE)) {
  4557. DNS_entry* dnsEntry;
  4558. int strLen;
  4559. word32 lenStartIdx = idx;
  4560. if (GetLength(input, &idx, &strLen, sz) < 0) {
  4561. WOLFSSL_MSG("\tfail: str length");
  4562. return ASN_PARSE_E;
  4563. }
  4564. length -= (idx - lenStartIdx);
  4565. dnsEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  4566. DYNAMIC_TYPE_ALTNAME);
  4567. if (dnsEntry == NULL) {
  4568. WOLFSSL_MSG("\tOut of Memory");
  4569. return MEMORY_E;
  4570. }
  4571. dnsEntry->type = ASN_DNS_TYPE;
  4572. dnsEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  4573. DYNAMIC_TYPE_ALTNAME);
  4574. if (dnsEntry->name == NULL) {
  4575. WOLFSSL_MSG("\tOut of Memory");
  4576. XFREE(dnsEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  4577. return MEMORY_E;
  4578. }
  4579. XMEMCPY(dnsEntry->name, &input[idx], strLen);
  4580. dnsEntry->name[strLen] = '\0';
  4581. dnsEntry->next = cert->altNames;
  4582. cert->altNames = dnsEntry;
  4583. length -= strLen;
  4584. idx += strLen;
  4585. }
  4586. #ifndef IGNORE_NAME_CONSTRAINTS
  4587. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_RFC822_TYPE)) {
  4588. DNS_entry* emailEntry;
  4589. int strLen;
  4590. word32 lenStartIdx = idx;
  4591. if (GetLength(input, &idx, &strLen, sz) < 0) {
  4592. WOLFSSL_MSG("\tfail: str length");
  4593. return ASN_PARSE_E;
  4594. }
  4595. length -= (idx - lenStartIdx);
  4596. emailEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  4597. DYNAMIC_TYPE_ALTNAME);
  4598. if (emailEntry == NULL) {
  4599. WOLFSSL_MSG("\tOut of Memory");
  4600. return MEMORY_E;
  4601. }
  4602. emailEntry->type = ASN_RFC822_TYPE;
  4603. emailEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  4604. DYNAMIC_TYPE_ALTNAME);
  4605. if (emailEntry->name == NULL) {
  4606. WOLFSSL_MSG("\tOut of Memory");
  4607. XFREE(emailEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  4608. return MEMORY_E;
  4609. }
  4610. XMEMCPY(emailEntry->name, &input[idx], strLen);
  4611. emailEntry->name[strLen] = '\0';
  4612. emailEntry->next = cert->altEmailNames;
  4613. cert->altEmailNames = emailEntry;
  4614. length -= strLen;
  4615. idx += strLen;
  4616. }
  4617. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_URI_TYPE)) {
  4618. DNS_entry* uriEntry;
  4619. int strLen;
  4620. word32 lenStartIdx = idx;
  4621. WOLFSSL_MSG("\tPutting URI into list but not using");
  4622. if (GetLength(input, &idx, &strLen, sz) < 0) {
  4623. WOLFSSL_MSG("\tfail: str length");
  4624. return ASN_PARSE_E;
  4625. }
  4626. length -= (idx - lenStartIdx);
  4627. uriEntry = (DNS_entry*)XMALLOC(sizeof(DNS_entry), cert->heap,
  4628. DYNAMIC_TYPE_ALTNAME);
  4629. if (uriEntry == NULL) {
  4630. WOLFSSL_MSG("\tOut of Memory");
  4631. return MEMORY_E;
  4632. }
  4633. uriEntry->type = ASN_URI_TYPE;
  4634. uriEntry->name = (char*)XMALLOC(strLen + 1, cert->heap,
  4635. DYNAMIC_TYPE_ALTNAME);
  4636. if (uriEntry->name == NULL) {
  4637. WOLFSSL_MSG("\tOut of Memory");
  4638. XFREE(uriEntry, cert->heap, DYNAMIC_TYPE_ALTNAME);
  4639. return MEMORY_E;
  4640. }
  4641. XMEMCPY(uriEntry->name, &input[idx], strLen);
  4642. uriEntry->name[strLen] = '\0';
  4643. uriEntry->next = cert->altNames;
  4644. cert->altNames = uriEntry;
  4645. length -= strLen;
  4646. idx += strLen;
  4647. }
  4648. #endif /* IGNORE_NAME_CONSTRAINTS */
  4649. #ifdef WOLFSSL_SEP
  4650. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | ASN_OTHER_TYPE))
  4651. {
  4652. int strLen;
  4653. word32 lenStartIdx = idx;
  4654. word32 oid = 0;
  4655. int ret;
  4656. if (GetLength(input, &idx, &strLen, sz) < 0) {
  4657. WOLFSSL_MSG("\tfail: other name length");
  4658. return ASN_PARSE_E;
  4659. }
  4660. /* Consume the rest of this sequence. */
  4661. length -= (strLen + idx - lenStartIdx);
  4662. if (GetObjectId(input, &idx, &oid, oidCertAltNameType, sz) < 0) {
  4663. WOLFSSL_MSG("\tbad OID");
  4664. return ASN_PARSE_E;
  4665. }
  4666. if (oid != HW_NAME_OID) {
  4667. WOLFSSL_MSG("\tincorrect OID");
  4668. return ASN_PARSE_E;
  4669. }
  4670. if (input[idx++] != (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED)) {
  4671. WOLFSSL_MSG("\twrong type");
  4672. return ASN_PARSE_E;
  4673. }
  4674. if (GetLength(input, &idx, &strLen, sz) < 0) {
  4675. WOLFSSL_MSG("\tfail: str len");
  4676. return ASN_PARSE_E;
  4677. }
  4678. if (GetSequence(input, &idx, &strLen, sz) < 0) {
  4679. WOLFSSL_MSG("\tBad Sequence");
  4680. return ASN_PARSE_E;
  4681. }
  4682. ret = GetASNObjectId(input, &idx, &strLen, sz);
  4683. if (ret != 0) {
  4684. WOLFSSL_MSG("\tbad OID");
  4685. return ret;
  4686. }
  4687. cert->hwType = (byte*)XMALLOC(strLen, cert->heap,
  4688. DYNAMIC_TYPE_X509_EXT);
  4689. if (cert->hwType == NULL) {
  4690. WOLFSSL_MSG("\tOut of Memory");
  4691. return MEMORY_E;
  4692. }
  4693. XMEMCPY(cert->hwType, &input[idx], strLen);
  4694. cert->hwTypeSz = strLen;
  4695. idx += strLen;
  4696. ret = GetOctetString(input, &idx, &strLen, sz);
  4697. if (ret < 0)
  4698. return ret;
  4699. cert->hwSerialNum = (byte*)XMALLOC(strLen + 1, cert->heap,
  4700. DYNAMIC_TYPE_X509_EXT);
  4701. if (cert->hwSerialNum == NULL) {
  4702. WOLFSSL_MSG("\tOut of Memory");
  4703. return MEMORY_E;
  4704. }
  4705. XMEMCPY(cert->hwSerialNum, &input[idx], strLen);
  4706. cert->hwSerialNum[strLen] = '\0';
  4707. cert->hwSerialNumSz = strLen;
  4708. idx += strLen;
  4709. }
  4710. #endif /* WOLFSSL_SEP */
  4711. else {
  4712. int strLen;
  4713. word32 lenStartIdx = idx;
  4714. WOLFSSL_MSG("\tUnsupported name type, skipping");
  4715. if (GetLength(input, &idx, &strLen, sz) < 0) {
  4716. WOLFSSL_MSG("\tfail: unsupported name length");
  4717. return ASN_PARSE_E;
  4718. }
  4719. length -= (strLen + idx - lenStartIdx);
  4720. idx += strLen;
  4721. }
  4722. }
  4723. return 0;
  4724. }
  4725. static int DecodeBasicCaConstraint(byte* input, int sz, DecodedCert* cert)
  4726. {
  4727. word32 idx = 0;
  4728. int length = 0;
  4729. int ret;
  4730. WOLFSSL_ENTER("DecodeBasicCaConstraint");
  4731. if (GetSequence(input, &idx, &length, sz) < 0) {
  4732. WOLFSSL_MSG("\tfail: bad SEQUENCE");
  4733. return ASN_PARSE_E;
  4734. }
  4735. if (length == 0)
  4736. return 0;
  4737. /* If the basic ca constraint is false, this extension may be named, but
  4738. * left empty. So, if the length is 0, just return. */
  4739. ret = GetBoolean(input, &idx, sz);
  4740. if (ret < 0) {
  4741. WOLFSSL_MSG("\tfail: constraint not valid BOOLEAN");
  4742. return ret;
  4743. }
  4744. cert->isCA = (byte)ret;
  4745. /* If there isn't any more data, return. */
  4746. if (idx >= (word32)sz)
  4747. return 0;
  4748. ret = GetInteger7Bit(input, &idx, sz);
  4749. if (ret < 0)
  4750. return ret;
  4751. cert->pathLength = (byte)ret;
  4752. cert->pathLengthSet = 1;
  4753. return 0;
  4754. }
  4755. #define CRLDP_FULL_NAME 0
  4756. /* From RFC3280 SS4.2.1.14, Distribution Point Name*/
  4757. #define GENERALNAME_URI 6
  4758. /* From RFC3280 SS4.2.1.7, GeneralName */
  4759. static int DecodeCrlDist(byte* input, int sz, DecodedCert* cert)
  4760. {
  4761. word32 idx = 0;
  4762. int length = 0;
  4763. WOLFSSL_ENTER("DecodeCrlDist");
  4764. /* Unwrap the list of Distribution Points*/
  4765. if (GetSequence(input, &idx, &length, sz) < 0)
  4766. return ASN_PARSE_E;
  4767. /* Unwrap a single Distribution Point */
  4768. if (GetSequence(input, &idx, &length, sz) < 0)
  4769. return ASN_PARSE_E;
  4770. /* The Distribution Point has three explicit optional members
  4771. * First check for a DistributionPointName
  4772. */
  4773. if (input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0))
  4774. {
  4775. idx++;
  4776. if (GetLength(input, &idx, &length, sz) < 0)
  4777. return ASN_PARSE_E;
  4778. if (input[idx] ==
  4779. (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CRLDP_FULL_NAME))
  4780. {
  4781. idx++;
  4782. if (GetLength(input, &idx, &length, sz) < 0)
  4783. return ASN_PARSE_E;
  4784. if (input[idx] == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI))
  4785. {
  4786. idx++;
  4787. if (GetLength(input, &idx, &length, sz) < 0)
  4788. return ASN_PARSE_E;
  4789. cert->extCrlInfoSz = length;
  4790. cert->extCrlInfo = input + idx;
  4791. idx += length;
  4792. }
  4793. else
  4794. /* This isn't a URI, skip it. */
  4795. idx += length;
  4796. }
  4797. else {
  4798. /* This isn't a FULLNAME, skip it. */
  4799. idx += length;
  4800. }
  4801. }
  4802. /* Check for reasonFlags */
  4803. if (idx < (word32)sz &&
  4804. input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  4805. {
  4806. idx++;
  4807. if (GetLength(input, &idx, &length, sz) < 0)
  4808. return ASN_PARSE_E;
  4809. idx += length;
  4810. }
  4811. /* Check for cRLIssuer */
  4812. if (idx < (word32)sz &&
  4813. input[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 2))
  4814. {
  4815. idx++;
  4816. if (GetLength(input, &idx, &length, sz) < 0)
  4817. return ASN_PARSE_E;
  4818. idx += length;
  4819. }
  4820. if (idx < (word32)sz)
  4821. {
  4822. WOLFSSL_MSG("\tThere are more CRL Distribution Point records, "
  4823. "but we only use the first one.");
  4824. }
  4825. return 0;
  4826. }
  4827. static int DecodeAuthInfo(byte* input, int sz, DecodedCert* cert)
  4828. /*
  4829. * Read the first of the Authority Information Access records. If there are
  4830. * any issues, return without saving the record.
  4831. */
  4832. {
  4833. word32 idx = 0;
  4834. int length = 0;
  4835. byte b;
  4836. word32 oid;
  4837. WOLFSSL_ENTER("DecodeAuthInfo");
  4838. /* Unwrap the list of AIAs */
  4839. if (GetSequence(input, &idx, &length, sz) < 0)
  4840. return ASN_PARSE_E;
  4841. while (idx < (word32)sz) {
  4842. /* Unwrap a single AIA */
  4843. if (GetSequence(input, &idx, &length, sz) < 0)
  4844. return ASN_PARSE_E;
  4845. oid = 0;
  4846. if (GetObjectId(input, &idx, &oid, oidCertAuthInfoType, sz) < 0)
  4847. return ASN_PARSE_E;
  4848. /* Only supporting URIs right now. */
  4849. b = input[idx++];
  4850. if (GetLength(input, &idx, &length, sz) < 0)
  4851. return ASN_PARSE_E;
  4852. if (b == (ASN_CONTEXT_SPECIFIC | GENERALNAME_URI) &&
  4853. oid == AIA_OCSP_OID)
  4854. {
  4855. cert->extAuthInfoSz = length;
  4856. cert->extAuthInfo = input + idx;
  4857. break;
  4858. }
  4859. idx += length;
  4860. }
  4861. return 0;
  4862. }
  4863. static int DecodeAuthKeyId(byte* input, int sz, DecodedCert* cert)
  4864. {
  4865. word32 idx = 0;
  4866. int length = 0, ret = 0;
  4867. WOLFSSL_ENTER("DecodeAuthKeyId");
  4868. if (GetSequence(input, &idx, &length, sz) < 0) {
  4869. WOLFSSL_MSG("\tfail: should be a SEQUENCE\n");
  4870. return ASN_PARSE_E;
  4871. }
  4872. if (input[idx++] != (ASN_CONTEXT_SPECIFIC | 0)) {
  4873. WOLFSSL_MSG("\tinfo: OPTIONAL item 0, not available\n");
  4874. return 0;
  4875. }
  4876. if (GetLength(input, &idx, &length, sz) <= 0) {
  4877. WOLFSSL_MSG("\tfail: extension data length");
  4878. return ASN_PARSE_E;
  4879. }
  4880. #ifdef OPENSSL_EXTRA
  4881. cert->extAuthKeyIdSrc = &input[idx];
  4882. cert->extAuthKeyIdSz = length;
  4883. #endif /* OPENSSL_EXTRA */
  4884. if (length == KEYID_SIZE) {
  4885. XMEMCPY(cert->extAuthKeyId, input + idx, length);
  4886. }
  4887. else {
  4888. #ifdef NO_SHA
  4889. ret = wc_Sha256Hash(input + idx, length, cert->extAuthKeyId);
  4890. #else
  4891. ret = wc_ShaHash(input + idx, length, cert->extAuthKeyId);
  4892. #endif
  4893. }
  4894. return ret;
  4895. }
  4896. static int DecodeSubjKeyId(byte* input, int sz, DecodedCert* cert)
  4897. {
  4898. word32 idx = 0;
  4899. int length = 0, ret = 0;
  4900. WOLFSSL_ENTER("DecodeSubjKeyId");
  4901. if (sz <= 0)
  4902. return ASN_PARSE_E;
  4903. ret = GetOctetString(input, &idx, &length, sz);
  4904. if (ret < 0)
  4905. return ret;
  4906. #ifdef OPENSSL_EXTRA
  4907. cert->extSubjKeyIdSrc = &input[idx];
  4908. cert->extSubjKeyIdSz = length;
  4909. #endif /* OPENSSL_EXTRA */
  4910. if (length == SIGNER_DIGEST_SIZE) {
  4911. XMEMCPY(cert->extSubjKeyId, input + idx, length);
  4912. }
  4913. else {
  4914. #ifdef NO_SHA
  4915. ret = wc_Sha256Hash(input + idx, length, cert->extSubjKeyId);
  4916. #else
  4917. ret = wc_ShaHash(input + idx, length, cert->extSubjKeyId);
  4918. #endif
  4919. }
  4920. return ret;
  4921. }
  4922. static int DecodeKeyUsage(byte* input, int sz, DecodedCert* cert)
  4923. {
  4924. word32 idx = 0;
  4925. int length;
  4926. int ret;
  4927. WOLFSSL_ENTER("DecodeKeyUsage");
  4928. ret = CheckBitString(input, &idx, &length, sz, 0, NULL);
  4929. if (ret != 0)
  4930. return ret;
  4931. cert->extKeyUsage = (word16)(input[idx]);
  4932. if (length == 2)
  4933. cert->extKeyUsage |= (word16)(input[idx+1] << 8);
  4934. return 0;
  4935. }
  4936. static int DecodeExtKeyUsage(byte* input, int sz, DecodedCert* cert)
  4937. {
  4938. word32 idx = 0, oid;
  4939. int length;
  4940. WOLFSSL_ENTER("DecodeExtKeyUsage");
  4941. if (GetSequence(input, &idx, &length, sz) < 0) {
  4942. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  4943. return ASN_PARSE_E;
  4944. }
  4945. #ifdef OPENSSL_EXTRA
  4946. cert->extExtKeyUsageSrc = input + idx;
  4947. cert->extExtKeyUsageSz = length;
  4948. #endif
  4949. while (idx < (word32)sz) {
  4950. if (GetObjectId(input, &idx, &oid, oidCertKeyUseType, sz) < 0)
  4951. return ASN_PARSE_E;
  4952. switch (oid) {
  4953. case EKU_ANY_OID:
  4954. cert->extExtKeyUsage |= EXTKEYUSE_ANY;
  4955. break;
  4956. case EKU_SERVER_AUTH_OID:
  4957. cert->extExtKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  4958. break;
  4959. case EKU_CLIENT_AUTH_OID:
  4960. cert->extExtKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  4961. break;
  4962. case EKU_CODESIGNING_OID:
  4963. cert->extExtKeyUsage |= EXTKEYUSE_CODESIGN;
  4964. break;
  4965. case EKU_EMAILPROTECT_OID:
  4966. cert->extExtKeyUsage |= EXTKEYUSE_EMAILPROT;
  4967. break;
  4968. case EKU_TIMESTAMP_OID:
  4969. cert->extExtKeyUsage |= EXTKEYUSE_TIMESTAMP;
  4970. break;
  4971. case EKU_OCSP_SIGN_OID:
  4972. cert->extExtKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  4973. break;
  4974. }
  4975. #ifdef OPENSSL_EXTRA
  4976. cert->extExtKeyUsageCount++;
  4977. #endif
  4978. }
  4979. return 0;
  4980. }
  4981. #ifndef IGNORE_NAME_CONSTRAINTS
  4982. #define ASN_TYPE_MASK 0xF
  4983. static int DecodeSubtree(byte* input, int sz, Base_entry** head, void* heap)
  4984. {
  4985. word32 idx = 0;
  4986. (void)heap;
  4987. while (idx < (word32)sz) {
  4988. int seqLength, strLength;
  4989. word32 nameIdx;
  4990. byte b, bType;
  4991. if (GetSequence(input, &idx, &seqLength, sz) < 0) {
  4992. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  4993. return ASN_PARSE_E;
  4994. }
  4995. nameIdx = idx;
  4996. b = input[nameIdx++];
  4997. if (GetLength(input, &nameIdx, &strLength, sz) <= 0) {
  4998. WOLFSSL_MSG("\tinvalid length");
  4999. return ASN_PARSE_E;
  5000. }
  5001. /* Get type, LSB 4-bits */
  5002. bType = (b & ASN_TYPE_MASK);
  5003. if (bType == ASN_DNS_TYPE || bType == ASN_RFC822_TYPE ||
  5004. bType == ASN_DIR_TYPE) {
  5005. Base_entry* entry;
  5006. /* if constructed has leading sequence */
  5007. if (b & ASN_CONSTRUCTED) {
  5008. if (GetSequence(input, &nameIdx, &strLength, sz) < 0) {
  5009. WOLFSSL_MSG("\tfail: constructed be a SEQUENCE");
  5010. return ASN_PARSE_E;
  5011. }
  5012. }
  5013. entry = (Base_entry*)XMALLOC(sizeof(Base_entry), heap,
  5014. DYNAMIC_TYPE_ALTNAME);
  5015. if (entry == NULL) {
  5016. WOLFSSL_MSG("allocate error");
  5017. return MEMORY_E;
  5018. }
  5019. entry->name = (char*)XMALLOC(strLength, heap, DYNAMIC_TYPE_ALTNAME);
  5020. if (entry->name == NULL) {
  5021. WOLFSSL_MSG("allocate error");
  5022. XFREE(entry, heap, DYNAMIC_TYPE_ALTNAME);
  5023. return MEMORY_E;
  5024. }
  5025. XMEMCPY(entry->name, &input[nameIdx], strLength);
  5026. entry->nameSz = strLength;
  5027. entry->type = bType;
  5028. entry->next = *head;
  5029. *head = entry;
  5030. }
  5031. idx += seqLength;
  5032. }
  5033. return 0;
  5034. }
  5035. static int DecodeNameConstraints(byte* input, int sz, DecodedCert* cert)
  5036. {
  5037. word32 idx = 0;
  5038. int length = 0;
  5039. WOLFSSL_ENTER("DecodeNameConstraints");
  5040. if (GetSequence(input, &idx, &length, sz) < 0) {
  5041. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  5042. return ASN_PARSE_E;
  5043. }
  5044. while (idx < (word32)sz) {
  5045. byte b = input[idx++];
  5046. Base_entry** subtree = NULL;
  5047. if (GetLength(input, &idx, &length, sz) <= 0) {
  5048. WOLFSSL_MSG("\tinvalid length");
  5049. return ASN_PARSE_E;
  5050. }
  5051. if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0))
  5052. subtree = &cert->permittedNames;
  5053. else if (b == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1))
  5054. subtree = &cert->excludedNames;
  5055. else {
  5056. WOLFSSL_MSG("\tinvalid subtree");
  5057. return ASN_PARSE_E;
  5058. }
  5059. DecodeSubtree(input + idx, length, subtree, cert->heap);
  5060. idx += length;
  5061. }
  5062. return 0;
  5063. }
  5064. #endif /* IGNORE_NAME_CONSTRAINTS */
  5065. #if (defined(WOLFSSL_CERT_EXT) && !defined(WOLFSSL_SEP)) || defined(OPENSSL_EXTRA)
  5066. static int Word32ToString(char* d, word32 number)
  5067. {
  5068. int i = 0;
  5069. if (d != NULL) {
  5070. word32 order = 1000000000;
  5071. word32 digit;
  5072. if (number == 0) {
  5073. d[i++] = '0';
  5074. }
  5075. else {
  5076. while (order) {
  5077. digit = number / order;
  5078. if (i > 0 || digit != 0) {
  5079. d[i++] = (char)digit + '0';
  5080. }
  5081. if (digit != 0)
  5082. number %= digit * order;
  5083. if (order > 1)
  5084. order /= 10;
  5085. else
  5086. order = 0;
  5087. }
  5088. }
  5089. d[i] = 0;
  5090. }
  5091. return i;
  5092. }
  5093. /* Decode ITU-T X.690 OID format to a string representation
  5094. * return string length */
  5095. int DecodePolicyOID(char *out, word32 outSz, byte *in, word32 inSz)
  5096. {
  5097. word32 val, idx = 0, nb_bytes;
  5098. size_t w_bytes = 0;
  5099. if (out == NULL || in == NULL || outSz < 4 || inSz < 2)
  5100. return BAD_FUNC_ARG;
  5101. /* first two byte must be interpreted as : 40 * int1 + int2 */
  5102. val = (word16)in[idx++];
  5103. w_bytes = Word32ToString(out, val / 40);
  5104. out[w_bytes++] = '.';
  5105. w_bytes += Word32ToString(out+w_bytes, val % 40);
  5106. while (idx < inSz) {
  5107. /* init value */
  5108. val = 0;
  5109. nb_bytes = 0;
  5110. /* check that output size is ok */
  5111. if (w_bytes > (outSz - 3))
  5112. return BUFFER_E;
  5113. /* first bit is used to set if value is coded on 1 or multiple bytes */
  5114. while ((in[idx+nb_bytes] & 0x80))
  5115. nb_bytes++;
  5116. if (!nb_bytes)
  5117. val = (word32)(in[idx++] & 0x7f);
  5118. else {
  5119. word32 base = 1, tmp = nb_bytes;
  5120. while (tmp != 0) {
  5121. val += (word32)(in[idx+tmp] & 0x7f) * base;
  5122. base *= 128;
  5123. tmp--;
  5124. }
  5125. val += (word32)(in[idx++] & 0x7f) * base;
  5126. idx += nb_bytes;
  5127. }
  5128. out[w_bytes++] = '.';
  5129. w_bytes += Word32ToString(out+w_bytes, val);
  5130. }
  5131. return (int)w_bytes;
  5132. }
  5133. #endif /* WOLFSSL_CERT_EXT && !WOLFSSL_SEP */
  5134. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  5135. /* Reference: https://tools.ietf.org/html/rfc5280#section-4.2.1.4 */
  5136. static int DecodeCertPolicy(byte* input, int sz, DecodedCert* cert)
  5137. {
  5138. word32 idx = 0;
  5139. word32 oldIdx;
  5140. int ret;
  5141. int total_length = 0, policy_length = 0, length = 0;
  5142. #if !defined(WOLFSSL_SEP) && defined(WOLFSSL_CERT_EXT) && \
  5143. !defined(WOLFSSL_DUP_CERTPOL)
  5144. int i;
  5145. #endif
  5146. WOLFSSL_ENTER("DecodeCertPolicy");
  5147. if (GetSequence(input, &idx, &total_length, sz) < 0) {
  5148. WOLFSSL_MSG("\tGet CertPolicy total seq failed");
  5149. return ASN_PARSE_E;
  5150. }
  5151. /* Validate total length */
  5152. if (total_length > (sz - (int)idx)) {
  5153. WOLFSSL_MSG("\tCertPolicy length mismatch");
  5154. return ASN_PARSE_E;
  5155. }
  5156. /* Unwrap certificatePolicies */
  5157. do {
  5158. if (GetSequence(input, &idx, &policy_length, sz) < 0) {
  5159. WOLFSSL_MSG("\tGet CertPolicy seq failed");
  5160. return ASN_PARSE_E;
  5161. }
  5162. oldIdx = idx;
  5163. ret = GetASNObjectId(input, &idx, &length, sz);
  5164. if (ret != 0)
  5165. return ret;
  5166. policy_length -= idx - oldIdx;
  5167. if (length > 0) {
  5168. /* Verify length won't overrun buffer */
  5169. if (length > (sz - (int)idx)) {
  5170. WOLFSSL_MSG("\tCertPolicy length exceeds input buffer");
  5171. return ASN_PARSE_E;
  5172. }
  5173. #if defined(WOLFSSL_SEP)
  5174. cert->deviceType = (byte*)XMALLOC(length, cert->heap,
  5175. DYNAMIC_TYPE_X509_EXT);
  5176. if (cert->deviceType == NULL) {
  5177. WOLFSSL_MSG("\tCouldn't alloc memory for deviceType");
  5178. return MEMORY_E;
  5179. }
  5180. cert->deviceTypeSz = length;
  5181. XMEMCPY(cert->deviceType, input + idx, length);
  5182. break;
  5183. #elif defined(WOLFSSL_CERT_EXT)
  5184. /* decode cert policy */
  5185. if (DecodePolicyOID(cert->extCertPolicies[cert->extCertPoliciesNb], MAX_CERTPOL_SZ,
  5186. input + idx, length) <= 0) {
  5187. WOLFSSL_MSG("\tCouldn't decode CertPolicy");
  5188. return ASN_PARSE_E;
  5189. }
  5190. #ifndef WOLFSSL_DUP_CERTPOL
  5191. /* From RFC 5280 section 4.2.1.3 "A certificate policy OID MUST
  5192. * NOT appear more than once in a certificate policies
  5193. * extension". This is a sanity check for duplicates.
  5194. * extCertPolicies should only have OID values, additional
  5195. * qualifiers need to be stored in a seperate array. */
  5196. for (i = 0; i < cert->extCertPoliciesNb; i++) {
  5197. if (XMEMCMP(cert->extCertPolicies[i],
  5198. cert->extCertPolicies[cert->extCertPoliciesNb],
  5199. MAX_CERTPOL_SZ) == 0) {
  5200. WOLFSSL_MSG("Duplicate policy OIDs not allowed");
  5201. WOLFSSL_MSG("Use WOLFSSL_DUP_CERTPOL if wanted");
  5202. return CERTPOLICIES_E;
  5203. }
  5204. }
  5205. #endif /* !WOLFSSL_DUP_CERTPOL */
  5206. cert->extCertPoliciesNb++;
  5207. #else
  5208. WOLFSSL_LEAVE("DecodeCertPolicy : unsupported mode", 0);
  5209. return 0;
  5210. #endif
  5211. }
  5212. idx += policy_length;
  5213. } while((int)idx < total_length
  5214. #if defined(WOLFSSL_CERT_EXT)
  5215. && cert->extCertPoliciesNb < MAX_CERTPOL_NB
  5216. #endif
  5217. );
  5218. WOLFSSL_LEAVE("DecodeCertPolicy", 0);
  5219. return 0;
  5220. }
  5221. #endif /* WOLFSSL_SEP */
  5222. static int DecodeCertExtensions(DecodedCert* cert)
  5223. /*
  5224. * Processing the Certificate Extensions. This does not modify the current
  5225. * index. It is works starting with the recorded extensions pointer.
  5226. */
  5227. {
  5228. int ret;
  5229. word32 idx = 0;
  5230. int sz = cert->extensionsSz;
  5231. byte* input = cert->extensions;
  5232. int length;
  5233. word32 oid;
  5234. byte critical = 0;
  5235. byte criticalFail = 0;
  5236. WOLFSSL_ENTER("DecodeCertExtensions");
  5237. if (input == NULL || sz == 0)
  5238. return BAD_FUNC_ARG;
  5239. if (input[idx++] != ASN_EXTENSIONS) {
  5240. WOLFSSL_MSG("\tfail: should be an EXTENSIONS");
  5241. return ASN_PARSE_E;
  5242. }
  5243. if (GetLength(input, &idx, &length, sz) < 0) {
  5244. WOLFSSL_MSG("\tfail: invalid length");
  5245. return ASN_PARSE_E;
  5246. }
  5247. if (GetSequence(input, &idx, &length, sz) < 0) {
  5248. WOLFSSL_MSG("\tfail: should be a SEQUENCE (1)");
  5249. return ASN_PARSE_E;
  5250. }
  5251. while (idx < (word32)sz) {
  5252. if (GetSequence(input, &idx, &length, sz) < 0) {
  5253. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  5254. return ASN_PARSE_E;
  5255. }
  5256. oid = 0;
  5257. if ((ret = GetObjectId(input, &idx, &oid, oidCertExtType, sz)) < 0) {
  5258. WOLFSSL_MSG("\tfail: OBJECT ID");
  5259. return ret;
  5260. }
  5261. /* check for critical flag */
  5262. critical = 0;
  5263. if (input[idx] == ASN_BOOLEAN) {
  5264. ret = GetBoolean(input, &idx, sz);
  5265. if (ret < 0) {
  5266. WOLFSSL_MSG("\tfail: critical boolean");
  5267. return ret;
  5268. }
  5269. critical = (byte)ret;
  5270. }
  5271. /* process the extension based on the OID */
  5272. ret = GetOctetString(input, &idx, &length, sz);
  5273. if (ret < 0) {
  5274. WOLFSSL_MSG("\tfail: bad OCTET STRING");
  5275. return ret;
  5276. }
  5277. switch (oid) {
  5278. case BASIC_CA_OID:
  5279. #ifdef OPENSSL_EXTRA
  5280. cert->extBasicConstSet = 1;
  5281. cert->extBasicConstCrit = critical;
  5282. #endif
  5283. if (DecodeBasicCaConstraint(&input[idx], length, cert) < 0)
  5284. return ASN_PARSE_E;
  5285. break;
  5286. case CRL_DIST_OID:
  5287. #ifdef OPENSSL_EXTRA
  5288. cert->extCRLdistSet = 1;
  5289. cert->extCRLdistCrit = critical;
  5290. #endif
  5291. if (DecodeCrlDist(&input[idx], length, cert) < 0)
  5292. return ASN_PARSE_E;
  5293. break;
  5294. case AUTH_INFO_OID:
  5295. #ifdef OPENSSL_EXTRA
  5296. cert->extAuthInfoSet = 1;
  5297. cert->extAuthInfoCrit = critical;
  5298. #endif
  5299. if (DecodeAuthInfo(&input[idx], length, cert) < 0)
  5300. return ASN_PARSE_E;
  5301. break;
  5302. case ALT_NAMES_OID:
  5303. #ifdef OPENSSL_EXTRA
  5304. cert->extSubjAltNameSet = 1;
  5305. cert->extSubjAltNameCrit = critical;
  5306. #endif
  5307. if (DecodeAltNames(&input[idx], length, cert) < 0)
  5308. return ASN_PARSE_E;
  5309. break;
  5310. case AUTH_KEY_OID:
  5311. cert->extAuthKeyIdSet = 1;
  5312. #ifdef OPENSSL_EXTRA
  5313. cert->extAuthKeyIdCrit = critical;
  5314. #endif
  5315. if (DecodeAuthKeyId(&input[idx], length, cert) < 0)
  5316. return ASN_PARSE_E;
  5317. break;
  5318. case SUBJ_KEY_OID:
  5319. cert->extSubjKeyIdSet = 1;
  5320. #ifdef OPENSSL_EXTRA
  5321. cert->extSubjKeyIdCrit = critical;
  5322. #endif
  5323. #ifndef WOLFSSL_ALLOW_CRIT_SKID
  5324. /* This check is added due to RFC 5280 section 4.2.1.2
  5325. * stating that conforming CA's must mark this extension
  5326. * as non-critical. When parsing extensions check that
  5327. * certificate was made in compliance with this. */
  5328. if (critical) {
  5329. WOLFSSL_MSG("Critical Subject Key ID is not allowed");
  5330. WOLFSSL_MSG("Use macro WOLFSSL_ALLOW_CRIT_SKID if wanted");
  5331. return ASN_CRIT_EXT_E;
  5332. }
  5333. #endif
  5334. if (DecodeSubjKeyId(&input[idx], length, cert) < 0)
  5335. return ASN_PARSE_E;
  5336. break;
  5337. case CERT_POLICY_OID:
  5338. #ifdef WOLFSSL_SEP
  5339. #ifdef OPENSSL_EXTRA
  5340. cert->extCertPolicySet = 1;
  5341. cert->extCertPolicyCrit = critical;
  5342. #endif
  5343. #endif
  5344. #if defined(WOLFSSL_SEP) || defined(WOLFSSL_CERT_EXT)
  5345. if (DecodeCertPolicy(&input[idx], length, cert) < 0) {
  5346. return ASN_PARSE_E;
  5347. }
  5348. #else
  5349. WOLFSSL_MSG("Certificate Policy extension not supported yet.");
  5350. #endif
  5351. break;
  5352. case KEY_USAGE_OID:
  5353. cert->extKeyUsageSet = 1;
  5354. #ifdef OPENSSL_EXTRA
  5355. cert->extKeyUsageCrit = critical;
  5356. #endif
  5357. if (DecodeKeyUsage(&input[idx], length, cert) < 0)
  5358. return ASN_PARSE_E;
  5359. break;
  5360. case EXT_KEY_USAGE_OID:
  5361. cert->extExtKeyUsageSet = 1;
  5362. #ifdef OPENSSL_EXTRA
  5363. cert->extExtKeyUsageCrit = critical;
  5364. #endif
  5365. if (DecodeExtKeyUsage(&input[idx], length, cert) < 0)
  5366. return ASN_PARSE_E;
  5367. break;
  5368. #ifndef IGNORE_NAME_CONSTRAINTS
  5369. case NAME_CONS_OID:
  5370. cert->extNameConstraintSet = 1;
  5371. #ifdef OPENSSL_EXTRA
  5372. cert->extNameConstraintCrit = critical;
  5373. #endif
  5374. if (DecodeNameConstraints(&input[idx], length, cert) < 0)
  5375. return ASN_PARSE_E;
  5376. break;
  5377. #endif /* IGNORE_NAME_CONSTRAINTS */
  5378. case INHIBIT_ANY_OID:
  5379. WOLFSSL_MSG("Inhibit anyPolicy extension not supported yet.");
  5380. break;
  5381. default:
  5382. /* While it is a failure to not support critical extensions,
  5383. * still parse the certificate ignoring the unsupported
  5384. * extension to allow caller to accept it with the verify
  5385. * callback. */
  5386. if (critical)
  5387. criticalFail = 1;
  5388. break;
  5389. }
  5390. idx += length;
  5391. }
  5392. return criticalFail ? ASN_CRIT_EXT_E : 0;
  5393. }
  5394. int ParseCert(DecodedCert* cert, int type, int verify, void* cm)
  5395. {
  5396. int ret;
  5397. char* ptr;
  5398. ret = ParseCertRelative(cert, type, verify, cm);
  5399. if (ret < 0)
  5400. return ret;
  5401. if (cert->subjectCNLen > 0) {
  5402. ptr = (char*) XMALLOC(cert->subjectCNLen + 1, cert->heap,
  5403. DYNAMIC_TYPE_SUBJECT_CN);
  5404. if (ptr == NULL)
  5405. return MEMORY_E;
  5406. XMEMCPY(ptr, cert->subjectCN, cert->subjectCNLen);
  5407. ptr[cert->subjectCNLen] = '\0';
  5408. cert->subjectCN = ptr;
  5409. cert->subjectCNStored = 1;
  5410. }
  5411. if (cert->keyOID == RSAk &&
  5412. cert->publicKey != NULL && cert->pubKeySize > 0) {
  5413. ptr = (char*) XMALLOC(cert->pubKeySize, cert->heap,
  5414. DYNAMIC_TYPE_PUBLIC_KEY);
  5415. if (ptr == NULL)
  5416. return MEMORY_E;
  5417. XMEMCPY(ptr, cert->publicKey, cert->pubKeySize);
  5418. cert->publicKey = (byte *)ptr;
  5419. cert->pubKeyStored = 1;
  5420. }
  5421. return ret;
  5422. }
  5423. /* from SSL proper, for locking can't do find here anymore */
  5424. #ifdef __cplusplus
  5425. extern "C" {
  5426. #endif
  5427. WOLFSSL_LOCAL Signer* GetCA(void* signers, byte* hash);
  5428. #ifndef NO_SKID
  5429. WOLFSSL_LOCAL Signer* GetCAByName(void* signers, byte* hash);
  5430. #endif
  5431. #ifdef __cplusplus
  5432. }
  5433. #endif
  5434. #if defined(WOLFCRYPT_ONLY) || defined(NO_CERTS)
  5435. /* dummy functions, not using wolfSSL so don't need actual ones */
  5436. Signer* GetCA(void* signers, byte* hash)
  5437. {
  5438. (void)hash;
  5439. return (Signer*)signers;
  5440. }
  5441. #ifndef NO_SKID
  5442. Signer* GetCAByName(void* signers, byte* hash)
  5443. {
  5444. (void)hash;
  5445. return (Signer*)signers;
  5446. }
  5447. #endif /* NO_SKID */
  5448. #endif /* WOLFCRYPT_ONLY || NO_CERTS */
  5449. #if (defined(WOLFSSL_ALT_CERT_CHAINS) || \
  5450. defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY)) && !defined(NO_SKID)
  5451. static Signer* GetCABySubjectAndPubKey(DecodedCert* cert, void* cm)
  5452. {
  5453. Signer* ca = NULL;
  5454. if (cert->extSubjKeyIdSet)
  5455. ca = GetCA(cm, cert->extSubjKeyId);
  5456. if (ca == NULL)
  5457. ca = GetCAByName(cm, cert->subjectHash);
  5458. if (ca) {
  5459. if ((ca->pubKeySize == cert->pubKeySize) &&
  5460. (XMEMCMP(ca->publicKey, cert->publicKey, ca->pubKeySize) == 0)) {
  5461. return ca;
  5462. }
  5463. }
  5464. return NULL;
  5465. }
  5466. #endif
  5467. int ParseCertRelative(DecodedCert* cert, int type, int verify, void* cm)
  5468. {
  5469. int ret = 0;
  5470. int badDate = 0;
  5471. int criticalExt = 0;
  5472. word32 confirmOID;
  5473. if (cert == NULL) {
  5474. return BAD_FUNC_ARG;
  5475. }
  5476. if (cert->sigCtx.state == SIG_STATE_BEGIN) {
  5477. if ((ret = DecodeToKey(cert, verify)) < 0) {
  5478. if (ret == ASN_BEFORE_DATE_E || ret == ASN_AFTER_DATE_E)
  5479. badDate = ret;
  5480. else
  5481. return ret;
  5482. }
  5483. WOLFSSL_MSG("Parsed Past Key");
  5484. if (cert->srcIdx < cert->sigIndex) {
  5485. #ifndef ALLOW_V1_EXTENSIONS
  5486. if (cert->version < 2) {
  5487. WOLFSSL_MSG("\tv1 and v2 certs not allowed extensions");
  5488. return ASN_VERSION_E;
  5489. }
  5490. #endif
  5491. /* save extensions */
  5492. cert->extensions = &cert->source[cert->srcIdx];
  5493. cert->extensionsSz = cert->sigIndex - cert->srcIdx;
  5494. cert->extensionsIdx = cert->srcIdx; /* for potential later use */
  5495. if ((ret = DecodeCertExtensions(cert)) < 0) {
  5496. if (ret == ASN_CRIT_EXT_E)
  5497. criticalExt = ret;
  5498. else
  5499. return ret;
  5500. }
  5501. /* advance past extensions */
  5502. cert->srcIdx = cert->sigIndex;
  5503. }
  5504. if ((ret = GetAlgoId(cert->source, &cert->srcIdx, &confirmOID,
  5505. oidSigType, cert->maxIdx)) < 0)
  5506. return ret;
  5507. if ((ret = GetSignature(cert)) < 0)
  5508. return ret;
  5509. if (confirmOID != cert->signatureOID)
  5510. return ASN_SIG_OID_E;
  5511. #ifndef NO_SKID
  5512. if (cert->extSubjKeyIdSet == 0 && cert->publicKey != NULL &&
  5513. cert->pubKeySize > 0) {
  5514. #ifdef NO_SHA
  5515. ret = wc_Sha256Hash(cert->publicKey, cert->pubKeySize,
  5516. cert->extSubjKeyId);
  5517. #else
  5518. ret = wc_ShaHash(cert->publicKey, cert->pubKeySize,
  5519. cert->extSubjKeyId);
  5520. #endif /* NO_SHA */
  5521. if (ret != 0)
  5522. return ret;
  5523. }
  5524. #endif /* !NO_SKID */
  5525. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  5526. cert->ca = NULL;
  5527. #ifndef NO_SKID
  5528. if (cert->extAuthKeyIdSet)
  5529. cert->ca = GetCA(cm, cert->extAuthKeyId);
  5530. if (cert->ca == NULL)
  5531. cert->ca = GetCAByName(cm, cert->issuerHash);
  5532. /* OCSP Only: alt lookup using subject and pub key w/o sig check */
  5533. #ifdef WOLFSSL_NO_TRUSTED_CERTS_VERIFY
  5534. if (cert->ca == NULL && verify == VERIFY_OCSP) {
  5535. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  5536. if (cert->ca) {
  5537. ret = 0; /* success */
  5538. goto exit_pcr;
  5539. }
  5540. }
  5541. #endif /* WOLFSSL_NO_TRUSTED_CERTS_VERIFY */
  5542. /* alt lookup using subject and public key */
  5543. #ifdef WOLFSSL_ALT_CERT_CHAINS
  5544. if (cert->ca == NULL)
  5545. cert->ca = GetCABySubjectAndPubKey(cert, cm);
  5546. #endif
  5547. #else
  5548. cert->ca = GetCA(cm, cert->issuerHash);
  5549. #endif /* !NO_SKID */
  5550. WOLFSSL_MSG("About to verify certificate signature");
  5551. if (cert->ca) {
  5552. if (cert->isCA) {
  5553. if (cert->ca->pathLengthSet) {
  5554. if (cert->ca->pathLength == 0) {
  5555. WOLFSSL_MSG("CA with path length 0 signing a CA");
  5556. return ASN_PATHLEN_INV_E;
  5557. }
  5558. if (cert->pathLengthSet &&
  5559. cert->pathLength >= cert->ca->pathLength) {
  5560. WOLFSSL_MSG("CA signing CA with longer path length");
  5561. return ASN_PATHLEN_INV_E;
  5562. }
  5563. }
  5564. }
  5565. #ifdef HAVE_OCSP
  5566. /* Need the CA's public key hash for OCSP */
  5567. #ifdef NO_SHA
  5568. ret = wc_Sha256Hash(cert->ca->publicKey, cert->ca->pubKeySize,
  5569. cert->issuerKeyHash);
  5570. #else
  5571. ret = wc_ShaHash(cert->ca->publicKey, cert->ca->pubKeySize,
  5572. cert->issuerKeyHash);
  5573. #endif /* NO_SHA */
  5574. if (ret != 0)
  5575. return ret;
  5576. #endif /* HAVE_OCSP */
  5577. }
  5578. }
  5579. }
  5580. if (verify != NO_VERIFY && type != CA_TYPE && type != TRUSTED_PEER_TYPE) {
  5581. if (cert->ca) {
  5582. if (verify == VERIFY || verify == VERIFY_OCSP) {
  5583. /* try to confirm/verify signature */
  5584. if ((ret = ConfirmSignature(&cert->sigCtx,
  5585. cert->source + cert->certBegin,
  5586. cert->sigIndex - cert->certBegin,
  5587. cert->ca->publicKey, cert->ca->pubKeySize,
  5588. cert->ca->keyOID, cert->signature,
  5589. cert->sigLength, cert->signatureOID)) != 0) {
  5590. if (ret != WC_PENDING_E) {
  5591. WOLFSSL_MSG("Confirm signature failed");
  5592. }
  5593. return ret;
  5594. }
  5595. #ifndef IGNORE_NAME_CONSTRAINTS
  5596. /* check that this cert's name is permitted by the signer's
  5597. * name constraints */
  5598. if (!ConfirmNameConstraints(cert->ca, cert)) {
  5599. WOLFSSL_MSG("Confirm name constraint failed");
  5600. return ASN_NAME_INVALID_E;
  5601. }
  5602. #endif /* IGNORE_NAME_CONSTRAINTS */
  5603. }
  5604. }
  5605. else {
  5606. /* no signer */
  5607. WOLFSSL_MSG("No CA signer to verify with");
  5608. return ASN_NO_SIGNER_E;
  5609. }
  5610. }
  5611. #if defined(WOLFSSL_NO_TRUSTED_CERTS_VERIFY) && !defined(NO_SKID)
  5612. exit_pcr:
  5613. #endif
  5614. if (badDate != 0)
  5615. return badDate;
  5616. if (criticalExt != 0)
  5617. return criticalExt;
  5618. return ret;
  5619. }
  5620. /* Create and init an new signer */
  5621. Signer* MakeSigner(void* heap)
  5622. {
  5623. Signer* signer = (Signer*) XMALLOC(sizeof(Signer), heap,
  5624. DYNAMIC_TYPE_SIGNER);
  5625. if (signer) {
  5626. signer->pubKeySize = 0;
  5627. signer->keyOID = 0;
  5628. signer->publicKey = NULL;
  5629. signer->nameLen = 0;
  5630. signer->name = NULL;
  5631. #ifndef IGNORE_NAME_CONSTRAINTS
  5632. signer->permittedNames = NULL;
  5633. signer->excludedNames = NULL;
  5634. #endif /* IGNORE_NAME_CONSTRAINTS */
  5635. signer->pathLengthSet = 0;
  5636. signer->pathLength = 0;
  5637. signer->next = NULL;
  5638. }
  5639. (void)heap;
  5640. return signer;
  5641. }
  5642. /* Free an individual signer */
  5643. void FreeSigner(Signer* signer, void* heap)
  5644. {
  5645. XFREE(signer->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  5646. XFREE(signer->publicKey, heap, DYNAMIC_TYPE_PUBLIC_KEY);
  5647. #ifndef IGNORE_NAME_CONSTRAINTS
  5648. if (signer->permittedNames)
  5649. FreeNameSubtrees(signer->permittedNames, heap);
  5650. if (signer->excludedNames)
  5651. FreeNameSubtrees(signer->excludedNames, heap);
  5652. #endif
  5653. XFREE(signer, heap, DYNAMIC_TYPE_SIGNER);
  5654. (void)heap;
  5655. }
  5656. /* Free the whole singer table with number of rows */
  5657. void FreeSignerTable(Signer** table, int rows, void* heap)
  5658. {
  5659. int i;
  5660. for (i = 0; i < rows; i++) {
  5661. Signer* signer = table[i];
  5662. while (signer) {
  5663. Signer* next = signer->next;
  5664. FreeSigner(signer, heap);
  5665. signer = next;
  5666. }
  5667. table[i] = NULL;
  5668. }
  5669. }
  5670. #ifdef WOLFSSL_TRUST_PEER_CERT
  5671. /* Free an individual trusted peer cert */
  5672. void FreeTrustedPeer(TrustedPeerCert* tp, void* heap)
  5673. {
  5674. if (tp == NULL) {
  5675. return;
  5676. }
  5677. if (tp->name) {
  5678. XFREE(tp->name, heap, DYNAMIC_TYPE_SUBJECT_CN);
  5679. }
  5680. if (tp->sig) {
  5681. XFREE(tp->sig, heap, DYNAMIC_TYPE_SIGNATURE);
  5682. }
  5683. #ifndef IGNORE_NAME_CONSTRAINTS
  5684. if (tp->permittedNames)
  5685. FreeNameSubtrees(tp->permittedNames, heap);
  5686. if (tp->excludedNames)
  5687. FreeNameSubtrees(tp->excludedNames, heap);
  5688. #endif
  5689. XFREE(tp, heap, DYNAMIC_TYPE_CERT);
  5690. (void)heap;
  5691. }
  5692. /* Free the whole Trusted Peer linked list */
  5693. void FreeTrustedPeerTable(TrustedPeerCert** table, int rows, void* heap)
  5694. {
  5695. int i;
  5696. for (i = 0; i < rows; i++) {
  5697. TrustedPeerCert* tp = table[i];
  5698. while (tp) {
  5699. TrustedPeerCert* next = tp->next;
  5700. FreeTrustedPeer(tp, heap);
  5701. tp = next;
  5702. }
  5703. table[i] = NULL;
  5704. }
  5705. }
  5706. #endif /* WOLFSSL_TRUST_PEER_CERT */
  5707. WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header)
  5708. {
  5709. int i = 0;
  5710. if (output == NULL)
  5711. return BAD_FUNC_ARG;
  5712. if (header) {
  5713. output[i++] = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED;
  5714. output[i++] = 3;
  5715. }
  5716. output[i++] = ASN_INTEGER;
  5717. output[i++] = 0x01;
  5718. output[i++] = (byte)version;
  5719. return i;
  5720. }
  5721. WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output,
  5722. int maxSnSz)
  5723. {
  5724. int i = 0;
  5725. int snSzInt = (int)snSz;
  5726. if (sn == NULL || output == NULL || snSzInt < 0)
  5727. return BAD_FUNC_ARG;
  5728. /* remove leading zeros */
  5729. while (snSzInt > 0 && sn[0] == 0) {
  5730. snSzInt--;
  5731. sn++;
  5732. }
  5733. /* truncate if input is too long */
  5734. if (snSzInt > maxSnSz)
  5735. snSzInt = maxSnSz;
  5736. /* encode ASN Integer, with length and value */
  5737. output[i++] = ASN_INTEGER;
  5738. /* handle MSB, to make sure value is positive */
  5739. if (sn[0] & 0x80) {
  5740. /* make room for zero pad */
  5741. if (snSzInt > maxSnSz-1)
  5742. snSzInt = maxSnSz-1;
  5743. /* add zero pad */
  5744. i += SetLength(snSzInt+1, &output[i]);
  5745. output[i++] = 0x00;
  5746. XMEMCPY(&output[i], sn, snSzInt);
  5747. }
  5748. else {
  5749. i += SetLength(snSzInt, &output[i]);
  5750. XMEMCPY(&output[i], sn, snSzInt);
  5751. }
  5752. /* compute final length */
  5753. i += snSzInt;
  5754. return i;
  5755. }
  5756. WOLFSSL_LOCAL int GetSerialNumber(const byte* input, word32* inOutIdx,
  5757. byte* serial, int* serialSz, word32 maxIdx)
  5758. {
  5759. int result = 0;
  5760. int ret;
  5761. WOLFSSL_ENTER("GetSerialNumber");
  5762. if (serial == NULL || input == NULL || serialSz == NULL) {
  5763. return BAD_FUNC_ARG;
  5764. }
  5765. /* First byte is ASN type */
  5766. if ((*inOutIdx+1) > maxIdx) {
  5767. WOLFSSL_MSG("Bad idx first");
  5768. return BUFFER_E;
  5769. }
  5770. ret = GetASNInt(input, inOutIdx, serialSz, maxIdx);
  5771. if (ret != 0)
  5772. return ret;
  5773. if (*serialSz > EXTERNAL_SERIAL_SIZE) {
  5774. WOLFSSL_MSG("Serial size bad");
  5775. return ASN_PARSE_E;
  5776. }
  5777. /* return serial */
  5778. XMEMCPY(serial, &input[*inOutIdx], *serialSz);
  5779. *inOutIdx += *serialSz;
  5780. return result;
  5781. }
  5782. const char* BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
  5783. const char* END_CERT = "-----END CERTIFICATE-----";
  5784. const char* BEGIN_CERT_REQ = "-----BEGIN CERTIFICATE REQUEST-----";
  5785. const char* END_CERT_REQ = "-----END CERTIFICATE REQUEST-----";
  5786. const char* BEGIN_DH_PARAM = "-----BEGIN DH PARAMETERS-----";
  5787. const char* END_DH_PARAM = "-----END DH PARAMETERS-----";
  5788. const char* BEGIN_DSA_PARAM = "-----BEGIN DSA PARAMETERS-----";
  5789. const char* END_DSA_PARAM = "-----END DSA PARAMETERS-----";
  5790. const char* BEGIN_X509_CRL = "-----BEGIN X509 CRL-----";
  5791. const char* END_X509_CRL = "-----END X509 CRL-----";
  5792. const char* BEGIN_RSA_PRIV = "-----BEGIN RSA PRIVATE KEY-----";
  5793. const char* END_RSA_PRIV = "-----END RSA PRIVATE KEY-----";
  5794. const char* BEGIN_PRIV_KEY = "-----BEGIN PRIVATE KEY-----";
  5795. const char* END_PRIV_KEY = "-----END PRIVATE KEY-----";
  5796. const char* BEGIN_ENC_PRIV_KEY = "-----BEGIN ENCRYPTED PRIVATE KEY-----";
  5797. const char* END_ENC_PRIV_KEY = "-----END ENCRYPTED PRIVATE KEY-----";
  5798. const char* BEGIN_EC_PRIV = "-----BEGIN EC PRIVATE KEY-----";
  5799. const char* END_EC_PRIV = "-----END EC PRIVATE KEY-----";
  5800. const char* BEGIN_DSA_PRIV = "-----BEGIN DSA PRIVATE KEY-----";
  5801. const char* END_DSA_PRIV = "-----END DSA PRIVATE KEY-----";
  5802. const char* BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
  5803. const char* END_PUB_KEY = "-----END PUBLIC KEY-----";
  5804. const char* BEGIN_EDDSA_PRIV = "-----BEGIN EDDSA PRIVATE KEY-----";
  5805. const char* END_EDDSA_PRIV = "-----END EDDSA PRIVATE KEY-----";
  5806. #if defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN) || defined(OPENSSL_EXTRA)
  5807. /* Used for compatibility API */
  5808. int wc_DerToPem(const byte* der, word32 derSz,
  5809. byte* output, word32 outSz, int type)
  5810. {
  5811. return wc_DerToPemEx(der, derSz, output, outSz, NULL, type);
  5812. }
  5813. /* convert der buffer to pem into output, can't do inplace, der and output
  5814. need to be different */
  5815. int wc_DerToPemEx(const byte* der, word32 derSz, byte* output, word32 outSz,
  5816. byte *cipher_info, int type)
  5817. {
  5818. #ifdef WOLFSSL_SMALL_STACK
  5819. char* header = NULL;
  5820. char* footer = NULL;
  5821. #else
  5822. char header[40 + HEADER_ENCRYPTED_KEY_SIZE];
  5823. char footer[40];
  5824. #endif
  5825. int headerLen = 40 + HEADER_ENCRYPTED_KEY_SIZE;
  5826. int footerLen = 40;
  5827. int i;
  5828. int err;
  5829. int outLen; /* return length or error */
  5830. if (der == output) /* no in place conversion */
  5831. return BAD_FUNC_ARG;
  5832. #ifdef WOLFSSL_SMALL_STACK
  5833. header = (char*)XMALLOC(headerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5834. if (header == NULL)
  5835. return MEMORY_E;
  5836. footer = (char*)XMALLOC(footerLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5837. if (footer == NULL) {
  5838. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5839. return MEMORY_E;
  5840. }
  5841. #endif
  5842. if (type == CERT_TYPE) {
  5843. XSTRNCPY(header, BEGIN_CERT, headerLen);
  5844. XSTRNCAT(header, "\n", 1);
  5845. XSTRNCPY(footer, END_CERT, footerLen);
  5846. XSTRNCAT(footer, "\n", 1);
  5847. }
  5848. else if (type == PRIVATEKEY_TYPE) {
  5849. XSTRNCPY(header, BEGIN_RSA_PRIV, headerLen);
  5850. XSTRNCAT(header, "\n", 1);
  5851. XSTRNCPY(footer, END_RSA_PRIV, footerLen);
  5852. XSTRNCAT(footer, "\n", 1);
  5853. }
  5854. else if (type == PUBLICKEY_TYPE) {
  5855. XSTRNCPY(header, BEGIN_PUB_KEY, headerLen);
  5856. XSTRNCAT(header, "\n", 1);
  5857. XSTRNCPY(footer, END_PUB_KEY, footerLen);
  5858. XSTRNCAT(footer, "\n", 1);
  5859. }
  5860. #ifndef NO_DSA
  5861. else if (type == DSA_PRIVATEKEY_TYPE) {
  5862. XSTRNCPY(header, BEGIN_DSA_PRIV, headerLen);
  5863. XSTRNCAT(header, "\n", 1);
  5864. XSTRNCPY(footer, END_DSA_PRIV, footerLen);
  5865. XSTRNCAT(footer, "\n", 1);
  5866. }
  5867. #endif
  5868. #ifdef HAVE_ECC
  5869. else if (type == ECC_PRIVATEKEY_TYPE) {
  5870. XSTRNCPY(header, BEGIN_EC_PRIV, headerLen);
  5871. XSTRNCAT(header, "\n", 1);
  5872. XSTRNCPY(footer, END_EC_PRIV, footerLen);
  5873. XSTRNCAT(footer, "\n", 1);
  5874. }
  5875. #endif
  5876. #ifdef HAVE_ED25519
  5877. else if (type == EDDSA_PRIVATEKEY_TYPE) {
  5878. XSTRNCPY(header, BEGIN_EDDSA_PRIV, headerLen);
  5879. XSTRNCAT(header, "\n", 1);
  5880. XSTRNCPY(footer, END_EDDSA_PRIV, footerLen);
  5881. XSTRNCAT(footer, "\n", 1);
  5882. }
  5883. #endif
  5884. #ifdef WOLFSSL_CERT_REQ
  5885. else if (type == CERTREQ_TYPE)
  5886. {
  5887. XSTRNCPY(header, BEGIN_CERT_REQ, headerLen);
  5888. XSTRNCAT(header, "\n", 1);
  5889. XSTRNCPY(footer, END_CERT_REQ, footerLen);
  5890. XSTRNCAT(footer, "\n", 1);
  5891. }
  5892. #endif
  5893. #ifdef HAVE_CRL
  5894. else if (type == CRL_TYPE)
  5895. {
  5896. XSTRNCPY(header, BEGIN_X509_CRL, headerLen);
  5897. XSTRNCAT(header, "\n", 1);
  5898. XSTRNCPY(footer, END_X509_CRL, footerLen);
  5899. XSTRNCAT(footer, "\n", 1);
  5900. }
  5901. #endif
  5902. else {
  5903. #ifdef WOLFSSL_SMALL_STACK
  5904. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5905. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5906. #endif
  5907. return BAD_FUNC_ARG;
  5908. }
  5909. /* extra header information for encrypted key */
  5910. if (cipher_info != NULL) {
  5911. size_t cipherInfoStrLen = XSTRLEN((char*)cipher_info);
  5912. if (cipherInfoStrLen > HEADER_ENCRYPTED_KEY_SIZE - (23+10+2))
  5913. cipherInfoStrLen = HEADER_ENCRYPTED_KEY_SIZE - (23+10+2);
  5914. XSTRNCAT(header, "Proc-Type: 4,ENCRYPTED\n", 23);
  5915. XSTRNCAT(header, "DEK-Info: ", 10);
  5916. XSTRNCAT(header, (char*)cipher_info, cipherInfoStrLen);
  5917. XSTRNCAT(header, "\n\n", 2);
  5918. }
  5919. headerLen = (int)XSTRLEN(header);
  5920. footerLen = (int)XSTRLEN(footer);
  5921. /* if null output and 0 size passed in then return size needed */
  5922. if (!output && outSz == 0) {
  5923. #ifdef WOLFSSL_SMALL_STACK
  5924. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5925. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5926. #endif
  5927. outLen = 0;
  5928. if ((err = Base64_Encode(der, derSz, NULL, (word32*)&outLen))
  5929. != LENGTH_ONLY_E) {
  5930. return err;
  5931. }
  5932. return headerLen + footerLen + outLen;
  5933. }
  5934. if (!der || !output) {
  5935. #ifdef WOLFSSL_SMALL_STACK
  5936. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5937. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5938. #endif
  5939. return BAD_FUNC_ARG;
  5940. }
  5941. /* don't even try if outSz too short */
  5942. if (outSz < headerLen + footerLen + derSz) {
  5943. #ifdef WOLFSSL_SMALL_STACK
  5944. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5945. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5946. #endif
  5947. return BAD_FUNC_ARG;
  5948. }
  5949. /* header */
  5950. XMEMCPY(output, header, headerLen);
  5951. i = headerLen;
  5952. #ifdef WOLFSSL_SMALL_STACK
  5953. XFREE(header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5954. #endif
  5955. /* body */
  5956. outLen = outSz - (headerLen + footerLen); /* input to Base64_Encode */
  5957. if ( (err = Base64_Encode(der, derSz, output + i, (word32*)&outLen)) < 0) {
  5958. #ifdef WOLFSSL_SMALL_STACK
  5959. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5960. #endif
  5961. return err;
  5962. }
  5963. i += outLen;
  5964. /* footer */
  5965. if ( (i + footerLen) > (int)outSz) {
  5966. #ifdef WOLFSSL_SMALL_STACK
  5967. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5968. #endif
  5969. return BAD_FUNC_ARG;
  5970. }
  5971. XMEMCPY(output + i, footer, footerLen);
  5972. #ifdef WOLFSSL_SMALL_STACK
  5973. XFREE(footer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5974. #endif
  5975. return outLen + headerLen + footerLen;
  5976. }
  5977. #endif /* WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN || OPENSSL_EXTRA */
  5978. #if !defined(NO_RSA) && (defined(WOLFSSL_CERT_GEN) || \
  5979. (defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)))
  5980. /* USER RSA ifdef portions used instead of refactor in consideration for
  5981. possible fips build */
  5982. /* Write a public RSA key to output */
  5983. static int SetRsaPublicKey(byte* output, RsaKey* key,
  5984. int outLen, int with_header)
  5985. {
  5986. #ifdef WOLFSSL_SMALL_STACK
  5987. byte* n = NULL;
  5988. byte* e = NULL;
  5989. #else
  5990. byte n[MAX_RSA_INT_SZ];
  5991. byte e[MAX_RSA_E_SZ];
  5992. #endif
  5993. byte seq[MAX_SEQ_SZ];
  5994. byte bitString[1 + MAX_LENGTH_SZ + 1];
  5995. int nSz;
  5996. int eSz;
  5997. int seqSz;
  5998. int bitStringSz;
  5999. int idx;
  6000. if (output == NULL || key == NULL || outLen < MAX_SEQ_SZ)
  6001. return BAD_FUNC_ARG;
  6002. /* n */
  6003. #ifdef WOLFSSL_SMALL_STACK
  6004. n = (byte*)XMALLOC(MAX_RSA_INT_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6005. if (n == NULL)
  6006. return MEMORY_E;
  6007. #endif
  6008. #ifdef HAVE_USER_RSA
  6009. nSz = SetASNIntRSA(key->n, n);
  6010. #else
  6011. nSz = SetASNIntMP(&key->n, MAX_RSA_INT_SZ, n);
  6012. #endif
  6013. if (nSz < 0) {
  6014. #ifdef WOLFSSL_SMALL_STACK
  6015. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6016. #endif
  6017. return nSz;
  6018. }
  6019. /* e */
  6020. #ifdef WOLFSSL_SMALL_STACK
  6021. e = (byte*)XMALLOC(MAX_RSA_E_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6022. if (e == NULL) {
  6023. #ifdef WOLFSSL_SMALL_STACK
  6024. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6025. #endif
  6026. return MEMORY_E;
  6027. }
  6028. #endif
  6029. #ifdef HAVE_USER_RSA
  6030. eSz = SetASNIntRSA(key->e, e);
  6031. #else
  6032. eSz = SetASNIntMP(&key->e, MAX_RSA_INT_SZ, e);
  6033. #endif
  6034. if (eSz < 0) {
  6035. #ifdef WOLFSSL_SMALL_STACK
  6036. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6037. XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6038. #endif
  6039. return eSz;
  6040. }
  6041. seqSz = SetSequence(nSz + eSz, seq);
  6042. /* check output size */
  6043. if ( (seqSz + nSz + eSz) > outLen) {
  6044. #ifdef WOLFSSL_SMALL_STACK
  6045. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6046. XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6047. #endif
  6048. return BUFFER_E;
  6049. }
  6050. /* headers */
  6051. if (with_header) {
  6052. int algoSz;
  6053. #ifdef WOLFSSL_SMALL_STACK
  6054. byte* algo = NULL;
  6055. algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6056. if (algo == NULL) {
  6057. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6058. XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6059. return MEMORY_E;
  6060. }
  6061. #else
  6062. byte algo[MAX_ALGO_SZ];
  6063. #endif
  6064. algoSz = SetAlgoID(RSAk, algo, oidKeyType, 0);
  6065. bitStringSz = SetBitString(seqSz + nSz + eSz, 0, bitString);
  6066. idx = SetSequence(nSz + eSz + seqSz + bitStringSz + algoSz, output);
  6067. /* check output size */
  6068. if ( (idx + algoSz + bitStringSz + seqSz + nSz + eSz) > outLen) {
  6069. #ifdef WOLFSSL_SMALL_STACK
  6070. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6071. XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6072. XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6073. #endif
  6074. return BUFFER_E;
  6075. }
  6076. /* algo */
  6077. XMEMCPY(output + idx, algo, algoSz);
  6078. idx += algoSz;
  6079. /* bit string */
  6080. XMEMCPY(output + idx, bitString, bitStringSz);
  6081. idx += bitStringSz;
  6082. #ifdef WOLFSSL_SMALL_STACK
  6083. XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6084. #endif
  6085. }
  6086. else
  6087. idx = 0;
  6088. /* seq */
  6089. XMEMCPY(output + idx, seq, seqSz);
  6090. idx += seqSz;
  6091. /* n */
  6092. XMEMCPY(output + idx, n, nSz);
  6093. idx += nSz;
  6094. /* e */
  6095. XMEMCPY(output + idx, e, eSz);
  6096. idx += eSz;
  6097. #ifdef WOLFSSL_SMALL_STACK
  6098. XFREE(n, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6099. XFREE(e, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6100. #endif
  6101. return idx;
  6102. }
  6103. #endif /* !NO_RSA && (WOLFSSL_CERT_GEN || (WOLFSSL_KEY_GEN &&
  6104. !HAVE_USER_RSA))) */
  6105. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA) && !defined(HAVE_USER_RSA)
  6106. static mp_int* GetRsaInt(RsaKey* key, int idx)
  6107. {
  6108. if (idx == 0)
  6109. return &key->n;
  6110. if (idx == 1)
  6111. return &key->e;
  6112. if (idx == 2)
  6113. return &key->d;
  6114. if (idx == 3)
  6115. return &key->p;
  6116. if (idx == 4)
  6117. return &key->q;
  6118. if (idx == 5)
  6119. return &key->dP;
  6120. if (idx == 6)
  6121. return &key->dQ;
  6122. if (idx == 7)
  6123. return &key->u;
  6124. return NULL;
  6125. }
  6126. /* Release Tmp RSA resources */
  6127. static INLINE void FreeTmpRsas(byte** tmps, void* heap)
  6128. {
  6129. int i;
  6130. (void)heap;
  6131. for (i = 0; i < RSA_INTS; i++)
  6132. XFREE(tmps[i], heap, DYNAMIC_TYPE_RSA);
  6133. }
  6134. /* Convert RsaKey key to DER format, write to output (inLen), return bytes
  6135. written */
  6136. int wc_RsaKeyToDer(RsaKey* key, byte* output, word32 inLen)
  6137. {
  6138. word32 seqSz, verSz, rawLen, intTotalLen = 0;
  6139. word32 sizes[RSA_INTS];
  6140. int i, j, outLen, ret = 0, mpSz;
  6141. byte seq[MAX_SEQ_SZ];
  6142. byte ver[MAX_VERSION_SZ];
  6143. byte* tmps[RSA_INTS];
  6144. if (!key || !output)
  6145. return BAD_FUNC_ARG;
  6146. if (key->type != RSA_PRIVATE)
  6147. return BAD_FUNC_ARG;
  6148. for (i = 0; i < RSA_INTS; i++)
  6149. tmps[i] = NULL;
  6150. /* write all big ints from key to DER tmps */
  6151. for (i = 0; i < RSA_INTS; i++) {
  6152. mp_int* keyInt = GetRsaInt(key, i);
  6153. rawLen = mp_unsigned_bin_size(keyInt) + 1;
  6154. tmps[i] = (byte*)XMALLOC(rawLen + MAX_SEQ_SZ, key->heap,
  6155. DYNAMIC_TYPE_RSA);
  6156. if (tmps[i] == NULL) {
  6157. ret = MEMORY_E;
  6158. break;
  6159. }
  6160. mpSz = SetASNIntMP(keyInt, MAX_RSA_INT_SZ, tmps[i]);
  6161. if (mpSz < 0) {
  6162. ret = mpSz;
  6163. break;
  6164. }
  6165. intTotalLen += (sizes[i] = mpSz);
  6166. }
  6167. if (ret != 0) {
  6168. FreeTmpRsas(tmps, key->heap);
  6169. return ret;
  6170. }
  6171. /* make headers */
  6172. verSz = SetMyVersion(0, ver, FALSE);
  6173. seqSz = SetSequence(verSz + intTotalLen, seq);
  6174. outLen = seqSz + verSz + intTotalLen;
  6175. if (outLen > (int)inLen)
  6176. return BAD_FUNC_ARG;
  6177. /* write to output */
  6178. XMEMCPY(output, seq, seqSz);
  6179. j = seqSz;
  6180. XMEMCPY(output + j, ver, verSz);
  6181. j += verSz;
  6182. for (i = 0; i < RSA_INTS; i++) {
  6183. XMEMCPY(output + j, tmps[i], sizes[i]);
  6184. j += sizes[i];
  6185. }
  6186. FreeTmpRsas(tmps, key->heap);
  6187. return outLen;
  6188. }
  6189. /* Convert Rsa Public key to DER format, write to output (inLen), return bytes
  6190. written */
  6191. int wc_RsaKeyToPublicDer(RsaKey* key, byte* output, word32 inLen)
  6192. {
  6193. return SetRsaPublicKey(output, key, inLen, 1);
  6194. }
  6195. #endif /* WOLFSSL_KEY_GEN && !NO_RSA && !HAVE_USER_RSA */
  6196. #ifdef WOLFSSL_CERT_GEN
  6197. /* Initialize and Set Certificate defaults:
  6198. version = 3 (0x2)
  6199. serial = 0
  6200. sigType = SHA_WITH_RSA
  6201. issuer = blank
  6202. daysValid = 500
  6203. selfSigned = 1 (true) use subject as issuer
  6204. subject = blank
  6205. */
  6206. int wc_InitCert(Cert* cert)
  6207. {
  6208. if (cert == NULL) {
  6209. return BAD_FUNC_ARG;
  6210. }
  6211. cert->version = 2; /* version 3 is hex 2 */
  6212. cert->sigType = CTC_SHAwRSA;
  6213. cert->daysValid = 500;
  6214. cert->selfSigned = 1;
  6215. cert->isCA = 0;
  6216. cert->bodySz = 0;
  6217. #ifdef WOLFSSL_ALT_NAMES
  6218. cert->altNamesSz = 0;
  6219. cert->beforeDateSz = 0;
  6220. cert->afterDateSz = 0;
  6221. #endif
  6222. #ifdef WOLFSSL_CERT_EXT
  6223. cert->skidSz = 0;
  6224. cert->akidSz = 0;
  6225. cert->keyUsage = 0;
  6226. cert->extKeyUsage = 0;
  6227. cert->certPoliciesNb = 0;
  6228. XMEMSET(cert->akid, 0, CTC_MAX_AKID_SIZE);
  6229. XMEMSET(cert->skid, 0, CTC_MAX_SKID_SIZE);
  6230. XMEMSET(cert->certPolicies, 0, CTC_MAX_CERTPOL_NB*CTC_MAX_CERTPOL_SZ);
  6231. #endif
  6232. cert->keyType = RSA_KEY;
  6233. XMEMSET(cert->serial, 0, CTC_SERIAL_SIZE);
  6234. cert->serialSz = 0;
  6235. cert->issuer.country[0] = '\0';
  6236. cert->issuer.countryEnc = CTC_PRINTABLE;
  6237. cert->issuer.state[0] = '\0';
  6238. cert->issuer.stateEnc = CTC_UTF8;
  6239. cert->issuer.locality[0] = '\0';
  6240. cert->issuer.localityEnc = CTC_UTF8;
  6241. cert->issuer.sur[0] = '\0';
  6242. cert->issuer.surEnc = CTC_UTF8;
  6243. cert->issuer.org[0] = '\0';
  6244. cert->issuer.orgEnc = CTC_UTF8;
  6245. cert->issuer.unit[0] = '\0';
  6246. cert->issuer.unitEnc = CTC_UTF8;
  6247. cert->issuer.commonName[0] = '\0';
  6248. cert->issuer.commonNameEnc = CTC_UTF8;
  6249. cert->issuer.email[0] = '\0';
  6250. cert->subject.country[0] = '\0';
  6251. cert->subject.countryEnc = CTC_PRINTABLE;
  6252. cert->subject.state[0] = '\0';
  6253. cert->subject.stateEnc = CTC_UTF8;
  6254. cert->subject.locality[0] = '\0';
  6255. cert->subject.localityEnc = CTC_UTF8;
  6256. cert->subject.sur[0] = '\0';
  6257. cert->subject.surEnc = CTC_UTF8;
  6258. cert->subject.org[0] = '\0';
  6259. cert->subject.orgEnc = CTC_UTF8;
  6260. cert->subject.unit[0] = '\0';
  6261. cert->subject.unitEnc = CTC_UTF8;
  6262. cert->subject.commonName[0] = '\0';
  6263. cert->subject.commonNameEnc = CTC_UTF8;
  6264. cert->subject.email[0] = '\0';
  6265. #ifdef WOLFSSL_CERT_REQ
  6266. cert->challengePw[0] ='\0';
  6267. #endif
  6268. #ifdef WOLFSSL_HEAP_TEST
  6269. cert->heap = (void*)WOLFSSL_HEAP_TEST;
  6270. #else
  6271. cert->heap = NULL;
  6272. #endif
  6273. return 0;
  6274. }
  6275. /* DER encoded x509 Certificate */
  6276. typedef struct DerCert {
  6277. byte size[MAX_LENGTH_SZ]; /* length encoded */
  6278. byte version[MAX_VERSION_SZ]; /* version encoded */
  6279. byte serial[CTC_SERIAL_SIZE + MAX_LENGTH_SZ]; /* serial number encoded */
  6280. byte sigAlgo[MAX_ALGO_SZ]; /* signature algo encoded */
  6281. byte issuer[ASN_NAME_MAX]; /* issuer encoded */
  6282. byte subject[ASN_NAME_MAX]; /* subject encoded */
  6283. byte validity[MAX_DATE_SIZE*2 + MAX_SEQ_SZ*2]; /* before and after dates */
  6284. byte publicKey[MAX_PUBLIC_KEY_SZ]; /* rsa / ntru public key encoded */
  6285. byte ca[MAX_CA_SZ]; /* basic constraint CA true size */
  6286. byte extensions[MAX_EXTENSIONS_SZ]; /* all extensions */
  6287. #ifdef WOLFSSL_CERT_EXT
  6288. byte skid[MAX_KID_SZ]; /* Subject Key Identifier extension */
  6289. byte akid[MAX_KID_SZ]; /* Authority Key Identifier extension */
  6290. byte keyUsage[MAX_KEYUSAGE_SZ]; /* Key Usage extension */
  6291. byte extKeyUsage[MAX_EXTKEYUSAGE_SZ]; /* Extended Key Usage extension */
  6292. byte certPolicies[MAX_CERTPOL_NB*MAX_CERTPOL_SZ]; /* Certificate Policies */
  6293. #endif
  6294. #ifdef WOLFSSL_CERT_REQ
  6295. byte attrib[MAX_ATTRIB_SZ]; /* Cert req attributes encoded */
  6296. #endif
  6297. #ifdef WOLFSSL_ALT_NAMES
  6298. byte altNames[CTC_MAX_ALT_SIZE]; /* Alternative Names encoded */
  6299. #endif
  6300. int sizeSz; /* encoded size length */
  6301. int versionSz; /* encoded version length */
  6302. int serialSz; /* encoded serial length */
  6303. int sigAlgoSz; /* encoded sig alog length */
  6304. int issuerSz; /* encoded issuer length */
  6305. int subjectSz; /* encoded subject length */
  6306. int validitySz; /* encoded validity length */
  6307. int publicKeySz; /* encoded public key length */
  6308. int caSz; /* encoded CA extension length */
  6309. #ifdef WOLFSSL_CERT_EXT
  6310. int skidSz; /* encoded SKID extension length */
  6311. int akidSz; /* encoded SKID extension length */
  6312. int keyUsageSz; /* encoded KeyUsage extension length */
  6313. int extKeyUsageSz; /* encoded ExtendedKeyUsage extension length */
  6314. int certPoliciesSz; /* encoded CertPolicies extension length*/
  6315. #endif
  6316. #ifdef WOLFSSL_ALT_NAMES
  6317. int altNamesSz; /* encoded AltNames extension length */
  6318. #endif
  6319. int extensionsSz; /* encoded extensions total length */
  6320. int total; /* total encoded lengths */
  6321. #ifdef WOLFSSL_CERT_REQ
  6322. int attribSz;
  6323. #endif
  6324. } DerCert;
  6325. #ifdef WOLFSSL_CERT_REQ
  6326. /* Write a set header to output */
  6327. static word32 SetUTF8String(word32 len, byte* output)
  6328. {
  6329. output[0] = ASN_UTF8STRING;
  6330. return SetLength(len, output + 1) + 1;
  6331. }
  6332. #endif /* WOLFSSL_CERT_REQ */
  6333. #endif /*WOLFSSL_CERT_GEN */
  6334. #if defined(HAVE_ECC)
  6335. /* Write a public ECC key to output */
  6336. static int SetEccPublicKey(byte* output, ecc_key* key, int with_header)
  6337. {
  6338. byte bitString[1 + MAX_LENGTH_SZ + 1];
  6339. int algoSz;
  6340. int curveSz;
  6341. int bitStringSz;
  6342. int idx;
  6343. word32 pubSz = ECC_BUFSIZE;
  6344. #ifdef WOLFSSL_SMALL_STACK
  6345. byte* algo = NULL;
  6346. byte* curve = NULL;
  6347. byte* pub = NULL;
  6348. #else
  6349. byte algo[MAX_ALGO_SZ];
  6350. byte curve[MAX_ALGO_SZ];
  6351. byte pub[ECC_BUFSIZE];
  6352. #endif
  6353. #ifdef WOLFSSL_SMALL_STACK
  6354. pub = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6355. if (pub == NULL)
  6356. return MEMORY_E;
  6357. #endif
  6358. int ret = wc_ecc_export_x963(key, pub, &pubSz);
  6359. if (ret != 0) {
  6360. #ifdef WOLFSSL_SMALL_STACK
  6361. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6362. #endif
  6363. return ret;
  6364. }
  6365. /* headers */
  6366. if (with_header) {
  6367. #ifdef WOLFSSL_SMALL_STACK
  6368. curve = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6369. if (curve == NULL) {
  6370. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6371. return MEMORY_E;
  6372. }
  6373. #endif
  6374. curveSz = SetCurve(key, curve);
  6375. if (curveSz <= 0) {
  6376. #ifdef WOLFSSL_SMALL_STACK
  6377. XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6378. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6379. #endif
  6380. return curveSz;
  6381. }
  6382. #ifdef WOLFSSL_SMALL_STACK
  6383. algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6384. if (algo == NULL) {
  6385. XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6386. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6387. return MEMORY_E;
  6388. }
  6389. #endif
  6390. algoSz = SetAlgoID(ECDSAk, algo, oidKeyType, curveSz);
  6391. bitStringSz = SetBitString(pubSz, 0, bitString);
  6392. idx = SetSequence(pubSz + curveSz + bitStringSz + algoSz, output);
  6393. /* algo */
  6394. XMEMCPY(output + idx, algo, algoSz);
  6395. idx += algoSz;
  6396. /* curve */
  6397. XMEMCPY(output + idx, curve, curveSz);
  6398. idx += curveSz;
  6399. /* bit string */
  6400. XMEMCPY(output + idx, bitString, bitStringSz);
  6401. idx += bitStringSz;
  6402. }
  6403. else
  6404. idx = 0;
  6405. /* pub */
  6406. XMEMCPY(output + idx, pub, pubSz);
  6407. idx += pubSz;
  6408. #ifdef WOLFSSL_SMALL_STACK
  6409. if (with_header) {
  6410. XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6411. XFREE(curve, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6412. }
  6413. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6414. #endif
  6415. return idx;
  6416. }
  6417. /* returns the size of buffer used, the public ECC key in DER format is stored
  6418. in output buffer
  6419. with_AlgCurve is a flag for when to include a header that has the Algorithm
  6420. and Curve infromation */
  6421. int wc_EccPublicKeyToDer(ecc_key* key, byte* output, word32 inLen,
  6422. int with_AlgCurve)
  6423. {
  6424. word32 infoSz = 0;
  6425. word32 keySz = 0;
  6426. int ret;
  6427. if (output == NULL || key == NULL) {
  6428. return BAD_FUNC_ARG;
  6429. }
  6430. if (with_AlgCurve) {
  6431. /* buffer space for algorithm/curve */
  6432. infoSz += MAX_SEQ_SZ;
  6433. infoSz += 2 * MAX_ALGO_SZ;
  6434. /* buffer space for public key sequence */
  6435. infoSz += MAX_SEQ_SZ;
  6436. infoSz += TRAILING_ZERO;
  6437. }
  6438. if ((ret = wc_ecc_export_x963(key, NULL, &keySz)) != LENGTH_ONLY_E) {
  6439. WOLFSSL_MSG("Error in getting ECC public key size");
  6440. return ret;
  6441. }
  6442. if (inLen < keySz + infoSz) {
  6443. return BUFFER_E;
  6444. }
  6445. return SetEccPublicKey(output, key, with_AlgCurve);
  6446. }
  6447. #endif /* HAVE_ECC */
  6448. #if defined(HAVE_ED25519) && (defined(WOLFSSL_CERT_GEN) || \
  6449. defined(WOLFSSL_KEY_GEN))
  6450. /* Write a public ECC key to output */
  6451. static int SetEd25519PublicKey(byte* output, ed25519_key* key, int with_header)
  6452. {
  6453. byte bitString[1 + MAX_LENGTH_SZ + 1];
  6454. int algoSz;
  6455. int bitStringSz;
  6456. int idx;
  6457. word32 pubSz = ED25519_PUB_KEY_SIZE;
  6458. #ifdef WOLFSSL_SMALL_STACK
  6459. byte* algo = NULL;
  6460. byte* pub = NULL;
  6461. #else
  6462. byte algo[MAX_ALGO_SZ];
  6463. byte pub[ED25519_PUB_KEY_SIZE];
  6464. #endif
  6465. #ifdef WOLFSSL_SMALL_STACK
  6466. pub = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6467. if (pub == NULL)
  6468. return MEMORY_E;
  6469. #endif
  6470. int ret = wc_ed25519_export_public(key, pub, &pubSz);
  6471. if (ret != 0) {
  6472. #ifdef WOLFSSL_SMALL_STACK
  6473. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6474. #endif
  6475. return ret;
  6476. }
  6477. /* headers */
  6478. if (with_header) {
  6479. #ifdef WOLFSSL_SMALL_STACK
  6480. algo = (byte*)XMALLOC(MAX_ALGO_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6481. if (algo == NULL) {
  6482. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6483. return MEMORY_E;
  6484. }
  6485. #endif
  6486. algoSz = SetAlgoID(ED25519k, algo, oidKeyType, 0);
  6487. bitStringSz = SetBitString(pubSz, 0, bitString);
  6488. idx = SetSequence(pubSz + bitStringSz + algoSz, output);
  6489. /* algo */
  6490. XMEMCPY(output + idx, algo, algoSz);
  6491. idx += algoSz;
  6492. /* bit string */
  6493. XMEMCPY(output + idx, bitString, bitStringSz);
  6494. idx += bitStringSz;
  6495. }
  6496. else
  6497. idx = 0;
  6498. /* pub */
  6499. XMEMCPY(output + idx, pub, pubSz);
  6500. idx += pubSz;
  6501. #ifdef WOLFSSL_SMALL_STACK
  6502. if (with_header) {
  6503. XFREE(algo, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6504. }
  6505. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6506. #endif
  6507. return idx;
  6508. }
  6509. int wc_Ed25519PublicKeyToDer(ed25519_key* key, byte* output, word32 inLen,
  6510. int withAlg)
  6511. {
  6512. word32 infoSz = 0;
  6513. word32 keySz = 0;
  6514. int ret;
  6515. if (output == NULL || key == NULL) {
  6516. return BAD_FUNC_ARG;
  6517. }
  6518. if (withAlg) {
  6519. /* buffer space for algorithm */
  6520. infoSz += MAX_SEQ_SZ;
  6521. infoSz += MAX_ALGO_SZ;
  6522. /* buffer space for public key sequence */
  6523. infoSz += MAX_SEQ_SZ;
  6524. infoSz += TRAILING_ZERO;
  6525. }
  6526. if ((ret = wc_ed25519_export_public(key, output, &keySz)) != BUFFER_E) {
  6527. WOLFSSL_MSG("Error in getting ECC public key size");
  6528. return ret;
  6529. }
  6530. if (inLen < keySz + infoSz) {
  6531. return BUFFER_E;
  6532. }
  6533. return SetEd25519PublicKey(output, key, withAlg);
  6534. }
  6535. #endif /* HAVE_ED25519 && (WOLFSSL_CERT_GEN || WOLFSSL_KEY_GEN) */
  6536. #ifdef WOLFSSL_CERT_GEN
  6537. static INLINE byte itob(int number)
  6538. {
  6539. return (byte)number + 0x30;
  6540. }
  6541. /* write time to output, format */
  6542. static void SetTime(struct tm* date, byte* output)
  6543. {
  6544. int i = 0;
  6545. output[i++] = itob((date->tm_year % 10000) / 1000);
  6546. output[i++] = itob((date->tm_year % 1000) / 100);
  6547. output[i++] = itob((date->tm_year % 100) / 10);
  6548. output[i++] = itob( date->tm_year % 10);
  6549. output[i++] = itob(date->tm_mon / 10);
  6550. output[i++] = itob(date->tm_mon % 10);
  6551. output[i++] = itob(date->tm_mday / 10);
  6552. output[i++] = itob(date->tm_mday % 10);
  6553. output[i++] = itob(date->tm_hour / 10);
  6554. output[i++] = itob(date->tm_hour % 10);
  6555. output[i++] = itob(date->tm_min / 10);
  6556. output[i++] = itob(date->tm_min % 10);
  6557. output[i++] = itob(date->tm_sec / 10);
  6558. output[i++] = itob(date->tm_sec % 10);
  6559. output[i] = 'Z'; /* Zulu profile */
  6560. }
  6561. #ifdef WOLFSSL_ALT_NAMES
  6562. /* Copy Dates from cert, return bytes written */
  6563. static int CopyValidity(byte* output, Cert* cert)
  6564. {
  6565. int seqSz;
  6566. WOLFSSL_ENTER("CopyValidity");
  6567. /* headers and output */
  6568. seqSz = SetSequence(cert->beforeDateSz + cert->afterDateSz, output);
  6569. XMEMCPY(output + seqSz, cert->beforeDate, cert->beforeDateSz);
  6570. XMEMCPY(output + seqSz + cert->beforeDateSz, cert->afterDate,
  6571. cert->afterDateSz);
  6572. return seqSz + cert->beforeDateSz + cert->afterDateSz;
  6573. }
  6574. #endif
  6575. /* for systems where mktime() doesn't normalize fully */
  6576. static void RebuildTime(time_t* in, struct tm* out)
  6577. {
  6578. #if defined(FREESCALE_MQX) || defined(FREESCALE_KSDK_MQX)
  6579. out = localtime_r(in, out);
  6580. #else
  6581. (void)in;
  6582. (void)out;
  6583. #endif
  6584. }
  6585. /* Set Date validity from now until now + daysValid
  6586. * return size in bytes written to output, 0 on error */
  6587. static int SetValidity(byte* output, int daysValid)
  6588. {
  6589. byte before[MAX_DATE_SIZE];
  6590. byte after[MAX_DATE_SIZE];
  6591. int beforeSz;
  6592. int afterSz;
  6593. int seqSz;
  6594. time_t ticks;
  6595. time_t normalTime;
  6596. struct tm* now;
  6597. struct tm* tmpTime = NULL;
  6598. struct tm local;
  6599. #if defined(NEED_TMP_TIME)
  6600. /* for use with gmtime_r */
  6601. struct tm tmpTimeStorage;
  6602. tmpTime = &tmpTimeStorage;
  6603. #else
  6604. (void)tmpTime;
  6605. #endif
  6606. ticks = XTIME(0);
  6607. now = XGMTIME(&ticks, tmpTime);
  6608. if (now == NULL) {
  6609. WOLFSSL_MSG("XGMTIME failed");
  6610. return 0; /* error */
  6611. }
  6612. /* before now */
  6613. local = *now;
  6614. before[0] = ASN_GENERALIZED_TIME;
  6615. beforeSz = SetLength(ASN_GEN_TIME_SZ, before + 1) + 1; /* gen tag */
  6616. /* subtract 1 day for more compliance */
  6617. local.tm_mday -= 1;
  6618. normalTime = mktime(&local);
  6619. RebuildTime(&normalTime, &local);
  6620. /* adjust */
  6621. local.tm_year += 1900;
  6622. local.tm_mon += 1;
  6623. SetTime(&local, before + beforeSz);
  6624. beforeSz += ASN_GEN_TIME_SZ;
  6625. /* after now + daysValid */
  6626. local = *now;
  6627. after[0] = ASN_GENERALIZED_TIME;
  6628. afterSz = SetLength(ASN_GEN_TIME_SZ, after + 1) + 1; /* gen tag */
  6629. /* add daysValid */
  6630. local.tm_mday += daysValid;
  6631. normalTime = mktime(&local);
  6632. RebuildTime(&normalTime, &local);
  6633. /* adjust */
  6634. local.tm_year += 1900;
  6635. local.tm_mon += 1;
  6636. SetTime(&local, after + afterSz);
  6637. afterSz += ASN_GEN_TIME_SZ;
  6638. /* headers and output */
  6639. seqSz = SetSequence(beforeSz + afterSz, output);
  6640. XMEMCPY(output + seqSz, before, beforeSz);
  6641. XMEMCPY(output + seqSz + beforeSz, after, afterSz);
  6642. return seqSz + beforeSz + afterSz;
  6643. }
  6644. /* ASN Encoded Name field */
  6645. typedef struct EncodedName {
  6646. int nameLen; /* actual string value length */
  6647. int totalLen; /* total encoded length */
  6648. int type; /* type of name */
  6649. int used; /* are we actually using this one */
  6650. byte encoded[CTC_NAME_SIZE * 2]; /* encoding */
  6651. } EncodedName;
  6652. /* Get Which Name from index */
  6653. static const char* GetOneName(CertName* name, int idx)
  6654. {
  6655. switch (idx) {
  6656. case 0:
  6657. return name->country;
  6658. case 1:
  6659. return name->state;
  6660. case 2:
  6661. return name->locality;
  6662. case 3:
  6663. return name->sur;
  6664. case 4:
  6665. return name->org;
  6666. case 5:
  6667. return name->unit;
  6668. case 6:
  6669. return name->commonName;
  6670. case 7:
  6671. return name->email;
  6672. default:
  6673. return 0;
  6674. }
  6675. }
  6676. /* Get Which Name Encoding from index */
  6677. static char GetNameType(CertName* name, int idx)
  6678. {
  6679. switch (idx) {
  6680. case 0:
  6681. return name->countryEnc;
  6682. case 1:
  6683. return name->stateEnc;
  6684. case 2:
  6685. return name->localityEnc;
  6686. case 3:
  6687. return name->surEnc;
  6688. case 4:
  6689. return name->orgEnc;
  6690. case 5:
  6691. return name->unitEnc;
  6692. case 6:
  6693. return name->commonNameEnc;
  6694. default:
  6695. return 0;
  6696. }
  6697. }
  6698. /* Get ASN Name from index */
  6699. static byte GetNameId(int idx)
  6700. {
  6701. switch (idx) {
  6702. case 0:
  6703. return ASN_COUNTRY_NAME;
  6704. case 1:
  6705. return ASN_STATE_NAME;
  6706. case 2:
  6707. return ASN_LOCALITY_NAME;
  6708. case 3:
  6709. return ASN_SUR_NAME;
  6710. case 4:
  6711. return ASN_ORG_NAME;
  6712. case 5:
  6713. return ASN_ORGUNIT_NAME;
  6714. case 6:
  6715. return ASN_COMMON_NAME;
  6716. case 7:
  6717. /* email uses different id type */
  6718. return 0;
  6719. default:
  6720. return 0;
  6721. }
  6722. }
  6723. /*
  6724. Extensions ::= SEQUENCE OF Extension
  6725. Extension ::= SEQUENCE {
  6726. extnId OBJECT IDENTIFIER,
  6727. critical BOOLEAN DEFAULT FALSE,
  6728. extnValue OCTET STRING }
  6729. */
  6730. /* encode all extensions, return total bytes written */
  6731. static int SetExtensions(byte* out, word32 outSz, int *IdxInOut,
  6732. const byte* ext, int extSz)
  6733. {
  6734. if (out == NULL || IdxInOut == NULL || ext == NULL)
  6735. return BAD_FUNC_ARG;
  6736. if (outSz < (word32)(*IdxInOut+extSz))
  6737. return BUFFER_E;
  6738. XMEMCPY(&out[*IdxInOut], ext, extSz); /* extensions */
  6739. *IdxInOut += extSz;
  6740. return *IdxInOut;
  6741. }
  6742. /* encode extensions header, return total bytes written */
  6743. static int SetExtensionsHeader(byte* out, word32 outSz, int extSz)
  6744. {
  6745. byte sequence[MAX_SEQ_SZ];
  6746. byte len[MAX_LENGTH_SZ];
  6747. int seqSz, lenSz, idx = 0;
  6748. if (out == NULL)
  6749. return BAD_FUNC_ARG;
  6750. if (outSz < 3)
  6751. return BUFFER_E;
  6752. seqSz = SetSequence(extSz, sequence);
  6753. /* encode extensions length provided */
  6754. lenSz = SetLength(extSz+seqSz, len);
  6755. if (outSz < (word32)(lenSz+seqSz+1))
  6756. return BUFFER_E;
  6757. out[idx++] = ASN_EXTENSIONS; /* extensions id */
  6758. XMEMCPY(&out[idx], len, lenSz); /* length */
  6759. idx += lenSz;
  6760. XMEMCPY(&out[idx], sequence, seqSz); /* sequence */
  6761. idx += seqSz;
  6762. return idx;
  6763. }
  6764. /* encode CA basic constraint true, return total bytes written */
  6765. static int SetCa(byte* out, word32 outSz)
  6766. {
  6767. static const byte ca[] = { 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04,
  6768. 0x05, 0x30, 0x03, 0x01, 0x01, 0xff };
  6769. if (out == NULL)
  6770. return BAD_FUNC_ARG;
  6771. if (outSz < sizeof(ca))
  6772. return BUFFER_E;
  6773. XMEMCPY(out, ca, sizeof(ca));
  6774. return (int)sizeof(ca);
  6775. }
  6776. #ifdef WOLFSSL_CERT_EXT
  6777. /* encode OID and associated value, return total bytes written */
  6778. static int SetOidValue(byte* out, word32 outSz, const byte *oid, word32 oidSz,
  6779. byte *in, word32 inSz)
  6780. {
  6781. int idx = 0;
  6782. if (out == NULL || oid == NULL || in == NULL)
  6783. return BAD_FUNC_ARG;
  6784. if (outSz < 3)
  6785. return BUFFER_E;
  6786. /* sequence, + 1 => byte to put value size */
  6787. idx = SetSequence(inSz + oidSz + 1, out);
  6788. if ((idx + inSz + oidSz + 1) > outSz)
  6789. return BUFFER_E;
  6790. XMEMCPY(out+idx, oid, oidSz);
  6791. idx += oidSz;
  6792. out[idx++] = (byte)inSz;
  6793. XMEMCPY(out+idx, in, inSz);
  6794. return (idx+inSz);
  6795. }
  6796. /* encode Subject Key Identifier, return total bytes written
  6797. * RFC5280 : non-critical */
  6798. static int SetSKID(byte* output, word32 outSz, const byte *input, word32 length)
  6799. {
  6800. byte skid_len[1 + MAX_LENGTH_SZ];
  6801. byte skid_enc_len[MAX_LENGTH_SZ];
  6802. int idx = 0, skid_lenSz, skid_enc_lenSz;
  6803. static const byte skid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04 };
  6804. if (output == NULL || input == NULL)
  6805. return BAD_FUNC_ARG;
  6806. /* Octet String header */
  6807. skid_lenSz = SetOctetString(length, skid_len);
  6808. /* length of encoded value */
  6809. skid_enc_lenSz = SetLength(length + skid_lenSz, skid_enc_len);
  6810. if (outSz < 3)
  6811. return BUFFER_E;
  6812. idx = SetSequence(length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz,
  6813. output);
  6814. if ((length + sizeof(skid_oid) + skid_lenSz + skid_enc_lenSz) > outSz)
  6815. return BUFFER_E;
  6816. /* put oid */
  6817. XMEMCPY(output+idx, skid_oid, sizeof(skid_oid));
  6818. idx += sizeof(skid_oid);
  6819. /* put encoded len */
  6820. XMEMCPY(output+idx, skid_enc_len, skid_enc_lenSz);
  6821. idx += skid_enc_lenSz;
  6822. /* put octet header */
  6823. XMEMCPY(output+idx, skid_len, skid_lenSz);
  6824. idx += skid_lenSz;
  6825. /* put value */
  6826. XMEMCPY(output+idx, input, length);
  6827. idx += length;
  6828. return idx;
  6829. }
  6830. /* encode Authority Key Identifier, return total bytes written
  6831. * RFC5280 : non-critical */
  6832. static int SetAKID(byte* output, word32 outSz,
  6833. byte *input, word32 length, void* heap)
  6834. {
  6835. byte *enc_val;
  6836. int ret, enc_valSz;
  6837. static const byte akid_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04 };
  6838. static const byte akid_cs[] = { 0x80 };
  6839. if (output == NULL || input == NULL)
  6840. return BAD_FUNC_ARG;
  6841. enc_valSz = length + 3 + sizeof(akid_cs);
  6842. enc_val = (byte *)XMALLOC(enc_valSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6843. if (enc_val == NULL)
  6844. return MEMORY_E;
  6845. /* sequence for ContentSpec & value */
  6846. ret = SetOidValue(enc_val, enc_valSz, akid_cs, sizeof(akid_cs),
  6847. input, length);
  6848. if (ret > 0) {
  6849. enc_valSz = ret;
  6850. ret = SetOidValue(output, outSz, akid_oid, sizeof(akid_oid),
  6851. enc_val, enc_valSz);
  6852. }
  6853. XFREE(enc_val, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6854. return ret;
  6855. }
  6856. /* encode Key Usage, return total bytes written
  6857. * RFC5280 : critical */
  6858. static int SetKeyUsage(byte* output, word32 outSz, word16 input)
  6859. {
  6860. byte ku[5];
  6861. int idx;
  6862. static const byte keyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x0f,
  6863. 0x01, 0x01, 0xff, 0x04};
  6864. if (output == NULL)
  6865. return BAD_FUNC_ARG;
  6866. idx = SetBitString16Bit(input, ku);
  6867. return SetOidValue(output, outSz, keyusage_oid, sizeof(keyusage_oid),
  6868. ku, idx);
  6869. }
  6870. static int SetOjectIdValue(byte* output, word32 outSz, int* idx,
  6871. const byte* oid, word32 oidSz)
  6872. {
  6873. /* verify room */
  6874. if (*idx + 2 + oidSz >= outSz)
  6875. return ASN_PARSE_E;
  6876. *idx += SetObjectId(oidSz, &output[*idx]);
  6877. XMEMCPY(&output[*idx], oid, oidSz);
  6878. *idx += oidSz;
  6879. return 0;
  6880. }
  6881. /* encode Extended Key Usage (RFC 5280 4.2.1.12), return total bytes written */
  6882. static int SetExtKeyUsage(byte* output, word32 outSz, byte input)
  6883. {
  6884. int idx = 0, oidListSz = 0, totalSz, ret = 0;
  6885. static const byte extkeyusage_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x25 };
  6886. if (output == NULL)
  6887. return BAD_FUNC_ARG;
  6888. /* Skip to OID List */
  6889. totalSz = 2 + sizeof(extkeyusage_oid) + 4;
  6890. idx = totalSz;
  6891. /* Build OID List */
  6892. /* If any set, then just use it */
  6893. if (input & EXTKEYUSE_ANY) {
  6894. ret |= SetOjectIdValue(output, outSz, &idx,
  6895. extExtKeyUsageAnyOid, sizeof(extExtKeyUsageAnyOid));
  6896. }
  6897. else {
  6898. if (input & EXTKEYUSE_SERVER_AUTH)
  6899. ret |= SetOjectIdValue(output, outSz, &idx,
  6900. extExtKeyUsageServerAuthOid, sizeof(extExtKeyUsageServerAuthOid));
  6901. if (input & EXTKEYUSE_CLIENT_AUTH)
  6902. ret |= SetOjectIdValue(output, outSz, &idx,
  6903. extExtKeyUsageClientAuthOid, sizeof(extExtKeyUsageClientAuthOid));
  6904. if (input & EXTKEYUSE_CODESIGN)
  6905. ret |= SetOjectIdValue(output, outSz, &idx,
  6906. extExtKeyUsageCodeSigningOid, sizeof(extExtKeyUsageCodeSigningOid));
  6907. if (input & EXTKEYUSE_EMAILPROT)
  6908. ret |= SetOjectIdValue(output, outSz, &idx,
  6909. extExtKeyUsageEmailProtectOid, sizeof(extExtKeyUsageEmailProtectOid));
  6910. if (input & EXTKEYUSE_TIMESTAMP)
  6911. ret |= SetOjectIdValue(output, outSz, &idx,
  6912. extExtKeyUsageTimestampOid, sizeof(extExtKeyUsageTimestampOid));
  6913. if (input & EXTKEYUSE_OCSP_SIGN)
  6914. ret |= SetOjectIdValue(output, outSz, &idx,
  6915. extExtKeyUsageOcspSignOid, sizeof(extExtKeyUsageOcspSignOid));
  6916. }
  6917. if (ret != 0)
  6918. return ASN_PARSE_E;
  6919. /* Calculate Sizes */
  6920. oidListSz = idx - totalSz;
  6921. totalSz = idx - 2; /* exclude first seq/len (2) */
  6922. /* 1. Seq + Total Len (2) */
  6923. idx = SetSequence(totalSz, output);
  6924. /* 2. Object ID (2) */
  6925. XMEMCPY(&output[idx], extkeyusage_oid, sizeof(extkeyusage_oid));
  6926. idx += sizeof(extkeyusage_oid);
  6927. /* 3. Octect String (2) */
  6928. idx += SetOctetString(totalSz - idx, &output[idx]);
  6929. /* 4. Seq + OidListLen (2) */
  6930. idx += SetSequence(oidListSz, &output[idx]);
  6931. /* 5. Oid List (already set in-place above) */
  6932. idx += oidListSz;
  6933. return idx;
  6934. }
  6935. /* Encode OID string representation to ITU-T X.690 format */
  6936. static int EncodePolicyOID(byte *out, word32 *outSz, const char *in, void* heap)
  6937. {
  6938. word32 val, idx = 0, nb_val;
  6939. char *token, *str, *ptr;
  6940. word32 len;
  6941. if (out == NULL || outSz == NULL || *outSz < 2 || in == NULL)
  6942. return BAD_FUNC_ARG;
  6943. len = (word32)XSTRLEN(in);
  6944. str = (char *)XMALLOC(len+1, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6945. if (str == NULL)
  6946. return MEMORY_E;
  6947. XSTRNCPY(str, in, len);
  6948. str[len] = 0x00;
  6949. nb_val = 0;
  6950. /* parse value, and set corresponding Policy OID value */
  6951. token = XSTRTOK(str, ".", &ptr);
  6952. while (token != NULL)
  6953. {
  6954. val = (word32)atoi(token);
  6955. if (nb_val == 0) {
  6956. if (val > 2) {
  6957. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6958. return ASN_OBJECT_ID_E;
  6959. }
  6960. out[idx] = (byte)(40 * val);
  6961. }
  6962. else if (nb_val == 1) {
  6963. if (val > 127) {
  6964. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6965. return ASN_OBJECT_ID_E;
  6966. }
  6967. if (idx > *outSz) {
  6968. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6969. return BUFFER_E;
  6970. }
  6971. out[idx++] += (byte)val;
  6972. }
  6973. else {
  6974. word32 tb = 0, x;
  6975. int i = 0;
  6976. byte oid[MAX_OID_SZ];
  6977. while (val >= 128) {
  6978. x = val % 128;
  6979. val /= 128;
  6980. oid[i++] = (byte) (((tb++) ? 0x80 : 0) | x);
  6981. }
  6982. if ((idx+(word32)i) > *outSz) {
  6983. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6984. return BUFFER_E;
  6985. }
  6986. oid[i] = (byte) (((tb++) ? 0x80 : 0) | val);
  6987. /* push value in the right order */
  6988. while (i >= 0)
  6989. out[idx++] = oid[i--];
  6990. }
  6991. token = XSTRTOK(NULL, ".", &ptr);
  6992. nb_val++;
  6993. }
  6994. *outSz = idx;
  6995. XFREE(str, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6996. return 0;
  6997. }
  6998. /* encode Certificate Policies, return total bytes written
  6999. * each input value must be ITU-T X.690 formatted : a.b.c...
  7000. * input must be an array of values with a NULL terminated for the latest
  7001. * RFC5280 : non-critical */
  7002. static int SetCertificatePolicies(byte *output,
  7003. word32 outputSz,
  7004. char input[MAX_CERTPOL_NB][MAX_CERTPOL_SZ],
  7005. word16 nb_certpol,
  7006. void* heap)
  7007. {
  7008. byte oid[MAX_OID_SZ],
  7009. der_oid[MAX_CERTPOL_NB][MAX_OID_SZ],
  7010. out[MAX_CERTPOL_SZ];
  7011. word32 oidSz;
  7012. word32 outSz, i = 0, der_oidSz[MAX_CERTPOL_NB];
  7013. int ret;
  7014. static const byte certpol_oid[] = { 0x06, 0x03, 0x55, 0x1d, 0x20, 0x04 };
  7015. static const byte oid_oid[] = { 0x06 };
  7016. if (output == NULL || input == NULL || nb_certpol > MAX_CERTPOL_NB)
  7017. return BAD_FUNC_ARG;
  7018. for (i = 0; i < nb_certpol; i++) {
  7019. oidSz = sizeof(oid);
  7020. XMEMSET(oid, 0, oidSz);
  7021. ret = EncodePolicyOID(oid, &oidSz, input[i], heap);
  7022. if (ret != 0)
  7023. return ret;
  7024. /* compute sequence value for the oid */
  7025. ret = SetOidValue(der_oid[i], MAX_OID_SZ, oid_oid,
  7026. sizeof(oid_oid), oid, oidSz);
  7027. if (ret <= 0)
  7028. return ret;
  7029. else
  7030. der_oidSz[i] = (word32)ret;
  7031. }
  7032. /* concatenate oid, keep two byte for sequence/size of the created value */
  7033. for (i = 0, outSz = 2; i < nb_certpol; i++) {
  7034. XMEMCPY(out+outSz, der_oid[i], der_oidSz[i]);
  7035. outSz += der_oidSz[i];
  7036. }
  7037. /* add sequence */
  7038. ret = SetSequence(outSz-2, out);
  7039. if (ret <= 0)
  7040. return ret;
  7041. /* add Policy OID to compute final value */
  7042. return SetOidValue(output, outputSz, certpol_oid, sizeof(certpol_oid),
  7043. out, outSz);
  7044. }
  7045. #endif /* WOLFSSL_CERT_EXT */
  7046. #ifdef WOLFSSL_ALT_NAMES
  7047. /* encode Alternative Names, return total bytes written */
  7048. static int SetAltNames(byte *out, word32 outSz, byte *input, word32 length)
  7049. {
  7050. if (out == NULL || input == NULL)
  7051. return BAD_FUNC_ARG;
  7052. if (outSz < length)
  7053. return BUFFER_E;
  7054. /* Alternative Names come from certificate or computed by
  7055. * external function, so already encoded. Just copy value */
  7056. XMEMCPY(out, input, length);
  7057. return length;
  7058. }
  7059. #endif /* WOLFSL_ALT_NAMES */
  7060. /* encode CertName into output, return total bytes written */
  7061. int SetName(byte* output, word32 outputSz, CertName* name)
  7062. {
  7063. int totalBytes = 0, i, idx;
  7064. #ifdef WOLFSSL_SMALL_STACK
  7065. EncodedName* names = NULL;
  7066. #else
  7067. EncodedName names[NAME_ENTRIES];
  7068. #endif
  7069. if (output == NULL || name == NULL)
  7070. return BAD_FUNC_ARG;
  7071. if (outputSz < 3)
  7072. return BUFFER_E;
  7073. #ifdef WOLFSSL_SMALL_STACK
  7074. names = (EncodedName*)XMALLOC(sizeof(EncodedName) * NAME_ENTRIES, NULL,
  7075. DYNAMIC_TYPE_TMP_BUFFER);
  7076. if (names == NULL)
  7077. return MEMORY_E;
  7078. #endif
  7079. for (i = 0; i < NAME_ENTRIES; i++) {
  7080. const char* nameStr = GetOneName(name, i);
  7081. if (nameStr) {
  7082. /* bottom up */
  7083. byte firstLen[1 + MAX_LENGTH_SZ];
  7084. byte secondLen[MAX_LENGTH_SZ];
  7085. byte sequence[MAX_SEQ_SZ];
  7086. byte set[MAX_SET_SZ];
  7087. int email = i == (NAME_ENTRIES - 1) ? 1 : 0;
  7088. int strLen = (int)XSTRLEN(nameStr);
  7089. int thisLen = strLen;
  7090. int firstSz, secondSz, seqSz, setSz;
  7091. if (strLen == 0) { /* no user data for this item */
  7092. names[i].used = 0;
  7093. continue;
  7094. }
  7095. /* Restrict country code size */
  7096. if (i == 0 && strLen != CTC_COUNTRY_SIZE) {
  7097. #ifdef WOLFSSL_SMALL_STACK
  7098. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7099. #endif
  7100. return ASN_COUNTRY_SIZE_E;
  7101. }
  7102. secondSz = SetLength(strLen, secondLen);
  7103. thisLen += secondSz;
  7104. if (email) {
  7105. thisLen += EMAIL_JOINT_LEN;
  7106. thisLen ++; /* id type */
  7107. firstSz = SetObjectId(EMAIL_JOINT_LEN, firstLen);
  7108. }
  7109. else {
  7110. thisLen++; /* str type */
  7111. thisLen++; /* id type */
  7112. thisLen += JOINT_LEN;
  7113. firstSz = SetObjectId(JOINT_LEN + 1, firstLen);
  7114. }
  7115. thisLen += firstSz;
  7116. seqSz = SetSequence(thisLen, sequence);
  7117. thisLen += seqSz;
  7118. setSz = SetSet(thisLen, set);
  7119. thisLen += setSz;
  7120. if (thisLen > (int)sizeof(names[i].encoded)) {
  7121. #ifdef WOLFSSL_SMALL_STACK
  7122. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7123. #endif
  7124. return BUFFER_E;
  7125. }
  7126. /* store it */
  7127. idx = 0;
  7128. /* set */
  7129. XMEMCPY(names[i].encoded, set, setSz);
  7130. idx += setSz;
  7131. /* seq */
  7132. XMEMCPY(names[i].encoded + idx, sequence, seqSz);
  7133. idx += seqSz;
  7134. /* asn object id */
  7135. XMEMCPY(names[i].encoded + idx, firstLen, firstSz);
  7136. idx += firstSz;
  7137. if (email) {
  7138. const byte EMAIL_OID[] = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d,
  7139. 0x01, 0x09, 0x01, 0x16 };
  7140. /* email joint id */
  7141. XMEMCPY(names[i].encoded + idx, EMAIL_OID, sizeof(EMAIL_OID));
  7142. idx += (int)sizeof(EMAIL_OID);
  7143. }
  7144. else {
  7145. /* joint id */
  7146. byte bType = GetNameId(i);
  7147. names[i].encoded[idx++] = 0x55;
  7148. names[i].encoded[idx++] = 0x04;
  7149. /* id type */
  7150. names[i].encoded[idx++] = bType;
  7151. /* str type */
  7152. names[i].encoded[idx++] = GetNameType(name, i);
  7153. }
  7154. /* second length */
  7155. XMEMCPY(names[i].encoded + idx, secondLen, secondSz);
  7156. idx += secondSz;
  7157. /* str value */
  7158. XMEMCPY(names[i].encoded + idx, nameStr, strLen);
  7159. idx += strLen;
  7160. totalBytes += idx;
  7161. names[i].totalLen = idx;
  7162. names[i].used = 1;
  7163. }
  7164. else
  7165. names[i].used = 0;
  7166. }
  7167. /* header */
  7168. idx = SetSequence(totalBytes, output);
  7169. totalBytes += idx;
  7170. if (totalBytes > ASN_NAME_MAX) {
  7171. #ifdef WOLFSSL_SMALL_STACK
  7172. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7173. #endif
  7174. return BUFFER_E;
  7175. }
  7176. for (i = 0; i < NAME_ENTRIES; i++) {
  7177. if (names[i].used) {
  7178. if (outputSz < (word32)(idx+names[i].totalLen)) {
  7179. #ifdef WOLFSSL_SMALL_STACK
  7180. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7181. #endif
  7182. return BUFFER_E;
  7183. }
  7184. XMEMCPY(output + idx, names[i].encoded, names[i].totalLen);
  7185. idx += names[i].totalLen;
  7186. }
  7187. }
  7188. #ifdef WOLFSSL_SMALL_STACK
  7189. XFREE(names, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7190. #endif
  7191. return totalBytes;
  7192. }
  7193. /* encode info from cert into DER encoded format */
  7194. static int EncodeCert(Cert* cert, DerCert* der, RsaKey* rsaKey, ecc_key* eccKey,
  7195. WC_RNG* rng, const byte* ntruKey, word16 ntruSz,
  7196. ed25519_key* ed25519Key)
  7197. {
  7198. int ret;
  7199. if (cert == NULL || der == NULL || rng == NULL)
  7200. return BAD_FUNC_ARG;
  7201. /* make sure at least one key type is provided */
  7202. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL && ntruKey == NULL)
  7203. return PUBLIC_KEY_E;
  7204. /* init */
  7205. XMEMSET(der, 0, sizeof(DerCert));
  7206. /* version */
  7207. der->versionSz = SetMyVersion(cert->version, der->version, TRUE);
  7208. /* serial number (must be positive) */
  7209. if (cert->serialSz == 0) {
  7210. /* generate random serial */
  7211. cert->serialSz = CTC_SERIAL_SIZE;
  7212. ret = wc_RNG_GenerateBlock(rng, cert->serial, cert->serialSz);
  7213. if (ret != 0)
  7214. return ret;
  7215. }
  7216. der->serialSz = SetSerialNumber(cert->serial, cert->serialSz, der->serial,
  7217. CTC_SERIAL_SIZE);
  7218. if (der->serialSz < 0)
  7219. return der->serialSz;
  7220. /* signature algo */
  7221. der->sigAlgoSz = SetAlgoID(cert->sigType, der->sigAlgo, oidSigType, 0);
  7222. if (der->sigAlgoSz <= 0)
  7223. return ALGO_ID_E;
  7224. /* public key */
  7225. #ifndef NO_RSA
  7226. if (cert->keyType == RSA_KEY) {
  7227. if (rsaKey == NULL)
  7228. return PUBLIC_KEY_E;
  7229. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  7230. sizeof(der->publicKey), 1);
  7231. }
  7232. #endif
  7233. #ifdef HAVE_ECC
  7234. if (cert->keyType == ECC_KEY) {
  7235. if (eccKey == NULL)
  7236. return PUBLIC_KEY_E;
  7237. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey, 1);
  7238. }
  7239. #endif
  7240. #ifdef HAVE_ED25519
  7241. if (cert->keyType == ED25519_KEY) {
  7242. if (ed25519Key == NULL)
  7243. return PUBLIC_KEY_E;
  7244. der->publicKeySz = SetEd25519PublicKey(der->publicKey, ed25519Key, 1);
  7245. }
  7246. #endif
  7247. #ifdef HAVE_NTRU
  7248. if (cert->keyType == NTRU_KEY) {
  7249. word32 rc;
  7250. word16 encodedSz;
  7251. if (ntruKey == NULL)
  7252. return PUBLIC_KEY_E;
  7253. rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo(ntruSz,
  7254. ntruKey, &encodedSz, NULL);
  7255. if (rc != NTRU_OK)
  7256. return PUBLIC_KEY_E;
  7257. if (encodedSz > MAX_PUBLIC_KEY_SZ)
  7258. return PUBLIC_KEY_E;
  7259. rc = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo(ntruSz,
  7260. ntruKey, &encodedSz, der->publicKey);
  7261. if (rc != NTRU_OK)
  7262. return PUBLIC_KEY_E;
  7263. der->publicKeySz = encodedSz;
  7264. }
  7265. #else
  7266. (void)ntruSz;
  7267. #endif /* HAVE_NTRU */
  7268. if (der->publicKeySz <= 0)
  7269. return PUBLIC_KEY_E;
  7270. der->validitySz = 0;
  7271. #ifdef WOLFSSL_ALT_NAMES
  7272. /* date validity copy ? */
  7273. if (cert->beforeDateSz && cert->afterDateSz) {
  7274. der->validitySz = CopyValidity(der->validity, cert);
  7275. if (der->validitySz <= 0)
  7276. return DATE_E;
  7277. }
  7278. #endif
  7279. /* date validity */
  7280. if (der->validitySz == 0) {
  7281. der->validitySz = SetValidity(der->validity, cert->daysValid);
  7282. if (der->validitySz <= 0)
  7283. return DATE_E;
  7284. }
  7285. /* subject name */
  7286. der->subjectSz = SetName(der->subject, sizeof(der->subject), &cert->subject);
  7287. if (der->subjectSz <= 0)
  7288. return SUBJECT_E;
  7289. /* issuer name */
  7290. der->issuerSz = SetName(der->issuer, sizeof(der->issuer), cert->selfSigned ?
  7291. &cert->subject : &cert->issuer);
  7292. if (der->issuerSz <= 0)
  7293. return ISSUER_E;
  7294. /* set the extensions */
  7295. der->extensionsSz = 0;
  7296. /* CA */
  7297. if (cert->isCA) {
  7298. der->caSz = SetCa(der->ca, sizeof(der->ca));
  7299. if (der->caSz <= 0)
  7300. return CA_TRUE_E;
  7301. der->extensionsSz += der->caSz;
  7302. }
  7303. else
  7304. der->caSz = 0;
  7305. #ifdef WOLFSSL_ALT_NAMES
  7306. /* Alternative Name */
  7307. if (cert->altNamesSz) {
  7308. der->altNamesSz = SetAltNames(der->altNames, sizeof(der->altNames),
  7309. cert->altNames, cert->altNamesSz);
  7310. if (der->altNamesSz <= 0)
  7311. return ALT_NAME_E;
  7312. der->extensionsSz += der->altNamesSz;
  7313. }
  7314. else
  7315. der->altNamesSz = 0;
  7316. #endif
  7317. #ifdef WOLFSSL_CERT_EXT
  7318. /* SKID */
  7319. if (cert->skidSz) {
  7320. /* check the provided SKID size */
  7321. if (cert->skidSz > (int)sizeof(der->skid))
  7322. return SKID_E;
  7323. /* Note: different skid buffers sizes for der (MAX_KID_SZ) and
  7324. cert (CTC_MAX_SKID_SIZE). */
  7325. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  7326. cert->skid, cert->skidSz);
  7327. if (der->skidSz <= 0)
  7328. return SKID_E;
  7329. der->extensionsSz += der->skidSz;
  7330. }
  7331. else
  7332. der->skidSz = 0;
  7333. /* AKID */
  7334. if (cert->akidSz) {
  7335. /* check the provided AKID size */
  7336. if (cert->akidSz > (int)sizeof(der->akid))
  7337. return AKID_E;
  7338. der->akidSz = SetAKID(der->akid, sizeof(der->akid),
  7339. cert->akid, cert->akidSz, cert->heap);
  7340. if (der->akidSz <= 0)
  7341. return AKID_E;
  7342. der->extensionsSz += der->akidSz;
  7343. }
  7344. else
  7345. der->akidSz = 0;
  7346. /* Key Usage */
  7347. if (cert->keyUsage != 0){
  7348. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  7349. cert->keyUsage);
  7350. if (der->keyUsageSz <= 0)
  7351. return KEYUSAGE_E;
  7352. der->extensionsSz += der->keyUsageSz;
  7353. }
  7354. else
  7355. der->keyUsageSz = 0;
  7356. /* Extended Key Usage */
  7357. if (cert->extKeyUsage != 0){
  7358. der->extKeyUsageSz = SetExtKeyUsage(der->extKeyUsage,
  7359. sizeof(der->extKeyUsage), cert->extKeyUsage);
  7360. if (der->extKeyUsageSz <= 0)
  7361. return EXTKEYUSAGE_E;
  7362. der->extensionsSz += der->extKeyUsageSz;
  7363. }
  7364. else
  7365. der->extKeyUsageSz = 0;
  7366. /* Certificate Policies */
  7367. if (cert->certPoliciesNb != 0) {
  7368. der->certPoliciesSz = SetCertificatePolicies(der->certPolicies,
  7369. sizeof(der->certPolicies),
  7370. cert->certPolicies,
  7371. cert->certPoliciesNb,
  7372. cert->heap);
  7373. if (der->certPoliciesSz <= 0)
  7374. return CERTPOLICIES_E;
  7375. der->extensionsSz += der->certPoliciesSz;
  7376. }
  7377. else
  7378. der->certPoliciesSz = 0;
  7379. #endif /* WOLFSSL_CERT_EXT */
  7380. /* put extensions */
  7381. if (der->extensionsSz > 0) {
  7382. /* put the start of extensions sequence (ID, Size) */
  7383. der->extensionsSz = SetExtensionsHeader(der->extensions,
  7384. sizeof(der->extensions),
  7385. der->extensionsSz);
  7386. if (der->extensionsSz <= 0)
  7387. return EXTENSIONS_E;
  7388. /* put CA */
  7389. if (der->caSz) {
  7390. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7391. &der->extensionsSz,
  7392. der->ca, der->caSz);
  7393. if (ret == 0)
  7394. return EXTENSIONS_E;
  7395. }
  7396. #ifdef WOLFSSL_ALT_NAMES
  7397. /* put Alternative Names */
  7398. if (der->altNamesSz) {
  7399. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7400. &der->extensionsSz,
  7401. der->altNames, der->altNamesSz);
  7402. if (ret <= 0)
  7403. return EXTENSIONS_E;
  7404. }
  7405. #endif
  7406. #ifdef WOLFSSL_CERT_EXT
  7407. /* put SKID */
  7408. if (der->skidSz) {
  7409. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7410. &der->extensionsSz,
  7411. der->skid, der->skidSz);
  7412. if (ret <= 0)
  7413. return EXTENSIONS_E;
  7414. }
  7415. /* put AKID */
  7416. if (der->akidSz) {
  7417. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7418. &der->extensionsSz,
  7419. der->akid, der->akidSz);
  7420. if (ret <= 0)
  7421. return EXTENSIONS_E;
  7422. }
  7423. /* put KeyUsage */
  7424. if (der->keyUsageSz) {
  7425. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7426. &der->extensionsSz,
  7427. der->keyUsage, der->keyUsageSz);
  7428. if (ret <= 0)
  7429. return EXTENSIONS_E;
  7430. }
  7431. /* put ExtendedKeyUsage */
  7432. if (der->extKeyUsageSz) {
  7433. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7434. &der->extensionsSz,
  7435. der->extKeyUsage, der->extKeyUsageSz);
  7436. if (ret <= 0)
  7437. return EXTENSIONS_E;
  7438. }
  7439. /* put Certificate Policies */
  7440. if (der->certPoliciesSz) {
  7441. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7442. &der->extensionsSz,
  7443. der->certPolicies, der->certPoliciesSz);
  7444. if (ret <= 0)
  7445. return EXTENSIONS_E;
  7446. }
  7447. #endif /* WOLFSSL_CERT_EXT */
  7448. }
  7449. der->total = der->versionSz + der->serialSz + der->sigAlgoSz +
  7450. der->publicKeySz + der->validitySz + der->subjectSz + der->issuerSz +
  7451. der->extensionsSz;
  7452. return 0;
  7453. }
  7454. /* write DER encoded cert to buffer, size already checked */
  7455. static int WriteCertBody(DerCert* der, byte* buffer)
  7456. {
  7457. int idx;
  7458. /* signed part header */
  7459. idx = SetSequence(der->total, buffer);
  7460. /* version */
  7461. XMEMCPY(buffer + idx, der->version, der->versionSz);
  7462. idx += der->versionSz;
  7463. /* serial */
  7464. XMEMCPY(buffer + idx, der->serial, der->serialSz);
  7465. idx += der->serialSz;
  7466. /* sig algo */
  7467. XMEMCPY(buffer + idx, der->sigAlgo, der->sigAlgoSz);
  7468. idx += der->sigAlgoSz;
  7469. /* issuer */
  7470. XMEMCPY(buffer + idx, der->issuer, der->issuerSz);
  7471. idx += der->issuerSz;
  7472. /* validity */
  7473. XMEMCPY(buffer + idx, der->validity, der->validitySz);
  7474. idx += der->validitySz;
  7475. /* subject */
  7476. XMEMCPY(buffer + idx, der->subject, der->subjectSz);
  7477. idx += der->subjectSz;
  7478. /* public key */
  7479. XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
  7480. idx += der->publicKeySz;
  7481. if (der->extensionsSz) {
  7482. /* extensions */
  7483. XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
  7484. (int)sizeof(der->extensions)));
  7485. idx += der->extensionsSz;
  7486. }
  7487. return idx;
  7488. }
  7489. /* Make RSA signature from buffer (sz), write to sig (sigSz) */
  7490. static int MakeSignature(CertSignCtx* certSignCtx, const byte* buffer, int sz,
  7491. byte* sig, int sigSz, RsaKey* rsaKey, ecc_key* eccKey,
  7492. ed25519_key* ed25519Key, WC_RNG* rng, int sigAlgoType, void* heap)
  7493. {
  7494. int digestSz = 0, typeH = 0, ret = 0;
  7495. (void)digestSz;
  7496. (void)typeH;
  7497. (void)buffer;
  7498. (void)sz;
  7499. (void)sig;
  7500. (void)sigSz;
  7501. (void)rsaKey;
  7502. (void)eccKey;
  7503. (void)ed25519Key;
  7504. (void)rng;
  7505. switch (certSignCtx->state) {
  7506. case CERTSIGN_STATE_BEGIN:
  7507. case CERTSIGN_STATE_DIGEST:
  7508. certSignCtx->state = CERTSIGN_STATE_DIGEST;
  7509. certSignCtx->digest = (byte*)XMALLOC(WC_MAX_DIGEST_SIZE, heap,
  7510. DYNAMIC_TYPE_TMP_BUFFER);
  7511. if (certSignCtx->digest == NULL) {
  7512. ret = MEMORY_E; goto exit_ms;
  7513. }
  7514. ret = HashForSignature(buffer, sz, sigAlgoType, certSignCtx->digest,
  7515. &typeH, &digestSz, 0);
  7516. /* set next state, since WC_PENDING rentry for these are not "call again" */
  7517. certSignCtx->state = CERTSIGN_STATE_ENCODE;
  7518. if (ret != 0) {
  7519. goto exit_ms;
  7520. }
  7521. FALL_THROUGH;
  7522. case CERTSIGN_STATE_ENCODE:
  7523. #ifndef NO_RSA
  7524. if (rsaKey) {
  7525. certSignCtx->encSig = (byte*)XMALLOC(MAX_DER_DIGEST_SZ, heap,
  7526. DYNAMIC_TYPE_TMP_BUFFER);
  7527. if (certSignCtx->encSig == NULL) {
  7528. ret = MEMORY_E; goto exit_ms;
  7529. }
  7530. /* signature */
  7531. certSignCtx->encSigSz = wc_EncodeSignature(certSignCtx->encSig,
  7532. certSignCtx->digest, digestSz, typeH);
  7533. }
  7534. #endif /* !NO_RSA */
  7535. FALL_THROUGH;
  7536. case CERTSIGN_STATE_DO:
  7537. certSignCtx->state = CERTSIGN_STATE_DO;
  7538. ret = ALGO_ID_E; /* default to error */
  7539. #ifndef NO_RSA
  7540. if (rsaKey) {
  7541. /* signature */
  7542. ret = wc_RsaSSL_Sign(certSignCtx->encSig, certSignCtx->encSigSz,
  7543. sig, sigSz, rsaKey, rng);
  7544. }
  7545. #endif /* !NO_RSA */
  7546. #ifdef HAVE_ECC
  7547. if (!rsaKey && eccKey) {
  7548. word32 outSz = sigSz;
  7549. ret = wc_ecc_sign_hash(certSignCtx->digest, digestSz,
  7550. sig, &outSz, rng, eccKey);
  7551. if (ret == 0)
  7552. ret = outSz;
  7553. }
  7554. #endif /* HAVE_ECC */
  7555. #ifdef HAVE_ED25519
  7556. if (!rsaKey && !eccKey && ed25519Key) {
  7557. word32 outSz = sigSz;
  7558. ret = wc_ed25519_sign_msg(buffer, sz, sig, &outSz, ed25519Key);
  7559. if (ret == 0)
  7560. ret = outSz;
  7561. }
  7562. #endif /* HAVE_ECC */
  7563. break;
  7564. }
  7565. exit_ms:
  7566. if (ret == WC_PENDING_E) {
  7567. return ret;
  7568. }
  7569. #ifndef NO_RSA
  7570. if (rsaKey) {
  7571. XFREE(certSignCtx->encSig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7572. }
  7573. #endif /* !NO_RSA */
  7574. XFREE(certSignCtx->digest, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7575. certSignCtx->digest = NULL;
  7576. /* reset state */
  7577. certSignCtx->state = CERTSIGN_STATE_BEGIN;
  7578. return ret;
  7579. }
  7580. /* add signature to end of buffer, size of buffer assumed checked, return
  7581. new length */
  7582. static int AddSignature(byte* buffer, int bodySz, const byte* sig, int sigSz,
  7583. int sigAlgoType)
  7584. {
  7585. byte seq[MAX_SEQ_SZ];
  7586. int idx = bodySz, seqSz;
  7587. /* algo */
  7588. idx += SetAlgoID(sigAlgoType, buffer + idx, oidSigType, 0);
  7589. /* bit string */
  7590. idx += SetBitString(sigSz, 0, buffer + idx);
  7591. /* signature */
  7592. XMEMCPY(buffer + idx, sig, sigSz);
  7593. idx += sigSz;
  7594. /* make room for overall header */
  7595. seqSz = SetSequence(idx, seq);
  7596. XMEMMOVE(buffer + seqSz, buffer, idx);
  7597. XMEMCPY(buffer, seq, seqSz);
  7598. return idx + seqSz;
  7599. }
  7600. /* Make an x509 Certificate v3 any key type from cert input, write to buffer */
  7601. static int MakeAnyCert(Cert* cert, byte* derBuffer, word32 derSz,
  7602. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng,
  7603. const byte* ntruKey, word16 ntruSz,
  7604. ed25519_key* ed25519Key)
  7605. {
  7606. int ret;
  7607. #ifdef WOLFSSL_SMALL_STACK
  7608. DerCert* der;
  7609. #else
  7610. DerCert der[1];
  7611. #endif
  7612. cert->keyType = eccKey ? ECC_KEY : (rsaKey ? RSA_KEY :
  7613. (ed25519Key ? ED25519_KEY : NTRU_KEY));
  7614. #ifdef WOLFSSL_SMALL_STACK
  7615. der = (DerCert*)XMALLOC(sizeof(DerCert), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7616. if (der == NULL)
  7617. return MEMORY_E;
  7618. #endif
  7619. ret = EncodeCert(cert, der, rsaKey, eccKey, rng, ntruKey, ntruSz,
  7620. ed25519Key);
  7621. if (ret == 0) {
  7622. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  7623. ret = BUFFER_E;
  7624. else
  7625. ret = cert->bodySz = WriteCertBody(der, derBuffer);
  7626. }
  7627. #ifdef WOLFSSL_SMALL_STACK
  7628. XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7629. #endif
  7630. return ret;
  7631. }
  7632. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  7633. int wc_MakeCert_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  7634. void* key, WC_RNG* rng)
  7635. {
  7636. RsaKey* rsaKey = NULL;
  7637. ecc_key* eccKey = NULL;
  7638. ed25519_key* ed25519Key = NULL;
  7639. if (keyType == RSA_TYPE)
  7640. rsaKey = (RsaKey*)key;
  7641. else if (keyType == ECC_TYPE)
  7642. eccKey = (ecc_key*)key;
  7643. else if (keyType == ED25519_TYPE)
  7644. ed25519Key = (ed25519_key*)key;
  7645. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0,
  7646. ed25519Key);
  7647. }
  7648. /* Make an x509 Certificate v3 RSA or ECC from cert input, write to buffer */
  7649. int wc_MakeCert(Cert* cert, byte* derBuffer, word32 derSz, RsaKey* rsaKey,
  7650. ecc_key* eccKey, WC_RNG* rng)
  7651. {
  7652. return MakeAnyCert(cert, derBuffer, derSz, rsaKey, eccKey, rng, NULL, 0,
  7653. NULL);
  7654. }
  7655. #ifdef HAVE_NTRU
  7656. int wc_MakeNtruCert(Cert* cert, byte* derBuffer, word32 derSz,
  7657. const byte* ntruKey, word16 keySz, WC_RNG* rng)
  7658. {
  7659. return MakeAnyCert(cert, derBuffer, derSz, NULL, NULL, rng, ntruKey, keySz);
  7660. }
  7661. #endif /* HAVE_NTRU */
  7662. #ifdef WOLFSSL_CERT_REQ
  7663. static int SetReqAttrib(byte* output, char* pw, int extSz)
  7664. {
  7665. static const byte cpOid[] =
  7666. { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
  7667. 0x09, 0x07 };
  7668. static const byte erOid[] =
  7669. { ASN_OBJECT_ID, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01,
  7670. 0x09, 0x0e };
  7671. int sz = 0; /* overall size */
  7672. int cpSz = 0; /* Challenge Password section size */
  7673. int cpSeqSz = 0;
  7674. int cpSetSz = 0;
  7675. int cpStrSz = 0;
  7676. int pwSz = 0;
  7677. int erSz = 0; /* Extension Request section size */
  7678. int erSeqSz = 0;
  7679. int erSetSz = 0;
  7680. byte cpSeq[MAX_SEQ_SZ];
  7681. byte cpSet[MAX_SET_SZ];
  7682. byte cpStr[MAX_PRSTR_SZ];
  7683. byte erSeq[MAX_SEQ_SZ];
  7684. byte erSet[MAX_SET_SZ];
  7685. output[0] = 0xa0;
  7686. sz++;
  7687. if (pw && pw[0]) {
  7688. pwSz = (int)XSTRLEN(pw);
  7689. cpStrSz = SetUTF8String(pwSz, cpStr);
  7690. cpSetSz = SetSet(cpStrSz + pwSz, cpSet);
  7691. cpSeqSz = SetSequence(sizeof(cpOid) + cpSetSz + cpStrSz + pwSz, cpSeq);
  7692. cpSz = cpSeqSz + sizeof(cpOid) + cpSetSz + cpStrSz + pwSz;
  7693. }
  7694. if (extSz) {
  7695. erSetSz = SetSet(extSz, erSet);
  7696. erSeqSz = SetSequence(erSetSz + sizeof(erOid) + extSz, erSeq);
  7697. erSz = extSz + erSetSz + erSeqSz + sizeof(erOid);
  7698. }
  7699. /* Put the pieces together. */
  7700. sz += SetLength(cpSz + erSz, &output[sz]);
  7701. if (cpSz) {
  7702. XMEMCPY(&output[sz], cpSeq, cpSeqSz);
  7703. sz += cpSeqSz;
  7704. XMEMCPY(&output[sz], cpOid, sizeof(cpOid));
  7705. sz += sizeof(cpOid);
  7706. XMEMCPY(&output[sz], cpSet, cpSetSz);
  7707. sz += cpSetSz;
  7708. XMEMCPY(&output[sz], cpStr, cpStrSz);
  7709. sz += cpStrSz;
  7710. XMEMCPY(&output[sz], pw, pwSz);
  7711. sz += pwSz;
  7712. }
  7713. if (erSz) {
  7714. XMEMCPY(&output[sz], erSeq, erSeqSz);
  7715. sz += erSeqSz;
  7716. XMEMCPY(&output[sz], erOid, sizeof(erOid));
  7717. sz += sizeof(erOid);
  7718. XMEMCPY(&output[sz], erSet, erSetSz);
  7719. sz += erSetSz;
  7720. /* The actual extension data will be tacked onto the output later. */
  7721. }
  7722. return sz;
  7723. }
  7724. /* encode info from cert into DER encoded format */
  7725. static int EncodeCertReq(Cert* cert, DerCert* der, RsaKey* rsaKey,
  7726. ecc_key* eccKey, ed25519_key* ed25519Key)
  7727. {
  7728. (void)eccKey;
  7729. (void)ed25519Key;
  7730. if (cert == NULL || der == NULL)
  7731. return BAD_FUNC_ARG;
  7732. if (rsaKey == NULL && eccKey == NULL && ed25519Key == NULL)
  7733. return PUBLIC_KEY_E;
  7734. /* init */
  7735. XMEMSET(der, 0, sizeof(DerCert));
  7736. /* version */
  7737. der->versionSz = SetMyVersion(cert->version, der->version, FALSE);
  7738. /* subject name */
  7739. der->subjectSz = SetName(der->subject, sizeof(der->subject), &cert->subject);
  7740. if (der->subjectSz <= 0)
  7741. return SUBJECT_E;
  7742. /* public key */
  7743. #ifndef NO_RSA
  7744. if (cert->keyType == RSA_KEY) {
  7745. if (rsaKey == NULL)
  7746. return PUBLIC_KEY_E;
  7747. der->publicKeySz = SetRsaPublicKey(der->publicKey, rsaKey,
  7748. sizeof(der->publicKey), 1);
  7749. }
  7750. #endif
  7751. #ifdef HAVE_ECC
  7752. if (cert->keyType == ECC_KEY) {
  7753. der->publicKeySz = SetEccPublicKey(der->publicKey, eccKey, 1);
  7754. }
  7755. #endif
  7756. #ifdef HAVE_ED25519
  7757. if (cert->keyType == ED25519_KEY) {
  7758. if (ed25519Key == NULL)
  7759. return PUBLIC_KEY_E;
  7760. der->publicKeySz = SetEd25519PublicKey(der->publicKey, ed25519Key, 1);
  7761. }
  7762. #endif
  7763. if (der->publicKeySz <= 0)
  7764. return PUBLIC_KEY_E;
  7765. /* set the extensions */
  7766. der->extensionsSz = 0;
  7767. /* CA */
  7768. if (cert->isCA) {
  7769. der->caSz = SetCa(der->ca, sizeof(der->ca));
  7770. if (der->caSz <= 0)
  7771. return CA_TRUE_E;
  7772. der->extensionsSz += der->caSz;
  7773. }
  7774. else
  7775. der->caSz = 0;
  7776. #ifdef WOLFSSL_CERT_EXT
  7777. /* SKID */
  7778. if (cert->skidSz) {
  7779. /* check the provided SKID size */
  7780. if (cert->skidSz > (int)sizeof(der->skid))
  7781. return SKID_E;
  7782. der->skidSz = SetSKID(der->skid, sizeof(der->skid),
  7783. cert->skid, cert->skidSz);
  7784. if (der->skidSz <= 0)
  7785. return SKID_E;
  7786. der->extensionsSz += der->skidSz;
  7787. }
  7788. else
  7789. der->skidSz = 0;
  7790. /* Key Usage */
  7791. if (cert->keyUsage != 0){
  7792. der->keyUsageSz = SetKeyUsage(der->keyUsage, sizeof(der->keyUsage),
  7793. cert->keyUsage);
  7794. if (der->keyUsageSz <= 0)
  7795. return KEYUSAGE_E;
  7796. der->extensionsSz += der->keyUsageSz;
  7797. }
  7798. else
  7799. der->keyUsageSz = 0;
  7800. /* Extended Key Usage */
  7801. if (cert->extKeyUsage != 0){
  7802. der->extKeyUsageSz = SetExtKeyUsage(der->extKeyUsage,
  7803. sizeof(der->extKeyUsage), cert->extKeyUsage);
  7804. if (der->extKeyUsageSz <= 0)
  7805. return EXTKEYUSAGE_E;
  7806. der->extensionsSz += der->extKeyUsageSz;
  7807. }
  7808. else
  7809. der->extKeyUsageSz = 0;
  7810. #endif /* WOLFSSL_CERT_EXT */
  7811. /* put extensions */
  7812. if (der->extensionsSz > 0) {
  7813. int ret;
  7814. /* put the start of sequence (ID, Size) */
  7815. der->extensionsSz = SetSequence(der->extensionsSz, der->extensions);
  7816. if (der->extensionsSz <= 0)
  7817. return EXTENSIONS_E;
  7818. /* put CA */
  7819. if (der->caSz) {
  7820. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7821. &der->extensionsSz,
  7822. der->ca, der->caSz);
  7823. if (ret <= 0)
  7824. return EXTENSIONS_E;
  7825. }
  7826. #ifdef WOLFSSL_CERT_EXT
  7827. /* put SKID */
  7828. if (der->skidSz) {
  7829. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7830. &der->extensionsSz,
  7831. der->skid, der->skidSz);
  7832. if (ret <= 0)
  7833. return EXTENSIONS_E;
  7834. }
  7835. /* put AKID */
  7836. if (der->akidSz) {
  7837. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7838. &der->extensionsSz,
  7839. der->akid, der->akidSz);
  7840. if (ret <= 0)
  7841. return EXTENSIONS_E;
  7842. }
  7843. /* put KeyUsage */
  7844. if (der->keyUsageSz) {
  7845. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7846. &der->extensionsSz,
  7847. der->keyUsage, der->keyUsageSz);
  7848. if (ret <= 0)
  7849. return EXTENSIONS_E;
  7850. }
  7851. /* put ExtendedKeyUsage */
  7852. if (der->extKeyUsageSz) {
  7853. ret = SetExtensions(der->extensions, sizeof(der->extensions),
  7854. &der->extensionsSz,
  7855. der->extKeyUsage, der->extKeyUsageSz);
  7856. if (ret <= 0)
  7857. return EXTENSIONS_E;
  7858. }
  7859. #endif /* WOLFSSL_CERT_EXT */
  7860. }
  7861. der->attribSz = SetReqAttrib(der->attrib,
  7862. cert->challengePw, der->extensionsSz);
  7863. if (der->attribSz <= 0)
  7864. return REQ_ATTRIBUTE_E;
  7865. der->total = der->versionSz + der->subjectSz + der->publicKeySz +
  7866. der->extensionsSz + der->attribSz;
  7867. return 0;
  7868. }
  7869. /* write DER encoded cert req to buffer, size already checked */
  7870. static int WriteCertReqBody(DerCert* der, byte* buffer)
  7871. {
  7872. int idx;
  7873. /* signed part header */
  7874. idx = SetSequence(der->total, buffer);
  7875. /* version */
  7876. XMEMCPY(buffer + idx, der->version, der->versionSz);
  7877. idx += der->versionSz;
  7878. /* subject */
  7879. XMEMCPY(buffer + idx, der->subject, der->subjectSz);
  7880. idx += der->subjectSz;
  7881. /* public key */
  7882. XMEMCPY(buffer + idx, der->publicKey, der->publicKeySz);
  7883. idx += der->publicKeySz;
  7884. /* attributes */
  7885. XMEMCPY(buffer + idx, der->attrib, der->attribSz);
  7886. idx += der->attribSz;
  7887. /* extensions */
  7888. if (der->extensionsSz) {
  7889. XMEMCPY(buffer + idx, der->extensions, min(der->extensionsSz,
  7890. (int)sizeof(der->extensions)));
  7891. idx += der->extensionsSz;
  7892. }
  7893. return idx;
  7894. }
  7895. static int MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  7896. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key)
  7897. {
  7898. int ret;
  7899. #ifdef WOLFSSL_SMALL_STACK
  7900. DerCert* der;
  7901. #else
  7902. DerCert der[1];
  7903. #endif
  7904. cert->keyType = eccKey ? ECC_KEY : (ed25519Key ? ED25519_KEY : RSA_KEY);
  7905. #ifdef WOLFSSL_SMALL_STACK
  7906. der = (DerCert*)XMALLOC(sizeof(DerCert), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7907. if (der == NULL)
  7908. return MEMORY_E;
  7909. #endif
  7910. ret = EncodeCertReq(cert, der, rsaKey, eccKey, ed25519Key);
  7911. if (ret == 0) {
  7912. if (der->total + MAX_SEQ_SZ * 2 > (int)derSz)
  7913. ret = BUFFER_E;
  7914. else
  7915. ret = cert->bodySz = WriteCertReqBody(der, derBuffer);
  7916. }
  7917. #ifdef WOLFSSL_SMALL_STACK
  7918. XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7919. #endif
  7920. return ret;
  7921. }
  7922. int wc_MakeCertReq_ex(Cert* cert, byte* derBuffer, word32 derSz, int keyType,
  7923. void* key)
  7924. {
  7925. RsaKey* rsaKey = NULL;
  7926. ecc_key* eccKey = NULL;
  7927. ed25519_key* ed25519Key = NULL;
  7928. if (keyType == RSA_TYPE)
  7929. rsaKey = (RsaKey*)key;
  7930. else if (keyType == ECC_TYPE)
  7931. eccKey = (ecc_key*)key;
  7932. else if (keyType == ED25519_TYPE)
  7933. ed25519Key = (ed25519_key*)key;
  7934. return MakeCertReq(cert, derBuffer, derSz, rsaKey, eccKey, ed25519Key);
  7935. }
  7936. int wc_MakeCertReq(Cert* cert, byte* derBuffer, word32 derSz,
  7937. RsaKey* rsaKey, ecc_key* eccKey)
  7938. {
  7939. return MakeCertReq(cert, derBuffer, derSz, rsaKey, eccKey, NULL);
  7940. }
  7941. #endif /* WOLFSSL_CERT_REQ */
  7942. static int SignCert(int requestSz, int sType, byte* buffer, word32 buffSz,
  7943. RsaKey* rsaKey, ecc_key* eccKey, ed25519_key* ed25519Key,
  7944. WC_RNG* rng)
  7945. {
  7946. int sigSz = 0;
  7947. void* heap = NULL;
  7948. CertSignCtx* certSignCtx = NULL;
  7949. #ifndef WOLFSSL_ASYNC_CRYPT
  7950. CertSignCtx certSignCtx_lcl;
  7951. certSignCtx = &certSignCtx_lcl;
  7952. XMEMSET(certSignCtx, 0, sizeof(CertSignCtx));
  7953. #endif
  7954. if (requestSz < 0)
  7955. return requestSz;
  7956. /* locate ctx */
  7957. if (rsaKey) {
  7958. #ifndef NO_RSA
  7959. #ifdef WOLFSSL_ASYNC_CRYPT
  7960. certSignCtx = &rsaKey->certSignCtx;
  7961. #endif
  7962. heap = rsaKey->heap;
  7963. #else
  7964. return NOT_COMPILED_IN;
  7965. #endif /* NO_RSA */
  7966. }
  7967. else if (eccKey) {
  7968. #ifdef HAVE_ECC
  7969. #ifdef WOLFSSL_ASYNC_CRYPT
  7970. certSignCtx = &eccKey->certSignCtx;
  7971. #endif
  7972. heap = eccKey->heap;
  7973. #else
  7974. return NOT_COMPILED_IN;
  7975. #endif /* HAVE_ECC */
  7976. }
  7977. #ifdef WOLFSSL_ASYNC_CRYPT
  7978. if (certSignCtx == NULL) {
  7979. return BAD_FUNC_ARG;
  7980. }
  7981. #endif
  7982. if (certSignCtx->sig == NULL) {
  7983. certSignCtx->sig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, heap,
  7984. DYNAMIC_TYPE_TMP_BUFFER);
  7985. if (certSignCtx->sig == NULL)
  7986. return MEMORY_E;
  7987. }
  7988. sigSz = MakeSignature(certSignCtx, buffer, requestSz, certSignCtx->sig,
  7989. MAX_ENCODED_SIG_SZ, rsaKey, eccKey, ed25519Key, rng, sType, heap);
  7990. if (sigSz == WC_PENDING_E)
  7991. return sigSz;
  7992. if (sigSz >= 0) {
  7993. if (requestSz + MAX_SEQ_SZ * 2 + sigSz > (int)buffSz)
  7994. sigSz = BUFFER_E;
  7995. else
  7996. sigSz = AddSignature(buffer, requestSz, certSignCtx->sig, sigSz, sType);
  7997. }
  7998. XFREE(certSignCtx->sig, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7999. certSignCtx->sig = NULL;
  8000. return sigSz;
  8001. }
  8002. int wc_SignCert_ex(int requestSz, int sType, byte* buffer, word32 buffSz,
  8003. int keyType, void* key, WC_RNG* rng)
  8004. {
  8005. RsaKey* rsaKey = NULL;
  8006. ecc_key* eccKey = NULL;
  8007. ed25519_key* ed25519Key = NULL;
  8008. if (keyType == RSA_TYPE)
  8009. rsaKey = (RsaKey*)key;
  8010. else if (keyType == ECC_TYPE)
  8011. eccKey = (ecc_key*)key;
  8012. else if (keyType == ED25519_TYPE)
  8013. ed25519Key = (ed25519_key*)key;
  8014. return SignCert(requestSz, sType, buffer, buffSz, rsaKey, eccKey,
  8015. ed25519Key, rng);
  8016. }
  8017. int wc_SignCert(int requestSz, int sType, byte* buffer, word32 buffSz,
  8018. RsaKey* rsaKey, ecc_key* eccKey, WC_RNG* rng)
  8019. {
  8020. return SignCert(requestSz, sType, buffer, buffSz, rsaKey, eccKey, NULL,
  8021. rng);
  8022. }
  8023. int wc_MakeSelfCert(Cert* cert, byte* buffer, word32 buffSz,
  8024. RsaKey* key, WC_RNG* rng)
  8025. {
  8026. int ret;
  8027. ret = wc_MakeCert(cert, buffer, buffSz, key, NULL, rng);
  8028. if (ret < 0)
  8029. return ret;
  8030. return wc_SignCert(cert->bodySz, cert->sigType,
  8031. buffer, buffSz, key, NULL, rng);
  8032. }
  8033. #ifdef WOLFSSL_CERT_EXT
  8034. /* Set KID from public key */
  8035. static int SetKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey,
  8036. byte *ntruKey, word16 ntruKeySz,
  8037. ed25519_key* ed25519Key, int kid_type)
  8038. {
  8039. byte *buffer;
  8040. int bufferSz, ret;
  8041. if (cert == NULL ||
  8042. (rsakey == NULL && eckey == NULL && ntruKey == NULL &&
  8043. ed25519Key == NULL) ||
  8044. (kid_type != SKID_TYPE && kid_type != AKID_TYPE))
  8045. return BAD_FUNC_ARG;
  8046. buffer = (byte *)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap,
  8047. DYNAMIC_TYPE_TMP_BUFFER);
  8048. if (buffer == NULL)
  8049. return MEMORY_E;
  8050. /* Public Key */
  8051. bufferSz = -1;
  8052. #ifndef NO_RSA
  8053. /* RSA public key */
  8054. if (rsakey != NULL)
  8055. bufferSz = SetRsaPublicKey(buffer, rsakey, MAX_PUBLIC_KEY_SZ, 0);
  8056. #endif
  8057. #ifdef HAVE_ECC
  8058. /* ECC public key */
  8059. if (eckey != NULL)
  8060. bufferSz = SetEccPublicKey(buffer, eckey, 0);
  8061. #endif
  8062. #ifdef HAVE_NTRU
  8063. /* NTRU public key */
  8064. if (ntruKey != NULL) {
  8065. bufferSz = MAX_PUBLIC_KEY_SZ;
  8066. ret = ntru_crypto_ntru_encrypt_publicKey2SubjectPublicKeyInfo(
  8067. ntruKeySz, ntruKey, (word16 *)(&bufferSz), buffer);
  8068. if (ret != NTRU_OK)
  8069. bufferSz = -1;
  8070. }
  8071. #else
  8072. (void)ntruKeySz;
  8073. #endif
  8074. #ifdef HAVE_ED25519
  8075. /* ED25519 public key */
  8076. if (ed25519Key != NULL)
  8077. bufferSz = SetEd25519PublicKey(buffer, ed25519Key, 0);
  8078. #endif
  8079. if (bufferSz <= 0) {
  8080. XFREE(buffer, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8081. return PUBLIC_KEY_E;
  8082. }
  8083. /* Compute SKID by hashing public key */
  8084. #ifdef NO_SHA
  8085. if (kid_type == SKID_TYPE) {
  8086. ret = wc_Sha256Hash(buffer, bufferSz, cert->skid);
  8087. cert->skidSz = WC_SHA256_DIGEST_SIZE;
  8088. }
  8089. else if (kid_type == AKID_TYPE) {
  8090. ret = wc_Sha256Hash(buffer, bufferSz, cert->akid);
  8091. cert->akidSz = WC_SHA256_DIGEST_SIZE;
  8092. }
  8093. else
  8094. ret = BAD_FUNC_ARG;
  8095. #else /* NO_SHA */
  8096. if (kid_type == SKID_TYPE) {
  8097. ret = wc_ShaHash(buffer, bufferSz, cert->skid);
  8098. cert->skidSz = WC_SHA_DIGEST_SIZE;
  8099. }
  8100. else if (kid_type == AKID_TYPE) {
  8101. ret = wc_ShaHash(buffer, bufferSz, cert->akid);
  8102. cert->akidSz = WC_SHA_DIGEST_SIZE;
  8103. }
  8104. else
  8105. ret = BAD_FUNC_ARG;
  8106. #endif /* NO_SHA */
  8107. XFREE(buffer, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8108. return ret;
  8109. }
  8110. int wc_SetSubjectKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  8111. {
  8112. RsaKey* rsaKey = NULL;
  8113. ecc_key* eccKey = NULL;
  8114. ed25519_key* ed25519Key = NULL;
  8115. if (keyType == RSA_TYPE)
  8116. rsaKey = (RsaKey*)key;
  8117. else if (keyType == ECC_TYPE)
  8118. eccKey = (ecc_key*)key;
  8119. else if (keyType == ED25519_TYPE)
  8120. ed25519Key = (ed25519_key*)key;
  8121. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, NULL, 0, ed25519Key,
  8122. SKID_TYPE);
  8123. }
  8124. /* Set SKID from RSA or ECC public key */
  8125. int wc_SetSubjectKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  8126. {
  8127. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, 0, NULL, SKID_TYPE);
  8128. }
  8129. #ifdef HAVE_NTRU
  8130. /* Set SKID from NTRU public key */
  8131. int wc_SetSubjectKeyIdFromNtruPublicKey(Cert *cert,
  8132. byte *ntruKey, word16 ntruKeySz)
  8133. {
  8134. return SetKeyIdFromPublicKey(cert, NULL,NULL,ntruKey, ntruKeySz, NULL,
  8135. SKID_TYPE);
  8136. }
  8137. #endif
  8138. int wc_SetAuthKeyIdFromPublicKey_ex(Cert *cert, int keyType, void* key)
  8139. {
  8140. RsaKey* rsaKey = NULL;
  8141. ecc_key* eccKey = NULL;
  8142. ed25519_key* ed25519Key = NULL;
  8143. if (keyType == RSA_TYPE)
  8144. rsaKey = (RsaKey*)key;
  8145. else if (keyType == ECC_TYPE)
  8146. eccKey = (ecc_key*)key;
  8147. else if (keyType == ED25519_TYPE)
  8148. ed25519Key = (ed25519_key*)key;
  8149. return SetKeyIdFromPublicKey(cert, rsaKey, eccKey, NULL, 0, ed25519Key,
  8150. AKID_TYPE);
  8151. }
  8152. /* Set SKID from RSA or ECC public key */
  8153. int wc_SetAuthKeyIdFromPublicKey(Cert *cert, RsaKey *rsakey, ecc_key *eckey)
  8154. {
  8155. return SetKeyIdFromPublicKey(cert, rsakey, eckey, NULL, 0, NULL, AKID_TYPE);
  8156. }
  8157. #ifndef NO_FILESYSTEM
  8158. /* Set SKID from public key file in PEM */
  8159. int wc_SetSubjectKeyId(Cert *cert, const char* file)
  8160. {
  8161. int ret, derSz;
  8162. byte* der;
  8163. word32 idx;
  8164. RsaKey *rsakey = NULL;
  8165. ecc_key *eckey = NULL;
  8166. if (cert == NULL || file == NULL)
  8167. return BAD_FUNC_ARG;
  8168. der = (byte*)XMALLOC(MAX_PUBLIC_KEY_SZ, cert->heap, DYNAMIC_TYPE_CERT);
  8169. if (der == NULL) {
  8170. WOLFSSL_MSG("wc_SetSubjectKeyId memory Problem");
  8171. return MEMORY_E;
  8172. }
  8173. derSz = wolfSSL_PemPubKeyToDer(file, der, MAX_PUBLIC_KEY_SZ);
  8174. if (derSz <= 0)
  8175. {
  8176. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8177. return derSz;
  8178. }
  8179. /* Load PubKey in internal structure */
  8180. #ifndef NO_RSA
  8181. rsakey = (RsaKey*) XMALLOC(sizeof(RsaKey), cert->heap, DYNAMIC_TYPE_RSA);
  8182. if (rsakey == NULL) {
  8183. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8184. return MEMORY_E;
  8185. }
  8186. if (wc_InitRsaKey(rsakey, cert->heap) != 0) {
  8187. WOLFSSL_MSG("wc_InitRsaKey failure");
  8188. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  8189. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8190. return MEMORY_E;
  8191. }
  8192. idx = 0;
  8193. ret = wc_RsaPublicKeyDecode(der, &idx, rsakey, derSz);
  8194. if (ret != 0)
  8195. #endif
  8196. {
  8197. #ifndef NO_RSA
  8198. WOLFSSL_MSG("wc_RsaPublicKeyDecode failed");
  8199. wc_FreeRsaKey(rsakey);
  8200. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  8201. rsakey = NULL;
  8202. #endif
  8203. #ifdef HAVE_ECC
  8204. /* Check to load ecc public key */
  8205. eckey = (ecc_key*) XMALLOC(sizeof(ecc_key), cert->heap,
  8206. DYNAMIC_TYPE_ECC);
  8207. if (eckey == NULL) {
  8208. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8209. return MEMORY_E;
  8210. }
  8211. if (wc_ecc_init(eckey) != 0) {
  8212. WOLFSSL_MSG("wc_ecc_init failure");
  8213. wc_ecc_free(eckey);
  8214. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  8215. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8216. return MEMORY_E;
  8217. }
  8218. idx = 0;
  8219. ret = wc_EccPublicKeyDecode(der, &idx, eckey, derSz);
  8220. if (ret != 0) {
  8221. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  8222. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8223. wc_ecc_free(eckey);
  8224. return PUBLIC_KEY_E;
  8225. }
  8226. #else
  8227. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8228. return PUBLIC_KEY_E;
  8229. #endif /* HAVE_ECC */
  8230. }
  8231. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8232. ret = wc_SetSubjectKeyIdFromPublicKey(cert, rsakey, eckey);
  8233. #ifndef NO_RSA
  8234. wc_FreeRsaKey(rsakey);
  8235. XFREE(rsakey, cert->heap, DYNAMIC_TYPE_RSA);
  8236. #endif
  8237. #ifdef HAVE_ECC
  8238. wc_ecc_free(eckey);
  8239. XFREE(eckey, cert->heap, DYNAMIC_TYPE_ECC);
  8240. #endif
  8241. return ret;
  8242. }
  8243. #endif /* NO_FILESYSTEM */
  8244. /* Set AKID from certificate contains in buffer (DER encoded) */
  8245. int wc_SetAuthKeyIdFromCert(Cert *cert, const byte *der, int derSz)
  8246. {
  8247. int ret;
  8248. #ifdef WOLFSSL_SMALL_STACK
  8249. DecodedCert* decoded;
  8250. #else
  8251. DecodedCert decoded[1];
  8252. #endif
  8253. if (cert == NULL || der == NULL || derSz <= 0)
  8254. return BAD_FUNC_ARG;
  8255. #ifdef WOLFSSL_SMALL_STACK
  8256. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert),
  8257. NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8258. if (decoded == NULL)
  8259. return MEMORY_E;
  8260. #endif
  8261. /* decode certificate and get SKID that will be AKID of current cert */
  8262. InitDecodedCert(decoded, (byte*)der, derSz, NULL);
  8263. ret = ParseCert(decoded, CERT_TYPE, NO_VERIFY, 0);
  8264. if (ret != 0) {
  8265. FreeDecodedCert(decoded);
  8266. #ifdef WOLFSSL_SMALL_STACK
  8267. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8268. #endif
  8269. return ret;
  8270. }
  8271. /* Subject Key Id not found !! */
  8272. if (decoded->extSubjKeyIdSet == 0) {
  8273. FreeDecodedCert(decoded);
  8274. #ifdef WOLFSSL_SMALL_STACK
  8275. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8276. #endif
  8277. return ASN_NO_SKID;
  8278. }
  8279. /* SKID invalid size */
  8280. if (sizeof(cert->akid) < sizeof(decoded->extSubjKeyId)) {
  8281. FreeDecodedCert(decoded);
  8282. #ifdef WOLFSSL_SMALL_STACK
  8283. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8284. #endif
  8285. return MEMORY_E;
  8286. }
  8287. /* Put the SKID of CA to AKID of certificate */
  8288. XMEMCPY(cert->akid, decoded->extSubjKeyId, KEYID_SIZE);
  8289. cert->akidSz = KEYID_SIZE;
  8290. FreeDecodedCert(decoded);
  8291. #ifdef WOLFSSL_SMALL_STACK
  8292. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8293. #endif
  8294. return 0;
  8295. }
  8296. #ifndef NO_FILESYSTEM
  8297. /* Set AKID from certificate file in PEM */
  8298. int wc_SetAuthKeyId(Cert *cert, const char* file)
  8299. {
  8300. int ret;
  8301. int derSz;
  8302. byte* der;
  8303. if (cert == NULL || file == NULL)
  8304. return BAD_FUNC_ARG;
  8305. der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  8306. if (der == NULL) {
  8307. WOLFSSL_MSG("wc_SetAuthKeyId OOF Problem");
  8308. return MEMORY_E;
  8309. }
  8310. derSz = wolfSSL_PemCertToDer(file, der, EIGHTK_BUF);
  8311. if (derSz <= 0)
  8312. {
  8313. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8314. return derSz;
  8315. }
  8316. ret = wc_SetAuthKeyIdFromCert(cert, der, derSz);
  8317. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8318. return ret;
  8319. }
  8320. #endif /* NO_FILESYSTEM */
  8321. /* Set KeyUsage from human readable string */
  8322. int wc_SetKeyUsage(Cert *cert, const char *value)
  8323. {
  8324. int ret = 0;
  8325. char *token, *str, *ptr;
  8326. word32 len;
  8327. if (cert == NULL || value == NULL)
  8328. return BAD_FUNC_ARG;
  8329. cert->keyUsage = 0;
  8330. str = (char*)XMALLOC(XSTRLEN(value)+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8331. if (str == NULL)
  8332. return MEMORY_E;
  8333. XMEMSET(str, 0, XSTRLEN(value)+1);
  8334. XSTRNCPY(str, value, XSTRLEN(value));
  8335. /* parse value, and set corresponding Key Usage value */
  8336. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  8337. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8338. return KEYUSAGE_E;
  8339. }
  8340. while (token != NULL)
  8341. {
  8342. len = (word32)XSTRLEN(token);
  8343. if (!XSTRNCASECMP(token, "digitalSignature", len))
  8344. cert->keyUsage |= KEYUSE_DIGITAL_SIG;
  8345. else if (!XSTRNCASECMP(token, "nonRepudiation", len) ||
  8346. !XSTRNCASECMP(token, "contentCommitment", len))
  8347. cert->keyUsage |= KEYUSE_CONTENT_COMMIT;
  8348. else if (!XSTRNCASECMP(token, "keyEncipherment", len))
  8349. cert->keyUsage |= KEYUSE_KEY_ENCIPHER;
  8350. else if (!XSTRNCASECMP(token, "dataEncipherment", len))
  8351. cert->keyUsage |= KEYUSE_DATA_ENCIPHER;
  8352. else if (!XSTRNCASECMP(token, "keyAgreement", len))
  8353. cert->keyUsage |= KEYUSE_KEY_AGREE;
  8354. else if (!XSTRNCASECMP(token, "keyCertSign", len))
  8355. cert->keyUsage |= KEYUSE_KEY_CERT_SIGN;
  8356. else if (!XSTRNCASECMP(token, "cRLSign", len))
  8357. cert->keyUsage |= KEYUSE_CRL_SIGN;
  8358. else if (!XSTRNCASECMP(token, "encipherOnly", len))
  8359. cert->keyUsage |= KEYUSE_ENCIPHER_ONLY;
  8360. else if (!XSTRNCASECMP(token, "decipherOnly", len))
  8361. cert->keyUsage |= KEYUSE_DECIPHER_ONLY;
  8362. else {
  8363. ret = KEYUSAGE_E;
  8364. break;
  8365. }
  8366. token = XSTRTOK(NULL, ",", &ptr);
  8367. }
  8368. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8369. return ret;
  8370. }
  8371. /* Set ExtendedKeyUsage from human readable string */
  8372. int wc_SetExtKeyUsage(Cert *cert, const char *value)
  8373. {
  8374. int ret = 0;
  8375. char *token, *str, *ptr;
  8376. word32 len;
  8377. if (cert == NULL || value == NULL)
  8378. return BAD_FUNC_ARG;
  8379. cert->extKeyUsage = 0;
  8380. str = (char*)XMALLOC(XSTRLEN(value)+1, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8381. if (str == NULL)
  8382. return MEMORY_E;
  8383. XMEMSET(str, 0, XSTRLEN(value)+1);
  8384. XSTRNCPY(str, value, XSTRLEN(value));
  8385. /* parse value, and set corresponding Key Usage value */
  8386. if ((token = XSTRTOK(str, ",", &ptr)) == NULL) {
  8387. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8388. return EXTKEYUSAGE_E;
  8389. }
  8390. while (token != NULL)
  8391. {
  8392. len = (word32)XSTRLEN(token);
  8393. if (!XSTRNCASECMP(token, "any", len))
  8394. cert->extKeyUsage |= EXTKEYUSE_ANY;
  8395. else if (!XSTRNCASECMP(token, "serverAuth", len))
  8396. cert->extKeyUsage |= EXTKEYUSE_SERVER_AUTH;
  8397. else if (!XSTRNCASECMP(token, "clientAuth", len))
  8398. cert->extKeyUsage |= EXTKEYUSE_CLIENT_AUTH;
  8399. else if (!XSTRNCASECMP(token, "codeSigning", len))
  8400. cert->extKeyUsage |= EXTKEYUSE_CODESIGN;
  8401. else if (!XSTRNCASECMP(token, "emailProtection", len))
  8402. cert->extKeyUsage |= EXTKEYUSE_EMAILPROT;
  8403. else if (!XSTRNCASECMP(token, "timeStamping", len))
  8404. cert->extKeyUsage |= EXTKEYUSE_TIMESTAMP;
  8405. else if (!XSTRNCASECMP(token, "OCSPSigning", len))
  8406. cert->extKeyUsage |= EXTKEYUSE_OCSP_SIGN;
  8407. else {
  8408. ret = EXTKEYUSAGE_E;
  8409. break;
  8410. }
  8411. token = XSTRTOK(NULL, ",", &ptr);
  8412. }
  8413. XFREE(str, cert->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8414. return ret;
  8415. }
  8416. #endif /* WOLFSSL_CERT_EXT */
  8417. #ifdef WOLFSSL_ALT_NAMES
  8418. /* Set Alt Names from der cert, return 0 on success */
  8419. static int SetAltNamesFromCert(Cert* cert, const byte* der, int derSz)
  8420. {
  8421. int ret;
  8422. #ifdef WOLFSSL_SMALL_STACK
  8423. DecodedCert* decoded;
  8424. #else
  8425. DecodedCert decoded[1];
  8426. #endif
  8427. if (derSz < 0)
  8428. return derSz;
  8429. #ifdef WOLFSSL_SMALL_STACK
  8430. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  8431. DYNAMIC_TYPE_TMP_BUFFER);
  8432. if (decoded == NULL)
  8433. return MEMORY_E;
  8434. #endif
  8435. InitDecodedCert(decoded, (byte*)der, derSz, NULL);
  8436. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  8437. if (ret < 0) {
  8438. WOLFSSL_MSG("ParseCertRelative error");
  8439. }
  8440. else if (decoded->extensions) {
  8441. byte b;
  8442. int length;
  8443. word32 maxExtensionsIdx;
  8444. decoded->srcIdx = decoded->extensionsIdx;
  8445. b = decoded->source[decoded->srcIdx++];
  8446. if (b != ASN_EXTENSIONS) {
  8447. ret = ASN_PARSE_E;
  8448. }
  8449. else if (GetLength(decoded->source, &decoded->srcIdx, &length,
  8450. decoded->maxIdx) < 0) {
  8451. ret = ASN_PARSE_E;
  8452. }
  8453. else if (GetSequence(decoded->source, &decoded->srcIdx, &length,
  8454. decoded->maxIdx) < 0) {
  8455. ret = ASN_PARSE_E;
  8456. }
  8457. else {
  8458. maxExtensionsIdx = decoded->srcIdx + length;
  8459. while (decoded->srcIdx < maxExtensionsIdx) {
  8460. word32 oid;
  8461. word32 startIdx = decoded->srcIdx;
  8462. word32 tmpIdx;
  8463. if (GetSequence(decoded->source, &decoded->srcIdx, &length,
  8464. decoded->maxIdx) < 0) {
  8465. ret = ASN_PARSE_E;
  8466. break;
  8467. }
  8468. tmpIdx = decoded->srcIdx;
  8469. decoded->srcIdx = startIdx;
  8470. if (GetAlgoId(decoded->source, &decoded->srcIdx, &oid,
  8471. oidCertExtType, decoded->maxIdx) < 0) {
  8472. ret = ASN_PARSE_E;
  8473. break;
  8474. }
  8475. if (oid == ALT_NAMES_OID) {
  8476. cert->altNamesSz = length + (tmpIdx - startIdx);
  8477. if (cert->altNamesSz < (int)sizeof(cert->altNames))
  8478. XMEMCPY(cert->altNames, &decoded->source[startIdx],
  8479. cert->altNamesSz);
  8480. else {
  8481. cert->altNamesSz = 0;
  8482. WOLFSSL_MSG("AltNames extensions too big");
  8483. ret = ALT_NAME_E;
  8484. break;
  8485. }
  8486. }
  8487. decoded->srcIdx = tmpIdx + length;
  8488. }
  8489. }
  8490. }
  8491. FreeDecodedCert(decoded);
  8492. #ifdef WOLFSSL_SMALL_STACK
  8493. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8494. #endif
  8495. return ret < 0 ? ret : 0;
  8496. }
  8497. /* Set Dates from der cert, return 0 on success */
  8498. static int SetDatesFromCert(Cert* cert, const byte* der, int derSz)
  8499. {
  8500. int ret;
  8501. #ifdef WOLFSSL_SMALL_STACK
  8502. DecodedCert* decoded;
  8503. #else
  8504. DecodedCert decoded[1];
  8505. #endif
  8506. WOLFSSL_ENTER("SetDatesFromCert");
  8507. if (derSz < 0)
  8508. return derSz;
  8509. #ifdef WOLFSSL_SMALL_STACK
  8510. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  8511. DYNAMIC_TYPE_TMP_BUFFER);
  8512. if (decoded == NULL)
  8513. return MEMORY_E;
  8514. #endif
  8515. InitDecodedCert(decoded, (byte*)der, derSz, NULL);
  8516. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  8517. if (ret < 0) {
  8518. WOLFSSL_MSG("ParseCertRelative error");
  8519. }
  8520. else if (decoded->beforeDate == NULL || decoded->afterDate == NULL) {
  8521. WOLFSSL_MSG("Couldn't extract dates");
  8522. ret = -1;
  8523. }
  8524. else if (decoded->beforeDateLen > MAX_DATE_SIZE ||
  8525. decoded->afterDateLen > MAX_DATE_SIZE) {
  8526. WOLFSSL_MSG("Bad date size");
  8527. ret = -1;
  8528. }
  8529. else {
  8530. XMEMCPY(cert->beforeDate, decoded->beforeDate, decoded->beforeDateLen);
  8531. XMEMCPY(cert->afterDate, decoded->afterDate, decoded->afterDateLen);
  8532. cert->beforeDateSz = decoded->beforeDateLen;
  8533. cert->afterDateSz = decoded->afterDateLen;
  8534. }
  8535. FreeDecodedCert(decoded);
  8536. #ifdef WOLFSSL_SMALL_STACK
  8537. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8538. #endif
  8539. return ret < 0 ? ret : 0;
  8540. }
  8541. #endif /* WOLFSSL_ALT_NAMES */
  8542. /* Set cn name from der buffer, return 0 on success */
  8543. static int SetNameFromCert(CertName* cn, const byte* der, int derSz)
  8544. {
  8545. int ret, sz;
  8546. #ifdef WOLFSSL_SMALL_STACK
  8547. DecodedCert* decoded;
  8548. #else
  8549. DecodedCert decoded[1];
  8550. #endif
  8551. if (derSz < 0)
  8552. return derSz;
  8553. #ifdef WOLFSSL_SMALL_STACK
  8554. decoded = (DecodedCert*)XMALLOC(sizeof(DecodedCert), NULL,
  8555. DYNAMIC_TYPE_TMP_BUFFER);
  8556. if (decoded == NULL)
  8557. return MEMORY_E;
  8558. #endif
  8559. InitDecodedCert(decoded, (byte*)der, derSz, NULL);
  8560. ret = ParseCertRelative(decoded, CA_TYPE, NO_VERIFY, 0);
  8561. if (ret < 0) {
  8562. WOLFSSL_MSG("ParseCertRelative error");
  8563. }
  8564. else {
  8565. if (decoded->subjectCN) {
  8566. sz = (decoded->subjectCNLen < CTC_NAME_SIZE) ? decoded->subjectCNLen
  8567. : CTC_NAME_SIZE - 1;
  8568. XSTRNCPY(cn->commonName, decoded->subjectCN, CTC_NAME_SIZE);
  8569. cn->commonName[sz] = 0;
  8570. cn->commonNameEnc = decoded->subjectCNEnc;
  8571. }
  8572. if (decoded->subjectC) {
  8573. sz = (decoded->subjectCLen < CTC_NAME_SIZE) ? decoded->subjectCLen
  8574. : CTC_NAME_SIZE - 1;
  8575. XSTRNCPY(cn->country, decoded->subjectC, CTC_NAME_SIZE);
  8576. cn->country[sz] = 0;
  8577. cn->countryEnc = decoded->subjectCEnc;
  8578. }
  8579. if (decoded->subjectST) {
  8580. sz = (decoded->subjectSTLen < CTC_NAME_SIZE) ? decoded->subjectSTLen
  8581. : CTC_NAME_SIZE - 1;
  8582. XSTRNCPY(cn->state, decoded->subjectST, CTC_NAME_SIZE);
  8583. cn->state[sz] = 0;
  8584. cn->stateEnc = decoded->subjectSTEnc;
  8585. }
  8586. if (decoded->subjectL) {
  8587. sz = (decoded->subjectLLen < CTC_NAME_SIZE) ? decoded->subjectLLen
  8588. : CTC_NAME_SIZE - 1;
  8589. XSTRNCPY(cn->locality, decoded->subjectL, CTC_NAME_SIZE);
  8590. cn->locality[sz] = 0;
  8591. cn->localityEnc = decoded->subjectLEnc;
  8592. }
  8593. if (decoded->subjectO) {
  8594. sz = (decoded->subjectOLen < CTC_NAME_SIZE) ? decoded->subjectOLen
  8595. : CTC_NAME_SIZE - 1;
  8596. XSTRNCPY(cn->org, decoded->subjectO, CTC_NAME_SIZE);
  8597. cn->org[sz] = 0;
  8598. cn->orgEnc = decoded->subjectOEnc;
  8599. }
  8600. if (decoded->subjectOU) {
  8601. sz = (decoded->subjectOULen < CTC_NAME_SIZE) ? decoded->subjectOULen
  8602. : CTC_NAME_SIZE - 1;
  8603. XSTRNCPY(cn->unit, decoded->subjectOU, CTC_NAME_SIZE);
  8604. cn->unit[sz] = 0;
  8605. cn->unitEnc = decoded->subjectOUEnc;
  8606. }
  8607. if (decoded->subjectSN) {
  8608. sz = (decoded->subjectSNLen < CTC_NAME_SIZE) ? decoded->subjectSNLen
  8609. : CTC_NAME_SIZE - 1;
  8610. XSTRNCPY(cn->sur, decoded->subjectSN, CTC_NAME_SIZE);
  8611. cn->sur[sz] = 0;
  8612. cn->surEnc = decoded->subjectSNEnc;
  8613. }
  8614. if (decoded->subjectEmail) {
  8615. sz = (decoded->subjectEmailLen < CTC_NAME_SIZE)
  8616. ? decoded->subjectEmailLen : CTC_NAME_SIZE - 1;
  8617. XSTRNCPY(cn->email, decoded->subjectEmail, CTC_NAME_SIZE);
  8618. cn->email[sz] = 0;
  8619. }
  8620. }
  8621. FreeDecodedCert(decoded);
  8622. #ifdef WOLFSSL_SMALL_STACK
  8623. XFREE(decoded, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8624. #endif
  8625. return ret < 0 ? ret : 0;
  8626. }
  8627. #ifndef NO_FILESYSTEM
  8628. /* Set cert issuer from issuerFile in PEM */
  8629. int wc_SetIssuer(Cert* cert, const char* issuerFile)
  8630. {
  8631. int ret;
  8632. int derSz;
  8633. byte* der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  8634. if (der == NULL) {
  8635. WOLFSSL_MSG("wc_SetIssuer OOF Problem");
  8636. return MEMORY_E;
  8637. }
  8638. derSz = wolfSSL_PemCertToDer(issuerFile, der, EIGHTK_BUF);
  8639. cert->selfSigned = 0;
  8640. ret = SetNameFromCert(&cert->issuer, der, derSz);
  8641. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8642. return ret;
  8643. }
  8644. /* Set cert subject from subjectFile in PEM */
  8645. int wc_SetSubject(Cert* cert, const char* subjectFile)
  8646. {
  8647. int ret;
  8648. int derSz;
  8649. byte* der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  8650. if (der == NULL) {
  8651. WOLFSSL_MSG("wc_SetSubject OOF Problem");
  8652. return MEMORY_E;
  8653. }
  8654. derSz = wolfSSL_PemCertToDer(subjectFile, der, EIGHTK_BUF);
  8655. ret = SetNameFromCert(&cert->subject, der, derSz);
  8656. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8657. return ret;
  8658. }
  8659. #ifdef WOLFSSL_ALT_NAMES
  8660. /* Set atl names from file in PEM */
  8661. int wc_SetAltNames(Cert* cert, const char* file)
  8662. {
  8663. int ret;
  8664. int derSz;
  8665. byte* der = (byte*)XMALLOC(EIGHTK_BUF, cert->heap, DYNAMIC_TYPE_CERT);
  8666. if (der == NULL) {
  8667. WOLFSSL_MSG("wc_SetAltNames OOF Problem");
  8668. return MEMORY_E;
  8669. }
  8670. derSz = wolfSSL_PemCertToDer(file, der, EIGHTK_BUF);
  8671. ret = SetAltNamesFromCert(cert, der, derSz);
  8672. XFREE(der, cert->heap, DYNAMIC_TYPE_CERT);
  8673. return ret;
  8674. }
  8675. #endif /* WOLFSSL_ALT_NAMES */
  8676. #endif /* NO_FILESYSTEM */
  8677. /* Set cert issuer from DER buffer */
  8678. int wc_SetIssuerBuffer(Cert* cert, const byte* der, int derSz)
  8679. {
  8680. cert->selfSigned = 0;
  8681. return SetNameFromCert(&cert->issuer, der, derSz);
  8682. }
  8683. /* Set cert subject from DER buffer */
  8684. int wc_SetSubjectBuffer(Cert* cert, const byte* der, int derSz)
  8685. {
  8686. return SetNameFromCert(&cert->subject, der, derSz);
  8687. }
  8688. #ifdef WOLFSSL_ALT_NAMES
  8689. /* Set cert alt names from DER buffer */
  8690. int wc_SetAltNamesBuffer(Cert* cert, const byte* der, int derSz)
  8691. {
  8692. return SetAltNamesFromCert(cert, der, derSz);
  8693. }
  8694. /* Set cert dates from DER buffer */
  8695. int wc_SetDatesBuffer(Cert* cert, const byte* der, int derSz)
  8696. {
  8697. return SetDatesFromCert(cert, der, derSz);
  8698. }
  8699. #endif /* WOLFSSL_ALT_NAMES */
  8700. #endif /* WOLFSSL_CERT_GEN */
  8701. #ifdef HAVE_ECC
  8702. /* Der Encode r & s ints into out, outLen is (in/out) size */
  8703. int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r, mp_int* s)
  8704. {
  8705. word32 idx = 0;
  8706. int rSz; /* encoding size */
  8707. int sSz;
  8708. word32 headerSz = 4; /* 2*ASN_TAG + 2*LEN(ENUM) */
  8709. /* If the leading bit on the INTEGER is a 1, add a leading zero */
  8710. int rLeadingZero = mp_leading_bit(r);
  8711. int sLeadingZero = mp_leading_bit(s);
  8712. int rLen = mp_unsigned_bin_size(r); /* big int size */
  8713. int sLen = mp_unsigned_bin_size(s);
  8714. if (*outLen < (rLen + rLeadingZero + sLen + sLeadingZero +
  8715. headerSz + 2)) /* SEQ_TAG + LEN(ENUM) */
  8716. return BUFFER_E;
  8717. idx = SetSequence(rLen + rLeadingZero + sLen+sLeadingZero + headerSz, out);
  8718. /* store r */
  8719. rSz = SetASNIntMP(r, -1, &out[idx]);
  8720. if (rSz < 0)
  8721. return rSz;
  8722. idx += rSz;
  8723. /* store s */
  8724. sSz = SetASNIntMP(s, -1, &out[idx]);
  8725. if (sSz < 0)
  8726. return sSz;
  8727. idx += sSz;
  8728. *outLen = idx;
  8729. return 0;
  8730. }
  8731. /* Der Decode ECC-DSA Signature, r & s stored as big ints */
  8732. int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen, mp_int* r, mp_int* s)
  8733. {
  8734. word32 idx = 0;
  8735. int len = 0;
  8736. if (GetSequence(sig, &idx, &len, sigLen) < 0) {
  8737. return ASN_ECC_KEY_E;
  8738. }
  8739. if ((word32)len > (sigLen - idx)) {
  8740. return ASN_ECC_KEY_E;
  8741. }
  8742. if (GetInt(r, sig, &idx, sigLen) < 0) {
  8743. return ASN_ECC_KEY_E;
  8744. }
  8745. if (GetInt(s, sig, &idx, sigLen) < 0) {
  8746. return ASN_ECC_KEY_E;
  8747. }
  8748. return 0;
  8749. }
  8750. int wc_EccPrivateKeyDecode(const byte* input, word32* inOutIdx, ecc_key* key,
  8751. word32 inSz)
  8752. {
  8753. word32 oidSum;
  8754. int version, length;
  8755. int privSz, pubSz = 0;
  8756. byte b;
  8757. int ret = 0;
  8758. int curve_id = ECC_CURVE_DEF;
  8759. #ifdef WOLFSSL_SMALL_STACK
  8760. byte* priv;
  8761. byte* pub;
  8762. #else
  8763. byte priv[ECC_MAXSIZE+1];
  8764. byte pub[2*(ECC_MAXSIZE+1)]; /* public key has two parts plus header */
  8765. #endif
  8766. byte* pubData = NULL;
  8767. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8768. return BAD_FUNC_ARG;
  8769. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8770. return ASN_PARSE_E;
  8771. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  8772. return ASN_PARSE_E;
  8773. b = input[*inOutIdx];
  8774. *inOutIdx += 1;
  8775. /* priv type */
  8776. if (b != 4 && b != 6 && b != 7)
  8777. return ASN_PARSE_E;
  8778. if (GetLength(input, inOutIdx, &length, inSz) < 0)
  8779. return ASN_PARSE_E;
  8780. if (length > ECC_MAXSIZE)
  8781. return BUFFER_E;
  8782. #ifdef WOLFSSL_SMALL_STACK
  8783. priv = (byte*)XMALLOC(ECC_MAXSIZE+1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8784. if (priv == NULL)
  8785. return MEMORY_E;
  8786. pub = (byte*)XMALLOC(2*(ECC_MAXSIZE+1), NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8787. if (pub == NULL) {
  8788. XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8789. return MEMORY_E;
  8790. }
  8791. #endif
  8792. /* priv key */
  8793. privSz = length;
  8794. XMEMCPY(priv, &input[*inOutIdx], privSz);
  8795. *inOutIdx += length;
  8796. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  8797. /* prefix 0, may have */
  8798. b = input[*inOutIdx];
  8799. if (b == ECC_PREFIX_0) {
  8800. *inOutIdx += 1;
  8801. if (GetLength(input, inOutIdx, &length, inSz) <= 0)
  8802. ret = ASN_PARSE_E;
  8803. else {
  8804. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType,
  8805. inSz);
  8806. if (ret == 0) {
  8807. if ((ret = CheckCurve(oidSum)) < 0)
  8808. ret = ECC_CURVE_OID_E;
  8809. else {
  8810. curve_id = ret;
  8811. ret = 0;
  8812. }
  8813. }
  8814. }
  8815. }
  8816. }
  8817. if (ret == 0 && (*inOutIdx + 1) < inSz) {
  8818. /* prefix 1 */
  8819. b = input[*inOutIdx];
  8820. *inOutIdx += 1;
  8821. if (b != ECC_PREFIX_1) {
  8822. ret = ASN_ECC_KEY_E;
  8823. }
  8824. else if (GetLength(input, inOutIdx, &length, inSz) <= 0) {
  8825. ret = ASN_PARSE_E;
  8826. }
  8827. else {
  8828. /* key header */
  8829. ret = CheckBitString(input, inOutIdx, &length, inSz, 0, NULL);
  8830. if (ret == 0) {
  8831. /* pub key */
  8832. pubSz = length;
  8833. if (pubSz < 2*(ECC_MAXSIZE+1)) {
  8834. XMEMCPY(pub, &input[*inOutIdx], pubSz);
  8835. *inOutIdx += length;
  8836. pubData = pub;
  8837. }
  8838. else
  8839. ret = BUFFER_E;
  8840. }
  8841. }
  8842. }
  8843. if (ret == 0) {
  8844. ret = wc_ecc_import_private_key_ex(priv, privSz, pubData, pubSz, key,
  8845. curve_id);
  8846. }
  8847. #ifdef WOLFSSL_SMALL_STACK
  8848. XFREE(priv, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8849. XFREE(pub, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8850. #endif
  8851. return ret;
  8852. }
  8853. int wc_EccPublicKeyDecode(const byte* input, word32* inOutIdx,
  8854. ecc_key* key, word32 inSz)
  8855. {
  8856. int length;
  8857. int ret;
  8858. #ifdef ECC_CHECK_PUBLIC_KEY_OID
  8859. word32 oidSum;
  8860. #endif
  8861. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  8862. return BAD_FUNC_ARG;
  8863. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8864. return ASN_PARSE_E;
  8865. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  8866. return ASN_PARSE_E;
  8867. ret = SkipObjectId(input, inOutIdx, inSz);
  8868. if (ret != 0)
  8869. return ret;
  8870. /* ecc params information */
  8871. #ifdef ECC_CHECK_PUBLIC_KEY_OID
  8872. ret = GetObjectId(input, inOutIdx, &oidSum, oidIgnoreType, inSz);
  8873. if (ret != 0)
  8874. return ret;
  8875. if (CheckCurve(oidSum) < 0)
  8876. return ECC_CURVE_OID_E;
  8877. #else
  8878. ret = SkipObjectId(input, inOutIdx, inSz);
  8879. if (ret != 0)
  8880. return ret;
  8881. #endif
  8882. /* key header */
  8883. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  8884. if (ret != 0)
  8885. return ret;
  8886. /* This is the raw point data compressed or uncompressed. */
  8887. if (wc_ecc_import_x963(input + *inOutIdx, inSz - *inOutIdx, key) != 0)
  8888. return ASN_ECC_KEY_E;
  8889. return 0;
  8890. }
  8891. /* build DER formatted ECC key, include optional public key if requested,
  8892. * return length on success, negative on error */
  8893. static int wc_BuildEccKeyDer(ecc_key* key, byte* output, word32 inLen,
  8894. int pubIn)
  8895. {
  8896. byte curve[MAX_ALGO_SZ+2];
  8897. byte ver[MAX_VERSION_SZ];
  8898. byte seq[MAX_SEQ_SZ];
  8899. byte *prv = NULL, *pub = NULL;
  8900. int ret, totalSz, curveSz, verSz;
  8901. int privHdrSz = ASN_ECC_HEADER_SZ;
  8902. int pubHdrSz = ASN_ECC_CONTEXT_SZ + ASN_ECC_HEADER_SZ;
  8903. word32 idx = 0, prvidx = 0, pubidx = 0, curveidx = 0;
  8904. word32 seqSz, privSz, pubSz = ECC_BUFSIZE;
  8905. if (key == NULL || output == NULL || inLen == 0)
  8906. return BAD_FUNC_ARG;
  8907. /* curve */
  8908. curve[curveidx++] = ECC_PREFIX_0;
  8909. curveidx++ /* to put the size after computation */;
  8910. curveSz = SetCurve(key, curve+curveidx);
  8911. if (curveSz < 0)
  8912. return curveSz;
  8913. /* set computed size */
  8914. curve[1] = (byte)curveSz;
  8915. curveidx += curveSz;
  8916. /* private */
  8917. privSz = key->dp->size;
  8918. prv = (byte*)XMALLOC(privSz + privHdrSz + MAX_SEQ_SZ,
  8919. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8920. if (prv == NULL) {
  8921. return MEMORY_E;
  8922. }
  8923. prvidx += SetOctetString8Bit(key->dp->size, &prv[prvidx]);
  8924. ret = wc_ecc_export_private_only(key, prv + prvidx, &privSz);
  8925. if (ret < 0) {
  8926. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8927. return ret;
  8928. }
  8929. prvidx += privSz;
  8930. /* pubIn */
  8931. if (pubIn) {
  8932. ret = wc_ecc_export_x963(key, NULL, &pubSz);
  8933. if (ret != LENGTH_ONLY_E) {
  8934. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8935. return ret;
  8936. }
  8937. pub = (byte*)XMALLOC(pubSz + pubHdrSz + MAX_SEQ_SZ,
  8938. key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8939. if (pub == NULL) {
  8940. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8941. return MEMORY_E;
  8942. }
  8943. pub[pubidx++] = ECC_PREFIX_1;
  8944. if (pubSz > 128) /* leading zero + extra size byte */
  8945. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 2, pub+pubidx);
  8946. else /* leading zero */
  8947. pubidx += SetLength(pubSz + ASN_ECC_CONTEXT_SZ + 1, pub+pubidx);
  8948. /* SetBitString adds leading zero */
  8949. pubidx += SetBitString(pubSz, 0, pub + pubidx);
  8950. ret = wc_ecc_export_x963(key, pub + pubidx, &pubSz);
  8951. if (ret != 0) {
  8952. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8953. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8954. return ret;
  8955. }
  8956. pubidx += pubSz;
  8957. }
  8958. /* make headers */
  8959. verSz = SetMyVersion(1, ver, FALSE);
  8960. seqSz = SetSequence(verSz + prvidx + pubidx + curveidx, seq);
  8961. totalSz = prvidx + pubidx + curveidx + verSz + seqSz;
  8962. if (totalSz > (int)inLen) {
  8963. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8964. if (pubIn) {
  8965. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8966. }
  8967. return BAD_FUNC_ARG;
  8968. }
  8969. /* write out */
  8970. /* seq */
  8971. XMEMCPY(output + idx, seq, seqSz);
  8972. idx = seqSz;
  8973. /* ver */
  8974. XMEMCPY(output + idx, ver, verSz);
  8975. idx += verSz;
  8976. /* private */
  8977. XMEMCPY(output + idx, prv, prvidx);
  8978. idx += prvidx;
  8979. XFREE(prv, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8980. /* curve */
  8981. XMEMCPY(output + idx, curve, curveidx);
  8982. idx += curveidx;
  8983. /* pubIn */
  8984. if (pubIn) {
  8985. XMEMCPY(output + idx, pub, pubidx);
  8986. /* idx += pubidx; not used after write, if more data remove comment */
  8987. XFREE(pub, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  8988. }
  8989. return totalSz;
  8990. }
  8991. /* Write a Private ecc key, including public to DER format,
  8992. * length on success else < 0 */
  8993. int wc_EccKeyToDer(ecc_key* key, byte* output, word32 inLen)
  8994. {
  8995. return wc_BuildEccKeyDer(key, output, inLen, 1);
  8996. }
  8997. /* Write only private ecc key to DER format,
  8998. * length on success else < 0 */
  8999. int wc_EccPrivateKeyToDer(ecc_key* key, byte* output, word32 inLen)
  9000. {
  9001. return wc_BuildEccKeyDer(key, output, inLen, 0);
  9002. }
  9003. /* Write only private ecc key to unencrypted PKCS#8 format.
  9004. *
  9005. * If output is NULL, places required PKCS#8 buffer size in outLen and
  9006. * returns LENGTH_ONLY_E.
  9007. *
  9008. * return length on success else < 0 */
  9009. int wc_EccPrivateKeyToPKCS8(ecc_key* key, byte* output, word32* outLen)
  9010. {
  9011. int ret, tmpDerSz;
  9012. int algoID = 0;
  9013. word32 oidSz = 0;
  9014. word32 pkcs8Sz = 0;
  9015. const byte* curveOID = NULL;
  9016. byte* tmpDer = NULL;
  9017. if (key == NULL || outLen == NULL)
  9018. return BAD_FUNC_ARG;
  9019. /* set algoID, get curve OID */
  9020. algoID = ECDSAk;
  9021. ret = wc_ecc_get_oid(key->dp->oidSum, &curveOID, &oidSz);
  9022. if (ret < 0)
  9023. return ret;
  9024. /* temp buffer for plain DER key */
  9025. tmpDer = (byte*)XMALLOC(ECC_BUFSIZE, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9026. if (tmpDer == NULL)
  9027. return MEMORY_E;
  9028. XMEMSET(tmpDer, 0, ECC_BUFSIZE);
  9029. tmpDerSz = wc_BuildEccKeyDer(key, tmpDer, ECC_BUFSIZE, 0);
  9030. if (tmpDerSz < 0) {
  9031. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9032. return tmpDerSz;
  9033. }
  9034. /* get pkcs8 expected output size */
  9035. ret = wc_CreatePKCS8Key(NULL, &pkcs8Sz, tmpDer, tmpDerSz, algoID,
  9036. curveOID, oidSz);
  9037. if (ret != LENGTH_ONLY_E) {
  9038. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9039. return ret;
  9040. }
  9041. if (output == NULL) {
  9042. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9043. *outLen = pkcs8Sz;
  9044. return LENGTH_ONLY_E;
  9045. } else if (*outLen < pkcs8Sz) {
  9046. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9047. WOLFSSL_MSG("Input buffer too small for ECC PKCS#8 key");
  9048. return BUFFER_E;
  9049. }
  9050. ret = wc_CreatePKCS8Key(output, &pkcs8Sz, tmpDer, tmpDerSz,
  9051. algoID, curveOID, oidSz);
  9052. if (ret < 0) {
  9053. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9054. return ret;
  9055. }
  9056. XFREE(tmpDer, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  9057. *outLen = ret;
  9058. return ret;
  9059. }
  9060. #endif /* HAVE_ECC */
  9061. #ifdef HAVE_ED25519
  9062. int wc_Ed25519PrivateKeyDecode(const byte* input, word32* inOutIdx,
  9063. ed25519_key* key, word32 inSz)
  9064. {
  9065. word32 oid;
  9066. int ret, version, length, endKeyIdx, privSz, pubSz;
  9067. const byte* priv;
  9068. const byte* pub;
  9069. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  9070. return BAD_FUNC_ARG;
  9071. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9072. return ASN_PARSE_E;
  9073. endKeyIdx = *inOutIdx + length;
  9074. if (GetMyVersion(input, inOutIdx, &version, inSz) < 0)
  9075. return ASN_PARSE_E;
  9076. if (version != 0) {
  9077. WOLFSSL_MSG("Unrecognized version of ED25519 private key");
  9078. return ASN_PARSE_E;
  9079. }
  9080. if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0)
  9081. return ASN_PARSE_E;
  9082. if (oid != ED25519k)
  9083. return ASN_PARSE_E;
  9084. if (GetOctetString(input, inOutIdx, &length, inSz) < 0)
  9085. return ASN_PARSE_E;
  9086. if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0)
  9087. return ASN_PARSE_E;
  9088. priv = input + *inOutIdx;
  9089. *inOutIdx += privSz;
  9090. if (endKeyIdx == (int)*inOutIdx) {
  9091. ret = wc_ed25519_import_private_only(priv, privSz, key);
  9092. }
  9093. else {
  9094. if (GetASNHeader(input, ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1,
  9095. inOutIdx, &length, inSz) < 0) {
  9096. return ASN_PARSE_E;
  9097. }
  9098. if (GetOctetString(input, inOutIdx, &pubSz, inSz) < 0)
  9099. return ASN_PARSE_E;
  9100. pub = input + *inOutIdx;
  9101. *inOutIdx += pubSz;
  9102. ret = wc_ed25519_import_private_key(priv, privSz, pub, pubSz, key);
  9103. }
  9104. if (ret == 0 && endKeyIdx != (int)*inOutIdx)
  9105. return ASN_PARSE_E;
  9106. return ret;
  9107. }
  9108. int wc_Ed25519PublicKeyDecode(const byte* input, word32* inOutIdx,
  9109. ed25519_key* key, word32 inSz)
  9110. {
  9111. int length;
  9112. int ret;
  9113. #ifdef ECC_CHECK_PUBLIC_KEY_OID
  9114. word32 oidSum;
  9115. #endif
  9116. if (input == NULL || inOutIdx == NULL || key == NULL || inSz == 0)
  9117. return BAD_FUNC_ARG;
  9118. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9119. return ASN_PARSE_E;
  9120. if (GetSequence(input, inOutIdx, &length, inSz) < 0)
  9121. return ASN_PARSE_E;
  9122. ret = SkipObjectId(input, inOutIdx, inSz);
  9123. if (ret != 0)
  9124. return ret;
  9125. /* key header */
  9126. ret = CheckBitString(input, inOutIdx, NULL, inSz, 1, NULL);
  9127. if (ret != 0)
  9128. return ret;
  9129. /* This is the raw point data compressed or uncompressed. */
  9130. if (wc_ed25519_import_public(input + *inOutIdx, inSz - *inOutIdx, key) != 0)
  9131. return ASN_ECC_KEY_E;
  9132. return 0;
  9133. }
  9134. #ifdef WOLFSSL_KEY_GEN
  9135. /* build DER formatted ED25519 key,
  9136. * return length on success, negative on error */
  9137. static int wc_BuildEd25519KeyDer(ed25519_key* key, byte* output, word32 inLen,
  9138. int pubOut)
  9139. {
  9140. byte algoArray[MAX_ALGO_SZ];
  9141. byte ver[MAX_VERSION_SZ];
  9142. byte seq[MAX_SEQ_SZ];
  9143. int ret;
  9144. word32 idx = 0, seqSz, verSz, algoSz, privSz, pubSz = 0;
  9145. if (key == NULL || output == NULL || inLen == 0)
  9146. return BAD_FUNC_ARG;
  9147. if (pubOut)
  9148. pubSz = 2 + 2 + ED25519_PUB_KEY_SIZE;
  9149. privSz = 2 + 2 + ED25519_KEY_SIZE;
  9150. algoSz = SetAlgoID(ED25519k, algoArray, oidKeyType, 0);
  9151. verSz = SetMyVersion(0, ver, FALSE);
  9152. seqSz = SetSequence(verSz + algoSz + privSz + pubSz, seq);
  9153. if (seqSz + verSz + algoSz + privSz + pubSz > inLen)
  9154. return BAD_FUNC_ARG;
  9155. /* write out */
  9156. /* seq */
  9157. XMEMCPY(output + idx, seq, seqSz);
  9158. idx = seqSz;
  9159. /* ver */
  9160. XMEMCPY(output + idx, ver, verSz);
  9161. idx += verSz;
  9162. /* algo */
  9163. XMEMCPY(output + idx, algoArray, algoSz);
  9164. idx += algoSz;
  9165. /* privKey */
  9166. idx += SetOctetString(2 + ED25519_KEY_SIZE, output + idx);
  9167. idx += SetOctetString(ED25519_KEY_SIZE, output + idx);
  9168. ret = wc_ed25519_export_private_only(key, output + idx, &privSz);
  9169. if (ret != 0)
  9170. return ret;
  9171. idx += privSz;
  9172. /* pubKey */
  9173. if (pubOut) {
  9174. idx += SetExplicit(1, 2 + ED25519_PUB_KEY_SIZE, output + idx);
  9175. idx += SetOctetString(ED25519_KEY_SIZE, output + idx);
  9176. ret = wc_ed25519_export_public(key, output + idx, &pubSz);
  9177. if (ret != 0)
  9178. return ret;
  9179. idx += pubSz;
  9180. }
  9181. return idx;
  9182. }
  9183. /* Write a Private ecc key, including public to DER format,
  9184. * length on success else < 0 */
  9185. int wc_Ed25519KeyToDer(ed25519_key* key, byte* output, word32 inLen)
  9186. {
  9187. return wc_BuildEd25519KeyDer(key, output, inLen, 1);
  9188. }
  9189. /* Write only private ecc key to DER format,
  9190. * length on success else < 0 */
  9191. int wc_Ed25519PrivateKeyToDer(ed25519_key* key, byte* output, word32 inLen)
  9192. {
  9193. return wc_BuildEd25519KeyDer(key, output, inLen, 0);
  9194. }
  9195. #endif /* WOLFSSL_KEY_GEN */
  9196. #endif /* HAVE_ED25519 */
  9197. #if defined(HAVE_OCSP) || defined(HAVE_CRL)
  9198. /* Get raw Date only, no processing, 0 on success */
  9199. static int GetBasicDate(const byte* source, word32* idx, byte* date,
  9200. byte* format, int maxIdx)
  9201. {
  9202. int length;
  9203. WOLFSSL_ENTER("GetBasicDate");
  9204. *format = source[*idx];
  9205. *idx += 1;
  9206. if (*format != ASN_UTC_TIME && *format != ASN_GENERALIZED_TIME)
  9207. return ASN_TIME_E;
  9208. if (GetLength(source, idx, &length, maxIdx) < 0)
  9209. return ASN_PARSE_E;
  9210. if (length > MAX_DATE_SIZE || length < MIN_DATE_SIZE)
  9211. return ASN_DATE_SZ_E;
  9212. XMEMCPY(date, &source[*idx], length);
  9213. *idx += length;
  9214. return 0;
  9215. }
  9216. #endif
  9217. #ifdef HAVE_OCSP
  9218. static int GetEnumerated(const byte* input, word32* inOutIdx, int *value)
  9219. {
  9220. word32 idx = *inOutIdx;
  9221. word32 len;
  9222. WOLFSSL_ENTER("GetEnumerated");
  9223. *value = 0;
  9224. if (input[idx++] != ASN_ENUMERATED)
  9225. return ASN_PARSE_E;
  9226. len = input[idx++];
  9227. if (len > 4)
  9228. return ASN_PARSE_E;
  9229. while (len--) {
  9230. *value = *value << 8 | input[idx++];
  9231. }
  9232. *inOutIdx = idx;
  9233. return *value;
  9234. }
  9235. static int DecodeSingleResponse(byte* source,
  9236. word32* ioIndex, OcspResponse* resp, word32 size)
  9237. {
  9238. word32 idx = *ioIndex, prevIndex, oid;
  9239. int length, wrapperSz;
  9240. CertStatus* cs = resp->status;
  9241. int ret;
  9242. WOLFSSL_ENTER("DecodeSingleResponse");
  9243. /* Outer wrapper of the SEQUENCE OF Single Responses. */
  9244. if (GetSequence(source, &idx, &wrapperSz, size) < 0)
  9245. return ASN_PARSE_E;
  9246. prevIndex = idx;
  9247. /* When making a request, we only request one status on one certificate
  9248. * at a time. There should only be one SingleResponse */
  9249. /* Wrapper around the Single Response */
  9250. if (GetSequence(source, &idx, &length, size) < 0)
  9251. return ASN_PARSE_E;
  9252. /* Wrapper around the CertID */
  9253. if (GetSequence(source, &idx, &length, size) < 0)
  9254. return ASN_PARSE_E;
  9255. /* Skip the hash algorithm */
  9256. if (GetAlgoId(source, &idx, &oid, oidIgnoreType, size) < 0)
  9257. return ASN_PARSE_E;
  9258. /* Save reference to the hash of CN */
  9259. ret = GetOctetString(source, &idx, &length, size);
  9260. if (ret < 0)
  9261. return ret;
  9262. resp->issuerHash = source + idx;
  9263. idx += length;
  9264. /* Save reference to the hash of the issuer public key */
  9265. ret = GetOctetString(source, &idx, &length, size);
  9266. if (ret < 0)
  9267. return ret;
  9268. resp->issuerKeyHash = source + idx;
  9269. idx += length;
  9270. /* Get serial number */
  9271. if (GetSerialNumber(source, &idx, cs->serial, &cs->serialSz, size) < 0)
  9272. return ASN_PARSE_E;
  9273. /* CertStatus */
  9274. switch (source[idx++])
  9275. {
  9276. case (ASN_CONTEXT_SPECIFIC | CERT_GOOD):
  9277. cs->status = CERT_GOOD;
  9278. idx++;
  9279. break;
  9280. case (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | CERT_REVOKED):
  9281. cs->status = CERT_REVOKED;
  9282. if (GetLength(source, &idx, &length, size) < 0)
  9283. return ASN_PARSE_E;
  9284. idx += length;
  9285. break;
  9286. case (ASN_CONTEXT_SPECIFIC | CERT_UNKNOWN):
  9287. cs->status = CERT_UNKNOWN;
  9288. idx++;
  9289. break;
  9290. default:
  9291. return ASN_PARSE_E;
  9292. }
  9293. #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  9294. cs->thisDateAsn = source + idx;
  9295. #endif
  9296. if (GetBasicDate(source, &idx, cs->thisDate,
  9297. &cs->thisDateFormat, size) < 0)
  9298. return ASN_PARSE_E;
  9299. #ifndef NO_ASN_TIME
  9300. if (!XVALIDATE_DATE(cs->thisDate, cs->thisDateFormat, BEFORE))
  9301. return ASN_BEFORE_DATE_E;
  9302. #endif
  9303. /* The following items are optional. Only check for them if there is more
  9304. * unprocessed data in the singleResponse wrapper. */
  9305. if (((int)(idx - prevIndex) < wrapperSz) &&
  9306. (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 0)))
  9307. {
  9308. idx++;
  9309. if (GetLength(source, &idx, &length, size) < 0)
  9310. return ASN_PARSE_E;
  9311. #if defined(WOLFSSL_NGINX) || defined(WOLFSSL_HAPROXY)
  9312. cs->nextDateAsn = source + idx;
  9313. #endif
  9314. if (GetBasicDate(source, &idx, cs->nextDate,
  9315. &cs->nextDateFormat, size) < 0)
  9316. return ASN_PARSE_E;
  9317. #ifndef NO_ASN_TIME
  9318. if (!XVALIDATE_DATE(cs->nextDate, cs->nextDateFormat, AFTER))
  9319. return ASN_AFTER_DATE_E;
  9320. #endif
  9321. }
  9322. if (((int)(idx - prevIndex) < wrapperSz) &&
  9323. (source[idx] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1)))
  9324. {
  9325. idx++;
  9326. if (GetLength(source, &idx, &length, size) < 0)
  9327. return ASN_PARSE_E;
  9328. idx += length;
  9329. }
  9330. *ioIndex = idx;
  9331. return 0;
  9332. }
  9333. static int DecodeOcspRespExtensions(byte* source,
  9334. word32* ioIndex, OcspResponse* resp, word32 sz)
  9335. {
  9336. word32 idx = *ioIndex;
  9337. int length;
  9338. int ext_bound; /* boundary index for the sequence of extensions */
  9339. word32 oid;
  9340. int ret;
  9341. WOLFSSL_ENTER("DecodeOcspRespExtensions");
  9342. if ((idx + 1) > sz)
  9343. return BUFFER_E;
  9344. if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC | 1))
  9345. return ASN_PARSE_E;
  9346. if (GetLength(source, &idx, &length, sz) < 0)
  9347. return ASN_PARSE_E;
  9348. if (GetSequence(source, &idx, &length, sz) < 0)
  9349. return ASN_PARSE_E;
  9350. ext_bound = idx + length;
  9351. while (idx < (word32)ext_bound) {
  9352. if (GetSequence(source, &idx, &length, sz) < 0) {
  9353. WOLFSSL_MSG("\tfail: should be a SEQUENCE");
  9354. return ASN_PARSE_E;
  9355. }
  9356. oid = 0;
  9357. if (GetObjectId(source, &idx, &oid, oidOcspType, sz) < 0) {
  9358. WOLFSSL_MSG("\tfail: OBJECT ID");
  9359. return ASN_PARSE_E;
  9360. }
  9361. /* check for critical flag */
  9362. if (source[idx] == ASN_BOOLEAN) {
  9363. WOLFSSL_MSG("\tfound optional critical flag, moving past");
  9364. ret = GetBoolean(source, &idx, sz);
  9365. if (ret < 0)
  9366. return ret;
  9367. }
  9368. ret = GetOctetString(source, &idx, &length, sz);
  9369. if (ret < 0)
  9370. return ret;
  9371. if (oid == OCSP_NONCE_OID) {
  9372. /* get data inside extra OCTET_STRING */
  9373. ret = GetOctetString(source, &idx, &length, sz);
  9374. if (ret < 0)
  9375. return ret;
  9376. resp->nonce = source + idx;
  9377. resp->nonceSz = length;
  9378. }
  9379. idx += length;
  9380. }
  9381. *ioIndex = idx;
  9382. return 0;
  9383. }
  9384. static int DecodeResponseData(byte* source,
  9385. word32* ioIndex, OcspResponse* resp, word32 size)
  9386. {
  9387. word32 idx = *ioIndex, prev_idx;
  9388. int length;
  9389. int version;
  9390. word32 responderId = 0;
  9391. WOLFSSL_ENTER("DecodeResponseData");
  9392. resp->response = source + idx;
  9393. prev_idx = idx;
  9394. if (GetSequence(source, &idx, &length, size) < 0)
  9395. return ASN_PARSE_E;
  9396. resp->responseSz = length + idx - prev_idx;
  9397. /* Get version. It is an EXPLICIT[0] DEFAULT(0) value. If this
  9398. * item isn't an EXPLICIT[0], then set version to zero and move
  9399. * onto the next item.
  9400. */
  9401. if (source[idx] == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED))
  9402. {
  9403. idx += 2; /* Eat the value and length */
  9404. if (GetMyVersion(source, &idx, &version, size) < 0)
  9405. return ASN_PARSE_E;
  9406. } else
  9407. version = 0;
  9408. responderId = source[idx++];
  9409. if ((responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1)) ||
  9410. (responderId == (ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 2)))
  9411. {
  9412. if (GetLength(source, &idx, &length, size) < 0)
  9413. return ASN_PARSE_E;
  9414. idx += length;
  9415. }
  9416. else
  9417. return ASN_PARSE_E;
  9418. /* save pointer to the producedAt time */
  9419. if (GetBasicDate(source, &idx, resp->producedDate,
  9420. &resp->producedDateFormat, size) < 0)
  9421. return ASN_PARSE_E;
  9422. if (DecodeSingleResponse(source, &idx, resp, size) < 0)
  9423. return ASN_PARSE_E;
  9424. /*
  9425. * Check the length of the ResponseData against the current index to
  9426. * see if there are extensions, they are optional.
  9427. */
  9428. if (idx - prev_idx < resp->responseSz)
  9429. if (DecodeOcspRespExtensions(source, &idx, resp, size) < 0)
  9430. return ASN_PARSE_E;
  9431. *ioIndex = idx;
  9432. return 0;
  9433. }
  9434. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  9435. static int DecodeCerts(byte* source,
  9436. word32* ioIndex, OcspResponse* resp, word32 size)
  9437. {
  9438. word32 idx = *ioIndex;
  9439. WOLFSSL_ENTER("DecodeCerts");
  9440. if (source[idx++] == (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  9441. {
  9442. int length;
  9443. if (GetLength(source, &idx, &length, size) < 0)
  9444. return ASN_PARSE_E;
  9445. if (GetSequence(source, &idx, &length, size) < 0)
  9446. return ASN_PARSE_E;
  9447. resp->cert = source + idx;
  9448. resp->certSz = length;
  9449. idx += length;
  9450. }
  9451. *ioIndex = idx;
  9452. return 0;
  9453. }
  9454. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  9455. static int DecodeBasicOcspResponse(byte* source, word32* ioIndex,
  9456. OcspResponse* resp, word32 size, void* cm, void* heap, int noVerify)
  9457. {
  9458. int length;
  9459. word32 idx = *ioIndex;
  9460. word32 end_index;
  9461. int ret;
  9462. int sigLength;
  9463. WOLFSSL_ENTER("DecodeBasicOcspResponse");
  9464. (void)heap;
  9465. if (GetSequence(source, &idx, &length, size) < 0)
  9466. return ASN_PARSE_E;
  9467. if (idx + length > size)
  9468. return ASN_INPUT_E;
  9469. end_index = idx + length;
  9470. if (DecodeResponseData(source, &idx, resp, size) < 0)
  9471. return ASN_PARSE_E;
  9472. /* Get the signature algorithm */
  9473. if (GetAlgoId(source, &idx, &resp->sigOID, oidSigType, size) < 0)
  9474. return ASN_PARSE_E;
  9475. ret = CheckBitString(source, &idx, &sigLength, size, 1, NULL);
  9476. if (ret != 0)
  9477. return ret;
  9478. resp->sigSz = sigLength;
  9479. resp->sig = source + idx;
  9480. idx += sigLength;
  9481. /*
  9482. * Check the length of the BasicOcspResponse against the current index to
  9483. * see if there are certificates, they are optional.
  9484. */
  9485. #ifndef WOLFSSL_NO_OCSP_OPTIONAL_CERTS
  9486. if (idx < end_index)
  9487. {
  9488. DecodedCert cert;
  9489. if (DecodeCerts(source, &idx, resp, size) < 0)
  9490. return ASN_PARSE_E;
  9491. InitDecodedCert(&cert, resp->cert, resp->certSz, heap);
  9492. /* Don't verify if we don't have access to Cert Manager. */
  9493. ret = ParseCertRelative(&cert, CERT_TYPE,
  9494. noVerify ? NO_VERIFY : VERIFY_OCSP, cm);
  9495. if (ret < 0) {
  9496. WOLFSSL_MSG("\tOCSP Responder certificate parsing failed");
  9497. FreeDecodedCert(&cert);
  9498. return ret;
  9499. }
  9500. #ifndef WOLFSSL_NO_OCSP_ISSUER_CHECK
  9501. if ((cert.extExtKeyUsage & EXTKEYUSE_OCSP_SIGN) == 0) {
  9502. if (XMEMCMP(cert.subjectHash,
  9503. resp->issuerHash, KEYID_SIZE) == 0) {
  9504. WOLFSSL_MSG("\tOCSP Response signed by issuer");
  9505. }
  9506. else {
  9507. WOLFSSL_MSG("\tOCSP Responder key usage check failed");
  9508. FreeDecodedCert(&cert);
  9509. return BAD_OCSP_RESPONDER;
  9510. }
  9511. }
  9512. #endif
  9513. /* ConfirmSignature is blocking here */
  9514. ret = ConfirmSignature(&cert.sigCtx,
  9515. resp->response, resp->responseSz,
  9516. cert.publicKey, cert.pubKeySize, cert.keyOID,
  9517. resp->sig, resp->sigSz, resp->sigOID);
  9518. FreeDecodedCert(&cert);
  9519. if (ret != 0) {
  9520. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  9521. return ASN_OCSP_CONFIRM_E;
  9522. }
  9523. }
  9524. else
  9525. #endif /* WOLFSSL_NO_OCSP_OPTIONAL_CERTS */
  9526. {
  9527. Signer* ca = NULL;
  9528. int sigValid = -1;
  9529. #ifndef NO_SKID
  9530. ca = GetCA(cm, resp->issuerKeyHash);
  9531. #else
  9532. ca = GetCA(cm, resp->issuerHash);
  9533. #endif
  9534. if (ca) {
  9535. SignatureCtx sigCtx;
  9536. InitSignatureCtx(&sigCtx, heap, INVALID_DEVID);
  9537. /* ConfirmSignature is blocking here */
  9538. sigValid = ConfirmSignature(&sigCtx, resp->response,
  9539. resp->responseSz, ca->publicKey, ca->pubKeySize, ca->keyOID,
  9540. resp->sig, resp->sigSz, resp->sigOID);
  9541. }
  9542. if (ca == NULL || sigValid != 0) {
  9543. WOLFSSL_MSG("\tOCSP Confirm signature failed");
  9544. return ASN_OCSP_CONFIRM_E;
  9545. }
  9546. (void)noVerify;
  9547. }
  9548. *ioIndex = idx;
  9549. return 0;
  9550. }
  9551. void InitOcspResponse(OcspResponse* resp, CertStatus* status,
  9552. byte* source, word32 inSz)
  9553. {
  9554. WOLFSSL_ENTER("InitOcspResponse");
  9555. XMEMSET(status, 0, sizeof(CertStatus));
  9556. XMEMSET(resp, 0, sizeof(OcspResponse));
  9557. resp->responseStatus = -1;
  9558. resp->status = status;
  9559. resp->source = source;
  9560. resp->maxIdx = inSz;
  9561. }
  9562. int OcspResponseDecode(OcspResponse* resp, void* cm, void* heap, int noVerify)
  9563. {
  9564. int ret;
  9565. int length = 0;
  9566. word32 idx = 0;
  9567. byte* source = resp->source;
  9568. word32 size = resp->maxIdx;
  9569. word32 oid;
  9570. WOLFSSL_ENTER("OcspResponseDecode");
  9571. /* peel the outer SEQUENCE wrapper */
  9572. if (GetSequence(source, &idx, &length, size) < 0)
  9573. return ASN_PARSE_E;
  9574. /* First get the responseStatus, an ENUMERATED */
  9575. if (GetEnumerated(source, &idx, &resp->responseStatus) < 0)
  9576. return ASN_PARSE_E;
  9577. if (resp->responseStatus != OCSP_SUCCESSFUL)
  9578. return 0;
  9579. /* Next is an EXPLICIT record called ResponseBytes, OPTIONAL */
  9580. if (idx >= size)
  9581. return ASN_INPUT_E;
  9582. if (source[idx++] != (ASN_CONSTRUCTED | ASN_CONTEXT_SPECIFIC))
  9583. return ASN_PARSE_E;
  9584. if (GetLength(source, &idx, &length, size) < 0)
  9585. return ASN_PARSE_E;
  9586. /* Get the responseBytes SEQUENCE */
  9587. if (GetSequence(source, &idx, &length, size) < 0)
  9588. return ASN_PARSE_E;
  9589. /* Check ObjectID for the resposeBytes */
  9590. if (GetObjectId(source, &idx, &oid, oidOcspType, size) < 0)
  9591. return ASN_PARSE_E;
  9592. if (oid != OCSP_BASIC_OID)
  9593. return ASN_PARSE_E;
  9594. ret = GetOctetString(source, &idx, &length, size);
  9595. if (ret < 0)
  9596. return ret;
  9597. ret = DecodeBasicOcspResponse(source, &idx, resp, size, cm, heap, noVerify);
  9598. if (ret < 0)
  9599. return ret;
  9600. return 0;
  9601. }
  9602. word32 EncodeOcspRequestExtensions(OcspRequest* req, byte* output, word32 size)
  9603. {
  9604. static const byte NonceObjId[] = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07,
  9605. 0x30, 0x01, 0x02 };
  9606. byte seqArray[5][MAX_SEQ_SZ];
  9607. word32 seqSz[5], totalSz = (word32)sizeof(NonceObjId);
  9608. WOLFSSL_ENTER("SetOcspReqExtensions");
  9609. if (!req || !output || !req->nonceSz)
  9610. return 0;
  9611. totalSz += req->nonceSz;
  9612. totalSz += seqSz[0] = SetOctetString(req->nonceSz, seqArray[0]);
  9613. totalSz += seqSz[1] = SetOctetString(req->nonceSz + seqSz[0], seqArray[1]);
  9614. totalSz += seqSz[2] = SetObjectId(sizeof(NonceObjId), seqArray[2]);
  9615. totalSz += seqSz[3] = SetSequence(totalSz, seqArray[3]);
  9616. totalSz += seqSz[4] = SetSequence(totalSz, seqArray[4]);
  9617. if (totalSz > size)
  9618. return 0;
  9619. totalSz = 0;
  9620. XMEMCPY(output + totalSz, seqArray[4], seqSz[4]);
  9621. totalSz += seqSz[4];
  9622. XMEMCPY(output + totalSz, seqArray[3], seqSz[3]);
  9623. totalSz += seqSz[3];
  9624. XMEMCPY(output + totalSz, seqArray[2], seqSz[2]);
  9625. totalSz += seqSz[2];
  9626. XMEMCPY(output + totalSz, NonceObjId, sizeof(NonceObjId));
  9627. totalSz += (word32)sizeof(NonceObjId);
  9628. XMEMCPY(output + totalSz, seqArray[1], seqSz[1]);
  9629. totalSz += seqSz[1];
  9630. XMEMCPY(output + totalSz, seqArray[0], seqSz[0]);
  9631. totalSz += seqSz[0];
  9632. XMEMCPY(output + totalSz, req->nonce, req->nonceSz);
  9633. totalSz += req->nonceSz;
  9634. return totalSz;
  9635. }
  9636. int EncodeOcspRequest(OcspRequest* req, byte* output, word32 size)
  9637. {
  9638. byte seqArray[5][MAX_SEQ_SZ];
  9639. /* The ASN.1 of the OCSP Request is an onion of sequences */
  9640. byte algoArray[MAX_ALGO_SZ];
  9641. byte issuerArray[MAX_ENCODED_DIG_SZ];
  9642. byte issuerKeyArray[MAX_ENCODED_DIG_SZ];
  9643. byte snArray[MAX_SN_SZ];
  9644. byte extArray[MAX_OCSP_EXT_SZ];
  9645. word32 seqSz[5], algoSz, issuerSz, issuerKeySz, extSz, totalSz;
  9646. int i, snSz;
  9647. WOLFSSL_ENTER("EncodeOcspRequest");
  9648. #ifdef NO_SHA
  9649. algoSz = SetAlgoID(SHA256h, algoArray, oidHashType, 0);
  9650. #else
  9651. algoSz = SetAlgoID(SHAh, algoArray, oidHashType, 0);
  9652. #endif
  9653. issuerSz = SetDigest(req->issuerHash, KEYID_SIZE, issuerArray);
  9654. issuerKeySz = SetDigest(req->issuerKeyHash, KEYID_SIZE, issuerKeyArray);
  9655. snSz = SetSerialNumber(req->serial, req->serialSz, snArray, MAX_SN_SZ);
  9656. extSz = 0;
  9657. if (snSz < 0)
  9658. return snSz;
  9659. if (req->nonceSz) {
  9660. /* TLS Extensions use this function too - put extensions after
  9661. * ASN.1: Context Specific [2].
  9662. */
  9663. extSz = EncodeOcspRequestExtensions(req, extArray + 2,
  9664. OCSP_NONCE_EXT_SZ);
  9665. extSz += SetExplicit(2, extSz, extArray);
  9666. }
  9667. totalSz = algoSz + issuerSz + issuerKeySz + snSz;
  9668. for (i = 4; i >= 0; i--) {
  9669. seqSz[i] = SetSequence(totalSz, seqArray[i]);
  9670. totalSz += seqSz[i];
  9671. if (i == 2) totalSz += extSz;
  9672. }
  9673. if (output == NULL)
  9674. return totalSz;
  9675. if (totalSz > size)
  9676. return BUFFER_E;
  9677. totalSz = 0;
  9678. for (i = 0; i < 5; i++) {
  9679. XMEMCPY(output + totalSz, seqArray[i], seqSz[i]);
  9680. totalSz += seqSz[i];
  9681. }
  9682. XMEMCPY(output + totalSz, algoArray, algoSz);
  9683. totalSz += algoSz;
  9684. XMEMCPY(output + totalSz, issuerArray, issuerSz);
  9685. totalSz += issuerSz;
  9686. XMEMCPY(output + totalSz, issuerKeyArray, issuerKeySz);
  9687. totalSz += issuerKeySz;
  9688. XMEMCPY(output + totalSz, snArray, snSz);
  9689. totalSz += snSz;
  9690. if (extSz != 0) {
  9691. XMEMCPY(output + totalSz, extArray, extSz);
  9692. totalSz += extSz;
  9693. }
  9694. return totalSz;
  9695. }
  9696. int InitOcspRequest(OcspRequest* req, DecodedCert* cert, byte useNonce,
  9697. void* heap)
  9698. {
  9699. int ret;
  9700. WOLFSSL_ENTER("InitOcspRequest");
  9701. if (req == NULL)
  9702. return BAD_FUNC_ARG;
  9703. ForceZero(req, sizeof(OcspRequest));
  9704. req->heap = heap;
  9705. if (cert) {
  9706. XMEMCPY(req->issuerHash, cert->issuerHash, KEYID_SIZE);
  9707. XMEMCPY(req->issuerKeyHash, cert->issuerKeyHash, KEYID_SIZE);
  9708. req->serial = (byte*)XMALLOC(cert->serialSz, req->heap,
  9709. DYNAMIC_TYPE_OCSP_REQUEST);
  9710. if (req->serial == NULL)
  9711. return MEMORY_E;
  9712. XMEMCPY(req->serial, cert->serial, cert->serialSz);
  9713. req->serialSz = cert->serialSz;
  9714. if (cert->extAuthInfoSz != 0 && cert->extAuthInfo != NULL) {
  9715. req->url = (byte*)XMALLOC(cert->extAuthInfoSz, req->heap,
  9716. DYNAMIC_TYPE_OCSP_REQUEST);
  9717. if (req->url == NULL) {
  9718. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP);
  9719. return MEMORY_E;
  9720. }
  9721. XMEMCPY(req->url, cert->extAuthInfo, cert->extAuthInfoSz);
  9722. req->urlSz = cert->extAuthInfoSz;
  9723. }
  9724. }
  9725. if (useNonce) {
  9726. WC_RNG rng;
  9727. #ifndef HAVE_FIPS
  9728. ret = wc_InitRng_ex(&rng, req->heap, INVALID_DEVID);
  9729. #else
  9730. ret = wc_InitRng(&rng);
  9731. #endif
  9732. if (ret != 0) {
  9733. WOLFSSL_MSG("\tCannot initialize RNG. Skipping the OSCP Nonce.");
  9734. } else {
  9735. if (wc_RNG_GenerateBlock(&rng, req->nonce, MAX_OCSP_NONCE_SZ) != 0)
  9736. WOLFSSL_MSG("\tCannot run RNG. Skipping the OSCP Nonce.");
  9737. else
  9738. req->nonceSz = MAX_OCSP_NONCE_SZ;
  9739. wc_FreeRng(&rng);
  9740. }
  9741. }
  9742. return 0;
  9743. }
  9744. void FreeOcspRequest(OcspRequest* req)
  9745. {
  9746. WOLFSSL_ENTER("FreeOcspRequest");
  9747. if (req) {
  9748. if (req->serial)
  9749. XFREE(req->serial, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  9750. if (req->url)
  9751. XFREE(req->url, req->heap, DYNAMIC_TYPE_OCSP_REQUEST);
  9752. }
  9753. }
  9754. int CompareOcspReqResp(OcspRequest* req, OcspResponse* resp)
  9755. {
  9756. int cmp;
  9757. WOLFSSL_ENTER("CompareOcspReqResp");
  9758. if (req == NULL)
  9759. {
  9760. WOLFSSL_MSG("\tReq missing");
  9761. return -1;
  9762. }
  9763. if (resp == NULL)
  9764. {
  9765. WOLFSSL_MSG("\tResp missing");
  9766. return 1;
  9767. }
  9768. /* Nonces are not critical. The responder may not necessarily add
  9769. * the nonce to the response. */
  9770. if (resp->nonceSz != 0) {
  9771. cmp = req->nonceSz - resp->nonceSz;
  9772. if (cmp != 0)
  9773. {
  9774. WOLFSSL_MSG("\tnonceSz mismatch");
  9775. return cmp;
  9776. }
  9777. cmp = XMEMCMP(req->nonce, resp->nonce, req->nonceSz);
  9778. if (cmp != 0)
  9779. {
  9780. WOLFSSL_MSG("\tnonce mismatch");
  9781. return cmp;
  9782. }
  9783. }
  9784. cmp = XMEMCMP(req->issuerHash, resp->issuerHash, KEYID_SIZE);
  9785. if (cmp != 0)
  9786. {
  9787. WOLFSSL_MSG("\tissuerHash mismatch");
  9788. return cmp;
  9789. }
  9790. cmp = XMEMCMP(req->issuerKeyHash, resp->issuerKeyHash, KEYID_SIZE);
  9791. if (cmp != 0)
  9792. {
  9793. WOLFSSL_MSG("\tissuerKeyHash mismatch");
  9794. return cmp;
  9795. }
  9796. cmp = req->serialSz - resp->status->serialSz;
  9797. if (cmp != 0)
  9798. {
  9799. WOLFSSL_MSG("\tserialSz mismatch");
  9800. return cmp;
  9801. }
  9802. cmp = XMEMCMP(req->serial, resp->status->serial, req->serialSz);
  9803. if (cmp != 0)
  9804. {
  9805. WOLFSSL_MSG("\tserial mismatch");
  9806. return cmp;
  9807. }
  9808. return 0;
  9809. }
  9810. #endif
  9811. /* store WC_SHA hash of NAME */
  9812. WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash,
  9813. int maxIdx)
  9814. {
  9815. int length; /* length of all distinguished names */
  9816. int ret;
  9817. word32 dummy;
  9818. WOLFSSL_ENTER("GetNameHash");
  9819. if (source[*idx] == ASN_OBJECT_ID) {
  9820. WOLFSSL_MSG("Trying optional prefix...");
  9821. if (GetLength(source, idx, &length, maxIdx) < 0)
  9822. return ASN_PARSE_E;
  9823. *idx += length;
  9824. WOLFSSL_MSG("Got optional prefix");
  9825. }
  9826. /* For OCSP, RFC2560 section 4.1.1 states the issuer hash should be
  9827. * calculated over the entire DER encoding of the Name field, including
  9828. * the tag and length. */
  9829. dummy = *idx;
  9830. if (GetSequence(source, idx, &length, maxIdx) < 0)
  9831. return ASN_PARSE_E;
  9832. #ifdef NO_SHA
  9833. ret = wc_Sha256Hash(source + dummy, length + *idx - dummy, hash);
  9834. #else
  9835. ret = wc_ShaHash(source + dummy, length + *idx - dummy, hash);
  9836. #endif
  9837. *idx += length;
  9838. return ret;
  9839. }
  9840. #ifdef HAVE_CRL
  9841. /* initialize decoded CRL */
  9842. void InitDecodedCRL(DecodedCRL* dcrl, void* heap)
  9843. {
  9844. WOLFSSL_MSG("InitDecodedCRL");
  9845. dcrl->certBegin = 0;
  9846. dcrl->sigIndex = 0;
  9847. dcrl->sigLength = 0;
  9848. dcrl->signatureOID = 0;
  9849. dcrl->certs = NULL;
  9850. dcrl->totalCerts = 0;
  9851. dcrl->heap = heap;
  9852. #ifdef WOLFSSL_HEAP_TEST
  9853. dcrl->heap = (void*)WOLFSSL_HEAP_TEST;
  9854. #endif
  9855. }
  9856. /* free decoded CRL resources */
  9857. void FreeDecodedCRL(DecodedCRL* dcrl)
  9858. {
  9859. RevokedCert* tmp = dcrl->certs;
  9860. WOLFSSL_MSG("FreeDecodedCRL");
  9861. while(tmp) {
  9862. RevokedCert* next = tmp->next;
  9863. XFREE(tmp, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  9864. tmp = next;
  9865. }
  9866. }
  9867. /* Get Revoked Cert list, 0 on success */
  9868. static int GetRevoked(const byte* buff, word32* idx, DecodedCRL* dcrl,
  9869. int maxIdx)
  9870. {
  9871. int len;
  9872. word32 end;
  9873. byte b;
  9874. RevokedCert* rc;
  9875. WOLFSSL_ENTER("GetRevoked");
  9876. if (GetSequence(buff, idx, &len, maxIdx) < 0)
  9877. return ASN_PARSE_E;
  9878. end = *idx + len;
  9879. rc = (RevokedCert*)XMALLOC(sizeof(RevokedCert), dcrl->heap,
  9880. DYNAMIC_TYPE_REVOKED);
  9881. if (rc == NULL) {
  9882. WOLFSSL_MSG("Alloc Revoked Cert failed");
  9883. return MEMORY_E;
  9884. }
  9885. if (GetSerialNumber(buff, idx, rc->serialNumber, &rc->serialSz,
  9886. maxIdx) < 0) {
  9887. XFREE(rc, dcrl->heap, DYNAMIC_TYPE_REVOKED);
  9888. return ASN_PARSE_E;
  9889. }
  9890. /* add to list */
  9891. rc->next = dcrl->certs;
  9892. dcrl->certs = rc;
  9893. dcrl->totalCerts++;
  9894. /* get date */
  9895. b = buff[*idx];
  9896. *idx += 1;
  9897. if (b != ASN_UTC_TIME && b != ASN_GENERALIZED_TIME) {
  9898. WOLFSSL_MSG("Expecting Date");
  9899. return ASN_PARSE_E;
  9900. }
  9901. if (GetLength(buff, idx, &len, maxIdx) < 0)
  9902. return ASN_PARSE_E;
  9903. /* skip for now */
  9904. *idx += len;
  9905. if (*idx != end) /* skip extensions */
  9906. *idx = end;
  9907. return 0;
  9908. }
  9909. /* Get CRL Signature, 0 on success */
  9910. static int GetCRL_Signature(const byte* source, word32* idx, DecodedCRL* dcrl,
  9911. int maxIdx)
  9912. {
  9913. int length;
  9914. int ret;
  9915. WOLFSSL_ENTER("GetCRL_Signature");
  9916. ret = CheckBitString(source, idx, &length, maxIdx, 1, NULL);
  9917. if (ret != 0)
  9918. return ret;
  9919. dcrl->sigLength = length;
  9920. dcrl->signature = (byte*)&source[*idx];
  9921. *idx += dcrl->sigLength;
  9922. return 0;
  9923. }
  9924. int VerifyCRL_Signature(SignatureCtx* sigCtx, const byte* toBeSigned,
  9925. word32 tbsSz, const byte* signature, word32 sigSz,
  9926. word32 signatureOID, Signer *ca, void* heap)
  9927. {
  9928. /* try to confirm/verify signature */
  9929. #ifndef IGNORE_KEY_EXTENSIONS
  9930. if ((ca->keyUsage & KEYUSE_CRL_SIGN) == 0) {
  9931. WOLFSSL_MSG("CA cannot sign CRLs");
  9932. return ASN_CRL_NO_SIGNER_E;
  9933. }
  9934. #endif /* IGNORE_KEY_EXTENSIONS */
  9935. InitSignatureCtx(sigCtx, heap, INVALID_DEVID);
  9936. if (ConfirmSignature(sigCtx, toBeSigned, tbsSz, ca->publicKey,
  9937. ca->pubKeySize, ca->keyOID, signature, sigSz,
  9938. signatureOID) != 0) {
  9939. WOLFSSL_MSG("CRL Confirm signature failed");
  9940. return ASN_CRL_CONFIRM_E;
  9941. }
  9942. return 0;
  9943. }
  9944. /* prase crl buffer into decoded state, 0 on success */
  9945. int ParseCRL(DecodedCRL* dcrl, const byte* buff, word32 sz, void* cm)
  9946. {
  9947. int version, len, doNextDate = 1;
  9948. word32 oid, idx = 0, dateIdx;
  9949. Signer* ca = NULL;
  9950. SignatureCtx sigCtx;
  9951. WOLFSSL_MSG("ParseCRL");
  9952. /* raw crl hash */
  9953. /* hash here if needed for optimized comparisons
  9954. * wc_Sha sha;
  9955. * wc_InitSha(&sha);
  9956. * wc_ShaUpdate(&sha, buff, sz);
  9957. * wc_ShaFinal(&sha, dcrl->crlHash); */
  9958. if (GetSequence(buff, &idx, &len, sz) < 0)
  9959. return ASN_PARSE_E;
  9960. dcrl->certBegin = idx;
  9961. if (GetSequence(buff, &idx, &len, sz) < 0)
  9962. return ASN_PARSE_E;
  9963. dcrl->sigIndex = len + idx;
  9964. /* may have version */
  9965. if (buff[idx] == ASN_INTEGER) {
  9966. if (GetMyVersion(buff, &idx, &version, sz) < 0)
  9967. return ASN_PARSE_E;
  9968. }
  9969. if (GetAlgoId(buff, &idx, &oid, oidIgnoreType, sz) < 0)
  9970. return ASN_PARSE_E;
  9971. if (GetNameHash(buff, &idx, dcrl->issuerHash, sz) < 0)
  9972. return ASN_PARSE_E;
  9973. if (GetBasicDate(buff, &idx, dcrl->lastDate, &dcrl->lastDateFormat, sz) < 0)
  9974. return ASN_PARSE_E;
  9975. dateIdx = idx;
  9976. if (GetBasicDate(buff, &idx, dcrl->nextDate, &dcrl->nextDateFormat, sz) < 0)
  9977. {
  9978. #ifndef WOLFSSL_NO_CRL_NEXT_DATE
  9979. (void)dateIdx;
  9980. return ASN_PARSE_E;
  9981. #else
  9982. dcrl->nextDateFormat = ASN_OTHER_TYPE; /* skip flag */
  9983. doNextDate = 0;
  9984. idx = dateIdx;
  9985. #endif
  9986. }
  9987. if (doNextDate) {
  9988. #ifndef NO_ASN_TIME
  9989. if (!XVALIDATE_DATE(dcrl->nextDate, dcrl->nextDateFormat, AFTER)) {
  9990. WOLFSSL_MSG("CRL after date is no longer valid");
  9991. return ASN_AFTER_DATE_E;
  9992. }
  9993. #endif
  9994. }
  9995. if (idx != dcrl->sigIndex && buff[idx] != CRL_EXTENSIONS) {
  9996. if (GetSequence(buff, &idx, &len, sz) < 0)
  9997. return ASN_PARSE_E;
  9998. len += idx;
  9999. while (idx < (word32)len) {
  10000. if (GetRevoked(buff, &idx, dcrl, sz) < 0)
  10001. return ASN_PARSE_E;
  10002. }
  10003. }
  10004. if (idx != dcrl->sigIndex)
  10005. idx = dcrl->sigIndex; /* skip extensions */
  10006. if (GetAlgoId(buff, &idx, &dcrl->signatureOID, oidSigType, sz) < 0)
  10007. return ASN_PARSE_E;
  10008. if (GetCRL_Signature(buff, &idx, dcrl, sz) < 0)
  10009. return ASN_PARSE_E;
  10010. /* openssl doesn't add skid by default for CRLs cause firefox chokes
  10011. we're not assuming it's available yet */
  10012. #if !defined(NO_SKID) && defined(CRL_SKID_READY)
  10013. if (dcrl->extAuthKeyIdSet)
  10014. ca = GetCA(cm, dcrl->extAuthKeyId);
  10015. if (ca == NULL)
  10016. ca = GetCAByName(cm, dcrl->issuerHash);
  10017. #else
  10018. ca = GetCA(cm, dcrl->issuerHash);
  10019. #endif /* !NO_SKID && CRL_SKID_READY */
  10020. WOLFSSL_MSG("About to verify CRL signature");
  10021. if (ca == NULL) {
  10022. WOLFSSL_MSG("Did NOT find CRL issuer CA");
  10023. return ASN_CRL_NO_SIGNER_E;
  10024. }
  10025. WOLFSSL_MSG("Found CRL issuer CA");
  10026. return VerifyCRL_Signature(&sigCtx, buff + dcrl->certBegin,
  10027. dcrl->sigIndex - dcrl->certBegin, dcrl->signature, dcrl->sigLength,
  10028. dcrl->signatureOID, ca, dcrl->heap);
  10029. }
  10030. #endif /* HAVE_CRL */
  10031. #undef ERROR_OUT
  10032. #endif /* !NO_ASN */
  10033. #ifdef WOLFSSL_SEP
  10034. #endif /* WOLFSSL_SEP */